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>
58 #include <sys/thread2.h>
59 #include <sys/spinlock2.h>
60 #include <sys/mplock2.h>
61 #include <vm/vm_page2.h>
72 BQUEUE_NONE, /* not on any queue */
73 BQUEUE_LOCKED, /* locked buffers */
74 BQUEUE_CLEAN, /* non-B_DELWRI buffers */
75 BQUEUE_DIRTY, /* B_DELWRI buffers */
76 BQUEUE_DIRTY_HW, /* B_DELWRI buffers - heavy weight */
77 BQUEUE_EMPTYKVA, /* empty buffer headers with KVA assignment */
78 BQUEUE_EMPTY, /* empty buffer headers */
80 BUFFER_QUEUES /* number of buffer queues */
83 typedef enum bufq_type bufq_type_t;
85 #define BD_WAKE_SIZE 16384
86 #define BD_WAKE_MASK (BD_WAKE_SIZE - 1)
88 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
89 struct spinlock bufspin = SPINLOCK_INITIALIZER(&bufspin);
91 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
93 struct buf *buf; /* buffer header pool */
95 static void vfs_clean_pages(struct buf *bp);
96 static void vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m);
97 static void vfs_vmio_release(struct buf *bp);
98 static int flushbufqueues(bufq_type_t q);
99 static vm_page_t bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit);
101 static void bd_signal(int totalspace);
102 static void buf_daemon(void);
103 static void buf_daemon_hw(void);
106 * bogus page -- for I/O to/from partially complete buffers
107 * this is a temporary solution to the problem, but it is not
108 * really that bad. it would be better to split the buffer
109 * for input in the case of buffers partially already in memory,
110 * but the code is intricate enough already.
112 vm_page_t bogus_page;
115 * These are all static, but make the ones we export globals so we do
116 * not need to use compiler magic.
118 int bufspace, maxbufspace,
119 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
120 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
121 static int lorunningspace, hirunningspace, runningbufreq;
122 int dirtybufspace, dirtybufspacehw, lodirtybufspace, hidirtybufspace;
123 int dirtybufcount, dirtybufcounthw;
124 int runningbufspace, runningbufcount;
125 static int getnewbufcalls;
126 static int getnewbufrestarts;
127 static int recoverbufcalls;
128 static int needsbuffer; /* locked by needsbuffer_spin */
129 static int bd_request; /* locked by needsbuffer_spin */
130 static int bd_request_hw; /* locked by needsbuffer_spin */
131 static u_int bd_wake_ary[BD_WAKE_SIZE];
132 static u_int bd_wake_index;
133 static u_int vm_cycle_point = ACT_INIT + ACT_ADVANCE * 6;
134 static struct spinlock needsbuffer_spin;
135 static int debug_commit;
137 static struct thread *bufdaemon_td;
138 static struct thread *bufdaemonhw_td;
142 * Sysctls for operational control of the buffer cache.
144 SYSCTL_INT(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
145 "Number of dirty buffers to flush before bufdaemon becomes inactive");
146 SYSCTL_INT(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
147 "High watermark used to trigger explicit flushing of dirty buffers");
148 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
149 "Minimum amount of buffer space required for active I/O");
150 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
151 "Maximum amount of buffer space to usable for active I/O");
152 SYSCTL_UINT(_vfs, OID_AUTO, vm_cycle_point, CTLFLAG_RW, &vm_cycle_point, 0,
153 "Recycle pages to active or inactive queue transition pt 0-64");
155 * Sysctls determining current state of the buffer cache.
157 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
158 "Total number of buffers in buffer cache");
159 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
160 "Pending bytes of dirty buffers (all)");
161 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
162 "Pending bytes of dirty buffers (heavy weight)");
163 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
164 "Pending number of dirty buffers");
165 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
166 "Pending number of dirty buffers (heavy weight)");
167 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
168 "I/O bytes currently in progress due to asynchronous writes");
169 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
170 "I/O buffers currently in progress due to asynchronous writes");
171 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
172 "Hard limit on maximum amount of memory usable for buffer space");
173 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
174 "Soft limit on maximum amount of memory usable for buffer space");
175 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
176 "Minimum amount of memory to reserve for system buffer space");
177 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
178 "Amount of memory available for buffers");
179 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
180 0, "Maximum amount of memory reserved for buffers using malloc");
181 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
182 "Amount of memory left for buffers using malloc-scheme");
183 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
184 "New buffer header acquisition requests");
185 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
186 0, "New buffer header acquisition restarts");
187 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
188 "Recover VM space in an emergency");
189 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
190 "Buffer acquisition restarts due to fragmented buffer map");
191 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
192 "Amount of time KVA space was deallocated in an arbitrary buffer");
193 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
194 "Amount of time buffer re-use operations were successful");
195 SYSCTL_INT(_vfs, OID_AUTO, debug_commit, CTLFLAG_RW, &debug_commit, 0, "");
196 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
197 "sizeof(struct buf)");
199 char *buf_wmesg = BUF_WMESG;
201 extern int vm_swap_size;
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);
1411 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1412 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1414 if (bp->b_flags & (B_INVAL | B_RELBUF))
1415 vfs_vmio_release(bp);
1419 * Rundown for non-VMIO buffers.
1421 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1425 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1432 if (bp->b_qindex != BQUEUE_NONE)
1433 panic("brelse: free buffer onto another queue???");
1434 if (BUF_REFCNTNB(bp) > 1) {
1435 /* Temporary panic to verify exclusive locking */
1436 /* This panic goes away when we allow shared refs */
1437 panic("brelse: multiple refs");
1443 * Figure out the correct queue to place the cleaned up buffer on.
1444 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1445 * disassociated from their vnode.
1447 spin_lock_wr(&bufspin);
1448 if (bp->b_flags & B_LOCKED) {
1450 * Buffers that are locked are placed in the locked queue
1451 * immediately, regardless of their state.
1453 bp->b_qindex = BQUEUE_LOCKED;
1454 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1455 } else if (bp->b_bufsize == 0) {
1457 * Buffers with no memory. Due to conditionals near the top
1458 * of brelse() such buffers should probably already be
1459 * marked B_INVAL and disassociated from their vnode.
1461 bp->b_flags |= B_INVAL;
1462 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1463 KKASSERT((bp->b_flags & B_HASHED) == 0);
1464 if (bp->b_kvasize) {
1465 bp->b_qindex = BQUEUE_EMPTYKVA;
1467 bp->b_qindex = BQUEUE_EMPTY;
1469 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1470 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) {
1472 * Buffers with junk contents. Again these buffers had better
1473 * already be disassociated from their vnode.
1475 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1476 KKASSERT((bp->b_flags & B_HASHED) == 0);
1477 bp->b_flags |= B_INVAL;
1478 bp->b_qindex = BQUEUE_CLEAN;
1479 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1482 * Remaining buffers. These buffers are still associated with
1485 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1487 bp->b_qindex = BQUEUE_DIRTY;
1488 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1490 case B_DELWRI | B_HEAVY:
1491 bp->b_qindex = BQUEUE_DIRTY_HW;
1492 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1497 * NOTE: Buffers are always placed at the end of the
1498 * queue. If B_AGE is not set the buffer will cycle
1499 * through the queue twice.
1501 bp->b_qindex = BQUEUE_CLEAN;
1502 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1506 spin_unlock_wr(&bufspin);
1509 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1510 * on the correct queue.
1512 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1516 * The bp is on an appropriate queue unless locked. If it is not
1517 * locked or dirty we can wakeup threads waiting for buffer space.
1519 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1520 * if B_INVAL is set ).
1522 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1526 * Something we can maybe free or reuse
1528 if (bp->b_bufsize || bp->b_kvasize)
1532 * Clean up temporary flags and unlock the buffer.
1534 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF | B_DIRECT);
1541 * Release a buffer back to the appropriate queue but do not try to free
1542 * it. The buffer is expected to be used again soon.
1544 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1545 * biodone() to requeue an async I/O on completion. It is also used when
1546 * known good buffers need to be requeued but we think we may need the data
1549 * XXX we should be able to leave the B_RELBUF hint set on completion.
1554 bqrelse(struct buf *bp)
1556 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1558 if (bp->b_qindex != BQUEUE_NONE)
1559 panic("bqrelse: free buffer onto another queue???");
1560 if (BUF_REFCNTNB(bp) > 1) {
1561 /* do not release to free list */
1562 panic("bqrelse: multiple refs");
1566 buf_act_advance(bp);
1568 spin_lock_wr(&bufspin);
1569 if (bp->b_flags & B_LOCKED) {
1571 * Locked buffers are released to the locked queue. However,
1572 * if the buffer is dirty it will first go into the dirty
1573 * queue and later on after the I/O completes successfully it
1574 * will be released to the locked queue.
1576 bp->b_qindex = BQUEUE_LOCKED;
1577 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1578 } else if (bp->b_flags & B_DELWRI) {
1579 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1580 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1581 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1582 } else if (vm_page_count_severe()) {
1584 * We are too low on memory, we have to try to free the
1585 * buffer (most importantly: the wired pages making up its
1586 * backing store) *now*.
1588 spin_unlock_wr(&bufspin);
1592 bp->b_qindex = BQUEUE_CLEAN;
1593 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1595 spin_unlock_wr(&bufspin);
1597 if ((bp->b_flags & B_LOCKED) == 0 &&
1598 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1603 * Something we can maybe free or reuse.
1605 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1609 * Final cleanup and unlock. Clear bits that are only used while a
1610 * buffer is actively locked.
1612 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF);
1619 * Return backing pages held by the buffer 'bp' back to the VM system
1620 * if possible. The pages are freed if they are no longer valid or
1621 * attempt to free if it was used for direct I/O otherwise they are
1622 * sent to the page cache.
1624 * Pages that were marked busy are left alone and skipped.
1626 * The KVA mapping (b_data) for the underlying pages is removed by
1630 vfs_vmio_release(struct buf *bp)
1636 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1637 m = bp->b_xio.xio_pages[i];
1638 bp->b_xio.xio_pages[i] = NULL;
1641 * This is a very important bit of code. We try to track
1642 * VM page use whether the pages are wired into the buffer
1643 * cache or not. While wired into the buffer cache the
1644 * bp tracks the act_count.
1646 * We can choose to place unwired pages on the inactive
1647 * queue (0) or active queue (1). If we place too many
1648 * on the active queue the queue will cycle the act_count
1649 * on pages we'd like to keep, just from single-use pages
1650 * (such as when doing a tar-up or file scan).
1652 if (bp->b_act_count < vm_cycle_point)
1653 vm_page_unwire(m, 0);
1655 vm_page_unwire(m, 1);
1658 * We don't mess with busy pages, it is
1659 * the responsibility of the process that
1660 * busied the pages to deal with them.
1662 if ((m->flags & PG_BUSY) || (m->busy != 0))
1665 if (m->wire_count == 0) {
1666 vm_page_flag_clear(m, PG_ZERO);
1668 * Might as well free the page if we can and it has
1669 * no valid data. We also free the page if the
1670 * buffer was used for direct I/O.
1673 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1674 m->hold_count == 0) {
1676 vm_page_protect(m, VM_PROT_NONE);
1680 if (bp->b_flags & B_DIRECT) {
1681 vm_page_try_to_free(m);
1682 } else if (vm_page_count_severe()) {
1683 m->act_count = bp->b_act_count;
1684 vm_page_try_to_cache(m);
1686 m->act_count = bp->b_act_count;
1691 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1692 if (bp->b_bufsize) {
1696 bp->b_xio.xio_npages = 0;
1697 bp->b_flags &= ~B_VMIO;
1698 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1709 * Implement clustered async writes for clearing out B_DELWRI buffers.
1710 * This is much better then the old way of writing only one buffer at
1711 * a time. Note that we may not be presented with the buffers in the
1712 * correct order, so we search for the cluster in both directions.
1714 * The buffer is locked on call.
1717 vfs_bio_awrite(struct buf *bp)
1721 off_t loffset = bp->b_loffset;
1722 struct vnode *vp = bp->b_vp;
1729 * right now we support clustered writing only to regular files. If
1730 * we find a clusterable block we could be in the middle of a cluster
1731 * rather then at the beginning.
1733 * NOTE: b_bio1 contains the logical loffset and is aliased
1734 * to b_loffset. b_bio2 contains the translated block number.
1736 if ((vp->v_type == VREG) &&
1737 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1738 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1740 size = vp->v_mount->mnt_stat.f_iosize;
1742 for (i = size; i < MAXPHYS; i += size) {
1743 if ((bpa = findblk(vp, loffset + i, FINDBLK_TEST)) &&
1744 BUF_REFCNT(bpa) == 0 &&
1745 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1746 (B_DELWRI | B_CLUSTEROK)) &&
1747 (bpa->b_bufsize == size)) {
1748 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1749 (bpa->b_bio2.bio_offset !=
1750 bp->b_bio2.bio_offset + i))
1756 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1757 if ((bpa = findblk(vp, loffset - j, FINDBLK_TEST)) &&
1758 BUF_REFCNT(bpa) == 0 &&
1759 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1760 (B_DELWRI | B_CLUSTEROK)) &&
1761 (bpa->b_bufsize == size)) {
1762 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1763 (bpa->b_bio2.bio_offset !=
1764 bp->b_bio2.bio_offset - j))
1774 * this is a possible cluster write
1776 if (nbytes != size) {
1778 nwritten = cluster_wbuild(vp, size,
1779 loffset - j, nbytes);
1785 * default (old) behavior, writing out only one block
1787 * XXX returns b_bufsize instead of b_bcount for nwritten?
1789 nwritten = bp->b_bufsize;
1799 * Find and initialize a new buffer header, freeing up existing buffers
1800 * in the bufqueues as necessary. The new buffer is returned locked.
1802 * Important: B_INVAL is not set. If the caller wishes to throw the
1803 * buffer away, the caller must set B_INVAL prior to calling brelse().
1806 * We have insufficient buffer headers
1807 * We have insufficient buffer space
1808 * buffer_map is too fragmented ( space reservation fails )
1809 * If we have to flush dirty buffers ( but we try to avoid this )
1811 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1812 * Instead we ask the buf daemon to do it for us. We attempt to
1813 * avoid piecemeal wakeups of the pageout daemon.
1818 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1824 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1825 static int flushingbufs;
1828 * We can't afford to block since we might be holding a vnode lock,
1829 * which may prevent system daemons from running. We deal with
1830 * low-memory situations by proactively returning memory and running
1831 * async I/O rather then sync I/O.
1835 --getnewbufrestarts;
1837 ++getnewbufrestarts;
1840 * Setup for scan. If we do not have enough free buffers,
1841 * we setup a degenerate case that immediately fails. Note
1842 * that if we are specially marked process, we are allowed to
1843 * dip into our reserves.
1845 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1847 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1848 * However, there are a number of cases (defragging, reusing, ...)
1849 * where we cannot backup.
1851 nqindex = BQUEUE_EMPTYKVA;
1852 spin_lock_wr(&bufspin);
1853 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1857 * If no EMPTYKVA buffers and we are either
1858 * defragging or reusing, locate a CLEAN buffer
1859 * to free or reuse. If bufspace useage is low
1860 * skip this step so we can allocate a new buffer.
1862 if (defrag || bufspace >= lobufspace) {
1863 nqindex = BQUEUE_CLEAN;
1864 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1868 * If we could not find or were not allowed to reuse a
1869 * CLEAN buffer, check to see if it is ok to use an EMPTY
1870 * buffer. We can only use an EMPTY buffer if allocating
1871 * its KVA would not otherwise run us out of buffer space.
1873 if (nbp == NULL && defrag == 0 &&
1874 bufspace + maxsize < hibufspace) {
1875 nqindex = BQUEUE_EMPTY;
1876 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1881 * Run scan, possibly freeing data and/or kva mappings on the fly
1884 * WARNING! bufspin is held!
1886 while ((bp = nbp) != NULL) {
1887 int qindex = nqindex;
1889 nbp = TAILQ_NEXT(bp, b_freelist);
1892 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
1893 * cycles through the queue twice before being selected.
1895 if (qindex == BQUEUE_CLEAN &&
1896 (bp->b_flags & B_AGE) == 0 && nbp) {
1897 bp->b_flags |= B_AGE;
1898 TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
1899 TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
1904 * Calculate next bp ( we can only use it if we do not block
1905 * or do other fancy things ).
1910 nqindex = BQUEUE_EMPTYKVA;
1911 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1914 case BQUEUE_EMPTYKVA:
1915 nqindex = BQUEUE_CLEAN;
1916 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1930 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1933 * Note: we no longer distinguish between VMIO and non-VMIO
1937 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1940 * If we are defragging then we need a buffer with
1941 * b_kvasize != 0. XXX this situation should no longer
1942 * occur, if defrag is non-zero the buffer's b_kvasize
1943 * should also be non-zero at this point. XXX
1945 if (defrag && bp->b_kvasize == 0) {
1946 kprintf("Warning: defrag empty buffer %p\n", bp);
1951 * Start freeing the bp. This is somewhat involved. nbp
1952 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1953 * on the clean list must be disassociated from their
1954 * current vnode. Buffers on the empty[kva] lists have
1955 * already been disassociated.
1958 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1959 spin_unlock_wr(&bufspin);
1960 kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1961 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1964 if (bp->b_qindex != qindex) {
1965 spin_unlock_wr(&bufspin);
1966 kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1970 bremfree_locked(bp);
1971 spin_unlock_wr(&bufspin);
1974 * Dependancies must be handled before we disassociate the
1977 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1978 * be immediately disassociated. HAMMER then becomes
1979 * responsible for releasing the buffer.
1981 * NOTE: bufspin is UNLOCKED now.
1983 if (LIST_FIRST(&bp->b_dep) != NULL) {
1987 if (bp->b_flags & B_LOCKED) {
1991 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1994 if (qindex == BQUEUE_CLEAN) {
1996 if (bp->b_flags & B_VMIO) {
1998 vfs_vmio_release(bp);
2007 * NOTE: nbp is now entirely invalid. We can only restart
2008 * the scan from this point on.
2010 * Get the rest of the buffer freed up. b_kva* is still
2011 * valid after this operation.
2014 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
2015 KKASSERT((bp->b_flags & B_HASHED) == 0);
2018 * critical section protection is not required when
2019 * scrapping a buffer's contents because it is already
2022 if (bp->b_bufsize) {
2028 bp->b_flags = B_BNOCLIP;
2029 bp->b_cmd = BUF_CMD_DONE;
2034 bp->b_xio.xio_npages = 0;
2035 bp->b_dirtyoff = bp->b_dirtyend = 0;
2036 bp->b_act_count = ACT_INIT;
2038 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2040 if (blkflags & GETBLK_BHEAVY)
2041 bp->b_flags |= B_HEAVY;
2044 * If we are defragging then free the buffer.
2047 bp->b_flags |= B_INVAL;
2055 * If we are overcomitted then recover the buffer and its
2056 * KVM space. This occurs in rare situations when multiple
2057 * processes are blocked in getnewbuf() or allocbuf().
2059 if (bufspace >= hibufspace)
2061 if (flushingbufs && bp->b_kvasize != 0) {
2062 bp->b_flags |= B_INVAL;
2067 if (bufspace < lobufspace)
2070 /* NOT REACHED, bufspin not held */
2074 * If we exhausted our list, sleep as appropriate. We may have to
2075 * wakeup various daemons and write out some dirty buffers.
2077 * Generally we are sleeping due to insufficient buffer space.
2079 * NOTE: bufspin is held if bp is NULL, else it is not held.
2085 spin_unlock_wr(&bufspin);
2087 flags = VFS_BIO_NEED_BUFSPACE;
2089 } else if (bufspace >= hibufspace) {
2091 flags = VFS_BIO_NEED_BUFSPACE;
2094 flags = VFS_BIO_NEED_ANY;
2097 needsbuffer |= flags;
2098 bd_speedup(); /* heeeelp */
2099 while (needsbuffer & flags) {
2100 if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
2105 * We finally have a valid bp. We aren't quite out of the
2106 * woods, we still have to reserve kva space. In order
2107 * to keep fragmentation sane we only allocate kva in
2110 * (bufspin is not held)
2112 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2114 if (maxsize != bp->b_kvasize) {
2115 vm_offset_t addr = 0;
2121 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2122 vm_map_lock(&buffer_map);
2124 if (vm_map_findspace(&buffer_map,
2125 vm_map_min(&buffer_map), maxsize,
2126 maxsize, 0, &addr)) {
2128 * Uh oh. Buffer map is too fragmented. We
2129 * must defragment the map.
2131 vm_map_unlock(&buffer_map);
2132 vm_map_entry_release(count);
2135 bp->b_flags |= B_INVAL;
2141 vm_map_insert(&buffer_map, &count,
2143 addr, addr + maxsize,
2145 VM_PROT_ALL, VM_PROT_ALL,
2148 bp->b_kvabase = (caddr_t) addr;
2149 bp->b_kvasize = maxsize;
2150 bufspace += bp->b_kvasize;
2153 vm_map_unlock(&buffer_map);
2154 vm_map_entry_release(count);
2157 bp->b_data = bp->b_kvabase;
2163 * This routine is called in an emergency to recover VM pages from the
2164 * buffer cache by cashing in clean buffers. The idea is to recover
2165 * enough pages to be able to satisfy a stuck bio_page_alloc().
2168 recoverbufpages(void)
2175 spin_lock_wr(&bufspin);
2176 while (bytes < MAXBSIZE) {
2177 bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
2182 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
2183 * cycles through the queue twice before being selected.
2185 if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) {
2186 bp->b_flags |= B_AGE;
2187 TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
2188 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN],
2196 KKASSERT(bp->b_qindex == BQUEUE_CLEAN);
2197 KKASSERT((bp->b_flags & B_DELWRI) == 0);
2200 * Start freeing the bp. This is somewhat involved.
2202 * Buffers on the clean list must be disassociated from
2203 * their current vnode
2206 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2207 kprintf("recoverbufpages: warning, locked buf %p, race corrected\n", bp);
2208 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
2211 if (bp->b_qindex != BQUEUE_CLEAN) {
2212 kprintf("recoverbufpages: warning, BUF_LOCK blocked unexpectedly on buf %p index %d, race corrected\n", bp, bp->b_qindex);
2216 bremfree_locked(bp);
2217 spin_unlock_wr(&bufspin);
2220 * Dependancies must be handled before we disassociate the
2223 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2224 * be immediately disassociated. HAMMER then becomes
2225 * responsible for releasing the buffer.
2227 if (LIST_FIRST(&bp->b_dep) != NULL) {
2229 if (bp->b_flags & B_LOCKED) {
2231 spin_lock_wr(&bufspin);
2234 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2237 bytes += bp->b_bufsize;
2240 if (bp->b_flags & B_VMIO) {
2241 bp->b_flags |= B_DIRECT; /* try to free pages */
2242 vfs_vmio_release(bp);
2247 KKASSERT(bp->b_vp == NULL);
2248 KKASSERT((bp->b_flags & B_HASHED) == 0);
2251 * critical section protection is not required when
2252 * scrapping a buffer's contents because it is already
2259 bp->b_flags = B_BNOCLIP;
2260 bp->b_cmd = BUF_CMD_DONE;
2265 bp->b_xio.xio_npages = 0;
2266 bp->b_dirtyoff = bp->b_dirtyend = 0;
2268 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2270 bp->b_flags |= B_INVAL;
2273 spin_lock_wr(&bufspin);
2275 spin_unlock_wr(&bufspin);
2282 * Buffer flushing daemon. Buffers are normally flushed by the
2283 * update daemon but if it cannot keep up this process starts to
2284 * take the load in an attempt to prevent getnewbuf() from blocking.
2286 * Once a flush is initiated it does not stop until the number
2287 * of buffers falls below lodirtybuffers, but we will wake up anyone
2288 * waiting at the mid-point.
2291 static struct kproc_desc buf_kp = {
2296 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2297 kproc_start, &buf_kp)
2299 static struct kproc_desc bufhw_kp = {
2304 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2305 kproc_start, &bufhw_kp)
2313 * This process needs to be suspended prior to shutdown sync.
2315 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2316 bufdaemon_td, SHUTDOWN_PRI_LAST);
2317 curthread->td_flags |= TDF_SYSTHREAD;
2320 * This process is allowed to take the buffer cache to the limit
2325 kproc_suspend_loop();
2328 * Do the flush as long as the number of dirty buffers
2329 * (including those running) exceeds lodirtybufspace.
2331 * When flushing limit running I/O to hirunningspace
2332 * Do the flush. Limit the amount of in-transit I/O we
2333 * allow to build up, otherwise we would completely saturate
2334 * the I/O system. Wakeup any waiting processes before we
2335 * normally would so they can run in parallel with our drain.
2337 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2338 * but because we split the operation into two threads we
2339 * have to cut it in half for each thread.
2341 waitrunningbufspace();
2342 limit = lodirtybufspace / 2;
2343 while (runningbufspace + dirtybufspace > limit ||
2344 dirtybufcount - dirtybufcounthw >= nbuf / 2) {
2345 if (flushbufqueues(BQUEUE_DIRTY) == 0)
2347 if (runningbufspace < hirunningspace)
2349 waitrunningbufspace();
2353 * We reached our low water mark, reset the
2354 * request and sleep until we are needed again.
2355 * The sleep is just so the suspend code works.
2357 spin_lock_wr(&needsbuffer_spin);
2358 if (bd_request == 0) {
2359 ssleep(&bd_request, &needsbuffer_spin, 0,
2363 spin_unlock_wr(&needsbuffer_spin);
2373 * This process needs to be suspended prior to shutdown sync.
2375 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2376 bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2377 curthread->td_flags |= TDF_SYSTHREAD;
2380 * This process is allowed to take the buffer cache to the limit
2385 kproc_suspend_loop();
2388 * Do the flush. Limit the amount of in-transit I/O we
2389 * allow to build up, otherwise we would completely saturate
2390 * the I/O system. Wakeup any waiting processes before we
2391 * normally would so they can run in parallel with our drain.
2393 * Once we decide to flush push the queued I/O up to
2394 * hirunningspace in order to trigger bursting by the bioq
2397 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2398 * but because we split the operation into two threads we
2399 * have to cut it in half for each thread.
2401 waitrunningbufspace();
2402 limit = lodirtybufspace / 2;
2403 while (runningbufspace + dirtybufspacehw > limit ||
2404 dirtybufcounthw >= nbuf / 2) {
2405 if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2407 if (runningbufspace < hirunningspace)
2409 waitrunningbufspace();
2413 * We reached our low water mark, reset the
2414 * request and sleep until we are needed again.
2415 * The sleep is just so the suspend code works.
2417 spin_lock_wr(&needsbuffer_spin);
2418 if (bd_request_hw == 0) {
2419 ssleep(&bd_request_hw, &needsbuffer_spin, 0,
2423 spin_unlock_wr(&needsbuffer_spin);
2430 * Try to flush a buffer in the dirty queue. We must be careful to
2431 * free up B_INVAL buffers instead of write them, which NFS is
2432 * particularly sensitive to.
2434 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate
2435 * that we really want to try to get the buffer out and reuse it
2436 * due to the write load on the machine.
2439 flushbufqueues(bufq_type_t q)
2445 spin_lock_wr(&bufspin);
2448 bp = TAILQ_FIRST(&bufqueues[q]);
2450 KASSERT((bp->b_flags & B_DELWRI),
2451 ("unexpected clean buffer %p", bp));
2453 if (bp->b_flags & B_DELWRI) {
2454 if (bp->b_flags & B_INVAL) {
2455 spin_unlock_wr(&bufspin);
2457 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2458 panic("flushbufqueues: locked buf");
2464 if (LIST_FIRST(&bp->b_dep) != NULL &&
2465 (bp->b_flags & B_DEFERRED) == 0 &&
2466 buf_countdeps(bp, 0)) {
2467 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2468 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2470 bp->b_flags |= B_DEFERRED;
2471 bp = TAILQ_FIRST(&bufqueues[q]);
2476 * Only write it out if we can successfully lock
2477 * it. If the buffer has a dependancy,
2478 * buf_checkwrite must also return 0 for us to
2479 * be able to initate the write.
2481 * If the buffer is flagged B_ERROR it may be
2482 * requeued over and over again, we try to
2483 * avoid a live lock.
2485 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2486 spin_unlock_wr(&bufspin);
2488 if (LIST_FIRST(&bp->b_dep) != NULL &&
2489 buf_checkwrite(bp)) {
2492 } else if (bp->b_flags & B_ERROR) {
2493 tsleep(bp, 0, "bioer", 1);
2494 bp->b_flags &= ~B_AGE;
2497 bp->b_flags |= B_AGE;
2504 bp = TAILQ_NEXT(bp, b_freelist);
2507 spin_unlock_wr(&bufspin);
2514 * Returns true if no I/O is needed to access the associated VM object.
2515 * This is like findblk except it also hunts around in the VM system for
2518 * Note that we ignore vm_page_free() races from interrupts against our
2519 * lookup, since if the caller is not protected our return value will not
2520 * be any more valid then otherwise once we exit the critical section.
2523 inmem(struct vnode *vp, off_t loffset)
2526 vm_offset_t toff, tinc, size;
2529 if (findblk(vp, loffset, FINDBLK_TEST))
2531 if (vp->v_mount == NULL)
2533 if ((obj = vp->v_object) == NULL)
2537 if (size > vp->v_mount->mnt_stat.f_iosize)
2538 size = vp->v_mount->mnt_stat.f_iosize;
2540 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2541 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2545 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2546 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2547 if (vm_page_is_valid(m,
2548 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2557 * Locate and return the specified buffer. Unless flagged otherwise,
2558 * a locked buffer will be returned if it exists or NULL if it does not.
2560 * findblk()'d buffers are still on the bufqueues and if you intend
2561 * to use your (locked NON-TEST) buffer you need to bremfree(bp)
2562 * and possibly do other stuff to it.
2564 * FINDBLK_TEST - Do not lock the buffer. The caller is responsible
2565 * for locking the buffer and ensuring that it remains
2566 * the desired buffer after locking.
2568 * FINDBLK_NBLOCK - Lock the buffer non-blocking. If we are unable
2569 * to acquire the lock we return NULL, even if the
2572 * (0) - Lock the buffer blocking.
2577 findblk(struct vnode *vp, off_t loffset, int flags)
2583 lkflags = LK_EXCLUSIVE;
2584 if (flags & FINDBLK_NBLOCK)
2585 lkflags |= LK_NOWAIT;
2588 lwkt_gettoken(&vlock, &vp->v_token);
2589 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2590 lwkt_reltoken(&vlock);
2591 if (bp == NULL || (flags & FINDBLK_TEST))
2593 if (BUF_LOCK(bp, lkflags)) {
2597 if (bp->b_vp == vp && bp->b_loffset == loffset)
2607 * Similar to getblk() except only returns the buffer if it is
2608 * B_CACHE and requires no other manipulation. Otherwise NULL
2611 * If B_RAM is set the buffer might be just fine, but we return
2612 * NULL anyway because we want the code to fall through to the
2613 * cluster read. Otherwise read-ahead breaks.
2616 getcacheblk(struct vnode *vp, off_t loffset)
2620 bp = findblk(vp, loffset, 0);
2622 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) == B_CACHE) {
2623 bp->b_flags &= ~B_AGE;
2636 * Get a block given a specified block and offset into a file/device.
2637 * B_INVAL may or may not be set on return. The caller should clear
2638 * B_INVAL prior to initiating a READ.
2640 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2641 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2642 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2643 * without doing any of those things the system will likely believe
2644 * the buffer to be valid (especially if it is not B_VMIO), and the
2645 * next getblk() will return the buffer with B_CACHE set.
2647 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2648 * an existing buffer.
2650 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2651 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2652 * and then cleared based on the backing VM. If the previous buffer is
2653 * non-0-sized but invalid, B_CACHE will be cleared.
2655 * If getblk() must create a new buffer, the new buffer is returned with
2656 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2657 * case it is returned with B_INVAL clear and B_CACHE set based on the
2660 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2661 * B_CACHE bit is clear.
2663 * What this means, basically, is that the caller should use B_CACHE to
2664 * determine whether the buffer is fully valid or not and should clear
2665 * B_INVAL prior to issuing a read. If the caller intends to validate
2666 * the buffer by loading its data area with something, the caller needs
2667 * to clear B_INVAL. If the caller does this without issuing an I/O,
2668 * the caller should set B_CACHE ( as an optimization ), else the caller
2669 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2670 * a write attempt or if it was a successfull read. If the caller
2671 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2672 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2676 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2677 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2682 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2685 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2689 if (size > MAXBSIZE)
2690 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2691 if (vp->v_object == NULL)
2692 panic("getblk: vnode %p has no object!", vp);
2695 if ((bp = findblk(vp, loffset, FINDBLK_TEST)) != NULL) {
2697 * The buffer was found in the cache, but we need to lock it.
2698 * Even with LK_NOWAIT the lockmgr may break our critical
2699 * section, so double-check the validity of the buffer
2700 * once the lock has been obtained.
2702 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2703 if (blkflags & GETBLK_NOWAIT)
2705 lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2706 if (blkflags & GETBLK_PCATCH)
2707 lkflags |= LK_PCATCH;
2708 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2710 if (error == ENOLCK)
2714 /* buffer may have changed on us */
2718 * Once the buffer has been locked, make sure we didn't race
2719 * a buffer recyclement. Buffers that are no longer hashed
2720 * will have b_vp == NULL, so this takes care of that check
2723 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2724 kprintf("Warning buffer %p (vp %p loffset %lld) "
2726 bp, vp, (long long)loffset);
2732 * If SZMATCH any pre-existing buffer must be of the requested
2733 * size or NULL is returned. The caller absolutely does not
2734 * want getblk() to bwrite() the buffer on a size mismatch.
2736 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2742 * All vnode-based buffers must be backed by a VM object.
2744 KKASSERT(bp->b_flags & B_VMIO);
2745 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2746 bp->b_flags &= ~B_AGE;
2749 * Make sure that B_INVAL buffers do not have a cached
2750 * block number translation.
2752 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2753 kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2754 " did not have cleared bio_offset cache\n",
2755 bp, vp, (long long)loffset);
2756 clearbiocache(&bp->b_bio2);
2760 * The buffer is locked. B_CACHE is cleared if the buffer is
2763 if (bp->b_flags & B_INVAL)
2764 bp->b_flags &= ~B_CACHE;
2768 * Any size inconsistancy with a dirty buffer or a buffer
2769 * with a softupdates dependancy must be resolved. Resizing
2770 * the buffer in such circumstances can lead to problems.
2772 * Dirty or dependant buffers are written synchronously.
2773 * Other types of buffers are simply released and
2774 * reconstituted as they may be backed by valid, dirty VM
2775 * pages (but not marked B_DELWRI).
2777 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2778 * and may be left over from a prior truncation (and thus
2779 * no longer represent the actual EOF point), so we
2780 * definitely do not want to B_NOCACHE the backing store.
2782 if (size != bp->b_bcount) {
2784 if (bp->b_flags & B_DELWRI) {
2785 bp->b_flags |= B_RELBUF;
2787 } else if (LIST_FIRST(&bp->b_dep)) {
2788 bp->b_flags |= B_RELBUF;
2791 bp->b_flags |= B_RELBUF;
2797 KKASSERT(size <= bp->b_kvasize);
2798 KASSERT(bp->b_loffset != NOOFFSET,
2799 ("getblk: no buffer offset"));
2802 * A buffer with B_DELWRI set and B_CACHE clear must
2803 * be committed before we can return the buffer in
2804 * order to prevent the caller from issuing a read
2805 * ( due to B_CACHE not being set ) and overwriting
2808 * Most callers, including NFS and FFS, need this to
2809 * operate properly either because they assume they
2810 * can issue a read if B_CACHE is not set, or because
2811 * ( for example ) an uncached B_DELWRI might loop due
2812 * to softupdates re-dirtying the buffer. In the latter
2813 * case, B_CACHE is set after the first write completes,
2814 * preventing further loops.
2816 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2817 * above while extending the buffer, we cannot allow the
2818 * buffer to remain with B_CACHE set after the write
2819 * completes or it will represent a corrupt state. To
2820 * deal with this we set B_NOCACHE to scrap the buffer
2823 * XXX Should this be B_RELBUF instead of B_NOCACHE?
2824 * I'm not even sure this state is still possible
2825 * now that getblk() writes out any dirty buffers
2828 * We might be able to do something fancy, like setting
2829 * B_CACHE in bwrite() except if B_DELWRI is already set,
2830 * so the below call doesn't set B_CACHE, but that gets real
2831 * confusing. This is much easier.
2834 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2836 kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
2837 "and CACHE clear, b_flags %08x\n",
2838 bp, (intmax_t)bp->b_loffset, bp->b_flags);
2839 bp->b_flags |= B_NOCACHE;
2846 * Buffer is not in-core, create new buffer. The buffer
2847 * returned by getnewbuf() is locked. Note that the returned
2848 * buffer is also considered valid (not marked B_INVAL).
2850 * Calculating the offset for the I/O requires figuring out
2851 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2852 * the mount's f_iosize otherwise. If the vnode does not
2853 * have an associated mount we assume that the passed size is
2856 * Note that vn_isdisk() cannot be used here since it may
2857 * return a failure for numerous reasons. Note that the
2858 * buffer size may be larger then the block size (the caller
2859 * will use block numbers with the proper multiple). Beware
2860 * of using any v_* fields which are part of unions. In
2861 * particular, in DragonFly the mount point overloading
2862 * mechanism uses the namecache only and the underlying
2863 * directory vnode is not a special case.
2867 if (vp->v_type == VBLK || vp->v_type == VCHR)
2869 else if (vp->v_mount)
2870 bsize = vp->v_mount->mnt_stat.f_iosize;
2874 maxsize = size + (loffset & PAGE_MASK);
2875 maxsize = imax(maxsize, bsize);
2877 bp = getnewbuf(blkflags, slptimeo, size, maxsize);
2879 if (slpflags || slptimeo)
2885 * Atomically insert the buffer into the hash, so that it can
2886 * be found by findblk().
2888 * If bgetvp() returns non-zero a collision occured, and the
2889 * bp will not be associated with the vnode.
2891 * Make sure the translation layer has been cleared.
2893 bp->b_loffset = loffset;
2894 bp->b_bio2.bio_offset = NOOFFSET;
2895 /* bp->b_bio2.bio_next = NULL; */
2897 if (bgetvp(vp, bp)) {
2898 bp->b_flags |= B_INVAL;
2904 * All vnode-based buffers must be backed by a VM object.
2906 KKASSERT(vp->v_object != NULL);
2907 bp->b_flags |= B_VMIO;
2908 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2920 * Reacquire a buffer that was previously released to the locked queue,
2921 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2922 * set B_LOCKED (which handles the acquisition race).
2924 * To this end, either B_LOCKED must be set or the dependancy list must be
2930 regetblk(struct buf *bp)
2932 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2933 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2940 * Get an empty, disassociated buffer of given size. The buffer is
2941 * initially set to B_INVAL.
2943 * critical section protection is not required for the allocbuf()
2944 * call because races are impossible here.
2954 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2956 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2961 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2969 * This code constitutes the buffer memory from either anonymous system
2970 * memory (in the case of non-VMIO operations) or from an associated
2971 * VM object (in the case of VMIO operations). This code is able to
2972 * resize a buffer up or down.
2974 * Note that this code is tricky, and has many complications to resolve
2975 * deadlock or inconsistant data situations. Tread lightly!!!
2976 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2977 * the caller. Calling this code willy nilly can result in the loss of data.
2979 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2980 * B_CACHE for the non-VMIO case.
2982 * This routine does not need to be called from a critical section but you
2983 * must own the buffer.
2988 allocbuf(struct buf *bp, int size)
2990 int newbsize, mbsize;
2993 if (BUF_REFCNT(bp) == 0)
2994 panic("allocbuf: buffer not busy");
2996 if (bp->b_kvasize < size)
2997 panic("allocbuf: buffer too small");
2999 if ((bp->b_flags & B_VMIO) == 0) {
3003 * Just get anonymous memory from the kernel. Don't
3004 * mess with B_CACHE.
3006 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3007 if (bp->b_flags & B_MALLOC)
3010 newbsize = round_page(size);
3012 if (newbsize < bp->b_bufsize) {
3014 * Malloced buffers are not shrunk
3016 if (bp->b_flags & B_MALLOC) {
3018 bp->b_bcount = size;
3020 kfree(bp->b_data, M_BIOBUF);
3021 if (bp->b_bufsize) {
3022 bufmallocspace -= bp->b_bufsize;
3026 bp->b_data = bp->b_kvabase;
3028 bp->b_flags &= ~B_MALLOC;
3034 (vm_offset_t) bp->b_data + newbsize,
3035 (vm_offset_t) bp->b_data + bp->b_bufsize);
3036 } else if (newbsize > bp->b_bufsize) {
3038 * We only use malloced memory on the first allocation.
3039 * and revert to page-allocated memory when the buffer
3042 if ((bufmallocspace < maxbufmallocspace) &&
3043 (bp->b_bufsize == 0) &&
3044 (mbsize <= PAGE_SIZE/2)) {
3046 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
3047 bp->b_bufsize = mbsize;
3048 bp->b_bcount = size;
3049 bp->b_flags |= B_MALLOC;
3050 bufmallocspace += mbsize;
3056 * If the buffer is growing on its other-than-first
3057 * allocation, then we revert to the page-allocation
3060 if (bp->b_flags & B_MALLOC) {
3061 origbuf = bp->b_data;
3062 origbufsize = bp->b_bufsize;
3063 bp->b_data = bp->b_kvabase;
3064 if (bp->b_bufsize) {
3065 bufmallocspace -= bp->b_bufsize;
3069 bp->b_flags &= ~B_MALLOC;
3070 newbsize = round_page(newbsize);
3074 (vm_offset_t) bp->b_data + bp->b_bufsize,
3075 (vm_offset_t) bp->b_data + newbsize);
3077 bcopy(origbuf, bp->b_data, origbufsize);
3078 kfree(origbuf, M_BIOBUF);
3085 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
3086 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3087 newbsize + PAGE_MASK) >> PAGE_SHIFT;
3088 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
3090 if (bp->b_flags & B_MALLOC)
3091 panic("allocbuf: VMIO buffer can't be malloced");
3093 * Set B_CACHE initially if buffer is 0 length or will become
3096 if (size == 0 || bp->b_bufsize == 0)
3097 bp->b_flags |= B_CACHE;
3099 if (newbsize < bp->b_bufsize) {
3101 * DEV_BSIZE aligned new buffer size is less then the
3102 * DEV_BSIZE aligned existing buffer size. Figure out
3103 * if we have to remove any pages.
3105 if (desiredpages < bp->b_xio.xio_npages) {
3106 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
3108 * the page is not freed here -- it
3109 * is the responsibility of
3110 * vnode_pager_setsize
3112 m = bp->b_xio.xio_pages[i];
3113 KASSERT(m != bogus_page,
3114 ("allocbuf: bogus page found"));
3115 while (vm_page_sleep_busy(m, TRUE, "biodep"))
3118 bp->b_xio.xio_pages[i] = NULL;
3119 vm_page_unwire(m, 0);
3121 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
3122 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
3123 bp->b_xio.xio_npages = desiredpages;
3125 } else if (size > bp->b_bcount) {
3127 * We are growing the buffer, possibly in a
3128 * byte-granular fashion.
3136 * Step 1, bring in the VM pages from the object,
3137 * allocating them if necessary. We must clear
3138 * B_CACHE if these pages are not valid for the
3139 * range covered by the buffer.
3141 * critical section protection is required to protect
3142 * against interrupts unbusying and freeing pages
3143 * between our vm_page_lookup() and our
3144 * busycheck/wiring call.
3150 while (bp->b_xio.xio_npages < desiredpages) {
3154 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
3155 if ((m = vm_page_lookup(obj, pi)) == NULL) {
3157 * note: must allocate system pages
3158 * since blocking here could intefere
3159 * with paging I/O, no matter which
3162 m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages);
3166 bp->b_flags &= ~B_CACHE;
3167 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3168 ++bp->b_xio.xio_npages;
3174 * We found a page. If we have to sleep on it,
3175 * retry because it might have gotten freed out
3178 * We can only test PG_BUSY here. Blocking on
3179 * m->busy might lead to a deadlock:
3181 * vm_fault->getpages->cluster_read->allocbuf
3185 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
3187 vm_page_flag_clear(m, PG_ZERO);
3189 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3190 ++bp->b_xio.xio_npages;
3191 if (bp->b_act_count < m->act_count)
3192 bp->b_act_count = m->act_count;
3197 * Step 2. We've loaded the pages into the buffer,
3198 * we have to figure out if we can still have B_CACHE
3199 * set. Note that B_CACHE is set according to the
3200 * byte-granular range ( bcount and size ), not the
3201 * aligned range ( newbsize ).
3203 * The VM test is against m->valid, which is DEV_BSIZE
3204 * aligned. Needless to say, the validity of the data
3205 * needs to also be DEV_BSIZE aligned. Note that this
3206 * fails with NFS if the server or some other client
3207 * extends the file's EOF. If our buffer is resized,
3208 * B_CACHE may remain set! XXX
3211 toff = bp->b_bcount;
3212 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3214 while ((bp->b_flags & B_CACHE) && toff < size) {
3217 if (tinc > (size - toff))
3220 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
3228 bp->b_xio.xio_pages[pi]
3235 * Step 3, fixup the KVM pmap. Remember that
3236 * bp->b_data is relative to bp->b_loffset, but
3237 * bp->b_loffset may be offset into the first page.
3240 bp->b_data = (caddr_t)
3241 trunc_page((vm_offset_t)bp->b_data);
3243 (vm_offset_t)bp->b_data,
3244 bp->b_xio.xio_pages,
3245 bp->b_xio.xio_npages
3247 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3248 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3252 /* adjust space use on already-dirty buffer */
3253 if (bp->b_flags & B_DELWRI) {
3254 dirtybufspace += newbsize - bp->b_bufsize;
3255 if (bp->b_flags & B_HEAVY)
3256 dirtybufspacehw += newbsize - bp->b_bufsize;
3258 if (newbsize < bp->b_bufsize)
3260 bp->b_bufsize = newbsize; /* actual buffer allocation */
3261 bp->b_bcount = size; /* requested buffer size */
3268 * Wait for buffer I/O completion, returning error status. B_EINTR
3269 * is converted into an EINTR error but not cleared (since a chain
3270 * of biowait() calls may occur).
3272 * On return bpdone() will have been called but the buffer will remain
3273 * locked and will not have been brelse()'d.
3275 * NOTE! If a timeout is specified and ETIMEDOUT occurs the I/O is
3276 * likely still in progress on return.
3278 * NOTE! This operation is on a BIO, not a BUF.
3280 * NOTE! BIO_DONE is cleared by vn_strategy()
3285 _biowait(struct bio *bio, const char *wmesg, int to)
3287 struct buf *bp = bio->bio_buf;
3292 KKASSERT(bio == &bp->b_bio1);
3294 flags = bio->bio_flags;
3295 if (flags & BIO_DONE)
3297 tsleep_interlock(bio, 0);
3298 nflags = flags | BIO_WANT;
3299 tsleep_interlock(bio, 0);
3300 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3302 error = tsleep(bio, PINTERLOCKED, wmesg, to);
3303 else if (bp->b_cmd == BUF_CMD_READ)
3304 error = tsleep(bio, PINTERLOCKED, "biord", to);
3306 error = tsleep(bio, PINTERLOCKED, "biowr", to);
3308 kprintf("tsleep error biowait %d\n", error);
3318 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3319 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
3320 if (bp->b_flags & B_EINTR)
3322 if (bp->b_flags & B_ERROR)
3323 return (bp->b_error ? bp->b_error : EIO);
3328 biowait(struct bio *bio, const char *wmesg)
3330 return(_biowait(bio, wmesg, 0));
3334 biowait_timeout(struct bio *bio, const char *wmesg, int to)
3336 return(_biowait(bio, wmesg, to));
3340 * This associates a tracking count with an I/O. vn_strategy() and
3341 * dev_dstrategy() do this automatically but there are a few cases
3342 * where a vnode or device layer is bypassed when a block translation
3343 * is cached. In such cases bio_start_transaction() may be called on
3344 * the bypassed layers so the system gets an I/O in progress indication
3345 * for those higher layers.
3348 bio_start_transaction(struct bio *bio, struct bio_track *track)
3350 bio->bio_track = track;
3351 bio_track_ref(track);
3355 * Initiate I/O on a vnode.
3358 vn_strategy(struct vnode *vp, struct bio *bio)
3360 struct bio_track *track;
3362 KKASSERT(bio->bio_buf->b_cmd != BUF_CMD_DONE);
3363 if (bio->bio_buf->b_cmd == BUF_CMD_READ)
3364 track = &vp->v_track_read;
3366 track = &vp->v_track_write;
3367 KKASSERT((bio->bio_flags & BIO_DONE) == 0);
3368 bio->bio_track = track;
3369 bio_track_ref(track);
3370 vop_strategy(*vp->v_ops, vp, bio);
3376 * Finish I/O on a buffer after all BIOs have been processed.
3377 * Called when the bio chain is exhausted or by biowait. If called
3378 * by biowait, elseit is typically 0.
3380 * bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3381 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3382 * assuming B_INVAL is clear.
3384 * For the VMIO case, we set B_CACHE if the op was a read and no
3385 * read error occured, or if the op was a write. B_CACHE is never
3386 * set if the buffer is invalid or otherwise uncacheable.
3388 * bpdone does not mess with B_INVAL, allowing the I/O routine or the
3389 * initiator to leave B_INVAL set to brelse the buffer out of existance
3390 * in the biodone routine.
3393 bpdone(struct buf *bp, int elseit)
3397 KASSERT(BUF_REFCNTNB(bp) > 0,
3398 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3399 KASSERT(bp->b_cmd != BUF_CMD_DONE,
3400 ("biodone: bp %p already done!", bp));
3403 * No more BIOs are left. All completion functions have been dealt
3404 * with, now we clean up the buffer.
3407 bp->b_cmd = BUF_CMD_DONE;
3410 * Only reads and writes are processed past this point.
3412 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3413 if (cmd == BUF_CMD_FREEBLKS)
3414 bp->b_flags |= B_NOCACHE;
3421 * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3422 * a lot worse. XXX - move this above the clearing of b_cmd
3424 if (LIST_FIRST(&bp->b_dep) != NULL)
3428 * A failed write must re-dirty the buffer unless B_INVAL
3429 * was set. Only applicable to normal buffers (with VPs).
3430 * vinum buffers may not have a vp.
3432 if (cmd == BUF_CMD_WRITE &&
3433 (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
3434 bp->b_flags &= ~B_NOCACHE;
3439 if (bp->b_flags & B_VMIO) {
3445 struct vnode *vp = bp->b_vp;
3449 #if defined(VFS_BIO_DEBUG)
3450 if (vp->v_auxrefs == 0)
3451 panic("biodone: zero vnode hold count");
3452 if ((vp->v_flag & VOBJBUF) == 0)
3453 panic("biodone: vnode is not setup for merged cache");
3456 foff = bp->b_loffset;
3457 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3458 KASSERT(obj != NULL, ("biodone: missing VM object"));
3460 #if defined(VFS_BIO_DEBUG)
3461 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3462 kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3463 obj->paging_in_progress, bp->b_xio.xio_npages);
3468 * Set B_CACHE if the op was a normal read and no error
3469 * occured. B_CACHE is set for writes in the b*write()
3472 iosize = bp->b_bcount - bp->b_resid;
3473 if (cmd == BUF_CMD_READ &&
3474 (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3475 bp->b_flags |= B_CACHE;
3480 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3484 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3489 * cleanup bogus pages, restoring the originals. Since
3490 * the originals should still be wired, we don't have
3491 * to worry about interrupt/freeing races destroying
3492 * the VM object association.
3494 m = bp->b_xio.xio_pages[i];
3495 if (m == bogus_page) {
3497 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3499 panic("biodone: page disappeared");
3500 bp->b_xio.xio_pages[i] = m;
3501 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3502 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3504 #if defined(VFS_BIO_DEBUG)
3505 if (OFF_TO_IDX(foff) != m->pindex) {
3506 kprintf("biodone: foff(%lu)/m->pindex(%ld) "
3508 (unsigned long)foff, (long)m->pindex);
3513 * In the write case, the valid and clean bits are
3514 * already changed correctly (see bdwrite()), so we
3515 * only need to do this here in the read case.
3517 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3518 vfs_clean_one_page(bp, i, m);
3520 vm_page_flag_clear(m, PG_ZERO);
3523 * when debugging new filesystems or buffer I/O
3524 * methods, this is the most common error that pops
3525 * up. if you see this, you have not set the page
3526 * busy flag correctly!!!
3529 kprintf("biodone: page busy < 0, "
3530 "pindex: %d, foff: 0x(%x,%x), "
3531 "resid: %d, index: %d\n",
3532 (int) m->pindex, (int)(foff >> 32),
3533 (int) foff & 0xffffffff, resid, i);
3534 if (!vn_isdisk(vp, NULL))
3535 kprintf(" iosize: %ld, loffset: %lld, "
3536 "flags: 0x%08x, npages: %d\n",
3537 bp->b_vp->v_mount->mnt_stat.f_iosize,
3538 (long long)bp->b_loffset,
3539 bp->b_flags, bp->b_xio.xio_npages);
3541 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3542 (long long)bp->b_loffset,
3543 bp->b_flags, bp->b_xio.xio_npages);
3544 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3545 m->valid, m->dirty, m->wire_count);
3546 panic("biodone: page busy < 0");
3548 vm_page_io_finish(m);
3549 vm_object_pip_subtract(obj, 1);
3550 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3554 vm_object_pip_wakeupn(obj, 0);
3560 * Finish up by releasing the buffer. There are no more synchronous
3561 * or asynchronous completions, those were handled by bio_done
3565 if (bp->b_flags & (B_NOCACHE|B_INVAL|B_ERROR|B_RELBUF))
3576 biodone(struct bio *bio)
3578 struct buf *bp = bio->bio_buf;
3580 runningbufwakeup(bp);
3583 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
3586 biodone_t *done_func;
3587 struct bio_track *track;
3590 * BIO tracking. Most but not all BIOs are tracked.
3592 if ((track = bio->bio_track) != NULL) {
3593 bio_track_rel(track);
3594 bio->bio_track = NULL;
3598 * A bio_done function terminates the loop. The function
3599 * will be responsible for any further chaining and/or
3600 * buffer management.
3602 * WARNING! The done function can deallocate the buffer!
3604 if ((done_func = bio->bio_done) != NULL) {
3605 bio->bio_done = NULL;
3609 bio = bio->bio_prev;
3613 * If we've run out of bio's do normal [a]synchronous completion.
3619 * Synchronous biodone - this terminates a synchronous BIO.
3621 * bpdone() is called with elseit=FALSE, leaving the buffer completed
3622 * but still locked. The caller must brelse() the buffer after waiting
3626 biodone_sync(struct bio *bio)
3628 struct buf *bp = bio->bio_buf;
3632 KKASSERT(bio == &bp->b_bio1);
3636 flags = bio->bio_flags;
3637 nflags = (flags | BIO_DONE) & ~BIO_WANT;
3639 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3640 if (flags & BIO_WANT)
3650 * This routine is called in lieu of iodone in the case of
3651 * incomplete I/O. This keeps the busy status for pages
3655 vfs_unbusy_pages(struct buf *bp)
3659 runningbufwakeup(bp);
3660 if (bp->b_flags & B_VMIO) {
3661 struct vnode *vp = bp->b_vp;
3666 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3667 vm_page_t m = bp->b_xio.xio_pages[i];
3670 * When restoring bogus changes the original pages
3671 * should still be wired, so we are in no danger of
3672 * losing the object association and do not need
3673 * critical section protection particularly.
3675 if (m == bogus_page) {
3676 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3678 panic("vfs_unbusy_pages: page missing");
3680 bp->b_xio.xio_pages[i] = m;
3681 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3682 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3684 vm_object_pip_subtract(obj, 1);
3685 vm_page_flag_clear(m, PG_ZERO);
3686 vm_page_io_finish(m);
3688 vm_object_pip_wakeupn(obj, 0);
3695 * This routine is called before a device strategy routine.
3696 * It is used to tell the VM system that paging I/O is in
3697 * progress, and treat the pages associated with the buffer
3698 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3699 * flag is handled to make sure that the object doesn't become
3702 * Since I/O has not been initiated yet, certain buffer flags
3703 * such as B_ERROR or B_INVAL may be in an inconsistant state
3704 * and should be ignored.
3707 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3710 struct lwp *lp = curthread->td_lwp;
3713 * The buffer's I/O command must already be set. If reading,
3714 * B_CACHE must be 0 (double check against callers only doing
3715 * I/O when B_CACHE is 0).
3717 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3718 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3720 if (bp->b_flags & B_VMIO) {
3724 KASSERT(bp->b_loffset != NOOFFSET,
3725 ("vfs_busy_pages: no buffer offset"));
3728 * Loop until none of the pages are busy.
3731 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3732 vm_page_t m = bp->b_xio.xio_pages[i];
3734 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3739 * Setup for I/O, soft-busy the page right now because
3740 * the next loop may block.
3742 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3743 vm_page_t m = bp->b_xio.xio_pages[i];
3745 vm_page_flag_clear(m, PG_ZERO);
3746 if ((bp->b_flags & B_CLUSTER) == 0) {
3747 vm_object_pip_add(obj, 1);
3748 vm_page_io_start(m);
3753 * Adjust protections for I/O and do bogus-page mapping.
3754 * Assume that vm_page_protect() can block (it can block
3755 * if VM_PROT_NONE, don't take any chances regardless).
3757 * In particularly note that for writes we must incorporate
3758 * page dirtyness from the VM system into the buffer's
3761 * For reads we theoretically must incorporate page dirtyness
3762 * from the VM system to determine if the page needs bogus
3763 * replacement, but we shortcut the test by simply checking
3764 * that all m->valid bits are set, indicating that the page
3765 * is fully valid and does not need to be re-read. For any
3766 * VM system dirtyness the page will also be fully valid
3767 * since it was mapped at one point.
3770 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3771 vm_page_t m = bp->b_xio.xio_pages[i];
3773 vm_page_flag_clear(m, PG_ZERO); /* XXX */
3774 if (bp->b_cmd == BUF_CMD_WRITE) {
3776 * When readying a vnode-backed buffer for
3777 * a write we must zero-fill any invalid
3778 * portions of the backing VM pages, mark
3779 * it valid and clear related dirty bits.
3781 * vfs_clean_one_page() incorporates any
3782 * VM dirtyness and updates the b_dirtyoff
3783 * range (after we've made the page RO).
3785 * It is also expected that the pmap modified
3786 * bit has already been cleared by the
3787 * vm_page_protect(). We may not be able
3788 * to clear all dirty bits for a page if it
3789 * was also memory mapped (NFS).
3791 vm_page_protect(m, VM_PROT_READ);
3792 vfs_clean_one_page(bp, i, m);
3793 } else if (m->valid == VM_PAGE_BITS_ALL) {
3795 * When readying a vnode-backed buffer for
3796 * read we must replace any dirty pages with
3797 * a bogus page so dirty data is not destroyed
3798 * when filling gaps.
3800 * To avoid testing whether the page is
3801 * dirty we instead test that the page was
3802 * at some point mapped (m->valid fully
3803 * valid) with the understanding that
3804 * this also covers the dirty case.
3806 bp->b_xio.xio_pages[i] = bogus_page;
3808 } else if (m->valid & m->dirty) {
3810 * This case should not occur as partial
3811 * dirtyment can only happen if the buffer
3812 * is B_CACHE, and this code is not entered
3813 * if the buffer is B_CACHE.
3815 kprintf("Warning: vfs_busy_pages - page not "
3816 "fully valid! loff=%jx bpf=%08x "
3817 "idx=%d val=%02x dir=%02x\n",
3818 (intmax_t)bp->b_loffset, bp->b_flags,
3819 i, m->valid, m->dirty);
3820 vm_page_protect(m, VM_PROT_NONE);
3823 * The page is not valid and can be made
3826 vm_page_protect(m, VM_PROT_NONE);
3830 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3831 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3836 * This is the easiest place to put the process accounting for the I/O
3840 if (bp->b_cmd == BUF_CMD_READ)
3841 lp->lwp_ru.ru_inblock++;
3843 lp->lwp_ru.ru_oublock++;
3850 * Tell the VM system that the pages associated with this buffer
3851 * are clean. This is used for delayed writes where the data is
3852 * going to go to disk eventually without additional VM intevention.
3854 * Note that while we only really need to clean through to b_bcount, we
3855 * just go ahead and clean through to b_bufsize.
3858 vfs_clean_pages(struct buf *bp)
3863 if ((bp->b_flags & B_VMIO) == 0)
3866 KASSERT(bp->b_loffset != NOOFFSET,
3867 ("vfs_clean_pages: no buffer offset"));
3869 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3870 m = bp->b_xio.xio_pages[i];
3871 vfs_clean_one_page(bp, i, m);
3876 * vfs_clean_one_page:
3878 * Set the valid bits and clear the dirty bits in a page within a
3879 * buffer. The range is restricted to the buffer's size and the
3880 * buffer's logical offset might index into the first page.
3882 * The caller has busied or soft-busied the page and it is not mapped,
3883 * test and incorporate the dirty bits into b_dirtyoff/end before
3884 * clearing them. Note that we need to clear the pmap modified bits
3885 * after determining the the page was dirty, vm_page_set_validclean()
3886 * does not do it for us.
3888 * This routine is typically called after a read completes (dirty should
3889 * be zero in that case as we are not called on bogus-replace pages),
3890 * or before a write is initiated.
3893 vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m)
3901 * Calculate offset range within the page but relative to buffer's
3902 * loffset. loffset might be offset into the first page.
3904 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
3905 bcount = bp->b_bcount + xoff; /* offset adjusted */
3911 soff = (pageno << PAGE_SHIFT);
3912 eoff = soff + PAGE_SIZE;
3920 * Test dirty bits and adjust b_dirtyoff/end.
3922 * If dirty pages are incorporated into the bp any prior
3923 * B_NEEDCOMMIT state (NFS) must be cleared because the
3924 * caller has not taken into account the new dirty data.
3926 * If the page was memory mapped the dirty bits might go beyond the
3927 * end of the buffer, but we can't really make the assumption that
3928 * a file EOF straddles the buffer (even though this is the case for
3929 * NFS if B_NEEDCOMMIT is also set). So for the purposes of clearing
3930 * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
3931 * This also saves some console spam.
3933 * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK,
3934 * NFS can handle huge commits but not huge writes.
3936 vm_page_test_dirty(m);
3938 if ((bp->b_flags & B_NEEDCOMMIT) &&
3939 (m->dirty & vm_page_bits(soff & PAGE_MASK, eoff - soff))) {
3941 kprintf("Warning: vfs_clean_one_page: bp %p "
3942 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT"
3943 " cmd %d vd %02x/%02x x/s/e %d %d %d "
3945 bp, (intmax_t)bp->b_loffset, bp->b_bcount,
3946 bp->b_flags, bp->b_cmd,
3947 m->valid, m->dirty, xoff, soff, eoff,
3948 bp->b_dirtyoff, bp->b_dirtyend);
3949 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
3954 * Only clear the pmap modified bits if ALL the dirty bits
3955 * are set, otherwise the system might mis-clear portions
3958 if (m->dirty == VM_PAGE_BITS_ALL &&
3959 (bp->b_flags & B_NEEDCOMMIT) == 0) {
3960 pmap_clear_modify(m);
3962 if (bp->b_dirtyoff > soff - xoff)
3963 bp->b_dirtyoff = soff - xoff;
3964 if (bp->b_dirtyend < eoff - xoff)
3965 bp->b_dirtyend = eoff - xoff;
3969 * Set related valid bits, clear related dirty bits.
3970 * Does not mess with the pmap modified bit.
3972 * WARNING! We cannot just clear all of m->dirty here as the
3973 * buffer cache buffers may use a DEV_BSIZE'd aligned
3974 * block size, or have an odd size (e.g. NFS at file EOF).
3975 * The putpages code can clear m->dirty to 0.
3977 * If a VOP_WRITE generates a buffer cache buffer which
3978 * covers the same space as mapped writable pages the
3979 * buffer flush might not be able to clear all the dirty
3980 * bits and still require a putpages from the VM system
3983 vm_page_set_validclean(m, soff & PAGE_MASK, eoff - soff);
3989 * Clear a buffer. This routine essentially fakes an I/O, so we need
3990 * to clear B_ERROR and B_INVAL.
3992 * Note that while we only theoretically need to clear through b_bcount,
3993 * we go ahead and clear through b_bufsize.
3997 vfs_bio_clrbuf(struct buf *bp)
4001 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
4002 bp->b_flags &= ~(B_INVAL | B_EINTR | B_ERROR);
4003 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4004 (bp->b_loffset & PAGE_MASK) == 0) {
4005 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4006 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
4010 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
4011 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
4012 bzero(bp->b_data, bp->b_bufsize);
4013 bp->b_xio.xio_pages[0]->valid |= mask;
4019 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
4020 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
4021 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
4022 ea = (caddr_t)(vm_offset_t)ulmin(
4023 (u_long)(vm_offset_t)ea,
4024 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
4025 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4026 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
4028 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
4029 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
4033 for (; sa < ea; sa += DEV_BSIZE, j++) {
4034 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
4035 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
4036 bzero(sa, DEV_BSIZE);
4039 bp->b_xio.xio_pages[i]->valid |= mask;
4040 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
4049 * vm_hold_load_pages:
4051 * Load pages into the buffer's address space. The pages are
4052 * allocated from the kernel object in order to reduce interference
4053 * with the any VM paging I/O activity. The range of loaded
4054 * pages will be wired.
4056 * If a page cannot be allocated, the 'pagedaemon' is woken up to
4057 * retrieve the full range (to - from) of pages.
4061 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4067 to = round_page(to);
4068 from = round_page(from);
4069 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4074 * Note: must allocate system pages since blocking here
4075 * could intefere with paging I/O, no matter which
4078 p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT,
4079 (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
4082 p->valid = VM_PAGE_BITS_ALL;
4083 vm_page_flag_clear(p, PG_ZERO);
4084 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
4085 bp->b_xio.xio_pages[index] = p;
4092 bp->b_xio.xio_npages = index;
4096 * Allocate pages for a buffer cache buffer.
4098 * Under extremely severe memory conditions even allocating out of the
4099 * system reserve can fail. If this occurs we must allocate out of the
4100 * interrupt reserve to avoid a deadlock with the pageout daemon.
4102 * The pageout daemon can run (putpages -> VOP_WRITE -> getblk -> allocbuf).
4103 * If the buffer cache's vm_page_alloc() fails a vm_wait() can deadlock
4104 * against the pageout daemon if pages are not freed from other sources.
4108 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit)
4113 * Try a normal allocation, allow use of system reserve.
4115 p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
4120 * The normal allocation failed and we clearly have a page
4121 * deficit. Try to reclaim some clean VM pages directly
4122 * from the buffer cache.
4124 vm_pageout_deficit += deficit;
4128 * We may have blocked, the caller will know what to do if the
4131 if (vm_page_lookup(obj, pg))
4135 * Allocate and allow use of the interrupt reserve.
4137 * If after all that we still can't allocate a VM page we are
4138 * in real trouble, but we slog on anyway hoping that the system
4141 p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
4142 VM_ALLOC_INTERRUPT);
4144 if (vm_page_count_severe()) {
4145 kprintf("bio_page_alloc: WARNING emergency page "
4150 kprintf("bio_page_alloc: WARNING emergency page "
4151 "allocation failed\n");
4158 * vm_hold_free_pages:
4160 * Return pages associated with the buffer back to the VM system.
4162 * The range of pages underlying the buffer's address space will
4163 * be unmapped and un-wired.
4166 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4170 int index, newnpages;
4172 from = round_page(from);
4173 to = round_page(to);
4174 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4176 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4177 p = bp->b_xio.xio_pages[index];
4178 if (p && (index < bp->b_xio.xio_npages)) {
4180 kprintf("vm_hold_free_pages: doffset: %lld, "
4182 (long long)bp->b_bio2.bio_offset,
4183 (long long)bp->b_loffset);
4185 bp->b_xio.xio_pages[index] = NULL;
4188 vm_page_unwire(p, 0);
4192 bp->b_xio.xio_npages = newnpages;
4198 * Map a user buffer into KVM via a pbuf. On return the buffer's
4199 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
4203 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
4214 * bp had better have a command and it better be a pbuf.
4216 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4217 KKASSERT(bp->b_flags & B_PAGING);
4223 * Map the user data into KVM. Mappings have to be page-aligned.
4225 addr = (caddr_t)trunc_page((vm_offset_t)udata);
4228 vmprot = VM_PROT_READ;
4229 if (bp->b_cmd == BUF_CMD_READ)
4230 vmprot |= VM_PROT_WRITE;
4232 while (addr < udata + bytes) {
4234 * Do the vm_fault if needed; do the copy-on-write thing
4235 * when reading stuff off device into memory.
4237 * vm_fault_page*() returns a held VM page.
4239 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
4240 va = trunc_page(va);
4242 m = vm_fault_page_quick(va, vmprot, &error);
4244 for (i = 0; i < pidx; ++i) {
4245 vm_page_unhold(bp->b_xio.xio_pages[i]);
4246 bp->b_xio.xio_pages[i] = NULL;
4250 bp->b_xio.xio_pages[pidx] = m;
4256 * Map the page array and set the buffer fields to point to
4257 * the mapped data buffer.
4259 if (pidx > btoc(MAXPHYS))
4260 panic("vmapbuf: mapped more than MAXPHYS");
4261 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
4263 bp->b_xio.xio_npages = pidx;
4264 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
4265 bp->b_bcount = bytes;
4266 bp->b_bufsize = bytes;
4273 * Free the io map PTEs associated with this IO operation.
4274 * We also invalidate the TLB entries and restore the original b_addr.
4277 vunmapbuf(struct buf *bp)
4282 KKASSERT(bp->b_flags & B_PAGING);
4284 npages = bp->b_xio.xio_npages;
4285 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4286 for (pidx = 0; pidx < npages; ++pidx) {
4287 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
4288 bp->b_xio.xio_pages[pidx] = NULL;
4290 bp->b_xio.xio_npages = 0;
4291 bp->b_data = bp->b_kvabase;
4295 * Scan all buffers in the system and issue the callback.
4298 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
4304 for (n = 0; n < nbuf; ++n) {
4305 if ((error = callback(&buf[n], info)) < 0) {
4315 * print out statistics from the current status of the buffer pool
4316 * this can be toggeled by the system control option debug.syncprt
4325 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
4326 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
4328 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
4330 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4333 TAILQ_FOREACH(bp, dp, b_freelist) {
4334 counts[bp->b_bufsize/PAGE_SIZE]++;
4338 kprintf("%s: total-%d", bname[i], count);
4339 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4341 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
4349 DB_SHOW_COMMAND(buffer, db_show_buffer)
4352 struct buf *bp = (struct buf *)addr;
4355 db_printf("usage: show buffer <addr>\n");
4359 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4360 db_printf("b_cmd = %d\n", bp->b_cmd);
4361 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
4362 "b_resid = %d\n, b_data = %p, "
4363 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
4364 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4366 (long long)bp->b_bio2.bio_offset,
4367 (long long)(bp->b_bio2.bio_next ?
4368 bp->b_bio2.bio_next->bio_offset : (off_t)-1));
4369 if (bp->b_xio.xio_npages) {
4371 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
4372 bp->b_xio.xio_npages);
4373 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4375 m = bp->b_xio.xio_pages[i];
4376 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4377 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4378 if ((i + 1) < bp->b_xio.xio_npages)