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
18 * this file contains a new buffer I/O scheme implementing a coherent
19 * VM object and buffer cache scheme. Pains have been taken to make
20 * sure that the performance degradation associated with schemes such
21 * as this is not realized.
23 * Author: John S. Dyson
24 * Significant help during the development and debugging phases
25 * had been provided by David Greenman, also of the FreeBSD core team.
27 * see man buf(9) for more info.
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/sysctl.h>
35 #include <sys/kthread.h>
36 #include <sys/vnode.h>
37 #include <sys/vmmeter.h>
40 #include <vm/vm_param.h>
41 #include <vm/vm_kern.h>
42 #include <vm/vm_pageout.h>
43 #include <vm/vm_page.h>
44 #include <vm/vm_object.h>
45 #include <vm/vm_extern.h>
46 #include <vm/vm_map.h>
48 #include <sys/mount.h>
49 #include <sys/malloc.h>
50 #include <sys/resourcevar.h>
53 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
55 struct bio_ops bioops; /* I/O operation notification */
57 struct buf *buf; /* buffer header pool */
58 struct swqueue bswlist;
60 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
62 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
64 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
65 int pageno, vm_page_t m);
66 static void vfs_clean_pages(struct buf * bp);
67 static void vfs_setdirty(struct buf *bp);
68 static void vfs_vmio_release(struct buf *bp);
69 static int flushbufqueues(void);
71 static int bd_request;
73 static void buf_daemon __P((void));
75 * bogus page -- for I/O to/from partially complete buffers
76 * this is a temporary solution to the problem, but it is not
77 * really that bad. it would be better to split the buffer
78 * for input in the case of buffers partially already in memory,
79 * but the code is intricate enough already.
83 int vmiodirenable = FALSE;
84 int buf_maxio = DFLTPHYS;
85 static vm_offset_t bogus_offset;
87 static int bufspace, maxbufspace, vmiospace,
88 bufmallocspace, maxbufmallocspace, hibufspace;
90 static int needsbuffer;
91 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
92 static int numfreebuffers, lofreebuffers, hifreebuffers;
93 static int getnewbufcalls;
94 static int getnewbufrestarts;
95 static int kvafreespace;
97 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD,
98 &numdirtybuffers, 0, "");
99 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW,
100 &lodirtybuffers, 0, "");
101 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW,
102 &hidirtybuffers, 0, "");
103 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD,
104 &numfreebuffers, 0, "");
105 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW,
106 &lofreebuffers, 0, "");
107 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW,
108 &hifreebuffers, 0, "");
109 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD,
110 &runningbufspace, 0, "");
111 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RW,
112 &maxbufspace, 0, "");
113 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD,
115 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD,
117 SYSCTL_INT(_vfs, OID_AUTO, maxbdrun, CTLFLAG_RW,
119 SYSCTL_INT(_vfs, OID_AUTO, vmiospace, CTLFLAG_RD,
121 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW,
122 &maxbufmallocspace, 0, "");
123 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD,
124 &bufmallocspace, 0, "");
125 SYSCTL_INT(_vfs, OID_AUTO, kvafreespace, CTLFLAG_RD,
126 &kvafreespace, 0, "");
127 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW,
128 &getnewbufcalls, 0, "");
129 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW,
130 &getnewbufrestarts, 0, "");
131 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW,
132 &vmiodirenable, 0, "");
135 static int bufhashmask;
136 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
137 struct bqueues bufqueues[BUFFER_QUEUES] = { { 0 } };
138 char *buf_wmesg = BUF_WMESG;
140 extern int vm_swap_size;
142 #define BUF_MAXUSE 24
144 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
145 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
146 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
147 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
148 #define VFS_BIO_NEED_KVASPACE 0x10 /* wait for buffer_map space, emerg */
151 * Buffer hash table code. Note that the logical block scans linearly, which
152 * gives us some L1 cache locality.
157 bufhash(struct vnode *vnp, daddr_t bn)
159 return(&bufhashtbl[(((uintptr_t)(vnp) >> 7) + (int)bn) & bufhashmask]);
165 * Called when kva space is potential available for recovery or when
166 * kva space is recovered in the buffer_map. This function wakes up
167 * anyone waiting for buffer_map kva space. Even though the buffer_map
168 * is larger then maxbufspace, this situation will typically occur
169 * when the buffer_map gets fragmented.
176 * If someone is waiting for KVA space, wake them up. Even
177 * though we haven't freed the kva space yet, the waiting
178 * process will be able to now.
180 if (needsbuffer & VFS_BIO_NEED_KVASPACE) {
181 needsbuffer &= ~VFS_BIO_NEED_KVASPACE;
182 wakeup(&needsbuffer);
189 * If someone is blocked due to there being too many dirty buffers,
190 * and numdirtybuffers is now reasonable, wake them up.
196 if (numdirtybuffers < hidirtybuffers) {
197 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
198 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
199 wakeup(&needsbuffer);
207 * Called when buffer space is potentially available for recovery or when
208 * buffer space is recovered. getnewbuf() will block on this flag when
209 * it is unable to free sufficient buffer space. Buffer space becomes
210 * recoverable when bp's get placed back in the queues.
217 * If someone is waiting for BUF space, wake them up. Even
218 * though we haven't freed the kva space yet, the waiting
219 * process will be able to now.
221 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
222 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
223 wakeup(&needsbuffer);
230 * Called when a buffer has been added to one of the free queues to
231 * account for the buffer and to wakeup anyone waiting for free buffers.
232 * This typically occurs when large amounts of metadata are being handled
233 * by the buffer cache ( else buffer space runs out first, usually ).
241 needsbuffer &= ~VFS_BIO_NEED_ANY;
242 if (numfreebuffers >= hifreebuffers)
243 needsbuffer &= ~VFS_BIO_NEED_FREE;
244 wakeup(&needsbuffer);
249 * vfs_buf_test_cache:
251 * Called when a buffer is extended. This function clears the B_CACHE
252 * bit if the newly extended portion of the buffer does not contain
257 vfs_buf_test_cache(struct buf *bp,
258 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
261 if (bp->b_flags & B_CACHE) {
262 int base = (foff + off) & PAGE_MASK;
263 if (vm_page_is_valid(m, base, size) == 0)
264 bp->b_flags &= ~B_CACHE;
270 bd_wakeup(int dirtybuflevel)
272 if (numdirtybuffers >= dirtybuflevel && bd_request == 0) {
280 * Initialize buffer headers and related structures.
284 bufhashinit(caddr_t vaddr)
286 /* first, make a null hash table */
287 for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
289 bufhashtbl = (void *)vaddr;
290 vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
301 TAILQ_INIT(&bswlist);
302 LIST_INIT(&invalhash);
303 simple_lock_init(&buftimelock);
305 for (i = 0; i <= bufhashmask; i++)
306 LIST_INIT(&bufhashtbl[i]);
308 /* next, make a null set of free lists */
309 for (i = 0; i < BUFFER_QUEUES; i++)
310 TAILQ_INIT(&bufqueues[i]);
312 /* finally, initialize each buffer header and stick on empty q */
313 for (i = 0; i < nbuf; i++) {
315 bzero(bp, sizeof *bp);
316 bp->b_flags = B_INVAL; /* we're just an empty header */
318 bp->b_rcred = NOCRED;
319 bp->b_wcred = NOCRED;
320 bp->b_qindex = QUEUE_EMPTY;
322 LIST_INIT(&bp->b_dep);
324 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
325 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
329 * maxbufspace is currently calculated to be maximally efficient
330 * when the filesystem block size is DFLTBSIZE or DFLTBSIZE*2
331 * (4K or 8K). To reduce the number of stall points our calculation
332 * is based on DFLTBSIZE which should reduce the chances of actually
333 * running out of buffer headers. The maxbufspace calculation is also
334 * based on DFLTBSIZE (4K) instead of BKVASIZE (8K) in order to
335 * reduce the chance that a KVA allocation will fail due to
336 * fragmentation. While this does not usually create a stall,
337 * the KVA map allocation/free functions are O(N) rather then O(1)
338 * so running them constantly would result in inefficient O(N*M)
339 * buffer cache operation.
341 maxbufspace = (nbuf + 8) * DFLTBSIZE;
342 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 5);
344 * Limit the amount of malloc memory since it is wired permanently into
345 * the kernel space. Even though this is accounted for in the buffer
346 * allocation, we don't want the malloced region to grow uncontrolled.
347 * The malloc scheme improves memory utilization significantly on average
348 * (small) directories.
350 maxbufmallocspace = hibufspace / 20;
353 * Reduce the chance of a deadlock occuring by limiting the number
354 * of delayed-write dirty buffers we allow to stack up.
356 lodirtybuffers = nbuf / 7 + 10;
357 hidirtybuffers = nbuf / 4 + 20;
360 * To support extreme low-memory systems, make sure hidirtybuffers cannot
361 * eat up all available buffer space. This occurs when our minimum cannot
362 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
363 * BKVASIZE'd (8K) buffers. We also reduce buf_maxio in this case (used
364 * by the clustering code) in an attempt to further reduce the load on
367 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
368 lodirtybuffers >>= 1;
369 hidirtybuffers >>= 1;
372 if (lodirtybuffers < 2) {
378 * Temporary, BKVASIZE may be manipulated soon, make sure we don't
379 * do something illegal. XXX
381 #if BKVASIZE < MAXBSIZE
382 if (buf_maxio < BKVASIZE * 2)
383 buf_maxio = BKVASIZE * 2;
385 if (buf_maxio < MAXBSIZE)
386 buf_maxio = MAXBSIZE;
390 * Try to keep the number of free buffers in the specified range,
391 * and give the syncer access to an emergency reserve.
393 lofreebuffers = nbuf / 18 + 5;
394 hifreebuffers = 2 * lofreebuffers;
395 numfreebuffers = nbuf;
398 * Maximum number of async ops initiated per buf_daemon loop. This is
399 * somewhat of a hack at the moment, we really need to limit ourselves
400 * based on the number of bytes of I/O in-transit that were initiated
403 if ((maxbdrun = nswbuf / 4) < 4)
408 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
409 bogus_page = vm_page_alloc(kernel_object,
410 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
417 * Free the kva allocation for a buffer
418 * Must be called only at splbio or higher,
419 * as this is the only locking for buffer_map.
422 bfreekva(struct buf * bp)
425 vm_map_delete(buffer_map,
426 (vm_offset_t) bp->b_kvabase,
427 (vm_offset_t) bp->b_kvabase + bp->b_kvasize
437 * Remove the buffer from the appropriate free list.
440 bremfree(struct buf * bp)
443 int old_qindex = bp->b_qindex;
445 if (bp->b_qindex != QUEUE_NONE) {
446 if (bp->b_qindex == QUEUE_EMPTYKVA) {
447 kvafreespace -= bp->b_kvasize;
449 KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
450 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
451 bp->b_qindex = QUEUE_NONE;
452 runningbufspace += bp->b_bufsize;
454 #if !defined(MAX_PERF)
455 if (BUF_REFCNT(bp) <= 1)
456 panic("bremfree: removing a buffer not on a queue");
461 * Fixup numfreebuffers count. If the buffer is invalid or not
462 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
463 * the buffer was free and we must decrement numfreebuffers.
465 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
482 * Get a buffer with the specified data. Look in the cache first. We
483 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
484 * is set, the buffer is valid and we do not have to do anything ( see
488 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
493 bp = getblk(vp, blkno, size, 0, 0);
496 /* if not found in cache, do some I/O */
497 if ((bp->b_flags & B_CACHE) == 0) {
499 curproc->p_stats->p_ru.ru_inblock++;
500 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
501 bp->b_flags |= B_READ;
502 bp->b_flags &= ~(B_ERROR | B_INVAL);
503 if (bp->b_rcred == NOCRED) {
508 vfs_busy_pages(bp, 0);
509 VOP_STRATEGY(vp, bp);
510 return (biowait(bp));
516 * Operates like bread, but also starts asynchronous I/O on
517 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
518 * to initiating I/O . If B_CACHE is set, the buffer is valid
519 * and we do not have to do anything.
522 breadn(struct vnode * vp, daddr_t blkno, int size,
523 daddr_t * rablkno, int *rabsize,
524 int cnt, struct ucred * cred, struct buf ** bpp)
526 struct buf *bp, *rabp;
528 int rv = 0, readwait = 0;
530 *bpp = bp = getblk(vp, blkno, size, 0, 0);
532 /* if not found in cache, do some I/O */
533 if ((bp->b_flags & B_CACHE) == 0) {
535 curproc->p_stats->p_ru.ru_inblock++;
536 bp->b_flags |= B_READ;
537 bp->b_flags &= ~(B_ERROR | B_INVAL);
538 if (bp->b_rcred == NOCRED) {
543 vfs_busy_pages(bp, 0);
544 VOP_STRATEGY(vp, bp);
548 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
549 if (inmem(vp, *rablkno))
551 rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
553 if ((rabp->b_flags & B_CACHE) == 0) {
555 curproc->p_stats->p_ru.ru_inblock++;
556 rabp->b_flags |= B_READ | B_ASYNC;
557 rabp->b_flags &= ~(B_ERROR | B_INVAL);
558 if (rabp->b_rcred == NOCRED) {
561 rabp->b_rcred = cred;
563 vfs_busy_pages(rabp, 0);
565 VOP_STRATEGY(vp, rabp);
578 * Write, release buffer on completion. (Done by iodone
579 * if async). Do not bother writing anything if the buffer
582 * Note that we set B_CACHE here, indicating that buffer is
583 * fully valid and thus cacheable. This is true even of NFS
584 * now so we set it generally. This could be set either here
585 * or in biodone() since the I/O is synchronous. We put it
589 bwrite(struct buf * bp)
595 if (bp->b_flags & B_INVAL) {
600 oldflags = bp->b_flags;
602 #if !defined(MAX_PERF)
603 if (BUF_REFCNT(bp) == 0)
604 panic("bwrite: buffer is not busy???");
609 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
610 bp->b_flags |= B_WRITEINPROG | B_CACHE;
612 bp->b_vp->v_numoutput++;
613 vfs_busy_pages(bp, 1);
615 curproc->p_stats->p_ru.ru_oublock++;
617 if (oldflags & B_ASYNC)
619 VOP_STRATEGY(bp->b_vp, bp);
622 * Collect statistics on synchronous and asynchronous writes.
623 * Writes to block devices are charged to their associated
624 * filesystem (if any).
626 if ((vp = bp->b_vp) != NULL) {
627 if (vp->v_type == VBLK)
628 mp = vp->v_specmountpoint;
632 if ((oldflags & B_ASYNC) == 0)
633 mp->mnt_stat.f_syncwrites++;
635 mp->mnt_stat.f_asyncwrites++;
639 if ((oldflags & B_ASYNC) == 0) {
640 int rtval = biowait(bp);
649 * Delayed write. (Buffer is marked dirty). Do not bother writing
650 * anything if the buffer is marked invalid.
652 * Note that since the buffer must be completely valid, we can safely
653 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
654 * biodone() in order to prevent getblk from writing the buffer
658 bdwrite(struct buf * bp)
660 #if !defined(MAX_PERF)
661 if (BUF_REFCNT(bp) == 0)
662 panic("bdwrite: buffer is not busy");
665 if (bp->b_flags & B_INVAL) {
672 * Set B_CACHE, indicating that the buffer is fully valid. This is
673 * true even of NFS now.
675 bp->b_flags |= B_CACHE;
678 * This bmap keeps the system from needing to do the bmap later,
679 * perhaps when the system is attempting to do a sync. Since it
680 * is likely that the indirect block -- or whatever other datastructure
681 * that the filesystem needs is still in memory now, it is a good
682 * thing to do this. Note also, that if the pageout daemon is
683 * requesting a sync -- there might not be enough memory to do
684 * the bmap then... So, this is important to do.
686 if (bp->b_lblkno == bp->b_blkno) {
687 VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
691 * Set the *dirty* buffer range based upon the VM system dirty pages.
696 * We need to do this here to satisfy the vnode_pager and the
697 * pageout daemon, so that it thinks that the pages have been
698 * "cleaned". Note that since the pages are in a delayed write
699 * buffer -- the VFS layer "will" see that the pages get written
700 * out on the next sync, or perhaps the cluster will be completed.
706 * Wakeup the buffer flushing daemon if we have saturated the
710 bd_wakeup(hidirtybuffers);
713 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
714 * due to the softdep code.
721 * Turn buffer into delayed write request. We must clear B_READ and
722 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
723 * itself to properly update it in the dirty/clean lists. We mark it
724 * B_DONE to ensure that any asynchronization of the buffer properly
725 * clears B_DONE ( else a panic will occur later ).
727 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
728 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
729 * should only be called if the buffer is known-good.
731 * Since the buffer is not on a queue, we do not update the numfreebuffers
734 * Must be called at splbio().
735 * The buffer must be on QUEUE_NONE.
741 KASSERT(bp->b_qindex == QUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
742 bp->b_flags &= ~(B_READ|B_RELBUF);
744 if ((bp->b_flags & B_DELWRI) == 0) {
745 bp->b_flags |= B_DONE | B_DELWRI;
746 reassignbuf(bp, bp->b_vp);
748 bd_wakeup(hidirtybuffers);
755 * Clear B_DELWRI for buffer.
757 * Since the buffer is not on a queue, we do not update the numfreebuffers
760 * Must be called at splbio().
761 * The buffer must be on QUEUE_NONE.
768 KASSERT(bp->b_qindex == QUEUE_NONE, ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
770 if (bp->b_flags & B_DELWRI) {
771 bp->b_flags &= ~B_DELWRI;
772 reassignbuf(bp, bp->b_vp);
781 * Asynchronous write. Start output on a buffer, but do not wait for
782 * it to complete. The buffer is released when the output completes.
784 * bwrite() ( or the VOP routine anyway ) is responsible for handling
785 * B_INVAL buffers. Not us.
788 bawrite(struct buf * bp)
790 bp->b_flags |= B_ASYNC;
791 (void) VOP_BWRITE(bp->b_vp, bp);
797 * Ordered write. Start output on a buffer, and flag it so that the
798 * device will write it in the order it was queued. The buffer is
799 * released when the output completes. bwrite() ( or the VOP routine
800 * anyway ) is responsible for handling B_INVAL buffers.
803 bowrite(struct buf * bp)
805 bp->b_flags |= B_ORDERED | B_ASYNC;
806 return (VOP_BWRITE(bp->b_vp, bp));
812 * Called prior to the locking of any vnodes when we are expecting to
813 * write. We do not want to starve the buffer cache with too many
814 * dirty buffers so we block here. By blocking prior to the locking
815 * of any vnodes we attempt to avoid the situation where a locked vnode
816 * prevents the various system daemons from flushing related buffers.
822 int twenty = (hidirtybuffers - lodirtybuffers) / 5;
824 if (numdirtybuffers > hidirtybuffers + twenty) {
828 while (numdirtybuffers > hidirtybuffers) {
829 bd_wakeup(hidirtybuffers);
830 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
831 tsleep(&needsbuffer, (PRIBIO + 4), "flswai", 0);
840 * Release a busy buffer and, if requested, free its resources. The
841 * buffer will be stashed in the appropriate bufqueue[] allowing it
842 * to be accessed later as a cache entity or reused for other purposes.
845 brelse(struct buf * bp)
850 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
854 if (bp->b_flags & B_LOCKED)
855 bp->b_flags &= ~B_ERROR;
857 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
859 * Failed write, redirty. Must clear B_ERROR to prevent
860 * pages from being scrapped. If B_INVAL is set then
861 * this case is not run and the next case is run to
862 * destroy the buffer. B_INVAL can occur if the buffer
863 * is outside the range supported by the underlying device.
865 bp->b_flags &= ~B_ERROR;
867 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
868 (bp->b_bufsize <= 0)) {
870 * Either a failed I/O or we were asked to free or not
873 bp->b_flags |= B_INVAL;
874 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
875 (*bioops.io_deallocate)(bp);
876 if (bp->b_flags & B_DELWRI) {
880 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
881 if ((bp->b_flags & B_VMIO) == 0) {
890 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
891 * is called with B_DELWRI set, the underlying pages may wind up
892 * getting freed causing a previous write (bdwrite()) to get 'lost'
893 * because pages associated with a B_DELWRI bp are marked clean.
895 * We still allow the B_INVAL case to call vfs_vmio_release(), even
896 * if B_DELWRI is set.
899 if (bp->b_flags & B_DELWRI)
900 bp->b_flags &= ~B_RELBUF;
903 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
904 * constituted, not even NFS buffers now. Two flags effect this. If
905 * B_INVAL, the struct buf is invalidated but the VM object is kept
906 * around ( i.e. so it is trivial to reconstitute the buffer later ).
908 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
909 * invalidated. B_ERROR cannot be set for a failed write unless the
910 * buffer is also B_INVAL because it hits the re-dirtying code above.
912 * Normally we can do this whether a buffer is B_DELWRI or not. If
913 * the buffer is an NFS buffer, it is tracking piecemeal writes or
914 * the commit state and we cannot afford to lose the buffer.
916 if ((bp->b_flags & B_VMIO)
917 && !(bp->b_vp->v_tag == VT_NFS &&
918 bp->b_vp->v_type != VBLK &&
919 (bp->b_flags & B_DELWRI))
932 * Get the base offset and length of the buffer. Note that
933 * for block sizes that are less then PAGE_SIZE, the b_data
934 * base of the buffer does not represent exactly b_offset and
935 * neither b_offset nor b_size are necessarily page aligned.
936 * Instead, the starting position of b_offset is:
938 * b_data + (b_offset & PAGE_MASK)
940 * block sizes less then DEV_BSIZE (usually 512) are not
941 * supported due to the page granularity bits (m->valid,
944 * See man buf(9) for more information
947 resid = bp->b_bufsize;
950 for (i = 0; i < bp->b_npages; i++) {
952 vm_page_flag_clear(m, PG_ZERO);
953 if (m == bogus_page) {
955 obj = (vm_object_t) vp->v_object;
956 poff = OFF_TO_IDX(bp->b_offset);
958 for (j = i; j < bp->b_npages; j++) {
960 if (m == bogus_page) {
961 m = vm_page_lookup(obj, poff + j);
962 #if !defined(MAX_PERF)
964 panic("brelse: page missing\n");
971 if ((bp->b_flags & B_INVAL) == 0) {
972 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
975 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
976 int poffset = foff & PAGE_MASK;
977 int presid = resid > (PAGE_SIZE - poffset) ?
978 (PAGE_SIZE - poffset) : resid;
980 KASSERT(presid >= 0, ("brelse: extra page"));
981 vm_page_set_invalid(m, poffset, presid);
983 resid -= PAGE_SIZE - (foff & PAGE_MASK);
984 foff = (foff + PAGE_SIZE) & ~PAGE_MASK;
987 if (bp->b_flags & (B_INVAL | B_RELBUF))
988 vfs_vmio_release(bp);
990 } else if (bp->b_flags & B_VMIO) {
992 if (bp->b_flags & (B_INVAL | B_RELBUF))
993 vfs_vmio_release(bp);
997 #if !defined(MAX_PERF)
998 if (bp->b_qindex != QUEUE_NONE)
999 panic("brelse: free buffer onto another queue???");
1001 if (BUF_REFCNT(bp) > 1) {
1002 /* Temporary panic to verify exclusive locking */
1003 /* This panic goes away when we allow shared refs */
1004 panic("brelse: multiple refs");
1005 /* do not release to free list */
1013 /* buffers with no memory */
1014 if (bp->b_bufsize == 0) {
1015 bp->b_flags |= B_INVAL;
1016 if (bp->b_kvasize) {
1017 bp->b_qindex = QUEUE_EMPTYKVA;
1020 bp->b_qindex = QUEUE_EMPTY;
1022 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1023 LIST_REMOVE(bp, b_hash);
1024 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1026 kvafreespace += bp->b_kvasize;
1027 /* buffers with junk contents */
1028 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1029 bp->b_flags |= B_INVAL;
1030 bp->b_qindex = QUEUE_CLEAN;
1033 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1034 LIST_REMOVE(bp, b_hash);
1035 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1038 /* buffers that are locked */
1039 } else if (bp->b_flags & B_LOCKED) {
1040 bp->b_qindex = QUEUE_LOCKED;
1041 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1043 /* remaining buffers */
1045 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1046 case B_DELWRI | B_AGE:
1047 bp->b_qindex = QUEUE_DIRTY;
1048 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1051 bp->b_qindex = QUEUE_DIRTY;
1052 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1055 bp->b_qindex = QUEUE_CLEAN;
1056 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1061 bp->b_qindex = QUEUE_CLEAN;
1062 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1070 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1071 * on the correct queue.
1073 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI)) {
1074 bp->b_flags &= ~B_DELWRI;
1079 runningbufspace -= bp->b_bufsize;
1082 * Fixup numfreebuffers count. The bp is on an appropriate queue
1083 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1084 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1085 * if B_INVAL is set ).
1088 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1092 * Something we can maybe free.
1102 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1107 * Release a buffer back to the appropriate queue but do not try to free
1110 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1111 * biodone() to requeue an async I/O on completion. It is also used when
1112 * known good buffers need to be requeued but we think we may need the data
1116 bqrelse(struct buf * bp)
1122 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1124 #if !defined(MAX_PERF)
1125 if (bp->b_qindex != QUEUE_NONE)
1126 panic("bqrelse: free buffer onto another queue???");
1128 if (BUF_REFCNT(bp) > 1) {
1129 /* do not release to free list */
1130 panic("bqrelse: multiple refs");
1135 if (bp->b_flags & B_LOCKED) {
1136 bp->b_flags &= ~B_ERROR;
1137 bp->b_qindex = QUEUE_LOCKED;
1138 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1139 /* buffers with stale but valid contents */
1140 } else if (bp->b_flags & B_DELWRI) {
1141 bp->b_qindex = QUEUE_DIRTY;
1142 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1144 bp->b_qindex = QUEUE_CLEAN;
1145 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1148 runningbufspace -= bp->b_bufsize;
1150 if ((bp->b_flags & B_LOCKED) == 0 &&
1151 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1156 * Something we can maybe wakeup
1158 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1163 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1168 vfs_vmio_release(bp)
1175 for (i = 0; i < bp->b_npages; i++) {
1177 bp->b_pages[i] = NULL;
1179 * In order to keep page LRU ordering consistent, put
1180 * everything on the inactive queue.
1182 vm_page_unwire(m, 0);
1184 * We don't mess with busy pages, it is
1185 * the responsibility of the process that
1186 * busied the pages to deal with them.
1188 if ((m->flags & PG_BUSY) || (m->busy != 0))
1191 if (m->wire_count == 0) {
1192 vm_page_flag_clear(m, PG_ZERO);
1194 * Might as well free the page if we can and it has
1197 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid && m->hold_count == 0) {
1199 vm_page_protect(m, VM_PROT_NONE);
1204 bufspace -= bp->b_bufsize;
1205 vmiospace -= bp->b_bufsize;
1206 runningbufspace -= bp->b_bufsize;
1208 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1213 bp->b_flags &= ~B_VMIO;
1219 * Check to see if a block is currently memory resident.
1222 gbincore(struct vnode * vp, daddr_t blkno)
1225 struct bufhashhdr *bh;
1227 bh = bufhash(vp, blkno);
1229 /* Search hash chain */
1230 LIST_FOREACH(bp, bh, b_hash) {
1232 if (bp->b_vp == vp && bp->b_lblkno == blkno &&
1233 (bp->b_flags & B_INVAL) == 0) {
1243 * Implement clustered async writes for clearing out B_DELWRI buffers.
1244 * This is much better then the old way of writing only one buffer at
1245 * a time. Note that we may not be presented with the buffers in the
1246 * correct order, so we search for the cluster in both directions.
1249 vfs_bio_awrite(struct buf * bp)
1253 daddr_t lblkno = bp->b_lblkno;
1254 struct vnode *vp = bp->b_vp;
1264 * right now we support clustered writing only to regular files. If
1265 * we find a clusterable block we could be in the middle of a cluster
1266 * rather then at the beginning.
1268 if ((vp->v_type == VREG) &&
1269 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1270 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1272 size = vp->v_mount->mnt_stat.f_iosize;
1273 maxcl = MAXPHYS / size;
1275 for (i = 1; i < maxcl; i++) {
1276 if ((bpa = gbincore(vp, lblkno + i)) &&
1277 BUF_REFCNT(bpa) == 0 &&
1278 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1279 (B_DELWRI | B_CLUSTEROK)) &&
1280 (bpa->b_bufsize == size)) {
1281 if ((bpa->b_blkno == bpa->b_lblkno) ||
1283 bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1289 for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1290 if ((bpa = gbincore(vp, lblkno - j)) &&
1291 BUF_REFCNT(bpa) == 0 &&
1292 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1293 (B_DELWRI | B_CLUSTEROK)) &&
1294 (bpa->b_bufsize == size)) {
1295 if ((bpa->b_blkno == bpa->b_lblkno) ||
1297 bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1306 * this is a possible cluster write
1309 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1315 BUF_LOCK(bp, LK_EXCLUSIVE);
1317 bp->b_flags |= B_ASYNC;
1321 * default (old) behavior, writing out only one block
1323 * XXX returns b_bufsize instead of b_bcount for nwritten?
1325 nwritten = bp->b_bufsize;
1326 (void) VOP_BWRITE(bp->b_vp, bp);
1334 * Find and initialize a new buffer header, freeing up existing buffers
1335 * in the bufqueues as necessary. The new buffer is returned locked.
1337 * Important: B_INVAL is not set. If the caller wishes to throw the
1338 * buffer away, the caller must set B_INVAL prior to calling brelse().
1341 * We have insufficient buffer headers
1342 * We have insufficient buffer space
1343 * buffer_map is too fragmented ( space reservation fails )
1344 * If we have to flush dirty buffers ( but we try to avoid this )
1346 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1347 * Instead we ask the buf daemon to do it for us. We attempt to
1348 * avoid piecemeal wakeups of the pageout daemon.
1352 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1362 --getnewbufrestarts;
1364 ++getnewbufrestarts;
1367 * Calculate whether we are out of buffer space. This state is
1368 * recalculated on every restart. If we are out of space, we
1369 * have to turn off defragmentation. Setting defrag to -1 when
1370 * outofspace is positive means "defrag while freeing buffers".
1371 * The looping conditional will be muffed up if defrag is left
1372 * positive when outofspace is positive.
1377 if (bufspace >= hibufspace) {
1378 if ((curproc && (curproc->p_flag & P_BUFEXHAUST) == 0) ||
1379 bufspace >= maxbufspace) {
1387 * defrag state is semi-persistant. 1 means we are flagged for
1388 * defragging. -1 means we actually defragged something.
1393 * Setup for scan. If we do not have enough free buffers,
1394 * we setup a degenerate case that immediately fails. Note
1395 * that if we are specially marked process, we are allowed to
1396 * dip into our reserves.
1398 * Normally we want to find an EMPTYKVA buffer. That is, a
1399 * buffer with kva already allocated. If there are no EMPTYKVA
1400 * buffers we back up to the truely EMPTY buffers. When defragging
1401 * we do not bother backing up since we have to locate buffers with
1402 * kva to defrag. If we are out of space we skip both EMPTY and
1403 * EMPTYKVA and dig right into the CLEAN queue.
1405 * In this manner we avoid scanning unnecessary buffers. It is very
1406 * important for us to do this because the buffer cache is almost
1407 * constantly out of space or in need of defragmentation.
1410 if (curproc && (curproc->p_flag & P_BUFEXHAUST) == 0 &&
1411 numfreebuffers < lofreebuffers) {
1412 nqindex = QUEUE_CLEAN;
1415 nqindex = QUEUE_EMPTYKVA;
1416 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1419 nqindex = QUEUE_EMPTY;
1420 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1423 if (outofspace || nbp == NULL) {
1424 nqindex = QUEUE_CLEAN;
1425 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1430 * Run scan, possibly freeing data and/or kva mappings on the fly
1434 while ((bp = nbp) != NULL) {
1435 int qindex = nqindex;
1438 * Calculate next bp ( we can only use it if we do not block
1439 * or do other fancy things ).
1441 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1444 nqindex = QUEUE_EMPTYKVA;
1445 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1448 case QUEUE_EMPTYKVA:
1449 nqindex = QUEUE_CLEAN;
1450 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1464 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1467 * Note: we no longer distinguish between VMIO and non-VMIO
1471 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1474 * If we are defragging and the buffer isn't useful for fixing
1475 * that problem we continue. If we are out of space and the
1476 * buffer isn't useful for fixing that problem we continue.
1479 if (defrag > 0 && bp->b_kvasize == 0)
1481 if (outofspace > 0 && bp->b_bufsize == 0)
1485 * Start freeing the bp. This is somewhat involved. nbp
1486 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1489 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1490 panic("getnewbuf: locked buf");
1493 if (qindex == QUEUE_CLEAN) {
1494 if (bp->b_flags & B_VMIO) {
1495 bp->b_flags &= ~B_ASYNC;
1496 vfs_vmio_release(bp);
1503 * NOTE: nbp is now entirely invalid. We can only restart
1504 * the scan from this point on.
1506 * Get the rest of the buffer freed up. b_kva* is still
1507 * valid after this operation.
1510 if (bp->b_rcred != NOCRED) {
1511 crfree(bp->b_rcred);
1512 bp->b_rcred = NOCRED;
1514 if (bp->b_wcred != NOCRED) {
1515 crfree(bp->b_wcred);
1516 bp->b_wcred = NOCRED;
1518 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1519 (*bioops.io_deallocate)(bp);
1520 LIST_REMOVE(bp, b_hash);
1521 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1529 bp->b_blkno = bp->b_lblkno = 0;
1530 bp->b_offset = NOOFFSET;
1536 bp->b_dirtyoff = bp->b_dirtyend = 0;
1538 LIST_INIT(&bp->b_dep);
1541 * Ok, now that we have a free buffer, if we are defragging
1542 * we have to recover the kvaspace. If we are out of space
1543 * we have to free the buffer (which we just did), but we
1544 * do not have to recover kva space unless we hit a defrag
1545 * hicup. Being able to avoid freeing the kva space leads
1546 * to a significant reduction in overhead.
1551 bp->b_flags |= B_INVAL;
1557 if (outofspace > 0) {
1559 bp->b_flags |= B_INVAL;
1573 * If we exhausted our list, sleep as appropriate. We may have to
1574 * wakeup various daemons and write out some dirty buffers.
1576 * Generally we are sleeping due to insufficient buffer space.
1584 flags = VFS_BIO_NEED_KVASPACE;
1586 } else if (outofspace > 0) {
1588 flags = VFS_BIO_NEED_BUFSPACE;
1591 flags = VFS_BIO_NEED_ANY;
1596 (void) speedup_syncer();
1597 needsbuffer |= flags;
1598 while (needsbuffer & flags) {
1599 if (tsleep(&needsbuffer, (PRIBIO + 4) | slpflag,
1605 * We finally have a valid bp. We aren't quite out of the
1606 * woods, we still have to reserve kva space.
1608 vm_offset_t addr = 0;
1610 maxsize = (maxsize + PAGE_MASK) & ~PAGE_MASK;
1612 if (maxsize != bp->b_kvasize) {
1615 if (vm_map_findspace(buffer_map,
1616 vm_map_min(buffer_map), maxsize, &addr)) {
1618 * Uh oh. Buffer map is to fragmented. Try
1623 bp->b_flags |= B_INVAL;
1628 * Uh oh. We couldn't seem to defragment
1630 panic("getnewbuf: unreachable code reached");
1634 vm_map_insert(buffer_map, NULL, 0,
1635 addr, addr + maxsize,
1636 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1638 bp->b_kvabase = (caddr_t) addr;
1639 bp->b_kvasize = maxsize;
1641 bp->b_data = bp->b_kvabase;
1649 * Wait for sufficient free buffers. Only called from normal processes.
1653 waitfreebuffers(int slpflag, int slptimeo)
1655 while (numfreebuffers < hifreebuffers) {
1656 if (numfreebuffers >= hifreebuffers)
1658 needsbuffer |= VFS_BIO_NEED_FREE;
1659 if (tsleep(&needsbuffer, (PRIBIO + 4)|slpflag, "biofre", slptimeo))
1667 * buffer flushing daemon. Buffers are normally flushed by the
1668 * update daemon but if it cannot keep up this process starts to
1669 * take the load in an attempt to prevent getnewbuf() from blocking.
1672 static struct proc *bufdaemonproc;
1673 static int bd_interval;
1674 static int bd_flushto;
1676 static struct kproc_desc buf_kp = {
1681 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1688 * This process is allowed to take the buffer cache to the limit
1690 curproc->p_flag |= P_BUFEXHAUST;
1693 bd_interval = 5 * hz; /* dynamically adjusted */
1694 bd_flushto = hidirtybuffers; /* dynamically adjusted */
1700 * Do the flush. Limit the number of buffers we flush in one
1701 * go. The failure condition occurs when processes are writing
1702 * buffers faster then we can dispose of them. In this case
1703 * we may be flushing so often that the previous set of flushes
1704 * have not had time to complete, causing us to run out of
1705 * physical buffers and block.
1708 int runcount = maxbdrun;
1710 while (numdirtybuffers > bd_flushto && runcount) {
1712 if (flushbufqueues() == 0)
1718 * If nobody is requesting anything we sleep
1720 if (bd_request == 0)
1721 tsleep(&bd_request, PVM, "psleep", bd_interval);
1724 * We calculate how much to add or subtract from bd_flushto
1725 * and bd_interval based on how far off we are from the
1726 * optimal number of dirty buffers, which is 20% below the
1727 * hidirtybuffers mark. We cannot use hidirtybuffers straight
1728 * because being right on the mark will cause getnewbuf()
1729 * to oscillate our wakeup.
1731 * The larger the error in either direction, the more we adjust
1732 * bd_flushto and bd_interval. The time interval is adjusted
1733 * by 2 seconds per whole-buffer-range of error. This is an
1734 * exponential convergence algorithm, with large errors
1735 * producing large changes and small errors producing small
1740 int brange = hidirtybuffers - lodirtybuffers;
1741 int middb = hidirtybuffers - brange / 5;
1742 int deltabuf = middb - numdirtybuffers;
1744 bd_flushto += deltabuf / 20;
1745 bd_interval += deltabuf * (2 * hz) / (brange * 1);
1747 if (bd_flushto < lodirtybuffers)
1748 bd_flushto = lodirtybuffers;
1749 if (bd_flushto > hidirtybuffers)
1750 bd_flushto = hidirtybuffers;
1751 if (bd_interval < hz / 10)
1752 bd_interval = hz / 10;
1753 if (bd_interval > 5 * hz)
1754 bd_interval = 5 * hz;
1761 * Try to flush a buffer in the dirty queue. We must be careful to
1762 * free up B_INVAL buffers instead of write them, which NFS is
1763 * particularly sensitive to.
1767 flushbufqueues(void)
1772 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1775 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1776 if ((bp->b_flags & B_DELWRI) != 0) {
1777 if (bp->b_flags & B_INVAL) {
1778 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1779 panic("flushbufqueues: locked buf");
1789 bp = TAILQ_NEXT(bp, b_freelist);
1795 * Check to see if a block is currently memory resident.
1798 incore(struct vnode * vp, daddr_t blkno)
1803 bp = gbincore(vp, blkno);
1809 * Returns true if no I/O is needed to access the
1810 * associated VM object. This is like incore except
1811 * it also hunts around in the VM system for the data.
1815 inmem(struct vnode * vp, daddr_t blkno)
1818 vm_offset_t toff, tinc, size;
1822 if (incore(vp, blkno))
1824 if (vp->v_mount == NULL)
1826 if ((vp->v_object == NULL) || (vp->v_flag & VOBJBUF) == 0)
1831 if (size > vp->v_mount->mnt_stat.f_iosize)
1832 size = vp->v_mount->mnt_stat.f_iosize;
1833 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
1835 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
1836 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
1840 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
1841 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
1842 if (vm_page_is_valid(m,
1843 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
1852 * Sets the dirty range for a buffer based on the status of the dirty
1853 * bits in the pages comprising the buffer.
1855 * The range is limited to the size of the buffer.
1857 * This routine is primarily used by NFS, but is generalized for the
1861 vfs_setdirty(struct buf *bp)
1867 * Degenerate case - empty buffer
1870 if (bp->b_bufsize == 0)
1874 * We qualify the scan for modified pages on whether the
1875 * object has been flushed yet. The OBJ_WRITEABLE flag
1876 * is not cleared simply by protecting pages off.
1879 if ((bp->b_flags & B_VMIO) == 0)
1882 object = bp->b_pages[0]->object;
1884 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
1885 printf("Warning: object %p writeable but not mightbedirty\n", object);
1886 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
1887 printf("Warning: object %p mightbedirty but not writeable\n", object);
1889 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
1890 vm_offset_t boffset;
1891 vm_offset_t eoffset;
1894 * test the pages to see if they have been modified directly
1895 * by users through the VM system.
1897 for (i = 0; i < bp->b_npages; i++) {
1898 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
1899 vm_page_test_dirty(bp->b_pages[i]);
1903 * Calculate the encompassing dirty range, boffset and eoffset,
1904 * (eoffset - boffset) bytes.
1907 for (i = 0; i < bp->b_npages; i++) {
1908 if (bp->b_pages[i]->dirty)
1911 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
1913 for (i = bp->b_npages - 1; i >= 0; --i) {
1914 if (bp->b_pages[i]->dirty) {
1918 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
1921 * Fit it to the buffer.
1924 if (eoffset > bp->b_bcount)
1925 eoffset = bp->b_bcount;
1928 * If we have a good dirty range, merge with the existing
1932 if (boffset < eoffset) {
1933 if (bp->b_dirtyoff > boffset)
1934 bp->b_dirtyoff = boffset;
1935 if (bp->b_dirtyend < eoffset)
1936 bp->b_dirtyend = eoffset;
1944 * Get a block given a specified block and offset into a file/device.
1945 * The buffers B_DONE bit will be cleared on return, making it almost
1946 * ready for an I/O initiation. B_INVAL may or may not be set on
1947 * return. The caller should clear B_INVAL prior to initiating a
1950 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
1951 * an existing buffer.
1953 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
1954 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
1955 * and then cleared based on the backing VM. If the previous buffer is
1956 * non-0-sized but invalid, B_CACHE will be cleared.
1958 * If getblk() must create a new buffer, the new buffer is returned with
1959 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
1960 * case it is returned with B_INVAL clear and B_CACHE set based on the
1963 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
1964 * B_CACHE bit is clear.
1966 * What this means, basically, is that the caller should use B_CACHE to
1967 * determine whether the buffer is fully valid or not and should clear
1968 * B_INVAL prior to issuing a read. If the caller intends to validate
1969 * the buffer by loading its data area with something, the caller needs
1970 * to clear B_INVAL. If the caller does this without issuing an I/O,
1971 * the caller should set B_CACHE ( as an optimization ), else the caller
1972 * should issue the I/O and biodone() will set B_CACHE if the I/O was
1973 * a write attempt or if it was a successfull read. If the caller
1974 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
1975 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
1978 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
1982 struct bufhashhdr *bh;
1984 #if !defined(MAX_PERF)
1985 if (size > MAXBSIZE)
1986 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
1992 * Block if we are low on buffers. Certain processes are allowed
1993 * to completely exhaust the buffer cache.
1995 * If this check ever becomes a bottleneck it may be better to
1996 * move it into the else, when gbincore() fails. At the moment
1997 * it isn't a problem.
1999 if (!curproc || (curproc->p_flag & P_BUFEXHAUST)) {
2000 if (numfreebuffers == 0) {
2003 needsbuffer |= VFS_BIO_NEED_ANY;
2004 tsleep(&needsbuffer, (PRIBIO + 4) | slpflag, "newbuf",
2007 } else if (numfreebuffers < lofreebuffers) {
2008 waitfreebuffers(slpflag, slptimeo);
2011 if ((bp = gbincore(vp, blkno))) {
2013 * Buffer is in-core. If the buffer is not busy, it must
2017 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2018 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2019 "getblk", slpflag, slptimeo) == ENOLCK)
2022 return (struct buf *) NULL;
2026 * The buffer is locked. B_CACHE is cleared if the buffer is
2027 * invalid. Ohterwise, for a non-VMIO buffer, B_CACHE is set
2028 * and for a VMIO buffer B_CACHE is adjusted according to the
2031 if (bp->b_flags & B_INVAL)
2032 bp->b_flags &= ~B_CACHE;
2033 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2034 bp->b_flags |= B_CACHE;
2038 * check for size inconsistancies for non-VMIO case.
2041 if (bp->b_bcount != size) {
2042 if ((bp->b_flags & B_VMIO) == 0 ||
2043 (size > bp->b_kvasize)) {
2044 if (bp->b_flags & B_DELWRI) {
2045 bp->b_flags |= B_NOCACHE;
2046 VOP_BWRITE(bp->b_vp, bp);
2048 if ((bp->b_flags & B_VMIO) &&
2049 (LIST_FIRST(&bp->b_dep) == NULL)) {
2050 bp->b_flags |= B_RELBUF;
2053 bp->b_flags |= B_NOCACHE;
2054 VOP_BWRITE(bp->b_vp, bp);
2062 * If the size is inconsistant in the VMIO case, we can resize
2063 * the buffer. This might lead to B_CACHE getting set or
2064 * cleared. If the size has not changed, B_CACHE remains
2065 * unchanged from its previous state.
2068 if (bp->b_bcount != size)
2071 KASSERT(bp->b_offset != NOOFFSET,
2072 ("getblk: no buffer offset"));
2075 * A buffer with B_DELWRI set and B_CACHE clear must
2076 * be committed before we can return the buffer in
2077 * order to prevent the caller from issuing a read
2078 * ( due to B_CACHE not being set ) and overwriting
2081 * Most callers, including NFS and FFS, need this to
2082 * operate properly either because they assume they
2083 * can issue a read if B_CACHE is not set, or because
2084 * ( for example ) an uncached B_DELWRI might loop due
2085 * to softupdates re-dirtying the buffer. In the latter
2086 * case, B_CACHE is set after the first write completes,
2087 * preventing further loops.
2090 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2091 VOP_BWRITE(bp->b_vp, bp);
2096 bp->b_flags &= ~B_DONE;
2099 * Buffer is not in-core, create new buffer. The buffer
2100 * returned by getnewbuf() is locked. Note that the returned
2101 * buffer is also considered valid (not marked B_INVAL).
2103 int bsize, maxsize, vmio;
2106 if (vp->v_type == VBLK)
2108 else if (vp->v_mountedhere)
2109 bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2110 else if (vp->v_mount)
2111 bsize = vp->v_mount->mnt_stat.f_iosize;
2115 offset = (off_t)blkno * bsize;
2116 vmio = (vp->v_object != 0) && (vp->v_flag & VOBJBUF);
2117 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2118 maxsize = imax(maxsize, bsize);
2120 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2121 if (slpflag || slptimeo) {
2129 * This code is used to make sure that a buffer is not
2130 * created while the getnewbuf routine is blocked.
2131 * This can be a problem whether the vnode is locked or not.
2132 * If the buffer is created out from under us, we have to
2133 * throw away the one we just created. There is now window
2134 * race because we are safely running at splbio() from the
2135 * point of the duplicate buffer creation through to here,
2136 * and we've locked the buffer.
2138 if (gbincore(vp, blkno)) {
2139 bp->b_flags |= B_INVAL;
2145 * Insert the buffer into the hash, so that it can
2146 * be found by incore.
2148 bp->b_blkno = bp->b_lblkno = blkno;
2149 bp->b_offset = offset;
2152 LIST_REMOVE(bp, b_hash);
2153 bh = bufhash(vp, blkno);
2154 LIST_INSERT_HEAD(bh, bp, b_hash);
2157 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2158 * buffer size starts out as 0, B_CACHE will be set by
2159 * allocbuf() for the VMIO case prior to it testing the
2160 * backing store for validity.
2164 bp->b_flags |= B_VMIO;
2165 #if defined(VFS_BIO_DEBUG)
2166 if (vp->v_type != VREG && vp->v_type != VBLK)
2167 printf("getblk: vmioing file type %d???\n", vp->v_type);
2170 bp->b_flags &= ~B_VMIO;
2176 bp->b_flags &= ~B_DONE;
2182 * Get an empty, disassociated buffer of given size. The buffer is initially
2192 while ((bp = getnewbuf(0, 0, size, MAXBSIZE)) == 0);
2195 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2201 * This code constitutes the buffer memory from either anonymous system
2202 * memory (in the case of non-VMIO operations) or from an associated
2203 * VM object (in the case of VMIO operations). This code is able to
2204 * resize a buffer up or down.
2206 * Note that this code is tricky, and has many complications to resolve
2207 * deadlock or inconsistant data situations. Tread lightly!!!
2208 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2209 * the caller. Calling this code willy nilly can result in the loss of data.
2211 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2212 * B_CACHE for the non-VMIO case.
2216 allocbuf(struct buf *bp, int size)
2218 int newbsize, mbsize;
2221 #if !defined(MAX_PERF)
2222 if (BUF_REFCNT(bp) == 0)
2223 panic("allocbuf: buffer not busy");
2225 if (bp->b_kvasize < size)
2226 panic("allocbuf: buffer too small");
2229 if ((bp->b_flags & B_VMIO) == 0) {
2233 * Just get anonymous memory from the kernel. Don't
2234 * mess with B_CACHE.
2236 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2237 #if !defined(NO_B_MALLOC)
2238 if (bp->b_flags & B_MALLOC)
2242 newbsize = round_page(size);
2244 if (newbsize < bp->b_bufsize) {
2245 #if !defined(NO_B_MALLOC)
2247 * malloced buffers are not shrunk
2249 if (bp->b_flags & B_MALLOC) {
2251 bp->b_bcount = size;
2253 free(bp->b_data, M_BIOBUF);
2254 bufspace -= bp->b_bufsize;
2255 bufmallocspace -= bp->b_bufsize;
2256 runningbufspace -= bp->b_bufsize;
2259 bp->b_data = bp->b_kvabase;
2262 bp->b_flags &= ~B_MALLOC;
2269 (vm_offset_t) bp->b_data + newbsize,
2270 (vm_offset_t) bp->b_data + bp->b_bufsize);
2271 } else if (newbsize > bp->b_bufsize) {
2272 #if !defined(NO_B_MALLOC)
2274 * We only use malloced memory on the first allocation.
2275 * and revert to page-allocated memory when the buffer
2278 if ( (bufmallocspace < maxbufmallocspace) &&
2279 (bp->b_bufsize == 0) &&
2280 (mbsize <= PAGE_SIZE/2)) {
2282 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2283 bp->b_bufsize = mbsize;
2284 bp->b_bcount = size;
2285 bp->b_flags |= B_MALLOC;
2287 bufmallocspace += mbsize;
2288 runningbufspace += bp->b_bufsize;
2294 #if !defined(NO_B_MALLOC)
2296 * If the buffer is growing on its other-than-first allocation,
2297 * then we revert to the page-allocation scheme.
2299 if (bp->b_flags & B_MALLOC) {
2300 origbuf = bp->b_data;
2301 origbufsize = bp->b_bufsize;
2302 bp->b_data = bp->b_kvabase;
2303 bufspace -= bp->b_bufsize;
2304 bufmallocspace -= bp->b_bufsize;
2305 runningbufspace -= bp->b_bufsize;
2309 bp->b_flags &= ~B_MALLOC;
2310 newbsize = round_page(newbsize);
2315 (vm_offset_t) bp->b_data + bp->b_bufsize,
2316 (vm_offset_t) bp->b_data + newbsize);
2317 #if !defined(NO_B_MALLOC)
2319 bcopy(origbuf, bp->b_data, origbufsize);
2320 free(origbuf, M_BIOBUF);
2328 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2329 desiredpages = (size == 0) ? 0 :
2330 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2332 #if !defined(NO_B_MALLOC)
2333 if (bp->b_flags & B_MALLOC)
2334 panic("allocbuf: VMIO buffer can't be malloced");
2337 * Set B_CACHE initially if buffer is 0 length or will become
2340 if (size == 0 || bp->b_bufsize == 0)
2341 bp->b_flags |= B_CACHE;
2343 if (newbsize < bp->b_bufsize) {
2345 * DEV_BSIZE aligned new buffer size is less then the
2346 * DEV_BSIZE aligned existing buffer size. Figure out
2347 * if we have to remove any pages.
2349 if (desiredpages < bp->b_npages) {
2350 for (i = desiredpages; i < bp->b_npages; i++) {
2352 * the page is not freed here -- it
2353 * is the responsibility of
2354 * vnode_pager_setsize
2357 KASSERT(m != bogus_page,
2358 ("allocbuf: bogus page found"));
2359 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2362 bp->b_pages[i] = NULL;
2363 vm_page_unwire(m, 0);
2365 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2366 (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2367 bp->b_npages = desiredpages;
2369 } else if (size > bp->b_bcount) {
2371 * We are growing the buffer, possibly in a
2372 * byte-granular fashion.
2380 * Step 1, bring in the VM pages from the object,
2381 * allocating them if necessary. We must clear
2382 * B_CACHE if these pages are not valid for the
2383 * range covered by the buffer.
2389 while (bp->b_npages < desiredpages) {
2393 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2394 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2395 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL);
2398 vm_pageout_deficit += desiredpages - bp->b_npages;
2402 bp->b_flags &= ~B_CACHE;
2403 bp->b_pages[bp->b_npages] = m;
2410 * We found a page. If we have to sleep on it,
2411 * retry because it might have gotten freed out
2414 * We can only test PG_BUSY here. Blocking on
2415 * m->busy might lead to a deadlock:
2417 * vm_fault->getpages->cluster_read->allocbuf
2421 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2425 * We have a good page. Should we wakeup the
2428 if ((curproc != pageproc) &&
2429 ((m->queue - m->pc) == PQ_CACHE) &&
2430 ((cnt.v_free_count + cnt.v_cache_count) <
2431 (cnt.v_free_min + cnt.v_cache_min))) {
2432 pagedaemon_wakeup();
2434 vm_page_flag_clear(m, PG_ZERO);
2436 bp->b_pages[bp->b_npages] = m;
2441 * Step 2. We've loaded the pages into the buffer,
2442 * we have to figure out if we can still have B_CACHE
2443 * set. Note that B_CACHE is set according to the
2444 * byte-granular range ( bcount and size ), new the
2445 * aligned range ( newbsize ).
2447 * The VM test is against m->valid, which is DEV_BSIZE
2448 * aligned. Needless to say, the validity of the data
2449 * needs to also be DEV_BSIZE aligned. Note that this
2450 * fails with NFS if the server or some other client
2451 * extends the file's EOF. If our buffer is resized,
2452 * B_CACHE may remain set! XXX
2455 toff = bp->b_bcount;
2456 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2458 while ((bp->b_flags & B_CACHE) && toff < size) {
2461 if (tinc > (size - toff))
2464 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2479 * Step 3, fixup the KVM pmap. Remember that
2480 * bp->b_data is relative to bp->b_offset, but
2481 * bp->b_offset may be offset into the first page.
2484 bp->b_data = (caddr_t)
2485 trunc_page((vm_offset_t)bp->b_data);
2487 (vm_offset_t)bp->b_data,
2491 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2492 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2495 if (bp->b_flags & B_VMIO)
2496 vmiospace += (newbsize - bp->b_bufsize);
2497 bufspace += (newbsize - bp->b_bufsize);
2498 runningbufspace += (newbsize - bp->b_bufsize);
2499 if (newbsize < bp->b_bufsize)
2501 bp->b_bufsize = newbsize; /* actual buffer allocation */
2502 bp->b_bcount = size; /* requested buffer size */
2509 * Wait for buffer I/O completion, returning error status. The buffer
2510 * is left locked and B_DONE on return. B_EINTR is converted into a EINTR
2511 * error and cleared.
2514 biowait(register struct buf * bp)
2519 while ((bp->b_flags & B_DONE) == 0) {
2520 #if defined(NO_SCHEDULE_MODS)
2521 tsleep(bp, PRIBIO, "biowait", 0);
2523 if (bp->b_flags & B_READ)
2524 tsleep(bp, PRIBIO, "biord", 0);
2526 tsleep(bp, PRIBIO, "biowr", 0);
2530 if (bp->b_flags & B_EINTR) {
2531 bp->b_flags &= ~B_EINTR;
2534 if (bp->b_flags & B_ERROR) {
2535 return (bp->b_error ? bp->b_error : EIO);
2544 * Finish I/O on a buffer, optionally calling a completion function.
2545 * This is usually called from an interrupt so process blocking is
2548 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2549 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2550 * assuming B_INVAL is clear.
2552 * For the VMIO case, we set B_CACHE if the op was a read and no
2553 * read error occured, or if the op was a write. B_CACHE is never
2554 * set if the buffer is invalid or otherwise uncacheable.
2556 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2557 * initiator to leave B_INVAL set to brelse the buffer out of existance
2558 * in the biodone routine.
2561 biodone(register struct buf * bp)
2567 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2568 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2570 bp->b_flags |= B_DONE;
2572 if (bp->b_flags & B_FREEBUF) {
2578 if ((bp->b_flags & B_READ) == 0) {
2582 /* call optional completion function if requested */
2583 if (bp->b_flags & B_CALL) {
2584 bp->b_flags &= ~B_CALL;
2585 (*bp->b_iodone) (bp);
2589 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2590 (*bioops.io_complete)(bp);
2592 if (bp->b_flags & B_VMIO) {
2598 struct vnode *vp = bp->b_vp;
2602 #if defined(VFS_BIO_DEBUG)
2603 if (vp->v_usecount == 0) {
2604 panic("biodone: zero vnode ref count");
2607 if (vp->v_object == NULL) {
2608 panic("biodone: missing VM object");
2611 if ((vp->v_flag & VOBJBUF) == 0) {
2612 panic("biodone: vnode is not setup for merged cache");
2616 foff = bp->b_offset;
2617 KASSERT(bp->b_offset != NOOFFSET,
2618 ("biodone: no buffer offset"));
2620 #if !defined(MAX_PERF)
2622 panic("biodone: no object");
2625 #if defined(VFS_BIO_DEBUG)
2626 if (obj->paging_in_progress < bp->b_npages) {
2627 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
2628 obj->paging_in_progress, bp->b_npages);
2633 * Set B_CACHE if the op was a normal read and no error
2634 * occured. B_CACHE is set for writes in the b*write()
2637 iosize = bp->b_bcount - bp->b_resid;
2638 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2639 bp->b_flags |= B_CACHE;
2642 for (i = 0; i < bp->b_npages; i++) {
2645 if (m == bogus_page) {
2647 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2649 #if defined(VFS_BIO_DEBUG)
2650 printf("biodone: page disappeared\n");
2652 vm_object_pip_subtract(obj, 1);
2653 bp->b_flags &= ~B_CACHE;
2657 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2659 #if defined(VFS_BIO_DEBUG)
2660 if (OFF_TO_IDX(foff) != m->pindex) {
2662 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2663 (unsigned long)foff, m->pindex);
2666 resid = IDX_TO_OFF(m->pindex + 1) - foff;
2671 * In the write case, the valid and clean bits are
2672 * already changed correctly ( see bdwrite() ), so we
2673 * only need to do this here in the read case.
2675 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
2676 vfs_page_set_valid(bp, foff, i, m);
2678 vm_page_flag_clear(m, PG_ZERO);
2681 * when debugging new filesystems or buffer I/O methods, this
2682 * is the most common error that pops up. if you see this, you
2683 * have not set the page busy flag correctly!!!
2686 #if !defined(MAX_PERF)
2687 printf("biodone: page busy < 0, "
2688 "pindex: %d, foff: 0x(%x,%x), "
2689 "resid: %d, index: %d\n",
2690 (int) m->pindex, (int)(foff >> 32),
2691 (int) foff & 0xffffffff, resid, i);
2693 if (vp->v_type != VBLK)
2694 #if !defined(MAX_PERF)
2695 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
2696 bp->b_vp->v_mount->mnt_stat.f_iosize,
2698 bp->b_flags, bp->b_npages);
2700 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
2702 bp->b_flags, bp->b_npages);
2703 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2704 m->valid, m->dirty, m->wire_count);
2706 panic("biodone: page busy < 0\n");
2708 vm_page_io_finish(m);
2709 vm_object_pip_subtract(obj, 1);
2714 vm_object_pip_wakeupn(obj, 0);
2717 * For asynchronous completions, release the buffer now. The brelse
2718 * will do a wakeup there if necessary - so no need to do a wakeup
2719 * here in the async case. The sync case always needs to do a wakeup.
2722 if (bp->b_flags & B_ASYNC) {
2723 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
2734 * This routine is called in lieu of iodone in the case of
2735 * incomplete I/O. This keeps the busy status for pages
2739 vfs_unbusy_pages(struct buf * bp)
2743 if (bp->b_flags & B_VMIO) {
2744 struct vnode *vp = bp->b_vp;
2745 vm_object_t obj = vp->v_object;
2747 for (i = 0; i < bp->b_npages; i++) {
2748 vm_page_t m = bp->b_pages[i];
2750 if (m == bogus_page) {
2751 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
2752 #if !defined(MAX_PERF)
2754 panic("vfs_unbusy_pages: page missing\n");
2758 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2760 vm_object_pip_subtract(obj, 1);
2761 vm_page_flag_clear(m, PG_ZERO);
2762 vm_page_io_finish(m);
2764 vm_object_pip_wakeupn(obj, 0);
2769 * vfs_page_set_valid:
2771 * Set the valid bits in a page based on the supplied offset. The
2772 * range is restricted to the buffer's size.
2774 * This routine is typically called after a read completes.
2777 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
2779 vm_ooffset_t soff, eoff;
2782 * Start and end offsets in buffer. eoff - soff may not cross a
2783 * page boundry or cross the end of the buffer. The end of the
2784 * buffer, in this case, is our file EOF, not the allocation size
2788 eoff = (off + PAGE_SIZE) & ~PAGE_MASK;
2789 if (eoff > bp->b_offset + bp->b_bcount)
2790 eoff = bp->b_offset + bp->b_bcount;
2793 * Set valid range. This is typically the entire buffer and thus the
2797 vm_page_set_validclean(
2799 (vm_offset_t) (soff & PAGE_MASK),
2800 (vm_offset_t) (eoff - soff)
2806 * This routine is called before a device strategy routine.
2807 * It is used to tell the VM system that paging I/O is in
2808 * progress, and treat the pages associated with the buffer
2809 * almost as being PG_BUSY. Also the object paging_in_progress
2810 * flag is handled to make sure that the object doesn't become
2813 * Since I/O has not been initiated yet, certain buffer flags
2814 * such as B_ERROR or B_INVAL may be in an inconsistant state
2815 * and should be ignored.
2818 vfs_busy_pages(struct buf * bp, int clear_modify)
2822 if (bp->b_flags & B_VMIO) {
2823 struct vnode *vp = bp->b_vp;
2824 vm_object_t obj = vp->v_object;
2827 foff = bp->b_offset;
2828 KASSERT(bp->b_offset != NOOFFSET,
2829 ("vfs_busy_pages: no buffer offset"));
2833 for (i = 0; i < bp->b_npages; i++) {
2834 vm_page_t m = bp->b_pages[i];
2835 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
2840 for (i = 0; i < bp->b_npages; i++) {
2841 vm_page_t m = bp->b_pages[i];
2843 vm_page_flag_clear(m, PG_ZERO);
2844 if ((bp->b_flags & B_CLUSTER) == 0) {
2845 vm_object_pip_add(obj, 1);
2846 vm_page_io_start(m);
2850 * When readying a buffer for a read ( i.e
2851 * clear_modify == 0 ), it is important to do
2852 * bogus_page replacement for valid pages in
2853 * partially instantiated buffers. Partially
2854 * instantiated buffers can, in turn, occur when
2855 * reconstituting a buffer from its VM backing store
2856 * base. We only have to do this if B_CACHE is
2857 * clear ( which causes the I/O to occur in the
2858 * first place ). The replacement prevents the read
2859 * I/O from overwriting potentially dirty VM-backed
2860 * pages. XXX bogus page replacement is, uh, bogus.
2861 * It may not work properly with small-block devices.
2862 * We need to find a better way.
2865 vm_page_protect(m, VM_PROT_NONE);
2867 vfs_page_set_valid(bp, foff, i, m);
2868 else if (m->valid == VM_PAGE_BITS_ALL &&
2869 (bp->b_flags & B_CACHE) == 0) {
2870 bp->b_pages[i] = bogus_page;
2873 foff = (foff + PAGE_SIZE) & ~PAGE_MASK;
2876 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2881 * Tell the VM system that the pages associated with this buffer
2882 * are clean. This is used for delayed writes where the data is
2883 * going to go to disk eventually without additional VM intevention.
2885 * Note that while we only really need to clean through to b_bcount, we
2886 * just go ahead and clean through to b_bufsize.
2889 vfs_clean_pages(struct buf * bp)
2893 if (bp->b_flags & B_VMIO) {
2896 foff = bp->b_offset;
2897 KASSERT(bp->b_offset != NOOFFSET,
2898 ("vfs_clean_pages: no buffer offset"));
2899 for (i = 0; i < bp->b_npages; i++) {
2900 vm_page_t m = bp->b_pages[i];
2901 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~PAGE_MASK;
2902 vm_ooffset_t eoff = noff;
2904 if (eoff > bp->b_offset + bp->b_bufsize)
2905 eoff = bp->b_offset + bp->b_bufsize;
2906 vfs_page_set_valid(bp, foff, i, m);
2907 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2914 * vfs_bio_set_validclean:
2916 * Set the range within the buffer to valid and clean. The range is
2917 * relative to the beginning of the buffer, b_offset. Note that b_offset
2918 * itself may be offset from the beginning of the first page.
2922 vfs_bio_set_validclean(struct buf *bp, int base, int size)
2924 if (bp->b_flags & B_VMIO) {
2929 * Fixup base to be relative to beginning of first page.
2930 * Set initial n to be the maximum number of bytes in the
2931 * first page that can be validated.
2934 base += (bp->b_offset & PAGE_MASK);
2935 n = PAGE_SIZE - (base & PAGE_MASK);
2937 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
2938 vm_page_t m = bp->b_pages[i];
2943 vm_page_set_validclean(m, base & PAGE_MASK, n);
2954 * clear a buffer. This routine essentially fakes an I/O, so we need
2955 * to clear B_ERROR and B_INVAL.
2957 * Note that while we only theoretically need to clear through b_bcount,
2958 * we go ahead and clear through b_bufsize.
2962 vfs_bio_clrbuf(struct buf *bp) {
2965 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
2966 bp->b_flags &= ~(B_INVAL|B_ERROR);
2967 if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
2968 (bp->b_offset & PAGE_MASK) == 0) {
2969 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
2970 if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
2971 ((bp->b_pages[0]->valid & mask) != mask)) {
2972 bzero(bp->b_data, bp->b_bufsize);
2974 bp->b_pages[0]->valid |= mask;
2978 ea = sa = bp->b_data;
2979 for(i=0;i<bp->b_npages;i++,sa=ea) {
2980 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
2981 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
2982 ea = (caddr_t)(vm_offset_t)ulmin(
2983 (u_long)(vm_offset_t)ea,
2984 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
2985 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
2986 if ((bp->b_pages[i]->valid & mask) == mask)
2988 if ((bp->b_pages[i]->valid & mask) == 0) {
2989 if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
2993 for (; sa < ea; sa += DEV_BSIZE, j++) {
2994 if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
2995 (bp->b_pages[i]->valid & (1<<j)) == 0)
2996 bzero(sa, DEV_BSIZE);
2999 bp->b_pages[i]->valid |= mask;
3000 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3009 * vm_hold_load_pages and vm_hold_unload pages get pages into
3010 * a buffers address space. The pages are anonymous and are
3011 * not associated with a file object.
3014 vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3020 to = round_page(to);
3021 from = round_page(from);
3022 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3024 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3028 p = vm_page_alloc(kernel_object,
3029 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3032 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3037 p->valid = VM_PAGE_BITS_ALL;
3038 vm_page_flag_clear(p, PG_ZERO);
3039 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3040 bp->b_pages[index] = p;
3043 bp->b_npages = index;
3047 vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3051 int index, newnpages;
3053 from = round_page(from);
3054 to = round_page(to);
3055 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3057 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3058 p = bp->b_pages[index];
3059 if (p && (index < bp->b_npages)) {
3060 #if !defined(MAX_PERF)
3062 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3063 bp->b_blkno, bp->b_lblkno);
3066 bp->b_pages[index] = NULL;
3069 vm_page_unwire(p, 0);
3073 bp->b_npages = newnpages;
3077 #include "opt_ddb.h"
3079 #include <ddb/ddb.h>
3081 DB_SHOW_COMMAND(buffer, db_show_buffer)
3084 struct buf *bp = (struct buf *)addr;
3087 db_printf("usage: show buffer <addr>\n");
3091 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3092 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3093 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3094 "b_blkno = %d, b_pblkno = %d\n",
3095 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3096 major(bp->b_dev), minor(bp->b_dev),
3097 bp->b_data, bp->b_blkno, bp->b_pblkno);
3100 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3101 for (i = 0; i < bp->b_npages; i++) {
3104 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3105 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3106 if ((i + 1) < bp->b_npages)