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 * $Id: vfs_bio.c,v 1.221 1999/07/08 06:05:52 mckusick Exp $
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.
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/sysproto.h>
34 #include <sys/kernel.h>
35 #include <sys/sysctl.h>
37 #include <sys/kthread.h>
38 #include <sys/vnode.h>
39 #include <sys/vmmeter.h>
41 #include <miscfs/specfs/specdev.h>
43 #include <vm/vm_param.h>
44 #include <vm/vm_prot.h>
45 #include <vm/vm_kern.h>
46 #include <vm/vm_pageout.h>
47 #include <vm/vm_page.h>
48 #include <vm/vm_object.h>
49 #include <vm/vm_extern.h>
50 #include <vm/vm_map.h>
52 #include <sys/mount.h>
53 #include <sys/malloc.h>
54 #include <sys/resourcevar.h>
56 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
58 struct bio_ops bioops; /* I/O operation notification */
60 struct buf *buf; /* buffer header pool */
61 struct swqueue bswlist;
63 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
65 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
67 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
68 int pageno, vm_page_t m);
69 static void vfs_clean_pages(struct buf * bp);
70 static void vfs_setdirty(struct buf *bp);
71 static void vfs_vmio_release(struct buf *bp);
72 static int flushbufqueues(void);
74 static int bd_request;
76 static void buf_daemon __P((void));
78 * bogus page -- for I/O to/from partially complete buffers
79 * this is a temporary solution to the problem, but it is not
80 * really that bad. it would be better to split the buffer
81 * for input in the case of buffers partially already in memory,
82 * but the code is intricate enough already.
86 static vm_offset_t bogus_offset;
88 static int bufspace, maxbufspace, vmiospace,
89 bufmallocspace, maxbufmallocspace, hibufspace;
91 static int maxvmiobufspace;
94 static int needsbuffer;
95 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
96 static int numfreebuffers, lofreebuffers, hifreebuffers;
97 static int getnewbufcalls;
98 static int getnewbufrestarts;
99 static int kvafreespace;
101 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD,
102 &numdirtybuffers, 0, "");
103 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW,
104 &lodirtybuffers, 0, "");
105 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW,
106 &hidirtybuffers, 0, "");
107 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD,
108 &numfreebuffers, 0, "");
109 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW,
110 &lofreebuffers, 0, "");
111 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW,
112 &hifreebuffers, 0, "");
113 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD,
114 &runningbufspace, 0, "");
115 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RW,
116 &maxbufspace, 0, "");
117 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD,
119 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD,
121 SYSCTL_INT(_vfs, OID_AUTO, maxbdrun, CTLFLAG_RW,
124 SYSCTL_INT(_vfs, OID_AUTO, maxvmiobufspace, CTLFLAG_RW,
125 &maxvmiobufspace, 0, "");
127 SYSCTL_INT(_vfs, OID_AUTO, vmiospace, CTLFLAG_RD,
129 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW,
130 &maxbufmallocspace, 0, "");
131 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD,
132 &bufmallocspace, 0, "");
133 SYSCTL_INT(_vfs, OID_AUTO, kvafreespace, CTLFLAG_RD,
134 &kvafreespace, 0, "");
135 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RW,
136 &getnewbufcalls, 0, "");
137 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RW,
138 &getnewbufrestarts, 0, "");
141 static int bufhashmask;
142 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
143 struct bqueues bufqueues[BUFFER_QUEUES] = { { 0 } };
144 char *buf_wmesg = BUF_WMESG;
146 extern int vm_swap_size;
148 #define BUF_MAXUSE 24
150 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
151 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
152 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
153 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
154 #define VFS_BIO_NEED_KVASPACE 0x10 /* wait for buffer_map space, emerg */
157 * Buffer hash table code. Note that the logical block scans linearly, which
158 * gives us some L1 cache locality.
163 bufhash(struct vnode *vnp, daddr_t bn)
165 return(&bufhashtbl[(((uintptr_t)(vnp) >> 7) + (int)bn) & bufhashmask]);
171 * Called when kva space is potential available for recovery or when
172 * kva space is recovered in the buffer_map. This function wakes up
173 * anyone waiting for buffer_map kva space. Even though the buffer_map
174 * is larger then maxbufspace, this situation will typically occur
175 * when the buffer_map gets fragmented.
182 * If someone is waiting for KVA space, wake them up. Even
183 * though we haven't freed the kva space yet, the waiting
184 * process will be able to now.
186 if (needsbuffer & VFS_BIO_NEED_KVASPACE) {
187 needsbuffer &= ~VFS_BIO_NEED_KVASPACE;
188 wakeup(&needsbuffer);
195 * If someone is blocked due to there being too many dirty buffers,
196 * and numdirtybuffers is now reasonable, wake them up.
202 if (numdirtybuffers < hidirtybuffers) {
203 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
204 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
205 wakeup(&needsbuffer);
213 * Called when buffer space is potentially available for recovery or when
214 * buffer space is recovered. getnewbuf() will block on this flag when
215 * it is unable to free sufficient buffer space. Buffer space becomes
216 * recoverable when bp's get placed back in the queues.
223 * If someone is waiting for BUF space, wake them up. Even
224 * though we haven't freed the kva space yet, the waiting
225 * process will be able to now.
227 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
228 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
229 wakeup(&needsbuffer);
236 * Called when a buffer has been added to one of the free queues to
237 * account for the buffer and to wakeup anyone waiting for free buffers.
238 * This typically occurs when large amounts of metadata are being handled
239 * by the buffer cache ( else buffer space runs out first, usually ).
247 needsbuffer &= ~VFS_BIO_NEED_ANY;
248 if (numfreebuffers >= hifreebuffers)
249 needsbuffer &= ~VFS_BIO_NEED_FREE;
250 wakeup(&needsbuffer);
255 * vfs_buf_test_cache:
257 * Called when a buffer is extended. This function clears the B_CACHE
258 * bit if the newly extended portion of the buffer does not contain
263 vfs_buf_test_cache(struct buf *bp,
264 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
267 if (bp->b_flags & B_CACHE) {
268 int base = (foff + off) & PAGE_MASK;
269 if (vm_page_is_valid(m, base, size) == 0)
270 bp->b_flags &= ~B_CACHE;
276 bd_wakeup(int dirtybuflevel)
278 if (numdirtybuffers >= dirtybuflevel && bd_request == 0) {
286 * Initialize buffer headers and related structures.
290 bufhashinit(vm_offset_t vaddr)
292 /* first, make a null hash table */
293 for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
295 bufhashtbl = (void *)vaddr;
296 vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
307 TAILQ_INIT(&bswlist);
308 LIST_INIT(&invalhash);
309 simple_lock_init(&buftimelock);
311 for (i = 0; i <= bufhashmask; i++)
312 LIST_INIT(&bufhashtbl[i]);
314 /* next, make a null set of free lists */
315 for (i = 0; i < BUFFER_QUEUES; i++)
316 TAILQ_INIT(&bufqueues[i]);
318 /* finally, initialize each buffer header and stick on empty q */
319 for (i = 0; i < nbuf; i++) {
321 bzero(bp, sizeof *bp);
322 bp->b_flags = B_INVAL; /* we're just an empty header */
324 bp->b_rcred = NOCRED;
325 bp->b_wcred = NOCRED;
326 bp->b_qindex = QUEUE_EMPTY;
328 LIST_INIT(&bp->b_dep);
330 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
331 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
335 * maxbufspace is currently calculated to support all filesystem
336 * blocks to be 8K. If you happen to use a 16K filesystem, the size
337 * of the buffer cache is still the same as it would be for 8K
338 * filesystems. This keeps the size of the buffer cache "in check"
339 * for big block filesystems.
341 * maxbufspace is calculated as around 50% of the KVA available in
342 * the buffer_map ( DFLTSIZE vs BKVASIZE ), I presume to reduce the
343 * effect of fragmentation.
345 maxbufspace = (nbuf + 8) * DFLTBSIZE;
346 if ((hibufspace = maxbufspace - MAXBSIZE * 5) <= MAXBSIZE)
347 hibufspace = 3 * maxbufspace / 4;
350 * reserve 1/3 of the buffers for metadata (VDIR) which might not be VMIO'ed
352 maxvmiobufspace = 2 * hibufspace / 3;
355 * Limit the amount of malloc memory since it is wired permanently into
356 * the kernel space. Even though this is accounted for in the buffer
357 * allocation, we don't want the malloced region to grow uncontrolled.
358 * The malloc scheme improves memory utilization significantly on average
359 * (small) directories.
361 maxbufmallocspace = hibufspace / 20;
364 * Reduce the chance of a deadlock occuring by limiting the number
365 * of delayed-write dirty buffers we allow to stack up.
367 lodirtybuffers = nbuf / 7 + 10;
368 hidirtybuffers = nbuf / 4 + 20;
372 * Try to keep the number of free buffers in the specified range,
373 * and give the syncer access to an emergency reserve.
375 lofreebuffers = nbuf / 18 + 5;
376 hifreebuffers = 2 * lofreebuffers;
377 numfreebuffers = nbuf;
380 * Maximum number of async ops initiated per buf_daemon loop. This is
381 * somewhat of a hack at the moment, we really need to limit ourselves
382 * based on the number of bytes of I/O in-transit that were initiated
385 if ((maxbdrun = nswbuf / 4) < 4)
390 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
391 bogus_page = vm_page_alloc(kernel_object,
392 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
398 * Free the kva allocation for a buffer
399 * Must be called only at splbio or higher,
400 * as this is the only locking for buffer_map.
403 bfreekva(struct buf * bp)
406 vm_map_delete(buffer_map,
407 (vm_offset_t) bp->b_kvabase,
408 (vm_offset_t) bp->b_kvabase + bp->b_kvasize
418 * Remove the buffer from the appropriate free list.
421 bremfree(struct buf * bp)
424 int old_qindex = bp->b_qindex;
426 if (bp->b_qindex != QUEUE_NONE) {
427 if (bp->b_qindex == QUEUE_EMPTYKVA) {
428 kvafreespace -= bp->b_kvasize;
430 KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
431 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
432 bp->b_qindex = QUEUE_NONE;
433 runningbufspace += bp->b_bufsize;
435 #if !defined(MAX_PERF)
436 if (BUF_REFCNT(bp) <= 1)
437 panic("bremfree: removing a buffer not on a queue");
442 * Fixup numfreebuffers count. If the buffer is invalid or not
443 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
444 * the buffer was free and we must decrement numfreebuffers.
446 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
463 * Get a buffer with the specified data. Look in the cache first. We
464 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
465 * is set, the buffer is valid and we do not have to do anything ( see
469 bread(struct vnode * vp, daddr_t blkno, int size, struct ucred * cred,
474 bp = getblk(vp, blkno, size, 0, 0);
477 /* if not found in cache, do some I/O */
478 if ((bp->b_flags & B_CACHE) == 0) {
480 curproc->p_stats->p_ru.ru_inblock++;
481 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
482 bp->b_flags |= B_READ;
483 bp->b_flags &= ~(B_ERROR | B_INVAL);
484 if (bp->b_rcred == NOCRED) {
489 vfs_busy_pages(bp, 0);
490 VOP_STRATEGY(vp, bp);
491 return (biowait(bp));
497 * Operates like bread, but also starts asynchronous I/O on
498 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
499 * to initiating I/O . If B_CACHE is set, the buffer is valid
500 * and we do not have to do anything.
503 breadn(struct vnode * vp, daddr_t blkno, int size,
504 daddr_t * rablkno, int *rabsize,
505 int cnt, struct ucred * cred, struct buf ** bpp)
507 struct buf *bp, *rabp;
509 int rv = 0, readwait = 0;
511 *bpp = bp = getblk(vp, blkno, size, 0, 0);
513 /* if not found in cache, do some I/O */
514 if ((bp->b_flags & B_CACHE) == 0) {
516 curproc->p_stats->p_ru.ru_inblock++;
517 bp->b_flags |= B_READ;
518 bp->b_flags &= ~(B_ERROR | B_INVAL);
519 if (bp->b_rcred == NOCRED) {
524 vfs_busy_pages(bp, 0);
525 VOP_STRATEGY(vp, bp);
529 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
530 if (inmem(vp, *rablkno))
532 rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
534 if ((rabp->b_flags & B_CACHE) == 0) {
536 curproc->p_stats->p_ru.ru_inblock++;
537 rabp->b_flags |= B_READ | B_ASYNC;
538 rabp->b_flags &= ~(B_ERROR | B_INVAL);
539 if (rabp->b_rcred == NOCRED) {
542 rabp->b_rcred = cred;
544 vfs_busy_pages(rabp, 0);
546 VOP_STRATEGY(vp, rabp);
559 * Write, release buffer on completion. (Done by iodone
560 * if async). Do not bother writing anything if the buffer
563 * Note that we set B_CACHE here, indicating that buffer is
564 * fully valid and thus cacheable. This is true even of NFS
565 * now so we set it generally. This could be set either here
566 * or in biodone() since the I/O is synchronous. We put it
570 bwrite(struct buf * bp)
576 if (bp->b_flags & B_INVAL) {
581 oldflags = bp->b_flags;
583 #if !defined(MAX_PERF)
584 if (BUF_REFCNT(bp) == 0)
585 panic("bwrite: buffer is not busy???");
590 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
591 bp->b_flags |= B_WRITEINPROG | B_CACHE;
593 bp->b_vp->v_numoutput++;
594 vfs_busy_pages(bp, 1);
596 curproc->p_stats->p_ru.ru_oublock++;
598 if (oldflags & B_ASYNC)
600 VOP_STRATEGY(bp->b_vp, bp);
603 * Collect statistics on synchronous and asynchronous writes.
604 * Writes to block devices are charged to their associated
605 * filesystem (if any).
607 if ((vp = bp->b_vp) != NULL) {
608 if (vp->v_type == VBLK)
609 mp = vp->v_specmountpoint;
613 if ((oldflags & B_ASYNC) == 0)
614 mp->mnt_stat.f_syncwrites++;
616 mp->mnt_stat.f_asyncwrites++;
620 if ((oldflags & B_ASYNC) == 0) {
621 int rtval = biowait(bp);
630 * Delayed write. (Buffer is marked dirty). Do not bother writing
631 * anything if the buffer is marked invalid.
633 * Note that since the buffer must be completely valid, we can safely
634 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
635 * biodone() in order to prevent getblk from writing the buffer
639 bdwrite(struct buf * bp)
645 #if !defined(MAX_PERF)
646 if (BUF_REFCNT(bp) == 0)
647 panic("bdwrite: buffer is not busy");
650 if (bp->b_flags & B_INVAL) {
657 * Set B_CACHE, indicating that the buffer is fully valid. This is
658 * true even of NFS now.
660 bp->b_flags |= B_CACHE;
663 * This bmap keeps the system from needing to do the bmap later,
664 * perhaps when the system is attempting to do a sync. Since it
665 * is likely that the indirect block -- or whatever other datastructure
666 * that the filesystem needs is still in memory now, it is a good
667 * thing to do this. Note also, that if the pageout daemon is
668 * requesting a sync -- there might not be enough memory to do
669 * the bmap then... So, this is important to do.
671 if (bp->b_lblkno == bp->b_blkno) {
672 VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
676 * Set the *dirty* buffer range based upon the VM system dirty pages.
681 * We need to do this here to satisfy the vnode_pager and the
682 * pageout daemon, so that it thinks that the pages have been
683 * "cleaned". Note that since the pages are in a delayed write
684 * buffer -- the VFS layer "will" see that the pages get written
685 * out on the next sync, or perhaps the cluster will be completed.
691 * Wakeup the buffer flushing daemon if we have saturated the
695 bd_wakeup(hidirtybuffers);
698 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
699 * due to the softdep code.
703 * XXX The soft dependency code is not prepared to
704 * have I/O done when a bdwrite is requested. For
705 * now we just let the write be delayed if it is
706 * requested by the soft dependency code.
708 if ((vp = bp->b_vp) &&
709 ((vp->v_type == VBLK && vp->v_specmountpoint &&
710 (vp->v_specmountpoint->mnt_flag & MNT_SOFTDEP)) ||
711 (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SOFTDEP))))
719 * Turn buffer into delayed write request. We must clear B_READ and
720 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
721 * itself to properly update it in the dirty/clean lists. We mark it
722 * B_DONE to ensure that any asynchronization of the buffer properly
723 * clears B_DONE ( else a panic will occur later ).
725 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
726 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
727 * should only be called if the buffer is known-good.
729 * Since the buffer is not on a queue, we do not update the numfreebuffers
732 * Must be called at splbio().
733 * The buffer must be on QUEUE_NONE.
739 KASSERT(bp->b_qindex == QUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
740 bp->b_flags &= ~(B_READ|B_RELBUF);
742 if ((bp->b_flags & B_DELWRI) == 0) {
743 bp->b_flags |= B_DONE | B_DELWRI;
744 reassignbuf(bp, bp->b_vp);
746 bd_wakeup(hidirtybuffers);
753 * Clear B_DELWRI for buffer.
755 * Since the buffer is not on a queue, we do not update the numfreebuffers
758 * Must be called at splbio().
759 * The buffer must be on QUEUE_NONE.
766 KASSERT(bp->b_qindex == QUEUE_NONE, ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
768 if (bp->b_flags & B_DELWRI) {
769 bp->b_flags &= ~B_DELWRI;
770 reassignbuf(bp, bp->b_vp);
779 * Asynchronous write. Start output on a buffer, but do not wait for
780 * it to complete. The buffer is released when the output completes.
782 * bwrite() ( or the VOP routine anyway ) is responsible for handling
783 * B_INVAL buffers. Not us.
786 bawrite(struct buf * bp)
788 bp->b_flags |= B_ASYNC;
789 (void) VOP_BWRITE(bp->b_vp, bp);
795 * Ordered write. Start output on a buffer, and flag it so that the
796 * device will write it in the order it was queued. The buffer is
797 * released when the output completes. bwrite() ( or the VOP routine
798 * anyway ) is responsible for handling B_INVAL buffers.
801 bowrite(struct buf * bp)
803 bp->b_flags |= B_ORDERED | B_ASYNC;
804 return (VOP_BWRITE(bp->b_vp, bp));
810 * Called prior to the locking of any vnodes when we are expecting to
811 * write. We do not want to starve the buffer cache with too many
812 * dirty buffers so we block here. By blocking prior to the locking
813 * of any vnodes we attempt to avoid the situation where a locked vnode
814 * prevents the various system daemons from flushing related buffers.
820 int twenty = (hidirtybuffers - lodirtybuffers) / 5;
822 if (numdirtybuffers > hidirtybuffers + twenty) {
826 while (numdirtybuffers > hidirtybuffers) {
827 bd_wakeup(hidirtybuffers);
828 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
829 tsleep(&needsbuffer, (PRIBIO + 4), "flswai", 0);
838 * Release a busy buffer and, if requested, free its resources. The
839 * buffer will be stashed in the appropriate bufqueue[] allowing it
840 * to be accessed later as a cache entity or reused for other purposes.
843 brelse(struct buf * bp)
847 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
850 if (bp->b_flags & B_CLUSTER) {
858 if (bp->b_flags & B_LOCKED)
859 bp->b_flags &= ~B_ERROR;
861 if ((bp->b_flags & (B_READ | B_ERROR)) == B_ERROR) {
863 * Failed write, redirty. Must clear B_ERROR to prevent
864 * pages from being scrapped. Note: B_INVAL is ignored
865 * here but will presumably be dealt with later.
867 bp->b_flags &= ~B_ERROR;
869 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
870 (bp->b_bufsize <= 0)) {
872 * Either a failed I/O or we were asked to free or not
875 bp->b_flags |= B_INVAL;
876 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
877 (*bioops.io_deallocate)(bp);
878 if (bp->b_flags & B_DELWRI) {
882 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
883 if ((bp->b_flags & B_VMIO) == 0) {
892 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
893 * is called with B_DELWRI set, the underlying pages may wind up
894 * getting freed causing a previous write (bdwrite()) to get 'lost'
895 * because pages associated with a B_DELWRI bp are marked clean.
897 * We still allow the B_INVAL case to call vfs_vmio_release(), even
898 * if B_DELWRI is set.
901 if (bp->b_flags & B_DELWRI)
902 bp->b_flags &= ~B_RELBUF;
905 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
906 * constituted, not even NFS buffers now. Two flags effect this. If
907 * B_INVAL, the struct buf is invalidated but the VM object is kept
908 * around ( i.e. so it is trivial to reconstitute the buffer later ).
910 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
911 * invalidated. B_ERROR cannot be set for a failed write unless the
912 * buffer is also B_INVAL because it hits the re-dirtying code above.
914 * Normally we can do this whether a buffer is B_DELWRI or not. If
915 * the buffer is an NFS buffer, it is tracking piecemeal writes or
916 * the commit state and we cannot afford to lose the buffer.
918 if ((bp->b_flags & B_VMIO)
919 && !(bp->b_vp->v_tag == VT_NFS &&
920 bp->b_vp->v_type != VBLK &&
921 (bp->b_flags & B_DELWRI))
934 * Get the base offset and length of the buffer. Note that
935 * for block sizes that are less then PAGE_SIZE, the b_data
936 * base of the buffer does not represent exactly b_offset and
937 * neither b_offset nor b_size are necessarily page aligned.
938 * Instead, the starting position of b_offset is:
940 * b_data + (b_offset & PAGE_MASK)
942 * block sizes less then DEV_BSIZE (usually 512) are not
943 * supported due to the page granularity bits (m->valid,
946 * See man buf(9) for more information
949 resid = bp->b_bufsize;
952 for (i = 0; i < bp->b_npages; i++) {
954 vm_page_flag_clear(m, PG_ZERO);
955 if (m == bogus_page) {
957 obj = (vm_object_t) vp->v_object;
958 poff = OFF_TO_IDX(bp->b_offset);
960 for (j = i; j < bp->b_npages; j++) {
962 if (m == bogus_page) {
963 m = vm_page_lookup(obj, poff + j);
964 #if !defined(MAX_PERF)
966 panic("brelse: page missing\n");
973 if ((bp->b_flags & B_INVAL) == 0) {
974 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
977 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
978 int poffset = foff & PAGE_MASK;
979 int presid = resid > (PAGE_SIZE - poffset) ?
980 (PAGE_SIZE - poffset) : resid;
982 KASSERT(presid >= 0, ("brelse: extra page"));
983 vm_page_set_invalid(m, poffset, presid);
985 resid -= PAGE_SIZE - (foff & PAGE_MASK);
986 foff = (foff + PAGE_SIZE) & ~PAGE_MASK;
989 if (bp->b_flags & (B_INVAL | B_RELBUF))
990 vfs_vmio_release(bp);
992 } else if (bp->b_flags & B_VMIO) {
994 if (bp->b_flags & (B_INVAL | B_RELBUF))
995 vfs_vmio_release(bp);
999 #if !defined(MAX_PERF)
1000 if (bp->b_qindex != QUEUE_NONE)
1001 panic("brelse: free buffer onto another queue???");
1003 if (BUF_REFCNT(bp) > 1) {
1004 /* Temporary panic to verify exclusive locking */
1005 /* This panic goes away when we allow shared refs */
1006 panic("brelse: multiple refs");
1007 /* do not release to free list */
1015 /* buffers with no memory */
1016 if (bp->b_bufsize == 0) {
1017 bp->b_flags |= B_INVAL;
1019 bp->b_qindex = QUEUE_EMPTYKVA;
1021 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;
1029 /* buffers with junk contents */
1030 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1031 bp->b_flags |= B_INVAL;
1032 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);
1059 bp->b_qindex = QUEUE_CLEAN;
1060 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1066 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1067 * on the correct queue.
1069 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI)) {
1070 bp->b_flags &= ~B_DELWRI;
1075 runningbufspace -= bp->b_bufsize;
1078 * Fixup numfreebuffers count. The bp is on an appropriate queue
1079 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1080 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1081 * if B_INVAL is set ).
1084 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1088 * Something we can maybe free.
1096 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1101 * Release a buffer back to the appropriate queue but do not try to free
1104 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1105 * biodone() to requeue an async I/O on completion. It is also used when
1106 * known good buffers need to be requeued but we think we may need the data
1110 bqrelse(struct buf * bp)
1116 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1118 #if !defined(MAX_PERF)
1119 if (bp->b_qindex != QUEUE_NONE)
1120 panic("bqrelse: free buffer onto another queue???");
1122 if (BUF_REFCNT(bp) > 1) {
1123 /* do not release to free list */
1124 panic("bqrelse: multiple refs");
1129 if (bp->b_flags & B_LOCKED) {
1130 bp->b_flags &= ~B_ERROR;
1131 bp->b_qindex = QUEUE_LOCKED;
1132 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1133 /* buffers with stale but valid contents */
1134 } else if (bp->b_flags & B_DELWRI) {
1135 bp->b_qindex = QUEUE_DIRTY;
1136 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1138 bp->b_qindex = QUEUE_CLEAN;
1139 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1142 runningbufspace -= bp->b_bufsize;
1144 if ((bp->b_flags & B_LOCKED) == 0 &&
1145 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1150 * Something we can maybe wakeup
1152 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1157 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1162 vfs_vmio_release(bp)
1169 for (i = 0; i < bp->b_npages; i++) {
1171 bp->b_pages[i] = NULL;
1173 * In order to keep page LRU ordering consistent, put
1174 * everything on the inactive queue.
1176 vm_page_unwire(m, 0);
1178 * We don't mess with busy pages, it is
1179 * the responsibility of the process that
1180 * busied the pages to deal with them.
1182 if ((m->flags & PG_BUSY) || (m->busy != 0))
1185 if (m->wire_count == 0) {
1186 vm_page_flag_clear(m, PG_ZERO);
1188 * Might as well free the page if we can and it has
1191 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid && m->hold_count == 0) {
1193 vm_page_protect(m, VM_PROT_NONE);
1198 bufspace -= bp->b_bufsize;
1199 vmiospace -= bp->b_bufsize;
1200 runningbufspace -= bp->b_bufsize;
1202 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_npages);
1207 bp->b_flags &= ~B_VMIO;
1213 * Check to see if a block is currently memory resident.
1216 gbincore(struct vnode * vp, daddr_t blkno)
1219 struct bufhashhdr *bh;
1221 bh = bufhash(vp, blkno);
1224 /* Search hash chain */
1225 while (bp != NULL) {
1227 if (bp->b_vp == vp && bp->b_lblkno == blkno &&
1228 (bp->b_flags & B_INVAL) == 0) {
1231 bp = bp->b_hash.le_next;
1239 * Implement clustered async writes for clearing out B_DELWRI buffers.
1240 * This is much better then the old way of writing only one buffer at
1241 * a time. Note that we may not be presented with the buffers in the
1242 * correct order, so we search for the cluster in both directions.
1245 vfs_bio_awrite(struct buf * bp)
1249 daddr_t lblkno = bp->b_lblkno;
1250 struct vnode *vp = bp->b_vp;
1260 * right now we support clustered writing only to regular files. If
1261 * we find a clusterable block we could be in the middle of a cluster
1262 * rather then at the beginning.
1264 if ((vp->v_type == VREG) &&
1265 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1266 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1268 size = vp->v_mount->mnt_stat.f_iosize;
1269 maxcl = MAXPHYS / size;
1271 for (i = 1; i < maxcl; i++) {
1272 if ((bpa = gbincore(vp, lblkno + i)) &&
1273 BUF_REFCNT(bpa) == 0 &&
1274 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1275 (B_DELWRI | B_CLUSTEROK)) &&
1276 (bpa->b_bufsize == size)) {
1277 if ((bpa->b_blkno == bpa->b_lblkno) ||
1279 bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1285 for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1286 if ((bpa = gbincore(vp, lblkno - j)) &&
1287 BUF_REFCNT(bpa) == 0 &&
1288 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1289 (B_DELWRI | B_CLUSTEROK)) &&
1290 (bpa->b_bufsize == size)) {
1291 if ((bpa->b_blkno == bpa->b_lblkno) ||
1293 bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1302 * this is a possible cluster write
1305 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1311 BUF_LOCK(bp, LK_EXCLUSIVE);
1313 bp->b_flags |= B_ASYNC;
1317 * default (old) behavior, writing out only one block
1319 * XXX returns b_bufsize instead of b_bcount for nwritten?
1321 nwritten = bp->b_bufsize;
1322 (void) VOP_BWRITE(bp->b_vp, bp);
1330 * Find and initialize a new buffer header, freeing up existing buffers
1331 * in the bufqueues as necessary. The new buffer is returned locked.
1333 * Important: B_INVAL is not set. If the caller wishes to throw the
1334 * buffer away, the caller must set B_INVAL prior to calling brelse().
1337 * We have insufficient buffer headers
1338 * We have insufficient buffer space
1339 * buffer_map is too fragmented ( space reservation fails )
1340 * If we have to flush dirty buffers ( but we try to avoid this )
1342 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1343 * Instead we ask the buf daemon to do it for us. We attempt to
1344 * avoid piecemeal wakeups of the pageout daemon.
1348 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1358 --getnewbufrestarts;
1360 ++getnewbufrestarts;
1363 * Calculate whether we are out of buffer space. This state is
1364 * recalculated on every restart. If we are out of space, we
1365 * have to turn off defragmentation. Setting defrag to -1 when
1366 * outofspace is positive means "defrag while freeing buffers".
1367 * The looping conditional will be muffed up if defrag is left
1368 * positive when outofspace is positive.
1373 if (bufspace >= hibufspace) {
1374 if ((curproc->p_flag & P_BUFEXHAUST) == 0 ||
1375 bufspace >= maxbufspace) {
1383 * defrag state is semi-persistant. 1 means we are flagged for
1384 * defragging. -1 means we actually defragged something.
1389 * Setup for scan. If we do not have enough free buffers,
1390 * we setup a degenerate case that immediately fails. Note
1391 * that if we are specially marked process, we are allowed to
1392 * dip into our reserves.
1394 * Normally we want to find an EMPTYKVA buffer. That is, a
1395 * buffer with kva already allocated. If there are no EMPTYKVA
1396 * buffers we back up to the truely EMPTY buffers. When defragging
1397 * we do not bother backing up since we have to locate buffers with
1398 * kva to defrag. If we are out of space we skip both EMPTY and
1399 * EMPTYKVA and dig right into the CLEAN queue.
1401 * In this manner we avoid scanning unnecessary buffers. It is very
1402 * important for us to do this because the buffer cache is almost
1403 * constantly out of space or in need of defragmentation.
1406 if ((curproc->p_flag & P_BUFEXHAUST) == 0 &&
1407 numfreebuffers < lofreebuffers) {
1408 nqindex = QUEUE_CLEAN;
1411 nqindex = QUEUE_EMPTYKVA;
1412 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1415 nqindex = QUEUE_EMPTY;
1416 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1419 if (outofspace || nbp == NULL) {
1420 nqindex = QUEUE_CLEAN;
1421 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1426 * Run scan, possibly freeing data and/or kva mappings on the fly
1430 while ((bp = nbp) != NULL) {
1431 int qindex = nqindex;
1434 * Calculate next bp ( we can only use it if we do not block
1435 * or do other fancy things ).
1437 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1440 nqindex = QUEUE_EMPTYKVA;
1441 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1444 case QUEUE_EMPTYKVA:
1445 nqindex = QUEUE_CLEAN;
1446 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1460 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1463 * Note: we no longer distinguish between VMIO and non-VMIO
1467 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1470 * If we are defragging and the buffer isn't useful for fixing
1471 * that problem we continue. If we are out of space and the
1472 * buffer isn't useful for fixing that problem we continue.
1475 if (defrag > 0 && bp->b_kvasize == 0)
1477 if (outofspace > 0 && bp->b_bufsize == 0)
1481 * Start freeing the bp. This is somewhat involved. nbp
1482 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1485 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1486 panic("getnewbuf: locked buf");
1489 if (qindex == QUEUE_CLEAN) {
1490 if (bp->b_flags & B_VMIO) {
1491 bp->b_flags &= ~B_ASYNC;
1492 vfs_vmio_release(bp);
1499 * NOTE: nbp is now entirely invalid. We can only restart
1500 * the scan from this point on.
1502 * Get the rest of the buffer freed up. b_kva* is still
1503 * valid after this operation.
1506 if (bp->b_rcred != NOCRED) {
1507 crfree(bp->b_rcred);
1508 bp->b_rcred = NOCRED;
1510 if (bp->b_wcred != NOCRED) {
1511 crfree(bp->b_wcred);
1512 bp->b_wcred = NOCRED;
1514 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1515 (*bioops.io_deallocate)(bp);
1516 LIST_REMOVE(bp, b_hash);
1517 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1525 bp->b_blkno = bp->b_lblkno = 0;
1526 bp->b_offset = NOOFFSET;
1532 bp->b_dirtyoff = bp->b_dirtyend = 0;
1534 LIST_INIT(&bp->b_dep);
1537 * Ok, now that we have a free buffer, if we are defragging
1538 * we have to recover the kvaspace. If we are out of space
1539 * we have to free the buffer (which we just did), but we
1540 * do not have to recover kva space unless we hit a defrag
1541 * hicup. Being able to avoid freeing the kva space leads
1542 * to a significant reduction in overhead.
1547 bp->b_flags |= B_INVAL;
1553 if (outofspace > 0) {
1555 bp->b_flags |= B_INVAL;
1569 * If we exhausted our list, sleep as appropriate. We may have to
1570 * wakeup various daemons and write out some dirty buffers.
1572 * Generally we are sleeping due to insufficient buffer space.
1581 flags = VFS_BIO_NEED_KVASPACE;
1583 } else if (outofspace > 0) {
1585 flags = VFS_BIO_NEED_BUFSPACE;
1588 flags = VFS_BIO_NEED_ANY;
1593 (void) speedup_syncer();
1594 needsbuffer |= flags;
1595 while (needsbuffer & flags) {
1596 if (tsleep(&needsbuffer, (PRIBIO + 4) | slpflag,
1602 * We finally have a valid bp. We aren't quite out of the
1603 * woods, we still have to reserve kva space.
1605 vm_offset_t addr = 0;
1607 maxsize = (maxsize + PAGE_MASK) & ~PAGE_MASK;
1609 if (maxsize != bp->b_kvasize) {
1612 if (vm_map_findspace(buffer_map,
1613 vm_map_min(buffer_map), maxsize, &addr)) {
1615 * Uh oh. Buffer map is to fragmented. Try
1620 bp->b_flags |= B_INVAL;
1625 * Uh oh. We couldn't seem to defragment
1632 vm_map_insert(buffer_map, NULL, 0,
1633 addr, addr + maxsize,
1634 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1636 bp->b_kvabase = (caddr_t) addr;
1637 bp->b_kvasize = maxsize;
1639 bp->b_data = bp->b_kvabase;
1647 * Wait for sufficient free buffers. Only called from normal processes.
1651 waitfreebuffers(int slpflag, int slptimeo)
1653 while (numfreebuffers < hifreebuffers) {
1654 if (numfreebuffers >= hifreebuffers)
1656 needsbuffer |= VFS_BIO_NEED_FREE;
1657 if (tsleep(&needsbuffer, (PRIBIO + 4)|slpflag, "biofre", slptimeo))
1665 * buffer flushing daemon. Buffers are normally flushed by the
1666 * update daemon but if it cannot keep up this process starts to
1667 * take the load in an attempt to prevent getnewbuf() from blocking.
1670 static struct proc *bufdaemonproc;
1671 static int bd_interval;
1672 static int bd_flushto;
1674 static struct kproc_desc buf_kp = {
1679 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1686 * This process is allowed to take the buffer cache to the limit
1688 curproc->p_flag |= P_BUFEXHAUST;
1691 bd_interval = 5 * hz; /* dynamically adjusted */
1692 bd_flushto = hidirtybuffers; /* dynamically adjusted */
1698 * Do the flush. Limit the number of buffers we flush in one
1699 * go. The failure condition occurs when processes are writing
1700 * buffers faster then we can dispose of them. In this case
1701 * we may be flushing so often that the previous set of flushes
1702 * have not had time to complete, causing us to run out of
1703 * physical buffers and block.
1706 int runcount = maxbdrun;
1708 while (numdirtybuffers > bd_flushto && runcount) {
1710 if (flushbufqueues() == 0)
1716 * If nobody is requesting anything we sleep
1718 if (bd_request == 0)
1719 tsleep(&bd_request, PVM, "psleep", bd_interval);
1722 * We calculate how much to add or subtract from bd_flushto
1723 * and bd_interval based on how far off we are from the
1724 * optimal number of dirty buffers, which is 20% below the
1725 * hidirtybuffers mark. We cannot use hidirtybuffers straight
1726 * because being right on the mark will cause getnewbuf()
1727 * to oscillate our wakeup.
1729 * The larger the error in either direction, the more we adjust
1730 * bd_flushto and bd_interval. The time interval is adjusted
1731 * by 2 seconds per whole-buffer-range of error. This is an
1732 * exponential convergence algorithm, with large errors
1733 * producing large changes and small errors producing small
1738 int brange = hidirtybuffers - lodirtybuffers;
1739 int middb = hidirtybuffers - brange / 5;
1740 int deltabuf = middb - numdirtybuffers;
1742 bd_flushto += deltabuf / 20;
1743 bd_interval += deltabuf * (2 * hz) / (brange * 1);
1745 if (bd_flushto < lodirtybuffers)
1746 bd_flushto = lodirtybuffers;
1747 if (bd_flushto > hidirtybuffers)
1748 bd_flushto = hidirtybuffers;
1749 if (bd_interval < hz / 10)
1750 bd_interval = hz / 10;
1751 if (bd_interval > 5 * hz)
1752 bd_interval = 5 * hz;
1759 * Try to flush a buffer in the dirty queue. We must be careful to
1760 * free up B_INVAL buffers instead of write them, which NFS is
1761 * particularly sensitive to.
1765 flushbufqueues(void)
1770 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1773 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1774 if ((bp->b_flags & B_DELWRI) != 0) {
1775 if (bp->b_flags & B_INVAL) {
1776 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1777 panic("flushbufqueues: locked buf");
1787 bp = TAILQ_NEXT(bp, b_freelist);
1793 * Check to see if a block is currently memory resident.
1796 incore(struct vnode * vp, daddr_t blkno)
1801 bp = gbincore(vp, blkno);
1807 * Returns true if no I/O is needed to access the
1808 * associated VM object. This is like incore except
1809 * it also hunts around in the VM system for the data.
1813 inmem(struct vnode * vp, daddr_t blkno)
1816 vm_offset_t toff, tinc, size;
1820 if (incore(vp, blkno))
1822 if (vp->v_mount == NULL)
1824 if ((vp->v_object == NULL) || (vp->v_flag & VOBJBUF) == 0)
1829 if (size > vp->v_mount->mnt_stat.f_iosize)
1830 size = vp->v_mount->mnt_stat.f_iosize;
1831 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
1833 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
1834 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
1838 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
1839 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
1840 if (vm_page_is_valid(m,
1841 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
1850 * Sets the dirty range for a buffer based on the status of the dirty
1851 * bits in the pages comprising the buffer.
1853 * The range is limited to the size of the buffer.
1855 * This routine is primarily used by NFS, but is generalized for the
1859 vfs_setdirty(struct buf *bp)
1865 * Degenerate case - empty buffer
1868 if (bp->b_bufsize == 0)
1872 * We qualify the scan for modified pages on whether the
1873 * object has been flushed yet. The OBJ_WRITEABLE flag
1874 * is not cleared simply by protecting pages off.
1877 if ((bp->b_flags & B_VMIO) == 0)
1880 object = bp->b_pages[0]->object;
1882 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
1883 printf("Warning: object %p writeable but not mightbedirty\n", object);
1884 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
1885 printf("Warning: object %p mightbedirty but not writeable\n", object);
1887 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
1888 vm_offset_t boffset;
1889 vm_offset_t eoffset;
1892 * test the pages to see if they have been modified directly
1893 * by users through the VM system.
1895 for (i = 0; i < bp->b_npages; i++) {
1896 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
1897 vm_page_test_dirty(bp->b_pages[i]);
1901 * Calculate the encompassing dirty range, boffset and eoffset,
1902 * (eoffset - boffset) bytes.
1905 for (i = 0; i < bp->b_npages; i++) {
1906 if (bp->b_pages[i]->dirty)
1909 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
1911 for (i = bp->b_npages - 1; i >= 0; --i) {
1912 if (bp->b_pages[i]->dirty) {
1916 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
1919 * Fit it to the buffer.
1922 if (eoffset > bp->b_bcount)
1923 eoffset = bp->b_bcount;
1926 * If we have a good dirty range, merge with the existing
1930 if (boffset < eoffset) {
1931 if (bp->b_dirtyoff > boffset)
1932 bp->b_dirtyoff = boffset;
1933 if (bp->b_dirtyend < eoffset)
1934 bp->b_dirtyend = eoffset;
1942 * Get a block given a specified block and offset into a file/device.
1943 * The buffers B_DONE bit will be cleared on return, making it almost
1944 * ready for an I/O initiation. B_INVAL may or may not be set on
1945 * return. The caller should clear B_INVAL prior to initiating a
1948 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
1949 * an existing buffer.
1951 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
1952 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
1953 * and then cleared based on the backing VM. If the previous buffer is
1954 * non-0-sized but invalid, B_CACHE will be cleared.
1956 * If getblk() must create a new buffer, the new buffer is returned with
1957 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
1958 * case it is returned with B_INVAL clear and B_CACHE set based on the
1961 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
1962 * B_CACHE bit is clear.
1964 * What this means, basically, is that the caller should use B_CACHE to
1965 * determine whether the buffer is fully valid or not and should clear
1966 * B_INVAL prior to issuing a read. If the caller intends to validate
1967 * the buffer by loading its data area with something, the caller needs
1968 * to clear B_INVAL. If the caller does this without issuing an I/O,
1969 * the caller should set B_CACHE ( as an optimization ), else the caller
1970 * should issue the I/O and biodone() will set B_CACHE if the I/O was
1971 * a write attempt or if it was a successfull read. If the caller
1972 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
1973 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
1976 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
1980 struct bufhashhdr *bh;
1982 #if !defined(MAX_PERF)
1983 if (size > MAXBSIZE)
1984 panic("getblk: size(%d) > MAXBSIZE(%d)\n", size, MAXBSIZE);
1990 * Block if we are low on buffers. Certain processes are allowed
1991 * to completely exhaust the buffer cache.
1993 if (curproc->p_flag & P_BUFEXHAUST) {
1994 if (numfreebuffers == 0) {
1995 needsbuffer |= VFS_BIO_NEED_ANY;
1996 tsleep(&needsbuffer, (PRIBIO + 4) | slpflag, "newbuf",
1999 } else if (numfreebuffers < lofreebuffers) {
2000 waitfreebuffers(slpflag, slptimeo);
2003 if ((bp = gbincore(vp, blkno))) {
2005 * Buffer is in-core. If the buffer is not busy, it must
2009 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2010 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2011 "getblk", slpflag, slptimeo) == ENOLCK)
2014 return (struct buf *) NULL;
2018 * The buffer is locked. B_CACHE is cleared if the buffer is
2019 * invalid. Ohterwise, for a non-VMIO buffer, B_CACHE is set
2020 * and for a VMIO buffer B_CACHE is adjusted according to the
2023 if (bp->b_flags & B_INVAL)
2024 bp->b_flags &= ~B_CACHE;
2025 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2026 bp->b_flags |= B_CACHE;
2030 * check for size inconsistancies for non-VMIO case.
2033 if (bp->b_bcount != size) {
2034 if ((bp->b_flags & B_VMIO) == 0 ||
2035 (size > bp->b_kvasize)) {
2036 if (bp->b_flags & B_DELWRI) {
2037 bp->b_flags |= B_NOCACHE;
2038 VOP_BWRITE(bp->b_vp, bp);
2040 if ((bp->b_flags & B_VMIO) &&
2041 (LIST_FIRST(&bp->b_dep) == NULL)) {
2042 bp->b_flags |= B_RELBUF;
2045 bp->b_flags |= B_NOCACHE;
2046 VOP_BWRITE(bp->b_vp, bp);
2054 * If the size is inconsistant in the VMIO case, we can resize
2055 * the buffer. This might lead to B_CACHE getting set or
2056 * cleared. If the size has not changed, B_CACHE remains
2057 * unchanged from its previous state.
2060 if (bp->b_bcount != size)
2063 KASSERT(bp->b_offset != NOOFFSET,
2064 ("getblk: no buffer offset"));
2067 * A buffer with B_DELWRI set and B_CACHE clear must
2068 * be committed before we can return the buffer in
2069 * order to prevent the caller from issuing a read
2070 * ( due to B_CACHE not being set ) and overwriting
2073 * Most callers, including NFS and FFS, need this to
2074 * operate properly either because they assume they
2075 * can issue a read if B_CACHE is not set, or because
2076 * ( for example ) an uncached B_DELWRI might loop due
2077 * to softupdates re-dirtying the buffer. In the latter
2078 * case, B_CACHE is set after the first write completes,
2079 * preventing further loops.
2082 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2083 VOP_BWRITE(bp->b_vp, bp);
2088 bp->b_flags &= ~B_DONE;
2091 * Buffer is not in-core, create new buffer. The buffer
2092 * returned by getnewbuf() is locked. Note that the returned
2093 * buffer is also considered valid (not marked B_INVAL).
2095 int bsize, maxsize, vmio;
2098 if (vp->v_type == VBLK)
2100 else if (vp->v_mountedhere)
2101 bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2102 else if (vp->v_mount)
2103 bsize = vp->v_mount->mnt_stat.f_iosize;
2107 offset = (off_t)blkno * bsize;
2108 vmio = (vp->v_object != 0) && (vp->v_flag & VOBJBUF);
2109 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2110 maxsize = imax(maxsize, bsize);
2112 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2113 if (slpflag || slptimeo) {
2121 * This code is used to make sure that a buffer is not
2122 * created while the getnewbuf routine is blocked.
2123 * This can be a problem whether the vnode is locked or not.
2124 * If the buffer is created out from under us, we have to
2125 * throw away the one we just created. There is now window
2126 * race because we are safely running at splbio() from the
2127 * point of the duplicate buffer creation through to here,
2128 * and we've locked the buffer.
2130 if (gbincore(vp, blkno)) {
2131 bp->b_flags |= B_INVAL;
2137 * Insert the buffer into the hash, so that it can
2138 * be found by incore.
2140 bp->b_blkno = bp->b_lblkno = blkno;
2141 bp->b_offset = offset;
2144 LIST_REMOVE(bp, b_hash);
2145 bh = bufhash(vp, blkno);
2146 LIST_INSERT_HEAD(bh, bp, b_hash);
2149 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2150 * buffer size starts out as 0, B_CACHE will be set by
2151 * allocbuf() for the VMIO case prior to it testing the
2152 * backing store for validity.
2156 bp->b_flags |= B_VMIO;
2157 #if defined(VFS_BIO_DEBUG)
2158 if (vp->v_type != VREG && vp->v_type != VBLK)
2159 printf("getblk: vmioing file type %d???\n", vp->v_type);
2162 bp->b_flags &= ~B_VMIO;
2168 bp->b_flags &= ~B_DONE;
2174 * Get an empty, disassociated buffer of given size. The buffer is initially
2184 while ((bp = getnewbuf(0, 0, size, MAXBSIZE)) == 0);
2187 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2193 * This code constitutes the buffer memory from either anonymous system
2194 * memory (in the case of non-VMIO operations) or from an associated
2195 * VM object (in the case of VMIO operations). This code is able to
2196 * resize a buffer up or down.
2198 * Note that this code is tricky, and has many complications to resolve
2199 * deadlock or inconsistant data situations. Tread lightly!!!
2200 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2201 * the caller. Calling this code willy nilly can result in the loss of data.
2203 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2204 * B_CACHE for the non-VMIO case.
2208 allocbuf(struct buf *bp, int size)
2210 int newbsize, mbsize;
2213 #if !defined(MAX_PERF)
2214 if (BUF_REFCNT(bp) == 0)
2215 panic("allocbuf: buffer not busy");
2217 if (bp->b_kvasize < size)
2218 panic("allocbuf: buffer too small");
2221 if ((bp->b_flags & B_VMIO) == 0) {
2225 * Just get anonymous memory from the kernel. Don't
2226 * mess with B_CACHE.
2228 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2229 #if !defined(NO_B_MALLOC)
2230 if (bp->b_flags & B_MALLOC)
2234 newbsize = round_page(size);
2236 if (newbsize < bp->b_bufsize) {
2237 #if !defined(NO_B_MALLOC)
2239 * malloced buffers are not shrunk
2241 if (bp->b_flags & B_MALLOC) {
2243 bp->b_bcount = size;
2245 free(bp->b_data, M_BIOBUF);
2246 bufspace -= bp->b_bufsize;
2247 bufmallocspace -= bp->b_bufsize;
2248 runningbufspace -= bp->b_bufsize;
2251 bp->b_data = bp->b_kvabase;
2254 bp->b_flags &= ~B_MALLOC;
2261 (vm_offset_t) bp->b_data + newbsize,
2262 (vm_offset_t) bp->b_data + bp->b_bufsize);
2263 } else if (newbsize > bp->b_bufsize) {
2264 #if !defined(NO_B_MALLOC)
2266 * We only use malloced memory on the first allocation.
2267 * and revert to page-allocated memory when the buffer
2270 if ( (bufmallocspace < maxbufmallocspace) &&
2271 (bp->b_bufsize == 0) &&
2272 (mbsize <= PAGE_SIZE/2)) {
2274 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2275 bp->b_bufsize = mbsize;
2276 bp->b_bcount = size;
2277 bp->b_flags |= B_MALLOC;
2279 bufmallocspace += mbsize;
2280 runningbufspace += bp->b_bufsize;
2286 #if !defined(NO_B_MALLOC)
2288 * If the buffer is growing on its other-than-first allocation,
2289 * then we revert to the page-allocation scheme.
2291 if (bp->b_flags & B_MALLOC) {
2292 origbuf = bp->b_data;
2293 origbufsize = bp->b_bufsize;
2294 bp->b_data = bp->b_kvabase;
2295 bufspace -= bp->b_bufsize;
2296 bufmallocspace -= bp->b_bufsize;
2297 runningbufspace -= bp->b_bufsize;
2301 bp->b_flags &= ~B_MALLOC;
2302 newbsize = round_page(newbsize);
2307 (vm_offset_t) bp->b_data + bp->b_bufsize,
2308 (vm_offset_t) bp->b_data + newbsize);
2309 #if !defined(NO_B_MALLOC)
2311 bcopy(origbuf, bp->b_data, origbufsize);
2312 free(origbuf, M_BIOBUF);
2320 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2321 desiredpages = (size == 0) ? 0 :
2322 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2324 #if !defined(NO_B_MALLOC)
2325 if (bp->b_flags & B_MALLOC)
2326 panic("allocbuf: VMIO buffer can't be malloced");
2329 * Set B_CACHE initially if buffer is 0 length or will become
2332 if (size == 0 || bp->b_bufsize == 0)
2333 bp->b_flags |= B_CACHE;
2335 if (newbsize < bp->b_bufsize) {
2337 * DEV_BSIZE aligned new buffer size is less then the
2338 * DEV_BSIZE aligned existing buffer size. Figure out
2339 * if we have to remove any pages.
2341 if (desiredpages < bp->b_npages) {
2342 for (i = desiredpages; i < bp->b_npages; i++) {
2344 * the page is not freed here -- it
2345 * is the responsibility of
2346 * vnode_pager_setsize
2349 KASSERT(m != bogus_page,
2350 ("allocbuf: bogus page found"));
2351 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2354 bp->b_pages[i] = NULL;
2355 vm_page_unwire(m, 0);
2357 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2358 (desiredpages << PAGE_SHIFT), (bp->b_npages - desiredpages));
2359 bp->b_npages = desiredpages;
2361 } else if (size > bp->b_bcount) {
2363 * We are growing the buffer, possibly in a
2364 * byte-granular fashion.
2372 * Step 1, bring in the VM pages from the object,
2373 * allocating them if necessary. We must clear
2374 * B_CACHE if these pages are not valid for the
2375 * range covered by the buffer.
2381 while (bp->b_npages < desiredpages) {
2385 pi = OFF_TO_IDX(bp->b_offset) + bp->b_npages;
2386 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2387 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL);
2390 vm_pageout_deficit += desiredpages - bp->b_npages;
2394 bp->b_flags &= ~B_CACHE;
2395 bp->b_pages[bp->b_npages] = m;
2402 * We found a page. If we have to sleep on it,
2403 * retry because it might have gotten freed out
2406 * We can only test PG_BUSY here. Blocking on
2407 * m->busy might lead to a deadlock:
2409 * vm_fault->getpages->cluster_read->allocbuf
2413 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2417 * We have a good page. Should we wakeup the
2420 if ((curproc != pageproc) &&
2421 ((m->queue - m->pc) == PQ_CACHE) &&
2422 ((cnt.v_free_count + cnt.v_cache_count) <
2423 (cnt.v_free_min + cnt.v_cache_min))) {
2424 pagedaemon_wakeup();
2426 vm_page_flag_clear(m, PG_ZERO);
2428 bp->b_pages[bp->b_npages] = m;
2433 * Step 2. We've loaded the pages into the buffer,
2434 * we have to figure out if we can still have B_CACHE
2435 * set. Note that B_CACHE is set according to the
2436 * byte-granular range ( bcount and size ), new the
2437 * aligned range ( newbsize ).
2439 * The VM test is against m->valid, which is DEV_BSIZE
2440 * aligned. Needless to say, the validity of the data
2441 * needs to also be DEV_BSIZE aligned. Note that this
2442 * fails with NFS if the server or some other client
2443 * extends the file's EOF. If our buffer is resized,
2444 * B_CACHE may remain set! XXX
2447 toff = bp->b_bcount;
2448 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2450 while ((bp->b_flags & B_CACHE) && toff < size) {
2453 if (tinc > (size - toff))
2456 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2471 * Step 3, fixup the KVM pmap. Remember that
2472 * bp->b_data is relative to bp->b_offset, but
2473 * bp->b_offset may be offset into the first page.
2476 bp->b_data = (caddr_t)
2477 trunc_page((vm_offset_t)bp->b_data);
2479 (vm_offset_t)bp->b_data,
2483 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2484 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2487 if (bp->b_flags & B_VMIO)
2488 vmiospace += (newbsize - bp->b_bufsize);
2489 bufspace += (newbsize - bp->b_bufsize);
2490 runningbufspace += (newbsize - bp->b_bufsize);
2491 if (newbsize < bp->b_bufsize)
2493 bp->b_bufsize = newbsize; /* actual buffer allocation */
2494 bp->b_bcount = size; /* requested buffer size */
2501 * Wait for buffer I/O completion, returning error status. The buffer
2502 * is left locked and B_DONE on return. B_EINTR is converted into a EINTR
2503 * error and cleared.
2506 biowait(register struct buf * bp)
2511 while ((bp->b_flags & B_DONE) == 0) {
2512 #if defined(NO_SCHEDULE_MODS)
2513 tsleep(bp, PRIBIO, "biowait", 0);
2515 if (bp->b_flags & B_READ)
2516 tsleep(bp, PRIBIO, "biord", 0);
2518 tsleep(bp, PRIBIO, "biowr", 0);
2522 if (bp->b_flags & B_EINTR) {
2523 bp->b_flags &= ~B_EINTR;
2526 if (bp->b_flags & B_ERROR) {
2527 return (bp->b_error ? bp->b_error : EIO);
2536 * Finish I/O on a buffer, optionally calling a completion function.
2537 * This is usually called from an interrupt so process blocking is
2540 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2541 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2542 * assuming B_INVAL is clear.
2544 * For the VMIO case, we set B_CACHE if the op was a read and no
2545 * read error occured, or if the op was a write. B_CACHE is never
2546 * set if the buffer is invalid or otherwise uncacheable.
2548 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2549 * initiator to leave B_INVAL set to brelse the buffer out of existance
2550 * in the biodone routine.
2553 biodone(register struct buf * bp)
2559 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2560 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2562 bp->b_flags |= B_DONE;
2564 if (bp->b_flags & B_FREEBUF) {
2570 if ((bp->b_flags & B_READ) == 0) {
2574 /* call optional completion function if requested */
2575 if (bp->b_flags & B_CALL) {
2576 bp->b_flags &= ~B_CALL;
2577 (*bp->b_iodone) (bp);
2581 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2582 (*bioops.io_complete)(bp);
2584 if (bp->b_flags & B_VMIO) {
2590 struct vnode *vp = bp->b_vp;
2594 #if defined(VFS_BIO_DEBUG)
2595 if (vp->v_usecount == 0) {
2596 panic("biodone: zero vnode ref count");
2599 if (vp->v_object == NULL) {
2600 panic("biodone: missing VM object");
2603 if ((vp->v_flag & VOBJBUF) == 0) {
2604 panic("biodone: vnode is not setup for merged cache");
2608 foff = bp->b_offset;
2609 KASSERT(bp->b_offset != NOOFFSET,
2610 ("biodone: no buffer offset"));
2612 #if !defined(MAX_PERF)
2614 panic("biodone: no object");
2617 #if defined(VFS_BIO_DEBUG)
2618 if (obj->paging_in_progress < bp->b_npages) {
2619 printf("biodone: paging in progress(%d) < bp->b_npages(%d)\n",
2620 obj->paging_in_progress, bp->b_npages);
2625 * Set B_CACHE if the op was a normal read and no error
2626 * occured. B_CACHE is set for writes in the b*write()
2629 iosize = bp->b_bcount;
2630 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2631 bp->b_flags |= B_CACHE;
2634 for (i = 0; i < bp->b_npages; i++) {
2637 if (m == bogus_page) {
2639 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2641 #if defined(VFS_BIO_DEBUG)
2642 printf("biodone: page disappeared\n");
2644 vm_object_pip_subtract(obj, 1);
2645 bp->b_flags &= ~B_CACHE;
2649 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2651 #if defined(VFS_BIO_DEBUG)
2652 if (OFF_TO_IDX(foff) != m->pindex) {
2654 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2655 (unsigned long)foff, m->pindex);
2658 resid = IDX_TO_OFF(m->pindex + 1) - foff;
2663 * In the write case, the valid and clean bits are
2664 * already changed correctly ( see bdwrite() ), so we
2665 * only need to do this here in the read case.
2667 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
2668 vfs_page_set_valid(bp, foff, i, m);
2670 vm_page_flag_clear(m, PG_ZERO);
2673 * when debugging new filesystems or buffer I/O methods, this
2674 * is the most common error that pops up. if you see this, you
2675 * have not set the page busy flag correctly!!!
2678 #if !defined(MAX_PERF)
2679 printf("biodone: page busy < 0, "
2680 "pindex: %d, foff: 0x(%x,%x), "
2681 "resid: %d, index: %d\n",
2682 (int) m->pindex, (int)(foff >> 32),
2683 (int) foff & 0xffffffff, resid, i);
2685 if (vp->v_type != VBLK)
2686 #if !defined(MAX_PERF)
2687 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
2688 bp->b_vp->v_mount->mnt_stat.f_iosize,
2690 bp->b_flags, bp->b_npages);
2692 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
2694 bp->b_flags, bp->b_npages);
2695 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2696 m->valid, m->dirty, m->wire_count);
2698 panic("biodone: page busy < 0\n");
2700 vm_page_io_finish(m);
2701 vm_object_pip_subtract(obj, 1);
2706 vm_object_pip_wakeupn(obj, 0);
2709 * For asynchronous completions, release the buffer now. The brelse
2710 * will do a wakeup there if necessary - so no need to do a wakeup
2711 * here in the async case. The sync case always needs to do a wakeup.
2714 if (bp->b_flags & B_ASYNC) {
2715 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
2726 * This routine is called in lieu of iodone in the case of
2727 * incomplete I/O. This keeps the busy status for pages
2731 vfs_unbusy_pages(struct buf * bp)
2735 if (bp->b_flags & B_VMIO) {
2736 struct vnode *vp = bp->b_vp;
2737 vm_object_t obj = vp->v_object;
2739 for (i = 0; i < bp->b_npages; i++) {
2740 vm_page_t m = bp->b_pages[i];
2742 if (m == bogus_page) {
2743 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
2744 #if !defined(MAX_PERF)
2746 panic("vfs_unbusy_pages: page missing\n");
2750 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2752 vm_object_pip_subtract(obj, 1);
2753 vm_page_flag_clear(m, PG_ZERO);
2754 vm_page_io_finish(m);
2756 vm_object_pip_wakeupn(obj, 0);
2761 * vfs_page_set_valid:
2763 * Set the valid bits in a page based on the supplied offset. The
2764 * range is restricted to the buffer's size.
2766 * This routine is typically called after a read completes.
2769 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
2771 vm_ooffset_t soff, eoff;
2774 * Start and end offsets in buffer. eoff - soff may not cross a
2775 * page boundry or cross the end of the buffer. The end of the
2776 * buffer, in this case, is our file EOF, not the allocation size
2780 eoff = (off + PAGE_SIZE) & ~PAGE_MASK;
2781 if (eoff > bp->b_offset + bp->b_bcount)
2782 eoff = bp->b_offset + bp->b_bcount;
2785 * Set valid range. This is typically the entire buffer and thus the
2789 vm_page_set_validclean(
2791 (vm_offset_t) (soff & PAGE_MASK),
2792 (vm_offset_t) (eoff - soff)
2798 * This routine is called before a device strategy routine.
2799 * It is used to tell the VM system that paging I/O is in
2800 * progress, and treat the pages associated with the buffer
2801 * almost as being PG_BUSY. Also the object paging_in_progress
2802 * flag is handled to make sure that the object doesn't become
2805 * Since I/O has not been initiated yet, certain buffer flags
2806 * such as B_ERROR or B_INVAL may be in an inconsistant state
2807 * and should be ignored.
2810 vfs_busy_pages(struct buf * bp, int clear_modify)
2814 if (bp->b_flags & B_VMIO) {
2815 struct vnode *vp = bp->b_vp;
2816 vm_object_t obj = vp->v_object;
2819 foff = bp->b_offset;
2820 KASSERT(bp->b_offset != NOOFFSET,
2821 ("vfs_busy_pages: no buffer offset"));
2825 for (i = 0; i < bp->b_npages; i++) {
2826 vm_page_t m = bp->b_pages[i];
2827 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
2832 for (i = 0; i < bp->b_npages; i++) {
2833 vm_page_t m = bp->b_pages[i];
2835 vm_page_flag_clear(m, PG_ZERO);
2836 if ((bp->b_flags & B_CLUSTER) == 0) {
2837 vm_object_pip_add(obj, 1);
2838 vm_page_io_start(m);
2842 * When readying a buffer for a read ( i.e
2843 * clear_modify == 0 ), it is important to do
2844 * bogus_page replacement for valid pages in
2845 * partially instantiated buffers. Partially
2846 * instantiated buffers can, in turn, occur when
2847 * reconstituting a buffer from its VM backing store
2848 * base. We only have to do this if B_CACHE is
2849 * clear ( which causes the I/O to occur in the
2850 * first place ). The replacement prevents the read
2851 * I/O from overwriting potentially dirty VM-backed
2852 * pages. XXX bogus page replacement is, uh, bogus.
2853 * It may not work properly with small-block devices.
2854 * We need to find a better way.
2857 vm_page_protect(m, VM_PROT_NONE);
2859 vfs_page_set_valid(bp, foff, i, m);
2860 else if (m->valid == VM_PAGE_BITS_ALL &&
2861 (bp->b_flags & B_CACHE) == 0) {
2862 bp->b_pages[i] = bogus_page;
2865 foff = (foff + PAGE_SIZE) & ~PAGE_MASK;
2868 pmap_qenter(trunc_page((vm_offset_t)bp->b_data), bp->b_pages, bp->b_npages);
2873 * Tell the VM system that the pages associated with this buffer
2874 * are clean. This is used for delayed writes where the data is
2875 * going to go to disk eventually without additional VM intevention.
2877 * Note that while we only really need to clean through to b_bcount, we
2878 * just go ahead and clean through to b_bufsize.
2881 vfs_clean_pages(struct buf * bp)
2885 if (bp->b_flags & B_VMIO) {
2888 foff = bp->b_offset;
2889 KASSERT(bp->b_offset != NOOFFSET,
2890 ("vfs_clean_pages: no buffer offset"));
2891 for (i = 0; i < bp->b_npages; i++) {
2892 vm_page_t m = bp->b_pages[i];
2893 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~PAGE_MASK;
2894 vm_ooffset_t eoff = noff;
2896 if (eoff > bp->b_offset + bp->b_bufsize)
2897 eoff = bp->b_offset + bp->b_bufsize;
2898 vfs_page_set_valid(bp, foff, i, m);
2899 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
2906 * vfs_bio_set_validclean:
2908 * Set the range within the buffer to valid and clean. The range is
2909 * relative to the beginning of the buffer, b_offset. Note that b_offset
2910 * itself may be offset from the beginning of the first page.
2914 vfs_bio_set_validclean(struct buf *bp, int base, int size)
2916 if (bp->b_flags & B_VMIO) {
2921 * Fixup base to be relative to beginning of first page.
2922 * Set initial n to be the maximum number of bytes in the
2923 * first page that can be validated.
2926 base += (bp->b_offset & PAGE_MASK);
2927 n = PAGE_SIZE - (base & PAGE_MASK);
2929 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_npages; ++i) {
2930 vm_page_t m = bp->b_pages[i];
2935 vm_page_set_validclean(m, base & PAGE_MASK, n);
2946 * clear a buffer. This routine essentially fakes an I/O, so we need
2947 * to clear B_ERROR and B_INVAL.
2949 * Note that while we only theoretically need to clear through b_bcount,
2950 * we go ahead and clear through b_bufsize.
2954 vfs_bio_clrbuf(struct buf *bp) {
2957 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
2958 bp->b_flags &= ~(B_INVAL|B_ERROR);
2959 if( (bp->b_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
2960 (bp->b_offset & PAGE_MASK) == 0) {
2961 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
2962 if (((bp->b_pages[0]->flags & PG_ZERO) == 0) &&
2963 ((bp->b_pages[0]->valid & mask) != mask)) {
2964 bzero(bp->b_data, bp->b_bufsize);
2966 bp->b_pages[0]->valid |= mask;
2970 ea = sa = bp->b_data;
2971 for(i=0;i<bp->b_npages;i++,sa=ea) {
2972 int j = ((u_long)sa & PAGE_MASK) / DEV_BSIZE;
2973 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
2974 ea = (caddr_t)ulmin((u_long)ea,
2975 (u_long)bp->b_data + bp->b_bufsize);
2976 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
2977 if ((bp->b_pages[i]->valid & mask) == mask)
2979 if ((bp->b_pages[i]->valid & mask) == 0) {
2980 if ((bp->b_pages[i]->flags & PG_ZERO) == 0) {
2984 for (; sa < ea; sa += DEV_BSIZE, j++) {
2985 if (((bp->b_pages[i]->flags & PG_ZERO) == 0) &&
2986 (bp->b_pages[i]->valid & (1<<j)) == 0)
2987 bzero(sa, DEV_BSIZE);
2990 bp->b_pages[i]->valid |= mask;
2991 vm_page_flag_clear(bp->b_pages[i], PG_ZERO);
3000 * vm_hold_load_pages and vm_hold_unload pages get pages into
3001 * a buffers address space. The pages are anonymous and are
3002 * not associated with a file object.
3005 vm_hold_load_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3011 to = round_page(to);
3012 from = round_page(from);
3013 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3015 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3019 p = vm_page_alloc(kernel_object,
3020 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3023 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3028 p->valid = VM_PAGE_BITS_ALL;
3029 vm_page_flag_clear(p, PG_ZERO);
3030 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3031 bp->b_pages[index] = p;
3034 bp->b_npages = index;
3038 vm_hold_free_pages(struct buf * bp, vm_offset_t from, vm_offset_t to)
3042 int index, newnpages;
3044 from = round_page(from);
3045 to = round_page(to);
3046 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3048 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3049 p = bp->b_pages[index];
3050 if (p && (index < bp->b_npages)) {
3051 #if !defined(MAX_PERF)
3053 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3054 bp->b_blkno, bp->b_lblkno);
3057 bp->b_pages[index] = NULL;
3060 vm_page_unwire(p, 0);
3064 bp->b_npages = newnpages;
3068 #include "opt_ddb.h"
3070 #include <ddb/ddb.h>
3072 DB_SHOW_COMMAND(buffer, db_show_buffer)
3075 struct buf *bp = (struct buf *)addr;
3078 db_printf("usage: show buffer <addr>\n");
3082 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3083 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3084 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3085 "b_blkno = %d, b_pblkno = %d\n",
3086 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3087 major(bp->b_dev), minor(bp->b_dev),
3088 bp->b_data, bp->b_blkno, bp->b_pblkno);
3091 db_printf("b_npages = %d, pages(OBJ, IDX, PA): ", bp->b_npages);
3092 for (i = 0; i < bp->b_npages; i++) {
3095 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3096 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3097 if ((i + 1) < bp->b_npages)