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.45 2005/08/07 03:28:50 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_flags = B_INVAL; /* we're just an empty header */
456 bp->b_qindex = BQUEUE_EMPTY;
459 xio_init(&bp->b_xio);
460 LIST_INIT(&bp->b_dep);
462 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
463 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
467 * maxbufspace is the absolute maximum amount of buffer space we are
468 * allowed to reserve in KVM and in real terms. The absolute maximum
469 * is nominally used by buf_daemon. hibufspace is the nominal maximum
470 * used by most other processes. The differential is required to
471 * ensure that buf_daemon is able to run when other processes might
472 * be blocked waiting for buffer space.
474 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
475 * this may result in KVM fragmentation which is not handled optimally
478 maxbufspace = nbuf * BKVASIZE;
479 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
480 lobufspace = hibufspace - MAXBSIZE;
482 lorunningspace = 512 * 1024;
483 hirunningspace = 1024 * 1024;
486 * Limit the amount of malloc memory since it is wired permanently into
487 * the kernel space. Even though this is accounted for in the buffer
488 * allocation, we don't want the malloced region to grow uncontrolled.
489 * The malloc scheme improves memory utilization significantly on average
490 * (small) directories.
492 maxbufmallocspace = hibufspace / 20;
495 * Reduce the chance of a deadlock occuring by limiting the number
496 * of delayed-write dirty buffers we allow to stack up.
498 hidirtybuffers = nbuf / 4 + 20;
501 * To support extreme low-memory systems, make sure hidirtybuffers cannot
502 * eat up all available buffer space. This occurs when our minimum cannot
503 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
504 * BKVASIZE'd (8K) buffers.
506 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
507 hidirtybuffers >>= 1;
509 lodirtybuffers = hidirtybuffers / 2;
512 * Try to keep the number of free buffers in the specified range,
513 * and give special processes (e.g. like buf_daemon) access to an
516 lofreebuffers = nbuf / 18 + 5;
517 hifreebuffers = 2 * lofreebuffers;
518 numfreebuffers = nbuf;
521 * Maximum number of async ops initiated per buf_daemon loop. This is
522 * somewhat of a hack at the moment, we really need to limit ourselves
523 * based on the number of bytes of I/O in-transit that were initiated
527 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
528 bogus_page = vm_page_alloc(kernel_object,
529 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
531 vmstats.v_wire_count++;
538 * Free the KVA allocation for buffer 'bp'.
540 * Must be called from a critical section as this is the only locking for
543 * Since this call frees up buffer space, we call bufspacewakeup().
546 bfreekva(struct buf * bp)
552 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
553 vm_map_lock(buffer_map);
554 bufspace -= bp->b_kvasize;
555 vm_map_delete(buffer_map,
556 (vm_offset_t) bp->b_kvabase,
557 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
560 vm_map_unlock(buffer_map);
561 vm_map_entry_release(count);
570 * Remove the buffer from the appropriate free list.
573 bremfree(struct buf * bp)
578 old_qindex = bp->b_qindex;
580 if (bp->b_qindex != BQUEUE_NONE) {
581 KASSERT(BUF_REFCNTNB(bp) == 1,
582 ("bremfree: bp %p not locked",bp));
583 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
584 bp->b_qindex = BQUEUE_NONE;
586 if (BUF_REFCNTNB(bp) <= 1)
587 panic("bremfree: removing a buffer not on a queue");
591 * Fixup numfreebuffers count. If the buffer is invalid or not
592 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
593 * the buffer was free and we must decrement numfreebuffers.
595 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
600 case BQUEUE_EMPTYKVA:
614 * Get a buffer with the specified data. Look in the cache first. We
615 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
616 * is set, the buffer is valid and we do not have to do anything ( see
620 bread(struct vnode * vp, daddr_t blkno, int size, struct buf ** bpp)
624 bp = getblk(vp, blkno, size, 0, 0);
627 /* if not found in cache, do some I/O */
628 if ((bp->b_flags & B_CACHE) == 0) {
629 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
630 bp->b_flags |= B_READ;
631 bp->b_flags &= ~(B_ERROR | B_INVAL);
632 vfs_busy_pages(bp, 0);
633 VOP_STRATEGY(vp, bp);
634 return (biowait(bp));
642 * Operates like bread, but also starts asynchronous I/O on
643 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
644 * to initiating I/O . If B_CACHE is set, the buffer is valid
645 * and we do not have to do anything.
648 breadn(struct vnode * vp, daddr_t blkno, int size, daddr_t * rablkno,
649 int *rabsize, int cnt, struct buf ** bpp)
651 struct buf *bp, *rabp;
653 int rv = 0, readwait = 0;
655 *bpp = bp = getblk(vp, blkno, size, 0, 0);
657 /* if not found in cache, do some I/O */
658 if ((bp->b_flags & B_CACHE) == 0) {
659 bp->b_flags |= B_READ;
660 bp->b_flags &= ~(B_ERROR | B_INVAL);
661 vfs_busy_pages(bp, 0);
662 VOP_STRATEGY(vp, bp);
666 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
667 if (inmem(vp, *rablkno))
669 rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
671 if ((rabp->b_flags & B_CACHE) == 0) {
672 rabp->b_flags |= B_READ | B_ASYNC;
673 rabp->b_flags &= ~(B_ERROR | B_INVAL);
674 vfs_busy_pages(rabp, 0);
676 VOP_STRATEGY(vp, rabp);
691 * Write, release buffer on completion. (Done by iodone
692 * if async). Do not bother writing anything if the buffer
695 * Note that we set B_CACHE here, indicating that buffer is
696 * fully valid and thus cacheable. This is true even of NFS
697 * now so we set it generally. This could be set either here
698 * or in biodone() since the I/O is synchronous. We put it
702 bwrite(struct buf * bp)
709 if (bp->b_flags & B_INVAL) {
714 oldflags = bp->b_flags;
716 if (BUF_REFCNTNB(bp) == 0)
717 panic("bwrite: buffer is not busy???");
720 * If a background write is already in progress, delay
721 * writing this block if it is asynchronous. Otherwise
722 * wait for the background write to complete.
724 if (bp->b_xflags & BX_BKGRDINPROG) {
725 if (bp->b_flags & B_ASYNC) {
730 bp->b_xflags |= BX_BKGRDWAIT;
731 tsleep(&bp->b_xflags, 0, "biord", 0);
732 if (bp->b_xflags & BX_BKGRDINPROG)
733 panic("bwrite: still writing");
736 /* Mark the buffer clean */
741 * If this buffer is marked for background writing and we
742 * do not have to wait for it, make a copy and write the
743 * copy so as to leave this buffer ready for further use.
745 * This optimization eats a lot of memory. If we have a page
746 * or buffer shortfull we can't do it.
748 * XXX DISABLED! This had to be removed to support the RB_TREE
749 * work and, really, this isn't the best place to do this sort
750 * of thing anyway. We really need a device copy-on-write feature.
753 (bp->b_xflags & BX_BKGRDWRITE) &&
754 (bp->b_flags & B_ASYNC) &&
755 !vm_page_count_severe() &&
756 !buf_dirty_count_severe()) {
758 panic("bwrite: need chained iodone");
760 /* get a new block */
761 newbp = geteblk(bp->b_bufsize);
763 /* set it to be identical to the old block */
764 memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
765 newbp->b_lblkno = bp->b_lblkno;
766 newbp->b_blkno = bp->b_blkno;
767 newbp->b_offset = bp->b_offset;
768 newbp->b_iodone = vfs_backgroundwritedone;
769 newbp->b_flags |= B_ASYNC;
770 newbp->b_flags &= ~B_INVAL;
771 bgetvp(bp->b_vp, newbp);
773 /* move over the dependencies */
774 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
775 (*bioops.io_movedeps)(bp, newbp);
778 * Initiate write on the copy, release the original to
779 * the B_LOCKED queue so that it cannot go away until
780 * the background write completes. If not locked it could go
781 * away and then be reconstituted while it was being written.
782 * If the reconstituted buffer were written, we could end up
783 * with two background copies being written at the same time.
785 bp->b_xflags |= BX_BKGRDINPROG;
786 bp->b_flags |= B_LOCKED;
792 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
793 bp->b_flags |= B_CACHE;
795 bp->b_vp->v_numoutput++;
796 vfs_busy_pages(bp, 1);
799 * Normal bwrites pipeline writes
801 bp->b_runningbufspace = bp->b_bufsize;
802 runningbufspace += bp->b_runningbufspace;
805 if (oldflags & B_ASYNC)
807 VOP_STRATEGY(bp->b_vp, bp);
809 if ((oldflags & B_ASYNC) == 0) {
810 int rtval = biowait(bp);
813 } else if ((oldflags & B_NOWDRAIN) == 0) {
815 * don't allow the async write to saturate the I/O
816 * system. Deadlocks can occur only if a device strategy
817 * routine (like in VN) turns around and issues another
818 * high-level write, in which case B_NOWDRAIN is expected
819 * to be set. Otherwise we will not deadlock here because
820 * we are blocking waiting for I/O that is already in-progress
823 waitrunningbufspace();
831 * Complete a background write started from bwrite.
834 vfs_backgroundwritedone(struct buf *bp)
839 * Find the original buffer that we are writing.
841 if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
842 panic("backgroundwritedone: lost buffer");
844 * Process dependencies then return any unfinished ones.
846 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
847 (*bioops.io_complete)(bp);
848 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
849 (*bioops.io_movedeps)(bp, origbp);
851 * Clear the BX_BKGRDINPROG flag in the original buffer
852 * and awaken it if it is waiting for the write to complete.
853 * If BX_BKGRDINPROG is not set in the original buffer it must
854 * have been released and re-instantiated - which is not legal.
856 KASSERT((origbp->b_xflags & BX_BKGRDINPROG), ("backgroundwritedone: lost buffer2"));
857 origbp->b_xflags &= ~BX_BKGRDINPROG;
858 if (origbp->b_xflags & BX_BKGRDWAIT) {
859 origbp->b_xflags &= ~BX_BKGRDWAIT;
860 wakeup(&origbp->b_xflags);
863 * Clear the B_LOCKED flag and remove it from the locked
864 * queue if it currently resides there.
866 origbp->b_flags &= ~B_LOCKED;
867 if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
872 * This buffer is marked B_NOCACHE, so when it is released
873 * by biodone, it will be tossed. We mark it with B_READ
874 * to avoid biodone doing a second vwakeup.
876 bp->b_flags |= B_NOCACHE | B_READ;
877 bp->b_flags &= ~(B_CACHE | B_DONE);
886 * Delayed write. (Buffer is marked dirty). Do not bother writing
887 * anything if the buffer is marked invalid.
889 * Note that since the buffer must be completely valid, we can safely
890 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
891 * biodone() in order to prevent getblk from writing the buffer
895 bdwrite(struct buf *bp)
897 if (BUF_REFCNTNB(bp) == 0)
898 panic("bdwrite: buffer is not busy");
900 if (bp->b_flags & B_INVAL) {
907 * Set B_CACHE, indicating that the buffer is fully valid. This is
908 * true even of NFS now.
910 bp->b_flags |= B_CACHE;
913 * This bmap keeps the system from needing to do the bmap later,
914 * perhaps when the system is attempting to do a sync. Since it
915 * is likely that the indirect block -- or whatever other datastructure
916 * that the filesystem needs is still in memory now, it is a good
917 * thing to do this. Note also, that if the pageout daemon is
918 * requesting a sync -- there might not be enough memory to do
919 * the bmap then... So, this is important to do.
921 if (bp->b_lblkno == bp->b_blkno) {
922 VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
926 * Set the *dirty* buffer range based upon the VM system dirty pages.
931 * We need to do this here to satisfy the vnode_pager and the
932 * pageout daemon, so that it thinks that the pages have been
933 * "cleaned". Note that since the pages are in a delayed write
934 * buffer -- the VFS layer "will" see that the pages get written
935 * out on the next sync, or perhaps the cluster will be completed.
941 * Wakeup the buffer flushing daemon if we have a lot of dirty
942 * buffers (midpoint between our recovery point and our stall
945 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
948 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
949 * due to the softdep code.
956 * Turn buffer into delayed write request. We must clear B_READ and
957 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
958 * itself to properly update it in the dirty/clean lists. We mark it
959 * B_DONE to ensure that any asynchronization of the buffer properly
960 * clears B_DONE ( else a panic will occur later ).
962 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
963 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
964 * should only be called if the buffer is known-good.
966 * Since the buffer is not on a queue, we do not update the numfreebuffers
969 * Must be called from a critical section.
970 * The buffer must be on BQUEUE_NONE.
973 bdirty(struct buf *bp)
975 KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
976 bp->b_flags &= ~(B_READ|B_RELBUF);
978 if ((bp->b_flags & B_DELWRI) == 0) {
979 bp->b_flags |= B_DONE | B_DELWRI;
980 reassignbuf(bp, bp->b_vp);
982 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
989 * Clear B_DELWRI for buffer.
991 * Since the buffer is not on a queue, we do not update the numfreebuffers
994 * Must be called from a critical section.
996 * The buffer is typically on BQUEUE_NONE but there is one case in
997 * brelse() that calls this function after placing the buffer on
1002 bundirty(struct buf *bp)
1004 if (bp->b_flags & B_DELWRI) {
1005 bp->b_flags &= ~B_DELWRI;
1006 reassignbuf(bp, bp->b_vp);
1008 numdirtywakeup(lodirtybuffers);
1011 * Since it is now being written, we can clear its deferred write flag.
1013 bp->b_flags &= ~B_DEFERRED;
1019 * Asynchronous write. Start output on a buffer, but do not wait for
1020 * it to complete. The buffer is released when the output completes.
1022 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1023 * B_INVAL buffers. Not us.
1026 bawrite(struct buf * bp)
1028 bp->b_flags |= B_ASYNC;
1029 (void) VOP_BWRITE(bp->b_vp, bp);
1035 * Ordered write. Start output on a buffer, and flag it so that the
1036 * device will write it in the order it was queued. The buffer is
1037 * released when the output completes. bwrite() ( or the VOP routine
1038 * anyway ) is responsible for handling B_INVAL buffers.
1041 bowrite(struct buf * bp)
1043 bp->b_flags |= B_ORDERED | B_ASYNC;
1044 return (VOP_BWRITE(bp->b_vp, bp));
1050 * Called prior to the locking of any vnodes when we are expecting to
1051 * write. We do not want to starve the buffer cache with too many
1052 * dirty buffers so we block here. By blocking prior to the locking
1053 * of any vnodes we attempt to avoid the situation where a locked vnode
1054 * prevents the various system daemons from flushing related buffers.
1060 if (numdirtybuffers >= hidirtybuffers) {
1062 while (numdirtybuffers >= hidirtybuffers) {
1064 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1065 tsleep(&needsbuffer, 0, "flswai", 0);
1072 * buf_dirty_count_severe:
1074 * Return true if we have too many dirty buffers.
1077 buf_dirty_count_severe(void)
1079 return(numdirtybuffers >= hidirtybuffers);
1085 * Release a busy buffer and, if requested, free its resources. The
1086 * buffer will be stashed in the appropriate bufqueue[] allowing it
1087 * to be accessed later as a cache entity or reused for other purposes.
1090 brelse(struct buf * bp)
1093 int saved_flags = bp->b_flags;
1096 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1100 if (bp->b_flags & B_LOCKED)
1101 bp->b_flags &= ~B_ERROR;
1103 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
1105 * Failed write, redirty. Must clear B_ERROR to prevent
1106 * pages from being scrapped. If B_INVAL is set then
1107 * this case is not run and the next case is run to
1108 * destroy the buffer. B_INVAL can occur if the buffer
1109 * is outside the range supported by the underlying device.
1111 bp->b_flags &= ~B_ERROR;
1113 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
1114 (bp->b_bufsize <= 0)) {
1116 * Either a failed I/O or we were asked to free or not
1119 bp->b_flags |= B_INVAL;
1120 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1121 (*bioops.io_deallocate)(bp);
1122 if (bp->b_flags & B_DELWRI) {
1124 numdirtywakeup(lodirtybuffers);
1126 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
1130 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1131 * is called with B_DELWRI set, the underlying pages may wind up
1132 * getting freed causing a previous write (bdwrite()) to get 'lost'
1133 * because pages associated with a B_DELWRI bp are marked clean.
1135 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1136 * if B_DELWRI is set.
1138 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1139 * on pages to return pages to the VM page queues.
1141 if (bp->b_flags & B_DELWRI)
1142 bp->b_flags &= ~B_RELBUF;
1143 else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1144 bp->b_flags |= B_RELBUF;
1147 * At this point destroying the buffer is governed by the B_INVAL
1148 * or B_RELBUF flags.
1152 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1153 * constituted, not even NFS buffers now. Two flags effect this. If
1154 * B_INVAL, the struct buf is invalidated but the VM object is kept
1155 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1157 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1158 * invalidated. B_ERROR cannot be set for a failed write unless the
1159 * buffer is also B_INVAL because it hits the re-dirtying code above.
1161 * Normally we can do this whether a buffer is B_DELWRI or not. If
1162 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1163 * the commit state and we cannot afford to lose the buffer. If the
1164 * buffer has a background write in progress, we need to keep it
1165 * around to prevent it from being reconstituted and starting a second
1168 if ((bp->b_flags & B_VMIO)
1169 && !(bp->b_vp->v_tag == VT_NFS &&
1170 !vn_isdisk(bp->b_vp, NULL) &&
1171 (bp->b_flags & B_DELWRI))
1174 * Rundown for VMIO buffers which are not dirty NFS buffers.
1186 * Get the base offset and length of the buffer. Note that
1187 * in the VMIO case if the buffer block size is not
1188 * page-aligned then b_data pointer may not be page-aligned.
1189 * But our b_xio.xio_pages array *IS* page aligned.
1191 * block sizes less then DEV_BSIZE (usually 512) are not
1192 * supported due to the page granularity bits (m->valid,
1193 * m->dirty, etc...).
1195 * See man buf(9) for more information
1198 resid = bp->b_bufsize;
1199 foff = bp->b_offset;
1201 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1202 m = bp->b_xio.xio_pages[i];
1203 vm_page_flag_clear(m, PG_ZERO);
1205 * If we hit a bogus page, fixup *all* of them
1206 * now. Note that we left these pages wired
1207 * when we removed them so they had better exist,
1208 * and they cannot be ripped out from under us so
1209 * no critical section protection is necessary.
1211 if (m == bogus_page) {
1212 VOP_GETVOBJECT(vp, &obj);
1213 poff = OFF_TO_IDX(bp->b_offset);
1215 for (j = i; j < bp->b_xio.xio_npages; j++) {
1218 mtmp = bp->b_xio.xio_pages[j];
1219 if (mtmp == bogus_page) {
1220 mtmp = vm_page_lookup(obj, poff + j);
1222 panic("brelse: page missing");
1224 bp->b_xio.xio_pages[j] = mtmp;
1228 if ((bp->b_flags & B_INVAL) == 0) {
1229 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1230 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1232 m = bp->b_xio.xio_pages[i];
1236 * Invalidate the backing store if B_NOCACHE is set
1237 * (e.g. used with vinvalbuf()). If this is NFS
1238 * we impose a requirement that the block size be
1239 * a multiple of PAGE_SIZE and create a temporary
1240 * hack to basically invalidate the whole page. The
1241 * problem is that NFS uses really odd buffer sizes
1242 * especially when tracking piecemeal writes and
1243 * it also vinvalbuf()'s a lot, which would result
1244 * in only partial page validation and invalidation
1245 * here. If the file page is mmap()'d, however,
1246 * all the valid bits get set so after we invalidate
1247 * here we would end up with weird m->valid values
1248 * like 0xfc. nfs_getpages() can't handle this so
1249 * we clear all the valid bits for the NFS case
1250 * instead of just some of them.
1252 * The real bug is the VM system having to set m->valid
1253 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1254 * itself is an artifact of the whole 512-byte
1255 * granular mess that exists to support odd block
1256 * sizes and UFS meta-data block sizes (e.g. 6144).
1257 * A complete rewrite is required.
1259 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1260 int poffset = foff & PAGE_MASK;
1263 presid = PAGE_SIZE - poffset;
1264 if (bp->b_vp->v_tag == VT_NFS &&
1265 bp->b_vp->v_type == VREG) {
1267 } else if (presid > resid) {
1270 KASSERT(presid >= 0, ("brelse: extra page"));
1271 vm_page_set_invalid(m, poffset, presid);
1273 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1274 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1276 if (bp->b_flags & (B_INVAL | B_RELBUF))
1277 vfs_vmio_release(bp);
1278 } else if (bp->b_flags & B_VMIO) {
1280 * Rundown for VMIO buffers which are dirty NFS buffers. Such
1281 * buffers contain tracking ranges for NFS and cannot normally
1282 * be released. Due to the dirty check above this series of
1283 * conditionals, B_RELBUF probably will never be set in this
1286 if (bp->b_flags & (B_INVAL | B_RELBUF))
1287 vfs_vmio_release(bp);
1290 * Rundown for non-VMIO buffers.
1292 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1295 printf("brelse bp %p %08x/%08lx: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1304 if (bp->b_qindex != BQUEUE_NONE)
1305 panic("brelse: free buffer onto another queue???");
1306 if (BUF_REFCNTNB(bp) > 1) {
1307 /* Temporary panic to verify exclusive locking */
1308 /* This panic goes away when we allow shared refs */
1309 panic("brelse: multiple refs");
1310 /* do not release to free list */
1317 * Figure out the correct queue to place the cleaned up buffer on.
1318 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1319 * disassociated from their vnode.
1322 if (bp->b_bufsize == 0) {
1324 * Buffers with no memory. Due to conditionals near the top
1325 * of brelse() such buffers should probably already be
1326 * marked B_INVAL and disassociated from their vnode.
1328 bp->b_flags |= B_INVAL;
1329 bp->b_xflags &= ~BX_BKGRDWRITE;
1330 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08lx vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1331 if (bp->b_xflags & BX_BKGRDINPROG)
1332 panic("losing buffer 1");
1333 if (bp->b_kvasize) {
1334 bp->b_qindex = BQUEUE_EMPTYKVA;
1336 bp->b_qindex = BQUEUE_EMPTY;
1338 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1339 LIST_REMOVE(bp, b_hash);
1340 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1342 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1344 * Buffers with junk contents. Again these buffers had better
1345 * already be disassociated from their vnode.
1347 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08lx vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1348 bp->b_flags |= B_INVAL;
1349 bp->b_xflags &= ~BX_BKGRDWRITE;
1350 if (bp->b_xflags & BX_BKGRDINPROG)
1351 panic("losing buffer 2");
1352 bp->b_qindex = BQUEUE_CLEAN;
1353 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1354 LIST_REMOVE(bp, b_hash);
1355 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1357 } else if (bp->b_flags & B_LOCKED) {
1359 * Buffers that are locked.
1361 bp->b_qindex = BQUEUE_LOCKED;
1362 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1365 * Remaining buffers. These buffers are still associated with
1368 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1369 case B_DELWRI | B_AGE:
1370 bp->b_qindex = BQUEUE_DIRTY;
1371 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1374 bp->b_qindex = BQUEUE_DIRTY;
1375 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1378 bp->b_qindex = BQUEUE_CLEAN;
1379 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1382 bp->b_qindex = BQUEUE_CLEAN;
1383 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1389 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1390 * on the correct queue.
1392 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1396 * Fixup numfreebuffers count. The bp is on an appropriate queue
1397 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1398 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1399 * if B_INVAL is set ).
1401 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1405 * Something we can maybe free or reuse
1407 if (bp->b_bufsize || bp->b_kvasize)
1412 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1413 B_DIRECT | B_NOWDRAIN);
1420 * Release a buffer back to the appropriate queue but do not try to free
1421 * it. The buffer is expected to be used again soon.
1423 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1424 * biodone() to requeue an async I/O on completion. It is also used when
1425 * known good buffers need to be requeued but we think we may need the data
1428 * XXX we should be able to leave the B_RELBUF hint set on completion.
1431 bqrelse(struct buf * bp)
1435 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1437 if (bp->b_qindex != BQUEUE_NONE)
1438 panic("bqrelse: free buffer onto another queue???");
1439 if (BUF_REFCNTNB(bp) > 1) {
1440 /* do not release to free list */
1441 panic("bqrelse: multiple refs");
1446 if (bp->b_flags & B_LOCKED) {
1447 bp->b_flags &= ~B_ERROR;
1448 bp->b_qindex = BQUEUE_LOCKED;
1449 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1450 /* buffers with stale but valid contents */
1451 } else if (bp->b_flags & B_DELWRI) {
1452 bp->b_qindex = BQUEUE_DIRTY;
1453 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1454 } else if (vm_page_count_severe()) {
1456 * We are too low on memory, we have to try to free the
1457 * buffer (most importantly: the wired pages making up its
1458 * backing store) *now*.
1464 bp->b_qindex = BQUEUE_CLEAN;
1465 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1468 if ((bp->b_flags & B_LOCKED) == 0 &&
1469 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1474 * Something we can maybe free or reuse.
1476 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1480 * Final cleanup and unlock. Clear bits that are only used while a
1481 * buffer is actively locked.
1483 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1491 * Return backing pages held by the buffer 'bp' back to the VM system
1492 * if possible. The pages are freed if they are no longer valid or
1493 * attempt to free if it was used for direct I/O otherwise they are
1494 * sent to the page cache.
1496 * Pages that were marked busy are left alone and skipped.
1498 * The KVA mapping (b_data) for the underlying pages is removed by
1502 vfs_vmio_release(struct buf *bp)
1508 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1509 m = bp->b_xio.xio_pages[i];
1510 bp->b_xio.xio_pages[i] = NULL;
1512 * In order to keep page LRU ordering consistent, put
1513 * everything on the inactive queue.
1515 vm_page_unwire(m, 0);
1517 * We don't mess with busy pages, it is
1518 * the responsibility of the process that
1519 * busied the pages to deal with them.
1521 if ((m->flags & PG_BUSY) || (m->busy != 0))
1524 if (m->wire_count == 0) {
1525 vm_page_flag_clear(m, PG_ZERO);
1527 * Might as well free the page if we can and it has
1528 * no valid data. We also free the page if the
1529 * buffer was used for direct I/O.
1531 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1532 m->hold_count == 0) {
1534 vm_page_protect(m, VM_PROT_NONE);
1536 } else if (bp->b_flags & B_DIRECT) {
1537 vm_page_try_to_free(m);
1538 } else if (vm_page_count_severe()) {
1539 vm_page_try_to_cache(m);
1544 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1545 if (bp->b_bufsize) {
1549 bp->b_xio.xio_npages = 0;
1550 bp->b_flags &= ~B_VMIO;
1558 * Check to see if a block is currently memory resident.
1561 gbincore(struct vnode * vp, daddr_t blkno)
1564 struct bufhashhdr *bh;
1566 bh = bufhash(vp, blkno);
1567 LIST_FOREACH(bp, bh, b_hash) {
1568 if (bp->b_vp == vp && bp->b_lblkno == blkno)
1577 * Implement clustered async writes for clearing out B_DELWRI buffers.
1578 * This is much better then the old way of writing only one buffer at
1579 * a time. Note that we may not be presented with the buffers in the
1580 * correct order, so we search for the cluster in both directions.
1583 vfs_bio_awrite(struct buf * bp)
1587 daddr_t lblkno = bp->b_lblkno;
1588 struct vnode *vp = bp->b_vp;
1597 * right now we support clustered writing only to regular files. If
1598 * we find a clusterable block we could be in the middle of a cluster
1599 * rather then at the beginning.
1601 if ((vp->v_type == VREG) &&
1602 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1603 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1605 size = vp->v_mount->mnt_stat.f_iosize;
1606 maxcl = MAXPHYS / size;
1608 for (i = 1; i < maxcl; i++) {
1609 if ((bpa = gbincore(vp, lblkno + i)) &&
1610 BUF_REFCNT(bpa) == 0 &&
1611 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1612 (B_DELWRI | B_CLUSTEROK)) &&
1613 (bpa->b_bufsize == size)) {
1614 if ((bpa->b_blkno == bpa->b_lblkno) ||
1616 bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1622 for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1623 if ((bpa = gbincore(vp, lblkno - j)) &&
1624 BUF_REFCNT(bpa) == 0 &&
1625 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1626 (B_DELWRI | B_CLUSTEROK)) &&
1627 (bpa->b_bufsize == size)) {
1628 if ((bpa->b_blkno == bpa->b_lblkno) ||
1630 bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1639 * this is a possible cluster write
1642 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1648 BUF_LOCK(bp, LK_EXCLUSIVE);
1650 bp->b_flags |= B_ASYNC;
1654 * default (old) behavior, writing out only one block
1656 * XXX returns b_bufsize instead of b_bcount for nwritten?
1658 nwritten = bp->b_bufsize;
1659 (void) VOP_BWRITE(bp->b_vp, bp);
1667 * Find and initialize a new buffer header, freeing up existing buffers
1668 * in the bufqueues as necessary. The new buffer is returned locked.
1670 * Important: B_INVAL is not set. If the caller wishes to throw the
1671 * buffer away, the caller must set B_INVAL prior to calling brelse().
1674 * We have insufficient buffer headers
1675 * We have insufficient buffer space
1676 * buffer_map is too fragmented ( space reservation fails )
1677 * If we have to flush dirty buffers ( but we try to avoid this )
1679 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1680 * Instead we ask the buf daemon to do it for us. We attempt to
1681 * avoid piecemeal wakeups of the pageout daemon.
1685 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1691 static int flushingbufs;
1694 * We can't afford to block since we might be holding a vnode lock,
1695 * which may prevent system daemons from running. We deal with
1696 * low-memory situations by proactively returning memory and running
1697 * async I/O rather then sync I/O.
1701 --getnewbufrestarts;
1703 ++getnewbufrestarts;
1706 * Setup for scan. If we do not have enough free buffers,
1707 * we setup a degenerate case that immediately fails. Note
1708 * that if we are specially marked process, we are allowed to
1709 * dip into our reserves.
1711 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1713 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1714 * However, there are a number of cases (defragging, reusing, ...)
1715 * where we cannot backup.
1717 nqindex = BQUEUE_EMPTYKVA;
1718 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1722 * If no EMPTYKVA buffers and we are either
1723 * defragging or reusing, locate a CLEAN buffer
1724 * to free or reuse. If bufspace useage is low
1725 * skip this step so we can allocate a new buffer.
1727 if (defrag || bufspace >= lobufspace) {
1728 nqindex = BQUEUE_CLEAN;
1729 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1733 * If we could not find or were not allowed to reuse a
1734 * CLEAN buffer, check to see if it is ok to use an EMPTY
1735 * buffer. We can only use an EMPTY buffer if allocating
1736 * its KVA would not otherwise run us out of buffer space.
1738 if (nbp == NULL && defrag == 0 &&
1739 bufspace + maxsize < hibufspace) {
1740 nqindex = BQUEUE_EMPTY;
1741 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1746 * Run scan, possibly freeing data and/or kva mappings on the fly
1750 while ((bp = nbp) != NULL) {
1751 int qindex = nqindex;
1754 * Calculate next bp ( we can only use it if we do not block
1755 * or do other fancy things ).
1757 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1760 nqindex = BQUEUE_EMPTYKVA;
1761 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1764 case BQUEUE_EMPTYKVA:
1765 nqindex = BQUEUE_CLEAN;
1766 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1780 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1783 * Note: we no longer distinguish between VMIO and non-VMIO
1787 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1790 * If we are defragging then we need a buffer with
1791 * b_kvasize != 0. XXX this situation should no longer
1792 * occur, if defrag is non-zero the buffer's b_kvasize
1793 * should also be non-zero at this point. XXX
1795 if (defrag && bp->b_kvasize == 0) {
1796 printf("Warning: defrag empty buffer %p\n", bp);
1801 * Start freeing the bp. This is somewhat involved. nbp
1802 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1803 * on the clean list must be disassociated from their
1804 * current vnode. Buffers on the empty[kva] lists have
1805 * already been disassociated.
1808 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1809 panic("getnewbuf: locked buf");
1812 if (qindex == BQUEUE_CLEAN) {
1813 if (bp->b_flags & B_VMIO) {
1814 bp->b_flags &= ~B_ASYNC;
1815 vfs_vmio_release(bp);
1822 * NOTE: nbp is now entirely invalid. We can only restart
1823 * the scan from this point on.
1825 * Get the rest of the buffer freed up. b_kva* is still
1826 * valid after this operation.
1829 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08lx vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1830 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1831 (*bioops.io_deallocate)(bp);
1832 if (bp->b_xflags & BX_BKGRDINPROG)
1833 panic("losing buffer 3");
1834 LIST_REMOVE(bp, b_hash);
1835 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1838 * critical section protection is not required when
1839 * scrapping a buffer's contents because it is already
1849 bp->b_blkno = bp->b_lblkno = 0;
1850 bp->b_offset = NOOFFSET;
1851 bp->b_iodone = NULL;
1855 bp->b_xio.xio_npages = 0;
1856 bp->b_dirtyoff = bp->b_dirtyend = 0;
1858 LIST_INIT(&bp->b_dep);
1861 * If we are defragging then free the buffer.
1864 bp->b_flags |= B_INVAL;
1872 * If we are overcomitted then recover the buffer and its
1873 * KVM space. This occurs in rare situations when multiple
1874 * processes are blocked in getnewbuf() or allocbuf().
1876 if (bufspace >= hibufspace)
1878 if (flushingbufs && bp->b_kvasize != 0) {
1879 bp->b_flags |= B_INVAL;
1884 if (bufspace < lobufspace)
1890 * If we exhausted our list, sleep as appropriate. We may have to
1891 * wakeup various daemons and write out some dirty buffers.
1893 * Generally we are sleeping due to insufficient buffer space.
1901 flags = VFS_BIO_NEED_BUFSPACE;
1903 } else if (bufspace >= hibufspace) {
1905 flags = VFS_BIO_NEED_BUFSPACE;
1908 flags = VFS_BIO_NEED_ANY;
1911 bd_speedup(); /* heeeelp */
1913 needsbuffer |= flags;
1914 while (needsbuffer & flags) {
1915 if (tsleep(&needsbuffer, slpflag, waitmsg, slptimeo))
1920 * We finally have a valid bp. We aren't quite out of the
1921 * woods, we still have to reserve kva space. In order
1922 * to keep fragmentation sane we only allocate kva in
1925 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1927 if (maxsize != bp->b_kvasize) {
1928 vm_offset_t addr = 0;
1933 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1934 vm_map_lock(buffer_map);
1936 if (vm_map_findspace(buffer_map,
1937 vm_map_min(buffer_map), maxsize,
1940 * Uh oh. Buffer map is too fragmented. We
1941 * must defragment the map.
1943 vm_map_unlock(buffer_map);
1944 vm_map_entry_release(count);
1947 bp->b_flags |= B_INVAL;
1952 vm_map_insert(buffer_map, &count,
1954 addr, addr + maxsize,
1955 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1957 bp->b_kvabase = (caddr_t) addr;
1958 bp->b_kvasize = maxsize;
1959 bufspace += bp->b_kvasize;
1962 vm_map_unlock(buffer_map);
1963 vm_map_entry_release(count);
1965 bp->b_data = bp->b_kvabase;
1973 * Buffer flushing daemon. Buffers are normally flushed by the
1974 * update daemon but if it cannot keep up this process starts to
1975 * take the load in an attempt to prevent getnewbuf() from blocking.
1978 static struct thread *bufdaemonthread;
1980 static struct kproc_desc buf_kp = {
1985 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1991 * This process needs to be suspended prior to shutdown sync.
1993 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1994 bufdaemonthread, SHUTDOWN_PRI_LAST);
1997 * This process is allowed to take the buffer cache to the limit
2002 kproc_suspend_loop();
2005 * Do the flush. Limit the amount of in-transit I/O we
2006 * allow to build up, otherwise we would completely saturate
2007 * the I/O system. Wakeup any waiting processes before we
2008 * normally would so they can run in parallel with our drain.
2010 while (numdirtybuffers > lodirtybuffers) {
2011 if (flushbufqueues() == 0)
2013 waitrunningbufspace();
2014 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
2018 * Only clear bd_request if we have reached our low water
2019 * mark. The buf_daemon normally waits 5 seconds and
2020 * then incrementally flushes any dirty buffers that have
2021 * built up, within reason.
2023 * If we were unable to hit our low water mark and couldn't
2024 * find any flushable buffers, we sleep half a second.
2025 * Otherwise we loop immediately.
2027 if (numdirtybuffers <= lodirtybuffers) {
2029 * We reached our low water mark, reset the
2030 * request and sleep until we are needed again.
2031 * The sleep is just so the suspend code works.
2034 tsleep(&bd_request, 0, "psleep", hz);
2037 * We couldn't find any flushable dirty buffers but
2038 * still have too many dirty buffers, we
2039 * have to sleep and try again. (rare)
2041 tsleep(&bd_request, 0, "qsleep", hz / 2);
2049 * Try to flush a buffer in the dirty queue. We must be careful to
2050 * free up B_INVAL buffers instead of write them, which NFS is
2051 * particularly sensitive to.
2055 flushbufqueues(void)
2060 bp = TAILQ_FIRST(&bufqueues[BQUEUE_DIRTY]);
2063 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
2064 if ((bp->b_flags & B_DELWRI) != 0 &&
2065 (bp->b_xflags & BX_BKGRDINPROG) == 0) {
2066 if (bp->b_flags & B_INVAL) {
2067 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2068 panic("flushbufqueues: locked buf");
2074 if (LIST_FIRST(&bp->b_dep) != NULL &&
2075 bioops.io_countdeps &&
2076 (bp->b_flags & B_DEFERRED) == 0 &&
2077 (*bioops.io_countdeps)(bp, 0)) {
2078 TAILQ_REMOVE(&bufqueues[BQUEUE_DIRTY],
2080 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY],
2082 bp->b_flags |= B_DEFERRED;
2083 bp = TAILQ_FIRST(&bufqueues[BQUEUE_DIRTY]);
2090 bp = TAILQ_NEXT(bp, b_freelist);
2098 * Check to see if a block is currently resident in memory.
2101 incore(struct vnode * vp, daddr_t blkno)
2106 bp = gbincore(vp, blkno);
2114 * Returns true if no I/O is needed to access the associated VM object.
2115 * This is like incore except it also hunts around in the VM system for
2118 * Note that we ignore vm_page_free() races from interrupts against our
2119 * lookup, since if the caller is not protected our return value will not
2120 * be any more valid then otherwise once we exit the critical section.
2123 inmem(struct vnode * vp, daddr_t blkno)
2126 vm_offset_t toff, tinc, size;
2130 if (incore(vp, blkno))
2132 if (vp->v_mount == NULL)
2134 if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
2138 if (size > vp->v_mount->mnt_stat.f_iosize)
2139 size = vp->v_mount->mnt_stat.f_iosize;
2140 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2142 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2143 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2147 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2148 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2149 if (vm_page_is_valid(m,
2150 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2159 * Sets the dirty range for a buffer based on the status of the dirty
2160 * bits in the pages comprising the buffer.
2162 * The range is limited to the size of the buffer.
2164 * This routine is primarily used by NFS, but is generalized for the
2168 vfs_setdirty(struct buf *bp)
2174 * Degenerate case - empty buffer
2177 if (bp->b_bufsize == 0)
2181 * We qualify the scan for modified pages on whether the
2182 * object has been flushed yet. The OBJ_WRITEABLE flag
2183 * is not cleared simply by protecting pages off.
2186 if ((bp->b_flags & B_VMIO) == 0)
2189 object = bp->b_xio.xio_pages[0]->object;
2191 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2192 printf("Warning: object %p writeable but not mightbedirty\n", object);
2193 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2194 printf("Warning: object %p mightbedirty but not writeable\n", object);
2196 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2197 vm_offset_t boffset;
2198 vm_offset_t eoffset;
2201 * test the pages to see if they have been modified directly
2202 * by users through the VM system.
2204 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2205 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2206 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2210 * Calculate the encompassing dirty range, boffset and eoffset,
2211 * (eoffset - boffset) bytes.
2214 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2215 if (bp->b_xio.xio_pages[i]->dirty)
2218 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2220 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2221 if (bp->b_xio.xio_pages[i]->dirty) {
2225 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2228 * Fit it to the buffer.
2231 if (eoffset > bp->b_bcount)
2232 eoffset = bp->b_bcount;
2235 * If we have a good dirty range, merge with the existing
2239 if (boffset < eoffset) {
2240 if (bp->b_dirtyoff > boffset)
2241 bp->b_dirtyoff = boffset;
2242 if (bp->b_dirtyend < eoffset)
2243 bp->b_dirtyend = eoffset;
2251 * Get a block given a specified block and offset into a file/device.
2252 * The buffers B_DONE bit will be cleared on return, making it almost
2253 * ready for an I/O initiation. B_INVAL may or may not be set on
2254 * return. The caller should clear B_INVAL prior to initiating a
2257 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2258 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2259 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2260 * without doing any of those things the system will likely believe
2261 * the buffer to be valid (especially if it is not B_VMIO), and the
2262 * next getblk() will return the buffer with B_CACHE set.
2264 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2265 * an existing buffer.
2267 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2268 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2269 * and then cleared based on the backing VM. If the previous buffer is
2270 * non-0-sized but invalid, B_CACHE will be cleared.
2272 * If getblk() must create a new buffer, the new buffer is returned with
2273 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2274 * case it is returned with B_INVAL clear and B_CACHE set based on the
2277 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2278 * B_CACHE bit is clear.
2280 * What this means, basically, is that the caller should use B_CACHE to
2281 * determine whether the buffer is fully valid or not and should clear
2282 * B_INVAL prior to issuing a read. If the caller intends to validate
2283 * the buffer by loading its data area with something, the caller needs
2284 * to clear B_INVAL. If the caller does this without issuing an I/O,
2285 * the caller should set B_CACHE ( as an optimization ), else the caller
2286 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2287 * a write attempt or if it was a successfull read. If the caller
2288 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2289 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2292 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2295 struct bufhashhdr *bh;
2297 if (size > MAXBSIZE)
2298 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2303 * Block if we are low on buffers. Certain processes are allowed
2304 * to completely exhaust the buffer cache.
2306 * If this check ever becomes a bottleneck it may be better to
2307 * move it into the else, when gbincore() fails. At the moment
2308 * it isn't a problem.
2310 * XXX remove, we cannot afford to block anywhere if holding a vnode
2311 * lock in low-memory situation, so take it to the max.
2313 if (numfreebuffers == 0) {
2316 needsbuffer |= VFS_BIO_NEED_ANY;
2317 tsleep(&needsbuffer, slpflag, "newbuf", slptimeo);
2320 if ((bp = gbincore(vp, blkno))) {
2322 * Buffer is in-core. If the buffer is not busy, it must
2326 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2327 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2328 "getblk", slpflag, slptimeo) == ENOLCK)
2331 return (struct buf *) NULL;
2335 * The buffer is locked. B_CACHE is cleared if the buffer is
2336 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
2337 * and for a VMIO buffer B_CACHE is adjusted according to the
2340 if (bp->b_flags & B_INVAL)
2341 bp->b_flags &= ~B_CACHE;
2342 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2343 bp->b_flags |= B_CACHE;
2347 * check for size inconsistancies for non-VMIO case.
2350 if (bp->b_bcount != size) {
2351 if ((bp->b_flags & B_VMIO) == 0 ||
2352 (size > bp->b_kvasize)) {
2353 if (bp->b_flags & B_DELWRI) {
2354 bp->b_flags |= B_NOCACHE;
2355 VOP_BWRITE(bp->b_vp, bp);
2357 if ((bp->b_flags & B_VMIO) &&
2358 (LIST_FIRST(&bp->b_dep) == NULL)) {
2359 bp->b_flags |= B_RELBUF;
2362 bp->b_flags |= B_NOCACHE;
2363 VOP_BWRITE(bp->b_vp, bp);
2371 * If the size is inconsistant in the VMIO case, we can resize
2372 * the buffer. This might lead to B_CACHE getting set or
2373 * cleared. If the size has not changed, B_CACHE remains
2374 * unchanged from its previous state.
2377 if (bp->b_bcount != size)
2380 KASSERT(bp->b_offset != NOOFFSET,
2381 ("getblk: no buffer offset"));
2384 * A buffer with B_DELWRI set and B_CACHE clear must
2385 * be committed before we can return the buffer in
2386 * order to prevent the caller from issuing a read
2387 * ( due to B_CACHE not being set ) and overwriting
2390 * Most callers, including NFS and FFS, need this to
2391 * operate properly either because they assume they
2392 * can issue a read if B_CACHE is not set, or because
2393 * ( for example ) an uncached B_DELWRI might loop due
2394 * to softupdates re-dirtying the buffer. In the latter
2395 * case, B_CACHE is set after the first write completes,
2396 * preventing further loops.
2398 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2399 * above while extending the buffer, we cannot allow the
2400 * buffer to remain with B_CACHE set after the write
2401 * completes or it will represent a corrupt state. To
2402 * deal with this we set B_NOCACHE to scrap the buffer
2405 * We might be able to do something fancy, like setting
2406 * B_CACHE in bwrite() except if B_DELWRI is already set,
2407 * so the below call doesn't set B_CACHE, but that gets real
2408 * confusing. This is much easier.
2411 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2412 bp->b_flags |= B_NOCACHE;
2413 VOP_BWRITE(bp->b_vp, bp);
2418 bp->b_flags &= ~B_DONE;
2421 * Buffer is not in-core, create new buffer. The buffer
2422 * returned by getnewbuf() is locked. Note that the returned
2423 * buffer is also considered valid (not marked B_INVAL).
2425 * Calculating the offset for the I/O requires figuring out
2426 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2427 * the mount's f_iosize otherwise. If the vnode does not
2428 * have an associated mount we assume that the passed size is
2431 * Note that vn_isdisk() cannot be used here since it may
2432 * return a failure for numerous reasons. Note that the
2433 * buffer size may be larger then the block size (the caller
2434 * will use block numbers with the proper multiple). Beware
2435 * of using any v_* fields which are part of unions. In
2436 * particular, in DragonFly the mount point overloading
2437 * mechanism is such that the underlying directory (with a
2438 * non-NULL v_mountedhere) is not a special case.
2440 int bsize, maxsize, vmio;
2443 if (vp->v_type == VBLK || vp->v_type == VCHR)
2445 else if (vp->v_mount)
2446 bsize = vp->v_mount->mnt_stat.f_iosize;
2450 offset = (off_t)blkno * bsize;
2451 vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2452 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2453 maxsize = imax(maxsize, bsize);
2455 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2456 if (slpflag || slptimeo) {
2464 * This code is used to make sure that a buffer is not
2465 * created while the getnewbuf routine is blocked.
2466 * This can be a problem whether the vnode is locked or not.
2467 * If the buffer is created out from under us, we have to
2468 * throw away the one we just created. There is now window
2469 * race because we are safely running in a critical section
2470 * from the point of the duplicate buffer creation through
2471 * to here, and we've locked the buffer.
2473 if (gbincore(vp, blkno)) {
2474 bp->b_flags |= B_INVAL;
2480 * Insert the buffer into the hash, so that it can
2481 * be found by incore. bgetvp() and bufhash()
2482 * must be synchronized with each other.
2484 bp->b_blkno = bp->b_lblkno = blkno;
2485 bp->b_offset = offset;
2488 LIST_REMOVE(bp, b_hash);
2489 bh = bufhash(vp, blkno);
2490 LIST_INSERT_HEAD(bh, bp, b_hash);
2493 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2494 * buffer size starts out as 0, B_CACHE will be set by
2495 * allocbuf() for the VMIO case prior to it testing the
2496 * backing store for validity.
2500 bp->b_flags |= B_VMIO;
2501 #if defined(VFS_BIO_DEBUG)
2502 if (vn_canvmio(vp) != TRUE)
2503 printf("getblk: vmioing file type %d???\n", vp->v_type);
2506 bp->b_flags &= ~B_VMIO;
2512 bp->b_flags &= ~B_DONE;
2520 * Get an empty, disassociated buffer of given size. The buffer is
2521 * initially set to B_INVAL.
2523 * critical section protection is not required for the allocbuf()
2524 * call because races are impossible here.
2532 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2535 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2539 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2547 * This code constitutes the buffer memory from either anonymous system
2548 * memory (in the case of non-VMIO operations) or from an associated
2549 * VM object (in the case of VMIO operations). This code is able to
2550 * resize a buffer up or down.
2552 * Note that this code is tricky, and has many complications to resolve
2553 * deadlock or inconsistant data situations. Tread lightly!!!
2554 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2555 * the caller. Calling this code willy nilly can result in the loss of data.
2557 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2558 * B_CACHE for the non-VMIO case.
2560 * This routine does not need to be called from a critical section but you
2561 * must own the buffer.
2564 allocbuf(struct buf *bp, int size)
2566 int newbsize, mbsize;
2569 if (BUF_REFCNT(bp) == 0)
2570 panic("allocbuf: buffer not busy");
2572 if (bp->b_kvasize < size)
2573 panic("allocbuf: buffer too small");
2575 if ((bp->b_flags & B_VMIO) == 0) {
2579 * Just get anonymous memory from the kernel. Don't
2580 * mess with B_CACHE.
2582 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2583 #if !defined(NO_B_MALLOC)
2584 if (bp->b_flags & B_MALLOC)
2588 newbsize = round_page(size);
2590 if (newbsize < bp->b_bufsize) {
2591 #if !defined(NO_B_MALLOC)
2593 * malloced buffers are not shrunk
2595 if (bp->b_flags & B_MALLOC) {
2597 bp->b_bcount = size;
2599 free(bp->b_data, M_BIOBUF);
2600 if (bp->b_bufsize) {
2601 bufmallocspace -= bp->b_bufsize;
2605 bp->b_data = bp->b_kvabase;
2607 bp->b_flags &= ~B_MALLOC;
2614 (vm_offset_t) bp->b_data + newbsize,
2615 (vm_offset_t) bp->b_data + bp->b_bufsize);
2616 } else if (newbsize > bp->b_bufsize) {
2617 #if !defined(NO_B_MALLOC)
2619 * We only use malloced memory on the first allocation.
2620 * and revert to page-allocated memory when the buffer
2623 if ( (bufmallocspace < maxbufmallocspace) &&
2624 (bp->b_bufsize == 0) &&
2625 (mbsize <= PAGE_SIZE/2)) {
2627 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2628 bp->b_bufsize = mbsize;
2629 bp->b_bcount = size;
2630 bp->b_flags |= B_MALLOC;
2631 bufmallocspace += mbsize;
2637 #if !defined(NO_B_MALLOC)
2639 * If the buffer is growing on its other-than-first allocation,
2640 * then we revert to the page-allocation scheme.
2642 if (bp->b_flags & B_MALLOC) {
2643 origbuf = bp->b_data;
2644 origbufsize = bp->b_bufsize;
2645 bp->b_data = bp->b_kvabase;
2646 if (bp->b_bufsize) {
2647 bufmallocspace -= bp->b_bufsize;
2651 bp->b_flags &= ~B_MALLOC;
2652 newbsize = round_page(newbsize);
2657 (vm_offset_t) bp->b_data + bp->b_bufsize,
2658 (vm_offset_t) bp->b_data + newbsize);
2659 #if !defined(NO_B_MALLOC)
2661 bcopy(origbuf, bp->b_data, origbufsize);
2662 free(origbuf, M_BIOBUF);
2670 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2671 desiredpages = (size == 0) ? 0 :
2672 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2674 #if !defined(NO_B_MALLOC)
2675 if (bp->b_flags & B_MALLOC)
2676 panic("allocbuf: VMIO buffer can't be malloced");
2679 * Set B_CACHE initially if buffer is 0 length or will become
2682 if (size == 0 || bp->b_bufsize == 0)
2683 bp->b_flags |= B_CACHE;
2685 if (newbsize < bp->b_bufsize) {
2687 * DEV_BSIZE aligned new buffer size is less then the
2688 * DEV_BSIZE aligned existing buffer size. Figure out
2689 * if we have to remove any pages.
2691 if (desiredpages < bp->b_xio.xio_npages) {
2692 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2694 * the page is not freed here -- it
2695 * is the responsibility of
2696 * vnode_pager_setsize
2698 m = bp->b_xio.xio_pages[i];
2699 KASSERT(m != bogus_page,
2700 ("allocbuf: bogus page found"));
2701 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2704 bp->b_xio.xio_pages[i] = NULL;
2705 vm_page_unwire(m, 0);
2707 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2708 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2709 bp->b_xio.xio_npages = desiredpages;
2711 } else if (size > bp->b_bcount) {
2713 * We are growing the buffer, possibly in a
2714 * byte-granular fashion.
2722 * Step 1, bring in the VM pages from the object,
2723 * allocating them if necessary. We must clear
2724 * B_CACHE if these pages are not valid for the
2725 * range covered by the buffer.
2727 * critical section protection is required to protect
2728 * against interrupts unbusying and freeing pages
2729 * between our vm_page_lookup() and our
2730 * busycheck/wiring call.
2733 VOP_GETVOBJECT(vp, &obj);
2736 while (bp->b_xio.xio_npages < desiredpages) {
2740 pi = OFF_TO_IDX(bp->b_offset) + bp->b_xio.xio_npages;
2741 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2743 * note: must allocate system pages
2744 * since blocking here could intefere
2745 * with paging I/O, no matter which
2748 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2751 vm_pageout_deficit += desiredpages -
2752 bp->b_xio.xio_npages;
2756 bp->b_flags &= ~B_CACHE;
2757 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2758 ++bp->b_xio.xio_npages;
2764 * We found a page. If we have to sleep on it,
2765 * retry because it might have gotten freed out
2768 * We can only test PG_BUSY here. Blocking on
2769 * m->busy might lead to a deadlock:
2771 * vm_fault->getpages->cluster_read->allocbuf
2775 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2779 * We have a good page. Should we wakeup the
2782 if ((curthread != pagethread) &&
2783 ((m->queue - m->pc) == PQ_CACHE) &&
2784 ((vmstats.v_free_count + vmstats.v_cache_count) <
2785 (vmstats.v_free_min + vmstats.v_cache_min))) {
2786 pagedaemon_wakeup();
2788 vm_page_flag_clear(m, PG_ZERO);
2790 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2791 ++bp->b_xio.xio_npages;
2796 * Step 2. We've loaded the pages into the buffer,
2797 * we have to figure out if we can still have B_CACHE
2798 * set. Note that B_CACHE is set according to the
2799 * byte-granular range ( bcount and size ), not the
2800 * aligned range ( newbsize ).
2802 * The VM test is against m->valid, which is DEV_BSIZE
2803 * aligned. Needless to say, the validity of the data
2804 * needs to also be DEV_BSIZE aligned. Note that this
2805 * fails with NFS if the server or some other client
2806 * extends the file's EOF. If our buffer is resized,
2807 * B_CACHE may remain set! XXX
2810 toff = bp->b_bcount;
2811 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2813 while ((bp->b_flags & B_CACHE) && toff < size) {
2816 if (tinc > (size - toff))
2819 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2827 bp->b_xio.xio_pages[pi]
2834 * Step 3, fixup the KVM pmap. Remember that
2835 * bp->b_data is relative to bp->b_offset, but
2836 * bp->b_offset may be offset into the first page.
2839 bp->b_data = (caddr_t)
2840 trunc_page((vm_offset_t)bp->b_data);
2842 (vm_offset_t)bp->b_data,
2843 bp->b_xio.xio_pages,
2844 bp->b_xio.xio_npages
2846 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2847 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2850 if (newbsize < bp->b_bufsize)
2852 bp->b_bufsize = newbsize; /* actual buffer allocation */
2853 bp->b_bcount = size; /* requested buffer size */
2860 * Wait for buffer I/O completion, returning error status. The buffer
2861 * is left locked and B_DONE on return. B_EINTR is converted into an
2862 * EINTR error and cleared.
2865 biowait(struct buf * bp)
2868 while ((bp->b_flags & B_DONE) == 0) {
2869 if (bp->b_flags & B_READ)
2870 tsleep(bp, 0, "biord", 0);
2872 tsleep(bp, 0, "biowr", 0);
2875 if (bp->b_flags & B_EINTR) {
2876 bp->b_flags &= ~B_EINTR;
2879 if (bp->b_flags & B_ERROR) {
2880 return (bp->b_error ? bp->b_error : EIO);
2889 * Finish I/O on a buffer, optionally calling a completion function.
2890 * This is usually called from an interrupt so process blocking is
2893 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2894 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2895 * assuming B_INVAL is clear.
2897 * For the VMIO case, we set B_CACHE if the op was a read and no
2898 * read error occured, or if the op was a write. B_CACHE is never
2899 * set if the buffer is invalid or otherwise uncacheable.
2901 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2902 * initiator to leave B_INVAL set to brelse the buffer out of existance
2903 * in the biodone routine.
2905 * b_dev is required to be reinitialized prior to the top level strategy
2906 * call in a device stack. To avoid improper reuse, biodone() sets
2910 biodone(struct buf *bp)
2916 KASSERT(BUF_REFCNTNB(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
2917 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2918 void (*b_iodone)(struct buf *);
2920 bp->b_flags |= B_DONE;
2922 runningbufwakeup(bp);
2924 if (bp->b_flags & B_FREEBUF) {
2930 if ((bp->b_flags & B_READ) == 0) {
2934 /* call optional completion function if requested */
2935 if (bp->b_iodone != NULL) {
2936 b_iodone = bp->b_iodone;
2937 bp->b_iodone = NULL;
2942 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2943 (*bioops.io_complete)(bp);
2945 if (bp->b_flags & B_VMIO) {
2951 struct vnode *vp = bp->b_vp;
2953 error = VOP_GETVOBJECT(vp, &obj);
2955 #if defined(VFS_BIO_DEBUG)
2956 if (vp->v_holdcnt == 0) {
2957 panic("biodone: zero vnode hold count");
2961 panic("biodone: missing VM object");
2964 if ((vp->v_flag & VOBJBUF) == 0) {
2965 panic("biodone: vnode is not setup for merged cache");
2969 foff = bp->b_offset;
2970 KASSERT(bp->b_offset != NOOFFSET,
2971 ("biodone: no buffer offset"));
2974 panic("biodone: no object");
2976 #if defined(VFS_BIO_DEBUG)
2977 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
2978 printf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
2979 obj->paging_in_progress, bp->b_xio.xio_npages);
2984 * Set B_CACHE if the op was a normal read and no error
2985 * occured. B_CACHE is set for writes in the b*write()
2988 iosize = bp->b_bcount - bp->b_resid;
2989 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2990 bp->b_flags |= B_CACHE;
2993 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2997 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3002 * cleanup bogus pages, restoring the originals. Since
3003 * the originals should still be wired, we don't have
3004 * to worry about interrupt/freeing races destroying
3005 * the VM object association.
3007 m = bp->b_xio.xio_pages[i];
3008 if (m == bogus_page) {
3010 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3012 panic("biodone: page disappeared");
3013 bp->b_xio.xio_pages[i] = m;
3014 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3015 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3017 #if defined(VFS_BIO_DEBUG)
3018 if (OFF_TO_IDX(foff) != m->pindex) {
3020 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3021 (unsigned long)foff, m->pindex);
3026 * In the write case, the valid and clean bits are
3027 * already changed correctly ( see bdwrite() ), so we
3028 * only need to do this here in the read case.
3030 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
3031 vfs_page_set_valid(bp, foff, i, m);
3033 vm_page_flag_clear(m, PG_ZERO);
3036 * when debugging new filesystems or buffer I/O methods, this
3037 * is the most common error that pops up. if you see this, you
3038 * have not set the page busy flag correctly!!!
3041 printf("biodone: page busy < 0, "
3042 "pindex: %d, foff: 0x(%x,%x), "
3043 "resid: %d, index: %d\n",
3044 (int) m->pindex, (int)(foff >> 32),
3045 (int) foff & 0xffffffff, resid, i);
3046 if (!vn_isdisk(vp, NULL))
3047 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
3048 bp->b_vp->v_mount->mnt_stat.f_iosize,
3050 bp->b_flags, bp->b_xio.xio_npages);
3052 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
3054 bp->b_flags, bp->b_xio.xio_npages);
3055 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3056 m->valid, m->dirty, m->wire_count);
3057 panic("biodone: page busy < 0");
3059 vm_page_io_finish(m);
3060 vm_object_pip_subtract(obj, 1);
3061 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3065 vm_object_pip_wakeupn(obj, 0);
3069 * For asynchronous completions, release the buffer now. The brelse
3070 * will do a wakeup there if necessary - so no need to do a wakeup
3071 * here in the async case. The sync case always needs to do a wakeup.
3074 if (bp->b_flags & B_ASYNC) {
3075 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3088 * This routine is called in lieu of iodone in the case of
3089 * incomplete I/O. This keeps the busy status for pages
3093 vfs_unbusy_pages(struct buf *bp)
3097 runningbufwakeup(bp);
3098 if (bp->b_flags & B_VMIO) {
3099 struct vnode *vp = bp->b_vp;
3102 VOP_GETVOBJECT(vp, &obj);
3104 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3105 vm_page_t m = bp->b_xio.xio_pages[i];
3108 * When restoring bogus changes the original pages
3109 * should still be wired, so we are in no danger of
3110 * losing the object association and do not need
3111 * critical section protection particularly.
3113 if (m == bogus_page) {
3114 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
3116 panic("vfs_unbusy_pages: page missing");
3118 bp->b_xio.xio_pages[i] = m;
3119 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3120 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3122 vm_object_pip_subtract(obj, 1);
3123 vm_page_flag_clear(m, PG_ZERO);
3124 vm_page_io_finish(m);
3126 vm_object_pip_wakeupn(obj, 0);
3131 * vfs_page_set_valid:
3133 * Set the valid bits in a page based on the supplied offset. The
3134 * range is restricted to the buffer's size.
3136 * This routine is typically called after a read completes.
3139 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3141 vm_ooffset_t soff, eoff;
3144 * Start and end offsets in buffer. eoff - soff may not cross a
3145 * page boundry or cross the end of the buffer. The end of the
3146 * buffer, in this case, is our file EOF, not the allocation size
3150 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3151 if (eoff > bp->b_offset + bp->b_bcount)
3152 eoff = bp->b_offset + bp->b_bcount;
3155 * Set valid range. This is typically the entire buffer and thus the
3159 vm_page_set_validclean(
3161 (vm_offset_t) (soff & PAGE_MASK),
3162 (vm_offset_t) (eoff - soff)
3170 * This routine is called before a device strategy routine.
3171 * It is used to tell the VM system that paging I/O is in
3172 * progress, and treat the pages associated with the buffer
3173 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3174 * flag is handled to make sure that the object doesn't become
3177 * Since I/O has not been initiated yet, certain buffer flags
3178 * such as B_ERROR or B_INVAL may be in an inconsistant state
3179 * and should be ignored.
3182 vfs_busy_pages(struct buf *bp, int clear_modify)
3186 if (bp->b_flags & B_VMIO) {
3187 struct vnode *vp = bp->b_vp;
3191 VOP_GETVOBJECT(vp, &obj);
3192 foff = bp->b_offset;
3193 KASSERT(bp->b_offset != NOOFFSET,
3194 ("vfs_busy_pages: no buffer offset"));
3198 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3199 vm_page_t m = bp->b_xio.xio_pages[i];
3200 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3205 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3206 vm_page_t m = bp->b_xio.xio_pages[i];
3208 vm_page_flag_clear(m, PG_ZERO);
3209 if ((bp->b_flags & B_CLUSTER) == 0) {
3210 vm_object_pip_add(obj, 1);
3211 vm_page_io_start(m);
3215 * When readying a buffer for a read ( i.e
3216 * clear_modify == 0 ), it is important to do
3217 * bogus_page replacement for valid pages in
3218 * partially instantiated buffers. Partially
3219 * instantiated buffers can, in turn, occur when
3220 * reconstituting a buffer from its VM backing store
3221 * base. We only have to do this if B_CACHE is
3222 * clear ( which causes the I/O to occur in the
3223 * first place ). The replacement prevents the read
3224 * I/O from overwriting potentially dirty VM-backed
3225 * pages. XXX bogus page replacement is, uh, bogus.
3226 * It may not work properly with small-block devices.
3227 * We need to find a better way.
3230 vm_page_protect(m, VM_PROT_NONE);
3232 vfs_page_set_valid(bp, foff, i, m);
3233 else if (m->valid == VM_PAGE_BITS_ALL &&
3234 (bp->b_flags & B_CACHE) == 0) {
3235 bp->b_xio.xio_pages[i] = bogus_page;
3238 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3241 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3242 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3246 * This is the easiest place to put the process accounting for the I/O
3252 if ((p = curthread->td_proc) != NULL) {
3253 if (bp->b_flags & B_READ)
3254 p->p_stats->p_ru.ru_inblock++;
3256 p->p_stats->p_ru.ru_oublock++;
3264 * Tell the VM system that the pages associated with this buffer
3265 * are clean. This is used for delayed writes where the data is
3266 * going to go to disk eventually without additional VM intevention.
3268 * Note that while we only really need to clean through to b_bcount, we
3269 * just go ahead and clean through to b_bufsize.
3272 vfs_clean_pages(struct buf *bp)
3276 if (bp->b_flags & B_VMIO) {
3279 foff = bp->b_offset;
3280 KASSERT(bp->b_offset != NOOFFSET,
3281 ("vfs_clean_pages: no buffer offset"));
3282 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3283 vm_page_t m = bp->b_xio.xio_pages[i];
3284 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3285 vm_ooffset_t eoff = noff;
3287 if (eoff > bp->b_offset + bp->b_bufsize)
3288 eoff = bp->b_offset + bp->b_bufsize;
3289 vfs_page_set_valid(bp, foff, i, m);
3290 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3297 * vfs_bio_set_validclean:
3299 * Set the range within the buffer to valid and clean. The range is
3300 * relative to the beginning of the buffer, b_offset. Note that b_offset
3301 * itself may be offset from the beginning of the first page.
3305 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3307 if (bp->b_flags & B_VMIO) {
3312 * Fixup base to be relative to beginning of first page.
3313 * Set initial n to be the maximum number of bytes in the
3314 * first page that can be validated.
3317 base += (bp->b_offset & PAGE_MASK);
3318 n = PAGE_SIZE - (base & PAGE_MASK);
3320 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3321 vm_page_t m = bp->b_xio.xio_pages[i];
3326 vm_page_set_validclean(m, base & PAGE_MASK, n);
3337 * Clear a buffer. This routine essentially fakes an I/O, so we need
3338 * to clear B_ERROR and B_INVAL.
3340 * Note that while we only theoretically need to clear through b_bcount,
3341 * we go ahead and clear through b_bufsize.
3345 vfs_bio_clrbuf(struct buf *bp)
3349 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3350 bp->b_flags &= ~(B_INVAL|B_ERROR);
3351 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3352 (bp->b_offset & PAGE_MASK) == 0) {
3353 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3354 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3358 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3359 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3360 bzero(bp->b_data, bp->b_bufsize);
3361 bp->b_xio.xio_pages[0]->valid |= mask;
3366 ea = sa = bp->b_data;
3367 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3368 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3369 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3370 ea = (caddr_t)(vm_offset_t)ulmin(
3371 (u_long)(vm_offset_t)ea,
3372 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3373 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3374 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3376 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3377 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3381 for (; sa < ea; sa += DEV_BSIZE, j++) {
3382 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3383 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3384 bzero(sa, DEV_BSIZE);
3387 bp->b_xio.xio_pages[i]->valid |= mask;
3388 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3397 * vm_hold_load_pages:
3399 * Load pages into the buffer's address space. The pages are
3400 * allocated from the kernel object in order to reduce interference
3401 * with the any VM paging I/O activity. The range of loaded
3402 * pages will be wired.
3404 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3405 * retrieve the full range (to - from) of pages.
3409 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3415 to = round_page(to);
3416 from = round_page(from);
3417 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3419 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3424 * Note: must allocate system pages since blocking here
3425 * could intefere with paging I/O, no matter which
3428 p = vm_page_alloc(kernel_object,
3429 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3430 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3432 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3437 p->valid = VM_PAGE_BITS_ALL;
3438 vm_page_flag_clear(p, PG_ZERO);
3439 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3440 bp->b_xio.xio_pages[index] = p;
3443 bp->b_xio.xio_npages = index;
3447 * vm_hold_free_pages:
3449 * Return pages associated with the buffer back to the VM system.
3451 * The range of pages underlying the buffer's address space will
3452 * be unmapped and un-wired.
3455 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3459 int index, newnpages;
3461 from = round_page(from);
3462 to = round_page(to);
3463 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3465 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3466 p = bp->b_xio.xio_pages[index];
3467 if (p && (index < bp->b_xio.xio_npages)) {
3469 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3470 bp->b_blkno, bp->b_lblkno);
3472 bp->b_xio.xio_pages[index] = NULL;
3475 vm_page_unwire(p, 0);
3479 bp->b_xio.xio_npages = newnpages;
3485 * Map an IO request into kernel virtual address space.
3487 * All requests are (re)mapped into kernel VA space.
3488 * Notice that we use b_bufsize for the size of the buffer
3489 * to be mapped. b_bcount might be modified by the driver.
3492 vmapbuf(struct buf *bp)
3494 caddr_t addr, v, kva;
3500 if ((bp->b_flags & B_PHYS) == 0)
3502 if (bp->b_bufsize < 0)
3504 for (v = bp->b_saveaddr,
3505 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3507 addr < bp->b_data + bp->b_bufsize;
3508 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3510 * Do the vm_fault if needed; do the copy-on-write thing
3511 * when reading stuff off device into memory.
3514 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3515 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3517 for (i = 0; i < pidx; ++i) {
3518 vm_page_unhold(bp->b_xio.xio_pages[i]);
3519 bp->b_xio.xio_pages[i] = NULL;
3525 * WARNING! If sparc support is MFCd in the future this will
3526 * have to be changed from pmap_kextract() to pmap_extract()
3530 #error "If MFCing sparc support use pmap_extract"
3532 pa = pmap_kextract((vm_offset_t)addr);
3534 printf("vmapbuf: warning, race against user address during I/O");
3537 m = PHYS_TO_VM_PAGE(pa);
3539 bp->b_xio.xio_pages[pidx] = m;
3541 if (pidx > btoc(MAXPHYS))
3542 panic("vmapbuf: mapped more than MAXPHYS");
3543 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_xio.xio_pages, pidx);
3545 kva = bp->b_saveaddr;
3546 bp->b_xio.xio_npages = pidx;
3547 bp->b_saveaddr = bp->b_data;
3548 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3555 * Free the io map PTEs associated with this IO operation.
3556 * We also invalidate the TLB entries and restore the original b_addr.
3559 vunmapbuf(struct buf *bp)
3565 if ((bp->b_flags & B_PHYS) == 0)
3568 npages = bp->b_xio.xio_npages;
3569 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3571 m = bp->b_xio.xio_pages;
3572 for (pidx = 0; pidx < npages; pidx++)
3573 vm_page_unhold(*m++);
3575 bp->b_data = bp->b_saveaddr;
3579 * print out statistics from the current status of the buffer pool
3580 * this can be toggeled by the system control option debug.syncprt
3589 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3590 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3592 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3594 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3597 TAILQ_FOREACH(bp, dp, b_freelist) {
3598 counts[bp->b_bufsize/PAGE_SIZE]++;
3602 printf("%s: total-%d", bname[i], count);
3603 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3605 printf(", %d-%d", j * PAGE_SIZE, counts[j]);
3611 #include "opt_ddb.h"
3613 #include <ddb/ddb.h>
3615 DB_SHOW_COMMAND(buffer, db_show_buffer)
3618 struct buf *bp = (struct buf *)addr;
3621 db_printf("usage: show buffer <addr>\n");
3625 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3626 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3627 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3628 "b_blkno = %d, b_pblkno = %d\n",
3629 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3630 major(bp->b_dev), minor(bp->b_dev),
3631 bp->b_data, bp->b_blkno, bp->b_pblkno);
3632 if (bp->b_xio.xio_npages) {
3634 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3635 bp->b_xio.xio_npages);
3636 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3638 m = bp->b_xio.xio_pages[i];
3639 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3640 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3641 if ((i + 1) < bp->b_xio.xio_npages)