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.64 2006/04/28 00:24:46 dillon Exp $
19 * this file contains a new buffer I/O scheme implementing a coherent
20 * VM object and buffer cache scheme. Pains have been taken to make
21 * sure that the performance degradation associated with schemes such
22 * as this is not realized.
24 * Author: John S. Dyson
25 * Significant help during the development and debugging phases
26 * had been provided by David Greenman, also of the FreeBSD core team.
28 * see man buf(9) for more info.
31 #include <sys/param.h>
32 #include <sys/systm.h>
35 #include <sys/eventhandler.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
58 #include <sys/thread2.h>
59 #include <vm/vm_page2.h>
64 #define BUFFER_QUEUES 6
66 BQUEUE_NONE, /* not on any queue */
67 BQUEUE_LOCKED, /* locked buffers */
68 BQUEUE_CLEAN, /* non-B_DELWRI buffers */
69 BQUEUE_DIRTY, /* B_DELWRI buffers */
70 BQUEUE_EMPTYKVA, /* empty buffer headers with KVA assignment */
71 BQUEUE_EMPTY /* empty buffer headers */
73 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
75 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
77 struct bio_ops bioops; /* I/O operation notification */
79 struct buf *buf; /* buffer header pool */
81 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
83 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
85 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
86 int pageno, vm_page_t m);
87 static void vfs_clean_pages(struct buf * bp);
88 static void vfs_setdirty(struct buf *bp);
89 static void vfs_vmio_release(struct buf *bp);
90 static int flushbufqueues(void);
92 static int bd_request;
94 static void buf_daemon (void);
96 * bogus page -- for I/O to/from partially complete buffers
97 * this is a temporary solution to the problem, but it is not
98 * really that bad. it would be better to split the buffer
99 * for input in the case of buffers partially already in memory,
100 * but the code is intricate enough already.
102 vm_page_t bogus_page;
105 static int bufspace, maxbufspace,
106 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
107 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
108 static int needsbuffer;
109 static int lorunningspace, hirunningspace, runningbufreq;
110 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
111 static int numfreebuffers, lofreebuffers, hifreebuffers;
112 static int getnewbufcalls;
113 static int getnewbufrestarts;
116 * Sysctls for operational control of the buffer cache.
118 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
119 "Number of dirty buffers to flush before bufdaemon becomes inactive");
120 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
121 "High watermark used to trigger explicit flushing of dirty buffers");
122 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
123 "Low watermark for special reserve in low-memory situations");
124 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
125 "High watermark for special reserve in low-memory situations");
126 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
127 "Minimum amount of buffer space required for active I/O");
128 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
129 "Maximum amount of buffer space to usable for active I/O");
131 * Sysctls determining current state of the buffer cache.
133 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
134 "Pending number of dirty buffers");
135 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
136 "Number of free buffers on the buffer cache free list");
137 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
138 "I/O bytes currently in progress due to asynchronous writes");
139 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
140 "Hard limit on maximum amount of memory usable for buffer space");
141 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
142 "Soft limit on maximum amount of memory usable for buffer space");
143 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
144 "Minimum amount of memory to reserve for system buffer space");
145 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
146 "Amount of memory available for buffers");
147 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
148 0, "Maximum amount of memory reserved for buffers using malloc");
149 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
150 "Amount of memory left for buffers using malloc-scheme");
151 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
152 "New buffer header acquisition requests");
153 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
154 0, "New buffer header acquisition restarts");
155 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
156 "Buffer acquisition restarts due to fragmented buffer map");
157 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
158 "Amount of time KVA space was deallocated in an arbitrary buffer");
159 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
160 "Amount of time buffer re-use operations were successful");
161 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
162 "sizeof(struct buf)");
164 char *buf_wmesg = BUF_WMESG;
166 extern int vm_swap_size;
168 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
169 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
170 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
171 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
176 * If someone is blocked due to there being too many dirty buffers,
177 * and numdirtybuffers is now reasonable, wake them up.
181 numdirtywakeup(int level)
183 if (numdirtybuffers <= level) {
184 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
185 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
186 wakeup(&needsbuffer);
194 * Called when buffer space is potentially available for recovery.
195 * getnewbuf() will block on this flag when it is unable to free
196 * sufficient buffer space. Buffer space becomes recoverable when
197 * bp's get placed back in the queues.
204 * If someone is waiting for BUF space, wake them up. Even
205 * though we haven't freed the kva space yet, the waiting
206 * process will be able to now.
208 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
209 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
210 wakeup(&needsbuffer);
217 * Accounting for I/O in progress.
221 runningbufwakeup(struct buf *bp)
223 if (bp->b_runningbufspace) {
224 runningbufspace -= bp->b_runningbufspace;
225 bp->b_runningbufspace = 0;
226 if (runningbufreq && runningbufspace <= lorunningspace) {
228 wakeup(&runningbufreq);
236 * Called when a buffer has been added to one of the free queues to
237 * account for the buffer and to wakeup anyone waiting for free buffers.
238 * This typically occurs when large amounts of metadata are being handled
239 * by the buffer cache ( else buffer space runs out first, usually ).
247 needsbuffer &= ~VFS_BIO_NEED_ANY;
248 if (numfreebuffers >= hifreebuffers)
249 needsbuffer &= ~VFS_BIO_NEED_FREE;
250 wakeup(&needsbuffer);
255 * waitrunningbufspace()
257 * runningbufspace is a measure of the amount of I/O currently
258 * running. This routine is used in async-write situations to
259 * prevent creating huge backups of pending writes to a device.
260 * Only asynchronous writes are governed by this function.
262 * Reads will adjust runningbufspace, but will not block based on it.
263 * The read load has a side effect of reducing the allowed write load.
265 * This does NOT turn an async write into a sync write. It waits
266 * for earlier writes to complete and generally returns before the
267 * caller's write has reached the device.
270 waitrunningbufspace(void)
272 if (runningbufspace > hirunningspace) {
274 while (runningbufspace > hirunningspace) {
276 tsleep(&runningbufreq, 0, "wdrain", 0);
283 * vfs_buf_test_cache:
285 * Called when a buffer is extended. This function clears the B_CACHE
286 * bit if the newly extended portion of the buffer does not contain
291 vfs_buf_test_cache(struct buf *bp,
292 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
295 if (bp->b_flags & B_CACHE) {
296 int base = (foff + off) & PAGE_MASK;
297 if (vm_page_is_valid(m, base, size) == 0)
298 bp->b_flags &= ~B_CACHE;
305 * Wake up the buffer daemon if the number of outstanding dirty buffers
306 * is above specified threshold 'dirtybuflevel'.
308 * The buffer daemon is explicitly woken up when (a) the pending number
309 * of dirty buffers exceeds the recovery and stall mid-point value,
310 * (b) during bwillwrite() or (c) buf freelist was exhausted.
314 bd_wakeup(int dirtybuflevel)
316 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
325 * Speed up the buffer cache flushing process.
338 * Load time initialisation of the buffer cache, called from machine
339 * dependant initialization code.
345 vm_offset_t bogus_offset;
348 /* next, make a null set of free lists */
349 for (i = 0; i < BUFFER_QUEUES; i++)
350 TAILQ_INIT(&bufqueues[i]);
352 /* finally, initialize each buffer header and stick on empty q */
353 for (i = 0; i < nbuf; i++) {
355 bzero(bp, sizeof *bp);
356 bp->b_flags = B_INVAL; /* we're just an empty header */
357 bp->b_qindex = BQUEUE_EMPTY;
359 xio_init(&bp->b_xio);
360 LIST_INIT(&bp->b_dep);
362 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
366 * maxbufspace is the absolute maximum amount of buffer space we are
367 * allowed to reserve in KVM and in real terms. The absolute maximum
368 * is nominally used by buf_daemon. hibufspace is the nominal maximum
369 * used by most other processes. The differential is required to
370 * ensure that buf_daemon is able to run when other processes might
371 * be blocked waiting for buffer space.
373 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
374 * this may result in KVM fragmentation which is not handled optimally
377 maxbufspace = nbuf * BKVASIZE;
378 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
379 lobufspace = hibufspace - MAXBSIZE;
381 lorunningspace = 512 * 1024;
382 hirunningspace = 1024 * 1024;
385 * Limit the amount of malloc memory since it is wired permanently into
386 * the kernel space. Even though this is accounted for in the buffer
387 * allocation, we don't want the malloced region to grow uncontrolled.
388 * The malloc scheme improves memory utilization significantly on average
389 * (small) directories.
391 maxbufmallocspace = hibufspace / 20;
394 * Reduce the chance of a deadlock occuring by limiting the number
395 * of delayed-write dirty buffers we allow to stack up.
397 hidirtybuffers = nbuf / 4 + 20;
400 * To support extreme low-memory systems, make sure hidirtybuffers cannot
401 * eat up all available buffer space. This occurs when our minimum cannot
402 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
403 * BKVASIZE'd (8K) buffers.
405 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
406 hidirtybuffers >>= 1;
408 lodirtybuffers = hidirtybuffers / 2;
411 * Try to keep the number of free buffers in the specified range,
412 * and give special processes (e.g. like buf_daemon) access to an
415 lofreebuffers = nbuf / 18 + 5;
416 hifreebuffers = 2 * lofreebuffers;
417 numfreebuffers = nbuf;
420 * Maximum number of async ops initiated per buf_daemon loop. This is
421 * somewhat of a hack at the moment, we really need to limit ourselves
422 * based on the number of bytes of I/O in-transit that were initiated
426 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
427 bogus_page = vm_page_alloc(kernel_object,
428 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
430 vmstats.v_wire_count++;
435 * Initialize the embedded bio structures
438 initbufbio(struct buf *bp)
440 bp->b_bio1.bio_buf = bp;
441 bp->b_bio1.bio_prev = NULL;
442 bp->b_bio1.bio_offset = NOOFFSET;
443 bp->b_bio1.bio_next = &bp->b_bio2;
444 bp->b_bio1.bio_done = NULL;
446 bp->b_bio2.bio_buf = bp;
447 bp->b_bio2.bio_prev = &bp->b_bio1;
448 bp->b_bio2.bio_offset = NOOFFSET;
449 bp->b_bio2.bio_next = NULL;
450 bp->b_bio2.bio_done = NULL;
454 * Reinitialize the embedded bio structures as well as any additional
455 * translation cache layers.
458 reinitbufbio(struct buf *bp)
462 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
463 bio->bio_done = NULL;
464 bio->bio_offset = NOOFFSET;
469 * Push another BIO layer onto an existing BIO and return it. The new
470 * BIO layer may already exist, holding cached translation data.
473 push_bio(struct bio *bio)
477 if ((nbio = bio->bio_next) == NULL) {
478 int index = bio - &bio->bio_buf->b_bio_array[0];
479 if (index >= NBUF_BIO) {
480 panic("push_bio: too many layers bp %p\n",
483 nbio = &bio->bio_buf->b_bio_array[index + 1];
484 bio->bio_next = nbio;
485 nbio->bio_prev = bio;
486 nbio->bio_buf = bio->bio_buf;
487 nbio->bio_offset = NOOFFSET;
488 nbio->bio_done = NULL;
489 nbio->bio_next = NULL;
491 KKASSERT(nbio->bio_done == NULL);
496 pop_bio(struct bio *bio)
502 clearbiocache(struct bio *bio)
505 bio->bio_offset = NOOFFSET;
513 * Free the KVA allocation for buffer 'bp'.
515 * Must be called from a critical section as this is the only locking for
518 * Since this call frees up buffer space, we call bufspacewakeup().
521 bfreekva(struct buf * bp)
527 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
528 vm_map_lock(buffer_map);
529 bufspace -= bp->b_kvasize;
530 vm_map_delete(buffer_map,
531 (vm_offset_t) bp->b_kvabase,
532 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
535 vm_map_unlock(buffer_map);
536 vm_map_entry_release(count);
545 * Remove the buffer from the appropriate free list.
548 bremfree(struct buf * bp)
553 old_qindex = bp->b_qindex;
555 if (bp->b_qindex != BQUEUE_NONE) {
556 KASSERT(BUF_REFCNTNB(bp) == 1,
557 ("bremfree: bp %p not locked",bp));
558 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
559 bp->b_qindex = BQUEUE_NONE;
561 if (BUF_REFCNTNB(bp) <= 1)
562 panic("bremfree: removing a buffer not on a queue");
566 * Fixup numfreebuffers count. If the buffer is invalid or not
567 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
568 * the buffer was free and we must decrement numfreebuffers.
570 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
575 case BQUEUE_EMPTYKVA:
589 * Get a buffer with the specified data. Look in the cache first. We
590 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
591 * is set, the buffer is valid and we do not have to do anything ( see
595 bread(struct vnode * vp, off_t loffset, int size, struct buf ** bpp)
599 bp = getblk(vp, loffset, size, 0, 0);
602 /* if not found in cache, do some I/O */
603 if ((bp->b_flags & B_CACHE) == 0) {
604 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
605 bp->b_flags |= B_READ;
606 bp->b_flags &= ~(B_ERROR | B_INVAL);
607 vfs_busy_pages(bp, 0);
608 vn_strategy(vp, &bp->b_bio1);
609 return (biowait(bp));
617 * Operates like bread, but also starts asynchronous I/O on
618 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
619 * to initiating I/O . If B_CACHE is set, the buffer is valid
620 * and we do not have to do anything.
623 breadn(struct vnode * vp, off_t loffset, int size, off_t *raoffset,
624 int *rabsize, int cnt, struct buf ** bpp)
626 struct buf *bp, *rabp;
628 int rv = 0, readwait = 0;
630 *bpp = bp = getblk(vp, loffset, size, 0, 0);
632 /* if not found in cache, do some I/O */
633 if ((bp->b_flags & B_CACHE) == 0) {
634 bp->b_flags |= B_READ;
635 bp->b_flags &= ~(B_ERROR | B_INVAL);
636 vfs_busy_pages(bp, 0);
637 vn_strategy(vp, &bp->b_bio1);
641 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
642 if (inmem(vp, *raoffset))
644 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
646 if ((rabp->b_flags & B_CACHE) == 0) {
647 rabp->b_flags |= B_READ | B_ASYNC;
648 rabp->b_flags &= ~(B_ERROR | B_INVAL);
649 vfs_busy_pages(rabp, 0);
651 vn_strategy(vp, &rabp->b_bio1);
666 * Write, release buffer on completion. (Done by iodone
667 * if async). Do not bother writing anything if the buffer
670 * Note that we set B_CACHE here, indicating that buffer is
671 * fully valid and thus cacheable. This is true even of NFS
672 * now so we set it generally. This could be set either here
673 * or in biodone() since the I/O is synchronous. We put it
677 bwrite(struct buf * bp)
681 if (bp->b_flags & B_INVAL) {
686 oldflags = bp->b_flags;
688 if (BUF_REFCNTNB(bp) == 0)
689 panic("bwrite: buffer is not busy???");
692 * If a background write is already in progress, delay
693 * writing this block if it is asynchronous. Otherwise
694 * wait for the background write to complete.
696 if (bp->b_xflags & BX_BKGRDINPROG) {
697 if (bp->b_flags & B_ASYNC) {
702 bp->b_xflags |= BX_BKGRDWAIT;
703 tsleep(&bp->b_xflags, 0, "biord", 0);
704 if (bp->b_xflags & BX_BKGRDINPROG)
705 panic("bwrite: still writing");
708 /* Mark the buffer clean */
711 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
712 bp->b_flags |= B_CACHE;
714 vfs_busy_pages(bp, 1);
717 * Normal bwrites pipeline writes
719 bp->b_runningbufspace = bp->b_bufsize;
720 runningbufspace += bp->b_runningbufspace;
723 if (oldflags & B_ASYNC)
725 vn_strategy(bp->b_vp, &bp->b_bio1);
727 if ((oldflags & B_ASYNC) == 0) {
728 int rtval = biowait(bp);
731 } else if ((oldflags & B_NOWDRAIN) == 0) {
733 * don't allow the async write to saturate the I/O
734 * system. Deadlocks can occur only if a device strategy
735 * routine (like in VN) turns around and issues another
736 * high-level write, in which case B_NOWDRAIN is expected
737 * to be set. Otherwise we will not deadlock here because
738 * we are blocking waiting for I/O that is already in-progress
741 waitrunningbufspace();
750 * Delayed write. (Buffer is marked dirty). Do not bother writing
751 * anything if the buffer is marked invalid.
753 * Note that since the buffer must be completely valid, we can safely
754 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
755 * biodone() in order to prevent getblk from writing the buffer
759 bdwrite(struct buf *bp)
761 if (BUF_REFCNTNB(bp) == 0)
762 panic("bdwrite: buffer is not busy");
764 if (bp->b_flags & B_INVAL) {
771 * Set B_CACHE, indicating that the buffer is fully valid. This is
772 * true even of NFS now.
774 bp->b_flags |= B_CACHE;
777 * This bmap keeps the system from needing to do the bmap later,
778 * perhaps when the system is attempting to do a sync. Since it
779 * is likely that the indirect block -- or whatever other datastructure
780 * that the filesystem needs is still in memory now, it is a good
781 * thing to do this. Note also, that if the pageout daemon is
782 * requesting a sync -- there might not be enough memory to do
783 * the bmap then... So, this is important to do.
785 if (bp->b_bio2.bio_offset == NOOFFSET) {
786 VOP_BMAP(bp->b_vp, bp->b_loffset, NULL, &bp->b_bio2.bio_offset,
791 * Set the *dirty* buffer range based upon the VM system dirty pages.
796 * We need to do this here to satisfy the vnode_pager and the
797 * pageout daemon, so that it thinks that the pages have been
798 * "cleaned". Note that since the pages are in a delayed write
799 * buffer -- the VFS layer "will" see that the pages get written
800 * out on the next sync, or perhaps the cluster will be completed.
806 * Wakeup the buffer flushing daemon if we have a lot of dirty
807 * buffers (midpoint between our recovery point and our stall
810 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
813 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
814 * due to the softdep code.
821 * Turn buffer into delayed write request. We must clear B_READ and
822 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
823 * itself to properly update it in the dirty/clean lists. We mark it
824 * B_DONE to ensure that any asynchronization of the buffer properly
825 * clears B_DONE ( else a panic will occur later ).
827 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
828 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
829 * should only be called if the buffer is known-good.
831 * Since the buffer is not on a queue, we do not update the numfreebuffers
834 * Must be called from a critical section.
835 * The buffer must be on BQUEUE_NONE.
838 bdirty(struct buf *bp)
840 KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
841 if (bp->b_flags & B_NOCACHE) {
842 printf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
843 bp->b_flags &= ~B_NOCACHE;
845 if (bp->b_flags & B_INVAL) {
846 printf("bdirty: warning, dirtying invalid buffer %p\n", bp);
848 bp->b_flags &= ~(B_READ|B_RELBUF);
850 if ((bp->b_flags & B_DELWRI) == 0) {
851 bp->b_flags |= B_DONE | B_DELWRI;
854 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
861 * Clear B_DELWRI for buffer.
863 * Since the buffer is not on a queue, we do not update the numfreebuffers
866 * Must be called from a critical section.
868 * The buffer is typically on BQUEUE_NONE but there is one case in
869 * brelse() that calls this function after placing the buffer on
874 bundirty(struct buf *bp)
876 if (bp->b_flags & B_DELWRI) {
877 bp->b_flags &= ~B_DELWRI;
880 numdirtywakeup(lodirtybuffers);
883 * Since it is now being written, we can clear its deferred write flag.
885 bp->b_flags &= ~B_DEFERRED;
891 * Asynchronous write. Start output on a buffer, but do not wait for
892 * it to complete. The buffer is released when the output completes.
894 * bwrite() ( or the VOP routine anyway ) is responsible for handling
895 * B_INVAL buffers. Not us.
898 bawrite(struct buf * bp)
900 bp->b_flags |= B_ASYNC;
901 (void) VOP_BWRITE(bp->b_vp, bp);
907 * Ordered write. Start output on a buffer, and flag it so that the
908 * device will write it in the order it was queued. The buffer is
909 * released when the output completes. bwrite() ( or the VOP routine
910 * anyway ) is responsible for handling B_INVAL buffers.
913 bowrite(struct buf * bp)
915 bp->b_flags |= B_ORDERED | B_ASYNC;
916 return (VOP_BWRITE(bp->b_vp, bp));
922 * Called prior to the locking of any vnodes when we are expecting to
923 * write. We do not want to starve the buffer cache with too many
924 * dirty buffers so we block here. By blocking prior to the locking
925 * of any vnodes we attempt to avoid the situation where a locked vnode
926 * prevents the various system daemons from flushing related buffers.
932 if (numdirtybuffers >= hidirtybuffers) {
934 while (numdirtybuffers >= hidirtybuffers) {
936 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
937 tsleep(&needsbuffer, 0, "flswai", 0);
944 * buf_dirty_count_severe:
946 * Return true if we have too many dirty buffers.
949 buf_dirty_count_severe(void)
951 return(numdirtybuffers >= hidirtybuffers);
957 * Release a busy buffer and, if requested, free its resources. The
958 * buffer will be stashed in the appropriate bufqueue[] allowing it
959 * to be accessed later as a cache entity or reused for other purposes.
962 brelse(struct buf * bp)
965 int saved_flags = bp->b_flags;
968 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
972 if ((bp->b_flags & (B_NOCACHE|B_DIRTY)) == (B_NOCACHE|B_DIRTY)) {
973 printf("warning: buf %p marked dirty & B_NOCACHE, clearing B_NOCACHE\n", bp);
974 bp->b_flags &= ~B_NOCACHE;
977 if (bp->b_flags & B_LOCKED)
978 bp->b_flags &= ~B_ERROR;
980 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
982 * Failed write, redirty. Must clear B_ERROR to prevent
983 * pages from being scrapped. If B_INVAL is set then
984 * this case is not run and the next case is run to
985 * destroy the buffer. B_INVAL can occur if the buffer
986 * is outside the range supported by the underlying device.
988 bp->b_flags &= ~B_ERROR;
990 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
991 (bp->b_bufsize <= 0)) {
993 * Either a failed I/O or we were asked to free or not
996 bp->b_flags |= B_INVAL;
997 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
998 (*bioops.io_deallocate)(bp);
999 if (bp->b_flags & B_DELWRI) {
1001 numdirtywakeup(lodirtybuffers);
1003 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
1007 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1008 * is called with B_DELWRI set, the underlying pages may wind up
1009 * getting freed causing a previous write (bdwrite()) to get 'lost'
1010 * because pages associated with a B_DELWRI bp are marked clean.
1012 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1013 * if B_DELWRI is set.
1015 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1016 * on pages to return pages to the VM page queues.
1018 if (bp->b_flags & B_DELWRI)
1019 bp->b_flags &= ~B_RELBUF;
1020 else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1021 bp->b_flags |= B_RELBUF;
1024 * At this point destroying the buffer is governed by the B_INVAL
1025 * or B_RELBUF flags.
1029 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1030 * constituted, not even NFS buffers now. Two flags effect this. If
1031 * B_INVAL, the struct buf is invalidated but the VM object is kept
1032 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1034 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1035 * invalidated. B_ERROR cannot be set for a failed write unless the
1036 * buffer is also B_INVAL because it hits the re-dirtying code above.
1038 * Normally we can do this whether a buffer is B_DELWRI or not. If
1039 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1040 * the commit state and we cannot afford to lose the buffer. If the
1041 * buffer has a background write in progress, we need to keep it
1042 * around to prevent it from being reconstituted and starting a second
1045 if ((bp->b_flags & B_VMIO)
1046 && !(bp->b_vp->v_tag == VT_NFS &&
1047 !vn_isdisk(bp->b_vp, NULL) &&
1048 (bp->b_flags & B_DELWRI))
1051 * Rundown for VMIO buffers which are not dirty NFS buffers.
1063 * Get the base offset and length of the buffer. Note that
1064 * in the VMIO case if the buffer block size is not
1065 * page-aligned then b_data pointer may not be page-aligned.
1066 * But our b_xio.xio_pages array *IS* page aligned.
1068 * block sizes less then DEV_BSIZE (usually 512) are not
1069 * supported due to the page granularity bits (m->valid,
1070 * m->dirty, etc...).
1072 * See man buf(9) for more information
1075 resid = bp->b_bufsize;
1076 foff = bp->b_loffset;
1078 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1079 m = bp->b_xio.xio_pages[i];
1080 vm_page_flag_clear(m, PG_ZERO);
1082 * If we hit a bogus page, fixup *all* of them
1083 * now. Note that we left these pages wired
1084 * when we removed them so they had better exist,
1085 * and they cannot be ripped out from under us so
1086 * no critical section protection is necessary.
1088 if (m == bogus_page) {
1090 poff = OFF_TO_IDX(bp->b_loffset);
1092 for (j = i; j < bp->b_xio.xio_npages; j++) {
1095 mtmp = bp->b_xio.xio_pages[j];
1096 if (mtmp == bogus_page) {
1097 mtmp = vm_page_lookup(obj, poff + j);
1099 panic("brelse: page missing");
1101 bp->b_xio.xio_pages[j] = mtmp;
1105 if ((bp->b_flags & B_INVAL) == 0) {
1106 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1107 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1109 m = bp->b_xio.xio_pages[i];
1113 * Invalidate the backing store if B_NOCACHE is set
1114 * (e.g. used with vinvalbuf()). If this is NFS
1115 * we impose a requirement that the block size be
1116 * a multiple of PAGE_SIZE and create a temporary
1117 * hack to basically invalidate the whole page. The
1118 * problem is that NFS uses really odd buffer sizes
1119 * especially when tracking piecemeal writes and
1120 * it also vinvalbuf()'s a lot, which would result
1121 * in only partial page validation and invalidation
1122 * here. If the file page is mmap()'d, however,
1123 * all the valid bits get set so after we invalidate
1124 * here we would end up with weird m->valid values
1125 * like 0xfc. nfs_getpages() can't handle this so
1126 * we clear all the valid bits for the NFS case
1127 * instead of just some of them.
1129 * The real bug is the VM system having to set m->valid
1130 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1131 * itself is an artifact of the whole 512-byte
1132 * granular mess that exists to support odd block
1133 * sizes and UFS meta-data block sizes (e.g. 6144).
1134 * A complete rewrite is required.
1136 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1137 int poffset = foff & PAGE_MASK;
1140 presid = PAGE_SIZE - poffset;
1141 if (bp->b_vp->v_tag == VT_NFS &&
1142 bp->b_vp->v_type == VREG) {
1144 } else if (presid > resid) {
1147 KASSERT(presid >= 0, ("brelse: extra page"));
1148 vm_page_set_invalid(m, poffset, presid);
1150 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1151 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1153 if (bp->b_flags & (B_INVAL | B_RELBUF))
1154 vfs_vmio_release(bp);
1155 } else if (bp->b_flags & B_VMIO) {
1157 * Rundown for VMIO buffers which are dirty NFS buffers. Such
1158 * buffers contain tracking ranges for NFS and cannot normally
1159 * be released. Due to the dirty check above this series of
1160 * conditionals, B_RELBUF probably will never be set in this
1163 if (bp->b_flags & (B_INVAL | B_RELBUF))
1164 vfs_vmio_release(bp);
1167 * Rundown for non-VMIO buffers.
1169 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1172 printf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1181 if (bp->b_qindex != BQUEUE_NONE)
1182 panic("brelse: free buffer onto another queue???");
1183 if (BUF_REFCNTNB(bp) > 1) {
1184 /* Temporary panic to verify exclusive locking */
1185 /* This panic goes away when we allow shared refs */
1186 panic("brelse: multiple refs");
1187 /* do not release to free list */
1194 * Figure out the correct queue to place the cleaned up buffer on.
1195 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1196 * disassociated from their vnode.
1199 if (bp->b_bufsize == 0) {
1201 * Buffers with no memory. Due to conditionals near the top
1202 * of brelse() such buffers should probably already be
1203 * marked B_INVAL and disassociated from their vnode.
1205 bp->b_flags |= B_INVAL;
1206 bp->b_xflags &= ~BX_BKGRDWRITE;
1207 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1208 KKASSERT((bp->b_flags & B_HASHED) == 0);
1209 if (bp->b_xflags & BX_BKGRDINPROG)
1210 panic("losing buffer 1");
1211 if (bp->b_kvasize) {
1212 bp->b_qindex = BQUEUE_EMPTYKVA;
1214 bp->b_qindex = BQUEUE_EMPTY;
1216 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1217 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1219 * Buffers with junk contents. Again these buffers had better
1220 * already be disassociated from their vnode.
1222 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1223 KKASSERT((bp->b_flags & B_HASHED) == 0);
1224 bp->b_flags |= B_INVAL;
1225 bp->b_xflags &= ~BX_BKGRDWRITE;
1226 if (bp->b_xflags & BX_BKGRDINPROG)
1227 panic("losing buffer 2");
1228 bp->b_qindex = BQUEUE_CLEAN;
1229 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1230 } else if (bp->b_flags & B_LOCKED) {
1232 * Buffers that are locked.
1234 bp->b_qindex = BQUEUE_LOCKED;
1235 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1238 * Remaining buffers. These buffers are still associated with
1241 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1242 case B_DELWRI | B_AGE:
1243 bp->b_qindex = BQUEUE_DIRTY;
1244 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1247 bp->b_qindex = BQUEUE_DIRTY;
1248 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1251 bp->b_qindex = BQUEUE_CLEAN;
1252 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1255 bp->b_qindex = BQUEUE_CLEAN;
1256 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1262 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1263 * on the correct queue.
1265 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1269 * Fixup numfreebuffers count. The bp is on an appropriate queue
1270 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1271 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1272 * if B_INVAL is set ).
1274 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1278 * Something we can maybe free or reuse
1280 if (bp->b_bufsize || bp->b_kvasize)
1284 * Clean up temporary flags and unlock the buffer.
1286 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1287 B_DIRECT | B_NOWDRAIN);
1295 * Release a buffer back to the appropriate queue but do not try to free
1296 * it. The buffer is expected to be used again soon.
1298 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1299 * biodone() to requeue an async I/O on completion. It is also used when
1300 * known good buffers need to be requeued but we think we may need the data
1303 * XXX we should be able to leave the B_RELBUF hint set on completion.
1306 bqrelse(struct buf * bp)
1310 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1312 if (bp->b_qindex != BQUEUE_NONE)
1313 panic("bqrelse: free buffer onto another queue???");
1314 if (BUF_REFCNTNB(bp) > 1) {
1315 /* do not release to free list */
1316 panic("bqrelse: multiple refs");
1321 if (bp->b_flags & B_LOCKED) {
1322 bp->b_flags &= ~B_ERROR;
1323 bp->b_qindex = BQUEUE_LOCKED;
1324 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1325 /* buffers with stale but valid contents */
1326 } else if (bp->b_flags & B_DELWRI) {
1327 bp->b_qindex = BQUEUE_DIRTY;
1328 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1329 } else if (vm_page_count_severe()) {
1331 * We are too low on memory, we have to try to free the
1332 * buffer (most importantly: the wired pages making up its
1333 * backing store) *now*.
1339 bp->b_qindex = BQUEUE_CLEAN;
1340 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1343 if ((bp->b_flags & B_LOCKED) == 0 &&
1344 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1349 * Something we can maybe free or reuse.
1351 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1355 * Final cleanup and unlock. Clear bits that are only used while a
1356 * buffer is actively locked.
1358 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1366 * Return backing pages held by the buffer 'bp' back to the VM system
1367 * if possible. The pages are freed if they are no longer valid or
1368 * attempt to free if it was used for direct I/O otherwise they are
1369 * sent to the page cache.
1371 * Pages that were marked busy are left alone and skipped.
1373 * The KVA mapping (b_data) for the underlying pages is removed by
1377 vfs_vmio_release(struct buf *bp)
1383 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1384 m = bp->b_xio.xio_pages[i];
1385 bp->b_xio.xio_pages[i] = NULL;
1387 * In order to keep page LRU ordering consistent, put
1388 * everything on the inactive queue.
1390 vm_page_unwire(m, 0);
1392 * We don't mess with busy pages, it is
1393 * the responsibility of the process that
1394 * busied the pages to deal with them.
1396 if ((m->flags & PG_BUSY) || (m->busy != 0))
1399 if (m->wire_count == 0) {
1400 vm_page_flag_clear(m, PG_ZERO);
1402 * Might as well free the page if we can and it has
1403 * no valid data. We also free the page if the
1404 * buffer was used for direct I/O.
1406 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1407 m->hold_count == 0) {
1409 vm_page_protect(m, VM_PROT_NONE);
1411 } else if (bp->b_flags & B_DIRECT) {
1412 vm_page_try_to_free(m);
1413 } else if (vm_page_count_severe()) {
1414 vm_page_try_to_cache(m);
1419 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1420 if (bp->b_bufsize) {
1424 bp->b_xio.xio_npages = 0;
1425 bp->b_flags &= ~B_VMIO;
1433 * Implement clustered async writes for clearing out B_DELWRI buffers.
1434 * This is much better then the old way of writing only one buffer at
1435 * a time. Note that we may not be presented with the buffers in the
1436 * correct order, so we search for the cluster in both directions.
1438 * The buffer is locked on call.
1441 vfs_bio_awrite(struct buf *bp)
1445 off_t loffset = bp->b_loffset;
1446 struct vnode *vp = bp->b_vp;
1454 * right now we support clustered writing only to regular files. If
1455 * we find a clusterable block we could be in the middle of a cluster
1456 * rather then at the beginning.
1458 * NOTE: b_bio1 contains the logical loffset and is aliased
1459 * to b_loffset. b_bio2 contains the translated block number.
1461 if ((vp->v_type == VREG) &&
1462 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1463 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1465 size = vp->v_mount->mnt_stat.f_iosize;
1467 for (i = size; i < MAXPHYS; i += size) {
1468 if ((bpa = findblk(vp, loffset + i)) &&
1469 BUF_REFCNT(bpa) == 0 &&
1470 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1471 (B_DELWRI | B_CLUSTEROK)) &&
1472 (bpa->b_bufsize == size)) {
1473 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1474 (bpa->b_bio2.bio_offset !=
1475 bp->b_bio2.bio_offset + i))
1481 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1482 if ((bpa = findblk(vp, loffset - j)) &&
1483 BUF_REFCNT(bpa) == 0 &&
1484 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1485 (B_DELWRI | B_CLUSTEROK)) &&
1486 (bpa->b_bufsize == size)) {
1487 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1488 (bpa->b_bio2.bio_offset !=
1489 bp->b_bio2.bio_offset - j))
1498 * this is a possible cluster write
1500 if (nbytes != size) {
1502 nwritten = cluster_wbuild(vp, size,
1503 loffset - j, nbytes);
1510 bp->b_flags |= B_ASYNC;
1514 * default (old) behavior, writing out only one block
1516 * XXX returns b_bufsize instead of b_bcount for nwritten?
1518 nwritten = bp->b_bufsize;
1519 (void) VOP_BWRITE(bp->b_vp, bp);
1527 * Find and initialize a new buffer header, freeing up existing buffers
1528 * in the bufqueues as necessary. The new buffer is returned locked.
1530 * Important: B_INVAL is not set. If the caller wishes to throw the
1531 * buffer away, the caller must set B_INVAL prior to calling brelse().
1534 * We have insufficient buffer headers
1535 * We have insufficient buffer space
1536 * buffer_map is too fragmented ( space reservation fails )
1537 * If we have to flush dirty buffers ( but we try to avoid this )
1539 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1540 * Instead we ask the buf daemon to do it for us. We attempt to
1541 * avoid piecemeal wakeups of the pageout daemon.
1545 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1551 static int flushingbufs;
1554 * We can't afford to block since we might be holding a vnode lock,
1555 * which may prevent system daemons from running. We deal with
1556 * low-memory situations by proactively returning memory and running
1557 * async I/O rather then sync I/O.
1561 --getnewbufrestarts;
1563 ++getnewbufrestarts;
1566 * Setup for scan. If we do not have enough free buffers,
1567 * we setup a degenerate case that immediately fails. Note
1568 * that if we are specially marked process, we are allowed to
1569 * dip into our reserves.
1571 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1573 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1574 * However, there are a number of cases (defragging, reusing, ...)
1575 * where we cannot backup.
1577 nqindex = BQUEUE_EMPTYKVA;
1578 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1582 * If no EMPTYKVA buffers and we are either
1583 * defragging or reusing, locate a CLEAN buffer
1584 * to free or reuse. If bufspace useage is low
1585 * skip this step so we can allocate a new buffer.
1587 if (defrag || bufspace >= lobufspace) {
1588 nqindex = BQUEUE_CLEAN;
1589 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1593 * If we could not find or were not allowed to reuse a
1594 * CLEAN buffer, check to see if it is ok to use an EMPTY
1595 * buffer. We can only use an EMPTY buffer if allocating
1596 * its KVA would not otherwise run us out of buffer space.
1598 if (nbp == NULL && defrag == 0 &&
1599 bufspace + maxsize < hibufspace) {
1600 nqindex = BQUEUE_EMPTY;
1601 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1606 * Run scan, possibly freeing data and/or kva mappings on the fly
1610 while ((bp = nbp) != NULL) {
1611 int qindex = nqindex;
1614 * Calculate next bp ( we can only use it if we do not block
1615 * or do other fancy things ).
1617 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1620 nqindex = BQUEUE_EMPTYKVA;
1621 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1624 case BQUEUE_EMPTYKVA:
1625 nqindex = BQUEUE_CLEAN;
1626 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1640 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1643 * Note: we no longer distinguish between VMIO and non-VMIO
1647 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1650 * If we are defragging then we need a buffer with
1651 * b_kvasize != 0. XXX this situation should no longer
1652 * occur, if defrag is non-zero the buffer's b_kvasize
1653 * should also be non-zero at this point. XXX
1655 if (defrag && bp->b_kvasize == 0) {
1656 printf("Warning: defrag empty buffer %p\n", bp);
1661 * Start freeing the bp. This is somewhat involved. nbp
1662 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1663 * on the clean list must be disassociated from their
1664 * current vnode. Buffers on the empty[kva] lists have
1665 * already been disassociated.
1668 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1669 printf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1670 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1673 if (bp->b_qindex != qindex) {
1674 printf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1680 if (qindex == BQUEUE_CLEAN) {
1681 if (bp->b_flags & B_VMIO) {
1682 bp->b_flags &= ~B_ASYNC;
1683 vfs_vmio_release(bp);
1690 * NOTE: nbp is now entirely invalid. We can only restart
1691 * the scan from this point on.
1693 * Get the rest of the buffer freed up. b_kva* is still
1694 * valid after this operation.
1697 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1698 KKASSERT((bp->b_flags & B_HASHED) == 0);
1699 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1700 (*bioops.io_deallocate)(bp);
1701 if (bp->b_xflags & BX_BKGRDINPROG)
1702 panic("losing buffer 3");
1705 * critical section protection is not required when
1706 * scrapping a buffer's contents because it is already
1718 bp->b_xio.xio_npages = 0;
1719 bp->b_dirtyoff = bp->b_dirtyend = 0;
1722 LIST_INIT(&bp->b_dep);
1725 * If we are defragging then free the buffer.
1728 bp->b_flags |= B_INVAL;
1736 * If we are overcomitted then recover the buffer and its
1737 * KVM space. This occurs in rare situations when multiple
1738 * processes are blocked in getnewbuf() or allocbuf().
1740 if (bufspace >= hibufspace)
1742 if (flushingbufs && bp->b_kvasize != 0) {
1743 bp->b_flags |= B_INVAL;
1748 if (bufspace < lobufspace)
1754 * If we exhausted our list, sleep as appropriate. We may have to
1755 * wakeup various daemons and write out some dirty buffers.
1757 * Generally we are sleeping due to insufficient buffer space.
1765 flags = VFS_BIO_NEED_BUFSPACE;
1767 } else if (bufspace >= hibufspace) {
1769 flags = VFS_BIO_NEED_BUFSPACE;
1772 flags = VFS_BIO_NEED_ANY;
1775 bd_speedup(); /* heeeelp */
1777 needsbuffer |= flags;
1778 while (needsbuffer & flags) {
1779 if (tsleep(&needsbuffer, slpflag, waitmsg, slptimeo))
1784 * We finally have a valid bp. We aren't quite out of the
1785 * woods, we still have to reserve kva space. In order
1786 * to keep fragmentation sane we only allocate kva in
1789 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1791 if (maxsize != bp->b_kvasize) {
1792 vm_offset_t addr = 0;
1797 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1798 vm_map_lock(buffer_map);
1800 if (vm_map_findspace(buffer_map,
1801 vm_map_min(buffer_map), maxsize,
1804 * Uh oh. Buffer map is too fragmented. We
1805 * must defragment the map.
1807 vm_map_unlock(buffer_map);
1808 vm_map_entry_release(count);
1811 bp->b_flags |= B_INVAL;
1816 vm_map_insert(buffer_map, &count,
1818 addr, addr + maxsize,
1819 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1821 bp->b_kvabase = (caddr_t) addr;
1822 bp->b_kvasize = maxsize;
1823 bufspace += bp->b_kvasize;
1826 vm_map_unlock(buffer_map);
1827 vm_map_entry_release(count);
1829 bp->b_data = bp->b_kvabase;
1837 * Buffer flushing daemon. Buffers are normally flushed by the
1838 * update daemon but if it cannot keep up this process starts to
1839 * take the load in an attempt to prevent getnewbuf() from blocking.
1842 static struct thread *bufdaemonthread;
1844 static struct kproc_desc buf_kp = {
1849 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1855 * This process needs to be suspended prior to shutdown sync.
1857 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1858 bufdaemonthread, SHUTDOWN_PRI_LAST);
1861 * This process is allowed to take the buffer cache to the limit
1866 kproc_suspend_loop();
1869 * Do the flush. Limit the amount of in-transit I/O we
1870 * allow to build up, otherwise we would completely saturate
1871 * the I/O system. Wakeup any waiting processes before we
1872 * normally would so they can run in parallel with our drain.
1874 while (numdirtybuffers > lodirtybuffers) {
1875 if (flushbufqueues() == 0)
1877 waitrunningbufspace();
1878 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
1882 * Only clear bd_request if we have reached our low water
1883 * mark. The buf_daemon normally waits 5 seconds and
1884 * then incrementally flushes any dirty buffers that have
1885 * built up, within reason.
1887 * If we were unable to hit our low water mark and couldn't
1888 * find any flushable buffers, we sleep half a second.
1889 * Otherwise we loop immediately.
1891 if (numdirtybuffers <= lodirtybuffers) {
1893 * We reached our low water mark, reset the
1894 * request and sleep until we are needed again.
1895 * The sleep is just so the suspend code works.
1898 tsleep(&bd_request, 0, "psleep", hz);
1901 * We couldn't find any flushable dirty buffers but
1902 * still have too many dirty buffers, we
1903 * have to sleep and try again. (rare)
1905 tsleep(&bd_request, 0, "qsleep", hz / 2);
1913 * Try to flush a buffer in the dirty queue. We must be careful to
1914 * free up B_INVAL buffers instead of write them, which NFS is
1915 * particularly sensitive to.
1919 flushbufqueues(void)
1924 bp = TAILQ_FIRST(&bufqueues[BQUEUE_DIRTY]);
1927 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1928 if ((bp->b_flags & B_DELWRI) != 0 &&
1929 (bp->b_xflags & BX_BKGRDINPROG) == 0) {
1930 if (bp->b_flags & B_INVAL) {
1931 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1932 panic("flushbufqueues: locked buf");
1938 if (LIST_FIRST(&bp->b_dep) != NULL &&
1939 bioops.io_countdeps &&
1940 (bp->b_flags & B_DEFERRED) == 0 &&
1941 (*bioops.io_countdeps)(bp, 0)) {
1942 TAILQ_REMOVE(&bufqueues[BQUEUE_DIRTY],
1944 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY],
1946 bp->b_flags |= B_DEFERRED;
1947 bp = TAILQ_FIRST(&bufqueues[BQUEUE_DIRTY]);
1952 * Only write it out if we can successfully lock
1955 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
1961 bp = TAILQ_NEXT(bp, b_freelist);
1969 * Returns true if no I/O is needed to access the associated VM object.
1970 * This is like findblk except it also hunts around in the VM system for
1973 * Note that we ignore vm_page_free() races from interrupts against our
1974 * lookup, since if the caller is not protected our return value will not
1975 * be any more valid then otherwise once we exit the critical section.
1978 inmem(struct vnode *vp, off_t loffset)
1981 vm_offset_t toff, tinc, size;
1984 if (findblk(vp, loffset))
1986 if (vp->v_mount == NULL)
1988 if ((obj = vp->v_object) == NULL)
1992 if (size > vp->v_mount->mnt_stat.f_iosize)
1993 size = vp->v_mount->mnt_stat.f_iosize;
1995 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
1996 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2000 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2001 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2002 if (vm_page_is_valid(m,
2003 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2012 * Sets the dirty range for a buffer based on the status of the dirty
2013 * bits in the pages comprising the buffer.
2015 * The range is limited to the size of the buffer.
2017 * This routine is primarily used by NFS, but is generalized for the
2021 vfs_setdirty(struct buf *bp)
2027 * Degenerate case - empty buffer
2030 if (bp->b_bufsize == 0)
2034 * We qualify the scan for modified pages on whether the
2035 * object has been flushed yet. The OBJ_WRITEABLE flag
2036 * is not cleared simply by protecting pages off.
2039 if ((bp->b_flags & B_VMIO) == 0)
2042 object = bp->b_xio.xio_pages[0]->object;
2044 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2045 printf("Warning: object %p writeable but not mightbedirty\n", object);
2046 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2047 printf("Warning: object %p mightbedirty but not writeable\n", object);
2049 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2050 vm_offset_t boffset;
2051 vm_offset_t eoffset;
2054 * test the pages to see if they have been modified directly
2055 * by users through the VM system.
2057 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2058 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2059 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2063 * Calculate the encompassing dirty range, boffset and eoffset,
2064 * (eoffset - boffset) bytes.
2067 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2068 if (bp->b_xio.xio_pages[i]->dirty)
2071 boffset = (i << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2073 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2074 if (bp->b_xio.xio_pages[i]->dirty) {
2078 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2081 * Fit it to the buffer.
2084 if (eoffset > bp->b_bcount)
2085 eoffset = bp->b_bcount;
2088 * If we have a good dirty range, merge with the existing
2092 if (boffset < eoffset) {
2093 if (bp->b_dirtyoff > boffset)
2094 bp->b_dirtyoff = boffset;
2095 if (bp->b_dirtyend < eoffset)
2096 bp->b_dirtyend = eoffset;
2104 * Locate and return the specified buffer, or NULL if the buffer does
2105 * not exist. Do not attempt to lock the buffer or manipulate it in
2106 * any way. The caller must validate that the correct buffer has been
2107 * obtain after locking it.
2110 findblk(struct vnode *vp, off_t loffset)
2115 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2123 * Get a block given a specified block and offset into a file/device.
2124 * The buffers B_DONE bit will be cleared on return, making it almost
2125 * ready for an I/O initiation. B_INVAL may or may not be set on
2126 * return. The caller should clear B_INVAL prior to initiating a
2129 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2130 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2131 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2132 * without doing any of those things the system will likely believe
2133 * the buffer to be valid (especially if it is not B_VMIO), and the
2134 * next getblk() will return the buffer with B_CACHE set.
2136 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2137 * an existing buffer.
2139 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2140 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2141 * and then cleared based on the backing VM. If the previous buffer is
2142 * non-0-sized but invalid, B_CACHE will be cleared.
2144 * If getblk() must create a new buffer, the new buffer is returned with
2145 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2146 * case it is returned with B_INVAL clear and B_CACHE set based on the
2149 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2150 * B_CACHE bit is clear.
2152 * What this means, basically, is that the caller should use B_CACHE to
2153 * determine whether the buffer is fully valid or not and should clear
2154 * B_INVAL prior to issuing a read. If the caller intends to validate
2155 * the buffer by loading its data area with something, the caller needs
2156 * to clear B_INVAL. If the caller does this without issuing an I/O,
2157 * the caller should set B_CACHE ( as an optimization ), else the caller
2158 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2159 * a write attempt or if it was a successfull read. If the caller
2160 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2161 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2164 getblk(struct vnode *vp, off_t loffset, int size, int slpflag, int slptimeo)
2168 if (size > MAXBSIZE)
2169 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2170 if (vp->v_object == NULL)
2171 panic("getblk: vnode %p has no object!", vp);
2176 * Block if we are low on buffers. Certain processes are allowed
2177 * to completely exhaust the buffer cache.
2179 * If this check ever becomes a bottleneck it may be better to
2180 * move it into the else, when findblk() fails. At the moment
2181 * it isn't a problem.
2183 * XXX remove, we cannot afford to block anywhere if holding a vnode
2184 * lock in low-memory situation, so take it to the max.
2186 if (numfreebuffers == 0) {
2189 needsbuffer |= VFS_BIO_NEED_ANY;
2190 tsleep(&needsbuffer, slpflag, "newbuf", slptimeo);
2193 if ((bp = findblk(vp, loffset))) {
2195 * The buffer was found in the cache, but we need to lock it.
2196 * Even with LK_NOWAIT the lockmgr may break our critical
2197 * section, so double-check the validity of the buffer
2198 * once the lock has been obtained.
2200 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2201 int lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2202 if (slpflag & PCATCH)
2203 lkflags |= LK_PCATCH;
2204 if (BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo) ==
2213 * Once the buffer has been locked, make sure we didn't race
2214 * a buffer recyclement. Buffers that are no longer hashed
2215 * will have b_vp == NULL, so this takes care of that check
2218 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2219 printf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp, vp, loffset);
2225 * All vnode-based buffers must be backed by a VM object.
2227 KKASSERT(bp->b_flags & B_VMIO);
2230 * Make sure that B_INVAL buffers do not have a cached
2231 * block number translation.
2233 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2234 printf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp, vp, loffset);
2235 clearbiocache(&bp->b_bio2);
2239 * The buffer is locked. B_CACHE is cleared if the buffer is
2242 if (bp->b_flags & B_INVAL)
2243 bp->b_flags &= ~B_CACHE;
2247 * Any size inconsistancy with a dirty buffer or a buffer
2248 * with a softupdates dependancy must be resolved. Resizing
2249 * the buffer in such circumstances can lead to problems.
2251 if (size != bp->b_bcount) {
2252 if (bp->b_flags & B_DELWRI) {
2253 bp->b_flags |= B_NOCACHE;
2254 VOP_BWRITE(bp->b_vp, bp);
2255 } else if (LIST_FIRST(&bp->b_dep)) {
2256 bp->b_flags |= B_NOCACHE;
2257 VOP_BWRITE(bp->b_vp, bp);
2259 bp->b_flags |= B_RELBUF;
2264 KKASSERT(size <= bp->b_kvasize);
2265 KASSERT(bp->b_loffset != NOOFFSET,
2266 ("getblk: no buffer offset"));
2269 * A buffer with B_DELWRI set and B_CACHE clear must
2270 * be committed before we can return the buffer in
2271 * order to prevent the caller from issuing a read
2272 * ( due to B_CACHE not being set ) and overwriting
2275 * Most callers, including NFS and FFS, need this to
2276 * operate properly either because they assume they
2277 * can issue a read if B_CACHE is not set, or because
2278 * ( for example ) an uncached B_DELWRI might loop due
2279 * to softupdates re-dirtying the buffer. In the latter
2280 * case, B_CACHE is set after the first write completes,
2281 * preventing further loops.
2283 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2284 * above while extending the buffer, we cannot allow the
2285 * buffer to remain with B_CACHE set after the write
2286 * completes or it will represent a corrupt state. To
2287 * deal with this we set B_NOCACHE to scrap the buffer
2290 * We might be able to do something fancy, like setting
2291 * B_CACHE in bwrite() except if B_DELWRI is already set,
2292 * so the below call doesn't set B_CACHE, but that gets real
2293 * confusing. This is much easier.
2296 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2297 bp->b_flags |= B_NOCACHE;
2298 VOP_BWRITE(bp->b_vp, bp);
2303 bp->b_flags &= ~B_DONE;
2306 * Buffer is not in-core, create new buffer. The buffer
2307 * returned by getnewbuf() is locked. Note that the returned
2308 * buffer is also considered valid (not marked B_INVAL).
2310 * Calculating the offset for the I/O requires figuring out
2311 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2312 * the mount's f_iosize otherwise. If the vnode does not
2313 * have an associated mount we assume that the passed size is
2316 * Note that vn_isdisk() cannot be used here since it may
2317 * return a failure for numerous reasons. Note that the
2318 * buffer size may be larger then the block size (the caller
2319 * will use block numbers with the proper multiple). Beware
2320 * of using any v_* fields which are part of unions. In
2321 * particular, in DragonFly the mount point overloading
2322 * mechanism is such that the underlying directory (with a
2323 * non-NULL v_mountedhere) is not a special case.
2327 if (vp->v_type == VBLK || vp->v_type == VCHR)
2329 else if (vp->v_mount)
2330 bsize = vp->v_mount->mnt_stat.f_iosize;
2334 maxsize = size + (loffset & PAGE_MASK);
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 (findblk(vp, loffset)) {
2356 bp->b_flags |= B_INVAL;
2362 * Insert the buffer into the hash, so that it can
2363 * be found by findblk().
2365 * Make sure the translation layer has been cleared.
2367 bp->b_loffset = loffset;
2368 bp->b_bio2.bio_offset = NOOFFSET;
2369 /* bp->b_bio2.bio_next = NULL; */
2374 * All vnode-based buffers must be backed by a VM object.
2376 KKASSERT(vp->v_object != NULL);
2377 bp->b_flags |= B_VMIO;
2382 bp->b_flags &= ~B_DONE;
2390 * Get an empty, disassociated buffer of given size. The buffer is
2391 * initially set to B_INVAL.
2393 * critical section protection is not required for the allocbuf()
2394 * call because races are impossible here.
2402 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2405 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2409 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2417 * This code constitutes the buffer memory from either anonymous system
2418 * memory (in the case of non-VMIO operations) or from an associated
2419 * VM object (in the case of VMIO operations). This code is able to
2420 * resize a buffer up or down.
2422 * Note that this code is tricky, and has many complications to resolve
2423 * deadlock or inconsistant data situations. Tread lightly!!!
2424 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2425 * the caller. Calling this code willy nilly can result in the loss of data.
2427 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2428 * B_CACHE for the non-VMIO case.
2430 * This routine does not need to be called from a critical section but you
2431 * must own the buffer.
2434 allocbuf(struct buf *bp, int size)
2436 int newbsize, mbsize;
2439 if (BUF_REFCNT(bp) == 0)
2440 panic("allocbuf: buffer not busy");
2442 if (bp->b_kvasize < size)
2443 panic("allocbuf: buffer too small");
2445 if ((bp->b_flags & B_VMIO) == 0) {
2449 * Just get anonymous memory from the kernel. Don't
2450 * mess with B_CACHE.
2452 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2453 if (bp->b_flags & B_MALLOC)
2456 newbsize = round_page(size);
2458 if (newbsize < bp->b_bufsize) {
2460 * malloced buffers are not shrunk
2462 if (bp->b_flags & B_MALLOC) {
2464 bp->b_bcount = size;
2466 free(bp->b_data, M_BIOBUF);
2467 if (bp->b_bufsize) {
2468 bufmallocspace -= bp->b_bufsize;
2472 bp->b_data = bp->b_kvabase;
2474 bp->b_flags &= ~B_MALLOC;
2480 (vm_offset_t) bp->b_data + newbsize,
2481 (vm_offset_t) bp->b_data + bp->b_bufsize);
2482 } else if (newbsize > bp->b_bufsize) {
2484 * We only use malloced memory on the first allocation.
2485 * and revert to page-allocated memory when the buffer
2488 if ((bufmallocspace < maxbufmallocspace) &&
2489 (bp->b_bufsize == 0) &&
2490 (mbsize <= PAGE_SIZE/2)) {
2492 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2493 bp->b_bufsize = mbsize;
2494 bp->b_bcount = size;
2495 bp->b_flags |= B_MALLOC;
2496 bufmallocspace += mbsize;
2502 * If the buffer is growing on its other-than-first
2503 * allocation, then we revert to the page-allocation
2506 if (bp->b_flags & B_MALLOC) {
2507 origbuf = bp->b_data;
2508 origbufsize = bp->b_bufsize;
2509 bp->b_data = bp->b_kvabase;
2510 if (bp->b_bufsize) {
2511 bufmallocspace -= bp->b_bufsize;
2515 bp->b_flags &= ~B_MALLOC;
2516 newbsize = round_page(newbsize);
2520 (vm_offset_t) bp->b_data + bp->b_bufsize,
2521 (vm_offset_t) bp->b_data + newbsize);
2523 bcopy(origbuf, bp->b_data, origbufsize);
2524 free(origbuf, M_BIOBUF);
2531 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2532 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
2533 newbsize + PAGE_MASK) >> PAGE_SHIFT;
2534 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
2536 if (bp->b_flags & B_MALLOC)
2537 panic("allocbuf: VMIO buffer can't be malloced");
2539 * Set B_CACHE initially if buffer is 0 length or will become
2542 if (size == 0 || bp->b_bufsize == 0)
2543 bp->b_flags |= B_CACHE;
2545 if (newbsize < bp->b_bufsize) {
2547 * DEV_BSIZE aligned new buffer size is less then the
2548 * DEV_BSIZE aligned existing buffer size. Figure out
2549 * if we have to remove any pages.
2551 if (desiredpages < bp->b_xio.xio_npages) {
2552 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2554 * the page is not freed here -- it
2555 * is the responsibility of
2556 * vnode_pager_setsize
2558 m = bp->b_xio.xio_pages[i];
2559 KASSERT(m != bogus_page,
2560 ("allocbuf: bogus page found"));
2561 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2564 bp->b_xio.xio_pages[i] = NULL;
2565 vm_page_unwire(m, 0);
2567 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2568 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2569 bp->b_xio.xio_npages = desiredpages;
2571 } else if (size > bp->b_bcount) {
2573 * We are growing the buffer, possibly in a
2574 * byte-granular fashion.
2582 * Step 1, bring in the VM pages from the object,
2583 * allocating them if necessary. We must clear
2584 * B_CACHE if these pages are not valid for the
2585 * range covered by the buffer.
2587 * critical section protection is required to protect
2588 * against interrupts unbusying and freeing pages
2589 * between our vm_page_lookup() and our
2590 * busycheck/wiring call.
2596 while (bp->b_xio.xio_npages < desiredpages) {
2600 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
2601 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2603 * note: must allocate system pages
2604 * since blocking here could intefere
2605 * with paging I/O, no matter which
2608 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2611 vm_pageout_deficit += desiredpages -
2612 bp->b_xio.xio_npages;
2616 bp->b_flags &= ~B_CACHE;
2617 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2618 ++bp->b_xio.xio_npages;
2624 * We found a page. If we have to sleep on it,
2625 * retry because it might have gotten freed out
2628 * We can only test PG_BUSY here. Blocking on
2629 * m->busy might lead to a deadlock:
2631 * vm_fault->getpages->cluster_read->allocbuf
2635 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2639 * We have a good page. Should we wakeup the
2642 if ((curthread != pagethread) &&
2643 ((m->queue - m->pc) == PQ_CACHE) &&
2644 ((vmstats.v_free_count + vmstats.v_cache_count) <
2645 (vmstats.v_free_min + vmstats.v_cache_min))) {
2646 pagedaemon_wakeup();
2648 vm_page_flag_clear(m, PG_ZERO);
2650 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2651 ++bp->b_xio.xio_npages;
2656 * Step 2. We've loaded the pages into the buffer,
2657 * we have to figure out if we can still have B_CACHE
2658 * set. Note that B_CACHE is set according to the
2659 * byte-granular range ( bcount and size ), not the
2660 * aligned range ( newbsize ).
2662 * The VM test is against m->valid, which is DEV_BSIZE
2663 * aligned. Needless to say, the validity of the data
2664 * needs to also be DEV_BSIZE aligned. Note that this
2665 * fails with NFS if the server or some other client
2666 * extends the file's EOF. If our buffer is resized,
2667 * B_CACHE may remain set! XXX
2670 toff = bp->b_bcount;
2671 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
2673 while ((bp->b_flags & B_CACHE) && toff < size) {
2676 if (tinc > (size - toff))
2679 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
2687 bp->b_xio.xio_pages[pi]
2694 * Step 3, fixup the KVM pmap. Remember that
2695 * bp->b_data is relative to bp->b_loffset, but
2696 * bp->b_loffset may be offset into the first page.
2699 bp->b_data = (caddr_t)
2700 trunc_page((vm_offset_t)bp->b_data);
2702 (vm_offset_t)bp->b_data,
2703 bp->b_xio.xio_pages,
2704 bp->b_xio.xio_npages
2706 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2707 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
2710 if (newbsize < bp->b_bufsize)
2712 bp->b_bufsize = newbsize; /* actual buffer allocation */
2713 bp->b_bcount = size; /* requested buffer size */
2720 * Wait for buffer I/O completion, returning error status. The buffer
2721 * is left locked and B_DONE on return. B_EINTR is converted into an
2722 * EINTR error and cleared.
2725 biowait(struct buf * bp)
2728 while ((bp->b_flags & B_DONE) == 0) {
2729 if (bp->b_flags & B_READ)
2730 tsleep(bp, 0, "biord", 0);
2732 tsleep(bp, 0, "biowr", 0);
2735 if (bp->b_flags & B_EINTR) {
2736 bp->b_flags &= ~B_EINTR;
2739 if (bp->b_flags & B_ERROR) {
2740 return (bp->b_error ? bp->b_error : EIO);
2747 * This associates a tracking count with an I/O. vn_strategy() and
2748 * dev_dstrategy() do this automatically but there are a few cases
2749 * where a vnode or device layer is bypassed when a block translation
2750 * is cached. In such cases bio_start_transaction() may be called on
2751 * the bypassed layers so the system gets an I/O in progress indication
2752 * for those higher layers.
2755 bio_start_transaction(struct bio *bio, struct bio_track *track)
2757 bio->bio_track = track;
2758 atomic_add_int(&track->bk_active, 1);
2762 * Initiate I/O on a vnode.
2765 vn_strategy(struct vnode *vp, struct bio *bio)
2767 struct bio_track *track;
2769 if (bio->bio_buf->b_flags & B_READ)
2770 track = &vp->v_track_read;
2772 track = &vp->v_track_write;
2773 bio->bio_track = track;
2774 atomic_add_int(&track->bk_active, 1);
2775 vop_strategy(*vp->v_ops, vp, bio);
2782 * Finish I/O on a buffer, optionally calling a completion function.
2783 * This is usually called from an interrupt so process blocking is
2786 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2787 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2788 * assuming B_INVAL is clear.
2790 * For the VMIO case, we set B_CACHE if the op was a read and no
2791 * read error occured, or if the op was a write. B_CACHE is never
2792 * set if the buffer is invalid or otherwise uncacheable.
2794 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2795 * initiator to leave B_INVAL set to brelse the buffer out of existance
2796 * in the biodone routine.
2799 biodone(struct bio *bio)
2801 struct buf *bp = bio->bio_buf;
2805 KASSERT(BUF_REFCNTNB(bp) > 0,
2806 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
2807 KASSERT(!(bp->b_flags & B_DONE),
2808 ("biodone: bp %p already done", bp));
2810 bp->b_flags |= B_DONE;
2811 runningbufwakeup(bp);
2814 * Run up the chain of BIO's.
2817 biodone_t *done_func;
2818 struct bio_track *track;
2821 * BIO tracking. Most but not all BIOs are tracked.
2823 if ((track = bio->bio_track) != NULL) {
2824 atomic_subtract_int(&track->bk_active, 1);
2825 if (track->bk_active < 0) {
2826 panic("biodone: bad active count bio %p\n",
2829 if (track->bk_waitflag) {
2830 track->bk_waitflag = 0;
2833 bio->bio_track = NULL;
2837 * A bio_done function terminates the loop. The function
2838 * will be responsible for any further chaining and/or
2839 * buffer management.
2841 if ((done_func = bio->bio_done) != NULL) {
2842 bio->bio_done = NULL;
2847 bio = bio->bio_prev;
2851 * Special case (XXX) - not a read or write.
2853 if (bp->b_flags & B_FREEBUF) {
2860 * Warning: softupdates may re-dirty the buffer.
2862 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2863 (*bioops.io_complete)(bp);
2865 if (bp->b_flags & B_VMIO) {
2871 struct vnode *vp = bp->b_vp;
2875 #if defined(VFS_BIO_DEBUG)
2876 if (vp->v_holdcnt == 0)
2877 panic("biodone: zero vnode hold count");
2878 if ((vp->v_flag & VOBJBUF) == 0)
2879 panic("biodone: vnode is not setup for merged cache");
2882 foff = bp->b_loffset;
2883 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
2884 KASSERT(obj != NULL, ("biodone: missing VM object"));
2886 #if defined(VFS_BIO_DEBUG)
2887 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
2888 printf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
2889 obj->paging_in_progress, bp->b_xio.xio_npages);
2894 * Set B_CACHE if the op was a normal read and no error
2895 * occured. B_CACHE is set for writes in the b*write()
2898 iosize = bp->b_bcount - bp->b_resid;
2899 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2900 bp->b_flags |= B_CACHE;
2903 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2907 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2912 * cleanup bogus pages, restoring the originals. Since
2913 * the originals should still be wired, we don't have
2914 * to worry about interrupt/freeing races destroying
2915 * the VM object association.
2917 m = bp->b_xio.xio_pages[i];
2918 if (m == bogus_page) {
2920 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2922 panic("biodone: page disappeared");
2923 bp->b_xio.xio_pages[i] = m;
2924 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2925 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
2927 #if defined(VFS_BIO_DEBUG)
2928 if (OFF_TO_IDX(foff) != m->pindex) {
2930 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2931 (unsigned long)foff, m->pindex);
2936 * In the write case, the valid and clean bits are
2937 * already changed correctly ( see bdwrite() ), so we
2938 * only need to do this here in the read case.
2940 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
2941 vfs_page_set_valid(bp, foff, i, m);
2943 vm_page_flag_clear(m, PG_ZERO);
2946 * when debugging new filesystems or buffer I/O methods, this
2947 * is the most common error that pops up. if you see this, you
2948 * have not set the page busy flag correctly!!!
2951 printf("biodone: page busy < 0, "
2952 "pindex: %d, foff: 0x(%x,%x), "
2953 "resid: %d, index: %d\n",
2954 (int) m->pindex, (int)(foff >> 32),
2955 (int) foff & 0xffffffff, resid, i);
2956 if (!vn_isdisk(vp, NULL))
2957 printf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
2958 bp->b_vp->v_mount->mnt_stat.f_iosize,
2960 bp->b_flags, bp->b_xio.xio_npages);
2962 printf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
2964 bp->b_flags, bp->b_xio.xio_npages);
2965 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2966 m->valid, m->dirty, m->wire_count);
2967 panic("biodone: page busy < 0");
2969 vm_page_io_finish(m);
2970 vm_object_pip_subtract(obj, 1);
2971 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2975 vm_object_pip_wakeupn(obj, 0);
2979 * For asynchronous completions, release the buffer now. The brelse
2980 * will do a wakeup there if necessary - so no need to do a wakeup
2981 * here in the async case. The sync case always needs to do a wakeup.
2984 if (bp->b_flags & B_ASYNC) {
2985 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
2998 * This routine is called in lieu of iodone in the case of
2999 * incomplete I/O. This keeps the busy status for pages
3003 vfs_unbusy_pages(struct buf *bp)
3007 runningbufwakeup(bp);
3008 if (bp->b_flags & B_VMIO) {
3009 struct vnode *vp = bp->b_vp;
3014 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3015 vm_page_t m = bp->b_xio.xio_pages[i];
3018 * When restoring bogus changes the original pages
3019 * should still be wired, so we are in no danger of
3020 * losing the object association and do not need
3021 * critical section protection particularly.
3023 if (m == bogus_page) {
3024 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3026 panic("vfs_unbusy_pages: page missing");
3028 bp->b_xio.xio_pages[i] = m;
3029 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3030 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3032 vm_object_pip_subtract(obj, 1);
3033 vm_page_flag_clear(m, PG_ZERO);
3034 vm_page_io_finish(m);
3036 vm_object_pip_wakeupn(obj, 0);
3041 * vfs_page_set_valid:
3043 * Set the valid bits in a page based on the supplied offset. The
3044 * range is restricted to the buffer's size.
3046 * This routine is typically called after a read completes.
3049 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3051 vm_ooffset_t soff, eoff;
3054 * Start and end offsets in buffer. eoff - soff may not cross a
3055 * page boundry or cross the end of the buffer. The end of the
3056 * buffer, in this case, is our file EOF, not the allocation size
3060 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3061 if (eoff > bp->b_loffset + bp->b_bcount)
3062 eoff = bp->b_loffset + bp->b_bcount;
3065 * Set valid range. This is typically the entire buffer and thus the
3069 vm_page_set_validclean(
3071 (vm_offset_t) (soff & PAGE_MASK),
3072 (vm_offset_t) (eoff - soff)
3080 * This routine is called before a device strategy routine.
3081 * It is used to tell the VM system that paging I/O is in
3082 * progress, and treat the pages associated with the buffer
3083 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3084 * flag is handled to make sure that the object doesn't become
3087 * Since I/O has not been initiated yet, certain buffer flags
3088 * such as B_ERROR or B_INVAL may be in an inconsistant state
3089 * and should be ignored.
3092 vfs_busy_pages(struct buf *bp, int clear_modify)
3095 struct proc *p = curthread->td_proc;
3097 if (bp->b_flags & B_VMIO) {
3098 struct vnode *vp = bp->b_vp;
3103 foff = bp->b_loffset;
3104 KASSERT(bp->b_loffset != NOOFFSET,
3105 ("vfs_busy_pages: no buffer offset"));
3109 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3110 vm_page_t m = bp->b_xio.xio_pages[i];
3111 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3116 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3117 vm_page_t m = bp->b_xio.xio_pages[i];
3119 vm_page_flag_clear(m, PG_ZERO);
3120 if ((bp->b_flags & B_CLUSTER) == 0) {
3121 vm_object_pip_add(obj, 1);
3122 vm_page_io_start(m);
3126 * When readying a buffer for a read ( i.e
3127 * clear_modify == 0 ), it is important to do
3128 * bogus_page replacement for valid pages in
3129 * partially instantiated buffers. Partially
3130 * instantiated buffers can, in turn, occur when
3131 * reconstituting a buffer from its VM backing store
3132 * base. We only have to do this if B_CACHE is
3133 * clear ( which causes the I/O to occur in the
3134 * first place ). The replacement prevents the read
3135 * I/O from overwriting potentially dirty VM-backed
3136 * pages. XXX bogus page replacement is, uh, bogus.
3137 * It may not work properly with small-block devices.
3138 * We need to find a better way.
3141 vm_page_protect(m, VM_PROT_NONE);
3143 vfs_page_set_valid(bp, foff, i, m);
3144 else if (m->valid == VM_PAGE_BITS_ALL &&
3145 (bp->b_flags & B_CACHE) == 0) {
3146 bp->b_xio.xio_pages[i] = bogus_page;
3149 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3152 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3153 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3157 * This is the easiest place to put the process accounting for the I/O
3161 if (bp->b_flags & B_READ)
3162 p->p_stats->p_ru.ru_inblock++;
3164 p->p_stats->p_ru.ru_oublock++;
3171 * Tell the VM system that the pages associated with this buffer
3172 * are clean. This is used for delayed writes where the data is
3173 * going to go to disk eventually without additional VM intevention.
3175 * Note that while we only really need to clean through to b_bcount, we
3176 * just go ahead and clean through to b_bufsize.
3179 vfs_clean_pages(struct buf *bp)
3183 if (bp->b_flags & B_VMIO) {
3186 foff = bp->b_loffset;
3187 KASSERT(foff != NOOFFSET, ("vfs_clean_pages: no buffer offset"));
3188 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3189 vm_page_t m = bp->b_xio.xio_pages[i];
3190 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3191 vm_ooffset_t eoff = noff;
3193 if (eoff > bp->b_loffset + bp->b_bufsize)
3194 eoff = bp->b_loffset + bp->b_bufsize;
3195 vfs_page_set_valid(bp, foff, i, m);
3196 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3203 * vfs_bio_set_validclean:
3205 * Set the range within the buffer to valid and clean. The range is
3206 * relative to the beginning of the buffer, b_loffset. Note that
3207 * b_loffset itself may be offset from the beginning of the first page.
3211 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3213 if (bp->b_flags & B_VMIO) {
3218 * Fixup base to be relative to beginning of first page.
3219 * Set initial n to be the maximum number of bytes in the
3220 * first page that can be validated.
3223 base += (bp->b_loffset & PAGE_MASK);
3224 n = PAGE_SIZE - (base & PAGE_MASK);
3226 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3227 vm_page_t m = bp->b_xio.xio_pages[i];
3232 vm_page_set_validclean(m, base & PAGE_MASK, n);
3243 * Clear a buffer. This routine essentially fakes an I/O, so we need
3244 * to clear B_ERROR and B_INVAL.
3246 * Note that while we only theoretically need to clear through b_bcount,
3247 * we go ahead and clear through b_bufsize.
3251 vfs_bio_clrbuf(struct buf *bp)
3255 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3256 bp->b_flags &= ~(B_INVAL|B_ERROR);
3257 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3258 (bp->b_loffset & PAGE_MASK) == 0) {
3259 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3260 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3264 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3265 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3266 bzero(bp->b_data, bp->b_bufsize);
3267 bp->b_xio.xio_pages[0]->valid |= mask;
3272 ea = sa = bp->b_data;
3273 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3274 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3275 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3276 ea = (caddr_t)(vm_offset_t)ulmin(
3277 (u_long)(vm_offset_t)ea,
3278 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3279 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3280 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3282 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3283 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3287 for (; sa < ea; sa += DEV_BSIZE, j++) {
3288 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3289 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3290 bzero(sa, DEV_BSIZE);
3293 bp->b_xio.xio_pages[i]->valid |= mask;
3294 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3303 * vm_hold_load_pages:
3305 * Load pages into the buffer's address space. The pages are
3306 * allocated from the kernel object in order to reduce interference
3307 * with the any VM paging I/O activity. The range of loaded
3308 * pages will be wired.
3310 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3311 * retrieve the full range (to - from) of pages.
3315 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3321 to = round_page(to);
3322 from = round_page(from);
3323 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3325 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3330 * Note: must allocate system pages since blocking here
3331 * could intefere with paging I/O, no matter which
3334 p = vm_page_alloc(kernel_object,
3335 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3336 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3338 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3343 p->valid = VM_PAGE_BITS_ALL;
3344 vm_page_flag_clear(p, PG_ZERO);
3345 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3346 bp->b_xio.xio_pages[index] = p;
3349 bp->b_xio.xio_npages = index;
3353 * vm_hold_free_pages:
3355 * Return pages associated with the buffer back to the VM system.
3357 * The range of pages underlying the buffer's address space will
3358 * be unmapped and un-wired.
3361 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3365 int index, newnpages;
3367 from = round_page(from);
3368 to = round_page(to);
3369 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3371 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3372 p = bp->b_xio.xio_pages[index];
3373 if (p && (index < bp->b_xio.xio_npages)) {
3375 printf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3376 bp->b_bio2.bio_offset, bp->b_loffset);
3378 bp->b_xio.xio_pages[index] = NULL;
3381 vm_page_unwire(p, 0);
3385 bp->b_xio.xio_npages = newnpages;
3391 * Map an IO request into kernel virtual address space.
3393 * All requests are (re)mapped into kernel VA space.
3394 * Notice that we use b_bufsize for the size of the buffer
3395 * to be mapped. b_bcount might be modified by the driver.
3398 vmapbuf(struct buf *bp)
3400 caddr_t addr, v, kva;
3406 if (bp->b_bufsize < 0)
3408 for (v = bp->b_saveaddr,
3409 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3411 addr < bp->b_data + bp->b_bufsize;
3412 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3414 * Do the vm_fault if needed; do the copy-on-write thing
3415 * when reading stuff off device into memory.
3418 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3419 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3421 for (i = 0; i < pidx; ++i) {
3422 vm_page_unhold(bp->b_xio.xio_pages[i]);
3423 bp->b_xio.xio_pages[i] = NULL;
3429 * WARNING! If sparc support is MFCd in the future this will
3430 * have to be changed from pmap_kextract() to pmap_extract()
3434 #error "If MFCing sparc support use pmap_extract"
3436 pa = pmap_kextract((vm_offset_t)addr);
3438 printf("vmapbuf: warning, race against user address during I/O");
3441 m = PHYS_TO_VM_PAGE(pa);
3443 bp->b_xio.xio_pages[pidx] = m;
3445 if (pidx > btoc(MAXPHYS))
3446 panic("vmapbuf: mapped more than MAXPHYS");
3447 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_xio.xio_pages, pidx);
3449 kva = bp->b_saveaddr;
3450 bp->b_xio.xio_npages = pidx;
3451 bp->b_saveaddr = bp->b_data;
3452 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3459 * Free the io map PTEs associated with this IO operation.
3460 * We also invalidate the TLB entries and restore the original b_addr.
3463 vunmapbuf(struct buf *bp)
3469 npages = bp->b_xio.xio_npages;
3470 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3472 m = bp->b_xio.xio_pages;
3473 for (pidx = 0; pidx < npages; pidx++)
3474 vm_page_unhold(*m++);
3476 bp->b_data = bp->b_saveaddr;
3480 * Scan all buffers in the system and issue the callback.
3483 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
3489 for (n = 0; n < nbuf; ++n) {
3490 if ((error = callback(&buf[n], info)) < 0) {
3500 * print out statistics from the current status of the buffer pool
3501 * this can be toggeled by the system control option debug.syncprt
3510 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3511 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3513 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3515 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3518 TAILQ_FOREACH(bp, dp, b_freelist) {
3519 counts[bp->b_bufsize/PAGE_SIZE]++;
3523 printf("%s: total-%d", bname[i], count);
3524 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3526 printf(", %d-%d", j * PAGE_SIZE, counts[j]);
3532 #include "opt_ddb.h"
3534 #include <ddb/ddb.h>
3536 DB_SHOW_COMMAND(buffer, db_show_buffer)
3539 struct buf *bp = (struct buf *)addr;
3542 db_printf("usage: show buffer <addr>\n");
3546 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3547 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3548 "b_resid = %d\n, b_data = %p, "
3549 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3550 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3551 bp->b_data, bp->b_bio2.bio_offset, (bp->b_bio2.bio_next ? bp->b_bio2.bio_next->bio_offset : (off_t)-1));
3552 if (bp->b_xio.xio_npages) {
3554 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3555 bp->b_xio.xio_npages);
3556 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3558 m = bp->b_xio.xio_pages[i];
3559 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3560 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3561 if ((i + 1) < bp->b_xio.xio_npages)