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.37 2005/06/06 15:02:28 dillon Exp $
19 * this file contains a new buffer I/O scheme implementing a coherent
20 * VM object and buffer cache scheme. Pains have been taken to make
21 * sure that the performance degradation associated with schemes such
22 * as this is not realized.
24 * Author: John S. Dyson
25 * Significant help during the development and debugging phases
26 * had been provided by David Greenman, also of the FreeBSD core team.
28 * see man buf(9) for more info.
31 #include <sys/param.h>
32 #include <sys/systm.h>
35 #include <sys/eventhandler.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
58 #include <sys/thread2.h>
59 #include <vm/vm_page2.h>
61 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
63 struct bio_ops bioops; /* I/O operation notification */
65 struct buf *buf; /* buffer header pool */
66 struct swqueue bswlist;
68 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
70 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
72 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
73 int pageno, vm_page_t m);
74 static void vfs_clean_pages(struct buf * bp);
75 static void vfs_setdirty(struct buf *bp);
76 static void vfs_vmio_release(struct buf *bp);
78 static void vfs_backgroundwritedone(struct buf *bp);
80 static int flushbufqueues(void);
82 static int bd_request;
84 static void buf_daemon (void);
86 * bogus page -- for I/O to/from partially complete buffers
87 * this is a temporary solution to the problem, but it is not
88 * really that bad. it would be better to split the buffer
89 * for input in the case of buffers partially already in memory,
90 * but the code is intricate enough already.
93 int vmiodirenable = TRUE;
95 struct lwkt_token buftimetoken; /* Interlock on setting prio and timo */
97 static vm_offset_t bogus_offset;
99 static int bufspace, maxbufspace,
100 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
101 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
102 static int needsbuffer;
103 static int lorunningspace, hirunningspace, runningbufreq;
104 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
105 static int numfreebuffers, lofreebuffers, hifreebuffers;
106 static int getnewbufcalls;
107 static int getnewbufrestarts;
109 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD,
110 &numdirtybuffers, 0, "");
111 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW,
112 &lodirtybuffers, 0, "");
113 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW,
114 &hidirtybuffers, 0, "");
115 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD,
116 &numfreebuffers, 0, "");
117 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW,
118 &lofreebuffers, 0, "");
119 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW,
120 &hifreebuffers, 0, "");
121 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD,
122 &runningbufspace, 0, "");
123 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW,
124 &lorunningspace, 0, "");
125 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW,
126 &hirunningspace, 0, "");
127 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD,
128 &maxbufspace, 0, "");
129 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD,
131 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD,
133 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD,
135 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW,
136 &maxbufmallocspace, 0, "");
137 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD,
138 &bufmallocspace, 0, "");
139 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW,
140 &getnewbufcalls, 0, "");
141 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW,
142 &getnewbufrestarts, 0, "");
143 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW,
144 &vmiodirenable, 0, "");
145 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW,
146 &bufdefragcnt, 0, "");
147 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW,
148 &buffreekvacnt, 0, "");
149 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW,
150 &bufreusecnt, 0, "");
154 * Disable background writes for now. There appear to be races in the
155 * flags tests and locking operations as well as races in the completion
156 * code modifying the original bp (origbp) without holding a lock, assuming
157 * critical section protection when there might not be critical section
160 * XXX disable also because the RB tree can't handle multiple blocks with
163 static int dobkgrdwrite = 0;
164 SYSCTL_INT(_debug, OID_AUTO, dobkgrdwrite, CTLFLAG_RW, &dobkgrdwrite, 0,
165 "Do background writes (honoring the BV_BKGRDWRITE flag)?");
168 static int bufhashmask;
169 static int bufhashshift;
170 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
171 struct bqueues bufqueues[BUFFER_QUEUES] = { { 0 } };
172 char *buf_wmesg = BUF_WMESG;
174 extern int vm_swap_size;
176 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
177 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
178 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
179 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
182 * Buffer hash table code. Note that the logical block scans linearly, which
183 * gives us some L1 cache locality.
188 bufhash(struct vnode *vnp, daddr_t bn)
194 * A variation on the Fibonacci hash that Knuth credits to
195 * R. W. Floyd, see Knuth's _Art of Computer Programming,
196 * Volume 3 / Sorting and Searching_
198 * We reduce the argument to 32 bits before doing the hash to
199 * avoid the need for a slow 64x64 multiply on 32 bit platforms.
201 * sizeof(struct vnode) is 168 on i386, so toss some of the lower
202 * bits of the vnode address to reduce the key range, which
203 * improves the distribution of keys across buckets.
205 * The file system cylinder group blocks are very heavily
206 * used. They are located at invervals of fbg, which is
207 * on the order of 89 to 94 * 2^10, depending on other
208 * filesystem parameters, for a 16k block size. Smaller block
209 * sizes will reduce fpg approximately proportionally. This
210 * will cause the cylinder group index to be hashed using the
211 * lower bits of the hash multiplier, which will not distribute
212 * the keys as uniformly in a classic Fibonacci hash where a
213 * relatively small number of the upper bits of the result
214 * are used. Using 2^16 as a close-enough approximation to
215 * fpg, split the hash multiplier in half, with the upper 16
216 * bits being the inverse of the golden ratio, and the lower
217 * 16 bits being a fraction between 1/3 and 3/7 (closer to
218 * 3/7 in this case), that gives good experimental results.
220 hashkey64 = ((u_int64_t)(uintptr_t)vnp >> 3) + (u_int64_t)bn;
221 hashkey = (((u_int32_t)(hashkey64 + (hashkey64 >> 32)) * 0x9E376DB1u) >>
222 bufhashshift) & bufhashmask;
223 return(&bufhashtbl[hashkey]);
229 * If someone is blocked due to there being too many dirty buffers,
230 * and numdirtybuffers is now reasonable, wake them up.
234 numdirtywakeup(int level)
236 if (numdirtybuffers <= level) {
237 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
238 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
239 wakeup(&needsbuffer);
247 * Called when buffer space is potentially available for recovery.
248 * getnewbuf() will block on this flag when it is unable to free
249 * sufficient buffer space. Buffer space becomes recoverable when
250 * bp's get placed back in the queues.
257 * If someone is waiting for BUF space, wake them up. Even
258 * though we haven't freed the kva space yet, the waiting
259 * process will be able to now.
261 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
262 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
263 wakeup(&needsbuffer);
268 * runningbufwakeup() - in-progress I/O accounting.
272 runningbufwakeup(struct buf *bp)
274 if (bp->b_runningbufspace) {
275 runningbufspace -= bp->b_runningbufspace;
276 bp->b_runningbufspace = 0;
277 if (runningbufreq && runningbufspace <= lorunningspace) {
279 wakeup(&runningbufreq);
287 * Called when a buffer has been added to one of the free queues to
288 * account for the buffer and to wakeup anyone waiting for free buffers.
289 * This typically occurs when large amounts of metadata are being handled
290 * by the buffer cache ( else buffer space runs out first, usually ).
298 needsbuffer &= ~VFS_BIO_NEED_ANY;
299 if (numfreebuffers >= hifreebuffers)
300 needsbuffer &= ~VFS_BIO_NEED_FREE;
301 wakeup(&needsbuffer);
306 * waitrunningbufspace()
308 * runningbufspace is a measure of the amount of I/O currently
309 * running. This routine is used in async-write situations to
310 * prevent creating huge backups of pending writes to a device.
311 * Only asynchronous writes are governed by this function.
313 * Reads will adjust runningbufspace, but will not block based on it.
314 * The read load has a side effect of reducing the allowed write load.
316 * This does NOT turn an async write into a sync write. It waits
317 * for earlier writes to complete and generally returns before the
318 * caller's write has reached the device.
321 waitrunningbufspace(void)
323 if (runningbufspace > hirunningspace) {
325 while (runningbufspace > hirunningspace) {
327 tsleep(&runningbufreq, 0, "wdrain", 0);
334 * vfs_buf_test_cache:
336 * Called when a buffer is extended. This function clears the B_CACHE
337 * bit if the newly extended portion of the buffer does not contain
342 vfs_buf_test_cache(struct buf *bp,
343 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
346 if (bp->b_flags & B_CACHE) {
347 int base = (foff + off) & PAGE_MASK;
348 if (vm_page_is_valid(m, base, size) == 0)
349 bp->b_flags &= ~B_CACHE;
355 bd_wakeup(int dirtybuflevel)
357 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
364 * bd_speedup - speedup the buffer cache flushing code
375 * Initialize buffer headers and related structures.
379 bufhashinit(caddr_t vaddr)
381 /* first, make a null hash table */
383 for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
385 bufhashtbl = (void *)vaddr;
386 vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
397 TAILQ_INIT(&bswlist);
398 LIST_INIT(&invalhash);
399 lwkt_token_init(&buftimetoken);
401 for (i = 0; i <= bufhashmask; i++)
402 LIST_INIT(&bufhashtbl[i]);
404 /* next, make a null set of free lists */
405 for (i = 0; i < BUFFER_QUEUES; i++)
406 TAILQ_INIT(&bufqueues[i]);
408 /* finally, initialize each buffer header and stick on empty q */
409 for (i = 0; i < nbuf; i++) {
411 bzero(bp, sizeof *bp);
412 bp->b_flags = B_INVAL; /* we're just an empty header */
414 bp->b_qindex = QUEUE_EMPTY;
416 xio_init(&bp->b_xio);
417 LIST_INIT(&bp->b_dep);
419 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
420 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
424 * maxbufspace is the absolute maximum amount of buffer space we are
425 * allowed to reserve in KVM and in real terms. The absolute maximum
426 * is nominally used by buf_daemon. hibufspace is the nominal maximum
427 * used by most other processes. The differential is required to
428 * ensure that buf_daemon is able to run when other processes might
429 * be blocked waiting for buffer space.
431 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
432 * this may result in KVM fragmentation which is not handled optimally
435 maxbufspace = nbuf * BKVASIZE;
436 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
437 lobufspace = hibufspace - MAXBSIZE;
439 lorunningspace = 512 * 1024;
440 hirunningspace = 1024 * 1024;
443 * Limit the amount of malloc memory since it is wired permanently into
444 * the kernel space. Even though this is accounted for in the buffer
445 * allocation, we don't want the malloced region to grow uncontrolled.
446 * The malloc scheme improves memory utilization significantly on average
447 * (small) directories.
449 maxbufmallocspace = hibufspace / 20;
452 * Reduce the chance of a deadlock occuring by limiting the number
453 * of delayed-write dirty buffers we allow to stack up.
455 hidirtybuffers = nbuf / 4 + 20;
458 * To support extreme low-memory systems, make sure hidirtybuffers cannot
459 * eat up all available buffer space. This occurs when our minimum cannot
460 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
461 * BKVASIZE'd (8K) buffers.
463 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
464 hidirtybuffers >>= 1;
466 lodirtybuffers = hidirtybuffers / 2;
469 * Try to keep the number of free buffers in the specified range,
470 * and give special processes (e.g. like buf_daemon) access to an
473 lofreebuffers = nbuf / 18 + 5;
474 hifreebuffers = 2 * lofreebuffers;
475 numfreebuffers = nbuf;
478 * Maximum number of async ops initiated per buf_daemon loop. This is
479 * somewhat of a hack at the moment, we really need to limit ourselves
480 * based on the number of bytes of I/O in-transit that were initiated
484 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
485 bogus_page = vm_page_alloc(kernel_object,
486 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
488 vmstats.v_wire_count++;
493 * bfreekva() - free the kva allocation for a buffer.
495 * Must be called from a critical section as this is the only locking for
498 * Since this call frees up buffer space, we call bufspacewakeup().
501 bfreekva(struct buf * bp)
507 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
508 vm_map_lock(buffer_map);
509 bufspace -= bp->b_kvasize;
510 vm_map_delete(buffer_map,
511 (vm_offset_t) bp->b_kvabase,
512 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
515 vm_map_unlock(buffer_map);
516 vm_map_entry_release(count);
525 * Remove the buffer from the appropriate free list.
528 bremfree(struct buf * bp)
533 old_qindex = bp->b_qindex;
535 if (bp->b_qindex != QUEUE_NONE) {
536 KASSERT(BUF_REFCNTNB(bp) == 1,
537 ("bremfree: bp %p not locked",bp));
538 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
539 bp->b_qindex = QUEUE_NONE;
541 if (BUF_REFCNTNB(bp) <= 1)
542 panic("bremfree: removing a buffer not on a queue");
546 * Fixup numfreebuffers count. If the buffer is invalid or not
547 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
548 * the buffer was free and we must decrement numfreebuffers.
550 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
567 * Get a buffer with the specified data. Look in the cache first. We
568 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
569 * is set, the buffer is valid and we do not have to do anything ( see
573 bread(struct vnode * vp, daddr_t blkno, int size, struct buf ** bpp)
577 bp = getblk(vp, blkno, size, 0, 0);
580 /* if not found in cache, do some I/O */
581 if ((bp->b_flags & B_CACHE) == 0) {
582 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
583 bp->b_flags |= B_READ;
584 bp->b_flags &= ~(B_ERROR | B_INVAL);
585 vfs_busy_pages(bp, 0);
586 VOP_STRATEGY(vp, bp);
587 return (biowait(bp));
593 * Operates like bread, but also starts asynchronous I/O on
594 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
595 * to initiating I/O . If B_CACHE is set, the buffer is valid
596 * and we do not have to do anything.
599 breadn(struct vnode * vp, daddr_t blkno, int size, daddr_t * rablkno,
600 int *rabsize, int cnt, struct buf ** bpp)
602 struct buf *bp, *rabp;
604 int rv = 0, readwait = 0;
606 *bpp = bp = getblk(vp, blkno, size, 0, 0);
608 /* if not found in cache, do some I/O */
609 if ((bp->b_flags & B_CACHE) == 0) {
610 bp->b_flags |= B_READ;
611 bp->b_flags &= ~(B_ERROR | B_INVAL);
612 vfs_busy_pages(bp, 0);
613 VOP_STRATEGY(vp, bp);
617 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
618 if (inmem(vp, *rablkno))
620 rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
622 if ((rabp->b_flags & B_CACHE) == 0) {
623 rabp->b_flags |= B_READ | B_ASYNC;
624 rabp->b_flags &= ~(B_ERROR | B_INVAL);
625 vfs_busy_pages(rabp, 0);
627 VOP_STRATEGY(vp, rabp);
640 * Write, release buffer on completion. (Done by iodone
641 * if async). Do not bother writing anything if the buffer
644 * Note that we set B_CACHE here, indicating that buffer is
645 * fully valid and thus cacheable. This is true even of NFS
646 * now so we set it generally. This could be set either here
647 * or in biodone() since the I/O is synchronous. We put it
651 bwrite(struct buf * bp)
658 if (bp->b_flags & B_INVAL) {
663 oldflags = bp->b_flags;
665 if (BUF_REFCNTNB(bp) == 0)
666 panic("bwrite: buffer is not busy???");
669 * If a background write is already in progress, delay
670 * writing this block if it is asynchronous. Otherwise
671 * wait for the background write to complete.
673 if (bp->b_xflags & BX_BKGRDINPROG) {
674 if (bp->b_flags & B_ASYNC) {
679 bp->b_xflags |= BX_BKGRDWAIT;
680 tsleep(&bp->b_xflags, 0, "biord", 0);
681 if (bp->b_xflags & BX_BKGRDINPROG)
682 panic("bwrite: still writing");
685 /* Mark the buffer clean */
690 * If this buffer is marked for background writing and we
691 * do not have to wait for it, make a copy and write the
692 * copy so as to leave this buffer ready for further use.
694 * This optimization eats a lot of memory. If we have a page
695 * or buffer shortfull we can't do it.
697 * XXX DISABLED! This had to be removed to support the RB_TREE
698 * work and, really, this isn't the best place to do this sort
699 * of thing anyway. We really need a device copy-on-write feature.
702 (bp->b_xflags & BX_BKGRDWRITE) &&
703 (bp->b_flags & B_ASYNC) &&
704 !vm_page_count_severe() &&
705 !buf_dirty_count_severe()) {
706 if (bp->b_flags & B_CALL)
707 panic("bwrite: need chained iodone");
709 /* get a new block */
710 newbp = geteblk(bp->b_bufsize);
712 /* set it to be identical to the old block */
713 memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
714 newbp->b_lblkno = bp->b_lblkno;
715 newbp->b_blkno = bp->b_blkno;
716 newbp->b_offset = bp->b_offset;
717 newbp->b_iodone = vfs_backgroundwritedone;
718 newbp->b_flags |= B_ASYNC | B_CALL;
719 newbp->b_flags &= ~B_INVAL;
720 bgetvp(bp->b_vp, newbp);
722 /* move over the dependencies */
723 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
724 (*bioops.io_movedeps)(bp, newbp);
727 * Initiate write on the copy, release the original to
728 * the B_LOCKED queue so that it cannot go away until
729 * the background write completes. If not locked it could go
730 * away and then be reconstituted while it was being written.
731 * If the reconstituted buffer were written, we could end up
732 * with two background copies being written at the same time.
734 bp->b_xflags |= BX_BKGRDINPROG;
735 bp->b_flags |= B_LOCKED;
741 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
742 bp->b_flags |= B_CACHE;
744 bp->b_vp->v_numoutput++;
745 vfs_busy_pages(bp, 1);
748 * Normal bwrites pipeline writes
750 bp->b_runningbufspace = bp->b_bufsize;
751 runningbufspace += bp->b_runningbufspace;
754 if (oldflags & B_ASYNC)
756 VOP_STRATEGY(bp->b_vp, bp);
758 if ((oldflags & B_ASYNC) == 0) {
759 int rtval = biowait(bp);
762 } else if ((oldflags & B_NOWDRAIN) == 0) {
764 * don't allow the async write to saturate the I/O
765 * system. Deadlocks can occur only if a device strategy
766 * routine (like in VN) turns around and issues another
767 * high-level write, in which case B_NOWDRAIN is expected
768 * to be set. Otherwise we will not deadlock here because
769 * we are blocking waiting for I/O that is already in-progress
772 waitrunningbufspace();
780 * Complete a background write started from bwrite.
783 vfs_backgroundwritedone(struct buf *bp)
788 * Find the original buffer that we are writing.
790 if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
791 panic("backgroundwritedone: lost buffer");
793 * Process dependencies then return any unfinished ones.
795 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
796 (*bioops.io_complete)(bp);
797 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
798 (*bioops.io_movedeps)(bp, origbp);
800 * Clear the BX_BKGRDINPROG flag in the original buffer
801 * and awaken it if it is waiting for the write to complete.
802 * If BX_BKGRDINPROG is not set in the original buffer it must
803 * have been released and re-instantiated - which is not legal.
805 KASSERT((origbp->b_xflags & BX_BKGRDINPROG), ("backgroundwritedone: lost buffer2"));
806 origbp->b_xflags &= ~BX_BKGRDINPROG;
807 if (origbp->b_xflags & BX_BKGRDWAIT) {
808 origbp->b_xflags &= ~BX_BKGRDWAIT;
809 wakeup(&origbp->b_xflags);
812 * Clear the B_LOCKED flag and remove it from the locked
813 * queue if it currently resides there.
815 origbp->b_flags &= ~B_LOCKED;
816 if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
821 * This buffer is marked B_NOCACHE, so when it is released
822 * by biodone, it will be tossed. We mark it with B_READ
823 * to avoid biodone doing a second vwakeup.
825 bp->b_flags |= B_NOCACHE | B_READ;
826 bp->b_flags &= ~(B_CACHE | B_CALL | B_DONE);
833 * Delayed write. (Buffer is marked dirty). Do not bother writing
834 * anything if the buffer is marked invalid.
836 * Note that since the buffer must be completely valid, we can safely
837 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
838 * biodone() in order to prevent getblk from writing the buffer
842 bdwrite(struct buf *bp)
844 if (BUF_REFCNTNB(bp) == 0)
845 panic("bdwrite: buffer is not busy");
847 if (bp->b_flags & B_INVAL) {
854 * Set B_CACHE, indicating that the buffer is fully valid. This is
855 * true even of NFS now.
857 bp->b_flags |= B_CACHE;
860 * This bmap keeps the system from needing to do the bmap later,
861 * perhaps when the system is attempting to do a sync. Since it
862 * is likely that the indirect block -- or whatever other datastructure
863 * that the filesystem needs is still in memory now, it is a good
864 * thing to do this. Note also, that if the pageout daemon is
865 * requesting a sync -- there might not be enough memory to do
866 * the bmap then... So, this is important to do.
868 if (bp->b_lblkno == bp->b_blkno) {
869 VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
873 * Set the *dirty* buffer range based upon the VM system dirty pages.
878 * We need to do this here to satisfy the vnode_pager and the
879 * pageout daemon, so that it thinks that the pages have been
880 * "cleaned". Note that since the pages are in a delayed write
881 * buffer -- the VFS layer "will" see that the pages get written
882 * out on the next sync, or perhaps the cluster will be completed.
888 * Wakeup the buffer flushing daemon if we have a lot of dirty
889 * buffers (midpoint between our recovery point and our stall
892 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
895 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
896 * due to the softdep code.
903 * Turn buffer into delayed write request. We must clear B_READ and
904 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
905 * itself to properly update it in the dirty/clean lists. We mark it
906 * B_DONE to ensure that any asynchronization of the buffer properly
907 * clears B_DONE ( else a panic will occur later ).
909 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
910 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
911 * should only be called if the buffer is known-good.
913 * Since the buffer is not on a queue, we do not update the numfreebuffers
916 * Must be called from a critical section.
917 * The buffer must be on QUEUE_NONE.
920 bdirty(struct buf *bp)
922 KASSERT(bp->b_qindex == QUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
923 bp->b_flags &= ~(B_READ|B_RELBUF);
925 if ((bp->b_flags & B_DELWRI) == 0) {
926 bp->b_flags |= B_DONE | B_DELWRI;
927 reassignbuf(bp, bp->b_vp);
929 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
936 * Clear B_DELWRI for buffer.
938 * Since the buffer is not on a queue, we do not update the numfreebuffers
941 * Must be called from a critical section.
943 * The buffer is typically on QUEUE_NONE but there is one case in
944 * brelse() that calls this function after placing the buffer on
949 bundirty(struct buf *bp)
951 if (bp->b_flags & B_DELWRI) {
952 bp->b_flags &= ~B_DELWRI;
953 reassignbuf(bp, bp->b_vp);
955 numdirtywakeup(lodirtybuffers);
958 * Since it is now being written, we can clear its deferred write flag.
960 bp->b_flags &= ~B_DEFERRED;
966 * Asynchronous write. Start output on a buffer, but do not wait for
967 * it to complete. The buffer is released when the output completes.
969 * bwrite() ( or the VOP routine anyway ) is responsible for handling
970 * B_INVAL buffers. Not us.
973 bawrite(struct buf * bp)
975 bp->b_flags |= B_ASYNC;
976 (void) VOP_BWRITE(bp->b_vp, bp);
982 * Ordered write. Start output on a buffer, and flag it so that the
983 * device will write it in the order it was queued. The buffer is
984 * released when the output completes. bwrite() ( or the VOP routine
985 * anyway ) is responsible for handling B_INVAL buffers.
988 bowrite(struct buf * bp)
990 bp->b_flags |= B_ORDERED | B_ASYNC;
991 return (VOP_BWRITE(bp->b_vp, bp));
997 * Called prior to the locking of any vnodes when we are expecting to
998 * write. We do not want to starve the buffer cache with too many
999 * dirty buffers so we block here. By blocking prior to the locking
1000 * of any vnodes we attempt to avoid the situation where a locked vnode
1001 * prevents the various system daemons from flushing related buffers.
1007 if (numdirtybuffers >= hidirtybuffers) {
1009 while (numdirtybuffers >= hidirtybuffers) {
1011 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
1012 tsleep(&needsbuffer, 0, "flswai", 0);
1019 * Return true if we have too many dirty buffers.
1022 buf_dirty_count_severe(void)
1024 return(numdirtybuffers >= hidirtybuffers);
1030 * Release a busy buffer and, if requested, free its resources. The
1031 * buffer will be stashed in the appropriate bufqueue[] allowing it
1032 * to be accessed later as a cache entity or reused for other purposes.
1035 brelse(struct buf * bp)
1037 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1041 if (bp->b_flags & B_LOCKED)
1042 bp->b_flags &= ~B_ERROR;
1044 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
1046 * Failed write, redirty. Must clear B_ERROR to prevent
1047 * pages from being scrapped. If B_INVAL is set then
1048 * this case is not run and the next case is run to
1049 * destroy the buffer. B_INVAL can occur if the buffer
1050 * is outside the range supported by the underlying device.
1052 bp->b_flags &= ~B_ERROR;
1054 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
1055 (bp->b_bufsize <= 0)) {
1057 * Either a failed I/O or we were asked to free or not
1060 bp->b_flags |= B_INVAL;
1061 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1062 (*bioops.io_deallocate)(bp);
1063 if (bp->b_flags & B_DELWRI) {
1065 numdirtywakeup(lodirtybuffers);
1067 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
1068 if ((bp->b_flags & B_VMIO) == 0) {
1077 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1078 * is called with B_DELWRI set, the underlying pages may wind up
1079 * getting freed causing a previous write (bdwrite()) to get 'lost'
1080 * because pages associated with a B_DELWRI bp are marked clean.
1082 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1083 * if B_DELWRI is set.
1085 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1086 * on pages to return pages to the VM page queues.
1088 if (bp->b_flags & B_DELWRI)
1089 bp->b_flags &= ~B_RELBUF;
1090 else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1091 bp->b_flags |= B_RELBUF;
1094 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1095 * constituted, not even NFS buffers now. Two flags effect this. If
1096 * B_INVAL, the struct buf is invalidated but the VM object is kept
1097 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1099 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1100 * invalidated. B_ERROR cannot be set for a failed write unless the
1101 * buffer is also B_INVAL because it hits the re-dirtying code above.
1103 * Normally we can do this whether a buffer is B_DELWRI or not. If
1104 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1105 * the commit state and we cannot afford to lose the buffer. If the
1106 * buffer has a background write in progress, we need to keep it
1107 * around to prevent it from being reconstituted and starting a second
1110 if ((bp->b_flags & B_VMIO)
1111 && !(bp->b_vp->v_tag == VT_NFS &&
1112 !vn_isdisk(bp->b_vp, NULL) &&
1113 (bp->b_flags & B_DELWRI))
1126 * Get the base offset and length of the buffer. Note that
1127 * in the VMIO case if the buffer block size is not
1128 * page-aligned then b_data pointer may not be page-aligned.
1129 * But our b_xio.xio_pages array *IS* page aligned.
1131 * block sizes less then DEV_BSIZE (usually 512) are not
1132 * supported due to the page granularity bits (m->valid,
1133 * m->dirty, etc...).
1135 * See man buf(9) for more information
1138 resid = bp->b_bufsize;
1139 foff = bp->b_offset;
1141 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1142 m = bp->b_xio.xio_pages[i];
1143 vm_page_flag_clear(m, PG_ZERO);
1145 * If we hit a bogus page, fixup *all* of them
1146 * now. Note that we left these pages wired
1147 * when we removed them so they had better exist,
1148 * and they cannot be ripped out from under us so
1149 * no critical section protection is necessary.
1151 if (m == bogus_page) {
1152 VOP_GETVOBJECT(vp, &obj);
1153 poff = OFF_TO_IDX(bp->b_offset);
1155 for (j = i; j < bp->b_xio.xio_npages; j++) {
1158 mtmp = bp->b_xio.xio_pages[j];
1159 if (mtmp == bogus_page) {
1160 mtmp = vm_page_lookup(obj, poff + j);
1162 panic("brelse: page missing");
1164 bp->b_xio.xio_pages[j] = mtmp;
1168 if ((bp->b_flags & B_INVAL) == 0) {
1169 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1170 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1172 m = bp->b_xio.xio_pages[i];
1176 * Invalidate the backing store if B_NOCACHE is set
1177 * (e.g. used with vinvalbuf()). If this is NFS
1178 * we impose a requirement that the block size be
1179 * a multiple of PAGE_SIZE and create a temporary
1180 * hack to basically invalidate the whole page. The
1181 * problem is that NFS uses really odd buffer sizes
1182 * especially when tracking piecemeal writes and
1183 * it also vinvalbuf()'s a lot, which would result
1184 * in only partial page validation and invalidation
1185 * here. If the file page is mmap()'d, however,
1186 * all the valid bits get set so after we invalidate
1187 * here we would end up with weird m->valid values
1188 * like 0xfc. nfs_getpages() can't handle this so
1189 * we clear all the valid bits for the NFS case
1190 * instead of just some of them.
1192 * The real bug is the VM system having to set m->valid
1193 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1194 * itself is an artifact of the whole 512-byte
1195 * granular mess that exists to support odd block
1196 * sizes and UFS meta-data block sizes (e.g. 6144).
1197 * A complete rewrite is required.
1199 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1200 int poffset = foff & PAGE_MASK;
1203 presid = PAGE_SIZE - poffset;
1204 if (bp->b_vp->v_tag == VT_NFS &&
1205 bp->b_vp->v_type == VREG) {
1207 } else if (presid > resid) {
1210 KASSERT(presid >= 0, ("brelse: extra page"));
1211 vm_page_set_invalid(m, poffset, presid);
1213 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1214 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1217 if (bp->b_flags & (B_INVAL | B_RELBUF))
1218 vfs_vmio_release(bp);
1220 } else if (bp->b_flags & B_VMIO) {
1222 if (bp->b_flags & (B_INVAL | B_RELBUF))
1223 vfs_vmio_release(bp);
1227 if (bp->b_qindex != QUEUE_NONE)
1228 panic("brelse: free buffer onto another queue???");
1229 if (BUF_REFCNTNB(bp) > 1) {
1230 /* Temporary panic to verify exclusive locking */
1231 /* This panic goes away when we allow shared refs */
1232 panic("brelse: multiple refs");
1233 /* do not release to free list */
1241 /* buffers with no memory */
1242 if (bp->b_bufsize == 0) {
1243 bp->b_flags |= B_INVAL;
1244 bp->b_xflags &= ~BX_BKGRDWRITE;
1245 if (bp->b_xflags & BX_BKGRDINPROG)
1246 panic("losing buffer 1");
1247 if (bp->b_kvasize) {
1248 bp->b_qindex = QUEUE_EMPTYKVA;
1250 bp->b_qindex = QUEUE_EMPTY;
1252 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1253 LIST_REMOVE(bp, b_hash);
1254 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1256 /* buffers with junk contents */
1257 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1258 bp->b_flags |= B_INVAL;
1259 bp->b_xflags &= ~BX_BKGRDWRITE;
1260 if (bp->b_xflags & BX_BKGRDINPROG)
1261 panic("losing buffer 2");
1262 bp->b_qindex = QUEUE_CLEAN;
1263 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1264 LIST_REMOVE(bp, b_hash);
1265 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1268 /* buffers that are locked */
1269 } else if (bp->b_flags & B_LOCKED) {
1270 bp->b_qindex = QUEUE_LOCKED;
1271 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1273 /* remaining buffers */
1275 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1276 case B_DELWRI | B_AGE:
1277 bp->b_qindex = QUEUE_DIRTY;
1278 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1281 bp->b_qindex = QUEUE_DIRTY;
1282 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1285 bp->b_qindex = QUEUE_CLEAN;
1286 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1289 bp->b_qindex = QUEUE_CLEAN;
1290 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1296 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1297 * on the correct queue.
1299 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1303 * Fixup numfreebuffers count. The bp is on an appropriate queue
1304 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1305 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1306 * if B_INVAL is set ).
1309 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1313 * Something we can maybe free or reuse
1315 if (bp->b_bufsize || bp->b_kvasize)
1320 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1321 B_DIRECT | B_NOWDRAIN);
1326 * Release a buffer back to the appropriate queue but do not try to free
1327 * it. The buffer is expected to be used again soon.
1329 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1330 * biodone() to requeue an async I/O on completion. It is also used when
1331 * known good buffers need to be requeued but we think we may need the data
1334 * XXX we should be able to leave the B_RELBUF hint set on completion.
1337 bqrelse(struct buf * bp)
1341 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1343 if (bp->b_qindex != QUEUE_NONE)
1344 panic("bqrelse: free buffer onto another queue???");
1345 if (BUF_REFCNTNB(bp) > 1) {
1346 /* do not release to free list */
1347 panic("bqrelse: multiple refs");
1352 if (bp->b_flags & B_LOCKED) {
1353 bp->b_flags &= ~B_ERROR;
1354 bp->b_qindex = QUEUE_LOCKED;
1355 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1356 /* buffers with stale but valid contents */
1357 } else if (bp->b_flags & B_DELWRI) {
1358 bp->b_qindex = QUEUE_DIRTY;
1359 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1360 } else if (vm_page_count_severe()) {
1362 * We are too low on memory, we have to try to free the
1363 * buffer (most importantly: the wired pages making up its
1364 * backing store) *now*.
1370 bp->b_qindex = QUEUE_CLEAN;
1371 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1374 if ((bp->b_flags & B_LOCKED) == 0 &&
1375 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1380 * Something we can maybe free or reuse.
1382 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1387 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1392 vfs_vmio_release(struct buf *bp)
1398 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1399 m = bp->b_xio.xio_pages[i];
1400 bp->b_xio.xio_pages[i] = NULL;
1402 * In order to keep page LRU ordering consistent, put
1403 * everything on the inactive queue.
1405 vm_page_unwire(m, 0);
1407 * We don't mess with busy pages, it is
1408 * the responsibility of the process that
1409 * busied the pages to deal with them.
1411 if ((m->flags & PG_BUSY) || (m->busy != 0))
1414 if (m->wire_count == 0) {
1415 vm_page_flag_clear(m, PG_ZERO);
1417 * Might as well free the page if we can and it has
1418 * no valid data. We also free the page if the
1419 * buffer was used for direct I/O.
1421 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid && m->hold_count == 0) {
1423 vm_page_protect(m, VM_PROT_NONE);
1425 } else if (bp->b_flags & B_DIRECT) {
1426 vm_page_try_to_free(m);
1427 } else if (vm_page_count_severe()) {
1428 vm_page_try_to_cache(m);
1433 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1434 if (bp->b_bufsize) {
1438 bp->b_xio.xio_npages = 0;
1439 bp->b_flags &= ~B_VMIO;
1445 * Check to see if a block is currently memory resident.
1448 gbincore(struct vnode * vp, daddr_t blkno)
1451 struct bufhashhdr *bh;
1453 bh = bufhash(vp, blkno);
1455 /* Search hash chain */
1456 LIST_FOREACH(bp, bh, b_hash) {
1458 if (bp->b_vp == vp && bp->b_lblkno == blkno)
1467 * Implement clustered async writes for clearing out B_DELWRI buffers.
1468 * This is much better then the old way of writing only one buffer at
1469 * a time. Note that we may not be presented with the buffers in the
1470 * correct order, so we search for the cluster in both directions.
1473 vfs_bio_awrite(struct buf * bp)
1477 daddr_t lblkno = bp->b_lblkno;
1478 struct vnode *vp = bp->b_vp;
1487 * right now we support clustered writing only to regular files. If
1488 * we find a clusterable block we could be in the middle of a cluster
1489 * rather then at the beginning.
1491 if ((vp->v_type == VREG) &&
1492 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1493 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1495 size = vp->v_mount->mnt_stat.f_iosize;
1496 maxcl = MAXPHYS / size;
1498 for (i = 1; i < maxcl; i++) {
1499 if ((bpa = gbincore(vp, lblkno + i)) &&
1500 BUF_REFCNT(bpa) == 0 &&
1501 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1502 (B_DELWRI | B_CLUSTEROK)) &&
1503 (bpa->b_bufsize == size)) {
1504 if ((bpa->b_blkno == bpa->b_lblkno) ||
1506 bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1512 for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1513 if ((bpa = gbincore(vp, lblkno - j)) &&
1514 BUF_REFCNT(bpa) == 0 &&
1515 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1516 (B_DELWRI | B_CLUSTEROK)) &&
1517 (bpa->b_bufsize == size)) {
1518 if ((bpa->b_blkno == bpa->b_lblkno) ||
1520 bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1529 * this is a possible cluster write
1532 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1538 BUF_LOCK(bp, LK_EXCLUSIVE);
1540 bp->b_flags |= B_ASYNC;
1544 * default (old) behavior, writing out only one block
1546 * XXX returns b_bufsize instead of b_bcount for nwritten?
1548 nwritten = bp->b_bufsize;
1549 (void) VOP_BWRITE(bp->b_vp, bp);
1557 * Find and initialize a new buffer header, freeing up existing buffers
1558 * in the bufqueues as necessary. The new buffer is returned locked.
1560 * Important: B_INVAL is not set. If the caller wishes to throw the
1561 * buffer away, the caller must set B_INVAL prior to calling brelse().
1564 * We have insufficient buffer headers
1565 * We have insufficient buffer space
1566 * buffer_map is too fragmented ( space reservation fails )
1567 * If we have to flush dirty buffers ( but we try to avoid this )
1569 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1570 * Instead we ask the buf daemon to do it for us. We attempt to
1571 * avoid piecemeal wakeups of the pageout daemon.
1575 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1581 static int flushingbufs;
1584 * We can't afford to block since we might be holding a vnode lock,
1585 * which may prevent system daemons from running. We deal with
1586 * low-memory situations by proactively returning memory and running
1587 * async I/O rather then sync I/O.
1591 --getnewbufrestarts;
1593 ++getnewbufrestarts;
1596 * Setup for scan. If we do not have enough free buffers,
1597 * we setup a degenerate case that immediately fails. Note
1598 * that if we are specially marked process, we are allowed to
1599 * dip into our reserves.
1601 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1603 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1604 * However, there are a number of cases (defragging, reusing, ...)
1605 * where we cannot backup.
1607 nqindex = QUEUE_EMPTYKVA;
1608 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1612 * If no EMPTYKVA buffers and we are either
1613 * defragging or reusing, locate a CLEAN buffer
1614 * to free or reuse. If bufspace useage is low
1615 * skip this step so we can allocate a new buffer.
1617 if (defrag || bufspace >= lobufspace) {
1618 nqindex = QUEUE_CLEAN;
1619 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1623 * If we could not find or were not allowed to reuse a
1624 * CLEAN buffer, check to see if it is ok to use an EMPTY
1625 * buffer. We can only use an EMPTY buffer if allocating
1626 * its KVA would not otherwise run us out of buffer space.
1628 if (nbp == NULL && defrag == 0 &&
1629 bufspace + maxsize < hibufspace) {
1630 nqindex = QUEUE_EMPTY;
1631 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1636 * Run scan, possibly freeing data and/or kva mappings on the fly
1640 while ((bp = nbp) != NULL) {
1641 int qindex = nqindex;
1644 * Calculate next bp ( we can only use it if we do not block
1645 * or do other fancy things ).
1647 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1650 nqindex = QUEUE_EMPTYKVA;
1651 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1654 case QUEUE_EMPTYKVA:
1655 nqindex = QUEUE_CLEAN;
1656 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1670 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1673 * Note: we no longer distinguish between VMIO and non-VMIO
1677 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1680 * If we are defragging then we need a buffer with
1681 * b_kvasize != 0. XXX this situation should no longer
1682 * occur, if defrag is non-zero the buffer's b_kvasize
1683 * should also be non-zero at this point. XXX
1685 if (defrag && bp->b_kvasize == 0) {
1686 printf("Warning: defrag empty buffer %p\n", bp);
1691 * Start freeing the bp. This is somewhat involved. nbp
1692 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1695 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1696 panic("getnewbuf: locked buf");
1699 if (qindex == QUEUE_CLEAN) {
1700 if (bp->b_flags & B_VMIO) {
1701 bp->b_flags &= ~B_ASYNC;
1702 vfs_vmio_release(bp);
1709 * NOTE: nbp is now entirely invalid. We can only restart
1710 * the scan from this point on.
1712 * Get the rest of the buffer freed up. b_kva* is still
1713 * valid after this operation.
1716 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1717 (*bioops.io_deallocate)(bp);
1718 if (bp->b_xflags & BX_BKGRDINPROG)
1719 panic("losing buffer 3");
1720 LIST_REMOVE(bp, b_hash);
1721 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1724 * critical section protection is not required when
1725 * scrapping a buffer's contents because it is already
1735 bp->b_blkno = bp->b_lblkno = 0;
1736 bp->b_offset = NOOFFSET;
1741 bp->b_xio.xio_npages = 0;
1742 bp->b_dirtyoff = bp->b_dirtyend = 0;
1744 LIST_INIT(&bp->b_dep);
1747 * If we are defragging then free the buffer.
1750 bp->b_flags |= B_INVAL;
1758 * If we are overcomitted then recover the buffer and its
1759 * KVM space. This occurs in rare situations when multiple
1760 * processes are blocked in getnewbuf() or allocbuf().
1762 if (bufspace >= hibufspace)
1764 if (flushingbufs && bp->b_kvasize != 0) {
1765 bp->b_flags |= B_INVAL;
1770 if (bufspace < lobufspace)
1776 * If we exhausted our list, sleep as appropriate. We may have to
1777 * wakeup various daemons and write out some dirty buffers.
1779 * Generally we are sleeping due to insufficient buffer space.
1787 flags = VFS_BIO_NEED_BUFSPACE;
1789 } else if (bufspace >= hibufspace) {
1791 flags = VFS_BIO_NEED_BUFSPACE;
1794 flags = VFS_BIO_NEED_ANY;
1797 bd_speedup(); /* heeeelp */
1799 needsbuffer |= flags;
1800 while (needsbuffer & flags) {
1801 if (tsleep(&needsbuffer, slpflag, waitmsg, slptimeo))
1806 * We finally have a valid bp. We aren't quite out of the
1807 * woods, we still have to reserve kva space. In order
1808 * to keep fragmentation sane we only allocate kva in
1811 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1813 if (maxsize != bp->b_kvasize) {
1814 vm_offset_t addr = 0;
1819 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1820 vm_map_lock(buffer_map);
1822 if (vm_map_findspace(buffer_map,
1823 vm_map_min(buffer_map), maxsize,
1826 * Uh oh. Buffer map is to fragmented. We
1827 * must defragment the map.
1829 vm_map_unlock(buffer_map);
1830 vm_map_entry_release(count);
1833 bp->b_flags |= B_INVAL;
1838 vm_map_insert(buffer_map, &count,
1840 addr, addr + maxsize,
1841 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1843 bp->b_kvabase = (caddr_t) addr;
1844 bp->b_kvasize = maxsize;
1845 bufspace += bp->b_kvasize;
1848 vm_map_unlock(buffer_map);
1849 vm_map_entry_release(count);
1851 bp->b_data = bp->b_kvabase;
1859 * buffer flushing daemon. Buffers are normally flushed by the
1860 * update daemon but if it cannot keep up this process starts to
1861 * take the load in an attempt to prevent getnewbuf() from blocking.
1864 static struct thread *bufdaemonthread;
1866 static struct kproc_desc buf_kp = {
1871 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1877 * This process needs to be suspended prior to shutdown sync.
1879 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1880 bufdaemonthread, SHUTDOWN_PRI_LAST);
1883 * This process is allowed to take the buffer cache to the limit
1888 kproc_suspend_loop();
1891 * Do the flush. Limit the amount of in-transit I/O we
1892 * allow to build up, otherwise we would completely saturate
1893 * the I/O system. Wakeup any waiting processes before we
1894 * normally would so they can run in parallel with our drain.
1896 while (numdirtybuffers > lodirtybuffers) {
1897 if (flushbufqueues() == 0)
1899 waitrunningbufspace();
1900 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
1904 * Only clear bd_request if we have reached our low water
1905 * mark. The buf_daemon normally waits 5 seconds and
1906 * then incrementally flushes any dirty buffers that have
1907 * built up, within reason.
1909 * If we were unable to hit our low water mark and couldn't
1910 * find any flushable buffers, we sleep half a second.
1911 * Otherwise we loop immediately.
1913 if (numdirtybuffers <= lodirtybuffers) {
1915 * We reached our low water mark, reset the
1916 * request and sleep until we are needed again.
1917 * The sleep is just so the suspend code works.
1920 tsleep(&bd_request, 0, "psleep", hz);
1923 * We couldn't find any flushable dirty buffers but
1924 * still have too many dirty buffers, we
1925 * have to sleep and try again. (rare)
1927 tsleep(&bd_request, 0, "qsleep", hz / 2);
1935 * Try to flush a buffer in the dirty queue. We must be careful to
1936 * free up B_INVAL buffers instead of write them, which NFS is
1937 * particularly sensitive to.
1941 flushbufqueues(void)
1946 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1949 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1950 if ((bp->b_flags & B_DELWRI) != 0 &&
1951 (bp->b_xflags & BX_BKGRDINPROG) == 0) {
1952 if (bp->b_flags & B_INVAL) {
1953 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1954 panic("flushbufqueues: locked buf");
1960 if (LIST_FIRST(&bp->b_dep) != NULL &&
1961 bioops.io_countdeps &&
1962 (bp->b_flags & B_DEFERRED) == 0 &&
1963 (*bioops.io_countdeps)(bp, 0)) {
1964 TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY],
1966 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY],
1968 bp->b_flags |= B_DEFERRED;
1969 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1976 bp = TAILQ_NEXT(bp, b_freelist);
1982 * Check to see if a block is currently memory resident.
1985 incore(struct vnode * vp, daddr_t blkno)
1990 bp = gbincore(vp, blkno);
1996 * Returns true if no I/O is needed to access the associated VM object.
1997 * This is like incore except it also hunts around in the VM system for
2000 * Note that we ignore vm_page_free() races from interrupts against our
2001 * lookup, since if the caller is not protected our return value will not
2002 * be any more valid then otherwise once we exit the critical section.
2005 inmem(struct vnode * vp, daddr_t blkno)
2008 vm_offset_t toff, tinc, size;
2012 if (incore(vp, blkno))
2014 if (vp->v_mount == NULL)
2016 if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
2020 if (size > vp->v_mount->mnt_stat.f_iosize)
2021 size = vp->v_mount->mnt_stat.f_iosize;
2022 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2024 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2025 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2029 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2030 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2031 if (vm_page_is_valid(m,
2032 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2041 * Sets the dirty range for a buffer based on the status of the dirty
2042 * bits in the pages comprising the buffer.
2044 * The range is limited to the size of the buffer.
2046 * This routine is primarily used by NFS, but is generalized for the
2050 vfs_setdirty(struct buf *bp)
2056 * Degenerate case - empty buffer
2059 if (bp->b_bufsize == 0)
2063 * We qualify the scan for modified pages on whether the
2064 * object has been flushed yet. The OBJ_WRITEABLE flag
2065 * is not cleared simply by protecting pages off.
2068 if ((bp->b_flags & B_VMIO) == 0)
2071 object = bp->b_xio.xio_pages[0]->object;
2073 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2074 printf("Warning: object %p writeable but not mightbedirty\n", object);
2075 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2076 printf("Warning: object %p mightbedirty but not writeable\n", object);
2078 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2079 vm_offset_t boffset;
2080 vm_offset_t eoffset;
2083 * test the pages to see if they have been modified directly
2084 * by users through the VM system.
2086 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2087 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2088 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2092 * Calculate the encompassing dirty range, boffset and eoffset,
2093 * (eoffset - boffset) bytes.
2096 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2097 if (bp->b_xio.xio_pages[i]->dirty)
2100 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2102 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2103 if (bp->b_xio.xio_pages[i]->dirty) {
2107 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2110 * Fit it to the buffer.
2113 if (eoffset > bp->b_bcount)
2114 eoffset = bp->b_bcount;
2117 * If we have a good dirty range, merge with the existing
2121 if (boffset < eoffset) {
2122 if (bp->b_dirtyoff > boffset)
2123 bp->b_dirtyoff = boffset;
2124 if (bp->b_dirtyend < eoffset)
2125 bp->b_dirtyend = eoffset;
2133 * Get a block given a specified block and offset into a file/device.
2134 * The buffers B_DONE bit will be cleared on return, making it almost
2135 * ready for an I/O initiation. B_INVAL may or may not be set on
2136 * return. The caller should clear B_INVAL prior to initiating a
2139 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2140 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2141 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2142 * without doing any of those things the system will likely believe
2143 * the buffer to be valid (especially if it is not B_VMIO), and the
2144 * next getblk() will return the buffer with B_CACHE set.
2146 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2147 * an existing buffer.
2149 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2150 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2151 * and then cleared based on the backing VM. If the previous buffer is
2152 * non-0-sized but invalid, B_CACHE will be cleared.
2154 * If getblk() must create a new buffer, the new buffer is returned with
2155 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2156 * case it is returned with B_INVAL clear and B_CACHE set based on the
2159 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2160 * B_CACHE bit is clear.
2162 * What this means, basically, is that the caller should use B_CACHE to
2163 * determine whether the buffer is fully valid or not and should clear
2164 * B_INVAL prior to issuing a read. If the caller intends to validate
2165 * the buffer by loading its data area with something, the caller needs
2166 * to clear B_INVAL. If the caller does this without issuing an I/O,
2167 * the caller should set B_CACHE ( as an optimization ), else the caller
2168 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2169 * a write attempt or if it was a successfull read. If the caller
2170 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2171 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2174 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2177 struct bufhashhdr *bh;
2179 if (size > MAXBSIZE)
2180 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2185 * Block if we are low on buffers. Certain processes are allowed
2186 * to completely exhaust the buffer cache.
2188 * If this check ever becomes a bottleneck it may be better to
2189 * move it into the else, when gbincore() fails. At the moment
2190 * it isn't a problem.
2192 * XXX remove, we cannot afford to block anywhere if holding a vnode
2193 * lock in low-memory situation, so take it to the max.
2195 if (numfreebuffers == 0) {
2198 needsbuffer |= VFS_BIO_NEED_ANY;
2199 tsleep(&needsbuffer, slpflag, "newbuf", slptimeo);
2202 if ((bp = gbincore(vp, blkno))) {
2204 * Buffer is in-core. If the buffer is not busy, it must
2208 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2209 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2210 "getblk", slpflag, slptimeo) == ENOLCK)
2213 return (struct buf *) NULL;
2217 * The buffer is locked. B_CACHE is cleared if the buffer is
2218 * invalid. Ohterwise, for a non-VMIO buffer, B_CACHE is set
2219 * and for a VMIO buffer B_CACHE is adjusted according to the
2222 if (bp->b_flags & B_INVAL)
2223 bp->b_flags &= ~B_CACHE;
2224 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2225 bp->b_flags |= B_CACHE;
2229 * check for size inconsistancies for non-VMIO case.
2232 if (bp->b_bcount != size) {
2233 if ((bp->b_flags & B_VMIO) == 0 ||
2234 (size > bp->b_kvasize)) {
2235 if (bp->b_flags & B_DELWRI) {
2236 bp->b_flags |= B_NOCACHE;
2237 VOP_BWRITE(bp->b_vp, bp);
2239 if ((bp->b_flags & B_VMIO) &&
2240 (LIST_FIRST(&bp->b_dep) == NULL)) {
2241 bp->b_flags |= B_RELBUF;
2244 bp->b_flags |= B_NOCACHE;
2245 VOP_BWRITE(bp->b_vp, bp);
2253 * If the size is inconsistant in the VMIO case, we can resize
2254 * the buffer. This might lead to B_CACHE getting set or
2255 * cleared. If the size has not changed, B_CACHE remains
2256 * unchanged from its previous state.
2259 if (bp->b_bcount != size)
2262 KASSERT(bp->b_offset != NOOFFSET,
2263 ("getblk: no buffer offset"));
2266 * A buffer with B_DELWRI set and B_CACHE clear must
2267 * be committed before we can return the buffer in
2268 * order to prevent the caller from issuing a read
2269 * ( due to B_CACHE not being set ) and overwriting
2272 * Most callers, including NFS and FFS, need this to
2273 * operate properly either because they assume they
2274 * can issue a read if B_CACHE is not set, or because
2275 * ( for example ) an uncached B_DELWRI might loop due
2276 * to softupdates re-dirtying the buffer. In the latter
2277 * case, B_CACHE is set after the first write completes,
2278 * preventing further loops.
2280 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2281 * above while extending the buffer, we cannot allow the
2282 * buffer to remain with B_CACHE set after the write
2283 * completes or it will represent a corrupt state. To
2284 * deal with this we set B_NOCACHE to scrap the buffer
2287 * We might be able to do something fancy, like setting
2288 * B_CACHE in bwrite() except if B_DELWRI is already set,
2289 * so the below call doesn't set B_CACHE, but that gets real
2290 * confusing. This is much easier.
2293 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2294 bp->b_flags |= B_NOCACHE;
2295 VOP_BWRITE(bp->b_vp, bp);
2300 bp->b_flags &= ~B_DONE;
2303 * Buffer is not in-core, create new buffer. The buffer
2304 * returned by getnewbuf() is locked. Note that the returned
2305 * buffer is also considered valid (not marked B_INVAL).
2307 * Calculating the offset for the I/O requires figuring out
2308 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2309 * the mount's f_iosize otherwise. If the vnode does not
2310 * have an associated mount we assume that the passed size is
2313 * Note that vn_isdisk() cannot be used here since it may
2314 * return a failure for numerous reasons. Note that the
2315 * buffer size may be larger then the block size (the caller
2316 * will use block numbers with the proper multiple). Beware
2317 * of using any v_* fields which are part of unions. In
2318 * particular, in DragonFly the mount point overloading
2319 * mechanism is such that the underlying directory (with a
2320 * non-NULL v_mountedhere) is not a special case.
2322 int bsize, maxsize, vmio;
2325 if (vp->v_type == VBLK || vp->v_type == VCHR)
2327 else if (vp->v_mount)
2328 bsize = vp->v_mount->mnt_stat.f_iosize;
2332 offset = (off_t)blkno * bsize;
2333 vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2334 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2335 maxsize = imax(maxsize, bsize);
2337 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2338 if (slpflag || slptimeo) {
2346 * This code is used to make sure that a buffer is not
2347 * created while the getnewbuf routine is blocked.
2348 * This can be a problem whether the vnode is locked or not.
2349 * If the buffer is created out from under us, we have to
2350 * throw away the one we just created. There is now window
2351 * race because we are safely running in a critical section
2352 * from the point of the duplicate buffer creation through
2353 * to here, and we've locked the buffer.
2355 if (gbincore(vp, blkno)) {
2356 bp->b_flags |= B_INVAL;
2362 * Insert the buffer into the hash, so that it can
2363 * be found by incore.
2365 bp->b_blkno = bp->b_lblkno = blkno;
2366 bp->b_offset = offset;
2369 LIST_REMOVE(bp, b_hash);
2370 bh = bufhash(vp, blkno);
2371 LIST_INSERT_HEAD(bh, bp, b_hash);
2374 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2375 * buffer size starts out as 0, B_CACHE will be set by
2376 * allocbuf() for the VMIO case prior to it testing the
2377 * backing store for validity.
2381 bp->b_flags |= B_VMIO;
2382 #if defined(VFS_BIO_DEBUG)
2383 if (vn_canvmio(vp) != TRUE)
2384 printf("getblk: vmioing file type %d???\n", vp->v_type);
2387 bp->b_flags &= ~B_VMIO;
2393 bp->b_flags &= ~B_DONE;
2399 * Get an empty, disassociated buffer of given size. The buffer is initially
2402 * critical section protection is not required for the allocbuf() call
2403 * because races are impossible here.
2411 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2414 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2418 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2424 * This code constitutes the buffer memory from either anonymous system
2425 * memory (in the case of non-VMIO operations) or from an associated
2426 * VM object (in the case of VMIO operations). This code is able to
2427 * resize a buffer up or down.
2429 * Note that this code is tricky, and has many complications to resolve
2430 * deadlock or inconsistant data situations. Tread lightly!!!
2431 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2432 * the caller. Calling this code willy nilly can result in the loss of data.
2434 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2435 * B_CACHE for the non-VMIO case.
2437 * This routine does not need to be called from a critical section but you
2438 * must own the buffer.
2441 allocbuf(struct buf *bp, int size)
2443 int newbsize, mbsize;
2446 if (BUF_REFCNT(bp) == 0)
2447 panic("allocbuf: buffer not busy");
2449 if (bp->b_kvasize < size)
2450 panic("allocbuf: buffer too small");
2452 if ((bp->b_flags & B_VMIO) == 0) {
2456 * Just get anonymous memory from the kernel. Don't
2457 * mess with B_CACHE.
2459 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2460 #if !defined(NO_B_MALLOC)
2461 if (bp->b_flags & B_MALLOC)
2465 newbsize = round_page(size);
2467 if (newbsize < bp->b_bufsize) {
2468 #if !defined(NO_B_MALLOC)
2470 * malloced buffers are not shrunk
2472 if (bp->b_flags & B_MALLOC) {
2474 bp->b_bcount = size;
2476 free(bp->b_data, M_BIOBUF);
2477 if (bp->b_bufsize) {
2478 bufmallocspace -= bp->b_bufsize;
2482 bp->b_data = bp->b_kvabase;
2484 bp->b_flags &= ~B_MALLOC;
2491 (vm_offset_t) bp->b_data + newbsize,
2492 (vm_offset_t) bp->b_data + bp->b_bufsize);
2493 } else if (newbsize > bp->b_bufsize) {
2494 #if !defined(NO_B_MALLOC)
2496 * We only use malloced memory on the first allocation.
2497 * and revert to page-allocated memory when the buffer
2500 if ( (bufmallocspace < maxbufmallocspace) &&
2501 (bp->b_bufsize == 0) &&
2502 (mbsize <= PAGE_SIZE/2)) {
2504 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2505 bp->b_bufsize = mbsize;
2506 bp->b_bcount = size;
2507 bp->b_flags |= B_MALLOC;
2508 bufmallocspace += mbsize;
2514 #if !defined(NO_B_MALLOC)
2516 * If the buffer is growing on its other-than-first allocation,
2517 * then we revert to the page-allocation scheme.
2519 if (bp->b_flags & B_MALLOC) {
2520 origbuf = bp->b_data;
2521 origbufsize = bp->b_bufsize;
2522 bp->b_data = bp->b_kvabase;
2523 if (bp->b_bufsize) {
2524 bufmallocspace -= bp->b_bufsize;
2528 bp->b_flags &= ~B_MALLOC;
2529 newbsize = round_page(newbsize);
2534 (vm_offset_t) bp->b_data + bp->b_bufsize,
2535 (vm_offset_t) bp->b_data + newbsize);
2536 #if !defined(NO_B_MALLOC)
2538 bcopy(origbuf, bp->b_data, origbufsize);
2539 free(origbuf, M_BIOBUF);
2547 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2548 desiredpages = (size == 0) ? 0 :
2549 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2551 #if !defined(NO_B_MALLOC)
2552 if (bp->b_flags & B_MALLOC)
2553 panic("allocbuf: VMIO buffer can't be malloced");
2556 * Set B_CACHE initially if buffer is 0 length or will become
2559 if (size == 0 || bp->b_bufsize == 0)
2560 bp->b_flags |= B_CACHE;
2562 if (newbsize < bp->b_bufsize) {
2564 * DEV_BSIZE aligned new buffer size is less then the
2565 * DEV_BSIZE aligned existing buffer size. Figure out
2566 * if we have to remove any pages.
2568 if (desiredpages < bp->b_xio.xio_npages) {
2569 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2571 * the page is not freed here -- it
2572 * is the responsibility of
2573 * vnode_pager_setsize
2575 m = bp->b_xio.xio_pages[i];
2576 KASSERT(m != bogus_page,
2577 ("allocbuf: bogus page found"));
2578 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2581 bp->b_xio.xio_pages[i] = NULL;
2582 vm_page_unwire(m, 0);
2584 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2585 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2586 bp->b_xio.xio_npages = desiredpages;
2588 } else if (size > bp->b_bcount) {
2590 * We are growing the buffer, possibly in a
2591 * byte-granular fashion.
2599 * Step 1, bring in the VM pages from the object,
2600 * allocating them if necessary. We must clear
2601 * B_CACHE if these pages are not valid for the
2602 * range covered by the buffer.
2604 * critical section protection is required to protect
2605 * against interrupts unbusying and freeing pages
2606 * between our vm_page_lookup() and our
2607 * busycheck/wiring call.
2610 VOP_GETVOBJECT(vp, &obj);
2613 while (bp->b_xio.xio_npages < desiredpages) {
2617 pi = OFF_TO_IDX(bp->b_offset) + bp->b_xio.xio_npages;
2618 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2620 * note: must allocate system pages
2621 * since blocking here could intefere
2622 * with paging I/O, no matter which
2625 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2628 vm_pageout_deficit += desiredpages -
2629 bp->b_xio.xio_npages;
2633 bp->b_flags &= ~B_CACHE;
2634 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2635 ++bp->b_xio.xio_npages;
2641 * We found a page. If we have to sleep on it,
2642 * retry because it might have gotten freed out
2645 * We can only test PG_BUSY here. Blocking on
2646 * m->busy might lead to a deadlock:
2648 * vm_fault->getpages->cluster_read->allocbuf
2652 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2656 * We have a good page. Should we wakeup the
2659 if ((curthread != pagethread) &&
2660 ((m->queue - m->pc) == PQ_CACHE) &&
2661 ((vmstats.v_free_count + vmstats.v_cache_count) <
2662 (vmstats.v_free_min + vmstats.v_cache_min))) {
2663 pagedaemon_wakeup();
2665 vm_page_flag_clear(m, PG_ZERO);
2667 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2668 ++bp->b_xio.xio_npages;
2673 * Step 2. We've loaded the pages into the buffer,
2674 * we have to figure out if we can still have B_CACHE
2675 * set. Note that B_CACHE is set according to the
2676 * byte-granular range ( bcount and size ), new the
2677 * aligned range ( newbsize ).
2679 * The VM test is against m->valid, which is DEV_BSIZE
2680 * aligned. Needless to say, the validity of the data
2681 * needs to also be DEV_BSIZE aligned. Note that this
2682 * fails with NFS if the server or some other client
2683 * extends the file's EOF. If our buffer is resized,
2684 * B_CACHE may remain set! XXX
2687 toff = bp->b_bcount;
2688 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2690 while ((bp->b_flags & B_CACHE) && toff < size) {
2693 if (tinc > (size - toff))
2696 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2704 bp->b_xio.xio_pages[pi]
2711 * Step 3, fixup the KVM pmap. Remember that
2712 * bp->b_data is relative to bp->b_offset, but
2713 * bp->b_offset may be offset into the first page.
2716 bp->b_data = (caddr_t)
2717 trunc_page((vm_offset_t)bp->b_data);
2719 (vm_offset_t)bp->b_data,
2720 bp->b_xio.xio_pages,
2721 bp->b_xio.xio_npages
2723 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2724 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2727 if (newbsize < bp->b_bufsize)
2729 bp->b_bufsize = newbsize; /* actual buffer allocation */
2730 bp->b_bcount = size; /* requested buffer size */
2737 * Wait for buffer I/O completion, returning error status. The buffer
2738 * is left locked and B_DONE on return. B_EINTR is converted into a EINTR
2739 * error and cleared.
2742 biowait(struct buf * bp)
2745 while ((bp->b_flags & B_DONE) == 0) {
2746 #if defined(NO_SCHEDULE_MODS)
2747 tsleep(bp, 0, "biowait", 0);
2749 if (bp->b_flags & B_READ)
2750 tsleep(bp, 0, "biord", 0);
2752 tsleep(bp, 0, "biowr", 0);
2756 if (bp->b_flags & B_EINTR) {
2757 bp->b_flags &= ~B_EINTR;
2760 if (bp->b_flags & B_ERROR) {
2761 return (bp->b_error ? bp->b_error : EIO);
2770 * Finish I/O on a buffer, optionally calling a completion function.
2771 * This is usually called from an interrupt so process blocking is
2774 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2775 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2776 * assuming B_INVAL is clear.
2778 * For the VMIO case, we set B_CACHE if the op was a read and no
2779 * read error occured, or if the op was a write. B_CACHE is never
2780 * set if the buffer is invalid or otherwise uncacheable.
2782 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2783 * initiator to leave B_INVAL set to brelse the buffer out of existance
2784 * in the biodone routine.
2786 * b_dev is required to be reinitialized prior to the top level strategy
2787 * call in a device stack. To avoid improper reuse, biodone() sets
2791 biodone(struct buf *bp)
2797 KASSERT(BUF_REFCNTNB(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
2798 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2800 bp->b_flags |= B_DONE;
2802 runningbufwakeup(bp);
2804 if (bp->b_flags & B_FREEBUF) {
2810 if ((bp->b_flags & B_READ) == 0) {
2814 /* call optional completion function if requested */
2815 if (bp->b_flags & B_CALL) {
2816 bp->b_flags &= ~B_CALL;
2817 (*bp->b_iodone) (bp);
2821 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2822 (*bioops.io_complete)(bp);
2824 if (bp->b_flags & B_VMIO) {
2830 struct vnode *vp = bp->b_vp;
2832 error = VOP_GETVOBJECT(vp, &obj);
2834 #if defined(VFS_BIO_DEBUG)
2835 if (vp->v_holdcnt == 0) {
2836 panic("biodone: zero vnode hold count");
2840 panic("biodone: missing VM object");
2843 if ((vp->v_flag & VOBJBUF) == 0) {
2844 panic("biodone: vnode is not setup for merged cache");
2848 foff = bp->b_offset;
2849 KASSERT(bp->b_offset != NOOFFSET,
2850 ("biodone: no buffer offset"));
2853 panic("biodone: no object");
2855 #if defined(VFS_BIO_DEBUG)
2856 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
2857 printf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
2858 obj->paging_in_progress, bp->b_xio.xio_npages);
2863 * Set B_CACHE if the op was a normal read and no error
2864 * occured. B_CACHE is set for writes in the b*write()
2867 iosize = bp->b_bcount - bp->b_resid;
2868 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2869 bp->b_flags |= B_CACHE;
2872 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2876 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2881 * cleanup bogus pages, restoring the originals. Since
2882 * the originals should still be wired, we don't have
2883 * to worry about interrupt/freeing races destroying
2884 * the VM object association.
2886 m = bp->b_xio.xio_pages[i];
2887 if (m == bogus_page) {
2889 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2891 panic("biodone: page disappeared");
2892 bp->b_xio.xio_pages[i] = m;
2893 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2894 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
2896 #if defined(VFS_BIO_DEBUG)
2897 if (OFF_TO_IDX(foff) != m->pindex) {
2899 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2900 (unsigned long)foff, m->pindex);
2905 * In the write case, the valid and clean bits are
2906 * already changed correctly ( see bdwrite() ), so we
2907 * only need to do this here in the read case.
2909 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
2910 vfs_page_set_valid(bp, foff, i, m);
2912 vm_page_flag_clear(m, PG_ZERO);
2915 * when debugging new filesystems or buffer I/O methods, this
2916 * is the most common error that pops up. if you see this, you
2917 * have not set the page busy flag correctly!!!
2920 printf("biodone: page busy < 0, "
2921 "pindex: %d, foff: 0x(%x,%x), "
2922 "resid: %d, index: %d\n",
2923 (int) m->pindex, (int)(foff >> 32),
2924 (int) foff & 0xffffffff, resid, i);
2925 if (!vn_isdisk(vp, NULL))
2926 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
2927 bp->b_vp->v_mount->mnt_stat.f_iosize,
2929 bp->b_flags, bp->b_xio.xio_npages);
2931 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
2933 bp->b_flags, bp->b_xio.xio_npages);
2934 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2935 m->valid, m->dirty, m->wire_count);
2936 panic("biodone: page busy < 0");
2938 vm_page_io_finish(m);
2939 vm_object_pip_subtract(obj, 1);
2940 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2944 vm_object_pip_wakeupn(obj, 0);
2948 * For asynchronous completions, release the buffer now. The brelse
2949 * will do a wakeup there if necessary - so no need to do a wakeup
2950 * here in the async case. The sync case always needs to do a wakeup.
2953 if (bp->b_flags & B_ASYNC) {
2954 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
2965 * This routine is called in lieu of iodone in the case of
2966 * incomplete I/O. This keeps the busy status for pages
2970 vfs_unbusy_pages(struct buf *bp)
2974 runningbufwakeup(bp);
2975 if (bp->b_flags & B_VMIO) {
2976 struct vnode *vp = bp->b_vp;
2979 VOP_GETVOBJECT(vp, &obj);
2981 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2982 vm_page_t m = bp->b_xio.xio_pages[i];
2985 * When restoring bogus changes the original pages
2986 * should still be wired, so we are in no danger of
2987 * losing the object association and do not need
2988 * critical section protection particularly.
2990 if (m == bogus_page) {
2991 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
2993 panic("vfs_unbusy_pages: page missing");
2995 bp->b_xio.xio_pages[i] = m;
2996 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2997 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
2999 vm_object_pip_subtract(obj, 1);
3000 vm_page_flag_clear(m, PG_ZERO);
3001 vm_page_io_finish(m);
3003 vm_object_pip_wakeupn(obj, 0);
3008 * vfs_page_set_valid:
3010 * Set the valid bits in a page based on the supplied offset. The
3011 * range is restricted to the buffer's size.
3013 * This routine is typically called after a read completes.
3016 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3018 vm_ooffset_t soff, eoff;
3021 * Start and end offsets in buffer. eoff - soff may not cross a
3022 * page boundry or cross the end of the buffer. The end of the
3023 * buffer, in this case, is our file EOF, not the allocation size
3027 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3028 if (eoff > bp->b_offset + bp->b_bcount)
3029 eoff = bp->b_offset + bp->b_bcount;
3032 * Set valid range. This is typically the entire buffer and thus the
3036 vm_page_set_validclean(
3038 (vm_offset_t) (soff & PAGE_MASK),
3039 (vm_offset_t) (eoff - soff)
3045 * This routine is called before a device strategy routine.
3046 * It is used to tell the VM system that paging I/O is in
3047 * progress, and treat the pages associated with the buffer
3048 * almost as being PG_BUSY. Also the object paging_in_progress
3049 * flag is handled to make sure that the object doesn't become
3052 * Since I/O has not been initiated yet, certain buffer flags
3053 * such as B_ERROR or B_INVAL may be in an inconsistant state
3054 * and should be ignored.
3057 vfs_busy_pages(struct buf *bp, int clear_modify)
3061 if (bp->b_flags & B_VMIO) {
3062 struct vnode *vp = bp->b_vp;
3066 VOP_GETVOBJECT(vp, &obj);
3067 foff = bp->b_offset;
3068 KASSERT(bp->b_offset != NOOFFSET,
3069 ("vfs_busy_pages: no buffer offset"));
3073 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3074 vm_page_t m = bp->b_xio.xio_pages[i];
3075 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3080 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3081 vm_page_t m = bp->b_xio.xio_pages[i];
3083 vm_page_flag_clear(m, PG_ZERO);
3084 if ((bp->b_flags & B_CLUSTER) == 0) {
3085 vm_object_pip_add(obj, 1);
3086 vm_page_io_start(m);
3090 * When readying a buffer for a read ( i.e
3091 * clear_modify == 0 ), it is important to do
3092 * bogus_page replacement for valid pages in
3093 * partially instantiated buffers. Partially
3094 * instantiated buffers can, in turn, occur when
3095 * reconstituting a buffer from its VM backing store
3096 * base. We only have to do this if B_CACHE is
3097 * clear ( which causes the I/O to occur in the
3098 * first place ). The replacement prevents the read
3099 * I/O from overwriting potentially dirty VM-backed
3100 * pages. XXX bogus page replacement is, uh, bogus.
3101 * It may not work properly with small-block devices.
3102 * We need to find a better way.
3105 vm_page_protect(m, VM_PROT_NONE);
3107 vfs_page_set_valid(bp, foff, i, m);
3108 else if (m->valid == VM_PAGE_BITS_ALL &&
3109 (bp->b_flags & B_CACHE) == 0) {
3110 bp->b_xio.xio_pages[i] = bogus_page;
3113 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3116 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3117 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3121 * This is the easiest place to put the process accounting for the I/O
3127 if ((p = curthread->td_proc) != NULL) {
3128 if (bp->b_flags & B_READ)
3129 p->p_stats->p_ru.ru_inblock++;
3131 p->p_stats->p_ru.ru_oublock++;
3137 * Tell the VM system that the pages associated with this buffer
3138 * are clean. This is used for delayed writes where the data is
3139 * going to go to disk eventually without additional VM intevention.
3141 * Note that while we only really need to clean through to b_bcount, we
3142 * just go ahead and clean through to b_bufsize.
3145 vfs_clean_pages(struct buf *bp)
3149 if (bp->b_flags & B_VMIO) {
3152 foff = bp->b_offset;
3153 KASSERT(bp->b_offset != NOOFFSET,
3154 ("vfs_clean_pages: no buffer offset"));
3155 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3156 vm_page_t m = bp->b_xio.xio_pages[i];
3157 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3158 vm_ooffset_t eoff = noff;
3160 if (eoff > bp->b_offset + bp->b_bufsize)
3161 eoff = bp->b_offset + bp->b_bufsize;
3162 vfs_page_set_valid(bp, foff, i, m);
3163 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3170 * vfs_bio_set_validclean:
3172 * Set the range within the buffer to valid and clean. The range is
3173 * relative to the beginning of the buffer, b_offset. Note that b_offset
3174 * itself may be offset from the beginning of the first page.
3178 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3180 if (bp->b_flags & B_VMIO) {
3185 * Fixup base to be relative to beginning of first page.
3186 * Set initial n to be the maximum number of bytes in the
3187 * first page that can be validated.
3190 base += (bp->b_offset & PAGE_MASK);
3191 n = PAGE_SIZE - (base & PAGE_MASK);
3193 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3194 vm_page_t m = bp->b_xio.xio_pages[i];
3199 vm_page_set_validclean(m, base & PAGE_MASK, n);
3210 * clear a buffer. This routine essentially fakes an I/O, so we need
3211 * to clear B_ERROR and B_INVAL.
3213 * Note that while we only theoretically need to clear through b_bcount,
3214 * we go ahead and clear through b_bufsize.
3218 vfs_bio_clrbuf(struct buf *bp)
3222 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3223 bp->b_flags &= ~(B_INVAL|B_ERROR);
3224 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3225 (bp->b_offset & PAGE_MASK) == 0) {
3226 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3227 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3231 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3232 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3233 bzero(bp->b_data, bp->b_bufsize);
3234 bp->b_xio.xio_pages[0]->valid |= mask;
3239 ea = sa = bp->b_data;
3240 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3241 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3242 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3243 ea = (caddr_t)(vm_offset_t)ulmin(
3244 (u_long)(vm_offset_t)ea,
3245 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3246 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3247 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3249 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3250 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3254 for (; sa < ea; sa += DEV_BSIZE, j++) {
3255 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3256 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3257 bzero(sa, DEV_BSIZE);
3260 bp->b_xio.xio_pages[i]->valid |= mask;
3261 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3270 * vm_hold_load_pages and vm_hold_unload pages get pages into
3271 * a buffers address space. The pages are anonymous and are
3272 * not associated with a file object.
3275 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3281 to = round_page(to);
3282 from = round_page(from);
3283 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3285 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3290 * note: must allocate system pages since blocking here
3291 * could intefere with paging I/O, no matter which
3294 p = vm_page_alloc(kernel_object,
3295 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3296 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3298 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3303 p->valid = VM_PAGE_BITS_ALL;
3304 vm_page_flag_clear(p, PG_ZERO);
3305 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3306 bp->b_xio.xio_pages[index] = p;
3309 bp->b_xio.xio_npages = index;
3313 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3317 int index, newnpages;
3319 from = round_page(from);
3320 to = round_page(to);
3321 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3323 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3324 p = bp->b_xio.xio_pages[index];
3325 if (p && (index < bp->b_xio.xio_npages)) {
3327 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3328 bp->b_blkno, bp->b_lblkno);
3330 bp->b_xio.xio_pages[index] = NULL;
3333 vm_page_unwire(p, 0);
3337 bp->b_xio.xio_npages = newnpages;
3341 * Map an IO request into kernel virtual address space.
3343 * All requests are (re)mapped into kernel VA space.
3344 * Notice that we use b_bufsize for the size of the buffer
3345 * to be mapped. b_bcount might be modified by the driver.
3348 vmapbuf(struct buf *bp)
3350 caddr_t addr, v, kva;
3356 if ((bp->b_flags & B_PHYS) == 0)
3358 if (bp->b_bufsize < 0)
3360 for (v = bp->b_saveaddr,
3361 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3363 addr < bp->b_data + bp->b_bufsize;
3364 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3366 * Do the vm_fault if needed; do the copy-on-write thing
3367 * when reading stuff off device into memory.
3370 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3371 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3373 for (i = 0; i < pidx; ++i) {
3374 vm_page_unhold(bp->b_xio.xio_pages[i]);
3375 bp->b_xio.xio_pages[i] = NULL;
3381 * WARNING! If sparc support is MFCd in the future this will
3382 * have to be changed from pmap_kextract() to pmap_extract()
3386 #error "If MFCing sparc support use pmap_extract"
3388 pa = pmap_kextract((vm_offset_t)addr);
3390 printf("vmapbuf: warning, race against user address during I/O");
3393 m = PHYS_TO_VM_PAGE(pa);
3395 bp->b_xio.xio_pages[pidx] = m;
3397 if (pidx > btoc(MAXPHYS))
3398 panic("vmapbuf: mapped more than MAXPHYS");
3399 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_xio.xio_pages, pidx);
3401 kva = bp->b_saveaddr;
3402 bp->b_xio.xio_npages = pidx;
3403 bp->b_saveaddr = bp->b_data;
3404 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3409 * Free the io map PTEs associated with this IO operation.
3410 * We also invalidate the TLB entries and restore the original b_addr.
3413 vunmapbuf(struct buf *bp)
3419 if ((bp->b_flags & B_PHYS) == 0)
3422 npages = bp->b_xio.xio_npages;
3423 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3425 m = bp->b_xio.xio_pages;
3426 for (pidx = 0; pidx < npages; pidx++)
3427 vm_page_unhold(*m++);
3429 bp->b_data = bp->b_saveaddr;
3432 #include "opt_ddb.h"
3434 #include <ddb/ddb.h>
3436 DB_SHOW_COMMAND(buffer, db_show_buffer)
3439 struct buf *bp = (struct buf *)addr;
3442 db_printf("usage: show buffer <addr>\n");
3446 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3447 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3448 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3449 "b_blkno = %d, b_pblkno = %d\n",
3450 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3451 major(bp->b_dev), minor(bp->b_dev),
3452 bp->b_data, bp->b_blkno, bp->b_pblkno);
3453 if (bp->b_xio.xio_npages) {
3455 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3456 bp->b_xio.xio_npages);
3457 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3459 m = bp->b_xio.xio_pages[i];
3460 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3461 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3462 if ((i + 1) < bp->b_xio.xio_npages)