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.59 2006/03/24 18:35:33 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 <vm/vm_page2.h>
64 #define BUFFER_QUEUES 6
66 BQUEUE_NONE, /* not on any queue */
67 BQUEUE_LOCKED, /* locked buffers */
68 BQUEUE_CLEAN, /* non-B_DELWRI buffers */
69 BQUEUE_DIRTY, /* B_DELWRI buffers */
70 BQUEUE_EMPTYKVA, /* empty buffer headers with KVA assignment */
71 BQUEUE_EMPTY /* empty buffer headers */
73 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
75 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
77 struct bio_ops bioops; /* I/O operation notification */
79 struct buf *buf; /* buffer header pool */
81 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
83 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
85 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
86 int pageno, vm_page_t m);
87 static void vfs_clean_pages(struct buf * bp);
88 static void vfs_setdirty(struct buf *bp);
89 static void vfs_vmio_release(struct buf *bp);
90 static int flushbufqueues(void);
92 static int bd_request;
94 static void buf_daemon (void);
96 * bogus page -- for I/O to/from partially complete buffers
97 * this is a temporary solution to the problem, but it is not
98 * really that bad. it would be better to split the buffer
99 * for input in the case of buffers partially already in memory,
100 * but the code is intricate enough already.
102 vm_page_t bogus_page;
103 int vmiodirenable = TRUE;
106 static int bufspace, maxbufspace,
107 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
108 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
109 static int needsbuffer;
110 static int lorunningspace, hirunningspace, runningbufreq;
111 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
112 static int numfreebuffers, lofreebuffers, hifreebuffers;
113 static int getnewbufcalls;
114 static int getnewbufrestarts;
117 * Sysctls for operational control of the buffer cache.
119 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
120 "Number of dirty buffers to flush before bufdaemon becomes inactive");
121 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
122 "High watermark used to trigger explicit flushing of dirty buffers");
123 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
124 "Low watermark for special reserve in low-memory situations");
125 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
126 "High watermark for special reserve in low-memory situations");
127 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
128 "Minimum amount of buffer space required for active I/O");
129 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
130 "Maximum amount of buffer space to usable for active I/O");
131 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW, &vmiodirenable, 0,
132 "Use the VM system for performing directory writes");
134 * Sysctls determining current state of the buffer cache.
136 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
137 "Pending number of dirty buffers");
138 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
139 "Number of free buffers on the buffer cache free list");
140 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
141 "I/O bytes currently in progress due to asynchronous writes");
142 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
143 "Hard limit on maximum amount of memory usable for buffer space");
144 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
145 "Soft limit on maximum amount of memory usable for buffer space");
146 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
147 "Minimum amount of memory to reserve for system buffer space");
148 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
149 "Amount of memory available for buffers");
150 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
151 0, "Maximum amount of memory reserved for buffers using malloc");
152 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
153 "Amount of memory left for buffers using malloc-scheme");
154 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
155 "New buffer header acquisition requests");
156 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
157 0, "New buffer header acquisition restarts");
158 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
159 "Buffer acquisition restarts due to fragmented buffer map");
160 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
161 "Amount of time KVA space was deallocated in an arbitrary buffer");
162 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
163 "Amount of time buffer re-use operations were successful");
164 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
165 "sizeof(struct buf)");
167 char *buf_wmesg = BUF_WMESG;
169 extern int vm_swap_size;
171 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
172 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
173 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
174 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
179 * If someone is blocked due to there being too many dirty buffers,
180 * and numdirtybuffers is now reasonable, wake them up.
184 numdirtywakeup(int level)
186 if (numdirtybuffers <= level) {
187 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
188 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
189 wakeup(&needsbuffer);
197 * Called when buffer space is potentially available for recovery.
198 * getnewbuf() will block on this flag when it is unable to free
199 * sufficient buffer space. Buffer space becomes recoverable when
200 * bp's get placed back in the queues.
207 * If someone is waiting for BUF space, wake them up. Even
208 * though we haven't freed the kva space yet, the waiting
209 * process will be able to now.
211 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
212 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
213 wakeup(&needsbuffer);
220 * Accounting for I/O in progress.
224 runningbufwakeup(struct buf *bp)
226 if (bp->b_runningbufspace) {
227 runningbufspace -= bp->b_runningbufspace;
228 bp->b_runningbufspace = 0;
229 if (runningbufreq && runningbufspace <= lorunningspace) {
231 wakeup(&runningbufreq);
239 * Called when a buffer has been added to one of the free queues to
240 * account for the buffer and to wakeup anyone waiting for free buffers.
241 * This typically occurs when large amounts of metadata are being handled
242 * by the buffer cache ( else buffer space runs out first, usually ).
250 needsbuffer &= ~VFS_BIO_NEED_ANY;
251 if (numfreebuffers >= hifreebuffers)
252 needsbuffer &= ~VFS_BIO_NEED_FREE;
253 wakeup(&needsbuffer);
258 * waitrunningbufspace()
260 * runningbufspace is a measure of the amount of I/O currently
261 * running. This routine is used in async-write situations to
262 * prevent creating huge backups of pending writes to a device.
263 * Only asynchronous writes are governed by this function.
265 * Reads will adjust runningbufspace, but will not block based on it.
266 * The read load has a side effect of reducing the allowed write load.
268 * This does NOT turn an async write into a sync write. It waits
269 * for earlier writes to complete and generally returns before the
270 * caller's write has reached the device.
273 waitrunningbufspace(void)
275 if (runningbufspace > hirunningspace) {
277 while (runningbufspace > hirunningspace) {
279 tsleep(&runningbufreq, 0, "wdrain", 0);
286 * vfs_buf_test_cache:
288 * Called when a buffer is extended. This function clears the B_CACHE
289 * bit if the newly extended portion of the buffer does not contain
294 vfs_buf_test_cache(struct buf *bp,
295 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
298 if (bp->b_flags & B_CACHE) {
299 int base = (foff + off) & PAGE_MASK;
300 if (vm_page_is_valid(m, base, size) == 0)
301 bp->b_flags &= ~B_CACHE;
308 * Wake up the buffer daemon if the number of outstanding dirty buffers
309 * is above specified threshold 'dirtybuflevel'.
311 * The buffer daemon is explicitly woken up when (a) the pending number
312 * of dirty buffers exceeds the recovery and stall mid-point value,
313 * (b) during bwillwrite() or (c) buf freelist was exhausted.
317 bd_wakeup(int dirtybuflevel)
319 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
328 * Speed up the buffer cache flushing process.
341 * Load time initialisation of the buffer cache, called from machine
342 * dependant initialization code.
348 vm_offset_t bogus_offset;
351 /* next, make a null set of free lists */
352 for (i = 0; i < BUFFER_QUEUES; i++)
353 TAILQ_INIT(&bufqueues[i]);
355 /* finally, initialize each buffer header and stick on empty q */
356 for (i = 0; i < nbuf; i++) {
358 bzero(bp, sizeof *bp);
359 bp->b_flags = B_INVAL; /* we're just an empty header */
360 bp->b_qindex = BQUEUE_EMPTY;
362 xio_init(&bp->b_xio);
363 LIST_INIT(&bp->b_dep);
365 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
369 * maxbufspace is the absolute maximum amount of buffer space we are
370 * allowed to reserve in KVM and in real terms. The absolute maximum
371 * is nominally used by buf_daemon. hibufspace is the nominal maximum
372 * used by most other processes. The differential is required to
373 * ensure that buf_daemon is able to run when other processes might
374 * be blocked waiting for buffer space.
376 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
377 * this may result in KVM fragmentation which is not handled optimally
380 maxbufspace = nbuf * BKVASIZE;
381 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
382 lobufspace = hibufspace - MAXBSIZE;
384 lorunningspace = 512 * 1024;
385 hirunningspace = 1024 * 1024;
388 * Limit the amount of malloc memory since it is wired permanently into
389 * the kernel space. Even though this is accounted for in the buffer
390 * allocation, we don't want the malloced region to grow uncontrolled.
391 * The malloc scheme improves memory utilization significantly on average
392 * (small) directories.
394 maxbufmallocspace = hibufspace / 20;
397 * Reduce the chance of a deadlock occuring by limiting the number
398 * of delayed-write dirty buffers we allow to stack up.
400 hidirtybuffers = nbuf / 4 + 20;
403 * To support extreme low-memory systems, make sure hidirtybuffers cannot
404 * eat up all available buffer space. This occurs when our minimum cannot
405 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
406 * BKVASIZE'd (8K) buffers.
408 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
409 hidirtybuffers >>= 1;
411 lodirtybuffers = hidirtybuffers / 2;
414 * Try to keep the number of free buffers in the specified range,
415 * and give special processes (e.g. like buf_daemon) access to an
418 lofreebuffers = nbuf / 18 + 5;
419 hifreebuffers = 2 * lofreebuffers;
420 numfreebuffers = nbuf;
423 * Maximum number of async ops initiated per buf_daemon loop. This is
424 * somewhat of a hack at the moment, we really need to limit ourselves
425 * based on the number of bytes of I/O in-transit that were initiated
429 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
430 bogus_page = vm_page_alloc(kernel_object,
431 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
433 vmstats.v_wire_count++;
438 * Initialize the embedded bio structures
441 initbufbio(struct buf *bp)
443 bp->b_bio1.bio_buf = bp;
444 bp->b_bio1.bio_prev = NULL;
445 bp->b_bio1.bio_offset = NOOFFSET;
446 bp->b_bio1.bio_next = &bp->b_bio2;
447 bp->b_bio1.bio_done = NULL;
449 bp->b_bio2.bio_buf = bp;
450 bp->b_bio2.bio_prev = &bp->b_bio1;
451 bp->b_bio2.bio_offset = NOOFFSET;
452 bp->b_bio2.bio_next = NULL;
453 bp->b_bio2.bio_done = NULL;
457 * Reinitialize the embedded bio structures as well as any additional
458 * translation cache layers.
461 reinitbufbio(struct buf *bp)
465 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
466 bio->bio_done = NULL;
467 bio->bio_offset = NOOFFSET;
472 * Push another BIO layer onto an existing BIO and return it. The new
473 * BIO layer may already exist, holding cached translation data.
476 push_bio(struct bio *bio)
480 if ((nbio = bio->bio_next) == NULL) {
481 int index = bio - &bio->bio_buf->b_bio_array[0];
482 if (index >= NBUF_BIO) {
483 panic("push_bio: too many layers bp %p\n",
486 nbio = &bio->bio_buf->b_bio_array[index + 1];
487 bio->bio_next = nbio;
488 nbio->bio_prev = bio;
489 nbio->bio_buf = bio->bio_buf;
490 nbio->bio_offset = NOOFFSET;
491 nbio->bio_done = NULL;
492 nbio->bio_next = NULL;
494 KKASSERT(nbio->bio_done == NULL);
499 pop_bio(struct bio *bio)
505 clearbiocache(struct bio *bio)
508 bio->bio_offset = NOOFFSET;
516 * Free the KVA allocation for buffer 'bp'.
518 * Must be called from a critical section as this is the only locking for
521 * Since this call frees up buffer space, we call bufspacewakeup().
524 bfreekva(struct buf * bp)
530 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
531 vm_map_lock(buffer_map);
532 bufspace -= bp->b_kvasize;
533 vm_map_delete(buffer_map,
534 (vm_offset_t) bp->b_kvabase,
535 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
538 vm_map_unlock(buffer_map);
539 vm_map_entry_release(count);
548 * Remove the buffer from the appropriate free list.
551 bremfree(struct buf * bp)
556 old_qindex = bp->b_qindex;
558 if (bp->b_qindex != BQUEUE_NONE) {
559 KASSERT(BUF_REFCNTNB(bp) == 1,
560 ("bremfree: bp %p not locked",bp));
561 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
562 bp->b_qindex = BQUEUE_NONE;
564 if (BUF_REFCNTNB(bp) <= 1)
565 panic("bremfree: removing a buffer not on a queue");
569 * Fixup numfreebuffers count. If the buffer is invalid or not
570 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
571 * the buffer was free and we must decrement numfreebuffers.
573 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
578 case BQUEUE_EMPTYKVA:
592 * Get a buffer with the specified data. Look in the cache first. We
593 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
594 * is set, the buffer is valid and we do not have to do anything ( see
598 bread(struct vnode * vp, off_t loffset, int size, struct buf ** bpp)
602 bp = getblk(vp, loffset, size, 0, 0);
605 /* if not found in cache, do some I/O */
606 if ((bp->b_flags & B_CACHE) == 0) {
607 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
608 bp->b_flags |= B_READ;
609 bp->b_flags &= ~(B_ERROR | B_INVAL);
610 vfs_busy_pages(bp, 0);
611 vn_strategy(vp, &bp->b_bio1);
612 return (biowait(bp));
620 * Operates like bread, but also starts asynchronous I/O on
621 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
622 * to initiating I/O . If B_CACHE is set, the buffer is valid
623 * and we do not have to do anything.
626 breadn(struct vnode * vp, off_t loffset, int size, off_t *raoffset,
627 int *rabsize, int cnt, struct buf ** bpp)
629 struct buf *bp, *rabp;
631 int rv = 0, readwait = 0;
633 *bpp = bp = getblk(vp, loffset, size, 0, 0);
635 /* if not found in cache, do some I/O */
636 if ((bp->b_flags & B_CACHE) == 0) {
637 bp->b_flags |= B_READ;
638 bp->b_flags &= ~(B_ERROR | B_INVAL);
639 vfs_busy_pages(bp, 0);
640 vn_strategy(vp, &bp->b_bio1);
644 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
645 if (inmem(vp, *raoffset))
647 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
649 if ((rabp->b_flags & B_CACHE) == 0) {
650 rabp->b_flags |= B_READ | B_ASYNC;
651 rabp->b_flags &= ~(B_ERROR | B_INVAL);
652 vfs_busy_pages(rabp, 0);
654 vn_strategy(vp, &rabp->b_bio1);
669 * Write, release buffer on completion. (Done by iodone
670 * if async). Do not bother writing anything if the buffer
673 * Note that we set B_CACHE here, indicating that buffer is
674 * fully valid and thus cacheable. This is true even of NFS
675 * now so we set it generally. This could be set either here
676 * or in biodone() since the I/O is synchronous. We put it
680 bwrite(struct buf * bp)
684 if (bp->b_flags & B_INVAL) {
689 oldflags = bp->b_flags;
691 if (BUF_REFCNTNB(bp) == 0)
692 panic("bwrite: buffer is not busy???");
695 * If a background write is already in progress, delay
696 * writing this block if it is asynchronous. Otherwise
697 * wait for the background write to complete.
699 if (bp->b_xflags & BX_BKGRDINPROG) {
700 if (bp->b_flags & B_ASYNC) {
705 bp->b_xflags |= BX_BKGRDWAIT;
706 tsleep(&bp->b_xflags, 0, "biord", 0);
707 if (bp->b_xflags & BX_BKGRDINPROG)
708 panic("bwrite: still writing");
711 /* Mark the buffer clean */
714 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
715 bp->b_flags |= B_CACHE;
717 vfs_busy_pages(bp, 1);
720 * Normal bwrites pipeline writes
722 bp->b_runningbufspace = bp->b_bufsize;
723 runningbufspace += bp->b_runningbufspace;
726 if (oldflags & B_ASYNC)
728 vn_strategy(bp->b_vp, &bp->b_bio1);
730 if ((oldflags & B_ASYNC) == 0) {
731 int rtval = biowait(bp);
734 } else if ((oldflags & B_NOWDRAIN) == 0) {
736 * don't allow the async write to saturate the I/O
737 * system. Deadlocks can occur only if a device strategy
738 * routine (like in VN) turns around and issues another
739 * high-level write, in which case B_NOWDRAIN is expected
740 * to be set. Otherwise we will not deadlock here because
741 * we are blocking waiting for I/O that is already in-progress
744 waitrunningbufspace();
753 * Delayed write. (Buffer is marked dirty). Do not bother writing
754 * anything if the buffer is marked invalid.
756 * Note that since the buffer must be completely valid, we can safely
757 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
758 * biodone() in order to prevent getblk from writing the buffer
762 bdwrite(struct buf *bp)
764 if (BUF_REFCNTNB(bp) == 0)
765 panic("bdwrite: buffer is not busy");
767 if (bp->b_flags & B_INVAL) {
774 * Set B_CACHE, indicating that the buffer is fully valid. This is
775 * true even of NFS now.
777 bp->b_flags |= B_CACHE;
780 * This bmap keeps the system from needing to do the bmap later,
781 * perhaps when the system is attempting to do a sync. Since it
782 * is likely that the indirect block -- or whatever other datastructure
783 * that the filesystem needs is still in memory now, it is a good
784 * thing to do this. Note also, that if the pageout daemon is
785 * requesting a sync -- there might not be enough memory to do
786 * the bmap then... So, this is important to do.
788 if (bp->b_bio2.bio_offset == NOOFFSET) {
789 VOP_BMAP(bp->b_vp, bp->b_loffset, NULL, &bp->b_bio2.bio_offset,
794 * Set the *dirty* buffer range based upon the VM system dirty pages.
799 * We need to do this here to satisfy the vnode_pager and the
800 * pageout daemon, so that it thinks that the pages have been
801 * "cleaned". Note that since the pages are in a delayed write
802 * buffer -- the VFS layer "will" see that the pages get written
803 * out on the next sync, or perhaps the cluster will be completed.
809 * Wakeup the buffer flushing daemon if we have a lot of dirty
810 * buffers (midpoint between our recovery point and our stall
813 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
816 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
817 * due to the softdep code.
824 * Turn buffer into delayed write request. We must clear B_READ and
825 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
826 * itself to properly update it in the dirty/clean lists. We mark it
827 * B_DONE to ensure that any asynchronization of the buffer properly
828 * clears B_DONE ( else a panic will occur later ).
830 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
831 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
832 * should only be called if the buffer is known-good.
834 * Since the buffer is not on a queue, we do not update the numfreebuffers
837 * Must be called from a critical section.
838 * The buffer must be on BQUEUE_NONE.
841 bdirty(struct buf *bp)
843 KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
844 bp->b_flags &= ~(B_READ|B_RELBUF);
846 if ((bp->b_flags & B_DELWRI) == 0) {
847 bp->b_flags |= B_DONE | B_DELWRI;
850 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
857 * Clear B_DELWRI for buffer.
859 * Since the buffer is not on a queue, we do not update the numfreebuffers
862 * Must be called from a critical section.
864 * The buffer is typically on BQUEUE_NONE but there is one case in
865 * brelse() that calls this function after placing the buffer on
870 bundirty(struct buf *bp)
872 if (bp->b_flags & B_DELWRI) {
873 bp->b_flags &= ~B_DELWRI;
876 numdirtywakeup(lodirtybuffers);
879 * Since it is now being written, we can clear its deferred write flag.
881 bp->b_flags &= ~B_DEFERRED;
887 * Asynchronous write. Start output on a buffer, but do not wait for
888 * it to complete. The buffer is released when the output completes.
890 * bwrite() ( or the VOP routine anyway ) is responsible for handling
891 * B_INVAL buffers. Not us.
894 bawrite(struct buf * bp)
896 bp->b_flags |= B_ASYNC;
897 (void) VOP_BWRITE(bp->b_vp, bp);
903 * Ordered write. Start output on a buffer, and flag it so that the
904 * device will write it in the order it was queued. The buffer is
905 * released when the output completes. bwrite() ( or the VOP routine
906 * anyway ) is responsible for handling B_INVAL buffers.
909 bowrite(struct buf * bp)
911 bp->b_flags |= B_ORDERED | B_ASYNC;
912 return (VOP_BWRITE(bp->b_vp, bp));
918 * Called prior to the locking of any vnodes when we are expecting to
919 * write. We do not want to starve the buffer cache with too many
920 * dirty buffers so we block here. By blocking prior to the locking
921 * of any vnodes we attempt to avoid the situation where a locked vnode
922 * prevents the various system daemons from flushing related buffers.
928 if (numdirtybuffers >= hidirtybuffers) {
930 while (numdirtybuffers >= hidirtybuffers) {
932 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
933 tsleep(&needsbuffer, 0, "flswai", 0);
940 * buf_dirty_count_severe:
942 * Return true if we have too many dirty buffers.
945 buf_dirty_count_severe(void)
947 return(numdirtybuffers >= hidirtybuffers);
953 * Release a busy buffer and, if requested, free its resources. The
954 * buffer will be stashed in the appropriate bufqueue[] allowing it
955 * to be accessed later as a cache entity or reused for other purposes.
958 brelse(struct buf * bp)
961 int saved_flags = bp->b_flags;
964 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
968 if (bp->b_flags & B_LOCKED)
969 bp->b_flags &= ~B_ERROR;
971 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
973 * Failed write, redirty. Must clear B_ERROR to prevent
974 * pages from being scrapped. If B_INVAL is set then
975 * this case is not run and the next case is run to
976 * destroy the buffer. B_INVAL can occur if the buffer
977 * is outside the range supported by the underlying device.
979 bp->b_flags &= ~B_ERROR;
981 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
982 (bp->b_bufsize <= 0)) {
984 * Either a failed I/O or we were asked to free or not
987 bp->b_flags |= B_INVAL;
988 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
989 (*bioops.io_deallocate)(bp);
990 if (bp->b_flags & B_DELWRI) {
992 numdirtywakeup(lodirtybuffers);
994 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
998 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
999 * is called with B_DELWRI set, the underlying pages may wind up
1000 * getting freed causing a previous write (bdwrite()) to get 'lost'
1001 * because pages associated with a B_DELWRI bp are marked clean.
1003 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1004 * if B_DELWRI is set.
1006 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1007 * on pages to return pages to the VM page queues.
1009 if (bp->b_flags & B_DELWRI)
1010 bp->b_flags &= ~B_RELBUF;
1011 else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1012 bp->b_flags |= B_RELBUF;
1015 * At this point destroying the buffer is governed by the B_INVAL
1016 * or B_RELBUF flags.
1020 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1021 * constituted, not even NFS buffers now. Two flags effect this. If
1022 * B_INVAL, the struct buf is invalidated but the VM object is kept
1023 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1025 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1026 * invalidated. B_ERROR cannot be set for a failed write unless the
1027 * buffer is also B_INVAL because it hits the re-dirtying code above.
1029 * Normally we can do this whether a buffer is B_DELWRI or not. If
1030 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1031 * the commit state and we cannot afford to lose the buffer. If the
1032 * buffer has a background write in progress, we need to keep it
1033 * around to prevent it from being reconstituted and starting a second
1036 if ((bp->b_flags & B_VMIO)
1037 && !(bp->b_vp->v_tag == VT_NFS &&
1038 !vn_isdisk(bp->b_vp, NULL) &&
1039 (bp->b_flags & B_DELWRI))
1042 * Rundown for VMIO buffers which are not dirty NFS buffers.
1054 * Get the base offset and length of the buffer. Note that
1055 * in the VMIO case if the buffer block size is not
1056 * page-aligned then b_data pointer may not be page-aligned.
1057 * But our b_xio.xio_pages array *IS* page aligned.
1059 * block sizes less then DEV_BSIZE (usually 512) are not
1060 * supported due to the page granularity bits (m->valid,
1061 * m->dirty, etc...).
1063 * See man buf(9) for more information
1066 resid = bp->b_bufsize;
1067 foff = bp->b_loffset;
1069 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1070 m = bp->b_xio.xio_pages[i];
1071 vm_page_flag_clear(m, PG_ZERO);
1073 * If we hit a bogus page, fixup *all* of them
1074 * now. Note that we left these pages wired
1075 * when we removed them so they had better exist,
1076 * and they cannot be ripped out from under us so
1077 * no critical section protection is necessary.
1079 if (m == bogus_page) {
1080 VOP_GETVOBJECT(vp, &obj);
1081 poff = OFF_TO_IDX(bp->b_loffset);
1083 for (j = i; j < bp->b_xio.xio_npages; j++) {
1086 mtmp = bp->b_xio.xio_pages[j];
1087 if (mtmp == bogus_page) {
1088 mtmp = vm_page_lookup(obj, poff + j);
1090 panic("brelse: page missing");
1092 bp->b_xio.xio_pages[j] = mtmp;
1096 if ((bp->b_flags & B_INVAL) == 0) {
1097 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1098 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1100 m = bp->b_xio.xio_pages[i];
1104 * Invalidate the backing store if B_NOCACHE is set
1105 * (e.g. used with vinvalbuf()). If this is NFS
1106 * we impose a requirement that the block size be
1107 * a multiple of PAGE_SIZE and create a temporary
1108 * hack to basically invalidate the whole page. The
1109 * problem is that NFS uses really odd buffer sizes
1110 * especially when tracking piecemeal writes and
1111 * it also vinvalbuf()'s a lot, which would result
1112 * in only partial page validation and invalidation
1113 * here. If the file page is mmap()'d, however,
1114 * all the valid bits get set so after we invalidate
1115 * here we would end up with weird m->valid values
1116 * like 0xfc. nfs_getpages() can't handle this so
1117 * we clear all the valid bits for the NFS case
1118 * instead of just some of them.
1120 * The real bug is the VM system having to set m->valid
1121 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1122 * itself is an artifact of the whole 512-byte
1123 * granular mess that exists to support odd block
1124 * sizes and UFS meta-data block sizes (e.g. 6144).
1125 * A complete rewrite is required.
1127 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1128 int poffset = foff & PAGE_MASK;
1131 presid = PAGE_SIZE - poffset;
1132 if (bp->b_vp->v_tag == VT_NFS &&
1133 bp->b_vp->v_type == VREG) {
1135 } else if (presid > resid) {
1138 KASSERT(presid >= 0, ("brelse: extra page"));
1139 vm_page_set_invalid(m, poffset, presid);
1141 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1142 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1144 if (bp->b_flags & (B_INVAL | B_RELBUF))
1145 vfs_vmio_release(bp);
1146 } else if (bp->b_flags & B_VMIO) {
1148 * Rundown for VMIO buffers which are dirty NFS buffers. Such
1149 * buffers contain tracking ranges for NFS and cannot normally
1150 * be released. Due to the dirty check above this series of
1151 * conditionals, B_RELBUF probably will never be set in this
1154 if (bp->b_flags & (B_INVAL | B_RELBUF))
1155 vfs_vmio_release(bp);
1158 * Rundown for non-VMIO buffers.
1160 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1163 printf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1172 if (bp->b_qindex != BQUEUE_NONE)
1173 panic("brelse: free buffer onto another queue???");
1174 if (BUF_REFCNTNB(bp) > 1) {
1175 /* Temporary panic to verify exclusive locking */
1176 /* This panic goes away when we allow shared refs */
1177 panic("brelse: multiple refs");
1178 /* do not release to free list */
1185 * Figure out the correct queue to place the cleaned up buffer on.
1186 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1187 * disassociated from their vnode.
1190 if (bp->b_bufsize == 0) {
1192 * Buffers with no memory. Due to conditionals near the top
1193 * of brelse() such buffers should probably already be
1194 * marked B_INVAL and disassociated from their vnode.
1196 bp->b_flags |= B_INVAL;
1197 bp->b_xflags &= ~BX_BKGRDWRITE;
1198 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1199 KKASSERT((bp->b_flags & B_HASHED) == 0);
1200 if (bp->b_xflags & BX_BKGRDINPROG)
1201 panic("losing buffer 1");
1202 if (bp->b_kvasize) {
1203 bp->b_qindex = BQUEUE_EMPTYKVA;
1205 bp->b_qindex = BQUEUE_EMPTY;
1207 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1208 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1210 * Buffers with junk contents. Again these buffers had better
1211 * already be disassociated from their vnode.
1213 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1214 KKASSERT((bp->b_flags & B_HASHED) == 0);
1215 bp->b_flags |= B_INVAL;
1216 bp->b_xflags &= ~BX_BKGRDWRITE;
1217 if (bp->b_xflags & BX_BKGRDINPROG)
1218 panic("losing buffer 2");
1219 bp->b_qindex = BQUEUE_CLEAN;
1220 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1221 } else if (bp->b_flags & B_LOCKED) {
1223 * Buffers that are locked.
1225 bp->b_qindex = BQUEUE_LOCKED;
1226 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1229 * Remaining buffers. These buffers are still associated with
1232 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1233 case B_DELWRI | B_AGE:
1234 bp->b_qindex = BQUEUE_DIRTY;
1235 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1238 bp->b_qindex = BQUEUE_DIRTY;
1239 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1242 bp->b_qindex = BQUEUE_CLEAN;
1243 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1246 bp->b_qindex = BQUEUE_CLEAN;
1247 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1253 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1254 * on the correct queue.
1256 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1260 * Fixup numfreebuffers count. The bp is on an appropriate queue
1261 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1262 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1263 * if B_INVAL is set ).
1265 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1269 * Something we can maybe free or reuse
1271 if (bp->b_bufsize || bp->b_kvasize)
1276 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1277 B_DIRECT | B_NOWDRAIN);
1284 * Release a buffer back to the appropriate queue but do not try to free
1285 * it. The buffer is expected to be used again soon.
1287 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1288 * biodone() to requeue an async I/O on completion. It is also used when
1289 * known good buffers need to be requeued but we think we may need the data
1292 * XXX we should be able to leave the B_RELBUF hint set on completion.
1295 bqrelse(struct buf * bp)
1299 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1301 if (bp->b_qindex != BQUEUE_NONE)
1302 panic("bqrelse: free buffer onto another queue???");
1303 if (BUF_REFCNTNB(bp) > 1) {
1304 /* do not release to free list */
1305 panic("bqrelse: multiple refs");
1310 if (bp->b_flags & B_LOCKED) {
1311 bp->b_flags &= ~B_ERROR;
1312 bp->b_qindex = BQUEUE_LOCKED;
1313 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1314 /* buffers with stale but valid contents */
1315 } else if (bp->b_flags & B_DELWRI) {
1316 bp->b_qindex = BQUEUE_DIRTY;
1317 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1318 } else if (vm_page_count_severe()) {
1320 * We are too low on memory, we have to try to free the
1321 * buffer (most importantly: the wired pages making up its
1322 * backing store) *now*.
1328 bp->b_qindex = BQUEUE_CLEAN;
1329 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1332 if ((bp->b_flags & B_LOCKED) == 0 &&
1333 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1338 * Something we can maybe free or reuse.
1340 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1344 * Final cleanup and unlock. Clear bits that are only used while a
1345 * buffer is actively locked.
1347 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1355 * Return backing pages held by the buffer 'bp' back to the VM system
1356 * if possible. The pages are freed if they are no longer valid or
1357 * attempt to free if it was used for direct I/O otherwise they are
1358 * sent to the page cache.
1360 * Pages that were marked busy are left alone and skipped.
1362 * The KVA mapping (b_data) for the underlying pages is removed by
1366 vfs_vmio_release(struct buf *bp)
1372 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1373 m = bp->b_xio.xio_pages[i];
1374 bp->b_xio.xio_pages[i] = NULL;
1376 * In order to keep page LRU ordering consistent, put
1377 * everything on the inactive queue.
1379 vm_page_unwire(m, 0);
1381 * We don't mess with busy pages, it is
1382 * the responsibility of the process that
1383 * busied the pages to deal with them.
1385 if ((m->flags & PG_BUSY) || (m->busy != 0))
1388 if (m->wire_count == 0) {
1389 vm_page_flag_clear(m, PG_ZERO);
1391 * Might as well free the page if we can and it has
1392 * no valid data. We also free the page if the
1393 * buffer was used for direct I/O.
1395 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1396 m->hold_count == 0) {
1398 vm_page_protect(m, VM_PROT_NONE);
1400 } else if (bp->b_flags & B_DIRECT) {
1401 vm_page_try_to_free(m);
1402 } else if (vm_page_count_severe()) {
1403 vm_page_try_to_cache(m);
1408 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1409 if (bp->b_bufsize) {
1413 bp->b_xio.xio_npages = 0;
1414 bp->b_flags &= ~B_VMIO;
1422 * Implement clustered async writes for clearing out B_DELWRI buffers.
1423 * This is much better then the old way of writing only one buffer at
1424 * a time. Note that we may not be presented with the buffers in the
1425 * correct order, so we search for the cluster in both directions.
1427 * The buffer is locked on call.
1430 vfs_bio_awrite(struct buf *bp)
1434 off_t loffset = bp->b_loffset;
1435 struct vnode *vp = bp->b_vp;
1443 * right now we support clustered writing only to regular files. If
1444 * we find a clusterable block we could be in the middle of a cluster
1445 * rather then at the beginning.
1447 * NOTE: b_bio1 contains the logical loffset and is aliased
1448 * to b_loffset. b_bio2 contains the translated block number.
1450 if ((vp->v_type == VREG) &&
1451 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1452 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1454 size = vp->v_mount->mnt_stat.f_iosize;
1456 for (i = size; i < MAXPHYS; i += size) {
1457 if ((bpa = findblk(vp, loffset + i)) &&
1458 BUF_REFCNT(bpa) == 0 &&
1459 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1460 (B_DELWRI | B_CLUSTEROK)) &&
1461 (bpa->b_bufsize == size)) {
1462 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1463 (bpa->b_bio2.bio_offset !=
1464 bp->b_bio2.bio_offset + i))
1470 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1471 if ((bpa = findblk(vp, loffset - j)) &&
1472 BUF_REFCNT(bpa) == 0 &&
1473 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1474 (B_DELWRI | B_CLUSTEROK)) &&
1475 (bpa->b_bufsize == size)) {
1476 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1477 (bpa->b_bio2.bio_offset !=
1478 bp->b_bio2.bio_offset - j))
1487 * this is a possible cluster write
1489 if (nbytes != size) {
1491 nwritten = cluster_wbuild(vp, size,
1492 loffset - j, nbytes);
1499 bp->b_flags |= B_ASYNC;
1503 * default (old) behavior, writing out only one block
1505 * XXX returns b_bufsize instead of b_bcount for nwritten?
1507 nwritten = bp->b_bufsize;
1508 (void) VOP_BWRITE(bp->b_vp, bp);
1516 * Find and initialize a new buffer header, freeing up existing buffers
1517 * in the bufqueues as necessary. The new buffer is returned locked.
1519 * Important: B_INVAL is not set. If the caller wishes to throw the
1520 * buffer away, the caller must set B_INVAL prior to calling brelse().
1523 * We have insufficient buffer headers
1524 * We have insufficient buffer space
1525 * buffer_map is too fragmented ( space reservation fails )
1526 * If we have to flush dirty buffers ( but we try to avoid this )
1528 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1529 * Instead we ask the buf daemon to do it for us. We attempt to
1530 * avoid piecemeal wakeups of the pageout daemon.
1534 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1540 static int flushingbufs;
1543 * We can't afford to block since we might be holding a vnode lock,
1544 * which may prevent system daemons from running. We deal with
1545 * low-memory situations by proactively returning memory and running
1546 * async I/O rather then sync I/O.
1550 --getnewbufrestarts;
1552 ++getnewbufrestarts;
1555 * Setup for scan. If we do not have enough free buffers,
1556 * we setup a degenerate case that immediately fails. Note
1557 * that if we are specially marked process, we are allowed to
1558 * dip into our reserves.
1560 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1562 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1563 * However, there are a number of cases (defragging, reusing, ...)
1564 * where we cannot backup.
1566 nqindex = BQUEUE_EMPTYKVA;
1567 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1571 * If no EMPTYKVA buffers and we are either
1572 * defragging or reusing, locate a CLEAN buffer
1573 * to free or reuse. If bufspace useage is low
1574 * skip this step so we can allocate a new buffer.
1576 if (defrag || bufspace >= lobufspace) {
1577 nqindex = BQUEUE_CLEAN;
1578 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1582 * If we could not find or were not allowed to reuse a
1583 * CLEAN buffer, check to see if it is ok to use an EMPTY
1584 * buffer. We can only use an EMPTY buffer if allocating
1585 * its KVA would not otherwise run us out of buffer space.
1587 if (nbp == NULL && defrag == 0 &&
1588 bufspace + maxsize < hibufspace) {
1589 nqindex = BQUEUE_EMPTY;
1590 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1595 * Run scan, possibly freeing data and/or kva mappings on the fly
1599 while ((bp = nbp) != NULL) {
1600 int qindex = nqindex;
1603 * Calculate next bp ( we can only use it if we do not block
1604 * or do other fancy things ).
1606 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1609 nqindex = BQUEUE_EMPTYKVA;
1610 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1613 case BQUEUE_EMPTYKVA:
1614 nqindex = BQUEUE_CLEAN;
1615 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1629 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1632 * Note: we no longer distinguish between VMIO and non-VMIO
1636 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1639 * If we are defragging then we need a buffer with
1640 * b_kvasize != 0. XXX this situation should no longer
1641 * occur, if defrag is non-zero the buffer's b_kvasize
1642 * should also be non-zero at this point. XXX
1644 if (defrag && bp->b_kvasize == 0) {
1645 printf("Warning: defrag empty buffer %p\n", bp);
1650 * Start freeing the bp. This is somewhat involved. nbp
1651 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1652 * on the clean list must be disassociated from their
1653 * current vnode. Buffers on the empty[kva] lists have
1654 * already been disassociated.
1657 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1658 printf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1659 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1662 if (bp->b_qindex != qindex) {
1663 printf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1669 if (qindex == BQUEUE_CLEAN) {
1670 if (bp->b_flags & B_VMIO) {
1671 bp->b_flags &= ~B_ASYNC;
1672 vfs_vmio_release(bp);
1679 * NOTE: nbp is now entirely invalid. We can only restart
1680 * the scan from this point on.
1682 * Get the rest of the buffer freed up. b_kva* is still
1683 * valid after this operation.
1686 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1687 KKASSERT((bp->b_flags & B_HASHED) == 0);
1688 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1689 (*bioops.io_deallocate)(bp);
1690 if (bp->b_xflags & BX_BKGRDINPROG)
1691 panic("losing buffer 3");
1694 * critical section protection is not required when
1695 * scrapping a buffer's contents because it is already
1707 bp->b_xio.xio_npages = 0;
1708 bp->b_dirtyoff = bp->b_dirtyend = 0;
1711 LIST_INIT(&bp->b_dep);
1714 * If we are defragging then free the buffer.
1717 bp->b_flags |= B_INVAL;
1725 * If we are overcomitted then recover the buffer and its
1726 * KVM space. This occurs in rare situations when multiple
1727 * processes are blocked in getnewbuf() or allocbuf().
1729 if (bufspace >= hibufspace)
1731 if (flushingbufs && bp->b_kvasize != 0) {
1732 bp->b_flags |= B_INVAL;
1737 if (bufspace < lobufspace)
1743 * If we exhausted our list, sleep as appropriate. We may have to
1744 * wakeup various daemons and write out some dirty buffers.
1746 * Generally we are sleeping due to insufficient buffer space.
1754 flags = VFS_BIO_NEED_BUFSPACE;
1756 } else if (bufspace >= hibufspace) {
1758 flags = VFS_BIO_NEED_BUFSPACE;
1761 flags = VFS_BIO_NEED_ANY;
1764 bd_speedup(); /* heeeelp */
1766 needsbuffer |= flags;
1767 while (needsbuffer & flags) {
1768 if (tsleep(&needsbuffer, slpflag, waitmsg, slptimeo))
1773 * We finally have a valid bp. We aren't quite out of the
1774 * woods, we still have to reserve kva space. In order
1775 * to keep fragmentation sane we only allocate kva in
1778 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1780 if (maxsize != bp->b_kvasize) {
1781 vm_offset_t addr = 0;
1786 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1787 vm_map_lock(buffer_map);
1789 if (vm_map_findspace(buffer_map,
1790 vm_map_min(buffer_map), maxsize,
1793 * Uh oh. Buffer map is too fragmented. We
1794 * must defragment the map.
1796 vm_map_unlock(buffer_map);
1797 vm_map_entry_release(count);
1800 bp->b_flags |= B_INVAL;
1805 vm_map_insert(buffer_map, &count,
1807 addr, addr + maxsize,
1808 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1810 bp->b_kvabase = (caddr_t) addr;
1811 bp->b_kvasize = maxsize;
1812 bufspace += bp->b_kvasize;
1815 vm_map_unlock(buffer_map);
1816 vm_map_entry_release(count);
1818 bp->b_data = bp->b_kvabase;
1826 * Buffer flushing daemon. Buffers are normally flushed by the
1827 * update daemon but if it cannot keep up this process starts to
1828 * take the load in an attempt to prevent getnewbuf() from blocking.
1831 static struct thread *bufdaemonthread;
1833 static struct kproc_desc buf_kp = {
1838 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1844 * This process needs to be suspended prior to shutdown sync.
1846 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1847 bufdaemonthread, SHUTDOWN_PRI_LAST);
1850 * This process is allowed to take the buffer cache to the limit
1855 kproc_suspend_loop();
1858 * Do the flush. Limit the amount of in-transit I/O we
1859 * allow to build up, otherwise we would completely saturate
1860 * the I/O system. Wakeup any waiting processes before we
1861 * normally would so they can run in parallel with our drain.
1863 while (numdirtybuffers > lodirtybuffers) {
1864 if (flushbufqueues() == 0)
1866 waitrunningbufspace();
1867 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
1871 * Only clear bd_request if we have reached our low water
1872 * mark. The buf_daemon normally waits 5 seconds and
1873 * then incrementally flushes any dirty buffers that have
1874 * built up, within reason.
1876 * If we were unable to hit our low water mark and couldn't
1877 * find any flushable buffers, we sleep half a second.
1878 * Otherwise we loop immediately.
1880 if (numdirtybuffers <= lodirtybuffers) {
1882 * We reached our low water mark, reset the
1883 * request and sleep until we are needed again.
1884 * The sleep is just so the suspend code works.
1887 tsleep(&bd_request, 0, "psleep", hz);
1890 * We couldn't find any flushable dirty buffers but
1891 * still have too many dirty buffers, we
1892 * have to sleep and try again. (rare)
1894 tsleep(&bd_request, 0, "qsleep", hz / 2);
1902 * Try to flush a buffer in the dirty queue. We must be careful to
1903 * free up B_INVAL buffers instead of write them, which NFS is
1904 * particularly sensitive to.
1908 flushbufqueues(void)
1913 bp = TAILQ_FIRST(&bufqueues[BQUEUE_DIRTY]);
1916 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1917 if ((bp->b_flags & B_DELWRI) != 0 &&
1918 (bp->b_xflags & BX_BKGRDINPROG) == 0) {
1919 if (bp->b_flags & B_INVAL) {
1920 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1921 panic("flushbufqueues: locked buf");
1927 if (LIST_FIRST(&bp->b_dep) != NULL &&
1928 bioops.io_countdeps &&
1929 (bp->b_flags & B_DEFERRED) == 0 &&
1930 (*bioops.io_countdeps)(bp, 0)) {
1931 TAILQ_REMOVE(&bufqueues[BQUEUE_DIRTY],
1933 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY],
1935 bp->b_flags |= B_DEFERRED;
1936 bp = TAILQ_FIRST(&bufqueues[BQUEUE_DIRTY]);
1941 * Only write it out if we can successfully lock
1944 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
1950 bp = TAILQ_NEXT(bp, b_freelist);
1958 * Returns true if no I/O is needed to access the associated VM object.
1959 * This is like findblk except it also hunts around in the VM system for
1962 * Note that we ignore vm_page_free() races from interrupts against our
1963 * lookup, since if the caller is not protected our return value will not
1964 * be any more valid then otherwise once we exit the critical section.
1967 inmem(struct vnode *vp, off_t loffset)
1970 vm_offset_t toff, tinc, size;
1973 if (findblk(vp, loffset))
1975 if (vp->v_mount == NULL)
1977 if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
1981 if (size > vp->v_mount->mnt_stat.f_iosize)
1982 size = vp->v_mount->mnt_stat.f_iosize;
1984 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
1985 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
1989 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
1990 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
1991 if (vm_page_is_valid(m,
1992 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2001 * Sets the dirty range for a buffer based on the status of the dirty
2002 * bits in the pages comprising the buffer.
2004 * The range is limited to the size of the buffer.
2006 * This routine is primarily used by NFS, but is generalized for the
2010 vfs_setdirty(struct buf *bp)
2016 * Degenerate case - empty buffer
2019 if (bp->b_bufsize == 0)
2023 * We qualify the scan for modified pages on whether the
2024 * object has been flushed yet. The OBJ_WRITEABLE flag
2025 * is not cleared simply by protecting pages off.
2028 if ((bp->b_flags & B_VMIO) == 0)
2031 object = bp->b_xio.xio_pages[0]->object;
2033 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2034 printf("Warning: object %p writeable but not mightbedirty\n", object);
2035 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2036 printf("Warning: object %p mightbedirty but not writeable\n", object);
2038 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2039 vm_offset_t boffset;
2040 vm_offset_t eoffset;
2043 * test the pages to see if they have been modified directly
2044 * by users through the VM system.
2046 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2047 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2048 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2052 * Calculate the encompassing dirty range, boffset and eoffset,
2053 * (eoffset - boffset) bytes.
2056 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2057 if (bp->b_xio.xio_pages[i]->dirty)
2060 boffset = (i << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2062 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2063 if (bp->b_xio.xio_pages[i]->dirty) {
2067 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2070 * Fit it to the buffer.
2073 if (eoffset > bp->b_bcount)
2074 eoffset = bp->b_bcount;
2077 * If we have a good dirty range, merge with the existing
2081 if (boffset < eoffset) {
2082 if (bp->b_dirtyoff > boffset)
2083 bp->b_dirtyoff = boffset;
2084 if (bp->b_dirtyend < eoffset)
2085 bp->b_dirtyend = eoffset;
2093 * Locate and return the specified buffer, or NULL if the buffer does
2094 * not exist. Do not attempt to lock the buffer or manipulate it in
2095 * any way. The caller must validate that the correct buffer has been
2096 * obtain after locking it.
2099 findblk(struct vnode *vp, off_t loffset)
2104 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2112 * Get a block given a specified block and offset into a file/device.
2113 * The buffers B_DONE bit will be cleared on return, making it almost
2114 * ready for an I/O initiation. B_INVAL may or may not be set on
2115 * return. The caller should clear B_INVAL prior to initiating a
2118 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2119 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2120 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2121 * without doing any of those things the system will likely believe
2122 * the buffer to be valid (especially if it is not B_VMIO), and the
2123 * next getblk() will return the buffer with B_CACHE set.
2125 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2126 * an existing buffer.
2128 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2129 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2130 * and then cleared based on the backing VM. If the previous buffer is
2131 * non-0-sized but invalid, B_CACHE will be cleared.
2133 * If getblk() must create a new buffer, the new buffer is returned with
2134 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2135 * case it is returned with B_INVAL clear and B_CACHE set based on the
2138 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2139 * B_CACHE bit is clear.
2141 * What this means, basically, is that the caller should use B_CACHE to
2142 * determine whether the buffer is fully valid or not and should clear
2143 * B_INVAL prior to issuing a read. If the caller intends to validate
2144 * the buffer by loading its data area with something, the caller needs
2145 * to clear B_INVAL. If the caller does this without issuing an I/O,
2146 * the caller should set B_CACHE ( as an optimization ), else the caller
2147 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2148 * a write attempt or if it was a successfull read. If the caller
2149 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2150 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2153 getblk(struct vnode *vp, off_t loffset, int size, int slpflag, int slptimeo)
2157 if (size > MAXBSIZE)
2158 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2163 * Block if we are low on buffers. Certain processes are allowed
2164 * to completely exhaust the buffer cache.
2166 * If this check ever becomes a bottleneck it may be better to
2167 * move it into the else, when findblk() fails. At the moment
2168 * it isn't a problem.
2170 * XXX remove, we cannot afford to block anywhere if holding a vnode
2171 * lock in low-memory situation, so take it to the max.
2173 if (numfreebuffers == 0) {
2176 needsbuffer |= VFS_BIO_NEED_ANY;
2177 tsleep(&needsbuffer, slpflag, "newbuf", slptimeo);
2180 if ((bp = findblk(vp, loffset))) {
2182 * The buffer was found in the cache, but we need to lock it.
2183 * Even with LK_NOWAIT the lockmgr may break our critical
2184 * section, so double-check the validity of the buffer
2185 * once the lock has been obtained.
2187 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2188 int lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2189 if (slpflag & PCATCH)
2190 lkflags |= LK_PCATCH;
2191 if (BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo) ==
2200 * Once the buffer has been locked, make sure we didn't race
2201 * a buffer recyclement. Buffers that are no longer hashed
2202 * will have b_vp == NULL, so this takes care of that check
2205 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2206 printf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp, vp, loffset);
2212 * Make sure that B_INVAL buffers do not have a cached
2213 * block number translation.
2215 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2216 printf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp, vp, loffset);
2217 clearbiocache(&bp->b_bio2);
2221 * The buffer is locked. B_CACHE is cleared if the buffer is
2222 * invalid. Otherwise, for a non-VMIO buffer, B_CACHE is set
2223 * and for a VMIO buffer B_CACHE is adjusted according to the
2226 if (bp->b_flags & B_INVAL)
2227 bp->b_flags &= ~B_CACHE;
2228 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2229 bp->b_flags |= B_CACHE;
2233 * check for size inconsistancies for non-VMIO case.
2236 if (bp->b_bcount != size) {
2237 if ((bp->b_flags & B_VMIO) == 0 ||
2238 (size > bp->b_kvasize)) {
2239 if (bp->b_flags & B_DELWRI) {
2240 bp->b_flags |= B_NOCACHE;
2241 VOP_BWRITE(bp->b_vp, bp);
2243 if ((bp->b_flags & B_VMIO) &&
2244 (LIST_FIRST(&bp->b_dep) == NULL)) {
2245 bp->b_flags |= B_RELBUF;
2248 bp->b_flags |= B_NOCACHE;
2249 VOP_BWRITE(bp->b_vp, bp);
2257 * If the size is inconsistant in the VMIO case, we can resize
2258 * the buffer. This might lead to B_CACHE getting set or
2259 * cleared. If the size has not changed, B_CACHE remains
2260 * unchanged from its previous state.
2263 if (bp->b_bcount != size)
2266 KASSERT(bp->b_loffset != NOOFFSET,
2267 ("getblk: no buffer offset"));
2270 * A buffer with B_DELWRI set and B_CACHE clear must
2271 * be committed before we can return the buffer in
2272 * order to prevent the caller from issuing a read
2273 * ( due to B_CACHE not being set ) and overwriting
2276 * Most callers, including NFS and FFS, need this to
2277 * operate properly either because they assume they
2278 * can issue a read if B_CACHE is not set, or because
2279 * ( for example ) an uncached B_DELWRI might loop due
2280 * to softupdates re-dirtying the buffer. In the latter
2281 * case, B_CACHE is set after the first write completes,
2282 * preventing further loops.
2284 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2285 * above while extending the buffer, we cannot allow the
2286 * buffer to remain with B_CACHE set after the write
2287 * completes or it will represent a corrupt state. To
2288 * deal with this we set B_NOCACHE to scrap the buffer
2291 * We might be able to do something fancy, like setting
2292 * B_CACHE in bwrite() except if B_DELWRI is already set,
2293 * so the below call doesn't set B_CACHE, but that gets real
2294 * confusing. This is much easier.
2297 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2298 bp->b_flags |= B_NOCACHE;
2299 VOP_BWRITE(bp->b_vp, bp);
2304 bp->b_flags &= ~B_DONE;
2307 * Buffer is not in-core, create new buffer. The buffer
2308 * returned by getnewbuf() is locked. Note that the returned
2309 * buffer is also considered valid (not marked B_INVAL).
2311 * Calculating the offset for the I/O requires figuring out
2312 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2313 * the mount's f_iosize otherwise. If the vnode does not
2314 * have an associated mount we assume that the passed size is
2317 * Note that vn_isdisk() cannot be used here since it may
2318 * return a failure for numerous reasons. Note that the
2319 * buffer size may be larger then the block size (the caller
2320 * will use block numbers with the proper multiple). Beware
2321 * of using any v_* fields which are part of unions. In
2322 * particular, in DragonFly the mount point overloading
2323 * mechanism is such that the underlying directory (with a
2324 * non-NULL v_mountedhere) is not a special case.
2326 int bsize, maxsize, vmio;
2328 if (vp->v_type == VBLK || vp->v_type == VCHR)
2330 else if (vp->v_mount)
2331 bsize = vp->v_mount->mnt_stat.f_iosize;
2335 vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2336 maxsize = vmio ? size + (loffset & PAGE_MASK) : size;
2337 maxsize = imax(maxsize, bsize);
2339 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2340 if (slpflag || slptimeo) {
2348 * This code is used to make sure that a buffer is not
2349 * created while the getnewbuf routine is blocked.
2350 * This can be a problem whether the vnode is locked or not.
2351 * If the buffer is created out from under us, we have to
2352 * throw away the one we just created. There is now window
2353 * race because we are safely running in a critical section
2354 * from the point of the duplicate buffer creation through
2355 * to here, and we've locked the buffer.
2357 if (findblk(vp, loffset)) {
2358 bp->b_flags |= B_INVAL;
2364 * Insert the buffer into the hash, so that it can
2365 * be found by findblk().
2367 * Make sure the translation layer has been cleared.
2369 bp->b_loffset = loffset;
2370 bp->b_bio2.bio_offset = NOOFFSET;
2371 /* bp->b_bio2.bio_next = NULL; */
2376 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2377 * buffer size starts out as 0, B_CACHE will be set by
2378 * allocbuf() for the VMIO case prior to it testing the
2379 * backing store for validity.
2383 bp->b_flags |= B_VMIO;
2384 #if defined(VFS_BIO_DEBUG)
2385 if (vn_canvmio(vp) != TRUE)
2386 printf("getblk: vmioing file type %d???\n", vp->v_type);
2389 bp->b_flags &= ~B_VMIO;
2395 bp->b_flags &= ~B_DONE;
2403 * Get an empty, disassociated buffer of given size. The buffer is
2404 * initially set to B_INVAL.
2406 * critical section protection is not required for the allocbuf()
2407 * call because races are impossible here.
2415 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2418 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2422 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2430 * This code constitutes the buffer memory from either anonymous system
2431 * memory (in the case of non-VMIO operations) or from an associated
2432 * VM object (in the case of VMIO operations). This code is able to
2433 * resize a buffer up or down.
2435 * Note that this code is tricky, and has many complications to resolve
2436 * deadlock or inconsistant data situations. Tread lightly!!!
2437 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2438 * the caller. Calling this code willy nilly can result in the loss of data.
2440 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2441 * B_CACHE for the non-VMIO case.
2443 * This routine does not need to be called from a critical section but you
2444 * must own the buffer.
2447 allocbuf(struct buf *bp, int size)
2449 int newbsize, mbsize;
2452 if (BUF_REFCNT(bp) == 0)
2453 panic("allocbuf: buffer not busy");
2455 if (bp->b_kvasize < size)
2456 panic("allocbuf: buffer too small");
2458 if ((bp->b_flags & B_VMIO) == 0) {
2462 * Just get anonymous memory from the kernel. Don't
2463 * mess with B_CACHE.
2465 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2466 if (bp->b_flags & B_MALLOC)
2469 newbsize = round_page(size);
2471 if (newbsize < bp->b_bufsize) {
2473 * malloced buffers are not shrunk
2475 if (bp->b_flags & B_MALLOC) {
2477 bp->b_bcount = size;
2479 free(bp->b_data, M_BIOBUF);
2480 if (bp->b_bufsize) {
2481 bufmallocspace -= bp->b_bufsize;
2485 bp->b_data = bp->b_kvabase;
2487 bp->b_flags &= ~B_MALLOC;
2493 (vm_offset_t) bp->b_data + newbsize,
2494 (vm_offset_t) bp->b_data + bp->b_bufsize);
2495 } else if (newbsize > bp->b_bufsize) {
2497 * We only use malloced memory on the first allocation.
2498 * and revert to page-allocated memory when the buffer
2501 if ( (bufmallocspace < maxbufmallocspace) &&
2502 (bp->b_bufsize == 0) &&
2503 (mbsize <= PAGE_SIZE/2)) {
2505 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2506 bp->b_bufsize = mbsize;
2507 bp->b_bcount = size;
2508 bp->b_flags |= B_MALLOC;
2509 bufmallocspace += mbsize;
2515 * If the buffer is growing on its other-than-first allocation,
2516 * then we revert to the page-allocation scheme.
2518 if (bp->b_flags & B_MALLOC) {
2519 origbuf = bp->b_data;
2520 origbufsize = bp->b_bufsize;
2521 bp->b_data = bp->b_kvabase;
2522 if (bp->b_bufsize) {
2523 bufmallocspace -= bp->b_bufsize;
2527 bp->b_flags &= ~B_MALLOC;
2528 newbsize = round_page(newbsize);
2532 (vm_offset_t) bp->b_data + bp->b_bufsize,
2533 (vm_offset_t) bp->b_data + newbsize);
2535 bcopy(origbuf, bp->b_data, origbufsize);
2536 free(origbuf, M_BIOBUF);
2543 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2544 desiredpages = (size == 0) ? 0 :
2545 num_pages((bp->b_loffset & PAGE_MASK) + newbsize);
2547 if (bp->b_flags & B_MALLOC)
2548 panic("allocbuf: VMIO buffer can't be malloced");
2550 * Set B_CACHE initially if buffer is 0 length or will become
2553 if (size == 0 || bp->b_bufsize == 0)
2554 bp->b_flags |= B_CACHE;
2556 if (newbsize < bp->b_bufsize) {
2558 * DEV_BSIZE aligned new buffer size is less then the
2559 * DEV_BSIZE aligned existing buffer size. Figure out
2560 * if we have to remove any pages.
2562 if (desiredpages < bp->b_xio.xio_npages) {
2563 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2565 * the page is not freed here -- it
2566 * is the responsibility of
2567 * vnode_pager_setsize
2569 m = bp->b_xio.xio_pages[i];
2570 KASSERT(m != bogus_page,
2571 ("allocbuf: bogus page found"));
2572 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2575 bp->b_xio.xio_pages[i] = NULL;
2576 vm_page_unwire(m, 0);
2578 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2579 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2580 bp->b_xio.xio_npages = desiredpages;
2582 } else if (size > bp->b_bcount) {
2584 * We are growing the buffer, possibly in a
2585 * byte-granular fashion.
2593 * Step 1, bring in the VM pages from the object,
2594 * allocating them if necessary. We must clear
2595 * B_CACHE if these pages are not valid for the
2596 * range covered by the buffer.
2598 * critical section protection is required to protect
2599 * against interrupts unbusying and freeing pages
2600 * between our vm_page_lookup() and our
2601 * busycheck/wiring call.
2604 VOP_GETVOBJECT(vp, &obj);
2607 while (bp->b_xio.xio_npages < desiredpages) {
2611 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
2612 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2614 * note: must allocate system pages
2615 * since blocking here could intefere
2616 * with paging I/O, no matter which
2619 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2622 vm_pageout_deficit += desiredpages -
2623 bp->b_xio.xio_npages;
2627 bp->b_flags &= ~B_CACHE;
2628 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2629 ++bp->b_xio.xio_npages;
2635 * We found a page. If we have to sleep on it,
2636 * retry because it might have gotten freed out
2639 * We can only test PG_BUSY here. Blocking on
2640 * m->busy might lead to a deadlock:
2642 * vm_fault->getpages->cluster_read->allocbuf
2646 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2650 * We have a good page. Should we wakeup the
2653 if ((curthread != pagethread) &&
2654 ((m->queue - m->pc) == PQ_CACHE) &&
2655 ((vmstats.v_free_count + vmstats.v_cache_count) <
2656 (vmstats.v_free_min + vmstats.v_cache_min))) {
2657 pagedaemon_wakeup();
2659 vm_page_flag_clear(m, PG_ZERO);
2661 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2662 ++bp->b_xio.xio_npages;
2667 * Step 2. We've loaded the pages into the buffer,
2668 * we have to figure out if we can still have B_CACHE
2669 * set. Note that B_CACHE is set according to the
2670 * byte-granular range ( bcount and size ), not the
2671 * aligned range ( newbsize ).
2673 * The VM test is against m->valid, which is DEV_BSIZE
2674 * aligned. Needless to say, the validity of the data
2675 * needs to also be DEV_BSIZE aligned. Note that this
2676 * fails with NFS if the server or some other client
2677 * extends the file's EOF. If our buffer is resized,
2678 * B_CACHE may remain set! XXX
2681 toff = bp->b_bcount;
2682 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
2684 while ((bp->b_flags & B_CACHE) && toff < size) {
2687 if (tinc > (size - toff))
2690 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
2698 bp->b_xio.xio_pages[pi]
2705 * Step 3, fixup the KVM pmap. Remember that
2706 * bp->b_data is relative to bp->b_loffset, but
2707 * bp->b_loffset may be offset into the first page.
2710 bp->b_data = (caddr_t)
2711 trunc_page((vm_offset_t)bp->b_data);
2713 (vm_offset_t)bp->b_data,
2714 bp->b_xio.xio_pages,
2715 bp->b_xio.xio_npages
2717 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2718 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
2721 if (newbsize < bp->b_bufsize)
2723 bp->b_bufsize = newbsize; /* actual buffer allocation */
2724 bp->b_bcount = size; /* requested buffer size */
2731 * Wait for buffer I/O completion, returning error status. The buffer
2732 * is left locked and B_DONE on return. B_EINTR is converted into an
2733 * EINTR error and cleared.
2736 biowait(struct buf * bp)
2739 while ((bp->b_flags & B_DONE) == 0) {
2740 if (bp->b_flags & B_READ)
2741 tsleep(bp, 0, "biord", 0);
2743 tsleep(bp, 0, "biowr", 0);
2746 if (bp->b_flags & B_EINTR) {
2747 bp->b_flags &= ~B_EINTR;
2750 if (bp->b_flags & B_ERROR) {
2751 return (bp->b_error ? bp->b_error : EIO);
2758 * This associates a tracking count with an I/O. vn_strategy() and
2759 * dev_dstrategy() do this automatically but there are a few cases
2760 * where a vnode or device layer is bypassed when a block translation
2761 * is cached. In such cases bio_start_transaction() may be called on
2762 * the bypassed layers so the system gets an I/O in progress indication
2763 * for those higher layers.
2766 bio_start_transaction(struct bio *bio, struct bio_track *track)
2768 bio->bio_track = track;
2769 atomic_add_int(&track->bk_active, 1);
2773 * Initiate I/O on a vnode.
2776 vn_strategy(struct vnode *vp, struct bio *bio)
2778 struct bio_track *track;
2780 if (bio->bio_buf->b_flags & B_READ)
2781 track = &vp->v_track_read;
2783 track = &vp->v_track_write;
2784 bio->bio_track = track;
2785 atomic_add_int(&track->bk_active, 1);
2786 vop_strategy(*vp->v_ops, vp, bio);
2793 * Finish I/O on a buffer, optionally calling a completion function.
2794 * This is usually called from an interrupt so process blocking is
2797 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2798 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2799 * assuming B_INVAL is clear.
2801 * For the VMIO case, we set B_CACHE if the op was a read and no
2802 * read error occured, or if the op was a write. B_CACHE is never
2803 * set if the buffer is invalid or otherwise uncacheable.
2805 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2806 * initiator to leave B_INVAL set to brelse the buffer out of existance
2807 * in the biodone routine.
2810 biodone(struct bio *bio)
2812 struct buf *bp = bio->bio_buf;
2817 KASSERT(BUF_REFCNTNB(bp) > 0,
2818 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
2819 KASSERT(!(bp->b_flags & B_DONE),
2820 ("biodone: bp %p already done", bp));
2822 bp->b_flags |= B_DONE;
2823 runningbufwakeup(bp);
2826 * Run up the chain of BIO's.
2829 biodone_t *done_func;
2830 struct bio_track *track;
2833 * BIO tracking. Most but not all BIOs are tracked.
2835 if ((track = bio->bio_track) != NULL) {
2836 atomic_subtract_int(&track->bk_active, 1);
2837 if (track->bk_active < 0) {
2838 panic("biodone: bad active count bio %p\n",
2841 if (track->bk_waitflag) {
2842 track->bk_waitflag = 0;
2845 bio->bio_track = NULL;
2849 * A bio_done function terminates the loop. The function
2850 * will be responsible for any further chaining and/or
2851 * buffer management.
2853 if ((done_func = bio->bio_done) != NULL) {
2854 bio->bio_done = NULL;
2859 bio = bio->bio_prev;
2863 * Special case (XXX) - not a read or write.
2865 if (bp->b_flags & B_FREEBUF) {
2871 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2872 (*bioops.io_complete)(bp);
2874 if (bp->b_flags & B_VMIO) {
2880 struct vnode *vp = bp->b_vp;
2882 error = VOP_GETVOBJECT(vp, &obj);
2884 #if defined(VFS_BIO_DEBUG)
2885 if (vp->v_holdcnt == 0) {
2886 panic("biodone: zero vnode hold count");
2890 panic("biodone: missing VM object");
2893 if ((vp->v_flag & VOBJBUF) == 0) {
2894 panic("biodone: vnode is not setup for merged cache");
2898 foff = bp->b_loffset;
2899 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
2902 panic("biodone: no object");
2904 #if defined(VFS_BIO_DEBUG)
2905 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
2906 printf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
2907 obj->paging_in_progress, bp->b_xio.xio_npages);
2912 * Set B_CACHE if the op was a normal read and no error
2913 * occured. B_CACHE is set for writes in the b*write()
2916 iosize = bp->b_bcount - bp->b_resid;
2917 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2918 bp->b_flags |= B_CACHE;
2921 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2925 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2930 * cleanup bogus pages, restoring the originals. Since
2931 * the originals should still be wired, we don't have
2932 * to worry about interrupt/freeing races destroying
2933 * the VM object association.
2935 m = bp->b_xio.xio_pages[i];
2936 if (m == bogus_page) {
2938 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2940 panic("biodone: page disappeared");
2941 bp->b_xio.xio_pages[i] = m;
2942 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2943 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
2945 #if defined(VFS_BIO_DEBUG)
2946 if (OFF_TO_IDX(foff) != m->pindex) {
2948 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2949 (unsigned long)foff, m->pindex);
2954 * In the write case, the valid and clean bits are
2955 * already changed correctly ( see bdwrite() ), so we
2956 * only need to do this here in the read case.
2958 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
2959 vfs_page_set_valid(bp, foff, i, m);
2961 vm_page_flag_clear(m, PG_ZERO);
2964 * when debugging new filesystems or buffer I/O methods, this
2965 * is the most common error that pops up. if you see this, you
2966 * have not set the page busy flag correctly!!!
2969 printf("biodone: page busy < 0, "
2970 "pindex: %d, foff: 0x(%x,%x), "
2971 "resid: %d, index: %d\n",
2972 (int) m->pindex, (int)(foff >> 32),
2973 (int) foff & 0xffffffff, resid, i);
2974 if (!vn_isdisk(vp, NULL))
2975 printf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
2976 bp->b_vp->v_mount->mnt_stat.f_iosize,
2978 bp->b_flags, bp->b_xio.xio_npages);
2980 printf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
2982 bp->b_flags, bp->b_xio.xio_npages);
2983 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2984 m->valid, m->dirty, m->wire_count);
2985 panic("biodone: page busy < 0");
2987 vm_page_io_finish(m);
2988 vm_object_pip_subtract(obj, 1);
2989 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2993 vm_object_pip_wakeupn(obj, 0);
2997 * For asynchronous completions, release the buffer now. The brelse
2998 * will do a wakeup there if necessary - so no need to do a wakeup
2999 * here in the async case. The sync case always needs to do a wakeup.
3002 if (bp->b_flags & B_ASYNC) {
3003 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3016 * This routine is called in lieu of iodone in the case of
3017 * incomplete I/O. This keeps the busy status for pages
3021 vfs_unbusy_pages(struct buf *bp)
3025 runningbufwakeup(bp);
3026 if (bp->b_flags & B_VMIO) {
3027 struct vnode *vp = bp->b_vp;
3030 VOP_GETVOBJECT(vp, &obj);
3032 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3033 vm_page_t m = bp->b_xio.xio_pages[i];
3036 * When restoring bogus changes the original pages
3037 * should still be wired, so we are in no danger of
3038 * losing the object association and do not need
3039 * critical section protection particularly.
3041 if (m == bogus_page) {
3042 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3044 panic("vfs_unbusy_pages: page missing");
3046 bp->b_xio.xio_pages[i] = m;
3047 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3048 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3050 vm_object_pip_subtract(obj, 1);
3051 vm_page_flag_clear(m, PG_ZERO);
3052 vm_page_io_finish(m);
3054 vm_object_pip_wakeupn(obj, 0);
3059 * vfs_page_set_valid:
3061 * Set the valid bits in a page based on the supplied offset. The
3062 * range is restricted to the buffer's size.
3064 * This routine is typically called after a read completes.
3067 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3069 vm_ooffset_t soff, eoff;
3072 * Start and end offsets in buffer. eoff - soff may not cross a
3073 * page boundry or cross the end of the buffer. The end of the
3074 * buffer, in this case, is our file EOF, not the allocation size
3078 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3079 if (eoff > bp->b_loffset + bp->b_bcount)
3080 eoff = bp->b_loffset + bp->b_bcount;
3083 * Set valid range. This is typically the entire buffer and thus the
3087 vm_page_set_validclean(
3089 (vm_offset_t) (soff & PAGE_MASK),
3090 (vm_offset_t) (eoff - soff)
3098 * This routine is called before a device strategy routine.
3099 * It is used to tell the VM system that paging I/O is in
3100 * progress, and treat the pages associated with the buffer
3101 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3102 * flag is handled to make sure that the object doesn't become
3105 * Since I/O has not been initiated yet, certain buffer flags
3106 * such as B_ERROR or B_INVAL may be in an inconsistant state
3107 * and should be ignored.
3110 vfs_busy_pages(struct buf *bp, int clear_modify)
3113 struct proc *p = curthread->td_proc;
3115 if (bp->b_flags & B_VMIO) {
3116 struct vnode *vp = bp->b_vp;
3120 VOP_GETVOBJECT(vp, &obj);
3121 foff = bp->b_loffset;
3122 KASSERT(bp->b_loffset != NOOFFSET,
3123 ("vfs_busy_pages: no buffer offset"));
3127 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3128 vm_page_t m = bp->b_xio.xio_pages[i];
3129 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3134 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3135 vm_page_t m = bp->b_xio.xio_pages[i];
3137 vm_page_flag_clear(m, PG_ZERO);
3138 if ((bp->b_flags & B_CLUSTER) == 0) {
3139 vm_object_pip_add(obj, 1);
3140 vm_page_io_start(m);
3144 * When readying a buffer for a read ( i.e
3145 * clear_modify == 0 ), it is important to do
3146 * bogus_page replacement for valid pages in
3147 * partially instantiated buffers. Partially
3148 * instantiated buffers can, in turn, occur when
3149 * reconstituting a buffer from its VM backing store
3150 * base. We only have to do this if B_CACHE is
3151 * clear ( which causes the I/O to occur in the
3152 * first place ). The replacement prevents the read
3153 * I/O from overwriting potentially dirty VM-backed
3154 * pages. XXX bogus page replacement is, uh, bogus.
3155 * It may not work properly with small-block devices.
3156 * We need to find a better way.
3159 vm_page_protect(m, VM_PROT_NONE);
3161 vfs_page_set_valid(bp, foff, i, m);
3162 else if (m->valid == VM_PAGE_BITS_ALL &&
3163 (bp->b_flags & B_CACHE) == 0) {
3164 bp->b_xio.xio_pages[i] = bogus_page;
3167 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3170 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3171 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3175 * This is the easiest place to put the process accounting for the I/O
3179 if (bp->b_flags & B_READ)
3180 p->p_stats->p_ru.ru_inblock++;
3182 p->p_stats->p_ru.ru_oublock++;
3189 * Tell the VM system that the pages associated with this buffer
3190 * are clean. This is used for delayed writes where the data is
3191 * going to go to disk eventually without additional VM intevention.
3193 * Note that while we only really need to clean through to b_bcount, we
3194 * just go ahead and clean through to b_bufsize.
3197 vfs_clean_pages(struct buf *bp)
3201 if (bp->b_flags & B_VMIO) {
3204 foff = bp->b_loffset;
3205 KASSERT(foff != NOOFFSET, ("vfs_clean_pages: no buffer offset"));
3206 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3207 vm_page_t m = bp->b_xio.xio_pages[i];
3208 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3209 vm_ooffset_t eoff = noff;
3211 if (eoff > bp->b_loffset + bp->b_bufsize)
3212 eoff = bp->b_loffset + bp->b_bufsize;
3213 vfs_page_set_valid(bp, foff, i, m);
3214 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3221 * vfs_bio_set_validclean:
3223 * Set the range within the buffer to valid and clean. The range is
3224 * relative to the beginning of the buffer, b_loffset. Note that
3225 * b_loffset itself may be offset from the beginning of the first page.
3229 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3231 if (bp->b_flags & B_VMIO) {
3236 * Fixup base to be relative to beginning of first page.
3237 * Set initial n to be the maximum number of bytes in the
3238 * first page that can be validated.
3241 base += (bp->b_loffset & PAGE_MASK);
3242 n = PAGE_SIZE - (base & PAGE_MASK);
3244 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3245 vm_page_t m = bp->b_xio.xio_pages[i];
3250 vm_page_set_validclean(m, base & PAGE_MASK, n);
3261 * Clear a buffer. This routine essentially fakes an I/O, so we need
3262 * to clear B_ERROR and B_INVAL.
3264 * Note that while we only theoretically need to clear through b_bcount,
3265 * we go ahead and clear through b_bufsize.
3269 vfs_bio_clrbuf(struct buf *bp)
3273 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3274 bp->b_flags &= ~(B_INVAL|B_ERROR);
3275 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3276 (bp->b_loffset & PAGE_MASK) == 0) {
3277 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3278 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3282 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3283 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3284 bzero(bp->b_data, bp->b_bufsize);
3285 bp->b_xio.xio_pages[0]->valid |= mask;
3290 ea = sa = bp->b_data;
3291 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3292 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3293 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3294 ea = (caddr_t)(vm_offset_t)ulmin(
3295 (u_long)(vm_offset_t)ea,
3296 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3297 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3298 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3300 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3301 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3305 for (; sa < ea; sa += DEV_BSIZE, j++) {
3306 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3307 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3308 bzero(sa, DEV_BSIZE);
3311 bp->b_xio.xio_pages[i]->valid |= mask;
3312 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3321 * vm_hold_load_pages:
3323 * Load pages into the buffer's address space. The pages are
3324 * allocated from the kernel object in order to reduce interference
3325 * with the any VM paging I/O activity. The range of loaded
3326 * pages will be wired.
3328 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3329 * retrieve the full range (to - from) of pages.
3333 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3339 to = round_page(to);
3340 from = round_page(from);
3341 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3343 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3348 * Note: must allocate system pages since blocking here
3349 * could intefere with paging I/O, no matter which
3352 p = vm_page_alloc(kernel_object,
3353 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3354 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3356 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3361 p->valid = VM_PAGE_BITS_ALL;
3362 vm_page_flag_clear(p, PG_ZERO);
3363 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3364 bp->b_xio.xio_pages[index] = p;
3367 bp->b_xio.xio_npages = index;
3371 * vm_hold_free_pages:
3373 * Return pages associated with the buffer back to the VM system.
3375 * The range of pages underlying the buffer's address space will
3376 * be unmapped and un-wired.
3379 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3383 int index, newnpages;
3385 from = round_page(from);
3386 to = round_page(to);
3387 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3389 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3390 p = bp->b_xio.xio_pages[index];
3391 if (p && (index < bp->b_xio.xio_npages)) {
3393 printf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3394 bp->b_bio2.bio_offset, bp->b_loffset);
3396 bp->b_xio.xio_pages[index] = NULL;
3399 vm_page_unwire(p, 0);
3403 bp->b_xio.xio_npages = newnpages;
3409 * Map an IO request into kernel virtual address space.
3411 * All requests are (re)mapped into kernel VA space.
3412 * Notice that we use b_bufsize for the size of the buffer
3413 * to be mapped. b_bcount might be modified by the driver.
3416 vmapbuf(struct buf *bp)
3418 caddr_t addr, v, kva;
3424 if ((bp->b_flags & B_PHYS) == 0)
3426 if (bp->b_bufsize < 0)
3428 for (v = bp->b_saveaddr,
3429 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3431 addr < bp->b_data + bp->b_bufsize;
3432 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3434 * Do the vm_fault if needed; do the copy-on-write thing
3435 * when reading stuff off device into memory.
3438 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3439 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3441 for (i = 0; i < pidx; ++i) {
3442 vm_page_unhold(bp->b_xio.xio_pages[i]);
3443 bp->b_xio.xio_pages[i] = NULL;
3449 * WARNING! If sparc support is MFCd in the future this will
3450 * have to be changed from pmap_kextract() to pmap_extract()
3454 #error "If MFCing sparc support use pmap_extract"
3456 pa = pmap_kextract((vm_offset_t)addr);
3458 printf("vmapbuf: warning, race against user address during I/O");
3461 m = PHYS_TO_VM_PAGE(pa);
3463 bp->b_xio.xio_pages[pidx] = m;
3465 if (pidx > btoc(MAXPHYS))
3466 panic("vmapbuf: mapped more than MAXPHYS");
3467 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_xio.xio_pages, pidx);
3469 kva = bp->b_saveaddr;
3470 bp->b_xio.xio_npages = pidx;
3471 bp->b_saveaddr = bp->b_data;
3472 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3479 * Free the io map PTEs associated with this IO operation.
3480 * We also invalidate the TLB entries and restore the original b_addr.
3483 vunmapbuf(struct buf *bp)
3489 if ((bp->b_flags & B_PHYS) == 0)
3492 npages = bp->b_xio.xio_npages;
3493 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3495 m = bp->b_xio.xio_pages;
3496 for (pidx = 0; pidx < npages; pidx++)
3497 vm_page_unhold(*m++);
3499 bp->b_data = bp->b_saveaddr;
3503 * print out statistics from the current status of the buffer pool
3504 * this can be toggeled by the system control option debug.syncprt
3513 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3514 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3516 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3518 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3521 TAILQ_FOREACH(bp, dp, b_freelist) {
3522 counts[bp->b_bufsize/PAGE_SIZE]++;
3526 printf("%s: total-%d", bname[i], count);
3527 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3529 printf(", %d-%d", j * PAGE_SIZE, counts[j]);
3535 #include "opt_ddb.h"
3537 #include <ddb/ddb.h>
3539 DB_SHOW_COMMAND(buffer, db_show_buffer)
3542 struct buf *bp = (struct buf *)addr;
3545 db_printf("usage: show buffer <addr>\n");
3549 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3550 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3551 "b_resid = %d\n, b_data = %p, "
3552 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3553 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3554 bp->b_data, bp->b_bio2.bio_offset, (bp->b_bio2.bio_next ? bp->b_bio2.bio_next->bio_offset : (off_t)-1));
3555 if (bp->b_xio.xio_npages) {
3557 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3558 bp->b_xio.xio_npages);
3559 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3561 m = bp->b_xio.xio_pages[i];
3562 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3563 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3564 if ((i + 1) < bp->b_xio.xio_npages)