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 $
18 * this file contains a new buffer I/O scheme implementing a coherent
19 * VM object and buffer cache scheme. Pains have been taken to make
20 * sure that the performance degradation associated with schemes such
21 * as this is not realized.
23 * Author: John S. Dyson
24 * Significant help during the development and debugging phases
25 * had been provided by David Greenman, also of the FreeBSD core team.
27 * see man buf(9) for more info.
30 #include <sys/param.h>
31 #include <sys/systm.h>
34 #include <sys/devicestat.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>
47 #include <sys/dsched.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>
56 #include <vm/vm_pager.h>
57 #include <vm/swap_pager.h>
60 #include <sys/thread2.h>
61 #include <sys/spinlock2.h>
62 #include <sys/mplock2.h>
63 #include <vm/vm_page2.h>
74 BQUEUE_NONE, /* not on any queue */
75 BQUEUE_LOCKED, /* locked buffers */
76 BQUEUE_CLEAN, /* non-B_DELWRI buffers */
77 BQUEUE_DIRTY, /* B_DELWRI buffers */
78 BQUEUE_DIRTY_HW, /* B_DELWRI buffers - heavy weight */
79 BQUEUE_EMPTYKVA, /* empty buffer headers with KVA assignment */
80 BQUEUE_EMPTY, /* empty buffer headers */
82 BUFFER_QUEUES /* number of buffer queues */
85 typedef enum bufq_type bufq_type_t;
87 #define BD_WAKE_SIZE 16384
88 #define BD_WAKE_MASK (BD_WAKE_SIZE - 1)
90 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
91 static struct spinlock bufqspin = SPINLOCK_INITIALIZER(&bufqspin);
92 static struct spinlock bufcspin = SPINLOCK_INITIALIZER(&bufcspin);
94 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
96 struct buf *buf; /* buffer header pool */
98 static void vfs_clean_pages(struct buf *bp);
99 static void vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m);
101 static void vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m);
103 static void vfs_vmio_release(struct buf *bp);
104 static int flushbufqueues(struct buf *marker, bufq_type_t q);
105 static vm_page_t bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit);
107 static void bd_signal(int totalspace);
108 static void buf_daemon(void);
109 static void buf_daemon_hw(void);
112 * bogus page -- for I/O to/from partially complete buffers
113 * this is a temporary solution to the problem, but it is not
114 * really that bad. it would be better to split the buffer
115 * for input in the case of buffers partially already in memory,
116 * but the code is intricate enough already.
118 vm_page_t bogus_page;
121 * These are all static, but make the ones we export globals so we do
122 * not need to use compiler magic.
124 long bufspace; /* locked by buffer_map */
126 static long bufmallocspace; /* atomic ops */
127 long maxbufmallocspace, lobufspace, hibufspace;
128 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
129 static long lorunningspace;
130 static long hirunningspace;
131 static int runningbufreq; /* locked by bufcspin */
132 static long dirtybufspace; /* locked by bufcspin */
133 static int dirtybufcount; /* locked by bufcspin */
134 static long dirtybufspacehw; /* locked by bufcspin */
135 static int dirtybufcounthw; /* locked by bufcspin */
136 static long runningbufspace; /* locked by bufcspin */
137 static int runningbufcount; /* locked by bufcspin */
138 long lodirtybufspace;
139 long hidirtybufspace;
140 static int getnewbufcalls;
141 static int getnewbufrestarts;
142 static int recoverbufcalls;
143 static int needsbuffer; /* locked by bufcspin */
144 static int bd_request; /* locked by bufcspin */
145 static int bd_request_hw; /* locked by bufcspin */
146 static u_int bd_wake_ary[BD_WAKE_SIZE];
147 static u_int bd_wake_index;
148 static u_int vm_cycle_point = 40; /* 23-36 will migrate more act->inact */
149 static int debug_commit;
151 static struct thread *bufdaemon_td;
152 static struct thread *bufdaemonhw_td;
153 static u_int lowmempgallocs;
154 static u_int lowmempgfails;
157 * Sysctls for operational control of the buffer cache.
159 SYSCTL_LONG(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
160 "Number of dirty buffers to flush before bufdaemon becomes inactive");
161 SYSCTL_LONG(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
162 "High watermark used to trigger explicit flushing of dirty buffers");
163 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
164 "Minimum amount of buffer space required for active I/O");
165 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
166 "Maximum amount of buffer space to usable for active I/O");
167 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgallocs, CTLFLAG_RW, &lowmempgallocs, 0,
168 "Page allocations done during periods of very low free memory");
169 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgfails, CTLFLAG_RW, &lowmempgfails, 0,
170 "Page allocations which failed during periods of very low free memory");
171 SYSCTL_UINT(_vfs, OID_AUTO, vm_cycle_point, CTLFLAG_RW, &vm_cycle_point, 0,
172 "Recycle pages to active or inactive queue transition pt 0-64");
174 * Sysctls determining current state of the buffer cache.
176 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
177 "Total number of buffers in buffer cache");
178 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
179 "Pending bytes of dirty buffers (all)");
180 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
181 "Pending bytes of dirty buffers (heavy weight)");
182 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
183 "Pending number of dirty buffers");
184 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
185 "Pending number of dirty buffers (heavy weight)");
186 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
187 "I/O bytes currently in progress due to asynchronous writes");
188 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
189 "I/O buffers currently in progress due to asynchronous writes");
190 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
191 "Hard limit on maximum amount of memory usable for buffer space");
192 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
193 "Soft limit on maximum amount of memory usable for buffer space");
194 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
195 "Minimum amount of memory to reserve for system buffer space");
196 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
197 "Amount of memory available for buffers");
198 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
199 0, "Maximum amount of memory reserved for buffers using malloc");
200 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
201 "Amount of memory left for buffers using malloc-scheme");
202 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
203 "New buffer header acquisition requests");
204 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
205 0, "New buffer header acquisition restarts");
206 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
207 "Recover VM space in an emergency");
208 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
209 "Buffer acquisition restarts due to fragmented buffer map");
210 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
211 "Amount of time KVA space was deallocated in an arbitrary buffer");
212 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
213 "Amount of time buffer re-use operations were successful");
214 SYSCTL_INT(_vfs, OID_AUTO, debug_commit, CTLFLAG_RW, &debug_commit, 0, "");
215 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
216 "sizeof(struct buf)");
218 char *buf_wmesg = BUF_WMESG;
220 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
221 #define VFS_BIO_NEED_UNUSED02 0x02
222 #define VFS_BIO_NEED_UNUSED04 0x04
223 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
228 * Called when buffer space is potentially available for recovery.
229 * getnewbuf() will block on this flag when it is unable to free
230 * sufficient buffer space. Buffer space becomes recoverable when
231 * bp's get placed back in the queues.
237 * If someone is waiting for BUF space, wake them up. Even
238 * though we haven't freed the kva space yet, the waiting
239 * process will be able to now.
241 spin_lock(&bufcspin);
242 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
243 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
244 spin_unlock(&bufcspin);
245 wakeup(&needsbuffer);
247 spin_unlock(&bufcspin);
254 * Accounting for I/O in progress.
258 runningbufwakeup(struct buf *bp)
263 if ((totalspace = bp->b_runningbufspace) != 0) {
264 spin_lock(&bufcspin);
265 runningbufspace -= totalspace;
267 bp->b_runningbufspace = 0;
270 * see waitrunningbufspace() for limit test.
272 limit = hirunningspace * 3 / 6;
273 if (runningbufreq && runningbufspace <= limit) {
275 spin_unlock(&bufcspin);
276 wakeup(&runningbufreq);
278 spin_unlock(&bufcspin);
280 bd_signal(totalspace);
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 ).
297 spin_lock(&bufcspin);
299 needsbuffer &= ~VFS_BIO_NEED_ANY;
300 spin_unlock(&bufcspin);
301 wakeup(&needsbuffer);
303 spin_unlock(&bufcspin);
308 * waitrunningbufspace()
310 * If runningbufspace exceeds 4/6 hirunningspace we block until
311 * runningbufspace drops to 3/6 hirunningspace. We also block if another
312 * thread blocked here in order to be fair, even if runningbufspace
313 * is now lower than the limit.
315 * The caller may be using this function to block in a tight loop, we
316 * must block while runningbufspace is greater than at least
317 * hirunningspace * 3 / 6.
320 waitrunningbufspace(void)
322 long limit = hirunningspace * 4 / 6;
324 if (runningbufspace > limit || runningbufreq) {
325 spin_lock(&bufcspin);
326 while (runningbufspace > limit || runningbufreq) {
328 ssleep(&runningbufreq, &bufcspin, 0, "wdrn1", 0);
330 spin_unlock(&bufcspin);
335 * buf_dirty_count_severe:
337 * Return true if we have too many dirty buffers.
340 buf_dirty_count_severe(void)
342 return (runningbufspace + dirtybufspace >= hidirtybufspace ||
343 dirtybufcount >= nbuf / 2);
347 * Return true if the amount of running I/O is severe and BIOQ should
351 buf_runningbufspace_severe(void)
353 return (runningbufspace >= hirunningspace * 4 / 6);
357 * vfs_buf_test_cache:
359 * Called when a buffer is extended. This function clears the B_CACHE
360 * bit if the newly extended portion of the buffer does not contain
363 * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer
364 * cache buffers. The VM pages remain dirty, as someone had mmap()'d
365 * them while a clean buffer was present.
369 vfs_buf_test_cache(struct buf *bp,
370 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
373 if (bp->b_flags & B_CACHE) {
374 int base = (foff + off) & PAGE_MASK;
375 if (vm_page_is_valid(m, base, size) == 0)
376 bp->b_flags &= ~B_CACHE;
383 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
392 if (dirtybufspace < lodirtybufspace && dirtybufcount < nbuf / 2)
395 if (bd_request == 0 &&
396 (dirtybufspace - dirtybufspacehw > lodirtybufspace / 2 ||
397 dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
398 spin_lock(&bufcspin);
400 spin_unlock(&bufcspin);
403 if (bd_request_hw == 0 &&
404 (dirtybufspacehw > lodirtybufspace / 2 ||
405 dirtybufcounthw >= nbuf / 2)) {
406 spin_lock(&bufcspin);
408 spin_unlock(&bufcspin);
409 wakeup(&bd_request_hw);
416 * Get the buf_daemon heated up when the number of running and dirty
417 * buffers exceeds the mid-point.
419 * Return the total number of dirty bytes past the second mid point
420 * as a measure of how much excess dirty data there is in the system.
431 mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
433 totalspace = runningbufspace + dirtybufspace;
434 if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
436 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
437 if (totalspace >= mid2)
438 return(totalspace - mid2);
446 * Wait for the buffer cache to flush (totalspace) bytes worth of
447 * buffers, then return.
449 * Regardless this function blocks while the number of dirty buffers
450 * exceeds hidirtybufspace.
455 bd_wait(int totalspace)
460 if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
463 while (totalspace > 0) {
465 if (totalspace > runningbufspace + dirtybufspace)
466 totalspace = runningbufspace + dirtybufspace;
467 count = totalspace / BKVASIZE;
468 if (count >= BD_WAKE_SIZE)
469 count = BD_WAKE_SIZE - 1;
471 spin_lock(&bufcspin);
472 i = (bd_wake_index + count) & BD_WAKE_MASK;
476 * This is not a strict interlock, so we play a bit loose
477 * with locking access to dirtybufspace*
479 tsleep_interlock(&bd_wake_ary[i], 0);
480 spin_unlock(&bufcspin);
481 tsleep(&bd_wake_ary[i], PINTERLOCKED, "flstik", hz);
483 totalspace = runningbufspace + dirtybufspace - hidirtybufspace;
490 * This function is called whenever runningbufspace or dirtybufspace
491 * is reduced. Track threads waiting for run+dirty buffer I/O
497 bd_signal(int totalspace)
501 if (totalspace > 0) {
502 if (totalspace > BKVASIZE * BD_WAKE_SIZE)
503 totalspace = BKVASIZE * BD_WAKE_SIZE;
504 spin_lock(&bufcspin);
505 while (totalspace > 0) {
508 if (bd_wake_ary[i]) {
510 spin_unlock(&bufcspin);
511 wakeup(&bd_wake_ary[i]);
512 spin_lock(&bufcspin);
514 totalspace -= BKVASIZE;
516 spin_unlock(&bufcspin);
521 * BIO tracking support routines.
523 * Release a ref on a bio_track. Wakeup requests are atomically released
524 * along with the last reference so bk_active will never wind up set to
531 bio_track_rel(struct bio_track *track)
539 active = track->bk_active;
540 if (active == 1 && atomic_cmpset_int(&track->bk_active, 1, 0))
544 * Full-on. Note that the wait flag is only atomically released on
545 * the 1->0 count transition.
547 * We check for a negative count transition using bit 30 since bit 31
548 * has a different meaning.
551 desired = (active & 0x7FFFFFFF) - 1;
553 desired |= active & 0x80000000;
554 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
555 if (desired & 0x40000000)
556 panic("bio_track_rel: bad count: %p\n", track);
557 if (active & 0x80000000)
561 active = track->bk_active;
566 * Wait for the tracking count to reach 0.
568 * Use atomic ops such that the wait flag is only set atomically when
569 * bk_active is non-zero.
574 bio_track_wait(struct bio_track *track, int slp_flags, int slp_timo)
583 if (track->bk_active == 0)
587 * Full-on. Note that the wait flag may only be atomically set if
588 * the active count is non-zero.
590 * NOTE: We cannot optimize active == desired since a wakeup could
591 * clear active prior to our tsleep_interlock().
594 while ((active = track->bk_active) != 0) {
596 desired = active | 0x80000000;
597 tsleep_interlock(track, slp_flags);
598 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
599 error = tsleep(track, slp_flags | PINTERLOCKED,
611 * Load time initialisation of the buffer cache, called from machine
612 * dependant initialization code.
618 vm_offset_t bogus_offset;
621 /* next, make a null set of free lists */
622 for (i = 0; i < BUFFER_QUEUES; i++)
623 TAILQ_INIT(&bufqueues[i]);
625 /* finally, initialize each buffer header and stick on empty q */
626 for (i = 0; i < nbuf; i++) {
628 bzero(bp, sizeof *bp);
629 bp->b_flags = B_INVAL; /* we're just an empty header */
630 bp->b_cmd = BUF_CMD_DONE;
631 bp->b_qindex = BQUEUE_EMPTY;
633 xio_init(&bp->b_xio);
635 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
639 * maxbufspace is the absolute maximum amount of buffer space we are
640 * allowed to reserve in KVM and in real terms. The absolute maximum
641 * is nominally used by buf_daemon. hibufspace is the nominal maximum
642 * used by most other processes. The differential is required to
643 * ensure that buf_daemon is able to run when other processes might
644 * be blocked waiting for buffer space.
646 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
647 * this may result in KVM fragmentation which is not handled optimally
650 maxbufspace = (long)nbuf * BKVASIZE;
651 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
652 lobufspace = hibufspace - MAXBSIZE;
654 lorunningspace = 512 * 1024;
655 /* hirunningspace -- see below */
658 * Limit the amount of malloc memory since it is wired permanently
659 * into the kernel space. Even though this is accounted for in
660 * the buffer allocation, we don't want the malloced region to grow
661 * uncontrolled. The malloc scheme improves memory utilization
662 * significantly on average (small) directories.
664 maxbufmallocspace = hibufspace / 20;
667 * Reduce the chance of a deadlock occuring by limiting the number
668 * of delayed-write dirty buffers we allow to stack up.
670 * We don't want too much actually queued to the device at once
671 * (XXX this needs to be per-mount!), because the buffers will
672 * wind up locked for a very long period of time while the I/O
675 hidirtybufspace = hibufspace / 2; /* dirty + running */
676 hirunningspace = hibufspace / 16; /* locked & queued to device */
677 if (hirunningspace < 1024 * 1024)
678 hirunningspace = 1024 * 1024;
683 lodirtybufspace = hidirtybufspace / 2;
686 * Maximum number of async ops initiated per buf_daemon loop. This is
687 * somewhat of a hack at the moment, we really need to limit ourselves
688 * based on the number of bytes of I/O in-transit that were initiated
692 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
693 vm_object_hold(&kernel_object);
694 bogus_page = vm_page_alloc(&kernel_object,
695 (bogus_offset >> PAGE_SHIFT),
697 vm_object_drop(&kernel_object);
698 vmstats.v_wire_count++;
703 * Initialize the embedded bio structures, typically used by
704 * deprecated code which tries to allocate its own struct bufs.
707 initbufbio(struct buf *bp)
709 bp->b_bio1.bio_buf = bp;
710 bp->b_bio1.bio_prev = NULL;
711 bp->b_bio1.bio_offset = NOOFFSET;
712 bp->b_bio1.bio_next = &bp->b_bio2;
713 bp->b_bio1.bio_done = NULL;
714 bp->b_bio1.bio_flags = 0;
716 bp->b_bio2.bio_buf = bp;
717 bp->b_bio2.bio_prev = &bp->b_bio1;
718 bp->b_bio2.bio_offset = NOOFFSET;
719 bp->b_bio2.bio_next = NULL;
720 bp->b_bio2.bio_done = NULL;
721 bp->b_bio2.bio_flags = 0;
727 * Reinitialize the embedded bio structures as well as any additional
728 * translation cache layers.
731 reinitbufbio(struct buf *bp)
735 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
736 bio->bio_done = NULL;
737 bio->bio_offset = NOOFFSET;
742 * Undo the effects of an initbufbio().
745 uninitbufbio(struct buf *bp)
752 * Push another BIO layer onto an existing BIO and return it. The new
753 * BIO layer may already exist, holding cached translation data.
756 push_bio(struct bio *bio)
760 if ((nbio = bio->bio_next) == NULL) {
761 int index = bio - &bio->bio_buf->b_bio_array[0];
762 if (index >= NBUF_BIO - 1) {
763 panic("push_bio: too many layers bp %p\n",
766 nbio = &bio->bio_buf->b_bio_array[index + 1];
767 bio->bio_next = nbio;
768 nbio->bio_prev = bio;
769 nbio->bio_buf = bio->bio_buf;
770 nbio->bio_offset = NOOFFSET;
771 nbio->bio_done = NULL;
772 nbio->bio_next = NULL;
774 KKASSERT(nbio->bio_done == NULL);
779 * Pop a BIO translation layer, returning the previous layer. The
780 * must have been previously pushed.
783 pop_bio(struct bio *bio)
785 return(bio->bio_prev);
789 clearbiocache(struct bio *bio)
792 bio->bio_offset = NOOFFSET;
800 * Free the KVA allocation for buffer 'bp'.
802 * Must be called from a critical section as this is the only locking for
805 * Since this call frees up buffer space, we call bufspacewakeup().
810 bfreekva(struct buf *bp)
816 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
817 vm_map_lock(&buffer_map);
818 bufspace -= bp->b_kvasize;
819 vm_map_delete(&buffer_map,
820 (vm_offset_t) bp->b_kvabase,
821 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
824 vm_map_unlock(&buffer_map);
825 vm_map_entry_release(count);
827 bp->b_kvabase = NULL;
835 * Remove the buffer from the appropriate free list.
838 _bremfree(struct buf *bp)
840 if (bp->b_qindex != BQUEUE_NONE) {
841 KASSERT(BUF_REFCNTNB(bp) == 1,
842 ("bremfree: bp %p not locked",bp));
843 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
844 bp->b_qindex = BQUEUE_NONE;
846 if (BUF_REFCNTNB(bp) <= 1)
847 panic("bremfree: removing a buffer not on a queue");
852 bremfree(struct buf *bp)
854 spin_lock(&bufqspin);
856 spin_unlock(&bufqspin);
860 bremfree_locked(struct buf *bp)
866 * This version of bread issues any required I/O asyncnronously and
867 * makes a callback on completion.
869 * The callback must check whether BIO_DONE is set in the bio and issue
870 * the bpdone(bp, 0) if it isn't. The callback is responsible for clearing
871 * BIO_DONE and disposing of the I/O (bqrelse()ing it).
874 breadcb(struct vnode *vp, off_t loffset, int size,
875 void (*func)(struct bio *), void *arg)
879 bp = getblk(vp, loffset, size, 0, 0);
881 /* if not found in cache, do some I/O */
882 if ((bp->b_flags & B_CACHE) == 0) {
883 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
884 bp->b_cmd = BUF_CMD_READ;
885 bp->b_bio1.bio_done = func;
886 bp->b_bio1.bio_caller_info1.ptr = arg;
887 vfs_busy_pages(vp, bp);
889 vn_strategy(vp, &bp->b_bio1);
892 * Since we are issuing the callback synchronously it cannot
893 * race the BIO_DONE, so no need for atomic ops here.
895 /*bp->b_bio1.bio_done = func;*/
896 bp->b_bio1.bio_caller_info1.ptr = arg;
897 bp->b_bio1.bio_flags |= BIO_DONE;
905 * breadnx() - Terminal function for bread() and breadn().
907 * This function will start asynchronous I/O on read-ahead blocks as well
908 * as satisfy the primary request.
910 * We must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE is
911 * set, the buffer is valid and we do not have to do anything.
914 breadnx(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
915 int *rabsize, int cnt, struct buf **bpp)
917 struct buf *bp, *rabp;
919 int rv = 0, readwait = 0;
924 *bpp = bp = getblk(vp, loffset, size, 0, 0);
926 /* if not found in cache, do some I/O */
927 if ((bp->b_flags & B_CACHE) == 0) {
928 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
929 bp->b_cmd = BUF_CMD_READ;
930 bp->b_bio1.bio_done = biodone_sync;
931 bp->b_bio1.bio_flags |= BIO_SYNC;
932 vfs_busy_pages(vp, bp);
933 vn_strategy(vp, &bp->b_bio1);
937 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
938 if (inmem(vp, *raoffset))
940 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
942 if ((rabp->b_flags & B_CACHE) == 0) {
943 rabp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
944 rabp->b_cmd = BUF_CMD_READ;
945 vfs_busy_pages(vp, rabp);
947 vn_strategy(vp, &rabp->b_bio1);
953 rv = biowait(&bp->b_bio1, "biord");
960 * Synchronous write, waits for completion.
962 * Write, release buffer on completion. (Done by iodone
963 * if async). Do not bother writing anything if the buffer
966 * Note that we set B_CACHE here, indicating that buffer is
967 * fully valid and thus cacheable. This is true even of NFS
968 * now so we set it generally. This could be set either here
969 * or in biodone() since the I/O is synchronous. We put it
973 bwrite(struct buf *bp)
977 if (bp->b_flags & B_INVAL) {
981 if (BUF_REFCNTNB(bp) == 0)
982 panic("bwrite: buffer is not busy???");
984 /* Mark the buffer clean */
987 bp->b_flags &= ~(B_ERROR | B_EINTR);
988 bp->b_flags |= B_CACHE;
989 bp->b_cmd = BUF_CMD_WRITE;
990 bp->b_bio1.bio_done = biodone_sync;
991 bp->b_bio1.bio_flags |= BIO_SYNC;
992 vfs_busy_pages(bp->b_vp, bp);
995 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
996 * valid for vnode-backed buffers.
998 bsetrunningbufspace(bp, bp->b_bufsize);
999 vn_strategy(bp->b_vp, &bp->b_bio1);
1000 error = biowait(&bp->b_bio1, "biows");
1009 * Asynchronous write. Start output on a buffer, but do not wait for
1010 * it to complete. The buffer is released when the output completes.
1012 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1013 * B_INVAL buffers. Not us.
1016 bawrite(struct buf *bp)
1018 if (bp->b_flags & B_INVAL) {
1022 if (BUF_REFCNTNB(bp) == 0)
1023 panic("bwrite: buffer is not busy???");
1025 /* Mark the buffer clean */
1028 bp->b_flags &= ~(B_ERROR | B_EINTR);
1029 bp->b_flags |= B_CACHE;
1030 bp->b_cmd = BUF_CMD_WRITE;
1031 KKASSERT(bp->b_bio1.bio_done == NULL);
1032 vfs_busy_pages(bp->b_vp, bp);
1035 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1036 * valid for vnode-backed buffers.
1038 bsetrunningbufspace(bp, bp->b_bufsize);
1040 vn_strategy(bp->b_vp, &bp->b_bio1);
1046 * Ordered write. Start output on a buffer, and flag it so that the
1047 * device will write it in the order it was queued. The buffer is
1048 * released when the output completes. bwrite() ( or the VOP routine
1049 * anyway ) is responsible for handling B_INVAL buffers.
1052 bowrite(struct buf *bp)
1054 bp->b_flags |= B_ORDERED;
1062 * Delayed write. (Buffer is marked dirty). Do not bother writing
1063 * anything if the buffer is marked invalid.
1065 * Note that since the buffer must be completely valid, we can safely
1066 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1067 * biodone() in order to prevent getblk from writing the buffer
1068 * out synchronously.
1071 bdwrite(struct buf *bp)
1073 if (BUF_REFCNTNB(bp) == 0)
1074 panic("bdwrite: buffer is not busy");
1076 if (bp->b_flags & B_INVAL) {
1082 if (dsched_is_clear_buf_priv(bp))
1086 * Set B_CACHE, indicating that the buffer is fully valid. This is
1087 * true even of NFS now.
1089 bp->b_flags |= B_CACHE;
1092 * This bmap keeps the system from needing to do the bmap later,
1093 * perhaps when the system is attempting to do a sync. Since it
1094 * is likely that the indirect block -- or whatever other datastructure
1095 * that the filesystem needs is still in memory now, it is a good
1096 * thing to do this. Note also, that if the pageout daemon is
1097 * requesting a sync -- there might not be enough memory to do
1098 * the bmap then... So, this is important to do.
1100 if (bp->b_bio2.bio_offset == NOOFFSET) {
1101 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
1102 NULL, NULL, BUF_CMD_WRITE);
1106 * Because the underlying pages may still be mapped and
1107 * writable trying to set the dirty buffer (b_dirtyoff/end)
1108 * range here will be inaccurate.
1110 * However, we must still clean the pages to satisfy the
1111 * vnode_pager and pageout daemon, so theythink the pages
1112 * have been "cleaned". What has really occured is that
1113 * they've been earmarked for later writing by the buffer
1116 * So we get the b_dirtyoff/end update but will not actually
1117 * depend on it (NFS that is) until the pages are busied for
1120 vfs_clean_pages(bp);
1124 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1125 * due to the softdep code.
1130 * Fake write - return pages to VM system as dirty, leave the buffer clean.
1131 * This is used by tmpfs.
1133 * It is important for any VFS using this routine to NOT use it for
1134 * IO_SYNC or IO_ASYNC operations which occur when the system really
1135 * wants to flush VM pages to backing store.
1138 buwrite(struct buf *bp)
1144 * Only works for VMIO buffers. If the buffer is already
1145 * marked for delayed-write we can't avoid the bdwrite().
1147 if ((bp->b_flags & B_VMIO) == 0 || (bp->b_flags & B_DELWRI)) {
1153 * Mark as needing a commit.
1155 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1156 m = bp->b_xio.xio_pages[i];
1157 vm_page_need_commit(m);
1165 * Turn buffer into delayed write request by marking it B_DELWRI.
1166 * B_RELBUF and B_NOCACHE must be cleared.
1168 * We reassign the buffer to itself to properly update it in the
1169 * dirty/clean lists.
1171 * Must be called from a critical section.
1172 * The buffer must be on BQUEUE_NONE.
1175 bdirty(struct buf *bp)
1177 KASSERT(bp->b_qindex == BQUEUE_NONE,
1178 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1179 if (bp->b_flags & B_NOCACHE) {
1180 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
1181 bp->b_flags &= ~B_NOCACHE;
1183 if (bp->b_flags & B_INVAL) {
1184 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
1186 bp->b_flags &= ~B_RELBUF;
1188 if ((bp->b_flags & B_DELWRI) == 0) {
1189 lwkt_gettoken(&bp->b_vp->v_token);
1190 bp->b_flags |= B_DELWRI;
1192 lwkt_reltoken(&bp->b_vp->v_token);
1194 spin_lock(&bufcspin);
1196 dirtybufspace += bp->b_bufsize;
1197 if (bp->b_flags & B_HEAVY) {
1199 dirtybufspacehw += bp->b_bufsize;
1201 spin_unlock(&bufcspin);
1208 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
1209 * needs to be flushed with a different buf_daemon thread to avoid
1210 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
1213 bheavy(struct buf *bp)
1215 if ((bp->b_flags & B_HEAVY) == 0) {
1216 bp->b_flags |= B_HEAVY;
1217 if (bp->b_flags & B_DELWRI) {
1218 spin_lock(&bufcspin);
1220 dirtybufspacehw += bp->b_bufsize;
1221 spin_unlock(&bufcspin);
1229 * Clear B_DELWRI for buffer.
1231 * Must be called from a critical section.
1233 * The buffer is typically on BQUEUE_NONE but there is one case in
1234 * brelse() that calls this function after placing the buffer on
1235 * a different queue.
1240 bundirty(struct buf *bp)
1242 if (bp->b_flags & B_DELWRI) {
1243 lwkt_gettoken(&bp->b_vp->v_token);
1244 bp->b_flags &= ~B_DELWRI;
1246 lwkt_reltoken(&bp->b_vp->v_token);
1248 spin_lock(&bufcspin);
1250 dirtybufspace -= bp->b_bufsize;
1251 if (bp->b_flags & B_HEAVY) {
1253 dirtybufspacehw -= bp->b_bufsize;
1255 spin_unlock(&bufcspin);
1257 bd_signal(bp->b_bufsize);
1260 * Since it is now being written, we can clear its deferred write flag.
1262 bp->b_flags &= ~B_DEFERRED;
1266 * Set the b_runningbufspace field, used to track how much I/O is
1267 * in progress at any given moment.
1270 bsetrunningbufspace(struct buf *bp, int bytes)
1272 bp->b_runningbufspace = bytes;
1274 spin_lock(&bufcspin);
1275 runningbufspace += bytes;
1277 spin_unlock(&bufcspin);
1284 * Release a busy buffer and, if requested, free its resources. The
1285 * buffer will be stashed in the appropriate bufqueue[] allowing it
1286 * to be accessed later as a cache entity or reused for other purposes.
1291 brelse(struct buf *bp)
1294 int saved_flags = bp->b_flags;
1297 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1300 * If B_NOCACHE is set we are being asked to destroy the buffer and
1301 * its backing store. Clear B_DELWRI.
1303 * B_NOCACHE is set in two cases: (1) when the caller really wants
1304 * to destroy the buffer and backing store and (2) when the caller
1305 * wants to destroy the buffer and backing store after a write
1308 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1312 if ((bp->b_flags & (B_INVAL | B_DELWRI)) == B_DELWRI) {
1314 * A re-dirtied buffer is only subject to destruction
1315 * by B_INVAL. B_ERROR and B_NOCACHE are ignored.
1317 /* leave buffer intact */
1318 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1319 (bp->b_bufsize <= 0)) {
1321 * Either a failed read or we were asked to free or not
1322 * cache the buffer. This path is reached with B_DELWRI
1323 * set only if B_INVAL is already set. B_NOCACHE governs
1324 * backing store destruction.
1326 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1327 * buffer cannot be immediately freed.
1329 bp->b_flags |= B_INVAL;
1330 if (LIST_FIRST(&bp->b_dep) != NULL)
1332 if (bp->b_flags & B_DELWRI) {
1333 spin_lock(&bufcspin);
1335 dirtybufspace -= bp->b_bufsize;
1336 if (bp->b_flags & B_HEAVY) {
1338 dirtybufspacehw -= bp->b_bufsize;
1340 spin_unlock(&bufcspin);
1342 bd_signal(bp->b_bufsize);
1344 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1348 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set,
1349 * or if b_refs is non-zero.
1351 * If vfs_vmio_release() is called with either bit set, the
1352 * underlying pages may wind up getting freed causing a previous
1353 * write (bdwrite()) to get 'lost' because pages associated with
1354 * a B_DELWRI bp are marked clean. Pages associated with a
1355 * B_LOCKED buffer may be mapped by the filesystem.
1357 * If we want to release the buffer ourselves (rather then the
1358 * originator asking us to release it), give the originator a
1359 * chance to countermand the release by setting B_LOCKED.
1361 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1362 * if B_DELWRI is set.
1364 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1365 * on pages to return pages to the VM page queues.
1367 if ((bp->b_flags & (B_DELWRI | B_LOCKED)) || bp->b_refs) {
1368 bp->b_flags &= ~B_RELBUF;
1369 } else if (vm_page_count_min(0)) {
1370 if (LIST_FIRST(&bp->b_dep) != NULL)
1371 buf_deallocate(bp); /* can set B_LOCKED */
1372 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1373 bp->b_flags &= ~B_RELBUF;
1375 bp->b_flags |= B_RELBUF;
1379 * Make sure b_cmd is clear. It may have already been cleared by
1382 * At this point destroying the buffer is governed by the B_INVAL
1383 * or B_RELBUF flags.
1385 bp->b_cmd = BUF_CMD_DONE;
1386 dsched_exit_buf(bp);
1389 * VMIO buffer rundown. Make sure the VM page array is restored
1390 * after an I/O may have replaces some of the pages with bogus pages
1391 * in order to not destroy dirty pages in a fill-in read.
1393 * Note that due to the code above, if a buffer is marked B_DELWRI
1394 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1395 * B_INVAL may still be set, however.
1397 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1398 * but not the backing store. B_NOCACHE will destroy the backing
1401 * Note that dirty NFS buffers contain byte-granular write ranges
1402 * and should not be destroyed w/ B_INVAL even if the backing store
1405 if (bp->b_flags & B_VMIO) {
1407 * Rundown for VMIO buffers which are not dirty NFS buffers.
1419 * Get the base offset and length of the buffer. Note that
1420 * in the VMIO case if the buffer block size is not
1421 * page-aligned then b_data pointer may not be page-aligned.
1422 * But our b_xio.xio_pages array *IS* page aligned.
1424 * block sizes less then DEV_BSIZE (usually 512) are not
1425 * supported due to the page granularity bits (m->valid,
1426 * m->dirty, etc...).
1428 * See man buf(9) for more information
1431 resid = bp->b_bufsize;
1432 foff = bp->b_loffset;
1434 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1435 m = bp->b_xio.xio_pages[i];
1436 vm_page_flag_clear(m, PG_ZERO);
1438 * If we hit a bogus page, fixup *all* of them
1439 * now. Note that we left these pages wired
1440 * when we removed them so they had better exist,
1441 * and they cannot be ripped out from under us so
1442 * no critical section protection is necessary.
1444 if (m == bogus_page) {
1446 poff = OFF_TO_IDX(bp->b_loffset);
1448 vm_object_hold(obj);
1449 for (j = i; j < bp->b_xio.xio_npages; j++) {
1452 mtmp = bp->b_xio.xio_pages[j];
1453 if (mtmp == bogus_page) {
1454 mtmp = vm_page_lookup(obj, poff + j);
1456 panic("brelse: page missing");
1458 bp->b_xio.xio_pages[j] = mtmp;
1461 bp->b_flags &= ~B_HASBOGUS;
1462 vm_object_drop(obj);
1464 if ((bp->b_flags & B_INVAL) == 0) {
1465 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1466 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1468 m = bp->b_xio.xio_pages[i];
1472 * Invalidate the backing store if B_NOCACHE is set
1473 * (e.g. used with vinvalbuf()). If this is NFS
1474 * we impose a requirement that the block size be
1475 * a multiple of PAGE_SIZE and create a temporary
1476 * hack to basically invalidate the whole page. The
1477 * problem is that NFS uses really odd buffer sizes
1478 * especially when tracking piecemeal writes and
1479 * it also vinvalbuf()'s a lot, which would result
1480 * in only partial page validation and invalidation
1481 * here. If the file page is mmap()'d, however,
1482 * all the valid bits get set so after we invalidate
1483 * here we would end up with weird m->valid values
1484 * like 0xfc. nfs_getpages() can't handle this so
1485 * we clear all the valid bits for the NFS case
1486 * instead of just some of them.
1488 * The real bug is the VM system having to set m->valid
1489 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1490 * itself is an artifact of the whole 512-byte
1491 * granular mess that exists to support odd block
1492 * sizes and UFS meta-data block sizes (e.g. 6144).
1493 * A complete rewrite is required.
1497 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1498 int poffset = foff & PAGE_MASK;
1501 presid = PAGE_SIZE - poffset;
1502 if (bp->b_vp->v_tag == VT_NFS &&
1503 bp->b_vp->v_type == VREG) {
1505 } else if (presid > resid) {
1508 KASSERT(presid >= 0, ("brelse: extra page"));
1509 vm_page_set_invalid(m, poffset, presid);
1512 * Also make sure any swap cache is removed
1513 * as it is now stale (HAMMER in particular
1514 * uses B_NOCACHE to deal with buffer
1517 swap_pager_unswapped(m);
1519 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1520 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1522 if (bp->b_flags & (B_INVAL | B_RELBUF))
1523 vfs_vmio_release(bp);
1526 * Rundown for non-VMIO buffers.
1528 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1531 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1537 if (bp->b_qindex != BQUEUE_NONE)
1538 panic("brelse: free buffer onto another queue???");
1539 if (BUF_REFCNTNB(bp) > 1) {
1540 /* Temporary panic to verify exclusive locking */
1541 /* This panic goes away when we allow shared refs */
1542 panic("brelse: multiple refs");
1548 * Figure out the correct queue to place the cleaned up buffer on.
1549 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1550 * disassociated from their vnode.
1552 spin_lock(&bufqspin);
1553 if (bp->b_flags & B_LOCKED) {
1555 * Buffers that are locked are placed in the locked queue
1556 * immediately, regardless of their state.
1558 bp->b_qindex = BQUEUE_LOCKED;
1559 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1560 } else if (bp->b_bufsize == 0) {
1562 * Buffers with no memory. Due to conditionals near the top
1563 * of brelse() such buffers should probably already be
1564 * marked B_INVAL and disassociated from their vnode.
1566 bp->b_flags |= B_INVAL;
1567 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1568 KKASSERT((bp->b_flags & B_HASHED) == 0);
1569 if (bp->b_kvasize) {
1570 bp->b_qindex = BQUEUE_EMPTYKVA;
1572 bp->b_qindex = BQUEUE_EMPTY;
1574 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1575 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) {
1577 * Buffers with junk contents. Again these buffers had better
1578 * already be disassociated from their vnode.
1580 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1581 KKASSERT((bp->b_flags & B_HASHED) == 0);
1582 bp->b_flags |= B_INVAL;
1583 bp->b_qindex = BQUEUE_CLEAN;
1584 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1587 * Remaining buffers. These buffers are still associated with
1590 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1592 bp->b_qindex = BQUEUE_DIRTY;
1593 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1595 case B_DELWRI | B_HEAVY:
1596 bp->b_qindex = BQUEUE_DIRTY_HW;
1597 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1602 * NOTE: Buffers are always placed at the end of the
1603 * queue. If B_AGE is not set the buffer will cycle
1604 * through the queue twice.
1606 bp->b_qindex = BQUEUE_CLEAN;
1607 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1611 spin_unlock(&bufqspin);
1614 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1615 * on the correct queue.
1617 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1621 * The bp is on an appropriate queue unless locked. If it is not
1622 * locked or dirty we can wakeup threads waiting for buffer space.
1624 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1625 * if B_INVAL is set ).
1627 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1631 * Something we can maybe free or reuse
1633 if (bp->b_bufsize || bp->b_kvasize)
1637 * Clean up temporary flags and unlock the buffer.
1639 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF | B_DIRECT);
1646 * Release a buffer back to the appropriate queue but do not try to free
1647 * it. The buffer is expected to be used again soon.
1649 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1650 * biodone() to requeue an async I/O on completion. It is also used when
1651 * known good buffers need to be requeued but we think we may need the data
1654 * XXX we should be able to leave the B_RELBUF hint set on completion.
1659 bqrelse(struct buf *bp)
1661 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1663 if (bp->b_qindex != BQUEUE_NONE)
1664 panic("bqrelse: free buffer onto another queue???");
1665 if (BUF_REFCNTNB(bp) > 1) {
1666 /* do not release to free list */
1667 panic("bqrelse: multiple refs");
1671 buf_act_advance(bp);
1673 spin_lock(&bufqspin);
1674 if (bp->b_flags & B_LOCKED) {
1676 * Locked buffers are released to the locked queue. However,
1677 * if the buffer is dirty it will first go into the dirty
1678 * queue and later on after the I/O completes successfully it
1679 * will be released to the locked queue.
1681 bp->b_qindex = BQUEUE_LOCKED;
1682 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1683 } else if (bp->b_flags & B_DELWRI) {
1684 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1685 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1686 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1687 } else if (vm_page_count_min(0)) {
1689 * We are too low on memory, we have to try to free the
1690 * buffer (most importantly: the wired pages making up its
1691 * backing store) *now*.
1693 spin_unlock(&bufqspin);
1697 bp->b_qindex = BQUEUE_CLEAN;
1698 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1700 spin_unlock(&bufqspin);
1702 if ((bp->b_flags & B_LOCKED) == 0 &&
1703 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1708 * Something we can maybe free or reuse.
1710 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1714 * Final cleanup and unlock. Clear bits that are only used while a
1715 * buffer is actively locked.
1717 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF);
1718 dsched_exit_buf(bp);
1723 * Hold a buffer, preventing it from being reused. This will prevent
1724 * normal B_RELBUF operations on the buffer but will not prevent B_INVAL
1725 * operations. If a B_INVAL operation occurs the buffer will remain held
1726 * but the underlying pages may get ripped out.
1728 * These functions are typically used in VOP_READ/VOP_WRITE functions
1729 * to hold a buffer during a copyin or copyout, preventing deadlocks
1730 * or recursive lock panics when read()/write() is used over mmap()'d
1733 * NOTE: bqhold() requires that the buffer be locked at the time of the
1734 * hold. bqdrop() has no requirements other than the buffer having
1735 * previously been held.
1738 bqhold(struct buf *bp)
1740 atomic_add_int(&bp->b_refs, 1);
1744 bqdrop(struct buf *bp)
1746 KKASSERT(bp->b_refs > 0);
1747 atomic_add_int(&bp->b_refs, -1);
1751 * Return backing pages held by the buffer 'bp' back to the VM system.
1752 * This routine is called when the bp is invalidated, released, or
1755 * The KVA mapping (b_data) for the underlying pages is removed by
1758 * WARNING! This routine is integral to the low memory critical path
1759 * when a buffer is B_RELBUF'd. If the system has a severe page
1760 * deficit we need to get the page(s) onto the PQ_FREE or PQ_CACHE
1761 * queues so they can be reused in the current pageout daemon
1765 vfs_vmio_release(struct buf *bp)
1770 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1771 m = bp->b_xio.xio_pages[i];
1772 bp->b_xio.xio_pages[i] = NULL;
1775 * We need to own the page in order to safely unwire it.
1777 vm_page_busy_wait(m, FALSE, "vmiopg");
1780 * The VFS is telling us this is not a meta-data buffer
1781 * even if it is backed by a block device.
1783 if (bp->b_flags & B_NOTMETA)
1784 vm_page_flag_set(m, PG_NOTMETA);
1787 * This is a very important bit of code. We try to track
1788 * VM page use whether the pages are wired into the buffer
1789 * cache or not. While wired into the buffer cache the
1790 * bp tracks the act_count.
1792 * We can choose to place unwired pages on the inactive
1793 * queue (0) or active queue (1). If we place too many
1794 * on the active queue the queue will cycle the act_count
1795 * on pages we'd like to keep, just from single-use pages
1796 * (such as when doing a tar-up or file scan).
1798 if (bp->b_act_count < vm_cycle_point)
1799 vm_page_unwire(m, 0);
1801 vm_page_unwire(m, 1);
1804 * If the wire_count has dropped to 0 we may need to take
1805 * further action before unbusying the page.
1807 * WARNING: vm_page_try_*() also checks PG_NEED_COMMIT for us.
1809 if (m->wire_count == 0) {
1810 vm_page_flag_clear(m, PG_ZERO);
1812 if (bp->b_flags & B_DIRECT) {
1814 * Attempt to free the page if B_DIRECT is
1815 * set, the caller does not desire the page
1819 vm_page_try_to_free(m);
1820 } else if ((bp->b_flags & B_NOTMETA) ||
1821 vm_page_count_min(0)) {
1823 * Attempt to move the page to PQ_CACHE
1824 * if B_NOTMETA is set. This flag is set
1825 * by HAMMER to remove one of the two pages
1826 * present when double buffering is enabled.
1828 * Attempt to move the page to PQ_CACHE
1829 * If we have a severe page deficit. This
1830 * will cause buffer cache operations related
1831 * to pageouts to recycle the related pages
1832 * in order to avoid a low memory deadlock.
1834 m->act_count = bp->b_act_count;
1836 vm_page_try_to_cache(m);
1839 * Nominal case, leave the page on the
1840 * queue the original unwiring placed it on
1841 * (active or inactive).
1843 m->act_count = bp->b_act_count;
1851 pmap_qremove(trunc_page((vm_offset_t) bp->b_data),
1852 bp->b_xio.xio_npages);
1853 if (bp->b_bufsize) {
1857 bp->b_xio.xio_npages = 0;
1858 bp->b_flags &= ~B_VMIO;
1859 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1867 * Find and initialize a new buffer header, freeing up existing buffers
1868 * in the bufqueues as necessary. The new buffer is returned locked.
1870 * Important: B_INVAL is not set. If the caller wishes to throw the
1871 * buffer away, the caller must set B_INVAL prior to calling brelse().
1874 * We have insufficient buffer headers
1875 * We have insufficient buffer space
1876 * buffer_map is too fragmented ( space reservation fails )
1877 * If we have to flush dirty buffers ( but we try to avoid this )
1879 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1880 * Instead we ask the buf daemon to do it for us. We attempt to
1881 * avoid piecemeal wakeups of the pageout daemon.
1886 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1892 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1893 static int flushingbufs;
1896 * We can't afford to block since we might be holding a vnode lock,
1897 * which may prevent system daemons from running. We deal with
1898 * low-memory situations by proactively returning memory and running
1899 * async I/O rather then sync I/O.
1903 --getnewbufrestarts;
1905 ++getnewbufrestarts;
1908 * Setup for scan. If we do not have enough free buffers,
1909 * we setup a degenerate case that immediately fails. Note
1910 * that if we are specially marked process, we are allowed to
1911 * dip into our reserves.
1913 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1915 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1916 * However, there are a number of cases (defragging, reusing, ...)
1917 * where we cannot backup.
1919 nqindex = BQUEUE_EMPTYKVA;
1920 spin_lock(&bufqspin);
1921 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1925 * If no EMPTYKVA buffers and we are either
1926 * defragging or reusing, locate a CLEAN buffer
1927 * to free or reuse. If bufspace useage is low
1928 * skip this step so we can allocate a new buffer.
1930 if (defrag || bufspace >= lobufspace) {
1931 nqindex = BQUEUE_CLEAN;
1932 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1936 * If we could not find or were not allowed to reuse a
1937 * CLEAN buffer, check to see if it is ok to use an EMPTY
1938 * buffer. We can only use an EMPTY buffer if allocating
1939 * its KVA would not otherwise run us out of buffer space.
1941 if (nbp == NULL && defrag == 0 &&
1942 bufspace + maxsize < hibufspace) {
1943 nqindex = BQUEUE_EMPTY;
1944 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1949 * Run scan, possibly freeing data and/or kva mappings on the fly
1952 * WARNING! bufqspin is held!
1954 while ((bp = nbp) != NULL) {
1955 int qindex = nqindex;
1957 nbp = TAILQ_NEXT(bp, b_freelist);
1960 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
1961 * cycles through the queue twice before being selected.
1963 if (qindex == BQUEUE_CLEAN &&
1964 (bp->b_flags & B_AGE) == 0 && nbp) {
1965 bp->b_flags |= B_AGE;
1966 TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
1967 TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
1972 * Calculate next bp ( we can only use it if we do not block
1973 * or do other fancy things ).
1978 nqindex = BQUEUE_EMPTYKVA;
1979 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1982 case BQUEUE_EMPTYKVA:
1983 nqindex = BQUEUE_CLEAN;
1984 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1998 KASSERT(bp->b_qindex == qindex,
1999 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2002 * Note: we no longer distinguish between VMIO and non-VMIO
2005 KASSERT((bp->b_flags & B_DELWRI) == 0,
2006 ("delwri buffer %p found in queue %d", bp, qindex));
2009 * Do not try to reuse a buffer with a non-zero b_refs.
2010 * This is an unsynchronized test. A synchronized test
2011 * is also performed after we lock the buffer.
2017 * If we are defragging then we need a buffer with
2018 * b_kvasize != 0. XXX this situation should no longer
2019 * occur, if defrag is non-zero the buffer's b_kvasize
2020 * should also be non-zero at this point. XXX
2022 if (defrag && bp->b_kvasize == 0) {
2023 kprintf("Warning: defrag empty buffer %p\n", bp);
2028 * Start freeing the bp. This is somewhat involved. nbp
2029 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
2030 * on the clean list must be disassociated from their
2031 * current vnode. Buffers on the empty[kva] lists have
2032 * already been disassociated.
2034 * b_refs is checked after locking along with queue changes.
2035 * We must check here to deal with zero->nonzero transitions
2036 * made by the owner of the buffer lock, which is used by
2037 * VFS's to hold the buffer while issuing an unlocked
2038 * uiomove()s. We cannot invalidate the buffer's pages
2039 * for this case. Once we successfully lock a buffer the
2040 * only 0->1 transitions of b_refs will occur via findblk().
2042 * We must also check for queue changes after successful
2043 * locking as the current lock holder may dispose of the
2044 * buffer and change its queue.
2046 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2047 spin_unlock(&bufqspin);
2048 tsleep(&bd_request, 0, "gnbxxx", (hz + 99) / 100);
2051 if (bp->b_qindex != qindex || bp->b_refs) {
2052 spin_unlock(&bufqspin);
2056 bremfree_locked(bp);
2057 spin_unlock(&bufqspin);
2060 * Dependancies must be handled before we disassociate the
2063 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2064 * be immediately disassociated. HAMMER then becomes
2065 * responsible for releasing the buffer.
2067 * NOTE: bufqspin is UNLOCKED now.
2069 if (LIST_FIRST(&bp->b_dep) != NULL) {
2071 if (bp->b_flags & B_LOCKED) {
2075 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2078 if (qindex == BQUEUE_CLEAN) {
2079 if (bp->b_flags & B_VMIO)
2080 vfs_vmio_release(bp);
2086 * NOTE: nbp is now entirely invalid. We can only restart
2087 * the scan from this point on.
2089 * Get the rest of the buffer freed up. b_kva* is still
2090 * valid after this operation.
2092 KASSERT(bp->b_vp == NULL,
2093 ("bp3 %p flags %08x vnode %p qindex %d "
2094 "unexpectededly still associated!",
2095 bp, bp->b_flags, bp->b_vp, qindex));
2096 KKASSERT((bp->b_flags & B_HASHED) == 0);
2099 * critical section protection is not required when
2100 * scrapping a buffer's contents because it is already
2106 bp->b_flags = B_BNOCLIP;
2107 bp->b_cmd = BUF_CMD_DONE;
2112 bp->b_xio.xio_npages = 0;
2113 bp->b_dirtyoff = bp->b_dirtyend = 0;
2114 bp->b_act_count = ACT_INIT;
2116 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2118 if (blkflags & GETBLK_BHEAVY)
2119 bp->b_flags |= B_HEAVY;
2122 * If we are defragging then free the buffer.
2125 bp->b_flags |= B_INVAL;
2133 * If we are overcomitted then recover the buffer and its
2134 * KVM space. This occurs in rare situations when multiple
2135 * processes are blocked in getnewbuf() or allocbuf().
2137 if (bufspace >= hibufspace)
2139 if (flushingbufs && bp->b_kvasize != 0) {
2140 bp->b_flags |= B_INVAL;
2145 if (bufspace < lobufspace)
2149 * b_refs can transition to a non-zero value while we hold
2150 * the buffer locked due to a findblk(). Our brelvp() above
2151 * interlocked any future possible transitions due to
2154 * If we find b_refs to be non-zero we can destroy the
2155 * buffer's contents but we cannot yet reuse the buffer.
2158 bp->b_flags |= B_INVAL;
2164 /* NOT REACHED, bufqspin not held */
2168 * If we exhausted our list, sleep as appropriate. We may have to
2169 * wakeup various daemons and write out some dirty buffers.
2171 * Generally we are sleeping due to insufficient buffer space.
2173 * NOTE: bufqspin is held if bp is NULL, else it is not held.
2179 spin_unlock(&bufqspin);
2181 flags = VFS_BIO_NEED_BUFSPACE;
2183 } else if (bufspace >= hibufspace) {
2185 flags = VFS_BIO_NEED_BUFSPACE;
2188 flags = VFS_BIO_NEED_ANY;
2191 bd_speedup(); /* heeeelp */
2192 spin_lock(&bufcspin);
2193 needsbuffer |= flags;
2194 while (needsbuffer & flags) {
2195 if (ssleep(&needsbuffer, &bufcspin,
2196 slpflags, waitmsg, slptimeo)) {
2197 spin_unlock(&bufcspin);
2201 spin_unlock(&bufcspin);
2204 * We finally have a valid bp. We aren't quite out of the
2205 * woods, we still have to reserve kva space. In order
2206 * to keep fragmentation sane we only allocate kva in
2209 * (bufqspin is not held)
2211 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2213 if (maxsize != bp->b_kvasize) {
2214 vm_offset_t addr = 0;
2219 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2220 vm_map_lock(&buffer_map);
2222 if (vm_map_findspace(&buffer_map,
2223 vm_map_min(&buffer_map), maxsize,
2224 maxsize, 0, &addr)) {
2226 * Uh oh. Buffer map is too fragmented. We
2227 * must defragment the map.
2229 vm_map_unlock(&buffer_map);
2230 vm_map_entry_release(count);
2233 bp->b_flags |= B_INVAL;
2238 vm_map_insert(&buffer_map, &count,
2240 addr, addr + maxsize,
2242 VM_PROT_ALL, VM_PROT_ALL,
2245 bp->b_kvabase = (caddr_t) addr;
2246 bp->b_kvasize = maxsize;
2247 bufspace += bp->b_kvasize;
2250 vm_map_unlock(&buffer_map);
2251 vm_map_entry_release(count);
2253 bp->b_data = bp->b_kvabase;
2260 * This routine is called in an emergency to recover VM pages from the
2261 * buffer cache by cashing in clean buffers. The idea is to recover
2262 * enough pages to be able to satisfy a stuck bio_page_alloc().
2264 * XXX Currently not implemented. This function can wind up deadlocking
2265 * against another thread holding one or more of the backing pages busy.
2268 recoverbufpages(void)
2275 spin_lock(&bufqspin);
2276 while (bytes < MAXBSIZE) {
2277 bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
2282 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
2283 * cycles through the queue twice before being selected.
2285 if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) {
2286 bp->b_flags |= B_AGE;
2287 TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
2288 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN],
2296 KKASSERT(bp->b_qindex == BQUEUE_CLEAN);
2297 KKASSERT((bp->b_flags & B_DELWRI) == 0);
2300 * Start freeing the bp. This is somewhat involved.
2302 * Buffers on the clean list must be disassociated from
2303 * their current vnode
2306 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2307 kprintf("recoverbufpages: warning, locked buf %p, "
2310 ssleep(&bd_request, &bufqspin, 0, "gnbxxx", hz / 100);
2313 if (bp->b_qindex != BQUEUE_CLEAN) {
2314 kprintf("recoverbufpages: warning, BUF_LOCK blocked "
2315 "unexpectedly on buf %p index %d, race "
2321 bremfree_locked(bp);
2322 spin_unlock(&bufqspin);
2325 * Sanity check. Only BQUEUE_DIRTY[_HW] employs markers.
2327 KKASSERT((bp->b_flags & B_MARKER) == 0);
2330 * Dependancies must be handled before we disassociate the
2333 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2334 * be immediately disassociated. HAMMER then becomes
2335 * responsible for releasing the buffer.
2337 if (LIST_FIRST(&bp->b_dep) != NULL) {
2339 if (bp->b_flags & B_LOCKED) {
2341 spin_lock(&bufqspin);
2344 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2347 bytes += bp->b_bufsize;
2349 if (bp->b_flags & B_VMIO) {
2350 bp->b_flags |= B_DIRECT; /* try to free pages */
2351 vfs_vmio_release(bp);
2356 KKASSERT(bp->b_vp == NULL);
2357 KKASSERT((bp->b_flags & B_HASHED) == 0);
2360 * critical section protection is not required when
2361 * scrapping a buffer's contents because it is already
2367 bp->b_flags = B_BNOCLIP;
2368 bp->b_cmd = BUF_CMD_DONE;
2373 bp->b_xio.xio_npages = 0;
2374 bp->b_dirtyoff = bp->b_dirtyend = 0;
2376 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2378 bp->b_flags |= B_INVAL;
2381 spin_lock(&bufqspin);
2383 spin_unlock(&bufqspin);
2391 * Buffer flushing daemon. Buffers are normally flushed by the
2392 * update daemon but if it cannot keep up this process starts to
2393 * take the load in an attempt to prevent getnewbuf() from blocking.
2395 * Once a flush is initiated it does not stop until the number
2396 * of buffers falls below lodirtybuffers, but we will wake up anyone
2397 * waiting at the mid-point.
2399 static struct kproc_desc buf_kp = {
2404 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2405 kproc_start, &buf_kp)
2407 static struct kproc_desc bufhw_kp = {
2412 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2413 kproc_start, &bufhw_kp)
2419 buf_daemon1(struct thread *td, int queue, int (*buf_limit_fn)(long),
2425 marker = kmalloc(sizeof(*marker), M_BIOBUF, M_WAITOK | M_ZERO);
2426 marker->b_flags |= B_MARKER;
2427 marker->b_qindex = BQUEUE_NONE;
2430 * This process needs to be suspended prior to shutdown sync.
2432 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2433 td, SHUTDOWN_PRI_LAST);
2434 curthread->td_flags |= TDF_SYSTHREAD;
2437 * This process is allowed to take the buffer cache to the limit
2440 kproc_suspend_loop();
2443 * Do the flush as long as the number of dirty buffers
2444 * (including those running) exceeds lodirtybufspace.
2446 * When flushing limit running I/O to hirunningspace
2447 * Do the flush. Limit the amount of in-transit I/O we
2448 * allow to build up, otherwise we would completely saturate
2449 * the I/O system. Wakeup any waiting processes before we
2450 * normally would so they can run in parallel with our drain.
2452 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2453 * but because we split the operation into two threads we
2454 * have to cut it in half for each thread.
2456 waitrunningbufspace();
2457 limit = lodirtybufspace / 2;
2458 while (buf_limit_fn(limit)) {
2459 if (flushbufqueues(marker, queue) == 0)
2461 if (runningbufspace < hirunningspace)
2463 waitrunningbufspace();
2467 * We reached our low water mark, reset the
2468 * request and sleep until we are needed again.
2469 * The sleep is just so the suspend code works.
2471 spin_lock(&bufcspin);
2473 ssleep(bd_req, &bufcspin, 0, "psleep", hz);
2475 spin_unlock(&bufcspin);
2478 /*kfree(marker, M_BIOBUF);*/
2482 buf_daemon_limit(long limit)
2484 return (runningbufspace + dirtybufspace > limit ||
2485 dirtybufcount - dirtybufcounthw >= nbuf / 2);
2489 buf_daemon_hw_limit(long limit)
2491 return (runningbufspace + dirtybufspacehw > limit ||
2492 dirtybufcounthw >= nbuf / 2);
2498 buf_daemon1(bufdaemon_td, BQUEUE_DIRTY, buf_daemon_limit,
2505 buf_daemon1(bufdaemonhw_td, BQUEUE_DIRTY_HW, buf_daemon_hw_limit,
2512 * Try to flush a buffer in the dirty queue. We must be careful to
2513 * free up B_INVAL buffers instead of write them, which NFS is
2514 * particularly sensitive to.
2516 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate
2517 * that we really want to try to get the buffer out and reuse it
2518 * due to the write load on the machine.
2520 * We must lock the buffer in order to check its validity before we
2521 * can mess with its contents. bufqspin isn't enough.
2524 flushbufqueues(struct buf *marker, bufq_type_t q)
2529 KKASSERT(marker->b_qindex == BQUEUE_NONE);
2530 KKASSERT(marker->b_flags & B_MARKER);
2533 * Spinlock needed to perform operations on the queue and may be
2534 * held through a non-blocking BUF_LOCK(), but cannot be held when
2535 * BUF_UNLOCK()ing or through any other major operation.
2537 spin_lock(&bufqspin);
2538 marker->b_qindex = q;
2539 TAILQ_INSERT_HEAD(&bufqueues[q], marker, b_freelist);
2542 while ((bp = TAILQ_NEXT(bp, b_freelist)) != NULL) {
2544 * NOTE: spinlock is always held at the top of the loop
2546 if (bp->b_flags & B_MARKER)
2548 if ((bp->b_flags & B_DELWRI) == 0) {
2549 kprintf("Unexpected clean buffer %p\n", bp);
2552 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
2554 KKASSERT(bp->b_qindex == q);
2557 * Once the buffer is locked we will have no choice but to
2558 * unlock the spinlock around a later BUF_UNLOCK and re-set
2559 * bp = marker when looping. Move the marker now to make
2562 TAILQ_REMOVE(&bufqueues[q], marker, b_freelist);
2563 TAILQ_INSERT_AFTER(&bufqueues[q], bp, marker, b_freelist);
2566 * Must recheck B_DELWRI after successfully locking
2569 if ((bp->b_flags & B_DELWRI) == 0) {
2570 spin_unlock(&bufqspin);
2572 spin_lock(&bufqspin);
2578 * Remove the buffer from its queue. We still own the
2584 * Disposing of an invalid buffer counts as a flush op
2586 if (bp->b_flags & B_INVAL) {
2587 spin_unlock(&bufqspin);
2589 spin_lock(&bufqspin);
2595 * Release the spinlock for the more complex ops we
2596 * are now going to do.
2598 spin_unlock(&bufqspin);
2602 * This is a bit messy
2604 if (LIST_FIRST(&bp->b_dep) != NULL &&
2605 (bp->b_flags & B_DEFERRED) == 0 &&
2606 buf_countdeps(bp, 0)) {
2607 spin_lock(&bufqspin);
2608 TAILQ_INSERT_TAIL(&bufqueues[q], bp, b_freelist);
2610 bp->b_flags |= B_DEFERRED;
2611 spin_unlock(&bufqspin);
2613 spin_lock(&bufqspin);
2619 * spinlock not held here.
2621 * If the buffer has a dependancy, buf_checkwrite() must
2622 * also return 0 for us to be able to initate the write.
2624 * If the buffer is flagged B_ERROR it may be requeued
2625 * over and over again, we try to avoid a live lock.
2627 * NOTE: buf_checkwrite is MPSAFE.
2629 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
2631 } else if (bp->b_flags & B_ERROR) {
2632 tsleep(bp, 0, "bioer", 1);
2633 bp->b_flags &= ~B_AGE;
2636 bp->b_flags |= B_AGE;
2639 spin_lock(&bufqspin);
2643 TAILQ_REMOVE(&bufqueues[q], marker, b_freelist);
2644 marker->b_qindex = BQUEUE_NONE;
2645 spin_unlock(&bufqspin);
2653 * Returns true if no I/O is needed to access the associated VM object.
2654 * This is like findblk except it also hunts around in the VM system for
2657 * Note that we ignore vm_page_free() races from interrupts against our
2658 * lookup, since if the caller is not protected our return value will not
2659 * be any more valid then otherwise once we exit the critical section.
2662 inmem(struct vnode *vp, off_t loffset)
2665 vm_offset_t toff, tinc, size;
2669 if (findblk(vp, loffset, FINDBLK_TEST))
2671 if (vp->v_mount == NULL)
2673 if ((obj = vp->v_object) == NULL)
2677 if (size > vp->v_mount->mnt_stat.f_iosize)
2678 size = vp->v_mount->mnt_stat.f_iosize;
2680 vm_object_hold(obj);
2681 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2682 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2688 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2689 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2690 if (vm_page_is_valid(m,
2691 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0) {
2696 vm_object_drop(obj);
2703 * Locate and return the specified buffer. Unless flagged otherwise,
2704 * a locked buffer will be returned if it exists or NULL if it does not.
2706 * findblk()'d buffers are still on the bufqueues and if you intend
2707 * to use your (locked NON-TEST) buffer you need to bremfree(bp)
2708 * and possibly do other stuff to it.
2710 * FINDBLK_TEST - Do not lock the buffer. The caller is responsible
2711 * for locking the buffer and ensuring that it remains
2712 * the desired buffer after locking.
2714 * FINDBLK_NBLOCK - Lock the buffer non-blocking. If we are unable
2715 * to acquire the lock we return NULL, even if the
2718 * FINDBLK_REF - Returns the buffer ref'd, which prevents normal
2719 * reuse by getnewbuf() but does not prevent
2720 * disassociation (B_INVAL). Used to avoid deadlocks
2721 * against random (vp,loffset)s due to reassignment.
2723 * (0) - Lock the buffer blocking.
2728 findblk(struct vnode *vp, off_t loffset, int flags)
2733 lkflags = LK_EXCLUSIVE;
2734 if (flags & FINDBLK_NBLOCK)
2735 lkflags |= LK_NOWAIT;
2739 * Lookup. Ref the buf while holding v_token to prevent
2740 * reuse (but does not prevent diassociation).
2742 lwkt_gettoken_shared(&vp->v_token);
2743 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2745 lwkt_reltoken(&vp->v_token);
2749 lwkt_reltoken(&vp->v_token);
2752 * If testing only break and return bp, do not lock.
2754 if (flags & FINDBLK_TEST)
2758 * Lock the buffer, return an error if the lock fails.
2759 * (only FINDBLK_NBLOCK can cause the lock to fail).
2761 if (BUF_LOCK(bp, lkflags)) {
2762 atomic_subtract_int(&bp->b_refs, 1);
2763 /* bp = NULL; not needed */
2768 * Revalidate the locked buf before allowing it to be
2771 if (bp->b_vp == vp && bp->b_loffset == loffset)
2773 atomic_subtract_int(&bp->b_refs, 1);
2780 if ((flags & FINDBLK_REF) == 0)
2781 atomic_subtract_int(&bp->b_refs, 1);
2788 * Similar to getblk() except only returns the buffer if it is
2789 * B_CACHE and requires no other manipulation. Otherwise NULL
2792 * If B_RAM is set the buffer might be just fine, but we return
2793 * NULL anyway because we want the code to fall through to the
2794 * cluster read. Otherwise read-ahead breaks.
2796 * If blksize is 0 the buffer cache buffer must already be fully
2799 * If blksize is non-zero getblk() will be used, allowing a buffer
2800 * to be reinstantiated from its VM backing store. The buffer must
2801 * still be fully cached after reinstantiation to be returned.
2804 getcacheblk(struct vnode *vp, off_t loffset, int blksize, int blkflags)
2807 int fndflags = (blkflags & GETBLK_NOWAIT) ? FINDBLK_NBLOCK : 0;
2810 bp = getblk(vp, loffset, blksize, blkflags, 0);
2812 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) ==
2814 bp->b_flags &= ~B_AGE;
2821 bp = findblk(vp, loffset, fndflags);
2823 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) ==
2825 bp->b_flags &= ~B_AGE;
2839 * Get a block given a specified block and offset into a file/device.
2840 * B_INVAL may or may not be set on return. The caller should clear
2841 * B_INVAL prior to initiating a READ.
2843 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2844 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2845 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2846 * without doing any of those things the system will likely believe
2847 * the buffer to be valid (especially if it is not B_VMIO), and the
2848 * next getblk() will return the buffer with B_CACHE set.
2850 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2851 * an existing buffer.
2853 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2854 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2855 * and then cleared based on the backing VM. If the previous buffer is
2856 * non-0-sized but invalid, B_CACHE will be cleared.
2858 * If getblk() must create a new buffer, the new buffer is returned with
2859 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2860 * case it is returned with B_INVAL clear and B_CACHE set based on the
2863 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2864 * B_CACHE bit is clear.
2866 * What this means, basically, is that the caller should use B_CACHE to
2867 * determine whether the buffer is fully valid or not and should clear
2868 * B_INVAL prior to issuing a read. If the caller intends to validate
2869 * the buffer by loading its data area with something, the caller needs
2870 * to clear B_INVAL. If the caller does this without issuing an I/O,
2871 * the caller should set B_CACHE ( as an optimization ), else the caller
2872 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2873 * a write attempt or if it was a successfull read. If the caller
2874 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2875 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2879 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2880 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2885 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2888 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2892 if (size > MAXBSIZE)
2893 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2894 if (vp->v_object == NULL)
2895 panic("getblk: vnode %p has no object!", vp);
2898 if ((bp = findblk(vp, loffset, FINDBLK_REF | FINDBLK_TEST)) != NULL) {
2900 * The buffer was found in the cache, but we need to lock it.
2901 * We must acquire a ref on the bp to prevent reuse, but
2902 * this will not prevent disassociation (brelvp()) so we
2903 * must recheck (vp,loffset) after acquiring the lock.
2905 * Without the ref the buffer could potentially be reused
2906 * before we acquire the lock and create a deadlock
2907 * situation between the thread trying to reuse the buffer
2908 * and us due to the fact that we would wind up blocking
2909 * on a random (vp,loffset).
2911 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2912 if (blkflags & GETBLK_NOWAIT) {
2916 lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2917 if (blkflags & GETBLK_PCATCH)
2918 lkflags |= LK_PCATCH;
2919 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2922 if (error == ENOLCK)
2926 /* buffer may have changed on us */
2931 * Once the buffer has been locked, make sure we didn't race
2932 * a buffer recyclement. Buffers that are no longer hashed
2933 * will have b_vp == NULL, so this takes care of that check
2936 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2937 kprintf("Warning buffer %p (vp %p loffset %lld) "
2939 bp, vp, (long long)loffset);
2945 * If SZMATCH any pre-existing buffer must be of the requested
2946 * size or NULL is returned. The caller absolutely does not
2947 * want getblk() to bwrite() the buffer on a size mismatch.
2949 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2955 * All vnode-based buffers must be backed by a VM object.
2957 KKASSERT(bp->b_flags & B_VMIO);
2958 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2959 bp->b_flags &= ~B_AGE;
2962 * Make sure that B_INVAL buffers do not have a cached
2963 * block number translation.
2965 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2966 kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2967 " did not have cleared bio_offset cache\n",
2968 bp, vp, (long long)loffset);
2969 clearbiocache(&bp->b_bio2);
2973 * The buffer is locked. B_CACHE is cleared if the buffer is
2976 if (bp->b_flags & B_INVAL)
2977 bp->b_flags &= ~B_CACHE;
2981 * Any size inconsistancy with a dirty buffer or a buffer
2982 * with a softupdates dependancy must be resolved. Resizing
2983 * the buffer in such circumstances can lead to problems.
2985 * Dirty or dependant buffers are written synchronously.
2986 * Other types of buffers are simply released and
2987 * reconstituted as they may be backed by valid, dirty VM
2988 * pages (but not marked B_DELWRI).
2990 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2991 * and may be left over from a prior truncation (and thus
2992 * no longer represent the actual EOF point), so we
2993 * definitely do not want to B_NOCACHE the backing store.
2995 if (size != bp->b_bcount) {
2996 if (bp->b_flags & B_DELWRI) {
2997 bp->b_flags |= B_RELBUF;
2999 } else if (LIST_FIRST(&bp->b_dep)) {
3000 bp->b_flags |= B_RELBUF;
3003 bp->b_flags |= B_RELBUF;
3008 KKASSERT(size <= bp->b_kvasize);
3009 KASSERT(bp->b_loffset != NOOFFSET,
3010 ("getblk: no buffer offset"));
3013 * A buffer with B_DELWRI set and B_CACHE clear must
3014 * be committed before we can return the buffer in
3015 * order to prevent the caller from issuing a read
3016 * ( due to B_CACHE not being set ) and overwriting
3019 * Most callers, including NFS and FFS, need this to
3020 * operate properly either because they assume they
3021 * can issue a read if B_CACHE is not set, or because
3022 * ( for example ) an uncached B_DELWRI might loop due
3023 * to softupdates re-dirtying the buffer. In the latter
3024 * case, B_CACHE is set after the first write completes,
3025 * preventing further loops.
3027 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3028 * above while extending the buffer, we cannot allow the
3029 * buffer to remain with B_CACHE set after the write
3030 * completes or it will represent a corrupt state. To
3031 * deal with this we set B_NOCACHE to scrap the buffer
3034 * XXX Should this be B_RELBUF instead of B_NOCACHE?
3035 * I'm not even sure this state is still possible
3036 * now that getblk() writes out any dirty buffers
3039 * We might be able to do something fancy, like setting
3040 * B_CACHE in bwrite() except if B_DELWRI is already set,
3041 * so the below call doesn't set B_CACHE, but that gets real
3042 * confusing. This is much easier.
3045 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3046 kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
3047 "and CACHE clear, b_flags %08x\n",
3048 bp, (intmax_t)bp->b_loffset, bp->b_flags);
3049 bp->b_flags |= B_NOCACHE;
3055 * Buffer is not in-core, create new buffer. The buffer
3056 * returned by getnewbuf() is locked. Note that the returned
3057 * buffer is also considered valid (not marked B_INVAL).
3059 * Calculating the offset for the I/O requires figuring out
3060 * the block size. We use DEV_BSIZE for VBLK or VCHR and
3061 * the mount's f_iosize otherwise. If the vnode does not
3062 * have an associated mount we assume that the passed size is
3065 * Note that vn_isdisk() cannot be used here since it may
3066 * return a failure for numerous reasons. Note that the
3067 * buffer size may be larger then the block size (the caller
3068 * will use block numbers with the proper multiple). Beware
3069 * of using any v_* fields which are part of unions. In
3070 * particular, in DragonFly the mount point overloading
3071 * mechanism uses the namecache only and the underlying
3072 * directory vnode is not a special case.
3076 if (vp->v_type == VBLK || vp->v_type == VCHR)
3078 else if (vp->v_mount)
3079 bsize = vp->v_mount->mnt_stat.f_iosize;
3083 maxsize = size + (loffset & PAGE_MASK);
3084 maxsize = imax(maxsize, bsize);
3086 bp = getnewbuf(blkflags, slptimeo, size, maxsize);
3088 if (slpflags || slptimeo)
3094 * Atomically insert the buffer into the hash, so that it can
3095 * be found by findblk().
3097 * If bgetvp() returns non-zero a collision occured, and the
3098 * bp will not be associated with the vnode.
3100 * Make sure the translation layer has been cleared.
3102 bp->b_loffset = loffset;
3103 bp->b_bio2.bio_offset = NOOFFSET;
3104 /* bp->b_bio2.bio_next = NULL; */
3106 if (bgetvp(vp, bp, size)) {
3107 bp->b_flags |= B_INVAL;
3113 * All vnode-based buffers must be backed by a VM object.
3115 KKASSERT(vp->v_object != NULL);
3116 bp->b_flags |= B_VMIO;
3117 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3121 KKASSERT(dsched_is_clear_buf_priv(bp));
3128 * Reacquire a buffer that was previously released to the locked queue,
3129 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
3130 * set B_LOCKED (which handles the acquisition race).
3132 * To this end, either B_LOCKED must be set or the dependancy list must be
3138 regetblk(struct buf *bp)
3140 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
3141 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
3148 * Get an empty, disassociated buffer of given size. The buffer is
3149 * initially set to B_INVAL.
3151 * critical section protection is not required for the allocbuf()
3152 * call because races are impossible here.
3162 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3164 while ((bp = getnewbuf(0, 0, size, maxsize)) == NULL)
3167 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3168 KKASSERT(dsched_is_clear_buf_priv(bp));
3176 * This code constitutes the buffer memory from either anonymous system
3177 * memory (in the case of non-VMIO operations) or from an associated
3178 * VM object (in the case of VMIO operations). This code is able to
3179 * resize a buffer up or down.
3181 * Note that this code is tricky, and has many complications to resolve
3182 * deadlock or inconsistant data situations. Tread lightly!!!
3183 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3184 * the caller. Calling this code willy nilly can result in the loss of
3187 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3188 * B_CACHE for the non-VMIO case.
3190 * This routine does not need to be called from a critical section but you
3191 * must own the buffer.
3196 allocbuf(struct buf *bp, int size)
3198 int newbsize, mbsize;
3201 if (BUF_REFCNT(bp) == 0)
3202 panic("allocbuf: buffer not busy");
3204 if (bp->b_kvasize < size)
3205 panic("allocbuf: buffer too small");
3207 if ((bp->b_flags & B_VMIO) == 0) {
3211 * Just get anonymous memory from the kernel. Don't
3212 * mess with B_CACHE.
3214 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3215 if (bp->b_flags & B_MALLOC)
3218 newbsize = round_page(size);
3220 if (newbsize < bp->b_bufsize) {
3222 * Malloced buffers are not shrunk
3224 if (bp->b_flags & B_MALLOC) {
3226 bp->b_bcount = size;
3228 kfree(bp->b_data, M_BIOBUF);
3229 if (bp->b_bufsize) {
3230 atomic_subtract_long(&bufmallocspace, bp->b_bufsize);
3234 bp->b_data = bp->b_kvabase;
3236 bp->b_flags &= ~B_MALLOC;
3242 (vm_offset_t) bp->b_data + newbsize,
3243 (vm_offset_t) bp->b_data + bp->b_bufsize);
3244 } else if (newbsize > bp->b_bufsize) {
3246 * We only use malloced memory on the first allocation.
3247 * and revert to page-allocated memory when the buffer
3250 if ((bufmallocspace < maxbufmallocspace) &&
3251 (bp->b_bufsize == 0) &&
3252 (mbsize <= PAGE_SIZE/2)) {
3254 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
3255 bp->b_bufsize = mbsize;
3256 bp->b_bcount = size;
3257 bp->b_flags |= B_MALLOC;
3258 atomic_add_long(&bufmallocspace, mbsize);
3264 * If the buffer is growing on its other-than-first
3265 * allocation, then we revert to the page-allocation
3268 if (bp->b_flags & B_MALLOC) {
3269 origbuf = bp->b_data;
3270 origbufsize = bp->b_bufsize;
3271 bp->b_data = bp->b_kvabase;
3272 if (bp->b_bufsize) {
3273 atomic_subtract_long(&bufmallocspace,
3278 bp->b_flags &= ~B_MALLOC;
3279 newbsize = round_page(newbsize);
3283 (vm_offset_t) bp->b_data + bp->b_bufsize,
3284 (vm_offset_t) bp->b_data + newbsize);
3286 bcopy(origbuf, bp->b_data, origbufsize);
3287 kfree(origbuf, M_BIOBUF);
3294 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3295 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3296 newbsize + PAGE_MASK) >> PAGE_SHIFT;
3297 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
3299 if (bp->b_flags & B_MALLOC)
3300 panic("allocbuf: VMIO buffer can't be malloced");
3302 * Set B_CACHE initially if buffer is 0 length or will become
3305 if (size == 0 || bp->b_bufsize == 0)
3306 bp->b_flags |= B_CACHE;
3308 if (newbsize < bp->b_bufsize) {
3310 * DEV_BSIZE aligned new buffer size is less then the
3311 * DEV_BSIZE aligned existing buffer size. Figure out
3312 * if we have to remove any pages.
3314 if (desiredpages < bp->b_xio.xio_npages) {
3315 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
3317 * the page is not freed here -- it
3318 * is the responsibility of
3319 * vnode_pager_setsize
3321 m = bp->b_xio.xio_pages[i];
3322 KASSERT(m != bogus_page,
3323 ("allocbuf: bogus page found"));
3324 vm_page_busy_wait(m, TRUE, "biodep");
3325 bp->b_xio.xio_pages[i] = NULL;
3326 vm_page_unwire(m, 0);
3329 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
3330 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
3331 bp->b_xio.xio_npages = desiredpages;
3333 } else if (size > bp->b_bcount) {
3335 * We are growing the buffer, possibly in a
3336 * byte-granular fashion.
3344 * Step 1, bring in the VM pages from the object,
3345 * allocating them if necessary. We must clear
3346 * B_CACHE if these pages are not valid for the
3347 * range covered by the buffer.
3349 * critical section protection is required to protect
3350 * against interrupts unbusying and freeing pages
3351 * between our vm_page_lookup() and our
3352 * busycheck/wiring call.
3357 vm_object_hold(obj);
3358 while (bp->b_xio.xio_npages < desiredpages) {
3363 pi = OFF_TO_IDX(bp->b_loffset) +
3364 bp->b_xio.xio_npages;
3367 * Blocking on m->busy might lead to a
3370 * vm_fault->getpages->cluster_read->allocbuf
3372 m = vm_page_lookup_busy_try(obj, pi, FALSE,
3375 vm_page_sleep_busy(m, FALSE, "pgtblk");
3380 * note: must allocate system pages
3381 * since blocking here could intefere
3382 * with paging I/O, no matter which
3385 m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages);
3388 vm_page_flag_clear(m, PG_ZERO);
3390 bp->b_flags &= ~B_CACHE;
3391 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3392 ++bp->b_xio.xio_npages;
3398 * We found a page and were able to busy it.
3400 vm_page_flag_clear(m, PG_ZERO);
3403 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3404 ++bp->b_xio.xio_npages;
3405 if (bp->b_act_count < m->act_count)
3406 bp->b_act_count = m->act_count;
3408 vm_object_drop(obj);
3411 * Step 2. We've loaded the pages into the buffer,
3412 * we have to figure out if we can still have B_CACHE
3413 * set. Note that B_CACHE is set according to the
3414 * byte-granular range ( bcount and size ), not the
3415 * aligned range ( newbsize ).
3417 * The VM test is against m->valid, which is DEV_BSIZE
3418 * aligned. Needless to say, the validity of the data
3419 * needs to also be DEV_BSIZE aligned. Note that this
3420 * fails with NFS if the server or some other client
3421 * extends the file's EOF. If our buffer is resized,
3422 * B_CACHE may remain set! XXX
3425 toff = bp->b_bcount;
3426 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3428 while ((bp->b_flags & B_CACHE) && toff < size) {
3431 if (tinc > (size - toff))
3434 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
3442 bp->b_xio.xio_pages[pi]
3449 * Step 3, fixup the KVM pmap. Remember that
3450 * bp->b_data is relative to bp->b_loffset, but
3451 * bp->b_loffset may be offset into the first page.
3454 bp->b_data = (caddr_t)
3455 trunc_page((vm_offset_t)bp->b_data);
3457 (vm_offset_t)bp->b_data,
3458 bp->b_xio.xio_pages,
3459 bp->b_xio.xio_npages
3461 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3462 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3466 /* adjust space use on already-dirty buffer */
3467 if (bp->b_flags & B_DELWRI) {
3468 spin_lock(&bufcspin);
3469 dirtybufspace += newbsize - bp->b_bufsize;
3470 if (bp->b_flags & B_HEAVY)
3471 dirtybufspacehw += newbsize - bp->b_bufsize;
3472 spin_unlock(&bufcspin);
3474 if (newbsize < bp->b_bufsize)
3476 bp->b_bufsize = newbsize; /* actual buffer allocation */
3477 bp->b_bcount = size; /* requested buffer size */
3484 * Wait for buffer I/O completion, returning error status. B_EINTR
3485 * is converted into an EINTR error but not cleared (since a chain
3486 * of biowait() calls may occur).
3488 * On return bpdone() will have been called but the buffer will remain
3489 * locked and will not have been brelse()'d.
3491 * NOTE! If a timeout is specified and ETIMEDOUT occurs the I/O is
3492 * likely still in progress on return.
3494 * NOTE! This operation is on a BIO, not a BUF.
3496 * NOTE! BIO_DONE is cleared by vn_strategy()
3501 _biowait(struct bio *bio, const char *wmesg, int to)
3503 struct buf *bp = bio->bio_buf;
3508 KKASSERT(bio == &bp->b_bio1);
3510 flags = bio->bio_flags;
3511 if (flags & BIO_DONE)
3513 nflags = flags | BIO_WANT;
3514 tsleep_interlock(bio, 0);
3515 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3517 error = tsleep(bio, PINTERLOCKED, wmesg, to);
3518 else if (bp->b_cmd == BUF_CMD_READ)
3519 error = tsleep(bio, PINTERLOCKED, "biord", to);
3521 error = tsleep(bio, PINTERLOCKED, "biowr", to);
3523 kprintf("tsleep error biowait %d\n", error);
3532 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3533 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
3534 if (bp->b_flags & B_EINTR)
3536 if (bp->b_flags & B_ERROR)
3537 return (bp->b_error ? bp->b_error : EIO);
3542 biowait(struct bio *bio, const char *wmesg)
3544 return(_biowait(bio, wmesg, 0));
3548 biowait_timeout(struct bio *bio, const char *wmesg, int to)
3550 return(_biowait(bio, wmesg, to));
3554 * This associates a tracking count with an I/O. vn_strategy() and
3555 * dev_dstrategy() do this automatically but there are a few cases
3556 * where a vnode or device layer is bypassed when a block translation
3557 * is cached. In such cases bio_start_transaction() may be called on
3558 * the bypassed layers so the system gets an I/O in progress indication
3559 * for those higher layers.
3562 bio_start_transaction(struct bio *bio, struct bio_track *track)
3564 bio->bio_track = track;
3565 if (dsched_is_clear_buf_priv(bio->bio_buf))
3566 dsched_new_buf(bio->bio_buf);
3567 bio_track_ref(track);
3571 * Initiate I/O on a vnode.
3573 * SWAPCACHE OPERATION:
3575 * Real buffer cache buffers have a non-NULL bp->b_vp. Unfortunately
3576 * devfs also uses b_vp for fake buffers so we also have to check
3577 * that B_PAGING is 0. In this case the passed 'vp' is probably the
3578 * underlying block device. The swap assignments are related to the
3579 * buffer cache buffer's b_vp, not the passed vp.
3581 * The passed vp == bp->b_vp only in the case where the strategy call
3582 * is made on the vp itself for its own buffers (a regular file or
3583 * block device vp). The filesystem usually then re-calls vn_strategy()
3584 * after translating the request to an underlying device.
3586 * Cluster buffers set B_CLUSTER and the passed vp is the vp of the
3587 * underlying buffer cache buffers.
3589 * We can only deal with page-aligned buffers at the moment, because
3590 * we can't tell what the real dirty state for pages straddling a buffer
3593 * In order to call swap_pager_strategy() we must provide the VM object
3594 * and base offset for the underlying buffer cache pages so it can find
3598 vn_strategy(struct vnode *vp, struct bio *bio)
3600 struct bio_track *track;
3601 struct buf *bp = bio->bio_buf;
3603 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3606 * Set when an I/O is issued on the bp. Cleared by consumers
3607 * (aka HAMMER), allowing the consumer to determine if I/O had
3608 * actually occurred.
3610 bp->b_flags |= B_IODEBUG;
3613 * Handle the swap cache intercept.
3615 if (vn_cache_strategy(vp, bio))
3619 * Otherwise do the operation through the filesystem
3621 if (bp->b_cmd == BUF_CMD_READ)
3622 track = &vp->v_track_read;
3624 track = &vp->v_track_write;
3625 KKASSERT((bio->bio_flags & BIO_DONE) == 0);
3626 bio->bio_track = track;
3627 if (dsched_is_clear_buf_priv(bio->bio_buf))
3628 dsched_new_buf(bio->bio_buf);
3629 bio_track_ref(track);
3630 vop_strategy(*vp->v_ops, vp, bio);
3633 static void vn_cache_strategy_callback(struct bio *bio);
3636 vn_cache_strategy(struct vnode *vp, struct bio *bio)
3638 struct buf *bp = bio->bio_buf;
3645 * Is this buffer cache buffer suitable for reading from
3648 if (vm_swapcache_read_enable == 0 ||
3649 bp->b_cmd != BUF_CMD_READ ||
3650 ((bp->b_flags & B_CLUSTER) == 0 &&
3651 (bp->b_vp == NULL || (bp->b_flags & B_PAGING))) ||
3652 ((int)bp->b_loffset & PAGE_MASK) != 0 ||
3653 (bp->b_bcount & PAGE_MASK) != 0) {
3658 * Figure out the original VM object (it will match the underlying
3659 * VM pages). Note that swap cached data uses page indices relative
3660 * to that object, not relative to bio->bio_offset.
3662 if (bp->b_flags & B_CLUSTER)
3663 object = vp->v_object;
3665 object = bp->b_vp->v_object;
3668 * In order to be able to use the swap cache all underlying VM
3669 * pages must be marked as such, and we can't have any bogus pages.
3671 for (i = 0; i < bp->b_xio.xio_npages; ++i) {
3672 m = bp->b_xio.xio_pages[i];
3673 if ((m->flags & PG_SWAPPED) == 0)
3675 if (m == bogus_page)
3680 * If we are good then issue the I/O using swap_pager_strategy().
3682 * We can only do this if the buffer actually supports object-backed
3683 * I/O. If it doesn't npages will be 0.
3685 if (i && i == bp->b_xio.xio_npages) {
3686 m = bp->b_xio.xio_pages[0];
3687 nbio = push_bio(bio);
3688 nbio->bio_done = vn_cache_strategy_callback;
3689 nbio->bio_offset = ptoa(m->pindex);
3690 KKASSERT(m->object == object);
3691 swap_pager_strategy(object, nbio);
3698 * This is a bit of a hack but since the vn_cache_strategy() function can
3699 * override a VFS's strategy function we must make sure that the bio, which
3700 * is probably bio2, doesn't leak an unexpected offset value back to the
3701 * filesystem. The filesystem (e.g. UFS) might otherwise assume that the
3702 * bio went through its own file strategy function and the the bio2 offset
3703 * is a cached disk offset when, in fact, it isn't.
3706 vn_cache_strategy_callback(struct bio *bio)
3708 bio->bio_offset = NOOFFSET;
3709 biodone(pop_bio(bio));
3715 * Finish I/O on a buffer after all BIOs have been processed.
3716 * Called when the bio chain is exhausted or by biowait. If called
3717 * by biowait, elseit is typically 0.
3719 * bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3720 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3721 * assuming B_INVAL is clear.
3723 * For the VMIO case, we set B_CACHE if the op was a read and no
3724 * read error occured, or if the op was a write. B_CACHE is never
3725 * set if the buffer is invalid or otherwise uncacheable.
3727 * bpdone does not mess with B_INVAL, allowing the I/O routine or the
3728 * initiator to leave B_INVAL set to brelse the buffer out of existance
3729 * in the biodone routine.
3732 bpdone(struct buf *bp, int elseit)
3736 KASSERT(BUF_REFCNTNB(bp) > 0,
3737 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3738 KASSERT(bp->b_cmd != BUF_CMD_DONE,
3739 ("biodone: bp %p already done!", bp));
3742 * No more BIOs are left. All completion functions have been dealt
3743 * with, now we clean up the buffer.
3746 bp->b_cmd = BUF_CMD_DONE;
3749 * Only reads and writes are processed past this point.
3751 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3752 if (cmd == BUF_CMD_FREEBLKS)
3753 bp->b_flags |= B_NOCACHE;
3760 * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3761 * a lot worse. XXX - move this above the clearing of b_cmd
3763 if (LIST_FIRST(&bp->b_dep) != NULL)
3764 buf_complete(bp); /* MPSAFE */
3767 * A failed write must re-dirty the buffer unless B_INVAL
3768 * was set. Only applicable to normal buffers (with VPs).
3769 * vinum buffers may not have a vp.
3771 if (cmd == BUF_CMD_WRITE &&
3772 (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
3773 bp->b_flags &= ~B_NOCACHE;
3778 if (bp->b_flags & B_VMIO) {
3784 struct vnode *vp = bp->b_vp;
3788 #if defined(VFS_BIO_DEBUG)
3789 if (vp->v_auxrefs == 0)
3790 panic("biodone: zero vnode hold count");
3791 if ((vp->v_flag & VOBJBUF) == 0)
3792 panic("biodone: vnode is not setup for merged cache");
3795 foff = bp->b_loffset;
3796 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3797 KASSERT(obj != NULL, ("biodone: missing VM object"));
3799 #if defined(VFS_BIO_DEBUG)
3800 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3801 kprintf("biodone: paging in progress(%d) < "
3802 "bp->b_xio.xio_npages(%d)\n",
3803 obj->paging_in_progress,
3804 bp->b_xio.xio_npages);
3809 * Set B_CACHE if the op was a normal read and no error
3810 * occured. B_CACHE is set for writes in the b*write()
3813 iosize = bp->b_bcount - bp->b_resid;
3814 if (cmd == BUF_CMD_READ &&
3815 (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3816 bp->b_flags |= B_CACHE;
3819 vm_object_hold(obj);
3820 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3824 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3829 * cleanup bogus pages, restoring the originals. Since
3830 * the originals should still be wired, we don't have
3831 * to worry about interrupt/freeing races destroying
3832 * the VM object association.
3834 m = bp->b_xio.xio_pages[i];
3835 if (m == bogus_page) {
3837 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3839 panic("biodone: page disappeared");
3840 bp->b_xio.xio_pages[i] = m;
3841 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3842 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3844 #if defined(VFS_BIO_DEBUG)
3845 if (OFF_TO_IDX(foff) != m->pindex) {
3846 kprintf("biodone: foff(%lu)/m->pindex(%ld) "
3848 (unsigned long)foff, (long)m->pindex);
3853 * In the write case, the valid and clean bits are
3854 * already changed correctly (see bdwrite()), so we
3855 * only need to do this here in the read case.
3857 vm_page_busy_wait(m, FALSE, "bpdpgw");
3858 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3859 vfs_clean_one_page(bp, i, m);
3861 vm_page_flag_clear(m, PG_ZERO);
3864 * when debugging new filesystems or buffer I/O
3865 * methods, this is the most common error that pops
3866 * up. if you see this, you have not set the page
3867 * busy flag correctly!!!
3870 kprintf("biodone: page busy < 0, "
3871 "pindex: %d, foff: 0x(%x,%x), "
3872 "resid: %d, index: %d\n",
3873 (int) m->pindex, (int)(foff >> 32),
3874 (int) foff & 0xffffffff, resid, i);
3875 if (!vn_isdisk(vp, NULL))
3876 kprintf(" iosize: %ld, loffset: %lld, "
3877 "flags: 0x%08x, npages: %d\n",
3878 bp->b_vp->v_mount->mnt_stat.f_iosize,
3879 (long long)bp->b_loffset,
3880 bp->b_flags, bp->b_xio.xio_npages);
3882 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3883 (long long)bp->b_loffset,
3884 bp->b_flags, bp->b_xio.xio_npages);
3885 kprintf(" valid: 0x%x, dirty: 0x%x, "
3889 panic("biodone: page busy < 0");
3891 vm_page_io_finish(m);
3893 vm_object_pip_wakeup(obj);
3894 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3897 bp->b_flags &= ~B_HASBOGUS;
3898 vm_object_drop(obj);
3902 * Finish up by releasing the buffer. There are no more synchronous
3903 * or asynchronous completions, those were handled by bio_done
3907 if (bp->b_flags & (B_NOCACHE|B_INVAL|B_ERROR|B_RELBUF))
3918 biodone(struct bio *bio)
3920 struct buf *bp = bio->bio_buf;
3922 runningbufwakeup(bp);
3925 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
3928 biodone_t *done_func;
3929 struct bio_track *track;
3932 * BIO tracking. Most but not all BIOs are tracked.
3934 if ((track = bio->bio_track) != NULL) {
3935 bio_track_rel(track);
3936 bio->bio_track = NULL;
3940 * A bio_done function terminates the loop. The function
3941 * will be responsible for any further chaining and/or
3942 * buffer management.
3944 * WARNING! The done function can deallocate the buffer!
3946 if ((done_func = bio->bio_done) != NULL) {
3947 bio->bio_done = NULL;
3951 bio = bio->bio_prev;
3955 * If we've run out of bio's do normal [a]synchronous completion.
3961 * Synchronous biodone - this terminates a synchronous BIO.
3963 * bpdone() is called with elseit=FALSE, leaving the buffer completed
3964 * but still locked. The caller must brelse() the buffer after waiting
3968 biodone_sync(struct bio *bio)
3970 struct buf *bp = bio->bio_buf;
3974 KKASSERT(bio == &bp->b_bio1);
3978 flags = bio->bio_flags;
3979 nflags = (flags | BIO_DONE) & ~BIO_WANT;
3981 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3982 if (flags & BIO_WANT)
3992 * This routine is called in lieu of iodone in the case of
3993 * incomplete I/O. This keeps the busy status for pages
3997 vfs_unbusy_pages(struct buf *bp)
4001 runningbufwakeup(bp);
4003 if (bp->b_flags & B_VMIO) {
4004 struct vnode *vp = bp->b_vp;
4008 vm_object_hold(obj);
4010 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4011 vm_page_t m = bp->b_xio.xio_pages[i];
4014 * When restoring bogus changes the original pages
4015 * should still be wired, so we are in no danger of
4016 * losing the object association and do not need
4017 * critical section protection particularly.
4019 if (m == bogus_page) {
4020 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
4022 panic("vfs_unbusy_pages: page missing");
4024 bp->b_xio.xio_pages[i] = m;
4025 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4026 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
4028 vm_page_busy_wait(m, FALSE, "bpdpgw");
4029 vm_page_flag_clear(m, PG_ZERO);
4030 vm_page_io_finish(m);
4032 vm_object_pip_wakeup(obj);
4034 bp->b_flags &= ~B_HASBOGUS;
4035 vm_object_drop(obj);
4042 * This routine is called before a device strategy routine.
4043 * It is used to tell the VM system that paging I/O is in
4044 * progress, and treat the pages associated with the buffer
4045 * almost as being PG_BUSY. Also the object 'paging_in_progress'
4046 * flag is handled to make sure that the object doesn't become
4049 * Since I/O has not been initiated yet, certain buffer flags
4050 * such as B_ERROR or B_INVAL may be in an inconsistant state
4051 * and should be ignored.
4056 vfs_busy_pages(struct vnode *vp, struct buf *bp)
4059 struct lwp *lp = curthread->td_lwp;
4062 * The buffer's I/O command must already be set. If reading,
4063 * B_CACHE must be 0 (double check against callers only doing
4064 * I/O when B_CACHE is 0).
4066 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4067 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
4069 if (bp->b_flags & B_VMIO) {
4073 KASSERT(bp->b_loffset != NOOFFSET,
4074 ("vfs_busy_pages: no buffer offset"));
4077 * Busy all the pages. We have to busy them all at once
4078 * to avoid deadlocks.
4081 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4082 vm_page_t m = bp->b_xio.xio_pages[i];
4084 if (vm_page_busy_try(m, FALSE)) {
4085 vm_page_sleep_busy(m, FALSE, "vbpage");
4087 vm_page_wakeup(bp->b_xio.xio_pages[i]);
4093 * Setup for I/O, soft-busy the page right now because
4094 * the next loop may block.
4096 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4097 vm_page_t m = bp->b_xio.xio_pages[i];
4099 vm_page_flag_clear(m, PG_ZERO);
4100 if ((bp->b_flags & B_CLUSTER) == 0) {
4101 vm_object_pip_add(obj, 1);
4102 vm_page_io_start(m);
4107 * Adjust protections for I/O and do bogus-page mapping.
4108 * Assume that vm_page_protect() can block (it can block
4109 * if VM_PROT_NONE, don't take any chances regardless).
4111 * In particular note that for writes we must incorporate
4112 * page dirtyness from the VM system into the buffer's
4115 * For reads we theoretically must incorporate page dirtyness
4116 * from the VM system to determine if the page needs bogus
4117 * replacement, but we shortcut the test by simply checking
4118 * that all m->valid bits are set, indicating that the page
4119 * is fully valid and does not need to be re-read. For any
4120 * VM system dirtyness the page will also be fully valid
4121 * since it was mapped at one point.
4124 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4125 vm_page_t m = bp->b_xio.xio_pages[i];
4127 vm_page_flag_clear(m, PG_ZERO); /* XXX */
4128 if (bp->b_cmd == BUF_CMD_WRITE) {
4130 * When readying a vnode-backed buffer for
4131 * a write we must zero-fill any invalid
4132 * portions of the backing VM pages, mark
4133 * it valid and clear related dirty bits.
4135 * vfs_clean_one_page() incorporates any
4136 * VM dirtyness and updates the b_dirtyoff
4137 * range (after we've made the page RO).
4139 * It is also expected that the pmap modified
4140 * bit has already been cleared by the
4141 * vm_page_protect(). We may not be able
4142 * to clear all dirty bits for a page if it
4143 * was also memory mapped (NFS).
4145 * Finally be sure to unassign any swap-cache
4146 * backing store as it is now stale.
4148 vm_page_protect(m, VM_PROT_READ);
4149 vfs_clean_one_page(bp, i, m);
4150 swap_pager_unswapped(m);
4151 } else if (m->valid == VM_PAGE_BITS_ALL) {
4153 * When readying a vnode-backed buffer for
4154 * read we must replace any dirty pages with
4155 * a bogus page so dirty data is not destroyed
4156 * when filling gaps.
4158 * To avoid testing whether the page is
4159 * dirty we instead test that the page was
4160 * at some point mapped (m->valid fully
4161 * valid) with the understanding that
4162 * this also covers the dirty case.
4164 bp->b_xio.xio_pages[i] = bogus_page;
4165 bp->b_flags |= B_HASBOGUS;
4167 } else if (m->valid & m->dirty) {
4169 * This case should not occur as partial
4170 * dirtyment can only happen if the buffer
4171 * is B_CACHE, and this code is not entered
4172 * if the buffer is B_CACHE.
4174 kprintf("Warning: vfs_busy_pages - page not "
4175 "fully valid! loff=%jx bpf=%08x "
4176 "idx=%d val=%02x dir=%02x\n",
4177 (intmax_t)bp->b_loffset, bp->b_flags,
4178 i, m->valid, m->dirty);
4179 vm_page_protect(m, VM_PROT_NONE);
4182 * The page is not valid and can be made
4185 vm_page_protect(m, VM_PROT_NONE);
4190 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4191 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
4196 * This is the easiest place to put the process accounting for the I/O
4200 if (bp->b_cmd == BUF_CMD_READ)
4201 lp->lwp_ru.ru_inblock++;
4203 lp->lwp_ru.ru_oublock++;
4208 * Tell the VM system that the pages associated with this buffer
4209 * are clean. This is used for delayed writes where the data is
4210 * going to go to disk eventually without additional VM intevention.
4212 * NOTE: While we only really need to clean through to b_bcount, we
4213 * just go ahead and clean through to b_bufsize.
4216 vfs_clean_pages(struct buf *bp)
4221 if ((bp->b_flags & B_VMIO) == 0)
4224 KASSERT(bp->b_loffset != NOOFFSET,
4225 ("vfs_clean_pages: no buffer offset"));
4227 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4228 m = bp->b_xio.xio_pages[i];
4229 vfs_clean_one_page(bp, i, m);
4234 * vfs_clean_one_page:
4236 * Set the valid bits and clear the dirty bits in a page within a
4237 * buffer. The range is restricted to the buffer's size and the
4238 * buffer's logical offset might index into the first page.
4240 * The caller has busied or soft-busied the page and it is not mapped,
4241 * test and incorporate the dirty bits into b_dirtyoff/end before
4242 * clearing them. Note that we need to clear the pmap modified bits
4243 * after determining the the page was dirty, vm_page_set_validclean()
4244 * does not do it for us.
4246 * This routine is typically called after a read completes (dirty should
4247 * be zero in that case as we are not called on bogus-replace pages),
4248 * or before a write is initiated.
4251 vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m)
4259 * Calculate offset range within the page but relative to buffer's
4260 * loffset. loffset might be offset into the first page.
4262 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
4263 bcount = bp->b_bcount + xoff; /* offset adjusted */
4269 soff = (pageno << PAGE_SHIFT);
4270 eoff = soff + PAGE_SIZE;
4278 * Test dirty bits and adjust b_dirtyoff/end.
4280 * If dirty pages are incorporated into the bp any prior
4281 * B_NEEDCOMMIT state (NFS) must be cleared because the
4282 * caller has not taken into account the new dirty data.
4284 * If the page was memory mapped the dirty bits might go beyond the
4285 * end of the buffer, but we can't really make the assumption that
4286 * a file EOF straddles the buffer (even though this is the case for
4287 * NFS if B_NEEDCOMMIT is also set). So for the purposes of clearing
4288 * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
4289 * This also saves some console spam.
4291 * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK,
4292 * NFS can handle huge commits but not huge writes.
4294 vm_page_test_dirty(m);
4296 if ((bp->b_flags & B_NEEDCOMMIT) &&
4297 (m->dirty & vm_page_bits(soff & PAGE_MASK, eoff - soff))) {
4299 kprintf("Warning: vfs_clean_one_page: bp %p "
4300 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT"
4301 " cmd %d vd %02x/%02x x/s/e %d %d %d "
4303 bp, (intmax_t)bp->b_loffset, bp->b_bcount,
4304 bp->b_flags, bp->b_cmd,
4305 m->valid, m->dirty, xoff, soff, eoff,
4306 bp->b_dirtyoff, bp->b_dirtyend);
4307 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
4309 print_backtrace(-1);
4312 * Only clear the pmap modified bits if ALL the dirty bits
4313 * are set, otherwise the system might mis-clear portions
4316 if (m->dirty == VM_PAGE_BITS_ALL &&
4317 (bp->b_flags & B_NEEDCOMMIT) == 0) {
4318 pmap_clear_modify(m);
4320 if (bp->b_dirtyoff > soff - xoff)
4321 bp->b_dirtyoff = soff - xoff;
4322 if (bp->b_dirtyend < eoff - xoff)
4323 bp->b_dirtyend = eoff - xoff;
4327 * Set related valid bits, clear related dirty bits.
4328 * Does not mess with the pmap modified bit.
4330 * WARNING! We cannot just clear all of m->dirty here as the
4331 * buffer cache buffers may use a DEV_BSIZE'd aligned
4332 * block size, or have an odd size (e.g. NFS at file EOF).
4333 * The putpages code can clear m->dirty to 0.
4335 * If a VOP_WRITE generates a buffer cache buffer which
4336 * covers the same space as mapped writable pages the
4337 * buffer flush might not be able to clear all the dirty
4338 * bits and still require a putpages from the VM system
4341 * WARNING! vm_page_set_validclean() currently assumes vm_token
4342 * is held. The page might not be busied (bdwrite() case).
4343 * XXX remove this comment once we've validated that this
4344 * is no longer an issue.
4346 vm_page_set_validclean(m, soff & PAGE_MASK, eoff - soff);
4351 * Similar to vfs_clean_one_page() but sets the bits to valid and dirty.
4352 * The page data is assumed to be valid (there is no zeroing here).
4355 vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m)
4363 * Calculate offset range within the page but relative to buffer's
4364 * loffset. loffset might be offset into the first page.
4366 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
4367 bcount = bp->b_bcount + xoff; /* offset adjusted */
4373 soff = (pageno << PAGE_SHIFT);
4374 eoff = soff + PAGE_SIZE;
4380 vm_page_set_validdirty(m, soff & PAGE_MASK, eoff - soff);
4387 * Clear a buffer. This routine essentially fakes an I/O, so we need
4388 * to clear B_ERROR and B_INVAL.
4390 * Note that while we only theoretically need to clear through b_bcount,
4391 * we go ahead and clear through b_bufsize.
4395 vfs_bio_clrbuf(struct buf *bp)
4399 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
4400 bp->b_flags &= ~(B_INVAL | B_EINTR | B_ERROR);
4401 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4402 (bp->b_loffset & PAGE_MASK) == 0) {
4403 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4404 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
4408 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
4409 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
4410 bzero(bp->b_data, bp->b_bufsize);
4411 bp->b_xio.xio_pages[0]->valid |= mask;
4417 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
4418 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
4419 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
4420 ea = (caddr_t)(vm_offset_t)ulmin(
4421 (u_long)(vm_offset_t)ea,
4422 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
4423 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4424 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
4426 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
4427 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
4431 for (; sa < ea; sa += DEV_BSIZE, j++) {
4432 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
4433 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
4434 bzero(sa, DEV_BSIZE);
4437 bp->b_xio.xio_pages[i]->valid |= mask;
4438 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
4447 * vm_hold_load_pages:
4449 * Load pages into the buffer's address space. The pages are
4450 * allocated from the kernel object in order to reduce interference
4451 * with the any VM paging I/O activity. The range of loaded
4452 * pages will be wired.
4454 * If a page cannot be allocated, the 'pagedaemon' is woken up to
4455 * retrieve the full range (to - from) of pages.
4460 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4466 to = round_page(to);
4467 from = round_page(from);
4468 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4473 * Note: must allocate system pages since blocking here
4474 * could intefere with paging I/O, no matter which
4477 vm_object_hold(&kernel_object);
4478 p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT,
4479 (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
4480 vm_object_drop(&kernel_object);
4483 p->valid = VM_PAGE_BITS_ALL;
4484 vm_page_flag_clear(p, PG_ZERO);
4485 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
4486 bp->b_xio.xio_pages[index] = p;
4493 bp->b_xio.xio_npages = index;
4497 * Allocate a page for a buffer cache buffer.
4499 * If NULL is returned the caller is expected to retry (typically check if
4500 * the page already exists on retry before trying to allocate one).
4502 * NOTE! Low-memory handling is dealt with in b[q]relse(), not here. This
4503 * function will use the system reserve with the hope that the page
4504 * allocations can be returned to PQ_CACHE/PQ_FREE when the caller
4505 * is done with the buffer.
4509 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit)
4511 int vmflags = VM_ALLOC_NORMAL | VM_ALLOC_NULL_OK;
4514 ASSERT_LWKT_TOKEN_HELD(vm_object_token(obj));
4517 * Try a normal allocation first.
4519 p = vm_page_alloc(obj, pg, vmflags);
4522 if (vm_page_lookup(obj, pg))
4524 vm_pageout_deficit += deficit;
4527 * Try again, digging into the system reserve.
4529 * Trying to recover pages from the buffer cache here can deadlock
4530 * against other threads trying to busy underlying pages so we
4531 * depend on the code in brelse() and bqrelse() to free/cache the
4532 * underlying buffer cache pages when memory is low.
4534 if (curthread->td_flags & TDF_SYSTHREAD)
4535 vmflags |= VM_ALLOC_SYSTEM | VM_ALLOC_INTERRUPT;
4537 vmflags |= VM_ALLOC_SYSTEM;
4539 /*recoverbufpages();*/
4540 p = vm_page_alloc(obj, pg, vmflags);
4543 if (vm_page_lookup(obj, pg))
4547 * Wait for memory to free up and try again
4549 if (vm_page_count_severe())
4551 vm_wait(hz / 20 + 1);
4553 p = vm_page_alloc(obj, pg, vmflags);
4556 if (vm_page_lookup(obj, pg))
4560 * Ok, now we are really in trouble.
4563 static struct krate biokrate = { .freq = 1 };
4564 krateprintf(&biokrate,
4565 "Warning: bio_page_alloc: memory exhausted "
4566 "during bufcache page allocation from %s\n",
4567 curthread->td_comm);
4569 if (curthread->td_flags & TDF_SYSTHREAD)
4570 vm_wait(hz / 20 + 1);
4572 vm_wait(hz / 2 + 1);
4577 * vm_hold_free_pages:
4579 * Return pages associated with the buffer back to the VM system.
4581 * The range of pages underlying the buffer's address space will
4582 * be unmapped and un-wired.
4587 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4591 int index, newnpages;
4593 from = round_page(from);
4594 to = round_page(to);
4595 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4598 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4599 p = bp->b_xio.xio_pages[index];
4600 if (p && (index < bp->b_xio.xio_npages)) {
4602 kprintf("vm_hold_free_pages: doffset: %lld, "
4604 (long long)bp->b_bio2.bio_offset,
4605 (long long)bp->b_loffset);
4607 bp->b_xio.xio_pages[index] = NULL;
4609 vm_page_busy_wait(p, FALSE, "vmhldpg");
4610 vm_page_unwire(p, 0);
4614 bp->b_xio.xio_npages = newnpages;
4620 * Map a user buffer into KVM via a pbuf. On return the buffer's
4621 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
4625 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
4636 * bp had better have a command and it better be a pbuf.
4638 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4639 KKASSERT(bp->b_flags & B_PAGING);
4640 KKASSERT(bp->b_kvabase);
4646 * Map the user data into KVM. Mappings have to be page-aligned.
4648 addr = (caddr_t)trunc_page((vm_offset_t)udata);
4651 vmprot = VM_PROT_READ;
4652 if (bp->b_cmd == BUF_CMD_READ)
4653 vmprot |= VM_PROT_WRITE;
4655 while (addr < udata + bytes) {
4657 * Do the vm_fault if needed; do the copy-on-write thing
4658 * when reading stuff off device into memory.
4660 * vm_fault_page*() returns a held VM page.
4662 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
4663 va = trunc_page(va);
4665 m = vm_fault_page_quick(va, vmprot, &error);
4667 for (i = 0; i < pidx; ++i) {
4668 vm_page_unhold(bp->b_xio.xio_pages[i]);
4669 bp->b_xio.xio_pages[i] = NULL;
4673 bp->b_xio.xio_pages[pidx] = m;
4679 * Map the page array and set the buffer fields to point to
4680 * the mapped data buffer.
4682 if (pidx > btoc(MAXPHYS))
4683 panic("vmapbuf: mapped more than MAXPHYS");
4684 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
4686 bp->b_xio.xio_npages = pidx;
4687 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
4688 bp->b_bcount = bytes;
4689 bp->b_bufsize = bytes;
4696 * Free the io map PTEs associated with this IO operation.
4697 * We also invalidate the TLB entries and restore the original b_addr.
4700 vunmapbuf(struct buf *bp)
4705 KKASSERT(bp->b_flags & B_PAGING);
4707 npages = bp->b_xio.xio_npages;
4708 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4709 for (pidx = 0; pidx < npages; ++pidx) {
4710 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
4711 bp->b_xio.xio_pages[pidx] = NULL;
4713 bp->b_xio.xio_npages = 0;
4714 bp->b_data = bp->b_kvabase;
4718 * Scan all buffers in the system and issue the callback.
4721 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
4727 for (n = 0; n < nbuf; ++n) {
4728 if ((error = callback(&buf[n], info)) < 0) {
4738 * nestiobuf_iodone: biodone callback for nested buffers and propagate
4739 * completion to the master buffer.
4742 nestiobuf_iodone(struct bio *bio)
4745 struct buf *mbp, *bp;
4746 struct devstat *stats;
4751 mbio = bio->bio_caller_info1.ptr;
4752 stats = bio->bio_caller_info2.ptr;
4753 mbp = mbio->bio_buf;
4755 KKASSERT(bp->b_bcount <= bp->b_bufsize);
4756 KKASSERT(mbp != bp);
4758 error = bp->b_error;
4759 if (bp->b_error == 0 &&
4760 (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) {
4762 * Not all got transfered, raise an error. We have no way to
4763 * propagate these conditions to mbp.
4768 donebytes = bp->b_bufsize;
4772 nestiobuf_done(mbio, donebytes, error, stats);
4776 nestiobuf_done(struct bio *mbio, int donebytes, int error, struct devstat *stats)
4780 mbp = mbio->bio_buf;
4782 KKASSERT((int)(intptr_t)mbio->bio_driver_info > 0);
4785 * If an error occured, propagate it to the master buffer.
4787 * Several biodone()s may wind up running concurrently so
4788 * use an atomic op to adjust b_flags.
4791 mbp->b_error = error;
4792 atomic_set_int(&mbp->b_flags, B_ERROR);
4796 * Decrement the operations in progress counter and terminate the
4797 * I/O if this was the last bit.
4799 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4802 devstat_end_transaction_buf(stats, mbp);
4808 * Initialize a nestiobuf for use. Set an initial count of 1 to prevent
4809 * the mbio from being biodone()'d while we are still adding sub-bios to
4813 nestiobuf_init(struct bio *bio)
4815 bio->bio_driver_info = (void *)1;
4819 * The BIOs added to the nestedio have already been started, remove the
4820 * count that placeheld our mbio and biodone() it if the count would
4824 nestiobuf_start(struct bio *mbio)
4826 struct buf *mbp = mbio->bio_buf;
4829 * Decrement the operations in progress counter and terminate the
4830 * I/O if this was the last bit.
4832 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4833 if (mbp->b_flags & B_ERROR)
4834 mbp->b_resid = mbp->b_bcount;
4842 * Set an intermediate error prior to calling nestiobuf_start()
4845 nestiobuf_error(struct bio *mbio, int error)
4847 struct buf *mbp = mbio->bio_buf;
4850 mbp->b_error = error;
4851 atomic_set_int(&mbp->b_flags, B_ERROR);
4856 * nestiobuf_add: setup a "nested" buffer.
4858 * => 'mbp' is a "master" buffer which is being divided into sub pieces.
4859 * => 'bp' should be a buffer allocated by getiobuf.
4860 * => 'offset' is a byte offset in the master buffer.
4861 * => 'size' is a size in bytes of this nested buffer.
4864 nestiobuf_add(struct bio *mbio, struct buf *bp, int offset, size_t size, struct devstat *stats)
4866 struct buf *mbp = mbio->bio_buf;
4867 struct vnode *vp = mbp->b_vp;
4869 KKASSERT(mbp->b_bcount >= offset + size);
4871 atomic_add_int((int *)&mbio->bio_driver_info, 1);
4873 /* kernel needs to own the lock for it to be released in biodone */
4876 bp->b_cmd = mbp->b_cmd;
4877 bp->b_bio1.bio_done = nestiobuf_iodone;
4878 bp->b_data = (char *)mbp->b_data + offset;
4879 bp->b_resid = bp->b_bcount = size;
4880 bp->b_bufsize = bp->b_bcount;
4882 bp->b_bio1.bio_track = NULL;
4883 bp->b_bio1.bio_caller_info1.ptr = mbio;
4884 bp->b_bio1.bio_caller_info2.ptr = stats;
4888 * print out statistics from the current status of the buffer pool
4889 * this can be toggeled by the system control option debug.syncprt
4898 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
4899 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
4901 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
4903 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4906 spin_lock(&bufqspin);
4907 TAILQ_FOREACH(bp, dp, b_freelist) {
4908 if (bp->b_flags & B_MARKER)
4910 counts[bp->b_bufsize/PAGE_SIZE]++;
4913 spin_unlock(&bufqspin);
4915 kprintf("%s: total-%d", bname[i], count);
4916 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4918 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
4926 DB_SHOW_COMMAND(buffer, db_show_buffer)
4929 struct buf *bp = (struct buf *)addr;
4932 db_printf("usage: show buffer <addr>\n");
4936 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4937 db_printf("b_cmd = %d\n", bp->b_cmd);
4938 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
4939 "b_resid = %d\n, b_data = %p, "
4940 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
4941 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4943 (long long)bp->b_bio2.bio_offset,
4944 (long long)(bp->b_bio2.bio_next ?
4945 bp->b_bio2.bio_next->bio_offset : (off_t)-1));
4946 if (bp->b_xio.xio_npages) {
4948 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
4949 bp->b_xio.xio_npages);
4950 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4952 m = bp->b_xio.xio_pages[i];
4953 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4954 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4955 if ((i + 1) < bp->b_xio.xio_npages)