2 * Copyright (c) 1994,1997 John S. Dyson
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice immediately at the beginning of the file, without modification,
10 * this list of conditions, and the following disclaimer.
11 * 2. Absolutely no warranty of function or purpose is made by the author
14 * $FreeBSD: src/sys/kern/vfs_bio.c,v 1.242.2.20 2003/05/28 18:38:10 alc Exp $
15 * $DragonFly: src/sys/kern/vfs_bio.c,v 1.115 2008/08/13 11:02:31 swildner Exp $
19 * this file contains a new buffer I/O scheme implementing a coherent
20 * VM object and buffer cache scheme. Pains have been taken to make
21 * sure that the performance degradation associated with schemes such
22 * as this is not realized.
24 * Author: John S. Dyson
25 * Significant help during the development and debugging phases
26 * had been provided by David Greenman, also of the FreeBSD core team.
28 * see man buf(9) for more info.
31 #include <sys/param.h>
32 #include <sys/systm.h>
35 #include <sys/eventhandler.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
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 struct spinlock bufspin = SPINLOCK_INITIALIZER(&bufspin);
93 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
95 struct buf *buf; /* buffer header pool */
97 static void vfs_clean_pages(struct buf *bp);
98 static void vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m);
99 static void vfs_vmio_release(struct buf *bp);
100 static int flushbufqueues(bufq_type_t q);
101 static vm_page_t bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit);
103 static void bd_signal(int totalspace);
104 static void buf_daemon(void);
105 static void buf_daemon_hw(void);
108 * bogus page -- for I/O to/from partially complete buffers
109 * this is a temporary solution to the problem, but it is not
110 * really that bad. it would be better to split the buffer
111 * for input in the case of buffers partially already in memory,
112 * but the code is intricate enough already.
114 vm_page_t bogus_page;
117 * These are all static, but make the ones we export globals so we do
118 * not need to use compiler magic.
120 int bufspace, maxbufspace,
121 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
122 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
123 static int lorunningspace, hirunningspace, runningbufreq;
124 int dirtybufspace, dirtybufspacehw, lodirtybufspace, hidirtybufspace;
125 int dirtybufcount, dirtybufcounthw;
126 int runningbufspace, runningbufcount;
127 static int getnewbufcalls;
128 static int getnewbufrestarts;
129 static int recoverbufcalls;
130 static int needsbuffer; /* locked by needsbuffer_spin */
131 static int bd_request; /* locked by needsbuffer_spin */
132 static int bd_request_hw; /* locked by needsbuffer_spin */
133 static u_int bd_wake_ary[BD_WAKE_SIZE];
134 static u_int bd_wake_index;
135 static u_int vm_cycle_point = ACT_INIT + ACT_ADVANCE * 6;
136 static struct spinlock needsbuffer_spin;
137 static int debug_commit;
139 static struct thread *bufdaemon_td;
140 static struct thread *bufdaemonhw_td;
144 * Sysctls for operational control of the buffer cache.
146 SYSCTL_INT(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
147 "Number of dirty buffers to flush before bufdaemon becomes inactive");
148 SYSCTL_INT(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
149 "High watermark used to trigger explicit flushing of dirty buffers");
150 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
151 "Minimum amount of buffer space required for active I/O");
152 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
153 "Maximum amount of buffer space to usable for active I/O");
154 SYSCTL_UINT(_vfs, OID_AUTO, vm_cycle_point, CTLFLAG_RW, &vm_cycle_point, 0,
155 "Recycle pages to active or inactive queue transition pt 0-64");
157 * Sysctls determining current state of the buffer cache.
159 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
160 "Total number of buffers in buffer cache");
161 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
162 "Pending bytes of dirty buffers (all)");
163 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
164 "Pending bytes of dirty buffers (heavy weight)");
165 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
166 "Pending number of dirty buffers");
167 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
168 "Pending number of dirty buffers (heavy weight)");
169 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
170 "I/O bytes currently in progress due to asynchronous writes");
171 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
172 "I/O buffers currently in progress due to asynchronous writes");
173 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
174 "Hard limit on maximum amount of memory usable for buffer space");
175 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
176 "Soft limit on maximum amount of memory usable for buffer space");
177 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
178 "Minimum amount of memory to reserve for system buffer space");
179 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
180 "Amount of memory available for buffers");
181 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
182 0, "Maximum amount of memory reserved for buffers using malloc");
183 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
184 "Amount of memory left for buffers using malloc-scheme");
185 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
186 "New buffer header acquisition requests");
187 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
188 0, "New buffer header acquisition restarts");
189 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
190 "Recover VM space in an emergency");
191 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
192 "Buffer acquisition restarts due to fragmented buffer map");
193 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
194 "Amount of time KVA space was deallocated in an arbitrary buffer");
195 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
196 "Amount of time buffer re-use operations were successful");
197 SYSCTL_INT(_vfs, OID_AUTO, debug_commit, CTLFLAG_RW, &debug_commit, 0, "");
198 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
199 "sizeof(struct buf)");
201 char *buf_wmesg = BUF_WMESG;
203 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
204 #define VFS_BIO_NEED_UNUSED02 0x02
205 #define VFS_BIO_NEED_UNUSED04 0x04
206 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
211 * Called when buffer space is potentially available for recovery.
212 * getnewbuf() will block on this flag when it is unable to free
213 * sufficient buffer space. Buffer space becomes recoverable when
214 * bp's get placed back in the queues.
221 * If someone is waiting for BUF space, wake them up. Even
222 * though we haven't freed the kva space yet, the waiting
223 * process will be able to now.
225 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
226 spin_lock_wr(&needsbuffer_spin);
227 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
228 spin_unlock_wr(&needsbuffer_spin);
229 wakeup(&needsbuffer);
236 * Accounting for I/O in progress.
240 runningbufwakeup(struct buf *bp)
245 if ((totalspace = bp->b_runningbufspace) != 0) {
246 atomic_subtract_int(&runningbufspace, totalspace);
247 atomic_subtract_int(&runningbufcount, 1);
248 bp->b_runningbufspace = 0;
251 * see waitrunningbufspace() for limit test.
253 limit = hirunningspace * 2 / 3;
254 if (runningbufreq && runningbufspace <= limit) {
256 wakeup(&runningbufreq);
258 bd_signal(totalspace);
265 * Called when a buffer has been added to one of the free queues to
266 * account for the buffer and to wakeup anyone waiting for free buffers.
267 * This typically occurs when large amounts of metadata are being handled
268 * by the buffer cache ( else buffer space runs out first, usually ).
276 spin_lock_wr(&needsbuffer_spin);
277 needsbuffer &= ~VFS_BIO_NEED_ANY;
278 spin_unlock_wr(&needsbuffer_spin);
279 wakeup(&needsbuffer);
284 * waitrunningbufspace()
286 * Wait for the amount of running I/O to drop to hirunningspace * 2 / 3.
287 * This is the point where write bursting stops so we don't want to wait
288 * for the running amount to drop below it (at least if we still want bioq
291 * The caller may be using this function to block in a tight loop, we
292 * must block while runningbufspace is greater then or equal to
293 * hirunningspace * 2 / 3.
295 * And even with that it may not be enough, due to the presence of
296 * B_LOCKED dirty buffers, so also wait for at least one running buffer
300 waitrunningbufspace(void)
302 int limit = hirunningspace * 2 / 3;
305 if (runningbufspace > limit) {
306 while (runningbufspace > limit) {
308 tsleep(&runningbufreq, 0, "wdrn1", 0);
310 } else if (runningbufspace) {
312 tsleep(&runningbufreq, 0, "wdrn2", 1);
318 * buf_dirty_count_severe:
320 * Return true if we have too many dirty buffers.
323 buf_dirty_count_severe(void)
325 return (runningbufspace + dirtybufspace >= hidirtybufspace ||
326 dirtybufcount >= nbuf / 2);
330 * Return true if the amount of running I/O is severe and BIOQ should
334 buf_runningbufspace_severe(void)
336 return (runningbufspace >= hirunningspace * 2 / 3);
340 * vfs_buf_test_cache:
342 * Called when a buffer is extended. This function clears the B_CACHE
343 * bit if the newly extended portion of the buffer does not contain
346 * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer
347 * cache buffers. The VM pages remain dirty, as someone had mmap()'d
348 * them while a clean buffer was present.
352 vfs_buf_test_cache(struct buf *bp,
353 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
356 if (bp->b_flags & B_CACHE) {
357 int base = (foff + off) & PAGE_MASK;
358 if (vm_page_is_valid(m, base, size) == 0)
359 bp->b_flags &= ~B_CACHE;
366 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
375 if (dirtybufspace < lodirtybufspace && dirtybufcount < nbuf / 2)
378 if (bd_request == 0 &&
379 (dirtybufspace - dirtybufspacehw > lodirtybufspace / 2 ||
380 dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
381 spin_lock_wr(&needsbuffer_spin);
383 spin_unlock_wr(&needsbuffer_spin);
386 if (bd_request_hw == 0 &&
387 (dirtybufspacehw > lodirtybufspace / 2 ||
388 dirtybufcounthw >= nbuf / 2)) {
389 spin_lock_wr(&needsbuffer_spin);
391 spin_unlock_wr(&needsbuffer_spin);
392 wakeup(&bd_request_hw);
399 * Get the buf_daemon heated up when the number of running and dirty
400 * buffers exceeds the mid-point.
402 * Return the total number of dirty bytes past the second mid point
403 * as a measure of how much excess dirty data there is in the system.
414 mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
416 totalspace = runningbufspace + dirtybufspace;
417 if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
419 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
420 if (totalspace >= mid2)
421 return(totalspace - mid2);
429 * Wait for the buffer cache to flush (totalspace) bytes worth of
430 * buffers, then return.
432 * Regardless this function blocks while the number of dirty buffers
433 * exceeds hidirtybufspace.
438 bd_wait(int totalspace)
443 if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
446 while (totalspace > 0) {
448 if (totalspace > runningbufspace + dirtybufspace)
449 totalspace = runningbufspace + dirtybufspace;
450 count = totalspace / BKVASIZE;
451 if (count >= BD_WAKE_SIZE)
452 count = BD_WAKE_SIZE - 1;
454 spin_lock_wr(&needsbuffer_spin);
455 i = (bd_wake_index + count) & BD_WAKE_MASK;
457 tsleep_interlock(&bd_wake_ary[i], 0);
458 spin_unlock_wr(&needsbuffer_spin);
459 tsleep(&bd_wake_ary[i], PINTERLOCKED, "flstik", hz);
461 totalspace = runningbufspace + dirtybufspace - hidirtybufspace;
468 * This function is called whenever runningbufspace or dirtybufspace
469 * is reduced. Track threads waiting for run+dirty buffer I/O
475 bd_signal(int totalspace)
479 if (totalspace > 0) {
480 if (totalspace > BKVASIZE * BD_WAKE_SIZE)
481 totalspace = BKVASIZE * BD_WAKE_SIZE;
482 spin_lock_wr(&needsbuffer_spin);
483 while (totalspace > 0) {
486 if (bd_wake_ary[i]) {
488 spin_unlock_wr(&needsbuffer_spin);
489 wakeup(&bd_wake_ary[i]);
490 spin_lock_wr(&needsbuffer_spin);
492 totalspace -= BKVASIZE;
494 spin_unlock_wr(&needsbuffer_spin);
499 * BIO tracking support routines.
501 * Release a ref on a bio_track. Wakeup requests are atomically released
502 * along with the last reference so bk_active will never wind up set to
509 bio_track_rel(struct bio_track *track)
517 active = track->bk_active;
518 if (active == 1 && atomic_cmpset_int(&track->bk_active, 1, 0))
522 * Full-on. Note that the wait flag is only atomically released on
523 * the 1->0 count transition.
525 * We check for a negative count transition using bit 30 since bit 31
526 * has a different meaning.
529 desired = (active & 0x7FFFFFFF) - 1;
531 desired |= active & 0x80000000;
532 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
533 if (desired & 0x40000000)
534 panic("bio_track_rel: bad count: %p\n", track);
535 if (active & 0x80000000)
539 active = track->bk_active;
544 * Wait for the tracking count to reach 0.
546 * Use atomic ops such that the wait flag is only set atomically when
547 * bk_active is non-zero.
552 bio_track_wait(struct bio_track *track, int slp_flags, int slp_timo)
561 if (track->bk_active == 0)
565 * Full-on. Note that the wait flag may only be atomically set if
566 * the active count is non-zero.
569 while ((active = track->bk_active) != 0) {
570 desired = active | 0x80000000;
571 tsleep_interlock(track, slp_flags);
572 if (active == desired ||
573 atomic_cmpset_int(&track->bk_active, active, desired)) {
574 error = tsleep(track, slp_flags | PINTERLOCKED,
586 * Load time initialisation of the buffer cache, called from machine
587 * dependant initialization code.
593 vm_offset_t bogus_offset;
596 spin_init(&needsbuffer_spin);
598 /* next, make a null set of free lists */
599 for (i = 0; i < BUFFER_QUEUES; i++)
600 TAILQ_INIT(&bufqueues[i]);
602 /* finally, initialize each buffer header and stick on empty q */
603 for (i = 0; i < nbuf; i++) {
605 bzero(bp, sizeof *bp);
606 bp->b_flags = B_INVAL; /* we're just an empty header */
607 bp->b_cmd = BUF_CMD_DONE;
608 bp->b_qindex = BQUEUE_EMPTY;
610 xio_init(&bp->b_xio);
613 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
617 * maxbufspace is the absolute maximum amount of buffer space we are
618 * allowed to reserve in KVM and in real terms. The absolute maximum
619 * is nominally used by buf_daemon. hibufspace is the nominal maximum
620 * used by most other processes. The differential is required to
621 * ensure that buf_daemon is able to run when other processes might
622 * be blocked waiting for buffer space.
624 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
625 * this may result in KVM fragmentation which is not handled optimally
628 maxbufspace = nbuf * BKVASIZE;
629 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
630 lobufspace = hibufspace - MAXBSIZE;
632 lorunningspace = 512 * 1024;
633 /* hirunningspace -- see below */
636 * Limit the amount of malloc memory since it is wired permanently
637 * into the kernel space. Even though this is accounted for in
638 * the buffer allocation, we don't want the malloced region to grow
639 * uncontrolled. The malloc scheme improves memory utilization
640 * significantly on average (small) directories.
642 maxbufmallocspace = hibufspace / 20;
645 * Reduce the chance of a deadlock occuring by limiting the number
646 * of delayed-write dirty buffers we allow to stack up.
648 * We don't want too much actually queued to the device at once
649 * (XXX this needs to be per-mount!), because the buffers will
650 * wind up locked for a very long period of time while the I/O
653 hidirtybufspace = hibufspace / 2; /* dirty + running */
654 hirunningspace = hibufspace / 16; /* locked & queued to device */
655 if (hirunningspace < 1024 * 1024)
656 hirunningspace = 1024 * 1024;
661 lodirtybufspace = hidirtybufspace / 2;
664 * Maximum number of async ops initiated per buf_daemon loop. This is
665 * somewhat of a hack at the moment, we really need to limit ourselves
666 * based on the number of bytes of I/O in-transit that were initiated
670 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
671 bogus_page = vm_page_alloc(&kernel_object,
672 (bogus_offset >> PAGE_SHIFT),
674 vmstats.v_wire_count++;
679 * Initialize the embedded bio structures
682 initbufbio(struct buf *bp)
684 bp->b_bio1.bio_buf = bp;
685 bp->b_bio1.bio_prev = NULL;
686 bp->b_bio1.bio_offset = NOOFFSET;
687 bp->b_bio1.bio_next = &bp->b_bio2;
688 bp->b_bio1.bio_done = NULL;
689 bp->b_bio1.bio_flags = 0;
691 bp->b_bio2.bio_buf = bp;
692 bp->b_bio2.bio_prev = &bp->b_bio1;
693 bp->b_bio2.bio_offset = NOOFFSET;
694 bp->b_bio2.bio_next = NULL;
695 bp->b_bio2.bio_done = NULL;
696 bp->b_bio2.bio_flags = 0;
700 * Reinitialize the embedded bio structures as well as any additional
701 * translation cache layers.
704 reinitbufbio(struct buf *bp)
708 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
709 bio->bio_done = NULL;
710 bio->bio_offset = NOOFFSET;
715 * Push another BIO layer onto an existing BIO and return it. The new
716 * BIO layer may already exist, holding cached translation data.
719 push_bio(struct bio *bio)
723 if ((nbio = bio->bio_next) == NULL) {
724 int index = bio - &bio->bio_buf->b_bio_array[0];
725 if (index >= NBUF_BIO - 1) {
726 panic("push_bio: too many layers bp %p\n",
729 nbio = &bio->bio_buf->b_bio_array[index + 1];
730 bio->bio_next = nbio;
731 nbio->bio_prev = bio;
732 nbio->bio_buf = bio->bio_buf;
733 nbio->bio_offset = NOOFFSET;
734 nbio->bio_done = NULL;
735 nbio->bio_next = NULL;
737 KKASSERT(nbio->bio_done == NULL);
742 * Pop a BIO translation layer, returning the previous layer. The
743 * must have been previously pushed.
746 pop_bio(struct bio *bio)
748 return(bio->bio_prev);
752 clearbiocache(struct bio *bio)
755 bio->bio_offset = NOOFFSET;
763 * Free the KVA allocation for buffer 'bp'.
765 * Must be called from a critical section as this is the only locking for
768 * Since this call frees up buffer space, we call bufspacewakeup().
773 bfreekva(struct buf *bp)
780 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
781 vm_map_lock(&buffer_map);
782 bufspace -= bp->b_kvasize;
783 vm_map_delete(&buffer_map,
784 (vm_offset_t) bp->b_kvabase,
785 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
788 vm_map_unlock(&buffer_map);
789 vm_map_entry_release(count);
799 * Remove the buffer from the appropriate free list.
802 _bremfree(struct buf *bp)
804 if (bp->b_qindex != BQUEUE_NONE) {
805 KASSERT(BUF_REFCNTNB(bp) == 1,
806 ("bremfree: bp %p not locked",bp));
807 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
808 bp->b_qindex = BQUEUE_NONE;
810 if (BUF_REFCNTNB(bp) <= 1)
811 panic("bremfree: removing a buffer not on a queue");
816 bremfree(struct buf *bp)
818 spin_lock_wr(&bufspin);
820 spin_unlock_wr(&bufspin);
824 bremfree_locked(struct buf *bp)
832 * Get a buffer with the specified data. Look in the cache first. We
833 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
834 * is set, the buffer is valid and we do not have to do anything ( see
840 bread(struct vnode *vp, off_t loffset, int size, struct buf **bpp)
844 bp = getblk(vp, loffset, size, 0, 0);
847 /* if not found in cache, do some I/O */
848 if ((bp->b_flags & B_CACHE) == 0) {
850 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
851 bp->b_cmd = BUF_CMD_READ;
852 bp->b_bio1.bio_done = biodone_sync;
853 bp->b_bio1.bio_flags |= BIO_SYNC;
854 vfs_busy_pages(vp, bp);
855 vn_strategy(vp, &bp->b_bio1);
857 return (biowait(&bp->b_bio1, "biord"));
865 * Operates like bread, but also starts asynchronous I/O on
866 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
867 * to initiating I/O . If B_CACHE is set, the buffer is valid
868 * and we do not have to do anything.
873 breadn(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
874 int *rabsize, int cnt, struct buf **bpp)
876 struct buf *bp, *rabp;
878 int rv = 0, readwait = 0;
880 *bpp = bp = getblk(vp, loffset, size, 0, 0);
882 /* if not found in cache, do some I/O */
883 if ((bp->b_flags & B_CACHE) == 0) {
885 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
886 bp->b_cmd = BUF_CMD_READ;
887 bp->b_bio1.bio_done = biodone_sync;
888 bp->b_bio1.bio_flags |= BIO_SYNC;
889 vfs_busy_pages(vp, bp);
890 vn_strategy(vp, &bp->b_bio1);
895 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
896 if (inmem(vp, *raoffset))
898 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
900 if ((rabp->b_flags & B_CACHE) == 0) {
902 rabp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
903 rabp->b_cmd = BUF_CMD_READ;
904 vfs_busy_pages(vp, rabp);
906 vn_strategy(vp, &rabp->b_bio1);
913 rv = biowait(&bp->b_bio1, "biord");
920 * Synchronous write, waits for completion.
922 * Write, release buffer on completion. (Done by iodone
923 * if async). Do not bother writing anything if the buffer
926 * Note that we set B_CACHE here, indicating that buffer is
927 * fully valid and thus cacheable. This is true even of NFS
928 * now so we set it generally. This could be set either here
929 * or in biodone() since the I/O is synchronous. We put it
933 bwrite(struct buf *bp)
937 if (bp->b_flags & B_INVAL) {
941 if (BUF_REFCNTNB(bp) == 0)
942 panic("bwrite: buffer is not busy???");
944 /* Mark the buffer clean */
947 bp->b_flags &= ~(B_ERROR | B_EINTR);
948 bp->b_flags |= B_CACHE;
949 bp->b_cmd = BUF_CMD_WRITE;
950 bp->b_bio1.bio_done = biodone_sync;
951 bp->b_bio1.bio_flags |= BIO_SYNC;
952 vfs_busy_pages(bp->b_vp, bp);
955 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
956 * valid for vnode-backed buffers.
958 bp->b_runningbufspace = bp->b_bufsize;
959 if (bp->b_runningbufspace) {
960 runningbufspace += bp->b_runningbufspace;
964 vn_strategy(bp->b_vp, &bp->b_bio1);
965 error = biowait(&bp->b_bio1, "biows");
973 * Asynchronous write. Start output on a buffer, but do not wait for
974 * it to complete. The buffer is released when the output completes.
976 * bwrite() ( or the VOP routine anyway ) is responsible for handling
977 * B_INVAL buffers. Not us.
980 bawrite(struct buf *bp)
982 if (bp->b_flags & B_INVAL) {
986 if (BUF_REFCNTNB(bp) == 0)
987 panic("bwrite: buffer is not busy???");
989 /* Mark the buffer clean */
992 bp->b_flags &= ~(B_ERROR | B_EINTR);
993 bp->b_flags |= B_CACHE;
994 bp->b_cmd = BUF_CMD_WRITE;
995 KKASSERT(bp->b_bio1.bio_done == NULL);
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 bp->b_runningbufspace = bp->b_bufsize;
1003 if (bp->b_runningbufspace) {
1004 runningbufspace += bp->b_runningbufspace;
1009 vn_strategy(bp->b_vp, &bp->b_bio1);
1015 * Ordered write. Start output on a buffer, and flag it so that the
1016 * device will write it in the order it was queued. The buffer is
1017 * released when the output completes. bwrite() ( or the VOP routine
1018 * anyway ) is responsible for handling B_INVAL buffers.
1021 bowrite(struct buf *bp)
1023 bp->b_flags |= B_ORDERED;
1031 * Delayed write. (Buffer is marked dirty). Do not bother writing
1032 * anything if the buffer is marked invalid.
1034 * Note that since the buffer must be completely valid, we can safely
1035 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1036 * biodone() in order to prevent getblk from writing the buffer
1037 * out synchronously.
1040 bdwrite(struct buf *bp)
1042 if (BUF_REFCNTNB(bp) == 0)
1043 panic("bdwrite: buffer is not busy");
1045 if (bp->b_flags & B_INVAL) {
1052 * Set B_CACHE, indicating that the buffer is fully valid. This is
1053 * true even of NFS now.
1055 bp->b_flags |= B_CACHE;
1058 * This bmap keeps the system from needing to do the bmap later,
1059 * perhaps when the system is attempting to do a sync. Since it
1060 * is likely that the indirect block -- or whatever other datastructure
1061 * that the filesystem needs is still in memory now, it is a good
1062 * thing to do this. Note also, that if the pageout daemon is
1063 * requesting a sync -- there might not be enough memory to do
1064 * the bmap then... So, this is important to do.
1066 if (bp->b_bio2.bio_offset == NOOFFSET) {
1067 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
1068 NULL, NULL, BUF_CMD_WRITE);
1072 * Because the underlying pages may still be mapped and
1073 * writable trying to set the dirty buffer (b_dirtyoff/end)
1074 * range here will be inaccurate.
1076 * However, we must still clean the pages to satisfy the
1077 * vnode_pager and pageout daemon, so theythink the pages
1078 * have been "cleaned". What has really occured is that
1079 * they've been earmarked for later writing by the buffer
1082 * So we get the b_dirtyoff/end update but will not actually
1083 * depend on it (NFS that is) until the pages are busied for
1086 vfs_clean_pages(bp);
1090 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1091 * due to the softdep code.
1098 * Turn buffer into delayed write request by marking it B_DELWRI.
1099 * B_RELBUF and B_NOCACHE must be cleared.
1101 * We reassign the buffer to itself to properly update it in the
1102 * dirty/clean lists.
1104 * Must be called from a critical section.
1105 * The buffer must be on BQUEUE_NONE.
1108 bdirty(struct buf *bp)
1110 KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1111 if (bp->b_flags & B_NOCACHE) {
1112 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
1113 bp->b_flags &= ~B_NOCACHE;
1115 if (bp->b_flags & B_INVAL) {
1116 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
1118 bp->b_flags &= ~B_RELBUF;
1120 if ((bp->b_flags & B_DELWRI) == 0) {
1121 bp->b_flags |= B_DELWRI;
1123 atomic_add_int(&dirtybufcount, 1);
1124 dirtybufspace += bp->b_bufsize;
1125 if (bp->b_flags & B_HEAVY) {
1126 atomic_add_int(&dirtybufcounthw, 1);
1127 atomic_add_int(&dirtybufspacehw, bp->b_bufsize);
1134 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
1135 * needs to be flushed with a different buf_daemon thread to avoid
1136 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
1139 bheavy(struct buf *bp)
1141 if ((bp->b_flags & B_HEAVY) == 0) {
1142 bp->b_flags |= B_HEAVY;
1143 if (bp->b_flags & B_DELWRI) {
1144 atomic_add_int(&dirtybufcounthw, 1);
1145 atomic_add_int(&dirtybufspacehw, bp->b_bufsize);
1153 * Clear B_DELWRI for buffer.
1155 * Must be called from a critical section.
1157 * The buffer is typically on BQUEUE_NONE but there is one case in
1158 * brelse() that calls this function after placing the buffer on
1159 * a different queue.
1164 bundirty(struct buf *bp)
1166 if (bp->b_flags & B_DELWRI) {
1167 bp->b_flags &= ~B_DELWRI;
1169 atomic_subtract_int(&dirtybufcount, 1);
1170 atomic_subtract_int(&dirtybufspace, bp->b_bufsize);
1171 if (bp->b_flags & B_HEAVY) {
1172 atomic_subtract_int(&dirtybufcounthw, 1);
1173 atomic_subtract_int(&dirtybufspacehw, bp->b_bufsize);
1175 bd_signal(bp->b_bufsize);
1178 * Since it is now being written, we can clear its deferred write flag.
1180 bp->b_flags &= ~B_DEFERRED;
1186 * Release a busy buffer and, if requested, free its resources. The
1187 * buffer will be stashed in the appropriate bufqueue[] allowing it
1188 * to be accessed later as a cache entity or reused for other purposes.
1193 brelse(struct buf *bp)
1196 int saved_flags = bp->b_flags;
1199 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1202 * If B_NOCACHE is set we are being asked to destroy the buffer and
1203 * its backing store. Clear B_DELWRI.
1205 * B_NOCACHE is set in two cases: (1) when the caller really wants
1206 * to destroy the buffer and backing store and (2) when the caller
1207 * wants to destroy the buffer and backing store after a write
1210 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1214 if ((bp->b_flags & (B_INVAL | B_DELWRI)) == B_DELWRI) {
1216 * A re-dirtied buffer is only subject to destruction
1217 * by B_INVAL. B_ERROR and B_NOCACHE are ignored.
1219 /* leave buffer intact */
1220 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1221 (bp->b_bufsize <= 0)) {
1223 * Either a failed read or we were asked to free or not
1224 * cache the buffer. This path is reached with B_DELWRI
1225 * set only if B_INVAL is already set. B_NOCACHE governs
1226 * backing store destruction.
1228 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1229 * buffer cannot be immediately freed.
1231 bp->b_flags |= B_INVAL;
1232 if (LIST_FIRST(&bp->b_dep) != NULL) {
1237 if (bp->b_flags & B_DELWRI) {
1238 atomic_subtract_int(&dirtybufcount, 1);
1239 atomic_subtract_int(&dirtybufspace, bp->b_bufsize);
1240 if (bp->b_flags & B_HEAVY) {
1241 atomic_subtract_int(&dirtybufcounthw, 1);
1242 atomic_subtract_int(&dirtybufspacehw, bp->b_bufsize);
1244 bd_signal(bp->b_bufsize);
1246 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1250 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1251 * If vfs_vmio_release() is called with either bit set, the
1252 * underlying pages may wind up getting freed causing a previous
1253 * write (bdwrite()) to get 'lost' because pages associated with
1254 * a B_DELWRI bp are marked clean. Pages associated with a
1255 * B_LOCKED buffer may be mapped by the filesystem.
1257 * If we want to release the buffer ourselves (rather then the
1258 * originator asking us to release it), give the originator a
1259 * chance to countermand the release by setting B_LOCKED.
1261 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1262 * if B_DELWRI is set.
1264 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1265 * on pages to return pages to the VM page queues.
1267 if (bp->b_flags & (B_DELWRI | B_LOCKED)) {
1268 bp->b_flags &= ~B_RELBUF;
1269 } else if (vm_page_count_severe()) {
1270 if (LIST_FIRST(&bp->b_dep) != NULL) {
1272 buf_deallocate(bp); /* can set B_LOCKED */
1275 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1276 bp->b_flags &= ~B_RELBUF;
1278 bp->b_flags |= B_RELBUF;
1282 * Make sure b_cmd is clear. It may have already been cleared by
1285 * At this point destroying the buffer is governed by the B_INVAL
1286 * or B_RELBUF flags.
1288 bp->b_cmd = BUF_CMD_DONE;
1291 * VMIO buffer rundown. Make sure the VM page array is restored
1292 * after an I/O may have replaces some of the pages with bogus pages
1293 * in order to not destroy dirty pages in a fill-in read.
1295 * Note that due to the code above, if a buffer is marked B_DELWRI
1296 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1297 * B_INVAL may still be set, however.
1299 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1300 * but not the backing store. B_NOCACHE will destroy the backing
1303 * Note that dirty NFS buffers contain byte-granular write ranges
1304 * and should not be destroyed w/ B_INVAL even if the backing store
1307 if (bp->b_flags & B_VMIO) {
1309 * Rundown for VMIO buffers which are not dirty NFS buffers.
1321 * Get the base offset and length of the buffer. Note that
1322 * in the VMIO case if the buffer block size is not
1323 * page-aligned then b_data pointer may not be page-aligned.
1324 * But our b_xio.xio_pages array *IS* page aligned.
1326 * block sizes less then DEV_BSIZE (usually 512) are not
1327 * supported due to the page granularity bits (m->valid,
1328 * m->dirty, etc...).
1330 * See man buf(9) for more information
1333 resid = bp->b_bufsize;
1334 foff = bp->b_loffset;
1337 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1338 m = bp->b_xio.xio_pages[i];
1339 vm_page_flag_clear(m, PG_ZERO);
1341 * If we hit a bogus page, fixup *all* of them
1342 * now. Note that we left these pages wired
1343 * when we removed them so they had better exist,
1344 * and they cannot be ripped out from under us so
1345 * no critical section protection is necessary.
1347 if (m == bogus_page) {
1349 poff = OFF_TO_IDX(bp->b_loffset);
1351 for (j = i; j < bp->b_xio.xio_npages; j++) {
1354 mtmp = bp->b_xio.xio_pages[j];
1355 if (mtmp == bogus_page) {
1356 mtmp = vm_page_lookup(obj, poff + j);
1358 panic("brelse: page missing");
1360 bp->b_xio.xio_pages[j] = mtmp;
1364 if ((bp->b_flags & B_INVAL) == 0) {
1365 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1366 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1368 m = bp->b_xio.xio_pages[i];
1372 * Invalidate the backing store if B_NOCACHE is set
1373 * (e.g. used with vinvalbuf()). If this is NFS
1374 * we impose a requirement that the block size be
1375 * a multiple of PAGE_SIZE and create a temporary
1376 * hack to basically invalidate the whole page. The
1377 * problem is that NFS uses really odd buffer sizes
1378 * especially when tracking piecemeal writes and
1379 * it also vinvalbuf()'s a lot, which would result
1380 * in only partial page validation and invalidation
1381 * here. If the file page is mmap()'d, however,
1382 * all the valid bits get set so after we invalidate
1383 * here we would end up with weird m->valid values
1384 * like 0xfc. nfs_getpages() can't handle this so
1385 * we clear all the valid bits for the NFS case
1386 * instead of just some of them.
1388 * The real bug is the VM system having to set m->valid
1389 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1390 * itself is an artifact of the whole 512-byte
1391 * granular mess that exists to support odd block
1392 * sizes and UFS meta-data block sizes (e.g. 6144).
1393 * A complete rewrite is required.
1397 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1398 int poffset = foff & PAGE_MASK;
1401 presid = PAGE_SIZE - poffset;
1402 if (bp->b_vp->v_tag == VT_NFS &&
1403 bp->b_vp->v_type == VREG) {
1405 } else if (presid > resid) {
1408 KASSERT(presid >= 0, ("brelse: extra page"));
1409 vm_page_set_invalid(m, poffset, presid);
1412 * Also make sure any swap cache is removed
1413 * as it is now stale (HAMMER in particular
1414 * uses B_NOCACHE to deal with buffer
1417 swap_pager_unswapped(m);
1419 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1420 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1422 if (bp->b_flags & (B_INVAL | B_RELBUF))
1423 vfs_vmio_release(bp);
1427 * Rundown for non-VMIO buffers.
1429 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1433 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1440 if (bp->b_qindex != BQUEUE_NONE)
1441 panic("brelse: free buffer onto another queue???");
1442 if (BUF_REFCNTNB(bp) > 1) {
1443 /* Temporary panic to verify exclusive locking */
1444 /* This panic goes away when we allow shared refs */
1445 panic("brelse: multiple refs");
1451 * Figure out the correct queue to place the cleaned up buffer on.
1452 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1453 * disassociated from their vnode.
1455 spin_lock_wr(&bufspin);
1456 if (bp->b_flags & B_LOCKED) {
1458 * Buffers that are locked are placed in the locked queue
1459 * immediately, regardless of their state.
1461 bp->b_qindex = BQUEUE_LOCKED;
1462 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1463 } else if (bp->b_bufsize == 0) {
1465 * Buffers with no memory. Due to conditionals near the top
1466 * of brelse() such buffers should probably already be
1467 * marked B_INVAL and disassociated from their vnode.
1469 bp->b_flags |= B_INVAL;
1470 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1471 KKASSERT((bp->b_flags & B_HASHED) == 0);
1472 if (bp->b_kvasize) {
1473 bp->b_qindex = BQUEUE_EMPTYKVA;
1475 bp->b_qindex = BQUEUE_EMPTY;
1477 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1478 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) {
1480 * Buffers with junk contents. Again these buffers had better
1481 * already be disassociated from their vnode.
1483 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1484 KKASSERT((bp->b_flags & B_HASHED) == 0);
1485 bp->b_flags |= B_INVAL;
1486 bp->b_qindex = BQUEUE_CLEAN;
1487 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1490 * Remaining buffers. These buffers are still associated with
1493 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1495 bp->b_qindex = BQUEUE_DIRTY;
1496 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1498 case B_DELWRI | B_HEAVY:
1499 bp->b_qindex = BQUEUE_DIRTY_HW;
1500 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1505 * NOTE: Buffers are always placed at the end of the
1506 * queue. If B_AGE is not set the buffer will cycle
1507 * through the queue twice.
1509 bp->b_qindex = BQUEUE_CLEAN;
1510 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1514 spin_unlock_wr(&bufspin);
1517 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1518 * on the correct queue.
1520 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1524 * The bp is on an appropriate queue unless locked. If it is not
1525 * locked or dirty we can wakeup threads waiting for buffer space.
1527 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1528 * if B_INVAL is set ).
1530 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1534 * Something we can maybe free or reuse
1536 if (bp->b_bufsize || bp->b_kvasize)
1540 * Clean up temporary flags and unlock the buffer.
1542 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF | B_DIRECT);
1549 * Release a buffer back to the appropriate queue but do not try to free
1550 * it. The buffer is expected to be used again soon.
1552 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1553 * biodone() to requeue an async I/O on completion. It is also used when
1554 * known good buffers need to be requeued but we think we may need the data
1557 * XXX we should be able to leave the B_RELBUF hint set on completion.
1562 bqrelse(struct buf *bp)
1564 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1566 if (bp->b_qindex != BQUEUE_NONE)
1567 panic("bqrelse: free buffer onto another queue???");
1568 if (BUF_REFCNTNB(bp) > 1) {
1569 /* do not release to free list */
1570 panic("bqrelse: multiple refs");
1574 buf_act_advance(bp);
1576 spin_lock_wr(&bufspin);
1577 if (bp->b_flags & B_LOCKED) {
1579 * Locked buffers are released to the locked queue. However,
1580 * if the buffer is dirty it will first go into the dirty
1581 * queue and later on after the I/O completes successfully it
1582 * will be released to the locked queue.
1584 bp->b_qindex = BQUEUE_LOCKED;
1585 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1586 } else if (bp->b_flags & B_DELWRI) {
1587 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1588 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1589 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1590 } else if (vm_page_count_severe()) {
1592 * We are too low on memory, we have to try to free the
1593 * buffer (most importantly: the wired pages making up its
1594 * backing store) *now*.
1596 spin_unlock_wr(&bufspin);
1600 bp->b_qindex = BQUEUE_CLEAN;
1601 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1603 spin_unlock_wr(&bufspin);
1605 if ((bp->b_flags & B_LOCKED) == 0 &&
1606 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1611 * Something we can maybe free or reuse.
1613 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1617 * Final cleanup and unlock. Clear bits that are only used while a
1618 * buffer is actively locked.
1620 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF);
1627 * Return backing pages held by the buffer 'bp' back to the VM system
1628 * if possible. The pages are freed if they are no longer valid or
1629 * attempt to free if it was used for direct I/O otherwise they are
1630 * sent to the page cache.
1632 * Pages that were marked busy are left alone and skipped.
1634 * The KVA mapping (b_data) for the underlying pages is removed by
1638 vfs_vmio_release(struct buf *bp)
1644 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1645 m = bp->b_xio.xio_pages[i];
1646 bp->b_xio.xio_pages[i] = NULL;
1649 * The VFS is telling us this is not a meta-data buffer
1650 * even if it is backed by a block device.
1652 if (bp->b_flags & B_NOTMETA)
1653 vm_page_flag_set(m, PG_NOTMETA);
1656 * This is a very important bit of code. We try to track
1657 * VM page use whether the pages are wired into the buffer
1658 * cache or not. While wired into the buffer cache the
1659 * bp tracks the act_count.
1661 * We can choose to place unwired pages on the inactive
1662 * queue (0) or active queue (1). If we place too many
1663 * on the active queue the queue will cycle the act_count
1664 * on pages we'd like to keep, just from single-use pages
1665 * (such as when doing a tar-up or file scan).
1667 if (bp->b_act_count < vm_cycle_point)
1668 vm_page_unwire(m, 0);
1670 vm_page_unwire(m, 1);
1673 * We don't mess with busy pages, it is
1674 * the responsibility of the process that
1675 * busied the pages to deal with them.
1677 if ((m->flags & PG_BUSY) || (m->busy != 0))
1680 if (m->wire_count == 0) {
1681 vm_page_flag_clear(m, PG_ZERO);
1683 * Might as well free the page if we can and it has
1684 * no valid data. We also free the page if the
1685 * buffer was used for direct I/O.
1688 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1689 m->hold_count == 0) {
1691 vm_page_protect(m, VM_PROT_NONE);
1695 if (bp->b_flags & B_DIRECT) {
1696 vm_page_try_to_free(m);
1697 } else if (vm_page_count_severe()) {
1698 m->act_count = bp->b_act_count;
1699 vm_page_try_to_cache(m);
1701 m->act_count = bp->b_act_count;
1706 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1707 if (bp->b_bufsize) {
1711 bp->b_xio.xio_npages = 0;
1712 bp->b_flags &= ~B_VMIO;
1713 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1724 * Implement clustered async writes for clearing out B_DELWRI buffers.
1725 * This is much better then the old way of writing only one buffer at
1726 * a time. Note that we may not be presented with the buffers in the
1727 * correct order, so we search for the cluster in both directions.
1729 * The buffer is locked on call.
1732 vfs_bio_awrite(struct buf *bp)
1736 off_t loffset = bp->b_loffset;
1737 struct vnode *vp = bp->b_vp;
1744 * right now we support clustered writing only to regular files. If
1745 * we find a clusterable block we could be in the middle of a cluster
1746 * rather then at the beginning.
1748 * NOTE: b_bio1 contains the logical loffset and is aliased
1749 * to b_loffset. b_bio2 contains the translated block number.
1751 if ((vp->v_type == VREG) &&
1752 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1753 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1755 size = vp->v_mount->mnt_stat.f_iosize;
1757 for (i = size; i < MAXPHYS; i += size) {
1758 if ((bpa = findblk(vp, loffset + i, FINDBLK_TEST)) &&
1759 BUF_REFCNT(bpa) == 0 &&
1760 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1761 (B_DELWRI | B_CLUSTEROK)) &&
1762 (bpa->b_bufsize == size)) {
1763 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1764 (bpa->b_bio2.bio_offset !=
1765 bp->b_bio2.bio_offset + i))
1771 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1772 if ((bpa = findblk(vp, loffset - j, FINDBLK_TEST)) &&
1773 BUF_REFCNT(bpa) == 0 &&
1774 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1775 (B_DELWRI | B_CLUSTEROK)) &&
1776 (bpa->b_bufsize == size)) {
1777 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1778 (bpa->b_bio2.bio_offset !=
1779 bp->b_bio2.bio_offset - j))
1789 * this is a possible cluster write
1791 if (nbytes != size) {
1793 nwritten = cluster_wbuild(vp, size,
1794 loffset - j, nbytes);
1800 * default (old) behavior, writing out only one block
1802 * XXX returns b_bufsize instead of b_bcount for nwritten?
1804 nwritten = bp->b_bufsize;
1814 * Find and initialize a new buffer header, freeing up existing buffers
1815 * in the bufqueues as necessary. The new buffer is returned locked.
1817 * Important: B_INVAL is not set. If the caller wishes to throw the
1818 * buffer away, the caller must set B_INVAL prior to calling brelse().
1821 * We have insufficient buffer headers
1822 * We have insufficient buffer space
1823 * buffer_map is too fragmented ( space reservation fails )
1824 * If we have to flush dirty buffers ( but we try to avoid this )
1826 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1827 * Instead we ask the buf daemon to do it for us. We attempt to
1828 * avoid piecemeal wakeups of the pageout daemon.
1833 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1839 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1840 static int flushingbufs;
1843 * We can't afford to block since we might be holding a vnode lock,
1844 * which may prevent system daemons from running. We deal with
1845 * low-memory situations by proactively returning memory and running
1846 * async I/O rather then sync I/O.
1850 --getnewbufrestarts;
1852 ++getnewbufrestarts;
1855 * Setup for scan. If we do not have enough free buffers,
1856 * we setup a degenerate case that immediately fails. Note
1857 * that if we are specially marked process, we are allowed to
1858 * dip into our reserves.
1860 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1862 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1863 * However, there are a number of cases (defragging, reusing, ...)
1864 * where we cannot backup.
1866 nqindex = BQUEUE_EMPTYKVA;
1867 spin_lock_wr(&bufspin);
1868 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1872 * If no EMPTYKVA buffers and we are either
1873 * defragging or reusing, locate a CLEAN buffer
1874 * to free or reuse. If bufspace useage is low
1875 * skip this step so we can allocate a new buffer.
1877 if (defrag || bufspace >= lobufspace) {
1878 nqindex = BQUEUE_CLEAN;
1879 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1883 * If we could not find or were not allowed to reuse a
1884 * CLEAN buffer, check to see if it is ok to use an EMPTY
1885 * buffer. We can only use an EMPTY buffer if allocating
1886 * its KVA would not otherwise run us out of buffer space.
1888 if (nbp == NULL && defrag == 0 &&
1889 bufspace + maxsize < hibufspace) {
1890 nqindex = BQUEUE_EMPTY;
1891 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1896 * Run scan, possibly freeing data and/or kva mappings on the fly
1899 * WARNING! bufspin is held!
1901 while ((bp = nbp) != NULL) {
1902 int qindex = nqindex;
1904 nbp = TAILQ_NEXT(bp, b_freelist);
1907 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
1908 * cycles through the queue twice before being selected.
1910 if (qindex == BQUEUE_CLEAN &&
1911 (bp->b_flags & B_AGE) == 0 && nbp) {
1912 bp->b_flags |= B_AGE;
1913 TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
1914 TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
1919 * Calculate next bp ( we can only use it if we do not block
1920 * or do other fancy things ).
1925 nqindex = BQUEUE_EMPTYKVA;
1926 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1929 case BQUEUE_EMPTYKVA:
1930 nqindex = BQUEUE_CLEAN;
1931 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1945 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1948 * Note: we no longer distinguish between VMIO and non-VMIO
1952 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1955 * If we are defragging then we need a buffer with
1956 * b_kvasize != 0. XXX this situation should no longer
1957 * occur, if defrag is non-zero the buffer's b_kvasize
1958 * should also be non-zero at this point. XXX
1960 if (defrag && bp->b_kvasize == 0) {
1961 kprintf("Warning: defrag empty buffer %p\n", bp);
1966 * Start freeing the bp. This is somewhat involved. nbp
1967 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1968 * on the clean list must be disassociated from their
1969 * current vnode. Buffers on the empty[kva] lists have
1970 * already been disassociated.
1973 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1974 spin_unlock_wr(&bufspin);
1975 kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1976 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1979 if (bp->b_qindex != qindex) {
1980 spin_unlock_wr(&bufspin);
1981 kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1985 bremfree_locked(bp);
1986 spin_unlock_wr(&bufspin);
1989 * Dependancies must be handled before we disassociate the
1992 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1993 * be immediately disassociated. HAMMER then becomes
1994 * responsible for releasing the buffer.
1996 * NOTE: bufspin is UNLOCKED now.
1998 if (LIST_FIRST(&bp->b_dep) != NULL) {
2002 if (bp->b_flags & B_LOCKED) {
2006 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2009 if (qindex == BQUEUE_CLEAN) {
2011 if (bp->b_flags & B_VMIO) {
2013 vfs_vmio_release(bp);
2022 * NOTE: nbp is now entirely invalid. We can only restart
2023 * the scan from this point on.
2025 * Get the rest of the buffer freed up. b_kva* is still
2026 * valid after this operation.
2029 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
2030 KKASSERT((bp->b_flags & B_HASHED) == 0);
2033 * critical section protection is not required when
2034 * scrapping a buffer's contents because it is already
2037 if (bp->b_bufsize) {
2043 bp->b_flags = B_BNOCLIP;
2044 bp->b_cmd = BUF_CMD_DONE;
2049 bp->b_xio.xio_npages = 0;
2050 bp->b_dirtyoff = bp->b_dirtyend = 0;
2051 bp->b_act_count = ACT_INIT;
2053 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2055 if (blkflags & GETBLK_BHEAVY)
2056 bp->b_flags |= B_HEAVY;
2059 * If we are defragging then free the buffer.
2062 bp->b_flags |= B_INVAL;
2070 * If we are overcomitted then recover the buffer and its
2071 * KVM space. This occurs in rare situations when multiple
2072 * processes are blocked in getnewbuf() or allocbuf().
2074 if (bufspace >= hibufspace)
2076 if (flushingbufs && bp->b_kvasize != 0) {
2077 bp->b_flags |= B_INVAL;
2082 if (bufspace < lobufspace)
2085 /* NOT REACHED, bufspin not held */
2089 * If we exhausted our list, sleep as appropriate. We may have to
2090 * wakeup various daemons and write out some dirty buffers.
2092 * Generally we are sleeping due to insufficient buffer space.
2094 * NOTE: bufspin is held if bp is NULL, else it is not held.
2100 spin_unlock_wr(&bufspin);
2102 flags = VFS_BIO_NEED_BUFSPACE;
2104 } else if (bufspace >= hibufspace) {
2106 flags = VFS_BIO_NEED_BUFSPACE;
2109 flags = VFS_BIO_NEED_ANY;
2112 needsbuffer |= flags;
2113 bd_speedup(); /* heeeelp */
2114 while (needsbuffer & flags) {
2115 if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
2120 * We finally have a valid bp. We aren't quite out of the
2121 * woods, we still have to reserve kva space. In order
2122 * to keep fragmentation sane we only allocate kva in
2125 * (bufspin is not held)
2127 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2129 if (maxsize != bp->b_kvasize) {
2130 vm_offset_t addr = 0;
2136 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2137 vm_map_lock(&buffer_map);
2139 if (vm_map_findspace(&buffer_map,
2140 vm_map_min(&buffer_map), maxsize,
2141 maxsize, 0, &addr)) {
2143 * Uh oh. Buffer map is too fragmented. We
2144 * must defragment the map.
2146 vm_map_unlock(&buffer_map);
2147 vm_map_entry_release(count);
2150 bp->b_flags |= B_INVAL;
2156 vm_map_insert(&buffer_map, &count,
2158 addr, addr + maxsize,
2160 VM_PROT_ALL, VM_PROT_ALL,
2163 bp->b_kvabase = (caddr_t) addr;
2164 bp->b_kvasize = maxsize;
2165 bufspace += bp->b_kvasize;
2168 vm_map_unlock(&buffer_map);
2169 vm_map_entry_release(count);
2172 bp->b_data = bp->b_kvabase;
2178 * This routine is called in an emergency to recover VM pages from the
2179 * buffer cache by cashing in clean buffers. The idea is to recover
2180 * enough pages to be able to satisfy a stuck bio_page_alloc().
2183 recoverbufpages(void)
2190 spin_lock_wr(&bufspin);
2191 while (bytes < MAXBSIZE) {
2192 bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
2197 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
2198 * cycles through the queue twice before being selected.
2200 if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) {
2201 bp->b_flags |= B_AGE;
2202 TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
2203 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN],
2211 KKASSERT(bp->b_qindex == BQUEUE_CLEAN);
2212 KKASSERT((bp->b_flags & B_DELWRI) == 0);
2215 * Start freeing the bp. This is somewhat involved.
2217 * Buffers on the clean list must be disassociated from
2218 * their current vnode
2221 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2222 kprintf("recoverbufpages: warning, locked buf %p, race corrected\n", bp);
2223 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
2226 if (bp->b_qindex != BQUEUE_CLEAN) {
2227 kprintf("recoverbufpages: warning, BUF_LOCK blocked unexpectedly on buf %p index %d, race corrected\n", bp, bp->b_qindex);
2231 bremfree_locked(bp);
2232 spin_unlock_wr(&bufspin);
2235 * Dependancies must be handled before we disassociate the
2238 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2239 * be immediately disassociated. HAMMER then becomes
2240 * responsible for releasing the buffer.
2242 if (LIST_FIRST(&bp->b_dep) != NULL) {
2244 if (bp->b_flags & B_LOCKED) {
2246 spin_lock_wr(&bufspin);
2249 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2252 bytes += bp->b_bufsize;
2255 if (bp->b_flags & B_VMIO) {
2256 bp->b_flags |= B_DIRECT; /* try to free pages */
2257 vfs_vmio_release(bp);
2262 KKASSERT(bp->b_vp == NULL);
2263 KKASSERT((bp->b_flags & B_HASHED) == 0);
2266 * critical section protection is not required when
2267 * scrapping a buffer's contents because it is already
2274 bp->b_flags = B_BNOCLIP;
2275 bp->b_cmd = BUF_CMD_DONE;
2280 bp->b_xio.xio_npages = 0;
2281 bp->b_dirtyoff = bp->b_dirtyend = 0;
2283 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2285 bp->b_flags |= B_INVAL;
2288 spin_lock_wr(&bufspin);
2290 spin_unlock_wr(&bufspin);
2297 * Buffer flushing daemon. Buffers are normally flushed by the
2298 * update daemon but if it cannot keep up this process starts to
2299 * take the load in an attempt to prevent getnewbuf() from blocking.
2301 * Once a flush is initiated it does not stop until the number
2302 * of buffers falls below lodirtybuffers, but we will wake up anyone
2303 * waiting at the mid-point.
2306 static struct kproc_desc buf_kp = {
2311 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2312 kproc_start, &buf_kp)
2314 static struct kproc_desc bufhw_kp = {
2319 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2320 kproc_start, &bufhw_kp)
2328 * This process needs to be suspended prior to shutdown sync.
2330 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2331 bufdaemon_td, SHUTDOWN_PRI_LAST);
2332 curthread->td_flags |= TDF_SYSTHREAD;
2335 * This process is allowed to take the buffer cache to the limit
2340 kproc_suspend_loop();
2343 * Do the flush as long as the number of dirty buffers
2344 * (including those running) exceeds lodirtybufspace.
2346 * When flushing limit running I/O to hirunningspace
2347 * Do the flush. Limit the amount of in-transit I/O we
2348 * allow to build up, otherwise we would completely saturate
2349 * the I/O system. Wakeup any waiting processes before we
2350 * normally would so they can run in parallel with our drain.
2352 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2353 * but because we split the operation into two threads we
2354 * have to cut it in half for each thread.
2356 waitrunningbufspace();
2357 limit = lodirtybufspace / 2;
2358 while (runningbufspace + dirtybufspace > limit ||
2359 dirtybufcount - dirtybufcounthw >= nbuf / 2) {
2360 if (flushbufqueues(BQUEUE_DIRTY) == 0)
2362 if (runningbufspace < hirunningspace)
2364 waitrunningbufspace();
2368 * We reached our low water mark, reset the
2369 * request and sleep until we are needed again.
2370 * The sleep is just so the suspend code works.
2372 spin_lock_wr(&needsbuffer_spin);
2373 if (bd_request == 0) {
2374 ssleep(&bd_request, &needsbuffer_spin, 0,
2378 spin_unlock_wr(&needsbuffer_spin);
2388 * This process needs to be suspended prior to shutdown sync.
2390 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2391 bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2392 curthread->td_flags |= TDF_SYSTHREAD;
2395 * This process is allowed to take the buffer cache to the limit
2400 kproc_suspend_loop();
2403 * Do the flush. Limit the amount of in-transit I/O we
2404 * allow to build up, otherwise we would completely saturate
2405 * the I/O system. Wakeup any waiting processes before we
2406 * normally would so they can run in parallel with our drain.
2408 * Once we decide to flush push the queued I/O up to
2409 * hirunningspace in order to trigger bursting by the bioq
2412 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2413 * but because we split the operation into two threads we
2414 * have to cut it in half for each thread.
2416 waitrunningbufspace();
2417 limit = lodirtybufspace / 2;
2418 while (runningbufspace + dirtybufspacehw > limit ||
2419 dirtybufcounthw >= nbuf / 2) {
2420 if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2422 if (runningbufspace < hirunningspace)
2424 waitrunningbufspace();
2428 * We reached our low water mark, reset the
2429 * request and sleep until we are needed again.
2430 * The sleep is just so the suspend code works.
2432 spin_lock_wr(&needsbuffer_spin);
2433 if (bd_request_hw == 0) {
2434 ssleep(&bd_request_hw, &needsbuffer_spin, 0,
2438 spin_unlock_wr(&needsbuffer_spin);
2445 * Try to flush a buffer in the dirty queue. We must be careful to
2446 * free up B_INVAL buffers instead of write them, which NFS is
2447 * particularly sensitive to.
2449 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate
2450 * that we really want to try to get the buffer out and reuse it
2451 * due to the write load on the machine.
2454 flushbufqueues(bufq_type_t q)
2460 spin_lock_wr(&bufspin);
2463 bp = TAILQ_FIRST(&bufqueues[q]);
2465 KASSERT((bp->b_flags & B_DELWRI),
2466 ("unexpected clean buffer %p", bp));
2468 if (bp->b_flags & B_DELWRI) {
2469 if (bp->b_flags & B_INVAL) {
2470 spin_unlock_wr(&bufspin);
2472 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2473 panic("flushbufqueues: locked buf");
2479 if (LIST_FIRST(&bp->b_dep) != NULL &&
2480 (bp->b_flags & B_DEFERRED) == 0 &&
2481 buf_countdeps(bp, 0)) {
2482 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2483 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2485 bp->b_flags |= B_DEFERRED;
2486 bp = TAILQ_FIRST(&bufqueues[q]);
2491 * Only write it out if we can successfully lock
2492 * it. If the buffer has a dependancy,
2493 * buf_checkwrite must also return 0 for us to
2494 * be able to initate the write.
2496 * If the buffer is flagged B_ERROR it may be
2497 * requeued over and over again, we try to
2498 * avoid a live lock.
2500 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2501 spin_unlock_wr(&bufspin);
2503 if (LIST_FIRST(&bp->b_dep) != NULL &&
2504 buf_checkwrite(bp)) {
2507 } else if (bp->b_flags & B_ERROR) {
2508 tsleep(bp, 0, "bioer", 1);
2509 bp->b_flags &= ~B_AGE;
2512 bp->b_flags |= B_AGE;
2519 bp = TAILQ_NEXT(bp, b_freelist);
2522 spin_unlock_wr(&bufspin);
2529 * Returns true if no I/O is needed to access the associated VM object.
2530 * This is like findblk except it also hunts around in the VM system for
2533 * Note that we ignore vm_page_free() races from interrupts against our
2534 * lookup, since if the caller is not protected our return value will not
2535 * be any more valid then otherwise once we exit the critical section.
2538 inmem(struct vnode *vp, off_t loffset)
2541 vm_offset_t toff, tinc, size;
2544 if (findblk(vp, loffset, FINDBLK_TEST))
2546 if (vp->v_mount == NULL)
2548 if ((obj = vp->v_object) == NULL)
2552 if (size > vp->v_mount->mnt_stat.f_iosize)
2553 size = vp->v_mount->mnt_stat.f_iosize;
2555 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2556 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2560 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2561 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2562 if (vm_page_is_valid(m,
2563 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2572 * Locate and return the specified buffer. Unless flagged otherwise,
2573 * a locked buffer will be returned if it exists or NULL if it does not.
2575 * findblk()'d buffers are still on the bufqueues and if you intend
2576 * to use your (locked NON-TEST) buffer you need to bremfree(bp)
2577 * and possibly do other stuff to it.
2579 * FINDBLK_TEST - Do not lock the buffer. The caller is responsible
2580 * for locking the buffer and ensuring that it remains
2581 * the desired buffer after locking.
2583 * FINDBLK_NBLOCK - Lock the buffer non-blocking. If we are unable
2584 * to acquire the lock we return NULL, even if the
2587 * (0) - Lock the buffer blocking.
2592 findblk(struct vnode *vp, off_t loffset, int flags)
2598 lkflags = LK_EXCLUSIVE;
2599 if (flags & FINDBLK_NBLOCK)
2600 lkflags |= LK_NOWAIT;
2603 lwkt_gettoken(&vlock, &vp->v_token);
2604 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2605 lwkt_reltoken(&vlock);
2606 if (bp == NULL || (flags & FINDBLK_TEST))
2608 if (BUF_LOCK(bp, lkflags)) {
2612 if (bp->b_vp == vp && bp->b_loffset == loffset)
2622 * Similar to getblk() except only returns the buffer if it is
2623 * B_CACHE and requires no other manipulation. Otherwise NULL
2626 * If B_RAM is set the buffer might be just fine, but we return
2627 * NULL anyway because we want the code to fall through to the
2628 * cluster read. Otherwise read-ahead breaks.
2631 getcacheblk(struct vnode *vp, off_t loffset)
2635 bp = findblk(vp, loffset, 0);
2637 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) == B_CACHE) {
2638 bp->b_flags &= ~B_AGE;
2651 * Get a block given a specified block and offset into a file/device.
2652 * B_INVAL may or may not be set on return. The caller should clear
2653 * B_INVAL prior to initiating a READ.
2655 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2656 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2657 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2658 * without doing any of those things the system will likely believe
2659 * the buffer to be valid (especially if it is not B_VMIO), and the
2660 * next getblk() will return the buffer with B_CACHE set.
2662 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2663 * an existing buffer.
2665 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2666 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2667 * and then cleared based on the backing VM. If the previous buffer is
2668 * non-0-sized but invalid, B_CACHE will be cleared.
2670 * If getblk() must create a new buffer, the new buffer is returned with
2671 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2672 * case it is returned with B_INVAL clear and B_CACHE set based on the
2675 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2676 * B_CACHE bit is clear.
2678 * What this means, basically, is that the caller should use B_CACHE to
2679 * determine whether the buffer is fully valid or not and should clear
2680 * B_INVAL prior to issuing a read. If the caller intends to validate
2681 * the buffer by loading its data area with something, the caller needs
2682 * to clear B_INVAL. If the caller does this without issuing an I/O,
2683 * the caller should set B_CACHE ( as an optimization ), else the caller
2684 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2685 * a write attempt or if it was a successfull read. If the caller
2686 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2687 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2691 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2692 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2697 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2700 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2704 if (size > MAXBSIZE)
2705 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2706 if (vp->v_object == NULL)
2707 panic("getblk: vnode %p has no object!", vp);
2710 if ((bp = findblk(vp, loffset, FINDBLK_TEST)) != NULL) {
2712 * The buffer was found in the cache, but we need to lock it.
2713 * Even with LK_NOWAIT the lockmgr may break our critical
2714 * section, so double-check the validity of the buffer
2715 * once the lock has been obtained.
2717 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2718 if (blkflags & GETBLK_NOWAIT)
2720 lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2721 if (blkflags & GETBLK_PCATCH)
2722 lkflags |= LK_PCATCH;
2723 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2725 if (error == ENOLCK)
2729 /* buffer may have changed on us */
2733 * Once the buffer has been locked, make sure we didn't race
2734 * a buffer recyclement. Buffers that are no longer hashed
2735 * will have b_vp == NULL, so this takes care of that check
2738 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2739 kprintf("Warning buffer %p (vp %p loffset %lld) "
2741 bp, vp, (long long)loffset);
2747 * If SZMATCH any pre-existing buffer must be of the requested
2748 * size or NULL is returned. The caller absolutely does not
2749 * want getblk() to bwrite() the buffer on a size mismatch.
2751 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2757 * All vnode-based buffers must be backed by a VM object.
2759 KKASSERT(bp->b_flags & B_VMIO);
2760 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2761 bp->b_flags &= ~B_AGE;
2764 * Make sure that B_INVAL buffers do not have a cached
2765 * block number translation.
2767 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2768 kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2769 " did not have cleared bio_offset cache\n",
2770 bp, vp, (long long)loffset);
2771 clearbiocache(&bp->b_bio2);
2775 * The buffer is locked. B_CACHE is cleared if the buffer is
2778 if (bp->b_flags & B_INVAL)
2779 bp->b_flags &= ~B_CACHE;
2783 * Any size inconsistancy with a dirty buffer or a buffer
2784 * with a softupdates dependancy must be resolved. Resizing
2785 * the buffer in such circumstances can lead to problems.
2787 * Dirty or dependant buffers are written synchronously.
2788 * Other types of buffers are simply released and
2789 * reconstituted as they may be backed by valid, dirty VM
2790 * pages (but not marked B_DELWRI).
2792 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2793 * and may be left over from a prior truncation (and thus
2794 * no longer represent the actual EOF point), so we
2795 * definitely do not want to B_NOCACHE the backing store.
2797 if (size != bp->b_bcount) {
2799 if (bp->b_flags & B_DELWRI) {
2800 bp->b_flags |= B_RELBUF;
2802 } else if (LIST_FIRST(&bp->b_dep)) {
2803 bp->b_flags |= B_RELBUF;
2806 bp->b_flags |= B_RELBUF;
2812 KKASSERT(size <= bp->b_kvasize);
2813 KASSERT(bp->b_loffset != NOOFFSET,
2814 ("getblk: no buffer offset"));
2817 * A buffer with B_DELWRI set and B_CACHE clear must
2818 * be committed before we can return the buffer in
2819 * order to prevent the caller from issuing a read
2820 * ( due to B_CACHE not being set ) and overwriting
2823 * Most callers, including NFS and FFS, need this to
2824 * operate properly either because they assume they
2825 * can issue a read if B_CACHE is not set, or because
2826 * ( for example ) an uncached B_DELWRI might loop due
2827 * to softupdates re-dirtying the buffer. In the latter
2828 * case, B_CACHE is set after the first write completes,
2829 * preventing further loops.
2831 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2832 * above while extending the buffer, we cannot allow the
2833 * buffer to remain with B_CACHE set after the write
2834 * completes or it will represent a corrupt state. To
2835 * deal with this we set B_NOCACHE to scrap the buffer
2838 * XXX Should this be B_RELBUF instead of B_NOCACHE?
2839 * I'm not even sure this state is still possible
2840 * now that getblk() writes out any dirty buffers
2843 * We might be able to do something fancy, like setting
2844 * B_CACHE in bwrite() except if B_DELWRI is already set,
2845 * so the below call doesn't set B_CACHE, but that gets real
2846 * confusing. This is much easier.
2849 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2851 kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
2852 "and CACHE clear, b_flags %08x\n",
2853 bp, (intmax_t)bp->b_loffset, bp->b_flags);
2854 bp->b_flags |= B_NOCACHE;
2861 * Buffer is not in-core, create new buffer. The buffer
2862 * returned by getnewbuf() is locked. Note that the returned
2863 * buffer is also considered valid (not marked B_INVAL).
2865 * Calculating the offset for the I/O requires figuring out
2866 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2867 * the mount's f_iosize otherwise. If the vnode does not
2868 * have an associated mount we assume that the passed size is
2871 * Note that vn_isdisk() cannot be used here since it may
2872 * return a failure for numerous reasons. Note that the
2873 * buffer size may be larger then the block size (the caller
2874 * will use block numbers with the proper multiple). Beware
2875 * of using any v_* fields which are part of unions. In
2876 * particular, in DragonFly the mount point overloading
2877 * mechanism uses the namecache only and the underlying
2878 * directory vnode is not a special case.
2882 if (vp->v_type == VBLK || vp->v_type == VCHR)
2884 else if (vp->v_mount)
2885 bsize = vp->v_mount->mnt_stat.f_iosize;
2889 maxsize = size + (loffset & PAGE_MASK);
2890 maxsize = imax(maxsize, bsize);
2892 bp = getnewbuf(blkflags, slptimeo, size, maxsize);
2894 if (slpflags || slptimeo)
2900 * Atomically insert the buffer into the hash, so that it can
2901 * be found by findblk().
2903 * If bgetvp() returns non-zero a collision occured, and the
2904 * bp will not be associated with the vnode.
2906 * Make sure the translation layer has been cleared.
2908 bp->b_loffset = loffset;
2909 bp->b_bio2.bio_offset = NOOFFSET;
2910 /* bp->b_bio2.bio_next = NULL; */
2912 if (bgetvp(vp, bp)) {
2913 bp->b_flags |= B_INVAL;
2919 * All vnode-based buffers must be backed by a VM object.
2921 KKASSERT(vp->v_object != NULL);
2922 bp->b_flags |= B_VMIO;
2923 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2935 * Reacquire a buffer that was previously released to the locked queue,
2936 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2937 * set B_LOCKED (which handles the acquisition race).
2939 * To this end, either B_LOCKED must be set or the dependancy list must be
2945 regetblk(struct buf *bp)
2947 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2948 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2955 * Get an empty, disassociated buffer of given size. The buffer is
2956 * initially set to B_INVAL.
2958 * critical section protection is not required for the allocbuf()
2959 * call because races are impossible here.
2969 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2971 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2976 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2984 * This code constitutes the buffer memory from either anonymous system
2985 * memory (in the case of non-VMIO operations) or from an associated
2986 * VM object (in the case of VMIO operations). This code is able to
2987 * resize a buffer up or down.
2989 * Note that this code is tricky, and has many complications to resolve
2990 * deadlock or inconsistant data situations. Tread lightly!!!
2991 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2992 * the caller. Calling this code willy nilly can result in the loss of data.
2994 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2995 * B_CACHE for the non-VMIO case.
2997 * This routine does not need to be called from a critical section but you
2998 * must own the buffer.
3003 allocbuf(struct buf *bp, int size)
3005 int newbsize, mbsize;
3008 if (BUF_REFCNT(bp) == 0)
3009 panic("allocbuf: buffer not busy");
3011 if (bp->b_kvasize < size)
3012 panic("allocbuf: buffer too small");
3014 if ((bp->b_flags & B_VMIO) == 0) {
3018 * Just get anonymous memory from the kernel. Don't
3019 * mess with B_CACHE.
3021 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3022 if (bp->b_flags & B_MALLOC)
3025 newbsize = round_page(size);
3027 if (newbsize < bp->b_bufsize) {
3029 * Malloced buffers are not shrunk
3031 if (bp->b_flags & B_MALLOC) {
3033 bp->b_bcount = size;
3035 kfree(bp->b_data, M_BIOBUF);
3036 if (bp->b_bufsize) {
3037 bufmallocspace -= bp->b_bufsize;
3041 bp->b_data = bp->b_kvabase;
3043 bp->b_flags &= ~B_MALLOC;
3049 (vm_offset_t) bp->b_data + newbsize,
3050 (vm_offset_t) bp->b_data + bp->b_bufsize);
3051 } else if (newbsize > bp->b_bufsize) {
3053 * We only use malloced memory on the first allocation.
3054 * and revert to page-allocated memory when the buffer
3057 if ((bufmallocspace < maxbufmallocspace) &&
3058 (bp->b_bufsize == 0) &&
3059 (mbsize <= PAGE_SIZE/2)) {
3061 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
3062 bp->b_bufsize = mbsize;
3063 bp->b_bcount = size;
3064 bp->b_flags |= B_MALLOC;
3065 bufmallocspace += mbsize;
3071 * If the buffer is growing on its other-than-first
3072 * allocation, then we revert to the page-allocation
3075 if (bp->b_flags & B_MALLOC) {
3076 origbuf = bp->b_data;
3077 origbufsize = bp->b_bufsize;
3078 bp->b_data = bp->b_kvabase;
3079 if (bp->b_bufsize) {
3080 bufmallocspace -= bp->b_bufsize;
3084 bp->b_flags &= ~B_MALLOC;
3085 newbsize = round_page(newbsize);
3089 (vm_offset_t) bp->b_data + bp->b_bufsize,
3090 (vm_offset_t) bp->b_data + newbsize);
3092 bcopy(origbuf, bp->b_data, origbufsize);
3093 kfree(origbuf, M_BIOBUF);
3100 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3101 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3102 newbsize + PAGE_MASK) >> PAGE_SHIFT;
3103 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
3105 if (bp->b_flags & B_MALLOC)
3106 panic("allocbuf: VMIO buffer can't be malloced");
3108 * Set B_CACHE initially if buffer is 0 length or will become
3111 if (size == 0 || bp->b_bufsize == 0)
3112 bp->b_flags |= B_CACHE;
3114 if (newbsize < bp->b_bufsize) {
3116 * DEV_BSIZE aligned new buffer size is less then the
3117 * DEV_BSIZE aligned existing buffer size. Figure out
3118 * if we have to remove any pages.
3120 if (desiredpages < bp->b_xio.xio_npages) {
3121 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
3123 * the page is not freed here -- it
3124 * is the responsibility of
3125 * vnode_pager_setsize
3127 m = bp->b_xio.xio_pages[i];
3128 KASSERT(m != bogus_page,
3129 ("allocbuf: bogus page found"));
3130 while (vm_page_sleep_busy(m, TRUE, "biodep"))
3133 bp->b_xio.xio_pages[i] = NULL;
3134 vm_page_unwire(m, 0);
3136 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
3137 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
3138 bp->b_xio.xio_npages = desiredpages;
3140 } else if (size > bp->b_bcount) {
3142 * We are growing the buffer, possibly in a
3143 * byte-granular fashion.
3151 * Step 1, bring in the VM pages from the object,
3152 * allocating them if necessary. We must clear
3153 * B_CACHE if these pages are not valid for the
3154 * range covered by the buffer.
3156 * critical section protection is required to protect
3157 * against interrupts unbusying and freeing pages
3158 * between our vm_page_lookup() and our
3159 * busycheck/wiring call.
3165 while (bp->b_xio.xio_npages < desiredpages) {
3169 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
3170 if ((m = vm_page_lookup(obj, pi)) == NULL) {
3172 * note: must allocate system pages
3173 * since blocking here could intefere
3174 * with paging I/O, no matter which
3177 m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages);
3181 vm_page_flag_clear(m, PG_ZERO);
3182 bp->b_flags &= ~B_CACHE;
3183 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3184 ++bp->b_xio.xio_npages;
3190 * We found a page. If we have to sleep on it,
3191 * retry because it might have gotten freed out
3194 * We can only test PG_BUSY here. Blocking on
3195 * m->busy might lead to a deadlock:
3197 * vm_fault->getpages->cluster_read->allocbuf
3201 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
3203 vm_page_flag_clear(m, PG_ZERO);
3205 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3206 ++bp->b_xio.xio_npages;
3207 if (bp->b_act_count < m->act_count)
3208 bp->b_act_count = m->act_count;
3213 * Step 2. We've loaded the pages into the buffer,
3214 * we have to figure out if we can still have B_CACHE
3215 * set. Note that B_CACHE is set according to the
3216 * byte-granular range ( bcount and size ), not the
3217 * aligned range ( newbsize ).
3219 * The VM test is against m->valid, which is DEV_BSIZE
3220 * aligned. Needless to say, the validity of the data
3221 * needs to also be DEV_BSIZE aligned. Note that this
3222 * fails with NFS if the server or some other client
3223 * extends the file's EOF. If our buffer is resized,
3224 * B_CACHE may remain set! XXX
3227 toff = bp->b_bcount;
3228 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3230 while ((bp->b_flags & B_CACHE) && toff < size) {
3233 if (tinc > (size - toff))
3236 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
3244 bp->b_xio.xio_pages[pi]
3251 * Step 3, fixup the KVM pmap. Remember that
3252 * bp->b_data is relative to bp->b_loffset, but
3253 * bp->b_loffset may be offset into the first page.
3256 bp->b_data = (caddr_t)
3257 trunc_page((vm_offset_t)bp->b_data);
3259 (vm_offset_t)bp->b_data,
3260 bp->b_xio.xio_pages,
3261 bp->b_xio.xio_npages
3263 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3264 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3268 /* adjust space use on already-dirty buffer */
3269 if (bp->b_flags & B_DELWRI) {
3270 dirtybufspace += newbsize - bp->b_bufsize;
3271 if (bp->b_flags & B_HEAVY)
3272 dirtybufspacehw += newbsize - bp->b_bufsize;
3274 if (newbsize < bp->b_bufsize)
3276 bp->b_bufsize = newbsize; /* actual buffer allocation */
3277 bp->b_bcount = size; /* requested buffer size */
3284 * Wait for buffer I/O completion, returning error status. B_EINTR
3285 * is converted into an EINTR error but not cleared (since a chain
3286 * of biowait() calls may occur).
3288 * On return bpdone() will have been called but the buffer will remain
3289 * locked and will not have been brelse()'d.
3291 * NOTE! If a timeout is specified and ETIMEDOUT occurs the I/O is
3292 * likely still in progress on return.
3294 * NOTE! This operation is on a BIO, not a BUF.
3296 * NOTE! BIO_DONE is cleared by vn_strategy()
3301 _biowait(struct bio *bio, const char *wmesg, int to)
3303 struct buf *bp = bio->bio_buf;
3308 KKASSERT(bio == &bp->b_bio1);
3310 flags = bio->bio_flags;
3311 if (flags & BIO_DONE)
3313 tsleep_interlock(bio, 0);
3314 nflags = flags | BIO_WANT;
3315 tsleep_interlock(bio, 0);
3316 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3318 error = tsleep(bio, PINTERLOCKED, wmesg, to);
3319 else if (bp->b_cmd == BUF_CMD_READ)
3320 error = tsleep(bio, PINTERLOCKED, "biord", to);
3322 error = tsleep(bio, PINTERLOCKED, "biowr", to);
3324 kprintf("tsleep error biowait %d\n", error);
3334 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3335 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
3336 if (bp->b_flags & B_EINTR)
3338 if (bp->b_flags & B_ERROR)
3339 return (bp->b_error ? bp->b_error : EIO);
3344 biowait(struct bio *bio, const char *wmesg)
3346 return(_biowait(bio, wmesg, 0));
3350 biowait_timeout(struct bio *bio, const char *wmesg, int to)
3352 return(_biowait(bio, wmesg, to));
3356 * This associates a tracking count with an I/O. vn_strategy() and
3357 * dev_dstrategy() do this automatically but there are a few cases
3358 * where a vnode or device layer is bypassed when a block translation
3359 * is cached. In such cases bio_start_transaction() may be called on
3360 * the bypassed layers so the system gets an I/O in progress indication
3361 * for those higher layers.
3364 bio_start_transaction(struct bio *bio, struct bio_track *track)
3366 bio->bio_track = track;
3367 bio_track_ref(track);
3371 * Initiate I/O on a vnode.
3373 * SWAPCACHE OPERATION:
3375 * Real buffer cache buffers have a non-NULL bp->b_vp. Unfortunately
3376 * devfs also uses b_vp for fake buffers so we also have to check
3377 * that B_PAGING is 0. In this case the passed 'vp' is probably the
3378 * underlying block device. The swap assignments are related to the
3379 * buffer cache buffer's b_vp, not the passed vp.
3381 * The passed vp == bp->b_vp only in the case where the strategy call
3382 * is made on the vp itself for its own buffers (a regular file or
3383 * block device vp). The filesystem usually then re-calls vn_strategy()
3384 * after translating the request to an underlying device.
3386 * Cluster buffers set B_CLUSTER and the passed vp is the vp of the
3387 * underlying buffer cache buffers.
3389 * We can only deal with page-aligned buffers at the moment, because
3390 * we can't tell what the real dirty state for pages straddling a buffer
3393 * In order to call swap_pager_strategy() we must provide the VM object
3394 * and base offset for the underlying buffer cache pages so it can find
3398 vn_strategy(struct vnode *vp, struct bio *bio)
3400 struct bio_track *track;
3401 struct buf *bp = bio->bio_buf;
3403 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3406 * Handle the swap cache intercept.
3408 if (vn_cache_strategy(vp, bio))
3412 * Otherwise do the operation through the filesystem
3414 if (bp->b_cmd == BUF_CMD_READ)
3415 track = &vp->v_track_read;
3417 track = &vp->v_track_write;
3418 KKASSERT((bio->bio_flags & BIO_DONE) == 0);
3419 bio->bio_track = track;
3420 bio_track_ref(track);
3421 vop_strategy(*vp->v_ops, vp, bio);
3425 vn_cache_strategy(struct vnode *vp, struct bio *bio)
3427 struct buf *bp = bio->bio_buf;
3434 * Is this buffer cache buffer suitable for reading from
3437 if (vm_swapcache_read_enable == 0 ||
3438 bp->b_cmd != BUF_CMD_READ ||
3439 ((bp->b_flags & B_CLUSTER) == 0 &&
3440 (bp->b_vp == NULL || (bp->b_flags & B_PAGING))) ||
3441 ((int)bp->b_loffset & PAGE_MASK) != 0 ||
3442 (bp->b_bcount & PAGE_MASK) != 0) {
3447 * Figure out the original VM object (it will match the underlying
3448 * VM pages). Note that swap cached data uses page indices relative
3449 * to that object, not relative to bio->bio_offset.
3451 if (bp->b_flags & B_CLUSTER)
3452 object = vp->v_object;
3454 object = bp->b_vp->v_object;
3457 * In order to be able to use the swap cache all underlying VM
3458 * pages must be marked as such, and we can't have any bogus pages.
3460 for (i = 0; i < bp->b_xio.xio_npages; ++i) {
3461 m = bp->b_xio.xio_pages[i];
3462 if ((m->flags & PG_SWAPPED) == 0)
3464 if (m == bogus_page)
3469 * If we are good then issue the I/O using swap_pager_strategy()
3471 if (i == bp->b_xio.xio_npages) {
3472 m = bp->b_xio.xio_pages[0];
3473 nbio = push_bio(bio);
3474 nbio->bio_offset = ptoa(m->pindex);
3475 KKASSERT(m->object == object);
3476 swap_pager_strategy(object, nbio);
3485 * Finish I/O on a buffer after all BIOs have been processed.
3486 * Called when the bio chain is exhausted or by biowait. If called
3487 * by biowait, elseit is typically 0.
3489 * bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3490 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3491 * assuming B_INVAL is clear.
3493 * For the VMIO case, we set B_CACHE if the op was a read and no
3494 * read error occured, or if the op was a write. B_CACHE is never
3495 * set if the buffer is invalid or otherwise uncacheable.
3497 * bpdone does not mess with B_INVAL, allowing the I/O routine or the
3498 * initiator to leave B_INVAL set to brelse the buffer out of existance
3499 * in the biodone routine.
3502 bpdone(struct buf *bp, int elseit)
3506 KASSERT(BUF_REFCNTNB(bp) > 0,
3507 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3508 KASSERT(bp->b_cmd != BUF_CMD_DONE,
3509 ("biodone: bp %p already done!", bp));
3512 * No more BIOs are left. All completion functions have been dealt
3513 * with, now we clean up the buffer.
3516 bp->b_cmd = BUF_CMD_DONE;
3519 * Only reads and writes are processed past this point.
3521 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3522 if (cmd == BUF_CMD_FREEBLKS)
3523 bp->b_flags |= B_NOCACHE;
3530 * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3531 * a lot worse. XXX - move this above the clearing of b_cmd
3533 if (LIST_FIRST(&bp->b_dep) != NULL)
3537 * A failed write must re-dirty the buffer unless B_INVAL
3538 * was set. Only applicable to normal buffers (with VPs).
3539 * vinum buffers may not have a vp.
3541 if (cmd == BUF_CMD_WRITE &&
3542 (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
3543 bp->b_flags &= ~B_NOCACHE;
3548 if (bp->b_flags & B_VMIO) {
3554 struct vnode *vp = bp->b_vp;
3558 #if defined(VFS_BIO_DEBUG)
3559 if (vp->v_auxrefs == 0)
3560 panic("biodone: zero vnode hold count");
3561 if ((vp->v_flag & VOBJBUF) == 0)
3562 panic("biodone: vnode is not setup for merged cache");
3565 foff = bp->b_loffset;
3566 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3567 KASSERT(obj != NULL, ("biodone: missing VM object"));
3569 #if defined(VFS_BIO_DEBUG)
3570 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3571 kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3572 obj->paging_in_progress, bp->b_xio.xio_npages);
3577 * Set B_CACHE if the op was a normal read and no error
3578 * occured. B_CACHE is set for writes in the b*write()
3581 iosize = bp->b_bcount - bp->b_resid;
3582 if (cmd == BUF_CMD_READ &&
3583 (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3584 bp->b_flags |= B_CACHE;
3589 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3593 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3598 * cleanup bogus pages, restoring the originals. Since
3599 * the originals should still be wired, we don't have
3600 * to worry about interrupt/freeing races destroying
3601 * the VM object association.
3603 m = bp->b_xio.xio_pages[i];
3604 if (m == bogus_page) {
3606 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3608 panic("biodone: page disappeared");
3609 bp->b_xio.xio_pages[i] = m;
3610 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3611 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3613 #if defined(VFS_BIO_DEBUG)
3614 if (OFF_TO_IDX(foff) != m->pindex) {
3615 kprintf("biodone: foff(%lu)/m->pindex(%ld) "
3617 (unsigned long)foff, (long)m->pindex);
3622 * In the write case, the valid and clean bits are
3623 * already changed correctly (see bdwrite()), so we
3624 * only need to do this here in the read case.
3626 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3627 vfs_clean_one_page(bp, i, m);
3629 vm_page_flag_clear(m, PG_ZERO);
3632 * when debugging new filesystems or buffer I/O
3633 * methods, this is the most common error that pops
3634 * up. if you see this, you have not set the page
3635 * busy flag correctly!!!
3638 kprintf("biodone: page busy < 0, "
3639 "pindex: %d, foff: 0x(%x,%x), "
3640 "resid: %d, index: %d\n",
3641 (int) m->pindex, (int)(foff >> 32),
3642 (int) foff & 0xffffffff, resid, i);
3643 if (!vn_isdisk(vp, NULL))
3644 kprintf(" iosize: %ld, loffset: %lld, "
3645 "flags: 0x%08x, npages: %d\n",
3646 bp->b_vp->v_mount->mnt_stat.f_iosize,
3647 (long long)bp->b_loffset,
3648 bp->b_flags, bp->b_xio.xio_npages);
3650 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3651 (long long)bp->b_loffset,
3652 bp->b_flags, bp->b_xio.xio_npages);
3653 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3654 m->valid, m->dirty, m->wire_count);
3655 panic("biodone: page busy < 0");
3657 vm_page_io_finish(m);
3658 vm_object_pip_subtract(obj, 1);
3659 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3663 vm_object_pip_wakeupn(obj, 0);
3669 * Finish up by releasing the buffer. There are no more synchronous
3670 * or asynchronous completions, those were handled by bio_done
3674 if (bp->b_flags & (B_NOCACHE|B_INVAL|B_ERROR|B_RELBUF))
3685 biodone(struct bio *bio)
3687 struct buf *bp = bio->bio_buf;
3689 runningbufwakeup(bp);
3692 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
3695 biodone_t *done_func;
3696 struct bio_track *track;
3699 * BIO tracking. Most but not all BIOs are tracked.
3701 if ((track = bio->bio_track) != NULL) {
3702 bio_track_rel(track);
3703 bio->bio_track = NULL;
3707 * A bio_done function terminates the loop. The function
3708 * will be responsible for any further chaining and/or
3709 * buffer management.
3711 * WARNING! The done function can deallocate the buffer!
3713 if ((done_func = bio->bio_done) != NULL) {
3714 bio->bio_done = NULL;
3718 bio = bio->bio_prev;
3722 * If we've run out of bio's do normal [a]synchronous completion.
3728 * Synchronous biodone - this terminates a synchronous BIO.
3730 * bpdone() is called with elseit=FALSE, leaving the buffer completed
3731 * but still locked. The caller must brelse() the buffer after waiting
3735 biodone_sync(struct bio *bio)
3737 struct buf *bp = bio->bio_buf;
3741 KKASSERT(bio == &bp->b_bio1);
3745 flags = bio->bio_flags;
3746 nflags = (flags | BIO_DONE) & ~BIO_WANT;
3748 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3749 if (flags & BIO_WANT)
3759 * This routine is called in lieu of iodone in the case of
3760 * incomplete I/O. This keeps the busy status for pages
3764 vfs_unbusy_pages(struct buf *bp)
3768 runningbufwakeup(bp);
3769 if (bp->b_flags & B_VMIO) {
3770 struct vnode *vp = bp->b_vp;
3775 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3776 vm_page_t m = bp->b_xio.xio_pages[i];
3779 * When restoring bogus changes the original pages
3780 * should still be wired, so we are in no danger of
3781 * losing the object association and do not need
3782 * critical section protection particularly.
3784 if (m == bogus_page) {
3785 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3787 panic("vfs_unbusy_pages: page missing");
3789 bp->b_xio.xio_pages[i] = m;
3790 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3791 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3793 vm_object_pip_subtract(obj, 1);
3794 vm_page_flag_clear(m, PG_ZERO);
3795 vm_page_io_finish(m);
3797 vm_object_pip_wakeupn(obj, 0);
3804 * This routine is called before a device strategy routine.
3805 * It is used to tell the VM system that paging I/O is in
3806 * progress, and treat the pages associated with the buffer
3807 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3808 * flag is handled to make sure that the object doesn't become
3811 * Since I/O has not been initiated yet, certain buffer flags
3812 * such as B_ERROR or B_INVAL may be in an inconsistant state
3813 * and should be ignored.
3816 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3819 struct lwp *lp = curthread->td_lwp;
3822 * The buffer's I/O command must already be set. If reading,
3823 * B_CACHE must be 0 (double check against callers only doing
3824 * I/O when B_CACHE is 0).
3826 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3827 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3829 if (bp->b_flags & B_VMIO) {
3833 KASSERT(bp->b_loffset != NOOFFSET,
3834 ("vfs_busy_pages: no buffer offset"));
3837 * Loop until none of the pages are busy.
3840 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3841 vm_page_t m = bp->b_xio.xio_pages[i];
3843 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3848 * Setup for I/O, soft-busy the page right now because
3849 * the next loop may block.
3851 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3852 vm_page_t m = bp->b_xio.xio_pages[i];
3854 vm_page_flag_clear(m, PG_ZERO);
3855 if ((bp->b_flags & B_CLUSTER) == 0) {
3856 vm_object_pip_add(obj, 1);
3857 vm_page_io_start(m);
3862 * Adjust protections for I/O and do bogus-page mapping.
3863 * Assume that vm_page_protect() can block (it can block
3864 * if VM_PROT_NONE, don't take any chances regardless).
3866 * In particular note that for writes we must incorporate
3867 * page dirtyness from the VM system into the buffer's
3870 * For reads we theoretically must incorporate page dirtyness
3871 * from the VM system to determine if the page needs bogus
3872 * replacement, but we shortcut the test by simply checking
3873 * that all m->valid bits are set, indicating that the page
3874 * is fully valid and does not need to be re-read. For any
3875 * VM system dirtyness the page will also be fully valid
3876 * since it was mapped at one point.
3879 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3880 vm_page_t m = bp->b_xio.xio_pages[i];
3882 vm_page_flag_clear(m, PG_ZERO); /* XXX */
3883 if (bp->b_cmd == BUF_CMD_WRITE) {
3885 * When readying a vnode-backed buffer for
3886 * a write we must zero-fill any invalid
3887 * portions of the backing VM pages, mark
3888 * it valid and clear related dirty bits.
3890 * vfs_clean_one_page() incorporates any
3891 * VM dirtyness and updates the b_dirtyoff
3892 * range (after we've made the page RO).
3894 * It is also expected that the pmap modified
3895 * bit has already been cleared by the
3896 * vm_page_protect(). We may not be able
3897 * to clear all dirty bits for a page if it
3898 * was also memory mapped (NFS).
3900 * Finally be sure to unassign any swap-cache
3901 * backing store as it is now stale.
3903 vm_page_protect(m, VM_PROT_READ);
3904 vfs_clean_one_page(bp, i, m);
3905 swap_pager_unswapped(m);
3906 } else if (m->valid == VM_PAGE_BITS_ALL) {
3908 * When readying a vnode-backed buffer for
3909 * read we must replace any dirty pages with
3910 * a bogus page so dirty data is not destroyed
3911 * when filling gaps.
3913 * To avoid testing whether the page is
3914 * dirty we instead test that the page was
3915 * at some point mapped (m->valid fully
3916 * valid) with the understanding that
3917 * this also covers the dirty case.
3919 bp->b_xio.xio_pages[i] = bogus_page;
3921 } else if (m->valid & m->dirty) {
3923 * This case should not occur as partial
3924 * dirtyment can only happen if the buffer
3925 * is B_CACHE, and this code is not entered
3926 * if the buffer is B_CACHE.
3928 kprintf("Warning: vfs_busy_pages - page not "
3929 "fully valid! loff=%jx bpf=%08x "
3930 "idx=%d val=%02x dir=%02x\n",
3931 (intmax_t)bp->b_loffset, bp->b_flags,
3932 i, m->valid, m->dirty);
3933 vm_page_protect(m, VM_PROT_NONE);
3936 * The page is not valid and can be made
3939 vm_page_protect(m, VM_PROT_NONE);
3943 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3944 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3949 * This is the easiest place to put the process accounting for the I/O
3953 if (bp->b_cmd == BUF_CMD_READ)
3954 lp->lwp_ru.ru_inblock++;
3956 lp->lwp_ru.ru_oublock++;
3963 * Tell the VM system that the pages associated with this buffer
3964 * are clean. This is used for delayed writes where the data is
3965 * going to go to disk eventually without additional VM intevention.
3967 * Note that while we only really need to clean through to b_bcount, we
3968 * just go ahead and clean through to b_bufsize.
3971 vfs_clean_pages(struct buf *bp)
3976 if ((bp->b_flags & B_VMIO) == 0)
3979 KASSERT(bp->b_loffset != NOOFFSET,
3980 ("vfs_clean_pages: no buffer offset"));
3982 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3983 m = bp->b_xio.xio_pages[i];
3984 vfs_clean_one_page(bp, i, m);
3989 * vfs_clean_one_page:
3991 * Set the valid bits and clear the dirty bits in a page within a
3992 * buffer. The range is restricted to the buffer's size and the
3993 * buffer's logical offset might index into the first page.
3995 * The caller has busied or soft-busied the page and it is not mapped,
3996 * test and incorporate the dirty bits into b_dirtyoff/end before
3997 * clearing them. Note that we need to clear the pmap modified bits
3998 * after determining the the page was dirty, vm_page_set_validclean()
3999 * does not do it for us.
4001 * This routine is typically called after a read completes (dirty should
4002 * be zero in that case as we are not called on bogus-replace pages),
4003 * or before a write is initiated.
4006 vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m)
4014 * Calculate offset range within the page but relative to buffer's
4015 * loffset. loffset might be offset into the first page.
4017 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
4018 bcount = bp->b_bcount + xoff; /* offset adjusted */
4024 soff = (pageno << PAGE_SHIFT);
4025 eoff = soff + PAGE_SIZE;
4033 * Test dirty bits and adjust b_dirtyoff/end.
4035 * If dirty pages are incorporated into the bp any prior
4036 * B_NEEDCOMMIT state (NFS) must be cleared because the
4037 * caller has not taken into account the new dirty data.
4039 * If the page was memory mapped the dirty bits might go beyond the
4040 * end of the buffer, but we can't really make the assumption that
4041 * a file EOF straddles the buffer (even though this is the case for
4042 * NFS if B_NEEDCOMMIT is also set). So for the purposes of clearing
4043 * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
4044 * This also saves some console spam.
4046 * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK,
4047 * NFS can handle huge commits but not huge writes.
4049 vm_page_test_dirty(m);
4051 if ((bp->b_flags & B_NEEDCOMMIT) &&
4052 (m->dirty & vm_page_bits(soff & PAGE_MASK, eoff - soff))) {
4054 kprintf("Warning: vfs_clean_one_page: bp %p "
4055 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT"
4056 " cmd %d vd %02x/%02x x/s/e %d %d %d "
4058 bp, (intmax_t)bp->b_loffset, bp->b_bcount,
4059 bp->b_flags, bp->b_cmd,
4060 m->valid, m->dirty, xoff, soff, eoff,
4061 bp->b_dirtyoff, bp->b_dirtyend);
4062 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
4067 * Only clear the pmap modified bits if ALL the dirty bits
4068 * are set, otherwise the system might mis-clear portions
4071 if (m->dirty == VM_PAGE_BITS_ALL &&
4072 (bp->b_flags & B_NEEDCOMMIT) == 0) {
4073 pmap_clear_modify(m);
4075 if (bp->b_dirtyoff > soff - xoff)
4076 bp->b_dirtyoff = soff - xoff;
4077 if (bp->b_dirtyend < eoff - xoff)
4078 bp->b_dirtyend = eoff - xoff;
4082 * Set related valid bits, clear related dirty bits.
4083 * Does not mess with the pmap modified bit.
4085 * WARNING! We cannot just clear all of m->dirty here as the
4086 * buffer cache buffers may use a DEV_BSIZE'd aligned
4087 * block size, or have an odd size (e.g. NFS at file EOF).
4088 * The putpages code can clear m->dirty to 0.
4090 * If a VOP_WRITE generates a buffer cache buffer which
4091 * covers the same space as mapped writable pages the
4092 * buffer flush might not be able to clear all the dirty
4093 * bits and still require a putpages from the VM system
4096 vm_page_set_validclean(m, soff & PAGE_MASK, eoff - soff);
4102 * Clear a buffer. This routine essentially fakes an I/O, so we need
4103 * to clear B_ERROR and B_INVAL.
4105 * Note that while we only theoretically need to clear through b_bcount,
4106 * we go ahead and clear through b_bufsize.
4110 vfs_bio_clrbuf(struct buf *bp)
4114 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
4115 bp->b_flags &= ~(B_INVAL | B_EINTR | B_ERROR);
4116 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4117 (bp->b_loffset & PAGE_MASK) == 0) {
4118 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4119 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
4123 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
4124 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
4125 bzero(bp->b_data, bp->b_bufsize);
4126 bp->b_xio.xio_pages[0]->valid |= mask;
4132 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
4133 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
4134 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
4135 ea = (caddr_t)(vm_offset_t)ulmin(
4136 (u_long)(vm_offset_t)ea,
4137 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
4138 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4139 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
4141 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
4142 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
4146 for (; sa < ea; sa += DEV_BSIZE, j++) {
4147 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
4148 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
4149 bzero(sa, DEV_BSIZE);
4152 bp->b_xio.xio_pages[i]->valid |= mask;
4153 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
4162 * vm_hold_load_pages:
4164 * Load pages into the buffer's address space. The pages are
4165 * allocated from the kernel object in order to reduce interference
4166 * with the any VM paging I/O activity. The range of loaded
4167 * pages will be wired.
4169 * If a page cannot be allocated, the 'pagedaemon' is woken up to
4170 * retrieve the full range (to - from) of pages.
4174 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4180 to = round_page(to);
4181 from = round_page(from);
4182 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4187 * Note: must allocate system pages since blocking here
4188 * could intefere with paging I/O, no matter which
4191 p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT,
4192 (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
4195 p->valid = VM_PAGE_BITS_ALL;
4196 vm_page_flag_clear(p, PG_ZERO);
4197 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
4198 bp->b_xio.xio_pages[index] = p;
4205 bp->b_xio.xio_npages = index;
4209 * Allocate pages for a buffer cache buffer.
4211 * Under extremely severe memory conditions even allocating out of the
4212 * system reserve can fail. If this occurs we must allocate out of the
4213 * interrupt reserve to avoid a deadlock with the pageout daemon.
4215 * The pageout daemon can run (putpages -> VOP_WRITE -> getblk -> allocbuf).
4216 * If the buffer cache's vm_page_alloc() fails a vm_wait() can deadlock
4217 * against the pageout daemon if pages are not freed from other sources.
4221 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit)
4226 * Try a normal allocation, allow use of system reserve.
4228 p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
4233 * The normal allocation failed and we clearly have a page
4234 * deficit. Try to reclaim some clean VM pages directly
4235 * from the buffer cache.
4237 vm_pageout_deficit += deficit;
4241 * We may have blocked, the caller will know what to do if the
4244 if (vm_page_lookup(obj, pg))
4248 * Allocate and allow use of the interrupt reserve.
4250 * If after all that we still can't allocate a VM page we are
4251 * in real trouble, but we slog on anyway hoping that the system
4254 p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
4255 VM_ALLOC_INTERRUPT);
4257 if (vm_page_count_severe()) {
4258 kprintf("bio_page_alloc: WARNING emergency page "
4263 kprintf("bio_page_alloc: WARNING emergency page "
4264 "allocation failed\n");
4271 * vm_hold_free_pages:
4273 * Return pages associated with the buffer back to the VM system.
4275 * The range of pages underlying the buffer's address space will
4276 * be unmapped and un-wired.
4279 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4283 int index, newnpages;
4285 from = round_page(from);
4286 to = round_page(to);
4287 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4289 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4290 p = bp->b_xio.xio_pages[index];
4291 if (p && (index < bp->b_xio.xio_npages)) {
4293 kprintf("vm_hold_free_pages: doffset: %lld, "
4295 (long long)bp->b_bio2.bio_offset,
4296 (long long)bp->b_loffset);
4298 bp->b_xio.xio_pages[index] = NULL;
4301 vm_page_unwire(p, 0);
4305 bp->b_xio.xio_npages = newnpages;
4311 * Map a user buffer into KVM via a pbuf. On return the buffer's
4312 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
4316 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
4327 * bp had better have a command and it better be a pbuf.
4329 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4330 KKASSERT(bp->b_flags & B_PAGING);
4336 * Map the user data into KVM. Mappings have to be page-aligned.
4338 addr = (caddr_t)trunc_page((vm_offset_t)udata);
4341 vmprot = VM_PROT_READ;
4342 if (bp->b_cmd == BUF_CMD_READ)
4343 vmprot |= VM_PROT_WRITE;
4345 while (addr < udata + bytes) {
4347 * Do the vm_fault if needed; do the copy-on-write thing
4348 * when reading stuff off device into memory.
4350 * vm_fault_page*() returns a held VM page.
4352 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
4353 va = trunc_page(va);
4355 m = vm_fault_page_quick(va, vmprot, &error);
4357 for (i = 0; i < pidx; ++i) {
4358 vm_page_unhold(bp->b_xio.xio_pages[i]);
4359 bp->b_xio.xio_pages[i] = NULL;
4363 bp->b_xio.xio_pages[pidx] = m;
4369 * Map the page array and set the buffer fields to point to
4370 * the mapped data buffer.
4372 if (pidx > btoc(MAXPHYS))
4373 panic("vmapbuf: mapped more than MAXPHYS");
4374 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
4376 bp->b_xio.xio_npages = pidx;
4377 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
4378 bp->b_bcount = bytes;
4379 bp->b_bufsize = bytes;
4386 * Free the io map PTEs associated with this IO operation.
4387 * We also invalidate the TLB entries and restore the original b_addr.
4390 vunmapbuf(struct buf *bp)
4395 KKASSERT(bp->b_flags & B_PAGING);
4397 npages = bp->b_xio.xio_npages;
4398 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4399 for (pidx = 0; pidx < npages; ++pidx) {
4400 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
4401 bp->b_xio.xio_pages[pidx] = NULL;
4403 bp->b_xio.xio_npages = 0;
4404 bp->b_data = bp->b_kvabase;
4408 * Scan all buffers in the system and issue the callback.
4411 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
4417 for (n = 0; n < nbuf; ++n) {
4418 if ((error = callback(&buf[n], info)) < 0) {
4428 * print out statistics from the current status of the buffer pool
4429 * this can be toggeled by the system control option debug.syncprt
4438 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
4439 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
4441 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
4443 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4446 TAILQ_FOREACH(bp, dp, b_freelist) {
4447 counts[bp->b_bufsize/PAGE_SIZE]++;
4451 kprintf("%s: total-%d", bname[i], count);
4452 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4454 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
4462 DB_SHOW_COMMAND(buffer, db_show_buffer)
4465 struct buf *bp = (struct buf *)addr;
4468 db_printf("usage: show buffer <addr>\n");
4472 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4473 db_printf("b_cmd = %d\n", bp->b_cmd);
4474 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
4475 "b_resid = %d\n, b_data = %p, "
4476 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
4477 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4479 (long long)bp->b_bio2.bio_offset,
4480 (long long)(bp->b_bio2.bio_next ?
4481 bp->b_bio2.bio_next->bio_offset : (off_t)-1));
4482 if (bp->b_xio.xio_npages) {
4484 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
4485 bp->b_xio.xio_npages);
4486 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4488 m = bp->b_xio.xio_pages[i];
4489 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4490 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4491 if ((i + 1) < bp->b_xio.xio_npages)