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(long 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 dirtykvaspace; /* locked by bufcspin */
133 static long dirtybufspace; /* locked by bufcspin */
134 static int dirtybufcount; /* locked by bufcspin */
135 static long dirtybufspacehw; /* locked by bufcspin */
136 static int dirtybufcounthw; /* locked by bufcspin */
137 static long runningbufspace; /* locked by bufcspin */
138 static int runningbufcount; /* locked by bufcspin */
139 long lodirtybufspace;
140 long hidirtybufspace;
141 static int getnewbufcalls;
142 static int getnewbufrestarts;
143 static int recoverbufcalls;
144 static int needsbuffer; /* locked by bufcspin */
145 static int bd_request; /* locked by bufcspin */
146 static int bd_request_hw; /* locked by bufcspin */
147 static u_int bd_wake_ary[BD_WAKE_SIZE];
148 static u_int bd_wake_index;
149 static u_int vm_cycle_point = 40; /* 23-36 will migrate more act->inact */
150 static int debug_commit;
152 static struct thread *bufdaemon_td;
153 static struct thread *bufdaemonhw_td;
154 static u_int lowmempgallocs;
155 static u_int lowmempgfails;
158 * Sysctls for operational control of the buffer cache.
160 SYSCTL_LONG(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
161 "Number of dirty buffers to flush before bufdaemon becomes inactive");
162 SYSCTL_LONG(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
163 "High watermark used to trigger explicit flushing of dirty buffers");
164 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
165 "Minimum amount of buffer space required for active I/O");
166 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
167 "Maximum amount of buffer space to usable for active I/O");
168 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgallocs, CTLFLAG_RW, &lowmempgallocs, 0,
169 "Page allocations done during periods of very low free memory");
170 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgfails, CTLFLAG_RW, &lowmempgfails, 0,
171 "Page allocations which failed during periods of very low free memory");
172 SYSCTL_UINT(_vfs, OID_AUTO, vm_cycle_point, CTLFLAG_RW, &vm_cycle_point, 0,
173 "Recycle pages to active or inactive queue transition pt 0-64");
175 * Sysctls determining current state of the buffer cache.
177 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
178 "Total number of buffers in buffer cache");
179 SYSCTL_LONG(_vfs, OID_AUTO, dirtykvaspace, CTLFLAG_RD, &dirtykvaspace, 0,
180 "KVA reserved by dirty buffers (all)");
181 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
182 "Pending bytes of dirty buffers (all)");
183 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
184 "Pending bytes of dirty buffers (heavy weight)");
185 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
186 "Pending number of dirty buffers");
187 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
188 "Pending number of dirty buffers (heavy weight)");
189 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
190 "I/O bytes currently in progress due to asynchronous writes");
191 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
192 "I/O buffers currently in progress due to asynchronous writes");
193 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
194 "Hard limit on maximum amount of memory usable for buffer space");
195 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
196 "Soft limit on maximum amount of memory usable for buffer space");
197 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
198 "Minimum amount of memory to reserve for system buffer space");
199 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
200 "Amount of memory available for buffers");
201 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
202 0, "Maximum amount of memory reserved for buffers using malloc");
203 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
204 "Amount of memory left for buffers using malloc-scheme");
205 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
206 "New buffer header acquisition requests");
207 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
208 0, "New buffer header acquisition restarts");
209 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
210 "Recover VM space in an emergency");
211 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
212 "Buffer acquisition restarts due to fragmented buffer map");
213 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
214 "Amount of time KVA space was deallocated in an arbitrary buffer");
215 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
216 "Amount of time buffer re-use operations were successful");
217 SYSCTL_INT(_vfs, OID_AUTO, debug_commit, CTLFLAG_RW, &debug_commit, 0, "");
218 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
219 "sizeof(struct buf)");
221 char *buf_wmesg = BUF_WMESG;
223 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
224 #define VFS_BIO_NEED_UNUSED02 0x02
225 #define VFS_BIO_NEED_UNUSED04 0x04
226 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
231 * Called when buffer space is potentially available for recovery.
232 * getnewbuf() will block on this flag when it is unable to free
233 * sufficient buffer space. Buffer space becomes recoverable when
234 * bp's get placed back in the queues.
240 * If someone is waiting for BUF space, wake them up. Even
241 * though we haven't freed the kva space yet, the waiting
242 * process will be able to now.
244 spin_lock(&bufcspin);
245 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
246 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
247 spin_unlock(&bufcspin);
248 wakeup(&needsbuffer);
250 spin_unlock(&bufcspin);
257 * Accounting for I/O in progress.
261 runningbufwakeup(struct buf *bp)
266 if ((totalspace = bp->b_runningbufspace) != 0) {
267 spin_lock(&bufcspin);
268 runningbufspace -= totalspace;
270 bp->b_runningbufspace = 0;
273 * see waitrunningbufspace() for limit test.
275 limit = hirunningspace * 3 / 6;
276 if (runningbufreq && runningbufspace <= limit) {
278 spin_unlock(&bufcspin);
279 wakeup(&runningbufreq);
281 spin_unlock(&bufcspin);
283 bd_signal(totalspace);
290 * Called when a buffer has been added to one of the free queues to
291 * account for the buffer and to wakeup anyone waiting for free buffers.
292 * This typically occurs when large amounts of metadata are being handled
293 * by the buffer cache ( else buffer space runs out first, usually ).
300 spin_lock(&bufcspin);
302 needsbuffer &= ~VFS_BIO_NEED_ANY;
303 spin_unlock(&bufcspin);
304 wakeup(&needsbuffer);
306 spin_unlock(&bufcspin);
311 * waitrunningbufspace()
313 * If runningbufspace exceeds 4/6 hirunningspace we block until
314 * runningbufspace drops to 3/6 hirunningspace. We also block if another
315 * thread blocked here in order to be fair, even if runningbufspace
316 * is now lower than the limit.
318 * The caller may be using this function to block in a tight loop, we
319 * must block while runningbufspace is greater than at least
320 * hirunningspace * 3 / 6.
323 waitrunningbufspace(void)
325 long limit = hirunningspace * 4 / 6;
327 if (runningbufspace > limit || runningbufreq) {
328 spin_lock(&bufcspin);
329 while (runningbufspace > limit || runningbufreq) {
331 ssleep(&runningbufreq, &bufcspin, 0, "wdrn1", 0);
333 spin_unlock(&bufcspin);
338 * buf_dirty_count_severe:
340 * Return true if we have too many dirty buffers.
343 buf_dirty_count_severe(void)
345 return (runningbufspace + dirtykvaspace >= hidirtybufspace ||
346 dirtybufcount >= nbuf / 2);
350 * Return true if the amount of running I/O is severe and BIOQ should
354 buf_runningbufspace_severe(void)
356 return (runningbufspace >= hirunningspace * 4 / 6);
360 * vfs_buf_test_cache:
362 * Called when a buffer is extended. This function clears the B_CACHE
363 * bit if the newly extended portion of the buffer does not contain
366 * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer
367 * cache buffers. The VM pages remain dirty, as someone had mmap()'d
368 * them while a clean buffer was present.
372 vfs_buf_test_cache(struct buf *bp,
373 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
376 if (bp->b_flags & B_CACHE) {
377 int base = (foff + off) & PAGE_MASK;
378 if (vm_page_is_valid(m, base, size) == 0)
379 bp->b_flags &= ~B_CACHE;
386 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
395 if (dirtykvaspace < lodirtybufspace && dirtybufcount < nbuf / 2)
398 if (bd_request == 0 &&
399 (dirtykvaspace > lodirtybufspace / 2 ||
400 dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
401 spin_lock(&bufcspin);
403 spin_unlock(&bufcspin);
406 if (bd_request_hw == 0 &&
407 (dirtykvaspace > lodirtybufspace / 2 ||
408 dirtybufcounthw >= nbuf / 2)) {
409 spin_lock(&bufcspin);
411 spin_unlock(&bufcspin);
412 wakeup(&bd_request_hw);
419 * Get the buf_daemon heated up when the number of running and dirty
420 * buffers exceeds the mid-point.
422 * Return the total number of dirty bytes past the second mid point
423 * as a measure of how much excess dirty data there is in the system.
434 mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
436 totalspace = runningbufspace + dirtykvaspace;
437 if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
439 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
440 if (totalspace >= mid2)
441 return(totalspace - mid2);
449 * Wait for the buffer cache to flush (totalspace) bytes worth of
450 * buffers, then return.
452 * Regardless this function blocks while the number of dirty buffers
453 * exceeds hidirtybufspace.
458 bd_wait(long totalspace)
463 if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
466 while (totalspace > 0) {
468 if (totalspace > runningbufspace + dirtykvaspace)
469 totalspace = runningbufspace + dirtykvaspace;
470 count = totalspace / BKVASIZE;
471 if (count >= BD_WAKE_SIZE)
472 count = BD_WAKE_SIZE - 1;
474 spin_lock(&bufcspin);
475 i = (bd_wake_index + count) & BD_WAKE_MASK;
479 * This is not a strict interlock, so we play a bit loose
480 * with locking access to dirtybufspace*
482 tsleep_interlock(&bd_wake_ary[i], 0);
483 spin_unlock(&bufcspin);
484 tsleep(&bd_wake_ary[i], PINTERLOCKED, "flstik", hz);
486 totalspace = runningbufspace + dirtykvaspace - hidirtybufspace;
493 * This function is called whenever runningbufspace or dirtykvaspace
494 * is reduced. Track threads waiting for run+dirty buffer I/O
500 bd_signal(long totalspace)
504 if (totalspace > 0) {
505 if (totalspace > BKVASIZE * BD_WAKE_SIZE)
506 totalspace = BKVASIZE * BD_WAKE_SIZE;
507 spin_lock(&bufcspin);
508 while (totalspace > 0) {
511 if (bd_wake_ary[i]) {
513 spin_unlock(&bufcspin);
514 wakeup(&bd_wake_ary[i]);
515 spin_lock(&bufcspin);
517 totalspace -= BKVASIZE;
519 spin_unlock(&bufcspin);
524 * BIO tracking support routines.
526 * Release a ref on a bio_track. Wakeup requests are atomically released
527 * along with the last reference so bk_active will never wind up set to
534 bio_track_rel(struct bio_track *track)
542 active = track->bk_active;
543 if (active == 1 && atomic_cmpset_int(&track->bk_active, 1, 0))
547 * Full-on. Note that the wait flag is only atomically released on
548 * the 1->0 count transition.
550 * We check for a negative count transition using bit 30 since bit 31
551 * has a different meaning.
554 desired = (active & 0x7FFFFFFF) - 1;
556 desired |= active & 0x80000000;
557 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
558 if (desired & 0x40000000)
559 panic("bio_track_rel: bad count: %p", track);
560 if (active & 0x80000000)
564 active = track->bk_active;
569 * Wait for the tracking count to reach 0.
571 * Use atomic ops such that the wait flag is only set atomically when
572 * bk_active is non-zero.
577 bio_track_wait(struct bio_track *track, int slp_flags, int slp_timo)
586 if (track->bk_active == 0)
590 * Full-on. Note that the wait flag may only be atomically set if
591 * the active count is non-zero.
593 * NOTE: We cannot optimize active == desired since a wakeup could
594 * clear active prior to our tsleep_interlock().
597 while ((active = track->bk_active) != 0) {
599 desired = active | 0x80000000;
600 tsleep_interlock(track, slp_flags);
601 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
602 error = tsleep(track, slp_flags | PINTERLOCKED,
614 * Load time initialisation of the buffer cache, called from machine
615 * dependant initialization code.
621 vm_offset_t bogus_offset;
624 /* next, make a null set of free lists */
625 for (i = 0; i < BUFFER_QUEUES; i++)
626 TAILQ_INIT(&bufqueues[i]);
628 /* finally, initialize each buffer header and stick on empty q */
629 for (i = 0; i < nbuf; i++) {
631 bzero(bp, sizeof *bp);
632 bp->b_flags = B_INVAL; /* we're just an empty header */
633 bp->b_cmd = BUF_CMD_DONE;
634 bp->b_qindex = BQUEUE_EMPTY;
636 xio_init(&bp->b_xio);
638 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
642 * maxbufspace is the absolute maximum amount of buffer space we are
643 * allowed to reserve in KVM and in real terms. The absolute maximum
644 * is nominally used by buf_daemon. hibufspace is the nominal maximum
645 * used by most other processes. The differential is required to
646 * ensure that buf_daemon is able to run when other processes might
647 * be blocked waiting for buffer space.
649 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
650 * this may result in KVM fragmentation which is not handled optimally
653 maxbufspace = (long)nbuf * BKVASIZE;
654 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
655 lobufspace = hibufspace - MAXBSIZE;
657 lorunningspace = 512 * 1024;
658 /* hirunningspace -- see below */
661 * Limit the amount of malloc memory since it is wired permanently
662 * into the kernel space. Even though this is accounted for in
663 * the buffer allocation, we don't want the malloced region to grow
664 * uncontrolled. The malloc scheme improves memory utilization
665 * significantly on average (small) directories.
667 maxbufmallocspace = hibufspace / 20;
670 * Reduce the chance of a deadlock occuring by limiting the number
671 * of delayed-write dirty buffers we allow to stack up.
673 * We don't want too much actually queued to the device at once
674 * (XXX this needs to be per-mount!), because the buffers will
675 * wind up locked for a very long period of time while the I/O
678 hidirtybufspace = hibufspace / 2; /* dirty + running */
679 hirunningspace = hibufspace / 16; /* locked & queued to device */
680 if (hirunningspace < 1024 * 1024)
681 hirunningspace = 1024 * 1024;
687 lodirtybufspace = hidirtybufspace / 2;
690 * Maximum number of async ops initiated per buf_daemon loop. This is
691 * somewhat of a hack at the moment, we really need to limit ourselves
692 * based on the number of bytes of I/O in-transit that were initiated
696 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
697 vm_object_hold(&kernel_object);
698 bogus_page = vm_page_alloc(&kernel_object,
699 (bogus_offset >> PAGE_SHIFT),
701 vm_object_drop(&kernel_object);
702 vmstats.v_wire_count++;
707 * Initialize the embedded bio structures, typically used by
708 * deprecated code which tries to allocate its own struct bufs.
711 initbufbio(struct buf *bp)
713 bp->b_bio1.bio_buf = bp;
714 bp->b_bio1.bio_prev = NULL;
715 bp->b_bio1.bio_offset = NOOFFSET;
716 bp->b_bio1.bio_next = &bp->b_bio2;
717 bp->b_bio1.bio_done = NULL;
718 bp->b_bio1.bio_flags = 0;
720 bp->b_bio2.bio_buf = bp;
721 bp->b_bio2.bio_prev = &bp->b_bio1;
722 bp->b_bio2.bio_offset = NOOFFSET;
723 bp->b_bio2.bio_next = NULL;
724 bp->b_bio2.bio_done = NULL;
725 bp->b_bio2.bio_flags = 0;
731 * Reinitialize the embedded bio structures as well as any additional
732 * translation cache layers.
735 reinitbufbio(struct buf *bp)
739 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
740 bio->bio_done = NULL;
741 bio->bio_offset = NOOFFSET;
746 * Undo the effects of an initbufbio().
749 uninitbufbio(struct buf *bp)
756 * Push another BIO layer onto an existing BIO and return it. The new
757 * BIO layer may already exist, holding cached translation data.
760 push_bio(struct bio *bio)
764 if ((nbio = bio->bio_next) == NULL) {
765 int index = bio - &bio->bio_buf->b_bio_array[0];
766 if (index >= NBUF_BIO - 1) {
767 panic("push_bio: too many layers bp %p",
770 nbio = &bio->bio_buf->b_bio_array[index + 1];
771 bio->bio_next = nbio;
772 nbio->bio_prev = bio;
773 nbio->bio_buf = bio->bio_buf;
774 nbio->bio_offset = NOOFFSET;
775 nbio->bio_done = NULL;
776 nbio->bio_next = NULL;
778 KKASSERT(nbio->bio_done == NULL);
783 * Pop a BIO translation layer, returning the previous layer. The
784 * must have been previously pushed.
787 pop_bio(struct bio *bio)
789 return(bio->bio_prev);
793 clearbiocache(struct bio *bio)
796 bio->bio_offset = NOOFFSET;
804 * Free the KVA allocation for buffer 'bp'.
806 * Must be called from a critical section as this is the only locking for
809 * Since this call frees up buffer space, we call bufspacewakeup().
814 bfreekva(struct buf *bp)
820 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
821 vm_map_lock(&buffer_map);
822 bufspace -= bp->b_kvasize;
823 vm_map_delete(&buffer_map,
824 (vm_offset_t) bp->b_kvabase,
825 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
828 vm_map_unlock(&buffer_map);
829 vm_map_entry_release(count);
831 bp->b_kvabase = NULL;
839 * Remove the buffer from the appropriate free list.
842 _bremfree(struct buf *bp)
844 if (bp->b_qindex != BQUEUE_NONE) {
845 KASSERT(BUF_REFCNTNB(bp) == 1,
846 ("bremfree: bp %p not locked",bp));
847 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
848 bp->b_qindex = BQUEUE_NONE;
850 if (BUF_REFCNTNB(bp) <= 1)
851 panic("bremfree: removing a buffer not on a queue");
856 bremfree(struct buf *bp)
858 spin_lock(&bufqspin);
860 spin_unlock(&bufqspin);
864 bremfree_locked(struct buf *bp)
870 * This version of bread issues any required I/O asyncnronously and
871 * makes a callback on completion.
873 * The callback must check whether BIO_DONE is set in the bio and issue
874 * the bpdone(bp, 0) if it isn't. The callback is responsible for clearing
875 * BIO_DONE and disposing of the I/O (bqrelse()ing it).
878 breadcb(struct vnode *vp, off_t loffset, int size,
879 void (*func)(struct bio *), void *arg)
883 bp = getblk(vp, loffset, size, 0, 0);
885 /* if not found in cache, do some I/O */
886 if ((bp->b_flags & B_CACHE) == 0) {
887 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
888 bp->b_cmd = BUF_CMD_READ;
889 bp->b_bio1.bio_done = func;
890 bp->b_bio1.bio_caller_info1.ptr = arg;
891 vfs_busy_pages(vp, bp);
893 vn_strategy(vp, &bp->b_bio1);
896 * Since we are issuing the callback synchronously it cannot
897 * race the BIO_DONE, so no need for atomic ops here.
899 /*bp->b_bio1.bio_done = func;*/
900 bp->b_bio1.bio_caller_info1.ptr = arg;
901 bp->b_bio1.bio_flags |= BIO_DONE;
909 * breadnx() - Terminal function for bread() and breadn().
911 * This function will start asynchronous I/O on read-ahead blocks as well
912 * as satisfy the primary request.
914 * We must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE is
915 * set, the buffer is valid and we do not have to do anything.
918 breadnx(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
919 int *rabsize, int cnt, struct buf **bpp)
921 struct buf *bp, *rabp;
923 int rv = 0, readwait = 0;
928 *bpp = bp = getblk(vp, loffset, size, 0, 0);
930 /* if not found in cache, do some I/O */
931 if ((bp->b_flags & B_CACHE) == 0) {
932 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
933 bp->b_cmd = BUF_CMD_READ;
934 bp->b_bio1.bio_done = biodone_sync;
935 bp->b_bio1.bio_flags |= BIO_SYNC;
936 vfs_busy_pages(vp, bp);
937 vn_strategy(vp, &bp->b_bio1);
941 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
942 if (inmem(vp, *raoffset))
944 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
946 if ((rabp->b_flags & B_CACHE) == 0) {
947 rabp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
948 rabp->b_cmd = BUF_CMD_READ;
949 vfs_busy_pages(vp, rabp);
951 vn_strategy(vp, &rabp->b_bio1);
957 rv = biowait(&bp->b_bio1, "biord");
964 * Synchronous write, waits for completion.
966 * Write, release buffer on completion. (Done by iodone
967 * if async). Do not bother writing anything if the buffer
970 * Note that we set B_CACHE here, indicating that buffer is
971 * fully valid and thus cacheable. This is true even of NFS
972 * now so we set it generally. This could be set either here
973 * or in biodone() since the I/O is synchronous. We put it
977 bwrite(struct buf *bp)
981 if (bp->b_flags & B_INVAL) {
985 if (BUF_REFCNTNB(bp) == 0)
986 panic("bwrite: buffer is not busy???");
988 /* Mark the buffer clean */
991 bp->b_flags &= ~(B_ERROR | B_EINTR);
992 bp->b_flags |= B_CACHE;
993 bp->b_cmd = BUF_CMD_WRITE;
994 bp->b_bio1.bio_done = biodone_sync;
995 bp->b_bio1.bio_flags |= BIO_SYNC;
996 vfs_busy_pages(bp->b_vp, bp);
999 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1000 * valid for vnode-backed buffers.
1002 bsetrunningbufspace(bp, bp->b_bufsize);
1003 vn_strategy(bp->b_vp, &bp->b_bio1);
1004 error = biowait(&bp->b_bio1, "biows");
1013 * Asynchronous write. Start output on a buffer, but do not wait for
1014 * it to complete. The buffer is released when the output completes.
1016 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1017 * B_INVAL buffers. Not us.
1020 bawrite(struct buf *bp)
1022 if (bp->b_flags & B_INVAL) {
1026 if (BUF_REFCNTNB(bp) == 0)
1027 panic("bwrite: buffer is not busy???");
1029 /* Mark the buffer clean */
1032 bp->b_flags &= ~(B_ERROR | B_EINTR);
1033 bp->b_flags |= B_CACHE;
1034 bp->b_cmd = BUF_CMD_WRITE;
1035 KKASSERT(bp->b_bio1.bio_done == NULL);
1036 vfs_busy_pages(bp->b_vp, bp);
1039 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1040 * valid for vnode-backed buffers.
1042 bsetrunningbufspace(bp, bp->b_bufsize);
1044 vn_strategy(bp->b_vp, &bp->b_bio1);
1050 * Ordered write. Start output on a buffer, and flag it so that the
1051 * device will write it in the order it was queued. The buffer is
1052 * released when the output completes. bwrite() ( or the VOP routine
1053 * anyway ) is responsible for handling B_INVAL buffers.
1056 bowrite(struct buf *bp)
1058 bp->b_flags |= B_ORDERED;
1066 * Delayed write. (Buffer is marked dirty). Do not bother writing
1067 * anything if the buffer is marked invalid.
1069 * Note that since the buffer must be completely valid, we can safely
1070 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1071 * biodone() in order to prevent getblk from writing the buffer
1072 * out synchronously.
1075 bdwrite(struct buf *bp)
1077 if (BUF_REFCNTNB(bp) == 0)
1078 panic("bdwrite: buffer is not busy");
1080 if (bp->b_flags & B_INVAL) {
1086 if (dsched_is_clear_buf_priv(bp))
1090 * Set B_CACHE, indicating that the buffer is fully valid. This is
1091 * true even of NFS now.
1093 bp->b_flags |= B_CACHE;
1096 * This bmap keeps the system from needing to do the bmap later,
1097 * perhaps when the system is attempting to do a sync. Since it
1098 * is likely that the indirect block -- or whatever other datastructure
1099 * that the filesystem needs is still in memory now, it is a good
1100 * thing to do this. Note also, that if the pageout daemon is
1101 * requesting a sync -- there might not be enough memory to do
1102 * the bmap then... So, this is important to do.
1104 if (bp->b_bio2.bio_offset == NOOFFSET) {
1105 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
1106 NULL, NULL, BUF_CMD_WRITE);
1110 * Because the underlying pages may still be mapped and
1111 * writable trying to set the dirty buffer (b_dirtyoff/end)
1112 * range here will be inaccurate.
1114 * However, we must still clean the pages to satisfy the
1115 * vnode_pager and pageout daemon, so theythink the pages
1116 * have been "cleaned". What has really occured is that
1117 * they've been earmarked for later writing by the buffer
1120 * So we get the b_dirtyoff/end update but will not actually
1121 * depend on it (NFS that is) until the pages are busied for
1124 vfs_clean_pages(bp);
1128 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1129 * due to the softdep code.
1134 * Fake write - return pages to VM system as dirty, leave the buffer clean.
1135 * This is used by tmpfs.
1137 * It is important for any VFS using this routine to NOT use it for
1138 * IO_SYNC or IO_ASYNC operations which occur when the system really
1139 * wants to flush VM pages to backing store.
1142 buwrite(struct buf *bp)
1148 * Only works for VMIO buffers. If the buffer is already
1149 * marked for delayed-write we can't avoid the bdwrite().
1151 if ((bp->b_flags & B_VMIO) == 0 || (bp->b_flags & B_DELWRI)) {
1157 * Mark as needing a commit.
1159 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1160 m = bp->b_xio.xio_pages[i];
1161 vm_page_need_commit(m);
1169 * Turn buffer into delayed write request by marking it B_DELWRI.
1170 * B_RELBUF and B_NOCACHE must be cleared.
1172 * We reassign the buffer to itself to properly update it in the
1173 * dirty/clean lists.
1175 * Must be called from a critical section.
1176 * The buffer must be on BQUEUE_NONE.
1179 bdirty(struct buf *bp)
1181 KASSERT(bp->b_qindex == BQUEUE_NONE,
1182 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1183 if (bp->b_flags & B_NOCACHE) {
1184 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
1185 bp->b_flags &= ~B_NOCACHE;
1187 if (bp->b_flags & B_INVAL) {
1188 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
1190 bp->b_flags &= ~B_RELBUF;
1192 if ((bp->b_flags & B_DELWRI) == 0) {
1193 lwkt_gettoken(&bp->b_vp->v_token);
1194 bp->b_flags |= B_DELWRI;
1196 lwkt_reltoken(&bp->b_vp->v_token);
1198 spin_lock(&bufcspin);
1200 dirtykvaspace += bp->b_kvasize;
1201 dirtybufspace += bp->b_bufsize;
1202 if (bp->b_flags & B_HEAVY) {
1204 dirtybufspacehw += bp->b_bufsize;
1206 spin_unlock(&bufcspin);
1213 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
1214 * needs to be flushed with a different buf_daemon thread to avoid
1215 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
1218 bheavy(struct buf *bp)
1220 if ((bp->b_flags & B_HEAVY) == 0) {
1221 bp->b_flags |= B_HEAVY;
1222 if (bp->b_flags & B_DELWRI) {
1223 spin_lock(&bufcspin);
1225 dirtybufspacehw += bp->b_bufsize;
1226 spin_unlock(&bufcspin);
1234 * Clear B_DELWRI for buffer.
1236 * Must be called from a critical section.
1238 * The buffer is typically on BQUEUE_NONE but there is one case in
1239 * brelse() that calls this function after placing the buffer on
1240 * a different queue.
1245 bundirty(struct buf *bp)
1247 if (bp->b_flags & B_DELWRI) {
1248 lwkt_gettoken(&bp->b_vp->v_token);
1249 bp->b_flags &= ~B_DELWRI;
1251 lwkt_reltoken(&bp->b_vp->v_token);
1253 spin_lock(&bufcspin);
1255 dirtykvaspace -= bp->b_kvasize;
1256 dirtybufspace -= bp->b_bufsize;
1257 if (bp->b_flags & B_HEAVY) {
1259 dirtybufspacehw -= bp->b_bufsize;
1261 spin_unlock(&bufcspin);
1263 bd_signal(bp->b_bufsize);
1266 * Since it is now being written, we can clear its deferred write flag.
1268 bp->b_flags &= ~B_DEFERRED;
1272 * Set the b_runningbufspace field, used to track how much I/O is
1273 * in progress at any given moment.
1276 bsetrunningbufspace(struct buf *bp, int bytes)
1278 bp->b_runningbufspace = bytes;
1280 spin_lock(&bufcspin);
1281 runningbufspace += bytes;
1283 spin_unlock(&bufcspin);
1290 * Release a busy buffer and, if requested, free its resources. The
1291 * buffer will be stashed in the appropriate bufqueue[] allowing it
1292 * to be accessed later as a cache entity or reused for other purposes.
1297 brelse(struct buf *bp)
1300 int saved_flags = bp->b_flags;
1303 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1306 * If B_NOCACHE is set we are being asked to destroy the buffer and
1307 * its backing store. Clear B_DELWRI.
1309 * B_NOCACHE is set in two cases: (1) when the caller really wants
1310 * to destroy the buffer and backing store and (2) when the caller
1311 * wants to destroy the buffer and backing store after a write
1314 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1318 if ((bp->b_flags & (B_INVAL | B_DELWRI)) == B_DELWRI) {
1320 * A re-dirtied buffer is only subject to destruction
1321 * by B_INVAL. B_ERROR and B_NOCACHE are ignored.
1323 /* leave buffer intact */
1324 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1325 (bp->b_bufsize <= 0)) {
1327 * Either a failed read or we were asked to free or not
1328 * cache the buffer. This path is reached with B_DELWRI
1329 * set only if B_INVAL is already set. B_NOCACHE governs
1330 * backing store destruction.
1332 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1333 * buffer cannot be immediately freed.
1335 bp->b_flags |= B_INVAL;
1336 if (LIST_FIRST(&bp->b_dep) != NULL)
1338 if (bp->b_flags & B_DELWRI) {
1339 spin_lock(&bufcspin);
1341 dirtykvaspace -= bp->b_kvasize;
1342 dirtybufspace -= bp->b_bufsize;
1343 if (bp->b_flags & B_HEAVY) {
1345 dirtybufspacehw -= bp->b_bufsize;
1347 spin_unlock(&bufcspin);
1349 bd_signal(bp->b_bufsize);
1351 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1355 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set,
1356 * or if b_refs is non-zero.
1358 * If vfs_vmio_release() is called with either bit set, the
1359 * underlying pages may wind up getting freed causing a previous
1360 * write (bdwrite()) to get 'lost' because pages associated with
1361 * a B_DELWRI bp are marked clean. Pages associated with a
1362 * B_LOCKED buffer may be mapped by the filesystem.
1364 * If we want to release the buffer ourselves (rather then the
1365 * originator asking us to release it), give the originator a
1366 * chance to countermand the release by setting B_LOCKED.
1368 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1369 * if B_DELWRI is set.
1371 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1372 * on pages to return pages to the VM page queues.
1374 if ((bp->b_flags & (B_DELWRI | B_LOCKED)) || bp->b_refs) {
1375 bp->b_flags &= ~B_RELBUF;
1376 } else if (vm_page_count_min(0)) {
1377 if (LIST_FIRST(&bp->b_dep) != NULL)
1378 buf_deallocate(bp); /* can set B_LOCKED */
1379 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1380 bp->b_flags &= ~B_RELBUF;
1382 bp->b_flags |= B_RELBUF;
1386 * Make sure b_cmd is clear. It may have already been cleared by
1389 * At this point destroying the buffer is governed by the B_INVAL
1390 * or B_RELBUF flags.
1392 bp->b_cmd = BUF_CMD_DONE;
1393 dsched_exit_buf(bp);
1396 * VMIO buffer rundown. Make sure the VM page array is restored
1397 * after an I/O may have replaces some of the pages with bogus pages
1398 * in order to not destroy dirty pages in a fill-in read.
1400 * Note that due to the code above, if a buffer is marked B_DELWRI
1401 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1402 * B_INVAL may still be set, however.
1404 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1405 * but not the backing store. B_NOCACHE will destroy the backing
1408 * Note that dirty NFS buffers contain byte-granular write ranges
1409 * and should not be destroyed w/ B_INVAL even if the backing store
1412 if (bp->b_flags & B_VMIO) {
1414 * Rundown for VMIO buffers which are not dirty NFS buffers.
1426 * Get the base offset and length of the buffer. Note that
1427 * in the VMIO case if the buffer block size is not
1428 * page-aligned then b_data pointer may not be page-aligned.
1429 * But our b_xio.xio_pages array *IS* page aligned.
1431 * block sizes less then DEV_BSIZE (usually 512) are not
1432 * supported due to the page granularity bits (m->valid,
1433 * m->dirty, etc...).
1435 * See man buf(9) for more information
1438 resid = bp->b_bufsize;
1439 foff = bp->b_loffset;
1441 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1442 m = bp->b_xio.xio_pages[i];
1443 vm_page_flag_clear(m, PG_ZERO);
1445 * If we hit a bogus page, fixup *all* of them
1446 * now. Note that we left these pages wired
1447 * when we removed them so they had better exist,
1448 * and they cannot be ripped out from under us so
1449 * no critical section protection is necessary.
1451 if (m == bogus_page) {
1453 poff = OFF_TO_IDX(bp->b_loffset);
1455 vm_object_hold(obj);
1456 for (j = i; j < bp->b_xio.xio_npages; j++) {
1459 mtmp = bp->b_xio.xio_pages[j];
1460 if (mtmp == bogus_page) {
1461 mtmp = vm_page_lookup(obj, poff + j);
1463 panic("brelse: page missing");
1465 bp->b_xio.xio_pages[j] = mtmp;
1468 bp->b_flags &= ~B_HASBOGUS;
1469 vm_object_drop(obj);
1471 if ((bp->b_flags & B_INVAL) == 0) {
1472 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1473 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1475 m = bp->b_xio.xio_pages[i];
1479 * Invalidate the backing store if B_NOCACHE is set
1480 * (e.g. used with vinvalbuf()). If this is NFS
1481 * we impose a requirement that the block size be
1482 * a multiple of PAGE_SIZE and create a temporary
1483 * hack to basically invalidate the whole page. The
1484 * problem is that NFS uses really odd buffer sizes
1485 * especially when tracking piecemeal writes and
1486 * it also vinvalbuf()'s a lot, which would result
1487 * in only partial page validation and invalidation
1488 * here. If the file page is mmap()'d, however,
1489 * all the valid bits get set so after we invalidate
1490 * here we would end up with weird m->valid values
1491 * like 0xfc. nfs_getpages() can't handle this so
1492 * we clear all the valid bits for the NFS case
1493 * instead of just some of them.
1495 * The real bug is the VM system having to set m->valid
1496 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1497 * itself is an artifact of the whole 512-byte
1498 * granular mess that exists to support odd block
1499 * sizes and UFS meta-data block sizes (e.g. 6144).
1500 * A complete rewrite is required.
1504 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1505 int poffset = foff & PAGE_MASK;
1508 presid = PAGE_SIZE - poffset;
1509 if (bp->b_vp->v_tag == VT_NFS &&
1510 bp->b_vp->v_type == VREG) {
1512 } else if (presid > resid) {
1515 KASSERT(presid >= 0, ("brelse: extra page"));
1516 vm_page_set_invalid(m, poffset, presid);
1519 * Also make sure any swap cache is removed
1520 * as it is now stale (HAMMER in particular
1521 * uses B_NOCACHE to deal with buffer
1524 swap_pager_unswapped(m);
1526 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1527 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1529 if (bp->b_flags & (B_INVAL | B_RELBUF))
1530 vfs_vmio_release(bp);
1533 * Rundown for non-VMIO buffers.
1535 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1538 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1544 if (bp->b_qindex != BQUEUE_NONE)
1545 panic("brelse: free buffer onto another queue???");
1546 if (BUF_REFCNTNB(bp) > 1) {
1547 /* Temporary panic to verify exclusive locking */
1548 /* This panic goes away when we allow shared refs */
1549 panic("brelse: multiple refs");
1555 * Figure out the correct queue to place the cleaned up buffer on.
1556 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1557 * disassociated from their vnode.
1559 spin_lock(&bufqspin);
1560 if (bp->b_flags & B_LOCKED) {
1562 * Buffers that are locked are placed in the locked queue
1563 * immediately, regardless of their state.
1565 bp->b_qindex = BQUEUE_LOCKED;
1566 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1567 } else if (bp->b_bufsize == 0) {
1569 * Buffers with no memory. Due to conditionals near the top
1570 * of brelse() such buffers should probably already be
1571 * marked B_INVAL and disassociated from their vnode.
1573 bp->b_flags |= B_INVAL;
1574 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1575 KKASSERT((bp->b_flags & B_HASHED) == 0);
1576 if (bp->b_kvasize) {
1577 bp->b_qindex = BQUEUE_EMPTYKVA;
1579 bp->b_qindex = BQUEUE_EMPTY;
1581 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1582 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) {
1584 * Buffers with junk contents. Again these buffers had better
1585 * already be disassociated from their vnode.
1587 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1588 KKASSERT((bp->b_flags & B_HASHED) == 0);
1589 bp->b_flags |= B_INVAL;
1590 bp->b_qindex = BQUEUE_CLEAN;
1591 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1594 * Remaining buffers. These buffers are still associated with
1597 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1599 bp->b_qindex = BQUEUE_DIRTY;
1600 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1602 case B_DELWRI | B_HEAVY:
1603 bp->b_qindex = BQUEUE_DIRTY_HW;
1604 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1609 * NOTE: Buffers are always placed at the end of the
1610 * queue. If B_AGE is not set the buffer will cycle
1611 * through the queue twice.
1613 bp->b_qindex = BQUEUE_CLEAN;
1614 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1618 spin_unlock(&bufqspin);
1621 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1622 * on the correct queue.
1624 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1628 * The bp is on an appropriate queue unless locked. If it is not
1629 * locked or dirty we can wakeup threads waiting for buffer space.
1631 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1632 * if B_INVAL is set ).
1634 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1638 * Something we can maybe free or reuse
1640 if (bp->b_bufsize || bp->b_kvasize)
1644 * Clean up temporary flags and unlock the buffer.
1646 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF | B_DIRECT);
1653 * Release a buffer back to the appropriate queue but do not try to free
1654 * it. The buffer is expected to be used again soon.
1656 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1657 * biodone() to requeue an async I/O on completion. It is also used when
1658 * known good buffers need to be requeued but we think we may need the data
1661 * XXX we should be able to leave the B_RELBUF hint set on completion.
1666 bqrelse(struct buf *bp)
1668 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1670 if (bp->b_qindex != BQUEUE_NONE)
1671 panic("bqrelse: free buffer onto another queue???");
1672 if (BUF_REFCNTNB(bp) > 1) {
1673 /* do not release to free list */
1674 panic("bqrelse: multiple refs");
1678 buf_act_advance(bp);
1680 spin_lock(&bufqspin);
1681 if (bp->b_flags & B_LOCKED) {
1683 * Locked buffers are released to the locked queue. However,
1684 * if the buffer is dirty it will first go into the dirty
1685 * queue and later on after the I/O completes successfully it
1686 * will be released to the locked queue.
1688 bp->b_qindex = BQUEUE_LOCKED;
1689 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1690 } else if (bp->b_flags & B_DELWRI) {
1691 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1692 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1693 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1694 } else if (vm_page_count_min(0)) {
1696 * We are too low on memory, we have to try to free the
1697 * buffer (most importantly: the wired pages making up its
1698 * backing store) *now*.
1700 spin_unlock(&bufqspin);
1704 bp->b_qindex = BQUEUE_CLEAN;
1705 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1707 spin_unlock(&bufqspin);
1709 if ((bp->b_flags & B_LOCKED) == 0 &&
1710 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1715 * Something we can maybe free or reuse.
1717 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1721 * Final cleanup and unlock. Clear bits that are only used while a
1722 * buffer is actively locked.
1724 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF);
1725 dsched_exit_buf(bp);
1730 * Hold a buffer, preventing it from being reused. This will prevent
1731 * normal B_RELBUF operations on the buffer but will not prevent B_INVAL
1732 * operations. If a B_INVAL operation occurs the buffer will remain held
1733 * but the underlying pages may get ripped out.
1735 * These functions are typically used in VOP_READ/VOP_WRITE functions
1736 * to hold a buffer during a copyin or copyout, preventing deadlocks
1737 * or recursive lock panics when read()/write() is used over mmap()'d
1740 * NOTE: bqhold() requires that the buffer be locked at the time of the
1741 * hold. bqdrop() has no requirements other than the buffer having
1742 * previously been held.
1745 bqhold(struct buf *bp)
1747 atomic_add_int(&bp->b_refs, 1);
1751 bqdrop(struct buf *bp)
1753 KKASSERT(bp->b_refs > 0);
1754 atomic_add_int(&bp->b_refs, -1);
1758 * Return backing pages held by the buffer 'bp' back to the VM system.
1759 * This routine is called when the bp is invalidated, released, or
1762 * The KVA mapping (b_data) for the underlying pages is removed by
1765 * WARNING! This routine is integral to the low memory critical path
1766 * when a buffer is B_RELBUF'd. If the system has a severe page
1767 * deficit we need to get the page(s) onto the PQ_FREE or PQ_CACHE
1768 * queues so they can be reused in the current pageout daemon
1772 vfs_vmio_release(struct buf *bp)
1777 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1778 m = bp->b_xio.xio_pages[i];
1779 bp->b_xio.xio_pages[i] = NULL;
1782 * We need to own the page in order to safely unwire it.
1784 vm_page_busy_wait(m, FALSE, "vmiopg");
1787 * The VFS is telling us this is not a meta-data buffer
1788 * even if it is backed by a block device.
1790 if (bp->b_flags & B_NOTMETA)
1791 vm_page_flag_set(m, PG_NOTMETA);
1794 * This is a very important bit of code. We try to track
1795 * VM page use whether the pages are wired into the buffer
1796 * cache or not. While wired into the buffer cache the
1797 * bp tracks the act_count.
1799 * We can choose to place unwired pages on the inactive
1800 * queue (0) or active queue (1). If we place too many
1801 * on the active queue the queue will cycle the act_count
1802 * on pages we'd like to keep, just from single-use pages
1803 * (such as when doing a tar-up or file scan).
1805 if (bp->b_act_count < vm_cycle_point)
1806 vm_page_unwire(m, 0);
1808 vm_page_unwire(m, 1);
1811 * If the wire_count has dropped to 0 we may need to take
1812 * further action before unbusying the page.
1814 * WARNING: vm_page_try_*() also checks PG_NEED_COMMIT for us.
1816 if (m->wire_count == 0) {
1817 vm_page_flag_clear(m, PG_ZERO);
1819 if (bp->b_flags & B_DIRECT) {
1821 * Attempt to free the page if B_DIRECT is
1822 * set, the caller does not desire the page
1826 vm_page_try_to_free(m);
1827 } else if ((bp->b_flags & B_NOTMETA) ||
1828 vm_page_count_min(0)) {
1830 * Attempt to move the page to PQ_CACHE
1831 * if B_NOTMETA is set. This flag is set
1832 * by HAMMER to remove one of the two pages
1833 * present when double buffering is enabled.
1835 * Attempt to move the page to PQ_CACHE
1836 * If we have a severe page deficit. This
1837 * will cause buffer cache operations related
1838 * to pageouts to recycle the related pages
1839 * in order to avoid a low memory deadlock.
1841 m->act_count = bp->b_act_count;
1843 vm_page_try_to_cache(m);
1846 * Nominal case, leave the page on the
1847 * queue the original unwiring placed it on
1848 * (active or inactive).
1850 m->act_count = bp->b_act_count;
1858 pmap_qremove(trunc_page((vm_offset_t) bp->b_data),
1859 bp->b_xio.xio_npages);
1860 if (bp->b_bufsize) {
1864 bp->b_xio.xio_npages = 0;
1865 bp->b_flags &= ~B_VMIO;
1866 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1874 * Find and initialize a new buffer header, freeing up existing buffers
1875 * in the bufqueues as necessary. The new buffer is returned locked.
1877 * Important: B_INVAL is not set. If the caller wishes to throw the
1878 * buffer away, the caller must set B_INVAL prior to calling brelse().
1881 * We have insufficient buffer headers
1882 * We have insufficient buffer space
1883 * buffer_map is too fragmented ( space reservation fails )
1884 * If we have to flush dirty buffers ( but we try to avoid this )
1886 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1887 * Instead we ask the buf daemon to do it for us. We attempt to
1888 * avoid piecemeal wakeups of the pageout daemon.
1893 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1899 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1900 static int flushingbufs;
1903 * We can't afford to block since we might be holding a vnode lock,
1904 * which may prevent system daemons from running. We deal with
1905 * low-memory situations by proactively returning memory and running
1906 * async I/O rather then sync I/O.
1910 --getnewbufrestarts;
1912 ++getnewbufrestarts;
1915 * Setup for scan. If we do not have enough free buffers,
1916 * we setup a degenerate case that immediately fails. Note
1917 * that if we are specially marked process, we are allowed to
1918 * dip into our reserves.
1920 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1922 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1923 * However, there are a number of cases (defragging, reusing, ...)
1924 * where we cannot backup.
1926 nqindex = BQUEUE_EMPTYKVA;
1927 spin_lock(&bufqspin);
1928 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1932 * If no EMPTYKVA buffers and we are either
1933 * defragging or reusing, locate a CLEAN buffer
1934 * to free or reuse. If bufspace useage is low
1935 * skip this step so we can allocate a new buffer.
1937 if (defrag || bufspace >= lobufspace) {
1938 nqindex = BQUEUE_CLEAN;
1939 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1943 * If we could not find or were not allowed to reuse a
1944 * CLEAN buffer, check to see if it is ok to use an EMPTY
1945 * buffer. We can only use an EMPTY buffer if allocating
1946 * its KVA would not otherwise run us out of buffer space.
1948 if (nbp == NULL && defrag == 0 &&
1949 bufspace + maxsize < hibufspace) {
1950 nqindex = BQUEUE_EMPTY;
1951 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1956 * Run scan, possibly freeing data and/or kva mappings on the fly
1959 * WARNING! bufqspin is held!
1961 while ((bp = nbp) != NULL) {
1962 int qindex = nqindex;
1964 nbp = TAILQ_NEXT(bp, b_freelist);
1967 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
1968 * cycles through the queue twice before being selected.
1970 if (qindex == BQUEUE_CLEAN &&
1971 (bp->b_flags & B_AGE) == 0 && nbp) {
1972 bp->b_flags |= B_AGE;
1973 TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
1974 TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
1979 * Calculate next bp ( we can only use it if we do not block
1980 * or do other fancy things ).
1985 nqindex = BQUEUE_EMPTYKVA;
1986 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1989 case BQUEUE_EMPTYKVA:
1990 nqindex = BQUEUE_CLEAN;
1991 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
2005 KASSERT(bp->b_qindex == qindex,
2006 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2009 * Note: we no longer distinguish between VMIO and non-VMIO
2012 KASSERT((bp->b_flags & B_DELWRI) == 0,
2013 ("delwri buffer %p found in queue %d", bp, qindex));
2016 * Do not try to reuse a buffer with a non-zero b_refs.
2017 * This is an unsynchronized test. A synchronized test
2018 * is also performed after we lock the buffer.
2024 * If we are defragging then we need a buffer with
2025 * b_kvasize != 0. XXX this situation should no longer
2026 * occur, if defrag is non-zero the buffer's b_kvasize
2027 * should also be non-zero at this point. XXX
2029 if (defrag && bp->b_kvasize == 0) {
2030 kprintf("Warning: defrag empty buffer %p\n", bp);
2035 * Start freeing the bp. This is somewhat involved. nbp
2036 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
2037 * on the clean list must be disassociated from their
2038 * current vnode. Buffers on the empty[kva] lists have
2039 * already been disassociated.
2041 * b_refs is checked after locking along with queue changes.
2042 * We must check here to deal with zero->nonzero transitions
2043 * made by the owner of the buffer lock, which is used by
2044 * VFS's to hold the buffer while issuing an unlocked
2045 * uiomove()s. We cannot invalidate the buffer's pages
2046 * for this case. Once we successfully lock a buffer the
2047 * only 0->1 transitions of b_refs will occur via findblk().
2049 * We must also check for queue changes after successful
2050 * locking as the current lock holder may dispose of the
2051 * buffer and change its queue.
2053 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2054 spin_unlock(&bufqspin);
2055 tsleep(&bd_request, 0, "gnbxxx", (hz + 99) / 100);
2058 if (bp->b_qindex != qindex || bp->b_refs) {
2059 spin_unlock(&bufqspin);
2063 bremfree_locked(bp);
2064 spin_unlock(&bufqspin);
2067 * Dependancies must be handled before we disassociate the
2070 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2071 * be immediately disassociated. HAMMER then becomes
2072 * responsible for releasing the buffer.
2074 * NOTE: bufqspin is UNLOCKED now.
2076 if (LIST_FIRST(&bp->b_dep) != NULL) {
2078 if (bp->b_flags & B_LOCKED) {
2082 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2085 if (qindex == BQUEUE_CLEAN) {
2086 if (bp->b_flags & B_VMIO)
2087 vfs_vmio_release(bp);
2093 * NOTE: nbp is now entirely invalid. We can only restart
2094 * the scan from this point on.
2096 * Get the rest of the buffer freed up. b_kva* is still
2097 * valid after this operation.
2099 KASSERT(bp->b_vp == NULL,
2100 ("bp3 %p flags %08x vnode %p qindex %d "
2101 "unexpectededly still associated!",
2102 bp, bp->b_flags, bp->b_vp, qindex));
2103 KKASSERT((bp->b_flags & B_HASHED) == 0);
2106 * critical section protection is not required when
2107 * scrapping a buffer's contents because it is already
2113 bp->b_flags = B_BNOCLIP;
2114 bp->b_cmd = BUF_CMD_DONE;
2119 bp->b_xio.xio_npages = 0;
2120 bp->b_dirtyoff = bp->b_dirtyend = 0;
2121 bp->b_act_count = ACT_INIT;
2123 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2125 if (blkflags & GETBLK_BHEAVY)
2126 bp->b_flags |= B_HEAVY;
2129 * If we are defragging then free the buffer.
2132 bp->b_flags |= B_INVAL;
2140 * If we are overcomitted then recover the buffer and its
2141 * KVM space. This occurs in rare situations when multiple
2142 * processes are blocked in getnewbuf() or allocbuf().
2144 if (bufspace >= hibufspace)
2146 if (flushingbufs && bp->b_kvasize != 0) {
2147 bp->b_flags |= B_INVAL;
2152 if (bufspace < lobufspace)
2156 * b_refs can transition to a non-zero value while we hold
2157 * the buffer locked due to a findblk(). Our brelvp() above
2158 * interlocked any future possible transitions due to
2161 * If we find b_refs to be non-zero we can destroy the
2162 * buffer's contents but we cannot yet reuse the buffer.
2165 bp->b_flags |= B_INVAL;
2171 /* NOT REACHED, bufqspin not held */
2175 * If we exhausted our list, sleep as appropriate. We may have to
2176 * wakeup various daemons and write out some dirty buffers.
2178 * Generally we are sleeping due to insufficient buffer space.
2180 * NOTE: bufqspin is held if bp is NULL, else it is not held.
2186 spin_unlock(&bufqspin);
2188 flags = VFS_BIO_NEED_BUFSPACE;
2190 } else if (bufspace >= hibufspace) {
2192 flags = VFS_BIO_NEED_BUFSPACE;
2195 flags = VFS_BIO_NEED_ANY;
2198 bd_speedup(); /* heeeelp */
2199 spin_lock(&bufcspin);
2200 needsbuffer |= flags;
2201 while (needsbuffer & flags) {
2202 if (ssleep(&needsbuffer, &bufcspin,
2203 slpflags, waitmsg, slptimeo)) {
2204 spin_unlock(&bufcspin);
2208 spin_unlock(&bufcspin);
2211 * We finally have a valid bp. We aren't quite out of the
2212 * woods, we still have to reserve kva space. In order
2213 * to keep fragmentation sane we only allocate kva in
2216 * (bufqspin is not held)
2218 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2220 if (maxsize != bp->b_kvasize) {
2221 vm_offset_t addr = 0;
2226 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2227 vm_map_lock(&buffer_map);
2229 if (vm_map_findspace(&buffer_map,
2230 vm_map_min(&buffer_map), maxsize,
2231 maxsize, 0, &addr)) {
2233 * Uh oh. Buffer map is too fragmented. We
2234 * must defragment the map.
2236 vm_map_unlock(&buffer_map);
2237 vm_map_entry_release(count);
2240 bp->b_flags |= B_INVAL;
2245 vm_map_insert(&buffer_map, &count,
2247 addr, addr + maxsize,
2249 VM_PROT_ALL, VM_PROT_ALL,
2252 bp->b_kvabase = (caddr_t) addr;
2253 bp->b_kvasize = maxsize;
2254 bufspace += bp->b_kvasize;
2257 vm_map_unlock(&buffer_map);
2258 vm_map_entry_release(count);
2260 bp->b_data = bp->b_kvabase;
2267 * This routine is called in an emergency to recover VM pages from the
2268 * buffer cache by cashing in clean buffers. The idea is to recover
2269 * enough pages to be able to satisfy a stuck bio_page_alloc().
2271 * XXX Currently not implemented. This function can wind up deadlocking
2272 * against another thread holding one or more of the backing pages busy.
2275 recoverbufpages(void)
2282 spin_lock(&bufqspin);
2283 while (bytes < MAXBSIZE) {
2284 bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
2289 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
2290 * cycles through the queue twice before being selected.
2292 if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) {
2293 bp->b_flags |= B_AGE;
2294 TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
2295 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN],
2303 KKASSERT(bp->b_qindex == BQUEUE_CLEAN);
2304 KKASSERT((bp->b_flags & B_DELWRI) == 0);
2307 * Start freeing the bp. This is somewhat involved.
2309 * Buffers on the clean list must be disassociated from
2310 * their current vnode
2313 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2314 kprintf("recoverbufpages: warning, locked buf %p, "
2317 ssleep(&bd_request, &bufqspin, 0, "gnbxxx", hz / 100);
2320 if (bp->b_qindex != BQUEUE_CLEAN) {
2321 kprintf("recoverbufpages: warning, BUF_LOCK blocked "
2322 "unexpectedly on buf %p index %d, race "
2328 bremfree_locked(bp);
2329 spin_unlock(&bufqspin);
2332 * Sanity check. Only BQUEUE_DIRTY[_HW] employs markers.
2334 KKASSERT((bp->b_flags & B_MARKER) == 0);
2337 * Dependancies must be handled before we disassociate the
2340 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2341 * be immediately disassociated. HAMMER then becomes
2342 * responsible for releasing the buffer.
2344 if (LIST_FIRST(&bp->b_dep) != NULL) {
2346 if (bp->b_flags & B_LOCKED) {
2348 spin_lock(&bufqspin);
2351 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2354 bytes += bp->b_bufsize;
2356 if (bp->b_flags & B_VMIO) {
2357 bp->b_flags |= B_DIRECT; /* try to free pages */
2358 vfs_vmio_release(bp);
2363 KKASSERT(bp->b_vp == NULL);
2364 KKASSERT((bp->b_flags & B_HASHED) == 0);
2367 * critical section protection is not required when
2368 * scrapping a buffer's contents because it is already
2374 bp->b_flags = B_BNOCLIP;
2375 bp->b_cmd = BUF_CMD_DONE;
2380 bp->b_xio.xio_npages = 0;
2381 bp->b_dirtyoff = bp->b_dirtyend = 0;
2383 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2385 bp->b_flags |= B_INVAL;
2388 spin_lock(&bufqspin);
2390 spin_unlock(&bufqspin);
2398 * Buffer flushing daemon. Buffers are normally flushed by the
2399 * update daemon but if it cannot keep up this process starts to
2400 * take the load in an attempt to prevent getnewbuf() from blocking.
2402 * Once a flush is initiated it does not stop until the number
2403 * of buffers falls below lodirtybuffers, but we will wake up anyone
2404 * waiting at the mid-point.
2406 static struct kproc_desc buf_kp = {
2411 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2412 kproc_start, &buf_kp)
2414 static struct kproc_desc bufhw_kp = {
2419 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2420 kproc_start, &bufhw_kp)
2426 buf_daemon1(struct thread *td, int queue, int (*buf_limit_fn)(long),
2432 marker = kmalloc(sizeof(*marker), M_BIOBUF, M_WAITOK | M_ZERO);
2433 marker->b_flags |= B_MARKER;
2434 marker->b_qindex = BQUEUE_NONE;
2437 * This process needs to be suspended prior to shutdown sync.
2439 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2440 td, SHUTDOWN_PRI_LAST);
2441 curthread->td_flags |= TDF_SYSTHREAD;
2444 * This process is allowed to take the buffer cache to the limit
2447 kproc_suspend_loop();
2450 * Do the flush as long as the number of dirty buffers
2451 * (including those running) exceeds lodirtybufspace.
2453 * When flushing limit running I/O to hirunningspace
2454 * Do the flush. Limit the amount of in-transit I/O we
2455 * allow to build up, otherwise we would completely saturate
2456 * the I/O system. Wakeup any waiting processes before we
2457 * normally would so they can run in parallel with our drain.
2459 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2460 * but because we split the operation into two threads we
2461 * have to cut it in half for each thread.
2463 waitrunningbufspace();
2464 limit = lodirtybufspace / 2;
2465 while (buf_limit_fn(limit)) {
2466 if (flushbufqueues(marker, queue) == 0)
2468 if (runningbufspace < hirunningspace)
2470 waitrunningbufspace();
2474 * We reached our low water mark, reset the
2475 * request and sleep until we are needed again.
2476 * The sleep is just so the suspend code works.
2478 spin_lock(&bufcspin);
2480 ssleep(bd_req, &bufcspin, 0, "psleep", hz);
2482 spin_unlock(&bufcspin);
2485 /*kfree(marker, M_BIOBUF);*/
2489 buf_daemon_limit(long limit)
2491 return (runningbufspace + dirtykvaspace > limit ||
2492 dirtybufcount - dirtybufcounthw >= nbuf / 2);
2496 buf_daemon_hw_limit(long limit)
2498 return (runningbufspace + dirtykvaspace > limit ||
2499 dirtybufcounthw >= nbuf / 2);
2505 buf_daemon1(bufdaemon_td, BQUEUE_DIRTY, buf_daemon_limit,
2512 buf_daemon1(bufdaemonhw_td, BQUEUE_DIRTY_HW, buf_daemon_hw_limit,
2519 * Try to flush a buffer in the dirty queue. We must be careful to
2520 * free up B_INVAL buffers instead of write them, which NFS is
2521 * particularly sensitive to.
2523 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate
2524 * that we really want to try to get the buffer out and reuse it
2525 * due to the write load on the machine.
2527 * We must lock the buffer in order to check its validity before we
2528 * can mess with its contents. bufqspin isn't enough.
2531 flushbufqueues(struct buf *marker, bufq_type_t q)
2536 KKASSERT(marker->b_qindex == BQUEUE_NONE);
2537 KKASSERT(marker->b_flags & B_MARKER);
2540 * Spinlock needed to perform operations on the queue and may be
2541 * held through a non-blocking BUF_LOCK(), but cannot be held when
2542 * BUF_UNLOCK()ing or through any other major operation.
2544 spin_lock(&bufqspin);
2545 marker->b_qindex = q;
2546 TAILQ_INSERT_HEAD(&bufqueues[q], marker, b_freelist);
2549 while ((bp = TAILQ_NEXT(bp, b_freelist)) != NULL) {
2551 * NOTE: spinlock is always held at the top of the loop
2553 if (bp->b_flags & B_MARKER)
2555 if ((bp->b_flags & B_DELWRI) == 0) {
2556 kprintf("Unexpected clean buffer %p\n", bp);
2559 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
2561 KKASSERT(bp->b_qindex == q);
2564 * Once the buffer is locked we will have no choice but to
2565 * unlock the spinlock around a later BUF_UNLOCK and re-set
2566 * bp = marker when looping. Move the marker now to make
2569 TAILQ_REMOVE(&bufqueues[q], marker, b_freelist);
2570 TAILQ_INSERT_AFTER(&bufqueues[q], bp, marker, b_freelist);
2573 * Must recheck B_DELWRI after successfully locking
2576 if ((bp->b_flags & B_DELWRI) == 0) {
2577 spin_unlock(&bufqspin);
2579 spin_lock(&bufqspin);
2585 * Remove the buffer from its queue. We still own the
2591 * Disposing of an invalid buffer counts as a flush op
2593 if (bp->b_flags & B_INVAL) {
2594 spin_unlock(&bufqspin);
2596 spin_lock(&bufqspin);
2602 * Release the spinlock for the more complex ops we
2603 * are now going to do.
2605 spin_unlock(&bufqspin);
2609 * This is a bit messy
2611 if (LIST_FIRST(&bp->b_dep) != NULL &&
2612 (bp->b_flags & B_DEFERRED) == 0 &&
2613 buf_countdeps(bp, 0)) {
2614 spin_lock(&bufqspin);
2615 TAILQ_INSERT_TAIL(&bufqueues[q], bp, b_freelist);
2617 bp->b_flags |= B_DEFERRED;
2618 spin_unlock(&bufqspin);
2620 spin_lock(&bufqspin);
2626 * spinlock not held here.
2628 * If the buffer has a dependancy, buf_checkwrite() must
2629 * also return 0 for us to be able to initate the write.
2631 * If the buffer is flagged B_ERROR it may be requeued
2632 * over and over again, we try to avoid a live lock.
2634 * NOTE: buf_checkwrite is MPSAFE.
2636 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
2638 } else if (bp->b_flags & B_ERROR) {
2639 tsleep(bp, 0, "bioer", 1);
2640 bp->b_flags &= ~B_AGE;
2643 bp->b_flags |= B_AGE;
2646 spin_lock(&bufqspin);
2650 TAILQ_REMOVE(&bufqueues[q], marker, b_freelist);
2651 marker->b_qindex = BQUEUE_NONE;
2652 spin_unlock(&bufqspin);
2660 * Returns true if no I/O is needed to access the associated VM object.
2661 * This is like findblk except it also hunts around in the VM system for
2664 * Note that we ignore vm_page_free() races from interrupts against our
2665 * lookup, since if the caller is not protected our return value will not
2666 * be any more valid then otherwise once we exit the critical section.
2669 inmem(struct vnode *vp, off_t loffset)
2672 vm_offset_t toff, tinc, size;
2676 if (findblk(vp, loffset, FINDBLK_TEST))
2678 if (vp->v_mount == NULL)
2680 if ((obj = vp->v_object) == NULL)
2684 if (size > vp->v_mount->mnt_stat.f_iosize)
2685 size = vp->v_mount->mnt_stat.f_iosize;
2687 vm_object_hold(obj);
2688 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2689 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2695 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2696 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2697 if (vm_page_is_valid(m,
2698 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0) {
2703 vm_object_drop(obj);
2710 * Locate and return the specified buffer. Unless flagged otherwise,
2711 * a locked buffer will be returned if it exists or NULL if it does not.
2713 * findblk()'d buffers are still on the bufqueues and if you intend
2714 * to use your (locked NON-TEST) buffer you need to bremfree(bp)
2715 * and possibly do other stuff to it.
2717 * FINDBLK_TEST - Do not lock the buffer. The caller is responsible
2718 * for locking the buffer and ensuring that it remains
2719 * the desired buffer after locking.
2721 * FINDBLK_NBLOCK - Lock the buffer non-blocking. If we are unable
2722 * to acquire the lock we return NULL, even if the
2725 * FINDBLK_REF - Returns the buffer ref'd, which prevents normal
2726 * reuse by getnewbuf() but does not prevent
2727 * disassociation (B_INVAL). Used to avoid deadlocks
2728 * against random (vp,loffset)s due to reassignment.
2730 * (0) - Lock the buffer blocking.
2735 findblk(struct vnode *vp, off_t loffset, int flags)
2740 lkflags = LK_EXCLUSIVE;
2741 if (flags & FINDBLK_NBLOCK)
2742 lkflags |= LK_NOWAIT;
2746 * Lookup. Ref the buf while holding v_token to prevent
2747 * reuse (but does not prevent diassociation).
2749 lwkt_gettoken_shared(&vp->v_token);
2750 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2752 lwkt_reltoken(&vp->v_token);
2756 lwkt_reltoken(&vp->v_token);
2759 * If testing only break and return bp, do not lock.
2761 if (flags & FINDBLK_TEST)
2765 * Lock the buffer, return an error if the lock fails.
2766 * (only FINDBLK_NBLOCK can cause the lock to fail).
2768 if (BUF_LOCK(bp, lkflags)) {
2769 atomic_subtract_int(&bp->b_refs, 1);
2770 /* bp = NULL; not needed */
2775 * Revalidate the locked buf before allowing it to be
2778 if (bp->b_vp == vp && bp->b_loffset == loffset)
2780 atomic_subtract_int(&bp->b_refs, 1);
2787 if ((flags & FINDBLK_REF) == 0)
2788 atomic_subtract_int(&bp->b_refs, 1);
2795 * Similar to getblk() except only returns the buffer if it is
2796 * B_CACHE and requires no other manipulation. Otherwise NULL
2799 * If B_RAM is set the buffer might be just fine, but we return
2800 * NULL anyway because we want the code to fall through to the
2801 * cluster read. Otherwise read-ahead breaks.
2803 * If blksize is 0 the buffer cache buffer must already be fully
2806 * If blksize is non-zero getblk() will be used, allowing a buffer
2807 * to be reinstantiated from its VM backing store. The buffer must
2808 * still be fully cached after reinstantiation to be returned.
2811 getcacheblk(struct vnode *vp, off_t loffset, int blksize, int blkflags)
2814 int fndflags = (blkflags & GETBLK_NOWAIT) ? FINDBLK_NBLOCK : 0;
2817 bp = getblk(vp, loffset, blksize, blkflags, 0);
2819 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) ==
2821 bp->b_flags &= ~B_AGE;
2828 bp = findblk(vp, loffset, fndflags);
2830 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) ==
2832 bp->b_flags &= ~B_AGE;
2846 * Get a block given a specified block and offset into a file/device.
2847 * B_INVAL may or may not be set on return. The caller should clear
2848 * B_INVAL prior to initiating a READ.
2850 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2851 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2852 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2853 * without doing any of those things the system will likely believe
2854 * the buffer to be valid (especially if it is not B_VMIO), and the
2855 * next getblk() will return the buffer with B_CACHE set.
2857 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2858 * an existing buffer.
2860 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2861 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2862 * and then cleared based on the backing VM. If the previous buffer is
2863 * non-0-sized but invalid, B_CACHE will be cleared.
2865 * If getblk() must create a new buffer, the new buffer is returned with
2866 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2867 * case it is returned with B_INVAL clear and B_CACHE set based on the
2870 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2871 * B_CACHE bit is clear.
2873 * What this means, basically, is that the caller should use B_CACHE to
2874 * determine whether the buffer is fully valid or not and should clear
2875 * B_INVAL prior to issuing a read. If the caller intends to validate
2876 * the buffer by loading its data area with something, the caller needs
2877 * to clear B_INVAL. If the caller does this without issuing an I/O,
2878 * the caller should set B_CACHE ( as an optimization ), else the caller
2879 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2880 * a write attempt or if it was a successfull read. If the caller
2881 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2882 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2886 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2887 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2892 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2895 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2899 if (size > MAXBSIZE)
2900 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2901 if (vp->v_object == NULL)
2902 panic("getblk: vnode %p has no object!", vp);
2905 if ((bp = findblk(vp, loffset, FINDBLK_REF | FINDBLK_TEST)) != NULL) {
2907 * The buffer was found in the cache, but we need to lock it.
2908 * We must acquire a ref on the bp to prevent reuse, but
2909 * this will not prevent disassociation (brelvp()) so we
2910 * must recheck (vp,loffset) after acquiring the lock.
2912 * Without the ref the buffer could potentially be reused
2913 * before we acquire the lock and create a deadlock
2914 * situation between the thread trying to reuse the buffer
2915 * and us due to the fact that we would wind up blocking
2916 * on a random (vp,loffset).
2918 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2919 if (blkflags & GETBLK_NOWAIT) {
2923 lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2924 if (blkflags & GETBLK_PCATCH)
2925 lkflags |= LK_PCATCH;
2926 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2929 if (error == ENOLCK)
2933 /* buffer may have changed on us */
2938 * Once the buffer has been locked, make sure we didn't race
2939 * a buffer recyclement. Buffers that are no longer hashed
2940 * will have b_vp == NULL, so this takes care of that check
2943 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2944 kprintf("Warning buffer %p (vp %p loffset %lld) "
2946 bp, vp, (long long)loffset);
2952 * If SZMATCH any pre-existing buffer must be of the requested
2953 * size or NULL is returned. The caller absolutely does not
2954 * want getblk() to bwrite() the buffer on a size mismatch.
2956 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2962 * All vnode-based buffers must be backed by a VM object.
2964 KKASSERT(bp->b_flags & B_VMIO);
2965 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2966 bp->b_flags &= ~B_AGE;
2969 * Make sure that B_INVAL buffers do not have a cached
2970 * block number translation.
2972 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2973 kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2974 " did not have cleared bio_offset cache\n",
2975 bp, vp, (long long)loffset);
2976 clearbiocache(&bp->b_bio2);
2980 * The buffer is locked. B_CACHE is cleared if the buffer is
2983 if (bp->b_flags & B_INVAL)
2984 bp->b_flags &= ~B_CACHE;
2988 * Any size inconsistancy with a dirty buffer or a buffer
2989 * with a softupdates dependancy must be resolved. Resizing
2990 * the buffer in such circumstances can lead to problems.
2992 * Dirty or dependant buffers are written synchronously.
2993 * Other types of buffers are simply released and
2994 * reconstituted as they may be backed by valid, dirty VM
2995 * pages (but not marked B_DELWRI).
2997 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2998 * and may be left over from a prior truncation (and thus
2999 * no longer represent the actual EOF point), so we
3000 * definitely do not want to B_NOCACHE the backing store.
3002 if (size != bp->b_bcount) {
3003 if (bp->b_flags & B_DELWRI) {
3004 bp->b_flags |= B_RELBUF;
3006 } else if (LIST_FIRST(&bp->b_dep)) {
3007 bp->b_flags |= B_RELBUF;
3010 bp->b_flags |= B_RELBUF;
3015 KKASSERT(size <= bp->b_kvasize);
3016 KASSERT(bp->b_loffset != NOOFFSET,
3017 ("getblk: no buffer offset"));
3020 * A buffer with B_DELWRI set and B_CACHE clear must
3021 * be committed before we can return the buffer in
3022 * order to prevent the caller from issuing a read
3023 * ( due to B_CACHE not being set ) and overwriting
3026 * Most callers, including NFS and FFS, need this to
3027 * operate properly either because they assume they
3028 * can issue a read if B_CACHE is not set, or because
3029 * ( for example ) an uncached B_DELWRI might loop due
3030 * to softupdates re-dirtying the buffer. In the latter
3031 * case, B_CACHE is set after the first write completes,
3032 * preventing further loops.
3034 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3035 * above while extending the buffer, we cannot allow the
3036 * buffer to remain with B_CACHE set after the write
3037 * completes or it will represent a corrupt state. To
3038 * deal with this we set B_NOCACHE to scrap the buffer
3041 * XXX Should this be B_RELBUF instead of B_NOCACHE?
3042 * I'm not even sure this state is still possible
3043 * now that getblk() writes out any dirty buffers
3046 * We might be able to do something fancy, like setting
3047 * B_CACHE in bwrite() except if B_DELWRI is already set,
3048 * so the below call doesn't set B_CACHE, but that gets real
3049 * confusing. This is much easier.
3052 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3053 kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
3054 "and CACHE clear, b_flags %08x\n",
3055 bp, (uintmax_t)bp->b_loffset, bp->b_flags);
3056 bp->b_flags |= B_NOCACHE;
3062 * Buffer is not in-core, create new buffer. The buffer
3063 * returned by getnewbuf() is locked. Note that the returned
3064 * buffer is also considered valid (not marked B_INVAL).
3066 * Calculating the offset for the I/O requires figuring out
3067 * the block size. We use DEV_BSIZE for VBLK or VCHR and
3068 * the mount's f_iosize otherwise. If the vnode does not
3069 * have an associated mount we assume that the passed size is
3072 * Note that vn_isdisk() cannot be used here since it may
3073 * return a failure for numerous reasons. Note that the
3074 * buffer size may be larger then the block size (the caller
3075 * will use block numbers with the proper multiple). Beware
3076 * of using any v_* fields which are part of unions. In
3077 * particular, in DragonFly the mount point overloading
3078 * mechanism uses the namecache only and the underlying
3079 * directory vnode is not a special case.
3083 if (vp->v_type == VBLK || vp->v_type == VCHR)
3085 else if (vp->v_mount)
3086 bsize = vp->v_mount->mnt_stat.f_iosize;
3090 maxsize = size + (loffset & PAGE_MASK);
3091 maxsize = imax(maxsize, bsize);
3093 bp = getnewbuf(blkflags, slptimeo, size, maxsize);
3095 if (slpflags || slptimeo)
3101 * Atomically insert the buffer into the hash, so that it can
3102 * be found by findblk().
3104 * If bgetvp() returns non-zero a collision occured, and the
3105 * bp will not be associated with the vnode.
3107 * Make sure the translation layer has been cleared.
3109 bp->b_loffset = loffset;
3110 bp->b_bio2.bio_offset = NOOFFSET;
3111 /* bp->b_bio2.bio_next = NULL; */
3113 if (bgetvp(vp, bp, size)) {
3114 bp->b_flags |= B_INVAL;
3120 * All vnode-based buffers must be backed by a VM object.
3122 KKASSERT(vp->v_object != NULL);
3123 bp->b_flags |= B_VMIO;
3124 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3128 KKASSERT(dsched_is_clear_buf_priv(bp));
3135 * Reacquire a buffer that was previously released to the locked queue,
3136 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
3137 * set B_LOCKED (which handles the acquisition race).
3139 * To this end, either B_LOCKED must be set or the dependancy list must be
3145 regetblk(struct buf *bp)
3147 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
3148 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
3155 * Get an empty, disassociated buffer of given size. The buffer is
3156 * initially set to B_INVAL.
3158 * critical section protection is not required for the allocbuf()
3159 * call because races are impossible here.
3169 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3171 while ((bp = getnewbuf(0, 0, size, maxsize)) == NULL)
3174 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3175 KKASSERT(dsched_is_clear_buf_priv(bp));
3183 * This code constitutes the buffer memory from either anonymous system
3184 * memory (in the case of non-VMIO operations) or from an associated
3185 * VM object (in the case of VMIO operations). This code is able to
3186 * resize a buffer up or down.
3188 * Note that this code is tricky, and has many complications to resolve
3189 * deadlock or inconsistant data situations. Tread lightly!!!
3190 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3191 * the caller. Calling this code willy nilly can result in the loss of
3194 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3195 * B_CACHE for the non-VMIO case.
3197 * This routine does not need to be called from a critical section but you
3198 * must own the buffer.
3203 allocbuf(struct buf *bp, int size)
3205 int newbsize, mbsize;
3208 if (BUF_REFCNT(bp) == 0)
3209 panic("allocbuf: buffer not busy");
3211 if (bp->b_kvasize < size)
3212 panic("allocbuf: buffer too small");
3214 if ((bp->b_flags & B_VMIO) == 0) {
3218 * Just get anonymous memory from the kernel. Don't
3219 * mess with B_CACHE.
3221 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3222 if (bp->b_flags & B_MALLOC)
3225 newbsize = round_page(size);
3227 if (newbsize < bp->b_bufsize) {
3229 * Malloced buffers are not shrunk
3231 if (bp->b_flags & B_MALLOC) {
3233 bp->b_bcount = size;
3235 kfree(bp->b_data, M_BIOBUF);
3236 if (bp->b_bufsize) {
3237 atomic_subtract_long(&bufmallocspace, bp->b_bufsize);
3241 bp->b_data = bp->b_kvabase;
3243 bp->b_flags &= ~B_MALLOC;
3249 (vm_offset_t) bp->b_data + newbsize,
3250 (vm_offset_t) bp->b_data + bp->b_bufsize);
3251 } else if (newbsize > bp->b_bufsize) {
3253 * We only use malloced memory on the first allocation.
3254 * and revert to page-allocated memory when the buffer
3257 if ((bufmallocspace < maxbufmallocspace) &&
3258 (bp->b_bufsize == 0) &&
3259 (mbsize <= PAGE_SIZE/2)) {
3261 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
3262 bp->b_bufsize = mbsize;
3263 bp->b_bcount = size;
3264 bp->b_flags |= B_MALLOC;
3265 atomic_add_long(&bufmallocspace, mbsize);
3271 * If the buffer is growing on its other-than-first
3272 * allocation, then we revert to the page-allocation
3275 if (bp->b_flags & B_MALLOC) {
3276 origbuf = bp->b_data;
3277 origbufsize = bp->b_bufsize;
3278 bp->b_data = bp->b_kvabase;
3279 if (bp->b_bufsize) {
3280 atomic_subtract_long(&bufmallocspace,
3285 bp->b_flags &= ~B_MALLOC;
3286 newbsize = round_page(newbsize);
3290 (vm_offset_t) bp->b_data + bp->b_bufsize,
3291 (vm_offset_t) bp->b_data + newbsize);
3293 bcopy(origbuf, bp->b_data, origbufsize);
3294 kfree(origbuf, M_BIOBUF);
3301 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3302 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3303 newbsize + PAGE_MASK) >> PAGE_SHIFT;
3304 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
3306 if (bp->b_flags & B_MALLOC)
3307 panic("allocbuf: VMIO buffer can't be malloced");
3309 * Set B_CACHE initially if buffer is 0 length or will become
3312 if (size == 0 || bp->b_bufsize == 0)
3313 bp->b_flags |= B_CACHE;
3315 if (newbsize < bp->b_bufsize) {
3317 * DEV_BSIZE aligned new buffer size is less then the
3318 * DEV_BSIZE aligned existing buffer size. Figure out
3319 * if we have to remove any pages.
3321 if (desiredpages < bp->b_xio.xio_npages) {
3322 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
3324 * the page is not freed here -- it
3325 * is the responsibility of
3326 * vnode_pager_setsize
3328 m = bp->b_xio.xio_pages[i];
3329 KASSERT(m != bogus_page,
3330 ("allocbuf: bogus page found"));
3331 vm_page_busy_wait(m, TRUE, "biodep");
3332 bp->b_xio.xio_pages[i] = NULL;
3333 vm_page_unwire(m, 0);
3336 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
3337 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
3338 bp->b_xio.xio_npages = desiredpages;
3340 } else if (size > bp->b_bcount) {
3342 * We are growing the buffer, possibly in a
3343 * byte-granular fashion.
3351 * Step 1, bring in the VM pages from the object,
3352 * allocating them if necessary. We must clear
3353 * B_CACHE if these pages are not valid for the
3354 * range covered by the buffer.
3356 * critical section protection is required to protect
3357 * against interrupts unbusying and freeing pages
3358 * between our vm_page_lookup() and our
3359 * busycheck/wiring call.
3364 vm_object_hold(obj);
3365 while (bp->b_xio.xio_npages < desiredpages) {
3370 pi = OFF_TO_IDX(bp->b_loffset) +
3371 bp->b_xio.xio_npages;
3374 * Blocking on m->busy might lead to a
3377 * vm_fault->getpages->cluster_read->allocbuf
3379 m = vm_page_lookup_busy_try(obj, pi, FALSE,
3382 vm_page_sleep_busy(m, FALSE, "pgtblk");
3387 * note: must allocate system pages
3388 * since blocking here could intefere
3389 * with paging I/O, no matter which
3392 m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages);
3395 vm_page_flag_clear(m, PG_ZERO);
3397 bp->b_flags &= ~B_CACHE;
3398 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3399 ++bp->b_xio.xio_npages;
3405 * We found a page and were able to busy it.
3407 vm_page_flag_clear(m, PG_ZERO);
3410 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3411 ++bp->b_xio.xio_npages;
3412 if (bp->b_act_count < m->act_count)
3413 bp->b_act_count = m->act_count;
3415 vm_object_drop(obj);
3418 * Step 2. We've loaded the pages into the buffer,
3419 * we have to figure out if we can still have B_CACHE
3420 * set. Note that B_CACHE is set according to the
3421 * byte-granular range ( bcount and size ), not the
3422 * aligned range ( newbsize ).
3424 * The VM test is against m->valid, which is DEV_BSIZE
3425 * aligned. Needless to say, the validity of the data
3426 * needs to also be DEV_BSIZE aligned. Note that this
3427 * fails with NFS if the server or some other client
3428 * extends the file's EOF. If our buffer is resized,
3429 * B_CACHE may remain set! XXX
3432 toff = bp->b_bcount;
3433 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3435 while ((bp->b_flags & B_CACHE) && toff < size) {
3438 if (tinc > (size - toff))
3441 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
3449 bp->b_xio.xio_pages[pi]
3456 * Step 3, fixup the KVM pmap. Remember that
3457 * bp->b_data is relative to bp->b_loffset, but
3458 * bp->b_loffset may be offset into the first page.
3461 bp->b_data = (caddr_t)
3462 trunc_page((vm_offset_t)bp->b_data);
3464 (vm_offset_t)bp->b_data,
3465 bp->b_xio.xio_pages,
3466 bp->b_xio.xio_npages
3468 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3469 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3473 /* adjust space use on already-dirty buffer */
3474 if (bp->b_flags & B_DELWRI) {
3475 spin_lock(&bufcspin);
3476 /* dirtykvaspace unchanged */
3477 dirtybufspace += newbsize - bp->b_bufsize;
3478 if (bp->b_flags & B_HEAVY)
3479 dirtybufspacehw += newbsize - bp->b_bufsize;
3480 spin_unlock(&bufcspin);
3482 if (newbsize < bp->b_bufsize)
3484 bp->b_bufsize = newbsize; /* actual buffer allocation */
3485 bp->b_bcount = size; /* requested buffer size */
3492 * Wait for buffer I/O completion, returning error status. B_EINTR
3493 * is converted into an EINTR error but not cleared (since a chain
3494 * of biowait() calls may occur).
3496 * On return bpdone() will have been called but the buffer will remain
3497 * locked and will not have been brelse()'d.
3499 * NOTE! If a timeout is specified and ETIMEDOUT occurs the I/O is
3500 * likely still in progress on return.
3502 * NOTE! This operation is on a BIO, not a BUF.
3504 * NOTE! BIO_DONE is cleared by vn_strategy()
3509 _biowait(struct bio *bio, const char *wmesg, int to)
3511 struct buf *bp = bio->bio_buf;
3516 KKASSERT(bio == &bp->b_bio1);
3518 flags = bio->bio_flags;
3519 if (flags & BIO_DONE)
3521 nflags = flags | BIO_WANT;
3522 tsleep_interlock(bio, 0);
3523 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3525 error = tsleep(bio, PINTERLOCKED, wmesg, to);
3526 else if (bp->b_cmd == BUF_CMD_READ)
3527 error = tsleep(bio, PINTERLOCKED, "biord", to);
3529 error = tsleep(bio, PINTERLOCKED, "biowr", to);
3531 kprintf("tsleep error biowait %d\n", error);
3540 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3541 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
3542 if (bp->b_flags & B_EINTR)
3544 if (bp->b_flags & B_ERROR)
3545 return (bp->b_error ? bp->b_error : EIO);
3550 biowait(struct bio *bio, const char *wmesg)
3552 return(_biowait(bio, wmesg, 0));
3556 biowait_timeout(struct bio *bio, const char *wmesg, int to)
3558 return(_biowait(bio, wmesg, to));
3562 * This associates a tracking count with an I/O. vn_strategy() and
3563 * dev_dstrategy() do this automatically but there are a few cases
3564 * where a vnode or device layer is bypassed when a block translation
3565 * is cached. In such cases bio_start_transaction() may be called on
3566 * the bypassed layers so the system gets an I/O in progress indication
3567 * for those higher layers.
3570 bio_start_transaction(struct bio *bio, struct bio_track *track)
3572 bio->bio_track = track;
3573 if (dsched_is_clear_buf_priv(bio->bio_buf))
3574 dsched_new_buf(bio->bio_buf);
3575 bio_track_ref(track);
3579 * Initiate I/O on a vnode.
3581 * SWAPCACHE OPERATION:
3583 * Real buffer cache buffers have a non-NULL bp->b_vp. Unfortunately
3584 * devfs also uses b_vp for fake buffers so we also have to check
3585 * that B_PAGING is 0. In this case the passed 'vp' is probably the
3586 * underlying block device. The swap assignments are related to the
3587 * buffer cache buffer's b_vp, not the passed vp.
3589 * The passed vp == bp->b_vp only in the case where the strategy call
3590 * is made on the vp itself for its own buffers (a regular file or
3591 * block device vp). The filesystem usually then re-calls vn_strategy()
3592 * after translating the request to an underlying device.
3594 * Cluster buffers set B_CLUSTER and the passed vp is the vp of the
3595 * underlying buffer cache buffers.
3597 * We can only deal with page-aligned buffers at the moment, because
3598 * we can't tell what the real dirty state for pages straddling a buffer
3601 * In order to call swap_pager_strategy() we must provide the VM object
3602 * and base offset for the underlying buffer cache pages so it can find
3606 vn_strategy(struct vnode *vp, struct bio *bio)
3608 struct bio_track *track;
3609 struct buf *bp = bio->bio_buf;
3611 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3614 * Set when an I/O is issued on the bp. Cleared by consumers
3615 * (aka HAMMER), allowing the consumer to determine if I/O had
3616 * actually occurred.
3618 bp->b_flags |= B_IODEBUG;
3621 * Handle the swap cache intercept.
3623 if (vn_cache_strategy(vp, bio))
3627 * Otherwise do the operation through the filesystem
3629 if (bp->b_cmd == BUF_CMD_READ)
3630 track = &vp->v_track_read;
3632 track = &vp->v_track_write;
3633 KKASSERT((bio->bio_flags & BIO_DONE) == 0);
3634 bio->bio_track = track;
3635 if (dsched_is_clear_buf_priv(bio->bio_buf))
3636 dsched_new_buf(bio->bio_buf);
3637 bio_track_ref(track);
3638 vop_strategy(*vp->v_ops, vp, bio);
3641 static void vn_cache_strategy_callback(struct bio *bio);
3644 vn_cache_strategy(struct vnode *vp, struct bio *bio)
3646 struct buf *bp = bio->bio_buf;
3653 * Is this buffer cache buffer suitable for reading from
3656 if (vm_swapcache_read_enable == 0 ||
3657 bp->b_cmd != BUF_CMD_READ ||
3658 ((bp->b_flags & B_CLUSTER) == 0 &&
3659 (bp->b_vp == NULL || (bp->b_flags & B_PAGING))) ||
3660 ((int)bp->b_loffset & PAGE_MASK) != 0 ||
3661 (bp->b_bcount & PAGE_MASK) != 0) {
3666 * Figure out the original VM object (it will match the underlying
3667 * VM pages). Note that swap cached data uses page indices relative
3668 * to that object, not relative to bio->bio_offset.
3670 if (bp->b_flags & B_CLUSTER)
3671 object = vp->v_object;
3673 object = bp->b_vp->v_object;
3676 * In order to be able to use the swap cache all underlying VM
3677 * pages must be marked as such, and we can't have any bogus pages.
3679 for (i = 0; i < bp->b_xio.xio_npages; ++i) {
3680 m = bp->b_xio.xio_pages[i];
3681 if ((m->flags & PG_SWAPPED) == 0)
3683 if (m == bogus_page)
3688 * If we are good then issue the I/O using swap_pager_strategy().
3690 * We can only do this if the buffer actually supports object-backed
3691 * I/O. If it doesn't npages will be 0.
3693 if (i && i == bp->b_xio.xio_npages) {
3694 m = bp->b_xio.xio_pages[0];
3695 nbio = push_bio(bio);
3696 nbio->bio_done = vn_cache_strategy_callback;
3697 nbio->bio_offset = ptoa(m->pindex);
3698 KKASSERT(m->object == object);
3699 swap_pager_strategy(object, nbio);
3706 * This is a bit of a hack but since the vn_cache_strategy() function can
3707 * override a VFS's strategy function we must make sure that the bio, which
3708 * is probably bio2, doesn't leak an unexpected offset value back to the
3709 * filesystem. The filesystem (e.g. UFS) might otherwise assume that the
3710 * bio went through its own file strategy function and the the bio2 offset
3711 * is a cached disk offset when, in fact, it isn't.
3714 vn_cache_strategy_callback(struct bio *bio)
3716 bio->bio_offset = NOOFFSET;
3717 biodone(pop_bio(bio));
3723 * Finish I/O on a buffer after all BIOs have been processed.
3724 * Called when the bio chain is exhausted or by biowait. If called
3725 * by biowait, elseit is typically 0.
3727 * bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3728 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3729 * assuming B_INVAL is clear.
3731 * For the VMIO case, we set B_CACHE if the op was a read and no
3732 * read error occured, or if the op was a write. B_CACHE is never
3733 * set if the buffer is invalid or otherwise uncacheable.
3735 * bpdone does not mess with B_INVAL, allowing the I/O routine or the
3736 * initiator to leave B_INVAL set to brelse the buffer out of existance
3737 * in the biodone routine.
3740 bpdone(struct buf *bp, int elseit)
3744 KASSERT(BUF_REFCNTNB(bp) > 0,
3745 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3746 KASSERT(bp->b_cmd != BUF_CMD_DONE,
3747 ("biodone: bp %p already done!", bp));
3750 * No more BIOs are left. All completion functions have been dealt
3751 * with, now we clean up the buffer.
3754 bp->b_cmd = BUF_CMD_DONE;
3757 * Only reads and writes are processed past this point.
3759 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3760 if (cmd == BUF_CMD_FREEBLKS)
3761 bp->b_flags |= B_NOCACHE;
3768 * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3769 * a lot worse. XXX - move this above the clearing of b_cmd
3771 if (LIST_FIRST(&bp->b_dep) != NULL)
3772 buf_complete(bp); /* MPSAFE */
3775 * A failed write must re-dirty the buffer unless B_INVAL
3776 * was set. Only applicable to normal buffers (with VPs).
3777 * vinum buffers may not have a vp.
3779 if (cmd == BUF_CMD_WRITE &&
3780 (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
3781 bp->b_flags &= ~B_NOCACHE;
3786 if (bp->b_flags & B_VMIO) {
3792 struct vnode *vp = bp->b_vp;
3796 #if defined(VFS_BIO_DEBUG)
3797 if (vp->v_auxrefs == 0)
3798 panic("biodone: zero vnode hold count");
3799 if ((vp->v_flag & VOBJBUF) == 0)
3800 panic("biodone: vnode is not setup for merged cache");
3803 foff = bp->b_loffset;
3804 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3805 KASSERT(obj != NULL, ("biodone: missing VM object"));
3807 #if defined(VFS_BIO_DEBUG)
3808 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3809 kprintf("biodone: paging in progress(%d) < "
3810 "bp->b_xio.xio_npages(%d)\n",
3811 obj->paging_in_progress,
3812 bp->b_xio.xio_npages);
3817 * Set B_CACHE if the op was a normal read and no error
3818 * occured. B_CACHE is set for writes in the b*write()
3821 iosize = bp->b_bcount - bp->b_resid;
3822 if (cmd == BUF_CMD_READ &&
3823 (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3824 bp->b_flags |= B_CACHE;
3827 vm_object_hold(obj);
3828 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3832 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3837 * cleanup bogus pages, restoring the originals. Since
3838 * the originals should still be wired, we don't have
3839 * to worry about interrupt/freeing races destroying
3840 * the VM object association.
3842 m = bp->b_xio.xio_pages[i];
3843 if (m == bogus_page) {
3845 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3847 panic("biodone: page disappeared");
3848 bp->b_xio.xio_pages[i] = m;
3849 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3850 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3852 #if defined(VFS_BIO_DEBUG)
3853 if (OFF_TO_IDX(foff) != m->pindex) {
3854 kprintf("biodone: foff(%lu)/m->pindex(%ld) "
3856 (unsigned long)foff, (long)m->pindex);
3861 * In the write case, the valid and clean bits are
3862 * already changed correctly (see bdwrite()), so we
3863 * only need to do this here in the read case.
3865 vm_page_busy_wait(m, FALSE, "bpdpgw");
3866 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3867 vfs_clean_one_page(bp, i, m);
3869 vm_page_flag_clear(m, PG_ZERO);
3872 * when debugging new filesystems or buffer I/O
3873 * methods, this is the most common error that pops
3874 * up. if you see this, you have not set the page
3875 * busy flag correctly!!!
3878 kprintf("biodone: page busy < 0, "
3879 "pindex: %d, foff: 0x(%x,%x), "
3880 "resid: %d, index: %d\n",
3881 (int) m->pindex, (int)(foff >> 32),
3882 (int) foff & 0xffffffff, resid, i);
3883 if (!vn_isdisk(vp, NULL))
3884 kprintf(" iosize: %ld, loffset: %lld, "
3885 "flags: 0x%08x, npages: %d\n",
3886 bp->b_vp->v_mount->mnt_stat.f_iosize,
3887 (long long)bp->b_loffset,
3888 bp->b_flags, bp->b_xio.xio_npages);
3890 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3891 (long long)bp->b_loffset,
3892 bp->b_flags, bp->b_xio.xio_npages);
3893 kprintf(" valid: 0x%x, dirty: 0x%x, "
3897 panic("biodone: page busy < 0");
3899 vm_page_io_finish(m);
3901 vm_object_pip_wakeup(obj);
3902 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3905 bp->b_flags &= ~B_HASBOGUS;
3906 vm_object_drop(obj);
3910 * Finish up by releasing the buffer. There are no more synchronous
3911 * or asynchronous completions, those were handled by bio_done
3915 if (bp->b_flags & (B_NOCACHE|B_INVAL|B_ERROR|B_RELBUF))
3926 biodone(struct bio *bio)
3928 struct buf *bp = bio->bio_buf;
3930 runningbufwakeup(bp);
3933 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
3936 biodone_t *done_func;
3937 struct bio_track *track;
3940 * BIO tracking. Most but not all BIOs are tracked.
3942 if ((track = bio->bio_track) != NULL) {
3943 bio_track_rel(track);
3944 bio->bio_track = NULL;
3948 * A bio_done function terminates the loop. The function
3949 * will be responsible for any further chaining and/or
3950 * buffer management.
3952 * WARNING! The done function can deallocate the buffer!
3954 if ((done_func = bio->bio_done) != NULL) {
3955 bio->bio_done = NULL;
3959 bio = bio->bio_prev;
3963 * If we've run out of bio's do normal [a]synchronous completion.
3969 * Synchronous biodone - this terminates a synchronous BIO.
3971 * bpdone() is called with elseit=FALSE, leaving the buffer completed
3972 * but still locked. The caller must brelse() the buffer after waiting
3976 biodone_sync(struct bio *bio)
3978 struct buf *bp = bio->bio_buf;
3982 KKASSERT(bio == &bp->b_bio1);
3986 flags = bio->bio_flags;
3987 nflags = (flags | BIO_DONE) & ~BIO_WANT;
3989 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3990 if (flags & BIO_WANT)
4000 * This routine is called in lieu of iodone in the case of
4001 * incomplete I/O. This keeps the busy status for pages
4005 vfs_unbusy_pages(struct buf *bp)
4009 runningbufwakeup(bp);
4011 if (bp->b_flags & B_VMIO) {
4012 struct vnode *vp = bp->b_vp;
4016 vm_object_hold(obj);
4018 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4019 vm_page_t m = bp->b_xio.xio_pages[i];
4022 * When restoring bogus changes the original pages
4023 * should still be wired, so we are in no danger of
4024 * losing the object association and do not need
4025 * critical section protection particularly.
4027 if (m == bogus_page) {
4028 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
4030 panic("vfs_unbusy_pages: page missing");
4032 bp->b_xio.xio_pages[i] = m;
4033 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4034 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
4036 vm_page_busy_wait(m, FALSE, "bpdpgw");
4037 vm_page_flag_clear(m, PG_ZERO);
4038 vm_page_io_finish(m);
4040 vm_object_pip_wakeup(obj);
4042 bp->b_flags &= ~B_HASBOGUS;
4043 vm_object_drop(obj);
4050 * This routine is called before a device strategy routine.
4051 * It is used to tell the VM system that paging I/O is in
4052 * progress, and treat the pages associated with the buffer
4053 * almost as being PG_BUSY. Also the object 'paging_in_progress'
4054 * flag is handled to make sure that the object doesn't become
4057 * Since I/O has not been initiated yet, certain buffer flags
4058 * such as B_ERROR or B_INVAL may be in an inconsistant state
4059 * and should be ignored.
4064 vfs_busy_pages(struct vnode *vp, struct buf *bp)
4067 struct lwp *lp = curthread->td_lwp;
4070 * The buffer's I/O command must already be set. If reading,
4071 * B_CACHE must be 0 (double check against callers only doing
4072 * I/O when B_CACHE is 0).
4074 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4075 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
4077 if (bp->b_flags & B_VMIO) {
4081 KASSERT(bp->b_loffset != NOOFFSET,
4082 ("vfs_busy_pages: no buffer offset"));
4085 * Busy all the pages. We have to busy them all at once
4086 * to avoid deadlocks.
4089 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4090 vm_page_t m = bp->b_xio.xio_pages[i];
4092 if (vm_page_busy_try(m, FALSE)) {
4093 vm_page_sleep_busy(m, FALSE, "vbpage");
4095 vm_page_wakeup(bp->b_xio.xio_pages[i]);
4101 * Setup for I/O, soft-busy the page right now because
4102 * the next loop may block.
4104 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4105 vm_page_t m = bp->b_xio.xio_pages[i];
4107 vm_page_flag_clear(m, PG_ZERO);
4108 if ((bp->b_flags & B_CLUSTER) == 0) {
4109 vm_object_pip_add(obj, 1);
4110 vm_page_io_start(m);
4115 * Adjust protections for I/O and do bogus-page mapping.
4116 * Assume that vm_page_protect() can block (it can block
4117 * if VM_PROT_NONE, don't take any chances regardless).
4119 * In particular note that for writes we must incorporate
4120 * page dirtyness from the VM system into the buffer's
4123 * For reads we theoretically must incorporate page dirtyness
4124 * from the VM system to determine if the page needs bogus
4125 * replacement, but we shortcut the test by simply checking
4126 * that all m->valid bits are set, indicating that the page
4127 * is fully valid and does not need to be re-read. For any
4128 * VM system dirtyness the page will also be fully valid
4129 * since it was mapped at one point.
4132 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4133 vm_page_t m = bp->b_xio.xio_pages[i];
4135 vm_page_flag_clear(m, PG_ZERO); /* XXX */
4136 if (bp->b_cmd == BUF_CMD_WRITE) {
4138 * When readying a vnode-backed buffer for
4139 * a write we must zero-fill any invalid
4140 * portions of the backing VM pages, mark
4141 * it valid and clear related dirty bits.
4143 * vfs_clean_one_page() incorporates any
4144 * VM dirtyness and updates the b_dirtyoff
4145 * range (after we've made the page RO).
4147 * It is also expected that the pmap modified
4148 * bit has already been cleared by the
4149 * vm_page_protect(). We may not be able
4150 * to clear all dirty bits for a page if it
4151 * was also memory mapped (NFS).
4153 * Finally be sure to unassign any swap-cache
4154 * backing store as it is now stale.
4156 vm_page_protect(m, VM_PROT_READ);
4157 vfs_clean_one_page(bp, i, m);
4158 swap_pager_unswapped(m);
4159 } else if (m->valid == VM_PAGE_BITS_ALL) {
4161 * When readying a vnode-backed buffer for
4162 * read we must replace any dirty pages with
4163 * a bogus page so dirty data is not destroyed
4164 * when filling gaps.
4166 * To avoid testing whether the page is
4167 * dirty we instead test that the page was
4168 * at some point mapped (m->valid fully
4169 * valid) with the understanding that
4170 * this also covers the dirty case.
4172 bp->b_xio.xio_pages[i] = bogus_page;
4173 bp->b_flags |= B_HASBOGUS;
4175 } else if (m->valid & m->dirty) {
4177 * This case should not occur as partial
4178 * dirtyment can only happen if the buffer
4179 * is B_CACHE, and this code is not entered
4180 * if the buffer is B_CACHE.
4182 kprintf("Warning: vfs_busy_pages - page not "
4183 "fully valid! loff=%jx bpf=%08x "
4184 "idx=%d val=%02x dir=%02x\n",
4185 (uintmax_t)bp->b_loffset, bp->b_flags,
4186 i, m->valid, m->dirty);
4187 vm_page_protect(m, VM_PROT_NONE);
4190 * The page is not valid and can be made
4193 vm_page_protect(m, VM_PROT_NONE);
4198 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4199 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
4204 * This is the easiest place to put the process accounting for the I/O
4208 if (bp->b_cmd == BUF_CMD_READ)
4209 lp->lwp_ru.ru_inblock++;
4211 lp->lwp_ru.ru_oublock++;
4216 * Tell the VM system that the pages associated with this buffer
4217 * are clean. This is used for delayed writes where the data is
4218 * going to go to disk eventually without additional VM intevention.
4220 * NOTE: While we only really need to clean through to b_bcount, we
4221 * just go ahead and clean through to b_bufsize.
4224 vfs_clean_pages(struct buf *bp)
4229 if ((bp->b_flags & B_VMIO) == 0)
4232 KASSERT(bp->b_loffset != NOOFFSET,
4233 ("vfs_clean_pages: no buffer offset"));
4235 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4236 m = bp->b_xio.xio_pages[i];
4237 vfs_clean_one_page(bp, i, m);
4242 * vfs_clean_one_page:
4244 * Set the valid bits and clear the dirty bits in a page within a
4245 * buffer. The range is restricted to the buffer's size and the
4246 * buffer's logical offset might index into the first page.
4248 * The caller has busied or soft-busied the page and it is not mapped,
4249 * test and incorporate the dirty bits into b_dirtyoff/end before
4250 * clearing them. Note that we need to clear the pmap modified bits
4251 * after determining the the page was dirty, vm_page_set_validclean()
4252 * does not do it for us.
4254 * This routine is typically called after a read completes (dirty should
4255 * be zero in that case as we are not called on bogus-replace pages),
4256 * or before a write is initiated.
4259 vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m)
4267 * Calculate offset range within the page but relative to buffer's
4268 * loffset. loffset might be offset into the first page.
4270 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
4271 bcount = bp->b_bcount + xoff; /* offset adjusted */
4277 soff = (pageno << PAGE_SHIFT);
4278 eoff = soff + PAGE_SIZE;
4286 * Test dirty bits and adjust b_dirtyoff/end.
4288 * If dirty pages are incorporated into the bp any prior
4289 * B_NEEDCOMMIT state (NFS) must be cleared because the
4290 * caller has not taken into account the new dirty data.
4292 * If the page was memory mapped the dirty bits might go beyond the
4293 * end of the buffer, but we can't really make the assumption that
4294 * a file EOF straddles the buffer (even though this is the case for
4295 * NFS if B_NEEDCOMMIT is also set). So for the purposes of clearing
4296 * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
4297 * This also saves some console spam.
4299 * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK,
4300 * NFS can handle huge commits but not huge writes.
4302 vm_page_test_dirty(m);
4304 if ((bp->b_flags & B_NEEDCOMMIT) &&
4305 (m->dirty & vm_page_bits(soff & PAGE_MASK, eoff - soff))) {
4307 kprintf("Warning: vfs_clean_one_page: bp %p "
4308 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT"
4309 " cmd %d vd %02x/%02x x/s/e %d %d %d "
4311 bp, (uintmax_t)bp->b_loffset, bp->b_bcount,
4312 bp->b_flags, bp->b_cmd,
4313 m->valid, m->dirty, xoff, soff, eoff,
4314 bp->b_dirtyoff, bp->b_dirtyend);
4315 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
4317 print_backtrace(-1);
4320 * Only clear the pmap modified bits if ALL the dirty bits
4321 * are set, otherwise the system might mis-clear portions
4324 if (m->dirty == VM_PAGE_BITS_ALL &&
4325 (bp->b_flags & B_NEEDCOMMIT) == 0) {
4326 pmap_clear_modify(m);
4328 if (bp->b_dirtyoff > soff - xoff)
4329 bp->b_dirtyoff = soff - xoff;
4330 if (bp->b_dirtyend < eoff - xoff)
4331 bp->b_dirtyend = eoff - xoff;
4335 * Set related valid bits, clear related dirty bits.
4336 * Does not mess with the pmap modified bit.
4338 * WARNING! We cannot just clear all of m->dirty here as the
4339 * buffer cache buffers may use a DEV_BSIZE'd aligned
4340 * block size, or have an odd size (e.g. NFS at file EOF).
4341 * The putpages code can clear m->dirty to 0.
4343 * If a VOP_WRITE generates a buffer cache buffer which
4344 * covers the same space as mapped writable pages the
4345 * buffer flush might not be able to clear all the dirty
4346 * bits and still require a putpages from the VM system
4349 * WARNING! vm_page_set_validclean() currently assumes vm_token
4350 * is held. The page might not be busied (bdwrite() case).
4351 * XXX remove this comment once we've validated that this
4352 * is no longer an issue.
4354 vm_page_set_validclean(m, soff & PAGE_MASK, eoff - soff);
4359 * Similar to vfs_clean_one_page() but sets the bits to valid and dirty.
4360 * The page data is assumed to be valid (there is no zeroing here).
4363 vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m)
4371 * Calculate offset range within the page but relative to buffer's
4372 * loffset. loffset might be offset into the first page.
4374 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
4375 bcount = bp->b_bcount + xoff; /* offset adjusted */
4381 soff = (pageno << PAGE_SHIFT);
4382 eoff = soff + PAGE_SIZE;
4388 vm_page_set_validdirty(m, soff & PAGE_MASK, eoff - soff);
4395 * Clear a buffer. This routine essentially fakes an I/O, so we need
4396 * to clear B_ERROR and B_INVAL.
4398 * Note that while we only theoretically need to clear through b_bcount,
4399 * we go ahead and clear through b_bufsize.
4403 vfs_bio_clrbuf(struct buf *bp)
4407 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
4408 bp->b_flags &= ~(B_INVAL | B_EINTR | B_ERROR);
4409 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4410 (bp->b_loffset & PAGE_MASK) == 0) {
4411 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4412 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
4416 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
4417 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
4418 bzero(bp->b_data, bp->b_bufsize);
4419 bp->b_xio.xio_pages[0]->valid |= mask;
4425 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
4426 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
4427 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
4428 ea = (caddr_t)(vm_offset_t)ulmin(
4429 (u_long)(vm_offset_t)ea,
4430 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
4431 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4432 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
4434 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
4435 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
4439 for (; sa < ea; sa += DEV_BSIZE, j++) {
4440 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
4441 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
4442 bzero(sa, DEV_BSIZE);
4445 bp->b_xio.xio_pages[i]->valid |= mask;
4446 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
4455 * vm_hold_load_pages:
4457 * Load pages into the buffer's address space. The pages are
4458 * allocated from the kernel object in order to reduce interference
4459 * with the any VM paging I/O activity. The range of loaded
4460 * pages will be wired.
4462 * If a page cannot be allocated, the 'pagedaemon' is woken up to
4463 * retrieve the full range (to - from) of pages.
4468 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4474 to = round_page(to);
4475 from = round_page(from);
4476 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4481 * Note: must allocate system pages since blocking here
4482 * could intefere with paging I/O, no matter which
4485 vm_object_hold(&kernel_object);
4486 p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT,
4487 (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
4488 vm_object_drop(&kernel_object);
4491 p->valid = VM_PAGE_BITS_ALL;
4492 vm_page_flag_clear(p, PG_ZERO);
4493 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
4494 bp->b_xio.xio_pages[index] = p;
4501 bp->b_xio.xio_npages = index;
4505 * Allocate a page for a buffer cache buffer.
4507 * If NULL is returned the caller is expected to retry (typically check if
4508 * the page already exists on retry before trying to allocate one).
4510 * NOTE! Low-memory handling is dealt with in b[q]relse(), not here. This
4511 * function will use the system reserve with the hope that the page
4512 * allocations can be returned to PQ_CACHE/PQ_FREE when the caller
4513 * is done with the buffer.
4517 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit)
4519 int vmflags = VM_ALLOC_NORMAL | VM_ALLOC_NULL_OK;
4522 ASSERT_LWKT_TOKEN_HELD(vm_object_token(obj));
4525 * Try a normal allocation first.
4527 p = vm_page_alloc(obj, pg, vmflags);
4530 if (vm_page_lookup(obj, pg))
4532 vm_pageout_deficit += deficit;
4535 * Try again, digging into the system reserve.
4537 * Trying to recover pages from the buffer cache here can deadlock
4538 * against other threads trying to busy underlying pages so we
4539 * depend on the code in brelse() and bqrelse() to free/cache the
4540 * underlying buffer cache pages when memory is low.
4542 if (curthread->td_flags & TDF_SYSTHREAD)
4543 vmflags |= VM_ALLOC_SYSTEM | VM_ALLOC_INTERRUPT;
4545 vmflags |= VM_ALLOC_SYSTEM;
4547 /*recoverbufpages();*/
4548 p = vm_page_alloc(obj, pg, vmflags);
4551 if (vm_page_lookup(obj, pg))
4555 * Wait for memory to free up and try again
4557 if (vm_page_count_severe())
4559 vm_wait(hz / 20 + 1);
4561 p = vm_page_alloc(obj, pg, vmflags);
4564 if (vm_page_lookup(obj, pg))
4568 * Ok, now we are really in trouble.
4571 static struct krate biokrate = { .freq = 1 };
4572 krateprintf(&biokrate,
4573 "Warning: bio_page_alloc: memory exhausted "
4574 "during bufcache page allocation from %s\n",
4575 curthread->td_comm);
4577 if (curthread->td_flags & TDF_SYSTHREAD)
4578 vm_wait(hz / 20 + 1);
4580 vm_wait(hz / 2 + 1);
4585 * vm_hold_free_pages:
4587 * Return pages associated with the buffer back to the VM system.
4589 * The range of pages underlying the buffer's address space will
4590 * be unmapped and un-wired.
4595 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4599 int index, newnpages;
4601 from = round_page(from);
4602 to = round_page(to);
4603 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4606 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4607 p = bp->b_xio.xio_pages[index];
4608 if (p && (index < bp->b_xio.xio_npages)) {
4610 kprintf("vm_hold_free_pages: doffset: %lld, "
4612 (long long)bp->b_bio2.bio_offset,
4613 (long long)bp->b_loffset);
4615 bp->b_xio.xio_pages[index] = NULL;
4617 vm_page_busy_wait(p, FALSE, "vmhldpg");
4618 vm_page_unwire(p, 0);
4622 bp->b_xio.xio_npages = newnpages;
4628 * Map a user buffer into KVM via a pbuf. On return the buffer's
4629 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
4633 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
4644 * bp had better have a command and it better be a pbuf.
4646 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4647 KKASSERT(bp->b_flags & B_PAGING);
4648 KKASSERT(bp->b_kvabase);
4654 * Map the user data into KVM. Mappings have to be page-aligned.
4656 addr = (caddr_t)trunc_page((vm_offset_t)udata);
4659 vmprot = VM_PROT_READ;
4660 if (bp->b_cmd == BUF_CMD_READ)
4661 vmprot |= VM_PROT_WRITE;
4663 while (addr < udata + bytes) {
4665 * Do the vm_fault if needed; do the copy-on-write thing
4666 * when reading stuff off device into memory.
4668 * vm_fault_page*() returns a held VM page.
4670 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
4671 va = trunc_page(va);
4673 m = vm_fault_page_quick(va, vmprot, &error);
4675 for (i = 0; i < pidx; ++i) {
4676 vm_page_unhold(bp->b_xio.xio_pages[i]);
4677 bp->b_xio.xio_pages[i] = NULL;
4681 bp->b_xio.xio_pages[pidx] = m;
4687 * Map the page array and set the buffer fields to point to
4688 * the mapped data buffer.
4690 if (pidx > btoc(MAXPHYS))
4691 panic("vmapbuf: mapped more than MAXPHYS");
4692 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
4694 bp->b_xio.xio_npages = pidx;
4695 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
4696 bp->b_bcount = bytes;
4697 bp->b_bufsize = bytes;
4704 * Free the io map PTEs associated with this IO operation.
4705 * We also invalidate the TLB entries and restore the original b_addr.
4708 vunmapbuf(struct buf *bp)
4713 KKASSERT(bp->b_flags & B_PAGING);
4715 npages = bp->b_xio.xio_npages;
4716 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4717 for (pidx = 0; pidx < npages; ++pidx) {
4718 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
4719 bp->b_xio.xio_pages[pidx] = NULL;
4721 bp->b_xio.xio_npages = 0;
4722 bp->b_data = bp->b_kvabase;
4726 * Scan all buffers in the system and issue the callback.
4729 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
4735 for (n = 0; n < nbuf; ++n) {
4736 if ((error = callback(&buf[n], info)) < 0) {
4746 * nestiobuf_iodone: biodone callback for nested buffers and propagate
4747 * completion to the master buffer.
4750 nestiobuf_iodone(struct bio *bio)
4753 struct buf *mbp, *bp;
4754 struct devstat *stats;
4759 mbio = bio->bio_caller_info1.ptr;
4760 stats = bio->bio_caller_info2.ptr;
4761 mbp = mbio->bio_buf;
4763 KKASSERT(bp->b_bcount <= bp->b_bufsize);
4764 KKASSERT(mbp != bp);
4766 error = bp->b_error;
4767 if (bp->b_error == 0 &&
4768 (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) {
4770 * Not all got transfered, raise an error. We have no way to
4771 * propagate these conditions to mbp.
4776 donebytes = bp->b_bufsize;
4780 nestiobuf_done(mbio, donebytes, error, stats);
4784 nestiobuf_done(struct bio *mbio, int donebytes, int error, struct devstat *stats)
4788 mbp = mbio->bio_buf;
4790 KKASSERT((int)(intptr_t)mbio->bio_driver_info > 0);
4793 * If an error occured, propagate it to the master buffer.
4795 * Several biodone()s may wind up running concurrently so
4796 * use an atomic op to adjust b_flags.
4799 mbp->b_error = error;
4800 atomic_set_int(&mbp->b_flags, B_ERROR);
4804 * Decrement the operations in progress counter and terminate the
4805 * I/O if this was the last bit.
4807 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4810 devstat_end_transaction_buf(stats, mbp);
4816 * Initialize a nestiobuf for use. Set an initial count of 1 to prevent
4817 * the mbio from being biodone()'d while we are still adding sub-bios to
4821 nestiobuf_init(struct bio *bio)
4823 bio->bio_driver_info = (void *)1;
4827 * The BIOs added to the nestedio have already been started, remove the
4828 * count that placeheld our mbio and biodone() it if the count would
4832 nestiobuf_start(struct bio *mbio)
4834 struct buf *mbp = mbio->bio_buf;
4837 * Decrement the operations in progress counter and terminate the
4838 * I/O if this was the last bit.
4840 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4841 if (mbp->b_flags & B_ERROR)
4842 mbp->b_resid = mbp->b_bcount;
4850 * Set an intermediate error prior to calling nestiobuf_start()
4853 nestiobuf_error(struct bio *mbio, int error)
4855 struct buf *mbp = mbio->bio_buf;
4858 mbp->b_error = error;
4859 atomic_set_int(&mbp->b_flags, B_ERROR);
4864 * nestiobuf_add: setup a "nested" buffer.
4866 * => 'mbp' is a "master" buffer which is being divided into sub pieces.
4867 * => 'bp' should be a buffer allocated by getiobuf.
4868 * => 'offset' is a byte offset in the master buffer.
4869 * => 'size' is a size in bytes of this nested buffer.
4872 nestiobuf_add(struct bio *mbio, struct buf *bp, int offset, size_t size, struct devstat *stats)
4874 struct buf *mbp = mbio->bio_buf;
4875 struct vnode *vp = mbp->b_vp;
4877 KKASSERT(mbp->b_bcount >= offset + size);
4879 atomic_add_int((int *)&mbio->bio_driver_info, 1);
4881 /* kernel needs to own the lock for it to be released in biodone */
4884 bp->b_cmd = mbp->b_cmd;
4885 bp->b_bio1.bio_done = nestiobuf_iodone;
4886 bp->b_data = (char *)mbp->b_data + offset;
4887 bp->b_resid = bp->b_bcount = size;
4888 bp->b_bufsize = bp->b_bcount;
4890 bp->b_bio1.bio_track = NULL;
4891 bp->b_bio1.bio_caller_info1.ptr = mbio;
4892 bp->b_bio1.bio_caller_info2.ptr = stats;
4896 * print out statistics from the current status of the buffer pool
4897 * this can be toggeled by the system control option debug.syncprt
4906 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
4907 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
4909 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
4911 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4914 spin_lock(&bufqspin);
4915 TAILQ_FOREACH(bp, dp, b_freelist) {
4916 if (bp->b_flags & B_MARKER)
4918 counts[bp->b_bufsize/PAGE_SIZE]++;
4921 spin_unlock(&bufqspin);
4923 kprintf("%s: total-%d", bname[i], count);
4924 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4926 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
4934 DB_SHOW_COMMAND(buffer, db_show_buffer)
4937 struct buf *bp = (struct buf *)addr;
4940 db_printf("usage: show buffer <addr>\n");
4944 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4945 db_printf("b_cmd = %d\n", bp->b_cmd);
4946 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
4947 "b_resid = %d\n, b_data = %p, "
4948 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
4949 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4951 (long long)bp->b_bio2.bio_offset,
4952 (long long)(bp->b_bio2.bio_next ?
4953 bp->b_bio2.bio_next->bio_offset : (off_t)-1));
4954 if (bp->b_xio.xio_npages) {
4956 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
4957 bp->b_xio.xio_npages);
4958 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4960 m = bp->b_xio.xio_pages[i];
4961 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4962 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4963 if ((i + 1) < bp->b_xio.xio_npages)