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.109 2008/07/01 02:02:54 dillon Exp $
19 * this file contains a new buffer I/O scheme implementing a coherent
20 * VM object and buffer cache scheme. Pains have been taken to make
21 * sure that the performance degradation associated with schemes such
22 * as this is not realized.
24 * Author: John S. Dyson
25 * Significant help during the development and debugging phases
26 * had been provided by David Greenman, also of the FreeBSD core team.
28 * see man buf(9) for more info.
31 #include <sys/param.h>
32 #include <sys/systm.h>
35 #include <sys/eventhandler.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
58 #include <sys/thread2.h>
59 #include <sys/spinlock2.h>
60 #include <vm/vm_page2.h>
71 BQUEUE_NONE, /* not on any queue */
72 BQUEUE_LOCKED, /* locked buffers */
73 BQUEUE_CLEAN, /* non-B_DELWRI buffers */
74 BQUEUE_DIRTY, /* B_DELWRI buffers */
75 BQUEUE_DIRTY_HW, /* B_DELWRI buffers - heavy weight */
76 BQUEUE_EMPTYKVA, /* empty buffer headers with KVA assignment */
77 BQUEUE_EMPTY, /* empty buffer headers */
79 BUFFER_QUEUES /* number of buffer queues */
82 typedef enum bufq_type bufq_type_t;
84 #define BD_WAKE_SIZE 128
85 #define BD_WAKE_MASK (BD_WAKE_SIZE - 1)
87 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
89 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
91 struct buf *buf; /* buffer header pool */
93 static void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
95 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
97 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
98 int pageno, vm_page_t m);
99 static void vfs_clean_pages(struct buf *bp);
100 static void vfs_setdirty(struct buf *bp);
101 static void vfs_vmio_release(struct buf *bp);
102 static int flushbufqueues(bufq_type_t q);
103 static vm_page_t bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit);
105 static void bd_signal(int totalspace);
106 static void buf_daemon(void);
107 static void buf_daemon_hw(void);
110 * bogus page -- for I/O to/from partially complete buffers
111 * this is a temporary solution to the problem, but it is not
112 * really that bad. it would be better to split the buffer
113 * for input in the case of buffers partially already in memory,
114 * but the code is intricate enough already.
116 vm_page_t bogus_page;
119 * These are all static, but make the ones we export globals so we do
120 * not need to use compiler magic.
122 int bufspace, maxbufspace,
123 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
124 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
125 static int lorunningspace, hirunningspace, runningbufreq;
126 int dirtybufspace, dirtybufspacehw, lodirtybufspace, hidirtybufspace;
127 int runningbufspace, runningbufcount;
128 static int getnewbufcalls;
129 static int getnewbufrestarts;
130 static int recoverbufcalls;
131 static int needsbuffer; /* locked by needsbuffer_spin */
132 static int bd_request; /* locked by needsbuffer_spin */
133 static int bd_request_hw; /* locked by needsbuffer_spin */
134 static u_int bd_wake_ary[BD_WAKE_SIZE];
135 static u_int bd_wake_index;
136 static struct spinlock needsbuffer_spin;
138 static struct thread *bufdaemon_td;
139 static struct thread *bufdaemonhw_td;
143 * Sysctls for operational control of the buffer cache.
145 SYSCTL_INT(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
146 "Number of dirty buffers to flush before bufdaemon becomes inactive");
147 SYSCTL_INT(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
148 "High watermark used to trigger explicit flushing of dirty buffers");
149 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
150 "Minimum amount of buffer space required for active I/O");
151 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
152 "Maximum amount of buffer space to usable for active I/O");
154 * Sysctls determining current state of the buffer cache.
156 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
157 "Total number of buffers in buffer cache");
158 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
159 "Pending number of dirty buffers (all)");
160 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
161 "Pending number of dirty buffers (heavy weight)");
162 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
163 "I/O bytes currently in progress due to asynchronous writes");
164 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
165 "I/O buffers currently in progress due to asynchronous writes");
166 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
167 "Hard limit on maximum amount of memory usable for buffer space");
168 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
169 "Soft limit on maximum amount of memory usable for buffer space");
170 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
171 "Minimum amount of memory to reserve for system buffer space");
172 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
173 "Amount of memory available for buffers");
174 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
175 0, "Maximum amount of memory reserved for buffers using malloc");
176 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
177 "Amount of memory left for buffers using malloc-scheme");
178 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
179 "New buffer header acquisition requests");
180 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
181 0, "New buffer header acquisition restarts");
182 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
183 "Recover VM space in an emergency");
184 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
185 "Buffer acquisition restarts due to fragmented buffer map");
186 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
187 "Amount of time KVA space was deallocated in an arbitrary buffer");
188 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
189 "Amount of time buffer re-use operations were successful");
190 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
191 "sizeof(struct buf)");
193 char *buf_wmesg = BUF_WMESG;
195 extern int vm_swap_size;
197 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
198 #define VFS_BIO_NEED_UNUSED02 0x02
199 #define VFS_BIO_NEED_UNUSED04 0x04
200 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
205 * Called when buffer space is potentially available for recovery.
206 * getnewbuf() will block on this flag when it is unable to free
207 * sufficient buffer space. Buffer space becomes recoverable when
208 * bp's get placed back in the queues.
215 * If someone is waiting for BUF space, wake them up. Even
216 * though we haven't freed the kva space yet, the waiting
217 * process will be able to now.
219 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
220 spin_lock_wr(&needsbuffer_spin);
221 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
222 spin_unlock_wr(&needsbuffer_spin);
223 wakeup(&needsbuffer);
230 * Accounting for I/O in progress.
234 runningbufwakeup(struct buf *bp)
238 if ((totalspace = bp->b_runningbufspace) != 0) {
239 runningbufspace -= totalspace;
241 bp->b_runningbufspace = 0;
242 if (runningbufreq && runningbufspace <= lorunningspace) {
244 wakeup(&runningbufreq);
246 bd_signal(totalspace);
253 * Called when a buffer has been added to one of the free queues to
254 * account for the buffer and to wakeup anyone waiting for free buffers.
255 * This typically occurs when large amounts of metadata are being handled
256 * by the buffer cache ( else buffer space runs out first, usually ).
263 spin_lock_wr(&needsbuffer_spin);
264 needsbuffer &= ~VFS_BIO_NEED_ANY;
265 spin_unlock_wr(&needsbuffer_spin);
266 wakeup(&needsbuffer);
271 * waitrunningbufspace()
273 * Wait for the amount of running I/O to drop to a reasonable level.
275 * The caller may be using this function to block in a tight loop, we
276 * must block of runningbufspace is greater then the passed limit.
277 * And even with that it may not be enough, due to the presence of
278 * B_LOCKED dirty buffers, so also wait for at least one running buffer
282 waitrunningbufspace(int limit)
286 if (lorunningspace < limit)
287 lorun = lorunningspace;
292 if (runningbufspace > lorun) {
293 while (runningbufspace > lorun) {
295 tsleep(&runningbufreq, 0, "wdrain", 0);
297 } else if (runningbufspace) {
299 tsleep(&runningbufreq, 0, "wdrain2", 1);
305 * vfs_buf_test_cache:
307 * Called when a buffer is extended. This function clears the B_CACHE
308 * bit if the newly extended portion of the buffer does not contain
313 vfs_buf_test_cache(struct buf *bp,
314 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
317 if (bp->b_flags & B_CACHE) {
318 int base = (foff + off) & PAGE_MASK;
319 if (vm_page_is_valid(m, base, size) == 0)
320 bp->b_flags &= ~B_CACHE;
327 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
334 if (dirtybufspace > lodirtybufspace)
337 if (bd_request == 0 &&
338 dirtybufspace - dirtybufspacehw > lodirtybufspace / 2) {
339 spin_lock_wr(&needsbuffer_spin);
341 spin_unlock_wr(&needsbuffer_spin);
344 if (bd_request_hw == 0 &&
345 dirtybufspacehw > lodirtybufspace / 2) {
346 spin_lock_wr(&needsbuffer_spin);
348 spin_unlock_wr(&needsbuffer_spin);
349 wakeup(&bd_request_hw);
356 * Get the buf_daemon heated up when the number of running and dirty
357 * buffers exceeds the mid-point.
366 mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
368 totalspace = runningbufspace + dirtybufspace;
369 if (totalspace >= mid1) {
371 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
372 if (totalspace >= mid2)
373 return(totalspace - mid2);
381 * Wait for the buffer cache to flush (totalspace) bytes worth of
382 * buffers, then return.
384 * Regardless this function blocks while the number of dirty buffers
385 * exceeds hidirtybufspace.
388 bd_wait(int totalspace)
393 if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
396 while (totalspace > 0) {
399 if (totalspace > runningbufspace + dirtybufspace)
400 totalspace = runningbufspace + dirtybufspace;
401 count = totalspace / BKVASIZE;
402 if (count >= BD_WAKE_SIZE)
403 count = BD_WAKE_SIZE - 1;
404 i = (bd_wake_index + count) & BD_WAKE_MASK;
406 tsleep(&bd_wake_ary[i], 0, "flstik", hz);
409 totalspace = runningbufspace + dirtybufspace - hidirtybufspace;
416 * This function is called whenever runningbufspace or dirtybufspace
417 * is reduced. Track threads waiting for run+dirty buffer I/O
421 bd_signal(int totalspace)
425 while (totalspace > 0) {
426 i = atomic_fetchadd_int(&bd_wake_index, 1);
428 if (bd_wake_ary[i]) {
430 wakeup(&bd_wake_ary[i]);
432 totalspace -= BKVASIZE;
439 * Load time initialisation of the buffer cache, called from machine
440 * dependant initialization code.
446 vm_offset_t bogus_offset;
449 spin_init(&needsbuffer_spin);
451 /* next, make a null set of free lists */
452 for (i = 0; i < BUFFER_QUEUES; i++)
453 TAILQ_INIT(&bufqueues[i]);
455 /* finally, initialize each buffer header and stick on empty q */
456 for (i = 0; i < nbuf; i++) {
458 bzero(bp, sizeof *bp);
459 bp->b_flags = B_INVAL; /* we're just an empty header */
460 bp->b_cmd = BUF_CMD_DONE;
461 bp->b_qindex = BQUEUE_EMPTY;
463 xio_init(&bp->b_xio);
466 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
470 * maxbufspace is the absolute maximum amount of buffer space we are
471 * allowed to reserve in KVM and in real terms. The absolute maximum
472 * is nominally used by buf_daemon. hibufspace is the nominal maximum
473 * used by most other processes. The differential is required to
474 * ensure that buf_daemon is able to run when other processes might
475 * be blocked waiting for buffer space.
477 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
478 * this may result in KVM fragmentation which is not handled optimally
481 maxbufspace = nbuf * BKVASIZE;
482 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
483 lobufspace = hibufspace - MAXBSIZE;
485 lorunningspace = 512 * 1024;
486 hirunningspace = 1024 * 1024;
489 * Limit the amount of malloc memory since it is wired permanently
490 * into the kernel space. Even though this is accounted for in
491 * the buffer allocation, we don't want the malloced region to grow
492 * uncontrolled. The malloc scheme improves memory utilization
493 * significantly on average (small) directories.
495 maxbufmallocspace = hibufspace / 20;
498 * Reduce the chance of a deadlock occuring by limiting the number
499 * of delayed-write dirty buffers we allow to stack up.
501 hidirtybufspace = hibufspace / 2;
505 lodirtybufspace = hidirtybufspace / 2;
508 * Maximum number of async ops initiated per buf_daemon loop. This is
509 * somewhat of a hack at the moment, we really need to limit ourselves
510 * based on the number of bytes of I/O in-transit that were initiated
514 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
515 bogus_page = vm_page_alloc(&kernel_object,
516 (bogus_offset >> PAGE_SHIFT),
518 vmstats.v_wire_count++;
523 * Initialize the embedded bio structures
526 initbufbio(struct buf *bp)
528 bp->b_bio1.bio_buf = bp;
529 bp->b_bio1.bio_prev = NULL;
530 bp->b_bio1.bio_offset = NOOFFSET;
531 bp->b_bio1.bio_next = &bp->b_bio2;
532 bp->b_bio1.bio_done = NULL;
534 bp->b_bio2.bio_buf = bp;
535 bp->b_bio2.bio_prev = &bp->b_bio1;
536 bp->b_bio2.bio_offset = NOOFFSET;
537 bp->b_bio2.bio_next = NULL;
538 bp->b_bio2.bio_done = NULL;
542 * Reinitialize the embedded bio structures as well as any additional
543 * translation cache layers.
546 reinitbufbio(struct buf *bp)
550 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
551 bio->bio_done = NULL;
552 bio->bio_offset = NOOFFSET;
557 * Push another BIO layer onto an existing BIO and return it. The new
558 * BIO layer may already exist, holding cached translation data.
561 push_bio(struct bio *bio)
565 if ((nbio = bio->bio_next) == NULL) {
566 int index = bio - &bio->bio_buf->b_bio_array[0];
567 if (index >= NBUF_BIO - 1) {
568 panic("push_bio: too many layers bp %p\n",
571 nbio = &bio->bio_buf->b_bio_array[index + 1];
572 bio->bio_next = nbio;
573 nbio->bio_prev = bio;
574 nbio->bio_buf = bio->bio_buf;
575 nbio->bio_offset = NOOFFSET;
576 nbio->bio_done = NULL;
577 nbio->bio_next = NULL;
579 KKASSERT(nbio->bio_done == NULL);
584 pop_bio(struct bio *bio)
590 clearbiocache(struct bio *bio)
593 bio->bio_offset = NOOFFSET;
601 * Free the KVA allocation for buffer 'bp'.
603 * Must be called from a critical section as this is the only locking for
606 * Since this call frees up buffer space, we call bufspacewakeup().
609 bfreekva(struct buf *bp)
615 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
616 vm_map_lock(&buffer_map);
617 bufspace -= bp->b_kvasize;
618 vm_map_delete(&buffer_map,
619 (vm_offset_t) bp->b_kvabase,
620 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
623 vm_map_unlock(&buffer_map);
624 vm_map_entry_release(count);
633 * Remove the buffer from the appropriate free list.
636 bremfree(struct buf *bp)
641 old_qindex = bp->b_qindex;
643 if (bp->b_qindex != BQUEUE_NONE) {
644 KASSERT(BUF_REFCNTNB(bp) == 1,
645 ("bremfree: bp %p not locked",bp));
646 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
647 bp->b_qindex = BQUEUE_NONE;
649 if (BUF_REFCNTNB(bp) <= 1)
650 panic("bremfree: removing a buffer not on a queue");
660 * Get a buffer with the specified data. Look in the cache first. We
661 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
662 * is set, the buffer is valid and we do not have to do anything ( see
666 bread(struct vnode *vp, off_t loffset, int size, struct buf **bpp)
670 bp = getblk(vp, loffset, size, 0, 0);
673 /* if not found in cache, do some I/O */
674 if ((bp->b_flags & B_CACHE) == 0) {
675 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
676 bp->b_flags &= ~(B_ERROR | B_INVAL);
677 bp->b_cmd = BUF_CMD_READ;
678 vfs_busy_pages(vp, bp);
679 vn_strategy(vp, &bp->b_bio1);
680 return (biowait(bp));
688 * Operates like bread, but also starts asynchronous I/O on
689 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
690 * to initiating I/O . If B_CACHE is set, the buffer is valid
691 * and we do not have to do anything.
694 breadn(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
695 int *rabsize, int cnt, struct buf **bpp)
697 struct buf *bp, *rabp;
699 int rv = 0, readwait = 0;
701 *bpp = bp = getblk(vp, loffset, size, 0, 0);
703 /* if not found in cache, do some I/O */
704 if ((bp->b_flags & B_CACHE) == 0) {
705 bp->b_flags &= ~(B_ERROR | B_INVAL);
706 bp->b_cmd = BUF_CMD_READ;
707 vfs_busy_pages(vp, bp);
708 vn_strategy(vp, &bp->b_bio1);
712 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
713 if (inmem(vp, *raoffset))
715 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
717 if ((rabp->b_flags & B_CACHE) == 0) {
718 rabp->b_flags |= B_ASYNC;
719 rabp->b_flags &= ~(B_ERROR | B_INVAL);
720 rabp->b_cmd = BUF_CMD_READ;
721 vfs_busy_pages(vp, rabp);
723 vn_strategy(vp, &rabp->b_bio1);
738 * Write, release buffer on completion. (Done by iodone
739 * if async). Do not bother writing anything if the buffer
742 * Note that we set B_CACHE here, indicating that buffer is
743 * fully valid and thus cacheable. This is true even of NFS
744 * now so we set it generally. This could be set either here
745 * or in biodone() since the I/O is synchronous. We put it
749 bwrite(struct buf *bp)
753 if (bp->b_flags & B_INVAL) {
758 oldflags = bp->b_flags;
760 if (BUF_REFCNTNB(bp) == 0)
761 panic("bwrite: buffer is not busy???");
764 /* Mark the buffer clean */
767 bp->b_flags &= ~B_ERROR;
768 bp->b_flags |= B_CACHE;
769 bp->b_cmd = BUF_CMD_WRITE;
770 vfs_busy_pages(bp->b_vp, bp);
773 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
774 * valid for vnode-backed buffers.
776 bp->b_runningbufspace = bp->b_bufsize;
777 if (bp->b_runningbufspace) {
778 runningbufspace += bp->b_runningbufspace;
783 if (oldflags & B_ASYNC)
785 vn_strategy(bp->b_vp, &bp->b_bio1);
787 if ((oldflags & B_ASYNC) == 0) {
788 int rtval = biowait(bp);
798 * Delayed write. (Buffer is marked dirty). Do not bother writing
799 * anything if the buffer is marked invalid.
801 * Note that since the buffer must be completely valid, we can safely
802 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
803 * biodone() in order to prevent getblk from writing the buffer
807 bdwrite(struct buf *bp)
809 if (BUF_REFCNTNB(bp) == 0)
810 panic("bdwrite: buffer is not busy");
812 if (bp->b_flags & B_INVAL) {
819 * Set B_CACHE, indicating that the buffer is fully valid. This is
820 * true even of NFS now.
822 bp->b_flags |= B_CACHE;
825 * This bmap keeps the system from needing to do the bmap later,
826 * perhaps when the system is attempting to do a sync. Since it
827 * is likely that the indirect block -- or whatever other datastructure
828 * that the filesystem needs is still in memory now, it is a good
829 * thing to do this. Note also, that if the pageout daemon is
830 * requesting a sync -- there might not be enough memory to do
831 * the bmap then... So, this is important to do.
833 if (bp->b_bio2.bio_offset == NOOFFSET) {
834 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
835 NULL, NULL, BUF_CMD_WRITE);
839 * Set the *dirty* buffer range based upon the VM system dirty pages.
844 * We need to do this here to satisfy the vnode_pager and the
845 * pageout daemon, so that it thinks that the pages have been
846 * "cleaned". Note that since the pages are in a delayed write
847 * buffer -- the VFS layer "will" see that the pages get written
848 * out on the next sync, or perhaps the cluster will be completed.
854 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
855 * due to the softdep code.
862 * Turn buffer into delayed write request by marking it B_DELWRI.
863 * B_RELBUF and B_NOCACHE must be cleared.
865 * We reassign the buffer to itself to properly update it in the
868 * Must be called from a critical section.
869 * The buffer must be on BQUEUE_NONE.
872 bdirty(struct buf *bp)
874 KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
875 if (bp->b_flags & B_NOCACHE) {
876 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
877 bp->b_flags &= ~B_NOCACHE;
879 if (bp->b_flags & B_INVAL) {
880 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
882 bp->b_flags &= ~B_RELBUF;
884 if ((bp->b_flags & B_DELWRI) == 0) {
885 bp->b_flags |= B_DELWRI;
887 dirtybufspace += bp->b_bufsize;
888 if (bp->b_flags & B_HEAVY)
889 dirtybufspacehw += bp->b_bufsize;
895 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
896 * needs to be flushed with a different buf_daemon thread to avoid
897 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
900 bheavy(struct buf *bp)
902 if ((bp->b_flags & B_HEAVY) == 0) {
903 bp->b_flags |= B_HEAVY;
904 if (bp->b_flags & B_DELWRI)
905 dirtybufspacehw += bp->b_bufsize;
912 * Clear B_DELWRI for buffer.
914 * Must be called from a critical section.
916 * The buffer is typically on BQUEUE_NONE but there is one case in
917 * brelse() that calls this function after placing the buffer on
922 bundirty(struct buf *bp)
924 if (bp->b_flags & B_DELWRI) {
925 bp->b_flags &= ~B_DELWRI;
927 dirtybufspace -= bp->b_bufsize;
928 if (bp->b_flags & B_HEAVY)
929 dirtybufspacehw -= bp->b_bufsize;
930 bd_signal(bp->b_bufsize);
933 * Since it is now being written, we can clear its deferred write flag.
935 bp->b_flags &= ~B_DEFERRED;
941 * Asynchronous write. Start output on a buffer, but do not wait for
942 * it to complete. The buffer is released when the output completes.
944 * bwrite() ( or the VOP routine anyway ) is responsible for handling
945 * B_INVAL buffers. Not us.
948 bawrite(struct buf *bp)
950 bp->b_flags |= B_ASYNC;
957 * Ordered write. Start output on a buffer, and flag it so that the
958 * device will write it in the order it was queued. The buffer is
959 * released when the output completes. bwrite() ( or the VOP routine
960 * anyway ) is responsible for handling B_INVAL buffers.
963 bowrite(struct buf *bp)
965 bp->b_flags |= B_ORDERED | B_ASYNC;
970 * buf_dirty_count_severe:
972 * Return true if we have too many dirty buffers.
975 buf_dirty_count_severe(void)
977 return(runningbufspace + dirtybufspace >= hidirtybufspace);
983 * Release a busy buffer and, if requested, free its resources. The
984 * buffer will be stashed in the appropriate bufqueue[] allowing it
985 * to be accessed later as a cache entity or reused for other purposes.
988 brelse(struct buf *bp)
991 int saved_flags = bp->b_flags;
994 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
999 * If B_NOCACHE is set we are being asked to destroy the buffer and
1000 * its backing store. Clear B_DELWRI.
1002 * B_NOCACHE is set in two cases: (1) when the caller really wants
1003 * to destroy the buffer and backing store and (2) when the caller
1004 * wants to destroy the buffer and backing store after a write
1007 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1011 if (bp->b_flags & B_LOCKED)
1012 bp->b_flags &= ~B_ERROR;
1015 * If a write error occurs and the caller does not want to throw
1016 * away the buffer, redirty the buffer. This will also clear
1019 if (bp->b_cmd == BUF_CMD_WRITE &&
1020 (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
1022 * Failed write, redirty. Must clear B_ERROR to prevent
1023 * pages from being scrapped. If B_INVAL is set then
1024 * this case is not run and the next case is run to
1025 * destroy the buffer. B_INVAL can occur if the buffer
1026 * is outside the range supported by the underlying device.
1028 bp->b_flags &= ~B_ERROR;
1030 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1031 (bp->b_bufsize <= 0) || bp->b_cmd == BUF_CMD_FREEBLKS) {
1033 * Either a failed I/O or we were asked to free or not
1036 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1037 * buffer cannot be immediately freed.
1039 bp->b_flags |= B_INVAL;
1040 if (LIST_FIRST(&bp->b_dep) != NULL)
1042 if (bp->b_flags & B_DELWRI) {
1043 dirtybufspace -= bp->b_bufsize;
1044 if (bp->b_flags & B_HEAVY)
1045 dirtybufspacehw -= bp->b_bufsize;
1046 bd_signal(bp->b_bufsize);
1048 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1052 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1053 * If vfs_vmio_release() is called with either bit set, the
1054 * underlying pages may wind up getting freed causing a previous
1055 * write (bdwrite()) to get 'lost' because pages associated with
1056 * a B_DELWRI bp are marked clean. Pages associated with a
1057 * B_LOCKED buffer may be mapped by the filesystem.
1059 * If we want to release the buffer ourselves (rather then the
1060 * originator asking us to release it), give the originator a
1061 * chance to countermand the release by setting B_LOCKED.
1063 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1064 * if B_DELWRI is set.
1066 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1067 * on pages to return pages to the VM page queues.
1069 if (bp->b_flags & (B_DELWRI | B_LOCKED)) {
1070 bp->b_flags &= ~B_RELBUF;
1071 } else if (vm_page_count_severe()) {
1072 if (LIST_FIRST(&bp->b_dep) != NULL)
1074 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1075 bp->b_flags &= ~B_RELBUF;
1077 bp->b_flags |= B_RELBUF;
1081 * At this point destroying the buffer is governed by the B_INVAL
1082 * or B_RELBUF flags.
1084 bp->b_cmd = BUF_CMD_DONE;
1087 * VMIO buffer rundown. Make sure the VM page array is restored
1088 * after an I/O may have replaces some of the pages with bogus pages
1089 * in order to not destroy dirty pages in a fill-in read.
1091 * Note that due to the code above, if a buffer is marked B_DELWRI
1092 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1093 * B_INVAL may still be set, however.
1095 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1096 * but not the backing store. B_NOCACHE will destroy the backing
1099 * Note that dirty NFS buffers contain byte-granular write ranges
1100 * and should not be destroyed w/ B_INVAL even if the backing store
1103 if (bp->b_flags & B_VMIO) {
1105 * Rundown for VMIO buffers which are not dirty NFS buffers.
1117 * Get the base offset and length of the buffer. Note that
1118 * in the VMIO case if the buffer block size is not
1119 * page-aligned then b_data pointer may not be page-aligned.
1120 * But our b_xio.xio_pages array *IS* page aligned.
1122 * block sizes less then DEV_BSIZE (usually 512) are not
1123 * supported due to the page granularity bits (m->valid,
1124 * m->dirty, etc...).
1126 * See man buf(9) for more information
1129 resid = bp->b_bufsize;
1130 foff = bp->b_loffset;
1132 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1133 m = bp->b_xio.xio_pages[i];
1134 vm_page_flag_clear(m, PG_ZERO);
1136 * If we hit a bogus page, fixup *all* of them
1137 * now. Note that we left these pages wired
1138 * when we removed them so they had better exist,
1139 * and they cannot be ripped out from under us so
1140 * no critical section protection is necessary.
1142 if (m == bogus_page) {
1144 poff = OFF_TO_IDX(bp->b_loffset);
1146 for (j = i; j < bp->b_xio.xio_npages; j++) {
1149 mtmp = bp->b_xio.xio_pages[j];
1150 if (mtmp == bogus_page) {
1151 mtmp = vm_page_lookup(obj, poff + j);
1153 panic("brelse: page missing");
1155 bp->b_xio.xio_pages[j] = mtmp;
1159 if ((bp->b_flags & B_INVAL) == 0) {
1160 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1161 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1163 m = bp->b_xio.xio_pages[i];
1167 * Invalidate the backing store if B_NOCACHE is set
1168 * (e.g. used with vinvalbuf()). If this is NFS
1169 * we impose a requirement that the block size be
1170 * a multiple of PAGE_SIZE and create a temporary
1171 * hack to basically invalidate the whole page. The
1172 * problem is that NFS uses really odd buffer sizes
1173 * especially when tracking piecemeal writes and
1174 * it also vinvalbuf()'s a lot, which would result
1175 * in only partial page validation and invalidation
1176 * here. If the file page is mmap()'d, however,
1177 * all the valid bits get set so after we invalidate
1178 * here we would end up with weird m->valid values
1179 * like 0xfc. nfs_getpages() can't handle this so
1180 * we clear all the valid bits for the NFS case
1181 * instead of just some of them.
1183 * The real bug is the VM system having to set m->valid
1184 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1185 * itself is an artifact of the whole 512-byte
1186 * granular mess that exists to support odd block
1187 * sizes and UFS meta-data block sizes (e.g. 6144).
1188 * A complete rewrite is required.
1190 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1191 int poffset = foff & PAGE_MASK;
1194 presid = PAGE_SIZE - poffset;
1195 if (bp->b_vp->v_tag == VT_NFS &&
1196 bp->b_vp->v_type == VREG) {
1198 } else if (presid > resid) {
1201 KASSERT(presid >= 0, ("brelse: extra page"));
1202 vm_page_set_invalid(m, poffset, presid);
1204 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1205 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1207 if (bp->b_flags & (B_INVAL | B_RELBUF))
1208 vfs_vmio_release(bp);
1211 * Rundown for non-VMIO buffers.
1213 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1216 kprintf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1220 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1226 if (bp->b_qindex != BQUEUE_NONE)
1227 panic("brelse: free buffer onto another queue???");
1228 if (BUF_REFCNTNB(bp) > 1) {
1229 /* Temporary panic to verify exclusive locking */
1230 /* This panic goes away when we allow shared refs */
1231 panic("brelse: multiple refs");
1232 /* do not release to free list */
1239 * Figure out the correct queue to place the cleaned up buffer on.
1240 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1241 * disassociated from their vnode.
1243 if (bp->b_flags & B_LOCKED) {
1245 * Buffers that are locked are placed in the locked queue
1246 * immediately, regardless of their state.
1248 bp->b_qindex = BQUEUE_LOCKED;
1249 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1250 } else if (bp->b_bufsize == 0) {
1252 * Buffers with no memory. Due to conditionals near the top
1253 * of brelse() such buffers should probably already be
1254 * marked B_INVAL and disassociated from their vnode.
1256 bp->b_flags |= B_INVAL;
1257 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1258 KKASSERT((bp->b_flags & B_HASHED) == 0);
1259 if (bp->b_kvasize) {
1260 bp->b_qindex = BQUEUE_EMPTYKVA;
1262 bp->b_qindex = BQUEUE_EMPTY;
1264 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1265 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1267 * Buffers with junk contents. Again these buffers had better
1268 * already be disassociated from their vnode.
1270 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1271 KKASSERT((bp->b_flags & B_HASHED) == 0);
1272 bp->b_flags |= B_INVAL;
1273 bp->b_qindex = BQUEUE_CLEAN;
1274 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1277 * Remaining buffers. These buffers are still associated with
1280 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1282 bp->b_qindex = BQUEUE_DIRTY;
1283 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1285 case B_DELWRI | B_HEAVY:
1286 bp->b_qindex = BQUEUE_DIRTY_HW;
1287 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1292 * NOTE: Buffers are always placed at the end of the
1293 * queue. If B_AGE is not set the buffer will cycle
1294 * through the queue twice.
1296 bp->b_qindex = BQUEUE_CLEAN;
1297 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1303 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1304 * on the correct queue.
1306 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1310 * The bp is on an appropriate queue unless locked. If it is not
1311 * locked or dirty we can wakeup threads waiting for buffer space.
1313 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1314 * if B_INVAL is set ).
1316 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1320 * Something we can maybe free or reuse
1322 if (bp->b_bufsize || bp->b_kvasize)
1326 * Clean up temporary flags and unlock the buffer.
1328 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_RELBUF | B_DIRECT);
1336 * Release a buffer back to the appropriate queue but do not try to free
1337 * it. The buffer is expected to be used again soon.
1339 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1340 * biodone() to requeue an async I/O on completion. It is also used when
1341 * known good buffers need to be requeued but we think we may need the data
1344 * XXX we should be able to leave the B_RELBUF hint set on completion.
1347 bqrelse(struct buf *bp)
1351 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1353 if (bp->b_qindex != BQUEUE_NONE)
1354 panic("bqrelse: free buffer onto another queue???");
1355 if (BUF_REFCNTNB(bp) > 1) {
1356 /* do not release to free list */
1357 panic("bqrelse: multiple refs");
1362 if (bp->b_flags & B_LOCKED) {
1364 * Locked buffers are released to the locked queue. However,
1365 * if the buffer is dirty it will first go into the dirty
1366 * queue and later on after the I/O completes successfully it
1367 * will be released to the locked queue.
1369 bp->b_flags &= ~B_ERROR;
1370 bp->b_qindex = BQUEUE_LOCKED;
1371 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1372 } else if (bp->b_flags & B_DELWRI) {
1373 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1374 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1375 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1376 } else if (vm_page_count_severe()) {
1378 * We are too low on memory, we have to try to free the
1379 * buffer (most importantly: the wired pages making up its
1380 * backing store) *now*.
1386 bp->b_qindex = BQUEUE_CLEAN;
1387 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1390 if ((bp->b_flags & B_LOCKED) == 0 &&
1391 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1396 * Something we can maybe free or reuse.
1398 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1402 * Final cleanup and unlock. Clear bits that are only used while a
1403 * buffer is actively locked.
1405 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_RELBUF);
1413 * Return backing pages held by the buffer 'bp' back to the VM system
1414 * if possible. The pages are freed if they are no longer valid or
1415 * attempt to free if it was used for direct I/O otherwise they are
1416 * sent to the page cache.
1418 * Pages that were marked busy are left alone and skipped.
1420 * The KVA mapping (b_data) for the underlying pages is removed by
1424 vfs_vmio_release(struct buf *bp)
1430 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1431 m = bp->b_xio.xio_pages[i];
1432 bp->b_xio.xio_pages[i] = NULL;
1434 * In order to keep page LRU ordering consistent, put
1435 * everything on the inactive queue.
1437 vm_page_unwire(m, 0);
1439 * We don't mess with busy pages, it is
1440 * the responsibility of the process that
1441 * busied the pages to deal with them.
1443 if ((m->flags & PG_BUSY) || (m->busy != 0))
1446 if (m->wire_count == 0) {
1447 vm_page_flag_clear(m, PG_ZERO);
1449 * Might as well free the page if we can and it has
1450 * no valid data. We also free the page if the
1451 * buffer was used for direct I/O.
1453 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1454 m->hold_count == 0) {
1456 vm_page_protect(m, VM_PROT_NONE);
1458 } else if (bp->b_flags & B_DIRECT) {
1459 vm_page_try_to_free(m);
1460 } else if (vm_page_count_severe()) {
1461 vm_page_try_to_cache(m);
1466 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1467 if (bp->b_bufsize) {
1471 bp->b_xio.xio_npages = 0;
1472 bp->b_flags &= ~B_VMIO;
1473 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1481 * Implement clustered async writes for clearing out B_DELWRI buffers.
1482 * This is much better then the old way of writing only one buffer at
1483 * a time. Note that we may not be presented with the buffers in the
1484 * correct order, so we search for the cluster in both directions.
1486 * The buffer is locked on call.
1489 vfs_bio_awrite(struct buf *bp)
1493 off_t loffset = bp->b_loffset;
1494 struct vnode *vp = bp->b_vp;
1502 * right now we support clustered writing only to regular files. If
1503 * we find a clusterable block we could be in the middle of a cluster
1504 * rather then at the beginning.
1506 * NOTE: b_bio1 contains the logical loffset and is aliased
1507 * to b_loffset. b_bio2 contains the translated block number.
1509 if ((vp->v_type == VREG) &&
1510 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1511 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1513 size = vp->v_mount->mnt_stat.f_iosize;
1515 for (i = size; i < MAXPHYS; i += size) {
1516 if ((bpa = findblk(vp, loffset + i)) &&
1517 BUF_REFCNT(bpa) == 0 &&
1518 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1519 (B_DELWRI | B_CLUSTEROK)) &&
1520 (bpa->b_bufsize == size)) {
1521 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1522 (bpa->b_bio2.bio_offset !=
1523 bp->b_bio2.bio_offset + i))
1529 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1530 if ((bpa = findblk(vp, loffset - j)) &&
1531 BUF_REFCNT(bpa) == 0 &&
1532 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1533 (B_DELWRI | B_CLUSTEROK)) &&
1534 (bpa->b_bufsize == size)) {
1535 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1536 (bpa->b_bio2.bio_offset !=
1537 bp->b_bio2.bio_offset - j))
1546 * this is a possible cluster write
1548 if (nbytes != size) {
1550 nwritten = cluster_wbuild(vp, size,
1551 loffset - j, nbytes);
1558 bp->b_flags |= B_ASYNC;
1562 * default (old) behavior, writing out only one block
1564 * XXX returns b_bufsize instead of b_bcount for nwritten?
1566 nwritten = bp->b_bufsize;
1575 * Find and initialize a new buffer header, freeing up existing buffers
1576 * in the bufqueues as necessary. The new buffer is returned locked.
1578 * Important: B_INVAL is not set. If the caller wishes to throw the
1579 * buffer away, the caller must set B_INVAL prior to calling brelse().
1582 * We have insufficient buffer headers
1583 * We have insufficient buffer space
1584 * buffer_map is too fragmented ( space reservation fails )
1585 * If we have to flush dirty buffers ( but we try to avoid this )
1587 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1588 * Instead we ask the buf daemon to do it for us. We attempt to
1589 * avoid piecemeal wakeups of the pageout daemon.
1593 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1599 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1600 static int flushingbufs;
1603 * We can't afford to block since we might be holding a vnode lock,
1604 * which may prevent system daemons from running. We deal with
1605 * low-memory situations by proactively returning memory and running
1606 * async I/O rather then sync I/O.
1610 --getnewbufrestarts;
1612 ++getnewbufrestarts;
1615 * Setup for scan. If we do not have enough free buffers,
1616 * we setup a degenerate case that immediately fails. Note
1617 * that if we are specially marked process, we are allowed to
1618 * dip into our reserves.
1620 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1622 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1623 * However, there are a number of cases (defragging, reusing, ...)
1624 * where we cannot backup.
1626 nqindex = BQUEUE_EMPTYKVA;
1627 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1631 * If no EMPTYKVA buffers and we are either
1632 * defragging or reusing, locate a CLEAN buffer
1633 * to free or reuse. If bufspace useage is low
1634 * skip this step so we can allocate a new buffer.
1636 if (defrag || bufspace >= lobufspace) {
1637 nqindex = BQUEUE_CLEAN;
1638 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1642 * If we could not find or were not allowed to reuse a
1643 * CLEAN buffer, check to see if it is ok to use an EMPTY
1644 * buffer. We can only use an EMPTY buffer if allocating
1645 * its KVA would not otherwise run us out of buffer space.
1647 if (nbp == NULL && defrag == 0 &&
1648 bufspace + maxsize < hibufspace) {
1649 nqindex = BQUEUE_EMPTY;
1650 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1655 * Run scan, possibly freeing data and/or kva mappings on the fly
1659 while ((bp = nbp) != NULL) {
1660 int qindex = nqindex;
1662 nbp = TAILQ_NEXT(bp, b_freelist);
1665 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
1666 * cycles through the queue twice before being selected.
1668 if (qindex == BQUEUE_CLEAN &&
1669 (bp->b_flags & B_AGE) == 0 && nbp) {
1670 bp->b_flags |= B_AGE;
1671 TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
1672 TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
1677 * Calculate next bp ( we can only use it if we do not block
1678 * or do other fancy things ).
1683 nqindex = BQUEUE_EMPTYKVA;
1684 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1687 case BQUEUE_EMPTYKVA:
1688 nqindex = BQUEUE_CLEAN;
1689 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1703 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1706 * Note: we no longer distinguish between VMIO and non-VMIO
1710 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1713 * If we are defragging then we need a buffer with
1714 * b_kvasize != 0. XXX this situation should no longer
1715 * occur, if defrag is non-zero the buffer's b_kvasize
1716 * should also be non-zero at this point. XXX
1718 if (defrag && bp->b_kvasize == 0) {
1719 kprintf("Warning: defrag empty buffer %p\n", bp);
1724 * Start freeing the bp. This is somewhat involved. nbp
1725 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1726 * on the clean list must be disassociated from their
1727 * current vnode. Buffers on the empty[kva] lists have
1728 * already been disassociated.
1731 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1732 kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1733 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1736 if (bp->b_qindex != qindex) {
1737 kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1744 * Dependancies must be handled before we disassociate the
1747 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1748 * be immediately disassociated. HAMMER then becomes
1749 * responsible for releasing the buffer.
1751 if (LIST_FIRST(&bp->b_dep) != NULL) {
1753 if (bp->b_flags & B_LOCKED) {
1757 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1760 if (qindex == BQUEUE_CLEAN) {
1761 if (bp->b_flags & B_VMIO) {
1762 bp->b_flags &= ~B_ASYNC;
1763 vfs_vmio_release(bp);
1770 * NOTE: nbp is now entirely invalid. We can only restart
1771 * the scan from this point on.
1773 * Get the rest of the buffer freed up. b_kva* is still
1774 * valid after this operation.
1777 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1778 KKASSERT((bp->b_flags & B_HASHED) == 0);
1781 * critical section protection is not required when
1782 * scrapping a buffer's contents because it is already
1788 bp->b_flags = B_BNOCLIP;
1789 bp->b_cmd = BUF_CMD_DONE;
1794 bp->b_xio.xio_npages = 0;
1795 bp->b_dirtyoff = bp->b_dirtyend = 0;
1797 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1799 if (blkflags & GETBLK_BHEAVY)
1800 bp->b_flags |= B_HEAVY;
1803 * If we are defragging then free the buffer.
1806 bp->b_flags |= B_INVAL;
1814 * If we are overcomitted then recover the buffer and its
1815 * KVM space. This occurs in rare situations when multiple
1816 * processes are blocked in getnewbuf() or allocbuf().
1818 if (bufspace >= hibufspace)
1820 if (flushingbufs && bp->b_kvasize != 0) {
1821 bp->b_flags |= B_INVAL;
1826 if (bufspace < lobufspace)
1832 * If we exhausted our list, sleep as appropriate. We may have to
1833 * wakeup various daemons and write out some dirty buffers.
1835 * Generally we are sleeping due to insufficient buffer space.
1843 flags = VFS_BIO_NEED_BUFSPACE;
1845 } else if (bufspace >= hibufspace) {
1847 flags = VFS_BIO_NEED_BUFSPACE;
1850 flags = VFS_BIO_NEED_ANY;
1853 needsbuffer |= flags;
1854 bd_speedup(); /* heeeelp */
1855 while (needsbuffer & flags) {
1856 if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
1861 * We finally have a valid bp. We aren't quite out of the
1862 * woods, we still have to reserve kva space. In order
1863 * to keep fragmentation sane we only allocate kva in
1866 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1868 if (maxsize != bp->b_kvasize) {
1869 vm_offset_t addr = 0;
1874 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1875 vm_map_lock(&buffer_map);
1877 if (vm_map_findspace(&buffer_map,
1878 vm_map_min(&buffer_map), maxsize,
1881 * Uh oh. Buffer map is too fragmented. We
1882 * must defragment the map.
1884 vm_map_unlock(&buffer_map);
1885 vm_map_entry_release(count);
1888 bp->b_flags |= B_INVAL;
1893 vm_map_insert(&buffer_map, &count,
1895 addr, addr + maxsize,
1897 VM_PROT_ALL, VM_PROT_ALL,
1900 bp->b_kvabase = (caddr_t) addr;
1901 bp->b_kvasize = maxsize;
1902 bufspace += bp->b_kvasize;
1905 vm_map_unlock(&buffer_map);
1906 vm_map_entry_release(count);
1908 bp->b_data = bp->b_kvabase;
1914 * This routine is called in an emergency to recover VM pages from the
1915 * buffer cache by cashing in clean buffers. The idea is to recover
1916 * enough pages to be able to satisfy a stuck bio_page_alloc().
1919 recoverbufpages(void)
1926 while (bytes < MAXBSIZE) {
1927 bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1932 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
1933 * cycles through the queue twice before being selected.
1935 if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) {
1936 bp->b_flags |= B_AGE;
1937 TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1938 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN],
1946 KKASSERT(bp->b_qindex == BQUEUE_CLEAN);
1947 KKASSERT((bp->b_flags & B_DELWRI) == 0);
1950 * Start freeing the bp. This is somewhat involved.
1952 * Buffers on the clean list must be disassociated from
1953 * their current vnode
1956 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1957 kprintf("recoverbufpages: warning, locked buf %p, race corrected\n", bp);
1958 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1961 if (bp->b_qindex != BQUEUE_CLEAN) {
1962 kprintf("recoverbufpages: warning, BUF_LOCK blocked unexpectedly on buf %p index %d, race corrected\n", bp, bp->b_qindex);
1969 * Dependancies must be handled before we disassociate the
1972 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1973 * be immediately disassociated. HAMMER then becomes
1974 * responsible for releasing the buffer.
1976 if (LIST_FIRST(&bp->b_dep) != NULL) {
1978 if (bp->b_flags & B_LOCKED) {
1982 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1985 bytes += bp->b_bufsize;
1987 if (bp->b_flags & B_VMIO) {
1988 bp->b_flags &= ~B_ASYNC;
1989 bp->b_flags |= B_DIRECT; /* try to free pages */
1990 vfs_vmio_release(bp);
1995 KKASSERT(bp->b_vp == NULL);
1996 KKASSERT((bp->b_flags & B_HASHED) == 0);
1999 * critical section protection is not required when
2000 * scrapping a buffer's contents because it is already
2006 bp->b_flags = B_BNOCLIP;
2007 bp->b_cmd = BUF_CMD_DONE;
2012 bp->b_xio.xio_npages = 0;
2013 bp->b_dirtyoff = bp->b_dirtyend = 0;
2015 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2017 bp->b_flags |= B_INVAL;
2027 * Buffer flushing daemon. Buffers are normally flushed by the
2028 * update daemon but if it cannot keep up this process starts to
2029 * take the load in an attempt to prevent getnewbuf() from blocking.
2031 * Once a flush is initiated it does not stop until the number
2032 * of buffers falls below lodirtybuffers, but we will wake up anyone
2033 * waiting at the mid-point.
2036 static struct kproc_desc buf_kp = {
2041 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2042 kproc_start, &buf_kp)
2044 static struct kproc_desc bufhw_kp = {
2049 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2050 kproc_start, &bufhw_kp)
2058 * This process needs to be suspended prior to shutdown sync.
2060 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2061 bufdaemon_td, SHUTDOWN_PRI_LAST);
2062 curthread->td_flags |= TDF_SYSTHREAD;
2065 * This process is allowed to take the buffer cache to the limit
2070 kproc_suspend_loop();
2073 * Do the flush. Limit the amount of in-transit I/O we
2074 * allow to build up, otherwise we would completely saturate
2075 * the I/O system. Wakeup any waiting processes before we
2076 * normally would so they can run in parallel with our drain.
2078 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2079 * but because we split the operation into two threads we
2080 * have to cut it in half for each thread.
2082 limit = lodirtybufspace / 2;
2083 waitrunningbufspace(limit);
2084 while (runningbufspace + dirtybufspace > limit) {
2085 if (flushbufqueues(BQUEUE_DIRTY) == 0)
2087 waitrunningbufspace(limit);
2091 * We reached our low water mark, reset the
2092 * request and sleep until we are needed again.
2093 * The sleep is just so the suspend code works.
2095 spin_lock_wr(&needsbuffer_spin);
2096 if (bd_request == 0) {
2097 msleep(&bd_request, &needsbuffer_spin, 0,
2101 spin_unlock_wr(&needsbuffer_spin);
2111 * This process needs to be suspended prior to shutdown sync.
2113 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2114 bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2115 curthread->td_flags |= TDF_SYSTHREAD;
2118 * This process is allowed to take the buffer cache to the limit
2123 kproc_suspend_loop();
2126 * Do the flush. Limit the amount of in-transit I/O we
2127 * allow to build up, otherwise we would completely saturate
2128 * the I/O system. Wakeup any waiting processes before we
2129 * normally would so they can run in parallel with our drain.
2131 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2132 * but because we split the operation into two threads we
2133 * have to cut it in half for each thread.
2135 limit = lodirtybufspace / 2;
2136 waitrunningbufspace(limit);
2137 while (runningbufspace + dirtybufspacehw > limit) {
2138 if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2140 waitrunningbufspace(limit);
2144 * We reached our low water mark, reset the
2145 * request and sleep until we are needed again.
2146 * The sleep is just so the suspend code works.
2148 spin_lock_wr(&needsbuffer_spin);
2149 if (bd_request_hw == 0) {
2150 msleep(&bd_request_hw, &needsbuffer_spin, 0,
2154 spin_unlock_wr(&needsbuffer_spin);
2161 * Try to flush a buffer in the dirty queue. We must be careful to
2162 * free up B_INVAL buffers instead of write them, which NFS is
2163 * particularly sensitive to.
2165 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate
2166 * that we really want to try to get the buffer out and reuse it
2167 * due to the write load on the machine.
2171 flushbufqueues(bufq_type_t q)
2176 bp = TAILQ_FIRST(&bufqueues[q]);
2179 KASSERT((bp->b_flags & B_DELWRI),
2180 ("unexpected clean buffer %p", bp));
2182 if (bp->b_flags & B_DELWRI) {
2183 if (bp->b_flags & B_INVAL) {
2184 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2185 panic("flushbufqueues: locked buf");
2191 if (LIST_FIRST(&bp->b_dep) != NULL &&
2192 (bp->b_flags & B_DEFERRED) == 0 &&
2193 buf_countdeps(bp, 0)) {
2194 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2195 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2197 bp->b_flags |= B_DEFERRED;
2198 bp = TAILQ_FIRST(&bufqueues[q]);
2203 * Only write it out if we can successfully lock
2204 * it. If the buffer has a dependancy,
2205 * buf_checkwrite must also return 0.
2207 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2208 if (LIST_FIRST(&bp->b_dep) != NULL &&
2209 buf_checkwrite(bp)) {
2213 bp->b_flags |= B_AGE;
2220 bp = TAILQ_NEXT(bp, b_freelist);
2228 * Returns true if no I/O is needed to access the associated VM object.
2229 * This is like findblk except it also hunts around in the VM system for
2232 * Note that we ignore vm_page_free() races from interrupts against our
2233 * lookup, since if the caller is not protected our return value will not
2234 * be any more valid then otherwise once we exit the critical section.
2237 inmem(struct vnode *vp, off_t loffset)
2240 vm_offset_t toff, tinc, size;
2243 if (findblk(vp, loffset))
2245 if (vp->v_mount == NULL)
2247 if ((obj = vp->v_object) == NULL)
2251 if (size > vp->v_mount->mnt_stat.f_iosize)
2252 size = vp->v_mount->mnt_stat.f_iosize;
2254 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2255 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2259 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2260 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2261 if (vm_page_is_valid(m,
2262 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2271 * Sets the dirty range for a buffer based on the status of the dirty
2272 * bits in the pages comprising the buffer.
2274 * The range is limited to the size of the buffer.
2276 * This routine is primarily used by NFS, but is generalized for the
2280 vfs_setdirty(struct buf *bp)
2286 * Degenerate case - empty buffer
2289 if (bp->b_bufsize == 0)
2293 * We qualify the scan for modified pages on whether the
2294 * object has been flushed yet. The OBJ_WRITEABLE flag
2295 * is not cleared simply by protecting pages off.
2298 if ((bp->b_flags & B_VMIO) == 0)
2301 object = bp->b_xio.xio_pages[0]->object;
2303 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2304 kprintf("Warning: object %p writeable but not mightbedirty\n", object);
2305 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2306 kprintf("Warning: object %p mightbedirty but not writeable\n", object);
2308 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2309 vm_offset_t boffset;
2310 vm_offset_t eoffset;
2313 * test the pages to see if they have been modified directly
2314 * by users through the VM system.
2316 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2317 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2318 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2322 * Calculate the encompassing dirty range, boffset and eoffset,
2323 * (eoffset - boffset) bytes.
2326 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2327 if (bp->b_xio.xio_pages[i]->dirty)
2330 boffset = (i << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2332 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2333 if (bp->b_xio.xio_pages[i]->dirty) {
2337 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2340 * Fit it to the buffer.
2343 if (eoffset > bp->b_bcount)
2344 eoffset = bp->b_bcount;
2347 * If we have a good dirty range, merge with the existing
2351 if (boffset < eoffset) {
2352 if (bp->b_dirtyoff > boffset)
2353 bp->b_dirtyoff = boffset;
2354 if (bp->b_dirtyend < eoffset)
2355 bp->b_dirtyend = eoffset;
2363 * Locate and return the specified buffer, or NULL if the buffer does
2364 * not exist. Do not attempt to lock the buffer or manipulate it in
2365 * any way. The caller must validate that the correct buffer has been
2366 * obtain after locking it.
2369 findblk(struct vnode *vp, off_t loffset)
2374 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2382 * Get a block given a specified block and offset into a file/device.
2383 * B_INVAL may or may not be set on return. The caller should clear
2384 * B_INVAL prior to initiating a READ.
2386 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2387 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2388 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2389 * without doing any of those things the system will likely believe
2390 * the buffer to be valid (especially if it is not B_VMIO), and the
2391 * next getblk() will return the buffer with B_CACHE set.
2393 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2394 * an existing buffer.
2396 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2397 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2398 * and then cleared based on the backing VM. If the previous buffer is
2399 * non-0-sized but invalid, B_CACHE will be cleared.
2401 * If getblk() must create a new buffer, the new buffer is returned with
2402 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2403 * case it is returned with B_INVAL clear and B_CACHE set based on the
2406 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2407 * B_CACHE bit is clear.
2409 * What this means, basically, is that the caller should use B_CACHE to
2410 * determine whether the buffer is fully valid or not and should clear
2411 * B_INVAL prior to issuing a read. If the caller intends to validate
2412 * the buffer by loading its data area with something, the caller needs
2413 * to clear B_INVAL. If the caller does this without issuing an I/O,
2414 * the caller should set B_CACHE ( as an optimization ), else the caller
2415 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2416 * a write attempt or if it was a successfull read. If the caller
2417 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2418 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2422 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2423 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2426 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2429 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2432 if (size > MAXBSIZE)
2433 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2434 if (vp->v_object == NULL)
2435 panic("getblk: vnode %p has no object!", vp);
2439 if ((bp = findblk(vp, loffset))) {
2441 * The buffer was found in the cache, but we need to lock it.
2442 * Even with LK_NOWAIT the lockmgr may break our critical
2443 * section, so double-check the validity of the buffer
2444 * once the lock has been obtained.
2446 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2447 int lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2448 if (blkflags & GETBLK_PCATCH)
2449 lkflags |= LK_PCATCH;
2450 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2452 if (error == ENOLCK)
2460 * Once the buffer has been locked, make sure we didn't race
2461 * a buffer recyclement. Buffers that are no longer hashed
2462 * will have b_vp == NULL, so this takes care of that check
2465 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2466 kprintf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp, vp, loffset);
2472 * All vnode-based buffers must be backed by a VM object.
2474 KKASSERT(bp->b_flags & B_VMIO);
2475 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2476 bp->b_flags &= ~B_AGE;
2479 * Make sure that B_INVAL buffers do not have a cached
2480 * block number translation.
2482 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2483 kprintf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp, vp, loffset);
2484 clearbiocache(&bp->b_bio2);
2488 * The buffer is locked. B_CACHE is cleared if the buffer is
2491 if (bp->b_flags & B_INVAL)
2492 bp->b_flags &= ~B_CACHE;
2496 * Any size inconsistancy with a dirty buffer or a buffer
2497 * with a softupdates dependancy must be resolved. Resizing
2498 * the buffer in such circumstances can lead to problems.
2500 if (size != bp->b_bcount) {
2501 if (bp->b_flags & B_DELWRI) {
2502 bp->b_flags |= B_NOCACHE;
2504 } else if (LIST_FIRST(&bp->b_dep)) {
2505 bp->b_flags |= B_NOCACHE;
2508 bp->b_flags |= B_RELBUF;
2513 KKASSERT(size <= bp->b_kvasize);
2514 KASSERT(bp->b_loffset != NOOFFSET,
2515 ("getblk: no buffer offset"));
2518 * A buffer with B_DELWRI set and B_CACHE clear must
2519 * be committed before we can return the buffer in
2520 * order to prevent the caller from issuing a read
2521 * ( due to B_CACHE not being set ) and overwriting
2524 * Most callers, including NFS and FFS, need this to
2525 * operate properly either because they assume they
2526 * can issue a read if B_CACHE is not set, or because
2527 * ( for example ) an uncached B_DELWRI might loop due
2528 * to softupdates re-dirtying the buffer. In the latter
2529 * case, B_CACHE is set after the first write completes,
2530 * preventing further loops.
2532 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2533 * above while extending the buffer, we cannot allow the
2534 * buffer to remain with B_CACHE set after the write
2535 * completes or it will represent a corrupt state. To
2536 * deal with this we set B_NOCACHE to scrap the buffer
2539 * We might be able to do something fancy, like setting
2540 * B_CACHE in bwrite() except if B_DELWRI is already set,
2541 * so the below call doesn't set B_CACHE, but that gets real
2542 * confusing. This is much easier.
2545 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2546 bp->b_flags |= B_NOCACHE;
2553 * Buffer is not in-core, create new buffer. The buffer
2554 * returned by getnewbuf() is locked. Note that the returned
2555 * buffer is also considered valid (not marked B_INVAL).
2557 * Calculating the offset for the I/O requires figuring out
2558 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2559 * the mount's f_iosize otherwise. If the vnode does not
2560 * have an associated mount we assume that the passed size is
2563 * Note that vn_isdisk() cannot be used here since it may
2564 * return a failure for numerous reasons. Note that the
2565 * buffer size may be larger then the block size (the caller
2566 * will use block numbers with the proper multiple). Beware
2567 * of using any v_* fields which are part of unions. In
2568 * particular, in DragonFly the mount point overloading
2569 * mechanism uses the namecache only and the underlying
2570 * directory vnode is not a special case.
2574 if (vp->v_type == VBLK || vp->v_type == VCHR)
2576 else if (vp->v_mount)
2577 bsize = vp->v_mount->mnt_stat.f_iosize;
2581 maxsize = size + (loffset & PAGE_MASK);
2582 maxsize = imax(maxsize, bsize);
2584 if ((bp = getnewbuf(blkflags, slptimeo, size, maxsize)) == NULL) {
2585 if (slpflags || slptimeo) {
2593 * This code is used to make sure that a buffer is not
2594 * created while the getnewbuf routine is blocked.
2595 * This can be a problem whether the vnode is locked or not.
2596 * If the buffer is created out from under us, we have to
2597 * throw away the one we just created. There is no window
2598 * race because we are safely running in a critical section
2599 * from the point of the duplicate buffer creation through
2600 * to here, and we've locked the buffer.
2602 if (findblk(vp, loffset)) {
2603 bp->b_flags |= B_INVAL;
2609 * Insert the buffer into the hash, so that it can
2610 * be found by findblk().
2612 * Make sure the translation layer has been cleared.
2614 bp->b_loffset = loffset;
2615 bp->b_bio2.bio_offset = NOOFFSET;
2616 /* bp->b_bio2.bio_next = NULL; */
2621 * All vnode-based buffers must be backed by a VM object.
2623 KKASSERT(vp->v_object != NULL);
2624 bp->b_flags |= B_VMIO;
2625 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2637 * Reacquire a buffer that was previously released to the locked queue,
2638 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2639 * set B_LOCKED (which handles the acquisition race).
2641 * To this end, either B_LOCKED must be set or the dependancy list must be
2645 regetblk(struct buf *bp)
2647 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2648 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2657 * Get an empty, disassociated buffer of given size. The buffer is
2658 * initially set to B_INVAL.
2660 * critical section protection is not required for the allocbuf()
2661 * call because races are impossible here.
2669 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2672 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2676 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2684 * This code constitutes the buffer memory from either anonymous system
2685 * memory (in the case of non-VMIO operations) or from an associated
2686 * VM object (in the case of VMIO operations). This code is able to
2687 * resize a buffer up or down.
2689 * Note that this code is tricky, and has many complications to resolve
2690 * deadlock or inconsistant data situations. Tread lightly!!!
2691 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2692 * the caller. Calling this code willy nilly can result in the loss of data.
2694 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2695 * B_CACHE for the non-VMIO case.
2697 * This routine does not need to be called from a critical section but you
2698 * must own the buffer.
2701 allocbuf(struct buf *bp, int size)
2703 int newbsize, mbsize;
2706 if (BUF_REFCNT(bp) == 0)
2707 panic("allocbuf: buffer not busy");
2709 if (bp->b_kvasize < size)
2710 panic("allocbuf: buffer too small");
2712 if ((bp->b_flags & B_VMIO) == 0) {
2716 * Just get anonymous memory from the kernel. Don't
2717 * mess with B_CACHE.
2719 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2720 if (bp->b_flags & B_MALLOC)
2723 newbsize = round_page(size);
2725 if (newbsize < bp->b_bufsize) {
2727 * Malloced buffers are not shrunk
2729 if (bp->b_flags & B_MALLOC) {
2731 bp->b_bcount = size;
2733 kfree(bp->b_data, M_BIOBUF);
2734 if (bp->b_bufsize) {
2735 bufmallocspace -= bp->b_bufsize;
2739 bp->b_data = bp->b_kvabase;
2741 bp->b_flags &= ~B_MALLOC;
2747 (vm_offset_t) bp->b_data + newbsize,
2748 (vm_offset_t) bp->b_data + bp->b_bufsize);
2749 } else if (newbsize > bp->b_bufsize) {
2751 * We only use malloced memory on the first allocation.
2752 * and revert to page-allocated memory when the buffer
2755 if ((bufmallocspace < maxbufmallocspace) &&
2756 (bp->b_bufsize == 0) &&
2757 (mbsize <= PAGE_SIZE/2)) {
2759 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
2760 bp->b_bufsize = mbsize;
2761 bp->b_bcount = size;
2762 bp->b_flags |= B_MALLOC;
2763 bufmallocspace += mbsize;
2769 * If the buffer is growing on its other-than-first
2770 * allocation, then we revert to the page-allocation
2773 if (bp->b_flags & B_MALLOC) {
2774 origbuf = bp->b_data;
2775 origbufsize = bp->b_bufsize;
2776 bp->b_data = bp->b_kvabase;
2777 if (bp->b_bufsize) {
2778 bufmallocspace -= bp->b_bufsize;
2782 bp->b_flags &= ~B_MALLOC;
2783 newbsize = round_page(newbsize);
2787 (vm_offset_t) bp->b_data + bp->b_bufsize,
2788 (vm_offset_t) bp->b_data + newbsize);
2790 bcopy(origbuf, bp->b_data, origbufsize);
2791 kfree(origbuf, M_BIOBUF);
2798 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2799 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
2800 newbsize + PAGE_MASK) >> PAGE_SHIFT;
2801 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
2803 if (bp->b_flags & B_MALLOC)
2804 panic("allocbuf: VMIO buffer can't be malloced");
2806 * Set B_CACHE initially if buffer is 0 length or will become
2809 if (size == 0 || bp->b_bufsize == 0)
2810 bp->b_flags |= B_CACHE;
2812 if (newbsize < bp->b_bufsize) {
2814 * DEV_BSIZE aligned new buffer size is less then the
2815 * DEV_BSIZE aligned existing buffer size. Figure out
2816 * if we have to remove any pages.
2818 if (desiredpages < bp->b_xio.xio_npages) {
2819 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2821 * the page is not freed here -- it
2822 * is the responsibility of
2823 * vnode_pager_setsize
2825 m = bp->b_xio.xio_pages[i];
2826 KASSERT(m != bogus_page,
2827 ("allocbuf: bogus page found"));
2828 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2831 bp->b_xio.xio_pages[i] = NULL;
2832 vm_page_unwire(m, 0);
2834 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2835 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2836 bp->b_xio.xio_npages = desiredpages;
2838 } else if (size > bp->b_bcount) {
2840 * We are growing the buffer, possibly in a
2841 * byte-granular fashion.
2849 * Step 1, bring in the VM pages from the object,
2850 * allocating them if necessary. We must clear
2851 * B_CACHE if these pages are not valid for the
2852 * range covered by the buffer.
2854 * critical section protection is required to protect
2855 * against interrupts unbusying and freeing pages
2856 * between our vm_page_lookup() and our
2857 * busycheck/wiring call.
2863 while (bp->b_xio.xio_npages < desiredpages) {
2867 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
2868 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2870 * note: must allocate system pages
2871 * since blocking here could intefere
2872 * with paging I/O, no matter which
2875 m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages);
2879 bp->b_flags &= ~B_CACHE;
2880 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2881 ++bp->b_xio.xio_npages;
2887 * We found a page. If we have to sleep on it,
2888 * retry because it might have gotten freed out
2891 * We can only test PG_BUSY here. Blocking on
2892 * m->busy might lead to a deadlock:
2894 * vm_fault->getpages->cluster_read->allocbuf
2898 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2902 * We have a good page. Should we wakeup the
2905 if ((curthread != pagethread) &&
2906 ((m->queue - m->pc) == PQ_CACHE) &&
2907 ((vmstats.v_free_count + vmstats.v_cache_count) <
2908 (vmstats.v_free_min + vmstats.v_cache_min))) {
2909 pagedaemon_wakeup();
2911 vm_page_flag_clear(m, PG_ZERO);
2913 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2914 ++bp->b_xio.xio_npages;
2919 * Step 2. We've loaded the pages into the buffer,
2920 * we have to figure out if we can still have B_CACHE
2921 * set. Note that B_CACHE is set according to the
2922 * byte-granular range ( bcount and size ), not the
2923 * aligned range ( newbsize ).
2925 * The VM test is against m->valid, which is DEV_BSIZE
2926 * aligned. Needless to say, the validity of the data
2927 * needs to also be DEV_BSIZE aligned. Note that this
2928 * fails with NFS if the server or some other client
2929 * extends the file's EOF. If our buffer is resized,
2930 * B_CACHE may remain set! XXX
2933 toff = bp->b_bcount;
2934 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
2936 while ((bp->b_flags & B_CACHE) && toff < size) {
2939 if (tinc > (size - toff))
2942 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
2950 bp->b_xio.xio_pages[pi]
2957 * Step 3, fixup the KVM pmap. Remember that
2958 * bp->b_data is relative to bp->b_loffset, but
2959 * bp->b_loffset may be offset into the first page.
2962 bp->b_data = (caddr_t)
2963 trunc_page((vm_offset_t)bp->b_data);
2965 (vm_offset_t)bp->b_data,
2966 bp->b_xio.xio_pages,
2967 bp->b_xio.xio_npages
2969 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2970 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
2973 if (bp->b_flags & B_DELWRI) {
2974 dirtybufspace += newbsize - bp->b_bufsize;
2975 if (bp->b_flags & B_HEAVY)
2976 dirtybufspacehw += newbsize - bp->b_bufsize;
2978 if (newbsize < bp->b_bufsize)
2980 bp->b_bufsize = newbsize; /* actual buffer allocation */
2981 bp->b_bcount = size; /* requested buffer size */
2988 * Wait for buffer I/O completion, returning error status. The buffer
2989 * is left locked on return. B_EINTR is converted into an EINTR error
2992 * NOTE! The original b_cmd is lost on return, since b_cmd will be
2993 * set to BUF_CMD_DONE.
2996 biowait(struct buf *bp)
2999 while (bp->b_cmd != BUF_CMD_DONE) {
3000 if (bp->b_cmd == BUF_CMD_READ)
3001 tsleep(bp, 0, "biord", 0);
3003 tsleep(bp, 0, "biowr", 0);
3006 if (bp->b_flags & B_EINTR) {
3007 bp->b_flags &= ~B_EINTR;
3010 if (bp->b_flags & B_ERROR) {
3011 return (bp->b_error ? bp->b_error : EIO);
3018 * This associates a tracking count with an I/O. vn_strategy() and
3019 * dev_dstrategy() do this automatically but there are a few cases
3020 * where a vnode or device layer is bypassed when a block translation
3021 * is cached. In such cases bio_start_transaction() may be called on
3022 * the bypassed layers so the system gets an I/O in progress indication
3023 * for those higher layers.
3026 bio_start_transaction(struct bio *bio, struct bio_track *track)
3028 bio->bio_track = track;
3029 atomic_add_int(&track->bk_active, 1);
3033 * Initiate I/O on a vnode.
3036 vn_strategy(struct vnode *vp, struct bio *bio)
3038 struct bio_track *track;
3040 KKASSERT(bio->bio_buf->b_cmd != BUF_CMD_DONE);
3041 if (bio->bio_buf->b_cmd == BUF_CMD_READ)
3042 track = &vp->v_track_read;
3044 track = &vp->v_track_write;
3045 bio->bio_track = track;
3046 atomic_add_int(&track->bk_active, 1);
3047 vop_strategy(*vp->v_ops, vp, bio);
3054 * Finish I/O on a buffer, optionally calling a completion function.
3055 * This is usually called from an interrupt so process blocking is
3058 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3059 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3060 * assuming B_INVAL is clear.
3062 * For the VMIO case, we set B_CACHE if the op was a read and no
3063 * read error occured, or if the op was a write. B_CACHE is never
3064 * set if the buffer is invalid or otherwise uncacheable.
3066 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3067 * initiator to leave B_INVAL set to brelse the buffer out of existance
3068 * in the biodone routine.
3071 biodone(struct bio *bio)
3073 struct buf *bp = bio->bio_buf;
3078 KASSERT(BUF_REFCNTNB(bp) > 0,
3079 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3080 KASSERT(bp->b_cmd != BUF_CMD_DONE,
3081 ("biodone: bp %p already done!", bp));
3083 runningbufwakeup(bp);
3086 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
3089 biodone_t *done_func;
3090 struct bio_track *track;
3093 * BIO tracking. Most but not all BIOs are tracked.
3095 if ((track = bio->bio_track) != NULL) {
3096 atomic_subtract_int(&track->bk_active, 1);
3097 if (track->bk_active < 0) {
3098 panic("biodone: bad active count bio %p\n",
3101 if (track->bk_waitflag) {
3102 track->bk_waitflag = 0;
3105 bio->bio_track = NULL;
3109 * A bio_done function terminates the loop. The function
3110 * will be responsible for any further chaining and/or
3111 * buffer management.
3113 * WARNING! The done function can deallocate the buffer!
3115 if ((done_func = bio->bio_done) != NULL) {
3116 bio->bio_done = NULL;
3121 bio = bio->bio_prev;
3125 bp->b_cmd = BUF_CMD_DONE;
3128 * Only reads and writes are processed past this point.
3130 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3137 * Warning: softupdates may re-dirty the buffer.
3139 if (LIST_FIRST(&bp->b_dep) != NULL)
3142 if (bp->b_flags & B_VMIO) {
3148 struct vnode *vp = bp->b_vp;
3152 #if defined(VFS_BIO_DEBUG)
3153 if (vp->v_auxrefs == 0)
3154 panic("biodone: zero vnode hold count");
3155 if ((vp->v_flag & VOBJBUF) == 0)
3156 panic("biodone: vnode is not setup for merged cache");
3159 foff = bp->b_loffset;
3160 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3161 KASSERT(obj != NULL, ("biodone: missing VM object"));
3163 #if defined(VFS_BIO_DEBUG)
3164 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3165 kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3166 obj->paging_in_progress, bp->b_xio.xio_npages);
3171 * Set B_CACHE if the op was a normal read and no error
3172 * occured. B_CACHE is set for writes in the b*write()
3175 iosize = bp->b_bcount - bp->b_resid;
3176 if (cmd == BUF_CMD_READ && (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3177 bp->b_flags |= B_CACHE;
3180 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3184 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3189 * cleanup bogus pages, restoring the originals. Since
3190 * the originals should still be wired, we don't have
3191 * to worry about interrupt/freeing races destroying
3192 * the VM object association.
3194 m = bp->b_xio.xio_pages[i];
3195 if (m == bogus_page) {
3197 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3199 panic("biodone: page disappeared");
3200 bp->b_xio.xio_pages[i] = m;
3201 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3202 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3204 #if defined(VFS_BIO_DEBUG)
3205 if (OFF_TO_IDX(foff) != m->pindex) {
3207 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3208 (unsigned long)foff, m->pindex);
3213 * In the write case, the valid and clean bits are
3214 * already changed correctly ( see bdwrite() ), so we
3215 * only need to do this here in the read case.
3217 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3218 vfs_page_set_valid(bp, foff, i, m);
3220 vm_page_flag_clear(m, PG_ZERO);
3223 * when debugging new filesystems or buffer I/O methods, this
3224 * is the most common error that pops up. if you see this, you
3225 * have not set the page busy flag correctly!!!
3228 kprintf("biodone: page busy < 0, "
3229 "pindex: %d, foff: 0x(%x,%x), "
3230 "resid: %d, index: %d\n",
3231 (int) m->pindex, (int)(foff >> 32),
3232 (int) foff & 0xffffffff, resid, i);
3233 if (!vn_isdisk(vp, NULL))
3234 kprintf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
3235 bp->b_vp->v_mount->mnt_stat.f_iosize,
3237 bp->b_flags, bp->b_xio.xio_npages);
3239 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3241 bp->b_flags, bp->b_xio.xio_npages);
3242 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3243 m->valid, m->dirty, m->wire_count);
3244 panic("biodone: page busy < 0");
3246 vm_page_io_finish(m);
3247 vm_object_pip_subtract(obj, 1);
3248 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3252 vm_object_pip_wakeupn(obj, 0);
3256 * For asynchronous completions, release the buffer now. The brelse
3257 * will do a wakeup there if necessary - so no need to do a wakeup
3258 * here in the async case. The sync case always needs to do a wakeup.
3261 if (bp->b_flags & B_ASYNC) {
3262 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3275 * This routine is called in lieu of iodone in the case of
3276 * incomplete I/O. This keeps the busy status for pages
3280 vfs_unbusy_pages(struct buf *bp)
3284 runningbufwakeup(bp);
3285 if (bp->b_flags & B_VMIO) {
3286 struct vnode *vp = bp->b_vp;
3291 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3292 vm_page_t m = bp->b_xio.xio_pages[i];
3295 * When restoring bogus changes the original pages
3296 * should still be wired, so we are in no danger of
3297 * losing the object association and do not need
3298 * critical section protection particularly.
3300 if (m == bogus_page) {
3301 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3303 panic("vfs_unbusy_pages: page missing");
3305 bp->b_xio.xio_pages[i] = m;
3306 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3307 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3309 vm_object_pip_subtract(obj, 1);
3310 vm_page_flag_clear(m, PG_ZERO);
3311 vm_page_io_finish(m);
3313 vm_object_pip_wakeupn(obj, 0);
3318 * vfs_page_set_valid:
3320 * Set the valid bits in a page based on the supplied offset. The
3321 * range is restricted to the buffer's size.
3323 * This routine is typically called after a read completes.
3326 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3328 vm_ooffset_t soff, eoff;
3331 * Start and end offsets in buffer. eoff - soff may not cross a
3332 * page boundry or cross the end of the buffer. The end of the
3333 * buffer, in this case, is our file EOF, not the allocation size
3337 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3338 if (eoff > bp->b_loffset + bp->b_bcount)
3339 eoff = bp->b_loffset + bp->b_bcount;
3342 * Set valid range. This is typically the entire buffer and thus the
3346 vm_page_set_validclean(
3348 (vm_offset_t) (soff & PAGE_MASK),
3349 (vm_offset_t) (eoff - soff)
3357 * This routine is called before a device strategy routine.
3358 * It is used to tell the VM system that paging I/O is in
3359 * progress, and treat the pages associated with the buffer
3360 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3361 * flag is handled to make sure that the object doesn't become
3364 * Since I/O has not been initiated yet, certain buffer flags
3365 * such as B_ERROR or B_INVAL may be in an inconsistant state
3366 * and should be ignored.
3369 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3372 struct lwp *lp = curthread->td_lwp;
3375 * The buffer's I/O command must already be set. If reading,
3376 * B_CACHE must be 0 (double check against callers only doing
3377 * I/O when B_CACHE is 0).
3379 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3380 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3382 if (bp->b_flags & B_VMIO) {
3387 foff = bp->b_loffset;
3388 KASSERT(bp->b_loffset != NOOFFSET,
3389 ("vfs_busy_pages: no buffer offset"));
3393 * Loop until none of the pages are busy.
3396 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3397 vm_page_t m = bp->b_xio.xio_pages[i];
3399 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3404 * Setup for I/O, soft-busy the page right now because
3405 * the next loop may block.
3407 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3408 vm_page_t m = bp->b_xio.xio_pages[i];
3410 vm_page_flag_clear(m, PG_ZERO);
3411 if ((bp->b_flags & B_CLUSTER) == 0) {
3412 vm_object_pip_add(obj, 1);
3413 vm_page_io_start(m);
3418 * Adjust protections for I/O and do bogus-page mapping.
3419 * Assume that vm_page_protect() can block (it can block
3420 * if VM_PROT_NONE, don't take any chances regardless).
3423 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3424 vm_page_t m = bp->b_xio.xio_pages[i];
3427 * When readying a vnode-backed buffer for a write
3428 * we must zero-fill any invalid portions of the
3431 * When readying a vnode-backed buffer for a read
3432 * we must replace any dirty pages with a bogus
3433 * page so we do not destroy dirty data when
3434 * filling in gaps. Dirty pages might not
3435 * necessarily be marked dirty yet, so use m->valid
3436 * as a reasonable test.
3438 * Bogus page replacement is, uh, bogus. We need
3439 * to find a better way.
3441 if (bp->b_cmd == BUF_CMD_WRITE) {
3442 vm_page_protect(m, VM_PROT_READ);
3443 vfs_page_set_valid(bp, foff, i, m);
3444 } else if (m->valid == VM_PAGE_BITS_ALL) {
3445 bp->b_xio.xio_pages[i] = bogus_page;
3448 vm_page_protect(m, VM_PROT_NONE);
3450 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3453 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3454 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3458 * This is the easiest place to put the process accounting for the I/O
3462 if (bp->b_cmd == BUF_CMD_READ)
3463 lp->lwp_ru.ru_inblock++;
3465 lp->lwp_ru.ru_oublock++;
3472 * Tell the VM system that the pages associated with this buffer
3473 * are clean. This is used for delayed writes where the data is
3474 * going to go to disk eventually without additional VM intevention.
3476 * Note that while we only really need to clean through to b_bcount, we
3477 * just go ahead and clean through to b_bufsize.
3480 vfs_clean_pages(struct buf *bp)
3484 if (bp->b_flags & B_VMIO) {
3487 foff = bp->b_loffset;
3488 KASSERT(foff != NOOFFSET, ("vfs_clean_pages: no buffer offset"));
3489 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3490 vm_page_t m = bp->b_xio.xio_pages[i];
3491 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3492 vm_ooffset_t eoff = noff;
3494 if (eoff > bp->b_loffset + bp->b_bufsize)
3495 eoff = bp->b_loffset + bp->b_bufsize;
3496 vfs_page_set_valid(bp, foff, i, m);
3497 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3504 * vfs_bio_set_validclean:
3506 * Set the range within the buffer to valid and clean. The range is
3507 * relative to the beginning of the buffer, b_loffset. Note that
3508 * b_loffset itself may be offset from the beginning of the first page.
3512 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3514 if (bp->b_flags & B_VMIO) {
3519 * Fixup base to be relative to beginning of first page.
3520 * Set initial n to be the maximum number of bytes in the
3521 * first page that can be validated.
3524 base += (bp->b_loffset & PAGE_MASK);
3525 n = PAGE_SIZE - (base & PAGE_MASK);
3527 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3528 vm_page_t m = bp->b_xio.xio_pages[i];
3533 vm_page_set_validclean(m, base & PAGE_MASK, n);
3544 * Clear a buffer. This routine essentially fakes an I/O, so we need
3545 * to clear B_ERROR and B_INVAL.
3547 * Note that while we only theoretically need to clear through b_bcount,
3548 * we go ahead and clear through b_bufsize.
3552 vfs_bio_clrbuf(struct buf *bp)
3556 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3557 bp->b_flags &= ~(B_INVAL|B_ERROR);
3558 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3559 (bp->b_loffset & PAGE_MASK) == 0) {
3560 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3561 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3565 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3566 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3567 bzero(bp->b_data, bp->b_bufsize);
3568 bp->b_xio.xio_pages[0]->valid |= mask;
3573 ea = sa = bp->b_data;
3574 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3575 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3576 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3577 ea = (caddr_t)(vm_offset_t)ulmin(
3578 (u_long)(vm_offset_t)ea,
3579 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3580 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3581 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3583 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3584 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3588 for (; sa < ea; sa += DEV_BSIZE, j++) {
3589 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3590 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3591 bzero(sa, DEV_BSIZE);
3594 bp->b_xio.xio_pages[i]->valid |= mask;
3595 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3604 * vm_hold_load_pages:
3606 * Load pages into the buffer's address space. The pages are
3607 * allocated from the kernel object in order to reduce interference
3608 * with the any VM paging I/O activity. The range of loaded
3609 * pages will be wired.
3611 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3612 * retrieve the full range (to - from) of pages.
3616 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3622 to = round_page(to);
3623 from = round_page(from);
3624 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3629 * Note: must allocate system pages since blocking here
3630 * could intefere with paging I/O, no matter which
3633 p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT,
3634 (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
3637 p->valid = VM_PAGE_BITS_ALL;
3638 vm_page_flag_clear(p, PG_ZERO);
3639 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3640 bp->b_xio.xio_pages[index] = p;
3647 bp->b_xio.xio_npages = index;
3651 * Allocate pages for a buffer cache buffer.
3653 * Under extremely severe memory conditions even allocating out of the
3654 * system reserve can fail. If this occurs we must allocate out of the
3655 * interrupt reserve to avoid a deadlock with the pageout daemon.
3657 * The pageout daemon can run (putpages -> VOP_WRITE -> getblk -> allocbuf).
3658 * If the buffer cache's vm_page_alloc() fails a vm_wait() can deadlock
3659 * against the pageout daemon if pages are not freed from other sources.
3663 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit)
3668 * Try a normal allocation, allow use of system reserve.
3670 p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3675 * The normal allocation failed and we clearly have a page
3676 * deficit. Try to reclaim some clean VM pages directly
3677 * from the buffer cache.
3679 vm_pageout_deficit += deficit;
3683 * We may have blocked, the caller will know what to do if the
3686 if (vm_page_lookup(obj, pg))
3690 * Allocate and allow use of the interrupt reserve.
3692 * If after all that we still can't allocate a VM page we are
3693 * in real trouble, but we slog on anyway hoping that the system
3696 p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
3697 VM_ALLOC_INTERRUPT);
3699 kprintf("bio_page_alloc: WARNING emergency page "
3701 if (vm_page_count_severe())
3704 kprintf("bio_page_alloc: WARNING emergency page "
3705 "allocation failed\n");
3712 * vm_hold_free_pages:
3714 * Return pages associated with the buffer back to the VM system.
3716 * The range of pages underlying the buffer's address space will
3717 * be unmapped and un-wired.
3720 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3724 int index, newnpages;
3726 from = round_page(from);
3727 to = round_page(to);
3728 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3730 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3731 p = bp->b_xio.xio_pages[index];
3732 if (p && (index < bp->b_xio.xio_npages)) {
3734 kprintf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3735 bp->b_bio2.bio_offset, bp->b_loffset);
3737 bp->b_xio.xio_pages[index] = NULL;
3740 vm_page_unwire(p, 0);
3744 bp->b_xio.xio_npages = newnpages;
3750 * Map a user buffer into KVM via a pbuf. On return the buffer's
3751 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3755 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
3766 * bp had better have a command and it better be a pbuf.
3768 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3769 KKASSERT(bp->b_flags & B_PAGING);
3775 * Map the user data into KVM. Mappings have to be page-aligned.
3777 addr = (caddr_t)trunc_page((vm_offset_t)udata);
3780 vmprot = VM_PROT_READ;
3781 if (bp->b_cmd == BUF_CMD_READ)
3782 vmprot |= VM_PROT_WRITE;
3784 while (addr < udata + bytes) {
3786 * Do the vm_fault if needed; do the copy-on-write thing
3787 * when reading stuff off device into memory.
3789 * vm_fault_page*() returns a held VM page.
3791 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
3792 va = trunc_page(va);
3794 m = vm_fault_page_quick(va, vmprot, &error);
3796 for (i = 0; i < pidx; ++i) {
3797 vm_page_unhold(bp->b_xio.xio_pages[i]);
3798 bp->b_xio.xio_pages[i] = NULL;
3802 bp->b_xio.xio_pages[pidx] = m;
3808 * Map the page array and set the buffer fields to point to
3809 * the mapped data buffer.
3811 if (pidx > btoc(MAXPHYS))
3812 panic("vmapbuf: mapped more than MAXPHYS");
3813 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
3815 bp->b_xio.xio_npages = pidx;
3816 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
3817 bp->b_bcount = bytes;
3818 bp->b_bufsize = bytes;
3825 * Free the io map PTEs associated with this IO operation.
3826 * We also invalidate the TLB entries and restore the original b_addr.
3829 vunmapbuf(struct buf *bp)
3834 KKASSERT(bp->b_flags & B_PAGING);
3836 npages = bp->b_xio.xio_npages;
3837 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3838 for (pidx = 0; pidx < npages; ++pidx) {
3839 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
3840 bp->b_xio.xio_pages[pidx] = NULL;
3842 bp->b_xio.xio_npages = 0;
3843 bp->b_data = bp->b_kvabase;
3847 * Scan all buffers in the system and issue the callback.
3850 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
3856 for (n = 0; n < nbuf; ++n) {
3857 if ((error = callback(&buf[n], info)) < 0) {
3867 * print out statistics from the current status of the buffer pool
3868 * this can be toggeled by the system control option debug.syncprt
3877 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3878 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3880 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3882 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3885 TAILQ_FOREACH(bp, dp, b_freelist) {
3886 counts[bp->b_bufsize/PAGE_SIZE]++;
3890 kprintf("%s: total-%d", bname[i], count);
3891 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3893 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
3901 DB_SHOW_COMMAND(buffer, db_show_buffer)
3904 struct buf *bp = (struct buf *)addr;
3907 db_printf("usage: show buffer <addr>\n");
3911 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3912 db_printf("b_cmd = %d\n", bp->b_cmd);
3913 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3914 "b_resid = %d\n, b_data = %p, "
3915 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3916 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3917 bp->b_data, bp->b_bio2.bio_offset, (bp->b_bio2.bio_next ? bp->b_bio2.bio_next->bio_offset : (off_t)-1));
3918 if (bp->b_xio.xio_npages) {
3920 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3921 bp->b_xio.xio_npages);
3922 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3924 m = bp->b_xio.xio_pages[i];
3925 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3926 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3927 if ((i + 1) < bp->b_xio.xio_npages)