2 * Copyright (c) 1994,1997 John S. Dyson
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice immediately at the beginning of the file, without modification,
10 * this list of conditions, and the following disclaimer.
11 * 2. Absolutely no warranty of function or purpose is made by the author
14 * $FreeBSD: src/sys/kern/vfs_bio.c,v 1.242.2.20 2003/05/28 18:38:10 alc Exp $
15 * $DragonFly: src/sys/kern/vfs_bio.c,v 1.30 2004/07/14 03:43:58 hmp Exp $
19 * this file contains a new buffer I/O scheme implementing a coherent
20 * VM object and buffer cache scheme. Pains have been taken to make
21 * sure that the performance degradation associated with schemes such
22 * as this is not realized.
24 * Author: John S. Dyson
25 * Significant help during the development and debugging phases
26 * had been provided by David Greenman, also of the FreeBSD core team.
28 * see man buf(9) for more info.
31 #include <sys/param.h>
32 #include <sys/systm.h>
35 #include <sys/eventhandler.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
57 #include <vm/vm_page2.h>
59 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
61 struct bio_ops bioops; /* I/O operation notification */
63 struct buf *buf; /* buffer header pool */
64 struct swqueue bswlist;
66 static void vm_hold_free_pages(struct buf * bp, vm_offset_t from,
68 static void vm_hold_load_pages(struct buf * bp, vm_offset_t from,
70 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
71 int pageno, vm_page_t m);
72 static void vfs_clean_pages(struct buf * bp);
73 static void vfs_setdirty(struct buf *bp);
74 static void vfs_vmio_release(struct buf *bp);
75 static void vfs_backgroundwritedone(struct buf *bp);
76 static int flushbufqueues(void);
78 static int bd_request;
80 static void buf_daemon (void);
82 * bogus page -- for I/O to/from partially complete buffers
83 * this is a temporary solution to the problem, but it is not
84 * really that bad. it would be better to split the buffer
85 * for input in the case of buffers partially already in memory,
86 * but the code is intricate enough already.
89 int vmiodirenable = TRUE;
91 struct lwkt_token buftimetoken; /* Interlock on setting prio and timo */
93 static vm_offset_t bogus_offset;
95 static int bufspace, maxbufspace,
96 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
97 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
98 static int needsbuffer;
99 static int lorunningspace, hirunningspace, runningbufreq;
100 static int numdirtybuffers, lodirtybuffers, hidirtybuffers;
101 static int numfreebuffers, lofreebuffers, hifreebuffers;
102 static int getnewbufcalls;
103 static int getnewbufrestarts;
105 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD,
106 &numdirtybuffers, 0, "");
107 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW,
108 &lodirtybuffers, 0, "");
109 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW,
110 &hidirtybuffers, 0, "");
111 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD,
112 &numfreebuffers, 0, "");
113 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW,
114 &lofreebuffers, 0, "");
115 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW,
116 &hifreebuffers, 0, "");
117 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD,
118 &runningbufspace, 0, "");
119 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW,
120 &lorunningspace, 0, "");
121 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW,
122 &hirunningspace, 0, "");
123 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD,
124 &maxbufspace, 0, "");
125 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD,
127 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD,
129 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD,
131 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RW,
132 &maxbufmallocspace, 0, "");
133 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD,
134 &bufmallocspace, 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, "");
139 SYSCTL_INT(_vfs, OID_AUTO, vmiodirenable, CTLFLAG_RW,
140 &vmiodirenable, 0, "");
141 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RW,
142 &bufdefragcnt, 0, "");
143 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RW,
144 &buffreekvacnt, 0, "");
145 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RW,
146 &bufreusecnt, 0, "");
149 * Disable background writes for now. There appear to be races in the
150 * flags tests and locking operations as well as races in the completion
151 * code modifying the original bp (origbp) without holding a lock, assuming
152 * splbio protection when there might not be splbio protection.
154 static int dobkgrdwrite = 0;
155 SYSCTL_INT(_debug, OID_AUTO, dobkgrdwrite, CTLFLAG_RW, &dobkgrdwrite, 0,
156 "Do background writes (honoring the BV_BKGRDWRITE flag)?");
158 static int bufhashmask;
159 static int bufhashshift;
160 static LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
161 struct bqueues bufqueues[BUFFER_QUEUES] = { { 0 } };
162 char *buf_wmesg = BUF_WMESG;
164 extern int vm_swap_size;
166 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
167 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
168 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
169 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
172 * Buffer hash table code. Note that the logical block scans linearly, which
173 * gives us some L1 cache locality.
178 bufhash(struct vnode *vnp, daddr_t bn)
184 * A variation on the Fibonacci hash that Knuth credits to
185 * R. W. Floyd, see Knuth's _Art of Computer Programming,
186 * Volume 3 / Sorting and Searching_
188 * We reduce the argument to 32 bits before doing the hash to
189 * avoid the need for a slow 64x64 multiply on 32 bit platforms.
191 * sizeof(struct vnode) is 168 on i386, so toss some of the lower
192 * bits of the vnode address to reduce the key range, which
193 * improves the distribution of keys across buckets.
195 * The file system cylinder group blocks are very heavily
196 * used. They are located at invervals of fbg, which is
197 * on the order of 89 to 94 * 2^10, depending on other
198 * filesystem parameters, for a 16k block size. Smaller block
199 * sizes will reduce fpg approximately proportionally. This
200 * will cause the cylinder group index to be hashed using the
201 * lower bits of the hash multiplier, which will not distribute
202 * the keys as uniformly in a classic Fibonacci hash where a
203 * relatively small number of the upper bits of the result
204 * are used. Using 2^16 as a close-enough approximation to
205 * fpg, split the hash multiplier in half, with the upper 16
206 * bits being the inverse of the golden ratio, and the lower
207 * 16 bits being a fraction between 1/3 and 3/7 (closer to
208 * 3/7 in this case), that gives good experimental results.
210 hashkey64 = ((u_int64_t)(uintptr_t)vnp >> 3) + (u_int64_t)bn;
211 hashkey = (((u_int32_t)(hashkey64 + (hashkey64 >> 32)) * 0x9E376DB1u) >>
212 bufhashshift) & bufhashmask;
213 return(&bufhashtbl[hashkey]);
219 * If someone is blocked due to there being too many dirty buffers,
220 * and numdirtybuffers is now reasonable, wake them up.
224 numdirtywakeup(int level)
226 if (numdirtybuffers <= level) {
227 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
228 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
229 wakeup(&needsbuffer);
237 * Called when buffer space is potentially available for recovery.
238 * getnewbuf() will block on this flag when it is unable to free
239 * sufficient buffer space. Buffer space becomes recoverable when
240 * bp's get placed back in the queues.
247 * If someone is waiting for BUF space, wake them up. Even
248 * though we haven't freed the kva space yet, the waiting
249 * process will be able to now.
251 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
252 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
253 wakeup(&needsbuffer);
258 * runningbufwakeup() - in-progress I/O accounting.
262 runningbufwakeup(struct buf *bp)
264 if (bp->b_runningbufspace) {
265 runningbufspace -= bp->b_runningbufspace;
266 bp->b_runningbufspace = 0;
267 if (runningbufreq && runningbufspace <= lorunningspace) {
269 wakeup(&runningbufreq);
277 * Called when a buffer has been added to one of the free queues to
278 * account for the buffer and to wakeup anyone waiting for free buffers.
279 * This typically occurs when large amounts of metadata are being handled
280 * by the buffer cache ( else buffer space runs out first, usually ).
288 needsbuffer &= ~VFS_BIO_NEED_ANY;
289 if (numfreebuffers >= hifreebuffers)
290 needsbuffer &= ~VFS_BIO_NEED_FREE;
291 wakeup(&needsbuffer);
296 * waitrunningbufspace()
298 * runningbufspace is a measure of the amount of I/O currently
299 * running. This routine is used in async-write situations to
300 * prevent creating huge backups of pending writes to a device.
301 * Only asynchronous writes are governed by this function.
303 * Reads will adjust runningbufspace, but will not block based on it.
304 * The read load has a side effect of reducing the allowed write load.
306 * This does NOT turn an async write into a sync write. It waits
307 * for earlier writes to complete and generally returns before the
308 * caller's write has reached the device.
311 waitrunningbufspace(void)
313 while (runningbufspace > hirunningspace) {
316 s = splbio(); /* fix race against interrupt/biodone() */
318 tsleep(&runningbufreq, 0, "wdrain", 0);
324 * vfs_buf_test_cache:
326 * Called when a buffer is extended. This function clears the B_CACHE
327 * bit if the newly extended portion of the buffer does not contain
332 vfs_buf_test_cache(struct buf *bp,
333 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
336 if (bp->b_flags & B_CACHE) {
337 int base = (foff + off) & PAGE_MASK;
338 if (vm_page_is_valid(m, base, size) == 0)
339 bp->b_flags &= ~B_CACHE;
345 bd_wakeup(int dirtybuflevel)
347 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
354 * bd_speedup - speedup the buffer cache flushing code
365 * Initialize buffer headers and related structures.
369 bufhashinit(caddr_t vaddr)
371 /* first, make a null hash table */
373 for (bufhashmask = 8; bufhashmask < nbuf / 4; bufhashmask <<= 1)
375 bufhashtbl = (void *)vaddr;
376 vaddr = vaddr + sizeof(*bufhashtbl) * bufhashmask;
387 TAILQ_INIT(&bswlist);
388 LIST_INIT(&invalhash);
389 lwkt_token_init(&buftimetoken);
391 for (i = 0; i <= bufhashmask; i++)
392 LIST_INIT(&bufhashtbl[i]);
394 /* next, make a null set of free lists */
395 for (i = 0; i < BUFFER_QUEUES; i++)
396 TAILQ_INIT(&bufqueues[i]);
398 /* finally, initialize each buffer header and stick on empty q */
399 for (i = 0; i < nbuf; i++) {
401 bzero(bp, sizeof *bp);
402 bp->b_flags = B_INVAL; /* we're just an empty header */
404 bp->b_qindex = QUEUE_EMPTY;
406 xio_init(&bp->b_xio);
407 LIST_INIT(&bp->b_dep);
409 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_EMPTY], bp, b_freelist);
410 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
414 * maxbufspace is the absolute maximum amount of buffer space we are
415 * allowed to reserve in KVM and in real terms. The absolute maximum
416 * is nominally used by buf_daemon. hibufspace is the nominal maximum
417 * used by most other processes. The differential is required to
418 * ensure that buf_daemon is able to run when other processes might
419 * be blocked waiting for buffer space.
421 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
422 * this may result in KVM fragmentation which is not handled optimally
425 maxbufspace = nbuf * BKVASIZE;
426 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
427 lobufspace = hibufspace - MAXBSIZE;
429 lorunningspace = 512 * 1024;
430 hirunningspace = 1024 * 1024;
433 * Limit the amount of malloc memory since it is wired permanently into
434 * the kernel space. Even though this is accounted for in the buffer
435 * allocation, we don't want the malloced region to grow uncontrolled.
436 * The malloc scheme improves memory utilization significantly on average
437 * (small) directories.
439 maxbufmallocspace = hibufspace / 20;
442 * Reduce the chance of a deadlock occuring by limiting the number
443 * of delayed-write dirty buffers we allow to stack up.
445 hidirtybuffers = nbuf / 4 + 20;
448 * To support extreme low-memory systems, make sure hidirtybuffers cannot
449 * eat up all available buffer space. This occurs when our minimum cannot
450 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
451 * BKVASIZE'd (8K) buffers.
453 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
454 hidirtybuffers >>= 1;
456 lodirtybuffers = hidirtybuffers / 2;
459 * Try to keep the number of free buffers in the specified range,
460 * and give special processes (e.g. like buf_daemon) access to an
463 lofreebuffers = nbuf / 18 + 5;
464 hifreebuffers = 2 * lofreebuffers;
465 numfreebuffers = nbuf;
468 * Maximum number of async ops initiated per buf_daemon loop. This is
469 * somewhat of a hack at the moment, we really need to limit ourselves
470 * based on the number of bytes of I/O in-transit that were initiated
474 bogus_offset = kmem_alloc_pageable(kernel_map, PAGE_SIZE);
475 bogus_page = vm_page_alloc(kernel_object,
476 ((bogus_offset - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
478 vmstats.v_wire_count++;
483 * bfreekva() - free the kva allocation for a buffer.
485 * Must be called at splbio() or higher as this is the only locking for
488 * Since this call frees up buffer space, we call bufspacewakeup().
491 bfreekva(struct buf * bp)
497 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
498 vm_map_lock(buffer_map);
499 bufspace -= bp->b_kvasize;
500 vm_map_delete(buffer_map,
501 (vm_offset_t) bp->b_kvabase,
502 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
505 vm_map_unlock(buffer_map);
506 vm_map_entry_release(count);
515 * Remove the buffer from the appropriate free list.
518 bremfree(struct buf * bp)
521 int old_qindex = bp->b_qindex;
523 if (bp->b_qindex != QUEUE_NONE) {
524 KASSERT(BUF_REFCNT(bp) == 1, ("bremfree: bp %p not locked",bp));
525 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
526 bp->b_qindex = QUEUE_NONE;
528 if (BUF_REFCNT(bp) <= 1)
529 panic("bremfree: removing a buffer not on a queue");
533 * Fixup numfreebuffers count. If the buffer is invalid or not
534 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
535 * the buffer was free and we must decrement numfreebuffers.
537 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
554 * Get a buffer with the specified data. Look in the cache first. We
555 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
556 * is set, the buffer is valid and we do not have to do anything ( see
560 bread(struct vnode * vp, daddr_t blkno, int size, struct buf ** bpp)
564 bp = getblk(vp, blkno, size, 0, 0);
567 /* if not found in cache, do some I/O */
568 if ((bp->b_flags & B_CACHE) == 0) {
569 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
570 bp->b_flags |= B_READ;
571 bp->b_flags &= ~(B_ERROR | B_INVAL);
572 vfs_busy_pages(bp, 0);
573 VOP_STRATEGY(vp, bp);
574 return (biowait(bp));
580 * Operates like bread, but also starts asynchronous I/O on
581 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
582 * to initiating I/O . If B_CACHE is set, the buffer is valid
583 * and we do not have to do anything.
586 breadn(struct vnode * vp, daddr_t blkno, int size, daddr_t * rablkno,
587 int *rabsize, int cnt, struct buf ** bpp)
589 struct buf *bp, *rabp;
591 int rv = 0, readwait = 0;
593 *bpp = bp = getblk(vp, blkno, size, 0, 0);
595 /* if not found in cache, do some I/O */
596 if ((bp->b_flags & B_CACHE) == 0) {
597 bp->b_flags |= B_READ;
598 bp->b_flags &= ~(B_ERROR | B_INVAL);
599 vfs_busy_pages(bp, 0);
600 VOP_STRATEGY(vp, bp);
604 for (i = 0; i < cnt; i++, rablkno++, rabsize++) {
605 if (inmem(vp, *rablkno))
607 rabp = getblk(vp, *rablkno, *rabsize, 0, 0);
609 if ((rabp->b_flags & B_CACHE) == 0) {
610 rabp->b_flags |= B_READ | B_ASYNC;
611 rabp->b_flags &= ~(B_ERROR | B_INVAL);
612 vfs_busy_pages(rabp, 0);
614 VOP_STRATEGY(vp, rabp);
627 * Write, release buffer on completion. (Done by iodone
628 * if async). Do not bother writing anything if the buffer
631 * Note that we set B_CACHE here, indicating that buffer is
632 * fully valid and thus cacheable. This is true even of NFS
633 * now so we set it generally. This could be set either here
634 * or in biodone() since the I/O is synchronous. We put it
638 bwrite(struct buf * bp)
643 if (bp->b_flags & B_INVAL) {
648 oldflags = bp->b_flags;
650 if (BUF_REFCNT(bp) == 0)
651 panic("bwrite: buffer is not busy???");
654 * If a background write is already in progress, delay
655 * writing this block if it is asynchronous. Otherwise
656 * wait for the background write to complete.
658 if (bp->b_xflags & BX_BKGRDINPROG) {
659 if (bp->b_flags & B_ASYNC) {
664 bp->b_xflags |= BX_BKGRDWAIT;
665 tsleep(&bp->b_xflags, 0, "biord", 0);
666 if (bp->b_xflags & BX_BKGRDINPROG)
667 panic("bwrite: still writing");
670 /* Mark the buffer clean */
674 * If this buffer is marked for background writing and we
675 * do not have to wait for it, make a copy and write the
676 * copy so as to leave this buffer ready for further use.
678 * This optimization eats a lot of memory. If we have a page
679 * or buffer shortfull we can't do it.
682 (bp->b_xflags & BX_BKGRDWRITE) &&
683 (bp->b_flags & B_ASYNC) &&
684 !vm_page_count_severe() &&
685 !buf_dirty_count_severe()) {
686 if (bp->b_flags & B_CALL)
687 panic("bwrite: need chained iodone");
689 /* get a new block */
690 newbp = geteblk(bp->b_bufsize);
692 /* set it to be identical to the old block */
693 memcpy(newbp->b_data, bp->b_data, bp->b_bufsize);
694 bgetvp(bp->b_vp, newbp);
695 newbp->b_lblkno = bp->b_lblkno;
696 newbp->b_blkno = bp->b_blkno;
697 newbp->b_offset = bp->b_offset;
698 newbp->b_iodone = vfs_backgroundwritedone;
699 newbp->b_flags |= B_ASYNC | B_CALL;
700 newbp->b_flags &= ~B_INVAL;
702 /* move over the dependencies */
703 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
704 (*bioops.io_movedeps)(bp, newbp);
707 * Initiate write on the copy, release the original to
708 * the B_LOCKED queue so that it cannot go away until
709 * the background write completes. If not locked it could go
710 * away and then be reconstituted while it was being written.
711 * If the reconstituted buffer were written, we could end up
712 * with two background copies being written at the same time.
714 bp->b_xflags |= BX_BKGRDINPROG;
715 bp->b_flags |= B_LOCKED;
720 bp->b_flags &= ~(B_READ | B_DONE | B_ERROR);
721 bp->b_flags |= B_WRITEINPROG | B_CACHE;
723 bp->b_vp->v_numoutput++;
724 vfs_busy_pages(bp, 1);
727 * Normal bwrites pipeline writes
729 bp->b_runningbufspace = bp->b_bufsize;
730 runningbufspace += bp->b_runningbufspace;
733 if (oldflags & B_ASYNC)
735 VOP_STRATEGY(bp->b_vp, bp);
737 if ((oldflags & B_ASYNC) == 0) {
738 int rtval = biowait(bp);
741 } else if ((oldflags & B_NOWDRAIN) == 0) {
743 * don't allow the async write to saturate the I/O
744 * system. Deadlocks can occur only if a device strategy
745 * routine (like in VN) turns around and issues another
746 * high-level write, in which case B_NOWDRAIN is expected
747 * to be set. Otherwise we will not deadlock here because
748 * we are blocking waiting for I/O that is already in-progress
751 waitrunningbufspace();
758 * Complete a background write started from bwrite.
761 vfs_backgroundwritedone(struct buf *bp)
766 * Find the original buffer that we are writing.
768 if ((origbp = gbincore(bp->b_vp, bp->b_lblkno)) == NULL)
769 panic("backgroundwritedone: lost buffer");
771 * Process dependencies then return any unfinished ones.
773 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
774 (*bioops.io_complete)(bp);
775 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_movedeps)
776 (*bioops.io_movedeps)(bp, origbp);
778 * Clear the BX_BKGRDINPROG flag in the original buffer
779 * and awaken it if it is waiting for the write to complete.
780 * If BX_BKGRDINPROG is not set in the original buffer it must
781 * have been released and re-instantiated - which is not legal.
783 KASSERT((origbp->b_xflags & BX_BKGRDINPROG), ("backgroundwritedone: lost buffer2"));
784 origbp->b_xflags &= ~BX_BKGRDINPROG;
785 if (origbp->b_xflags & BX_BKGRDWAIT) {
786 origbp->b_xflags &= ~BX_BKGRDWAIT;
787 wakeup(&origbp->b_xflags);
790 * Clear the B_LOCKED flag and remove it from the locked
791 * queue if it currently resides there.
793 origbp->b_flags &= ~B_LOCKED;
794 if (BUF_LOCK(origbp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
799 * This buffer is marked B_NOCACHE, so when it is released
800 * by biodone, it will be tossed. We mark it with B_READ
801 * to avoid biodone doing a second vwakeup.
803 bp->b_flags |= B_NOCACHE | B_READ;
804 bp->b_flags &= ~(B_CACHE | B_CALL | B_DONE);
810 * Delayed write. (Buffer is marked dirty). Do not bother writing
811 * anything if the buffer is marked invalid.
813 * Note that since the buffer must be completely valid, we can safely
814 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
815 * biodone() in order to prevent getblk from writing the buffer
819 bdwrite(struct buf *bp)
821 if (BUF_REFCNT(bp) == 0)
822 panic("bdwrite: buffer is not busy");
824 if (bp->b_flags & B_INVAL) {
831 * Set B_CACHE, indicating that the buffer is fully valid. This is
832 * true even of NFS now.
834 bp->b_flags |= B_CACHE;
837 * This bmap keeps the system from needing to do the bmap later,
838 * perhaps when the system is attempting to do a sync. Since it
839 * is likely that the indirect block -- or whatever other datastructure
840 * that the filesystem needs is still in memory now, it is a good
841 * thing to do this. Note also, that if the pageout daemon is
842 * requesting a sync -- there might not be enough memory to do
843 * the bmap then... So, this is important to do.
845 if (bp->b_lblkno == bp->b_blkno) {
846 VOP_BMAP(bp->b_vp, bp->b_lblkno, NULL, &bp->b_blkno, NULL, NULL);
850 * Set the *dirty* buffer range based upon the VM system dirty pages.
855 * We need to do this here to satisfy the vnode_pager and the
856 * pageout daemon, so that it thinks that the pages have been
857 * "cleaned". Note that since the pages are in a delayed write
858 * buffer -- the VFS layer "will" see that the pages get written
859 * out on the next sync, or perhaps the cluster will be completed.
865 * Wakeup the buffer flushing daemon if we have a lot of dirty
866 * buffers (midpoint between our recovery point and our stall
869 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
872 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
873 * due to the softdep code.
880 * Turn buffer into delayed write request. We must clear B_READ and
881 * B_RELBUF, and we must set B_DELWRI. We reassign the buffer to
882 * itself to properly update it in the dirty/clean lists. We mark it
883 * B_DONE to ensure that any asynchronization of the buffer properly
884 * clears B_DONE ( else a panic will occur later ).
886 * bdirty() is kinda like bdwrite() - we have to clear B_INVAL which
887 * might have been set pre-getblk(). Unlike bwrite/bdwrite, bdirty()
888 * should only be called if the buffer is known-good.
890 * Since the buffer is not on a queue, we do not update the numfreebuffers
893 * Must be called at splbio().
894 * The buffer must be on QUEUE_NONE.
897 bdirty(struct buf *bp)
899 KASSERT(bp->b_qindex == QUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
900 bp->b_flags &= ~(B_READ|B_RELBUF);
902 if ((bp->b_flags & B_DELWRI) == 0) {
903 bp->b_flags |= B_DONE | B_DELWRI;
904 reassignbuf(bp, bp->b_vp);
906 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
913 * Clear B_DELWRI for buffer.
915 * Since the buffer is not on a queue, we do not update the numfreebuffers
918 * Must be called at splbio().
919 * The buffer must be on QUEUE_NONE.
923 bundirty(struct buf *bp)
925 KASSERT(bp->b_qindex == QUEUE_NONE, ("bundirty: buffer %p still on queue %d", bp, bp->b_qindex));
927 if (bp->b_flags & B_DELWRI) {
928 bp->b_flags &= ~B_DELWRI;
929 reassignbuf(bp, bp->b_vp);
931 numdirtywakeup(lodirtybuffers);
934 * Since it is now being written, we can clear its deferred write flag.
936 bp->b_flags &= ~B_DEFERRED;
942 * Asynchronous write. Start output on a buffer, but do not wait for
943 * it to complete. The buffer is released when the output completes.
945 * bwrite() ( or the VOP routine anyway ) is responsible for handling
946 * B_INVAL buffers. Not us.
949 bawrite(struct buf * bp)
951 bp->b_flags |= B_ASYNC;
952 (void) VOP_BWRITE(bp->b_vp, bp);
958 * Ordered write. Start output on a buffer, and flag it so that the
959 * device will write it in the order it was queued. The buffer is
960 * released when the output completes. bwrite() ( or the VOP routine
961 * anyway ) is responsible for handling B_INVAL buffers.
964 bowrite(struct buf * bp)
966 bp->b_flags |= B_ORDERED | B_ASYNC;
967 return (VOP_BWRITE(bp->b_vp, bp));
973 * Called prior to the locking of any vnodes when we are expecting to
974 * write. We do not want to starve the buffer cache with too many
975 * dirty buffers so we block here. By blocking prior to the locking
976 * of any vnodes we attempt to avoid the situation where a locked vnode
977 * prevents the various system daemons from flushing related buffers.
983 if (numdirtybuffers >= hidirtybuffers) {
987 while (numdirtybuffers >= hidirtybuffers) {
989 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
990 tsleep(&needsbuffer, 0, "flswai", 0);
997 * Return true if we have too many dirty buffers.
1000 buf_dirty_count_severe(void)
1002 return(numdirtybuffers >= hidirtybuffers);
1008 * Release a busy buffer and, if requested, free its resources. The
1009 * buffer will be stashed in the appropriate bufqueue[] allowing it
1010 * to be accessed later as a cache entity or reused for other purposes.
1013 brelse(struct buf * bp)
1017 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1021 if (bp->b_flags & B_LOCKED)
1022 bp->b_flags &= ~B_ERROR;
1024 if ((bp->b_flags & (B_READ | B_ERROR | B_INVAL)) == B_ERROR) {
1026 * Failed write, redirty. Must clear B_ERROR to prevent
1027 * pages from being scrapped. If B_INVAL is set then
1028 * this case is not run and the next case is run to
1029 * destroy the buffer. B_INVAL can occur if the buffer
1030 * is outside the range supported by the underlying device.
1032 bp->b_flags &= ~B_ERROR;
1034 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_FREEBUF)) ||
1035 (bp->b_bufsize <= 0)) {
1037 * Either a failed I/O or we were asked to free or not
1040 bp->b_flags |= B_INVAL;
1041 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1042 (*bioops.io_deallocate)(bp);
1043 if (bp->b_flags & B_DELWRI) {
1045 numdirtywakeup(lodirtybuffers);
1047 bp->b_flags &= ~(B_DELWRI | B_CACHE | B_FREEBUF);
1048 if ((bp->b_flags & B_VMIO) == 0) {
1057 * We must clear B_RELBUF if B_DELWRI is set. If vfs_vmio_release()
1058 * is called with B_DELWRI set, the underlying pages may wind up
1059 * getting freed causing a previous write (bdwrite()) to get 'lost'
1060 * because pages associated with a B_DELWRI bp are marked clean.
1062 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1063 * if B_DELWRI is set.
1065 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1066 * on pages to return pages to the VM page queues.
1068 if (bp->b_flags & B_DELWRI)
1069 bp->b_flags &= ~B_RELBUF;
1070 else if (vm_page_count_severe() && !(bp->b_xflags & BX_BKGRDINPROG))
1071 bp->b_flags |= B_RELBUF;
1074 * VMIO buffer rundown. It is not very necessary to keep a VMIO buffer
1075 * constituted, not even NFS buffers now. Two flags effect this. If
1076 * B_INVAL, the struct buf is invalidated but the VM object is kept
1077 * around ( i.e. so it is trivial to reconstitute the buffer later ).
1079 * If B_ERROR or B_NOCACHE is set, pages in the VM object will be
1080 * invalidated. B_ERROR cannot be set for a failed write unless the
1081 * buffer is also B_INVAL because it hits the re-dirtying code above.
1083 * Normally we can do this whether a buffer is B_DELWRI or not. If
1084 * the buffer is an NFS buffer, it is tracking piecemeal writes or
1085 * the commit state and we cannot afford to lose the buffer. If the
1086 * buffer has a background write in progress, we need to keep it
1087 * around to prevent it from being reconstituted and starting a second
1090 if ((bp->b_flags & B_VMIO)
1091 && !(bp->b_vp->v_tag == VT_NFS &&
1092 !vn_isdisk(bp->b_vp, NULL) &&
1093 (bp->b_flags & B_DELWRI))
1106 * Get the base offset and length of the buffer. Note that
1107 * in the VMIO case if the buffer block size is not
1108 * page-aligned then b_data pointer may not be page-aligned.
1109 * But our b_xio.xio_pages array *IS* page aligned.
1111 * block sizes less then DEV_BSIZE (usually 512) are not
1112 * supported due to the page granularity bits (m->valid,
1113 * m->dirty, etc...).
1115 * See man buf(9) for more information
1118 resid = bp->b_bufsize;
1119 foff = bp->b_offset;
1121 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1122 m = bp->b_xio.xio_pages[i];
1123 vm_page_flag_clear(m, PG_ZERO);
1125 * If we hit a bogus page, fixup *all* of them
1126 * now. Note that we left these pages wired
1127 * when we removed them so they had better exist,
1128 * and they cannot be ripped out from under us so
1129 * no splvm() protection is necessary.
1131 if (m == bogus_page) {
1132 VOP_GETVOBJECT(vp, &obj);
1133 poff = OFF_TO_IDX(bp->b_offset);
1135 for (j = i; j < bp->b_xio.xio_npages; j++) {
1138 mtmp = bp->b_xio.xio_pages[j];
1139 if (mtmp == bogus_page) {
1140 mtmp = vm_page_lookup(obj, poff + j);
1142 panic("brelse: page missing");
1144 bp->b_xio.xio_pages[j] = mtmp;
1148 if ((bp->b_flags & B_INVAL) == 0) {
1149 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1150 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1152 m = bp->b_xio.xio_pages[i];
1156 * Invalidate the backing store if B_NOCACHE is set
1157 * (e.g. used with vinvalbuf()). If this is NFS
1158 * we impose a requirement that the block size be
1159 * a multiple of PAGE_SIZE and create a temporary
1160 * hack to basically invalidate the whole page. The
1161 * problem is that NFS uses really odd buffer sizes
1162 * especially when tracking piecemeal writes and
1163 * it also vinvalbuf()'s a lot, which would result
1164 * in only partial page validation and invalidation
1165 * here. If the file page is mmap()'d, however,
1166 * all the valid bits get set so after we invalidate
1167 * here we would end up with weird m->valid values
1168 * like 0xfc. nfs_getpages() can't handle this so
1169 * we clear all the valid bits for the NFS case
1170 * instead of just some of them.
1172 * The real bug is the VM system having to set m->valid
1173 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1174 * itself is an artifact of the whole 512-byte
1175 * granular mess that exists to support odd block
1176 * sizes and UFS meta-data block sizes (e.g. 6144).
1177 * A complete rewrite is required.
1179 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1180 int poffset = foff & PAGE_MASK;
1183 presid = PAGE_SIZE - poffset;
1184 if (bp->b_vp->v_tag == VT_NFS &&
1185 bp->b_vp->v_type == VREG) {
1187 } else if (presid > resid) {
1190 KASSERT(presid >= 0, ("brelse: extra page"));
1191 vm_page_set_invalid(m, poffset, presid);
1193 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1194 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1197 if (bp->b_flags & (B_INVAL | B_RELBUF))
1198 vfs_vmio_release(bp);
1200 } else if (bp->b_flags & B_VMIO) {
1202 if (bp->b_flags & (B_INVAL | B_RELBUF))
1203 vfs_vmio_release(bp);
1207 if (bp->b_qindex != QUEUE_NONE)
1208 panic("brelse: free buffer onto another queue???");
1209 if (BUF_REFCNT(bp) > 1) {
1210 /* Temporary panic to verify exclusive locking */
1211 /* This panic goes away when we allow shared refs */
1212 panic("brelse: multiple refs");
1213 /* do not release to free list */
1221 /* buffers with no memory */
1222 if (bp->b_bufsize == 0) {
1223 bp->b_flags |= B_INVAL;
1224 bp->b_xflags &= ~BX_BKGRDWRITE;
1225 if (bp->b_xflags & BX_BKGRDINPROG)
1226 panic("losing buffer 1");
1227 if (bp->b_kvasize) {
1228 bp->b_qindex = QUEUE_EMPTYKVA;
1230 bp->b_qindex = QUEUE_EMPTY;
1232 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1233 LIST_REMOVE(bp, b_hash);
1234 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1236 /* buffers with junk contents */
1237 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1238 bp->b_flags |= B_INVAL;
1239 bp->b_xflags &= ~BX_BKGRDWRITE;
1240 if (bp->b_xflags & BX_BKGRDINPROG)
1241 panic("losing buffer 2");
1242 bp->b_qindex = QUEUE_CLEAN;
1243 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1244 LIST_REMOVE(bp, b_hash);
1245 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1248 /* buffers that are locked */
1249 } else if (bp->b_flags & B_LOCKED) {
1250 bp->b_qindex = QUEUE_LOCKED;
1251 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1253 /* remaining buffers */
1255 switch(bp->b_flags & (B_DELWRI|B_AGE)) {
1256 case B_DELWRI | B_AGE:
1257 bp->b_qindex = QUEUE_DIRTY;
1258 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1261 bp->b_qindex = QUEUE_DIRTY;
1262 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1265 bp->b_qindex = QUEUE_CLEAN;
1266 TAILQ_INSERT_HEAD(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1269 bp->b_qindex = QUEUE_CLEAN;
1270 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1276 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1277 * on the correct queue.
1279 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1283 * Fixup numfreebuffers count. The bp is on an appropriate queue
1284 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1285 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1286 * if B_INVAL is set ).
1289 if ((bp->b_flags & B_LOCKED) == 0 && !(bp->b_flags & B_DELWRI))
1293 * Something we can maybe free or reuse
1295 if (bp->b_bufsize || bp->b_kvasize)
1300 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1301 B_DIRECT | B_NOWDRAIN);
1306 * Release a buffer back to the appropriate queue but do not try to free
1307 * it. The buffer is expected to be used again soon.
1309 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1310 * biodone() to requeue an async I/O on completion. It is also used when
1311 * known good buffers need to be requeued but we think we may need the data
1314 * XXX we should be able to leave the B_RELBUF hint set on completion.
1317 bqrelse(struct buf * bp)
1323 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1325 if (bp->b_qindex != QUEUE_NONE)
1326 panic("bqrelse: free buffer onto another queue???");
1327 if (BUF_REFCNT(bp) > 1) {
1328 /* do not release to free list */
1329 panic("bqrelse: multiple refs");
1334 if (bp->b_flags & B_LOCKED) {
1335 bp->b_flags &= ~B_ERROR;
1336 bp->b_qindex = QUEUE_LOCKED;
1337 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_LOCKED], bp, b_freelist);
1338 /* buffers with stale but valid contents */
1339 } else if (bp->b_flags & B_DELWRI) {
1340 bp->b_qindex = QUEUE_DIRTY;
1341 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY], bp, b_freelist);
1342 } else if (vm_page_count_severe()) {
1344 * We are too low on memory, we have to try to free the
1345 * buffer (most importantly: the wired pages making up its
1346 * backing store) *now*.
1352 bp->b_qindex = QUEUE_CLEAN;
1353 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_CLEAN], bp, b_freelist);
1356 if ((bp->b_flags & B_LOCKED) == 0 &&
1357 ((bp->b_flags & B_INVAL) || !(bp->b_flags & B_DELWRI))) {
1362 * Something we can maybe free or reuse.
1364 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1369 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1374 vfs_vmio_release(struct buf *bp)
1380 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1381 m = bp->b_xio.xio_pages[i];
1382 bp->b_xio.xio_pages[i] = NULL;
1384 * In order to keep page LRU ordering consistent, put
1385 * everything on the inactive queue.
1387 vm_page_unwire(m, 0);
1389 * We don't mess with busy pages, it is
1390 * the responsibility of the process that
1391 * busied the pages to deal with them.
1393 if ((m->flags & PG_BUSY) || (m->busy != 0))
1396 if (m->wire_count == 0) {
1397 vm_page_flag_clear(m, PG_ZERO);
1399 * Might as well free the page if we can and it has
1400 * no valid data. We also free the page if the
1401 * buffer was used for direct I/O.
1403 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid && m->hold_count == 0) {
1405 vm_page_protect(m, VM_PROT_NONE);
1407 } else if (bp->b_flags & B_DIRECT) {
1408 vm_page_try_to_free(m);
1409 } else if (vm_page_count_severe()) {
1410 vm_page_try_to_cache(m);
1415 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1416 if (bp->b_bufsize) {
1420 bp->b_xio.xio_npages = 0;
1421 bp->b_flags &= ~B_VMIO;
1427 * Check to see if a block is currently memory resident.
1430 gbincore(struct vnode * vp, daddr_t blkno)
1433 struct bufhashhdr *bh;
1435 bh = bufhash(vp, blkno);
1437 /* Search hash chain */
1438 LIST_FOREACH(bp, bh, b_hash) {
1440 if (bp->b_vp == vp && bp->b_lblkno == blkno &&
1441 (bp->b_flags & B_INVAL) == 0) {
1451 * Implement clustered async writes for clearing out B_DELWRI buffers.
1452 * This is much better then the old way of writing only one buffer at
1453 * a time. Note that we may not be presented with the buffers in the
1454 * correct order, so we search for the cluster in both directions.
1457 vfs_bio_awrite(struct buf * bp)
1461 daddr_t lblkno = bp->b_lblkno;
1462 struct vnode *vp = bp->b_vp;
1472 * right now we support clustered writing only to regular files. If
1473 * we find a clusterable block we could be in the middle of a cluster
1474 * rather then at the beginning.
1476 if ((vp->v_type == VREG) &&
1477 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1478 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1480 size = vp->v_mount->mnt_stat.f_iosize;
1481 maxcl = MAXPHYS / size;
1483 for (i = 1; i < maxcl; i++) {
1484 if ((bpa = gbincore(vp, lblkno + i)) &&
1485 BUF_REFCNT(bpa) == 0 &&
1486 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1487 (B_DELWRI | B_CLUSTEROK)) &&
1488 (bpa->b_bufsize == size)) {
1489 if ((bpa->b_blkno == bpa->b_lblkno) ||
1491 bp->b_blkno + ((i * size) >> DEV_BSHIFT)))
1497 for (j = 1; i + j <= maxcl && j <= lblkno; j++) {
1498 if ((bpa = gbincore(vp, lblkno - j)) &&
1499 BUF_REFCNT(bpa) == 0 &&
1500 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1501 (B_DELWRI | B_CLUSTEROK)) &&
1502 (bpa->b_bufsize == size)) {
1503 if ((bpa->b_blkno == bpa->b_lblkno) ||
1505 bp->b_blkno - ((j * size) >> DEV_BSHIFT)))
1514 * this is a possible cluster write
1517 nwritten = cluster_wbuild(vp, size, lblkno - j, ncl);
1523 BUF_LOCK(bp, LK_EXCLUSIVE);
1525 bp->b_flags |= B_ASYNC;
1529 * default (old) behavior, writing out only one block
1531 * XXX returns b_bufsize instead of b_bcount for nwritten?
1533 nwritten = bp->b_bufsize;
1534 (void) VOP_BWRITE(bp->b_vp, bp);
1542 * Find and initialize a new buffer header, freeing up existing buffers
1543 * in the bufqueues as necessary. The new buffer is returned locked.
1545 * Important: B_INVAL is not set. If the caller wishes to throw the
1546 * buffer away, the caller must set B_INVAL prior to calling brelse().
1549 * We have insufficient buffer headers
1550 * We have insufficient buffer space
1551 * buffer_map is too fragmented ( space reservation fails )
1552 * If we have to flush dirty buffers ( but we try to avoid this )
1554 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1555 * Instead we ask the buf daemon to do it for us. We attempt to
1556 * avoid piecemeal wakeups of the pageout daemon.
1560 getnewbuf(int slpflag, int slptimeo, int size, int maxsize)
1566 static int flushingbufs;
1569 * We can't afford to block since we might be holding a vnode lock,
1570 * which may prevent system daemons from running. We deal with
1571 * low-memory situations by proactively returning memory and running
1572 * async I/O rather then sync I/O.
1576 --getnewbufrestarts;
1578 ++getnewbufrestarts;
1581 * Setup for scan. If we do not have enough free buffers,
1582 * we setup a degenerate case that immediately fails. Note
1583 * that if we are specially marked process, we are allowed to
1584 * dip into our reserves.
1586 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1588 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1589 * However, there are a number of cases (defragging, reusing, ...)
1590 * where we cannot backup.
1592 nqindex = QUEUE_EMPTYKVA;
1593 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA]);
1597 * If no EMPTYKVA buffers and we are either
1598 * defragging or reusing, locate a CLEAN buffer
1599 * to free or reuse. If bufspace useage is low
1600 * skip this step so we can allocate a new buffer.
1602 if (defrag || bufspace >= lobufspace) {
1603 nqindex = QUEUE_CLEAN;
1604 nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN]);
1608 * If we could not find or were not allowed to reuse a
1609 * CLEAN buffer, check to see if it is ok to use an EMPTY
1610 * buffer. We can only use an EMPTY buffer if allocating
1611 * its KVA would not otherwise run us out of buffer space.
1613 if (nbp == NULL && defrag == 0 &&
1614 bufspace + maxsize < hibufspace) {
1615 nqindex = QUEUE_EMPTY;
1616 nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTY]);
1621 * Run scan, possibly freeing data and/or kva mappings on the fly
1625 while ((bp = nbp) != NULL) {
1626 int qindex = nqindex;
1629 * Calculate next bp ( we can only use it if we do not block
1630 * or do other fancy things ).
1632 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1635 nqindex = QUEUE_EMPTYKVA;
1636 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_EMPTYKVA])))
1639 case QUEUE_EMPTYKVA:
1640 nqindex = QUEUE_CLEAN;
1641 if ((nbp = TAILQ_FIRST(&bufqueues[QUEUE_CLEAN])))
1655 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistant queue %d bp %p", qindex, bp));
1658 * Note: we no longer distinguish between VMIO and non-VMIO
1662 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1665 * If we are defragging then we need a buffer with
1666 * b_kvasize != 0. XXX this situation should no longer
1667 * occur, if defrag is non-zero the buffer's b_kvasize
1668 * should also be non-zero at this point. XXX
1670 if (defrag && bp->b_kvasize == 0) {
1671 printf("Warning: defrag empty buffer %p\n", bp);
1676 * Start freeing the bp. This is somewhat involved. nbp
1677 * remains valid only for QUEUE_EMPTY[KVA] bp's.
1680 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1681 panic("getnewbuf: locked buf");
1684 if (qindex == QUEUE_CLEAN) {
1685 if (bp->b_flags & B_VMIO) {
1686 bp->b_flags &= ~B_ASYNC;
1687 vfs_vmio_release(bp);
1694 * NOTE: nbp is now entirely invalid. We can only restart
1695 * the scan from this point on.
1697 * Get the rest of the buffer freed up. b_kva* is still
1698 * valid after this operation.
1701 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1702 (*bioops.io_deallocate)(bp);
1703 if (bp->b_xflags & BX_BKGRDINPROG)
1704 panic("losing buffer 3");
1705 LIST_REMOVE(bp, b_hash);
1706 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1709 * spl protection not required when scrapping a buffer's
1710 * contents because it is already wired.
1719 bp->b_blkno = bp->b_lblkno = 0;
1720 bp->b_offset = NOOFFSET;
1725 bp->b_xio.xio_npages = 0;
1726 bp->b_dirtyoff = bp->b_dirtyend = 0;
1728 LIST_INIT(&bp->b_dep);
1731 * If we are defragging then free the buffer.
1734 bp->b_flags |= B_INVAL;
1742 * If we are overcomitted then recover the buffer and its
1743 * KVM space. This occurs in rare situations when multiple
1744 * processes are blocked in getnewbuf() or allocbuf().
1746 if (bufspace >= hibufspace)
1748 if (flushingbufs && bp->b_kvasize != 0) {
1749 bp->b_flags |= B_INVAL;
1754 if (bufspace < lobufspace)
1760 * If we exhausted our list, sleep as appropriate. We may have to
1761 * wakeup various daemons and write out some dirty buffers.
1763 * Generally we are sleeping due to insufficient buffer space.
1771 flags = VFS_BIO_NEED_BUFSPACE;
1773 } else if (bufspace >= hibufspace) {
1775 flags = VFS_BIO_NEED_BUFSPACE;
1778 flags = VFS_BIO_NEED_ANY;
1781 bd_speedup(); /* heeeelp */
1783 needsbuffer |= flags;
1784 while (needsbuffer & flags) {
1785 if (tsleep(&needsbuffer, slpflag, waitmsg, slptimeo))
1790 * We finally have a valid bp. We aren't quite out of the
1791 * woods, we still have to reserve kva space. In order
1792 * to keep fragmentation sane we only allocate kva in
1795 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1797 if (maxsize != bp->b_kvasize) {
1798 vm_offset_t addr = 0;
1803 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1804 vm_map_lock(buffer_map);
1806 if (vm_map_findspace(buffer_map,
1807 vm_map_min(buffer_map), maxsize,
1810 * Uh oh. Buffer map is to fragmented. We
1811 * must defragment the map.
1813 vm_map_unlock(buffer_map);
1814 vm_map_entry_release(count);
1817 bp->b_flags |= B_INVAL;
1822 vm_map_insert(buffer_map, &count,
1824 addr, addr + maxsize,
1825 VM_PROT_ALL, VM_PROT_ALL, MAP_NOFAULT);
1827 bp->b_kvabase = (caddr_t) addr;
1828 bp->b_kvasize = maxsize;
1829 bufspace += bp->b_kvasize;
1832 vm_map_unlock(buffer_map);
1833 vm_map_entry_release(count);
1835 bp->b_data = bp->b_kvabase;
1843 * buffer flushing daemon. Buffers are normally flushed by the
1844 * update daemon but if it cannot keep up this process starts to
1845 * take the load in an attempt to prevent getnewbuf() from blocking.
1848 static struct thread *bufdaemonthread;
1850 static struct kproc_desc buf_kp = {
1855 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kproc_start, &buf_kp)
1863 * This process needs to be suspended prior to shutdown sync.
1865 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1866 bufdaemonthread, SHUTDOWN_PRI_LAST);
1869 * This process is allowed to take the buffer cache to the limit
1874 kproc_suspend_loop();
1877 * Do the flush. Limit the amount of in-transit I/O we
1878 * allow to build up, otherwise we would completely saturate
1879 * the I/O system. Wakeup any waiting processes before we
1880 * normally would so they can run in parallel with our drain.
1882 while (numdirtybuffers > lodirtybuffers) {
1883 if (flushbufqueues() == 0)
1885 waitrunningbufspace();
1886 numdirtywakeup((lodirtybuffers + hidirtybuffers) / 2);
1890 * Only clear bd_request if we have reached our low water
1891 * mark. The buf_daemon normally waits 5 seconds and
1892 * then incrementally flushes any dirty buffers that have
1893 * built up, within reason.
1895 * If we were unable to hit our low water mark and couldn't
1896 * find any flushable buffers, we sleep half a second.
1897 * Otherwise we loop immediately.
1899 if (numdirtybuffers <= lodirtybuffers) {
1901 * We reached our low water mark, reset the
1902 * request and sleep until we are needed again.
1903 * The sleep is just so the suspend code works.
1906 tsleep(&bd_request, 0, "psleep", hz);
1909 * We couldn't find any flushable dirty buffers but
1910 * still have too many dirty buffers, we
1911 * have to sleep and try again. (rare)
1913 tsleep(&bd_request, 0, "qsleep", hz / 2);
1921 * Try to flush a buffer in the dirty queue. We must be careful to
1922 * free up B_INVAL buffers instead of write them, which NFS is
1923 * particularly sensitive to.
1927 flushbufqueues(void)
1932 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1935 KASSERT((bp->b_flags & B_DELWRI), ("unexpected clean buffer %p", bp));
1936 if ((bp->b_flags & B_DELWRI) != 0 &&
1937 (bp->b_xflags & BX_BKGRDINPROG) == 0) {
1938 if (bp->b_flags & B_INVAL) {
1939 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
1940 panic("flushbufqueues: locked buf");
1946 if (LIST_FIRST(&bp->b_dep) != NULL &&
1947 bioops.io_countdeps &&
1948 (bp->b_flags & B_DEFERRED) == 0 &&
1949 (*bioops.io_countdeps)(bp, 0)) {
1950 TAILQ_REMOVE(&bufqueues[QUEUE_DIRTY],
1952 TAILQ_INSERT_TAIL(&bufqueues[QUEUE_DIRTY],
1954 bp->b_flags |= B_DEFERRED;
1955 bp = TAILQ_FIRST(&bufqueues[QUEUE_DIRTY]);
1962 bp = TAILQ_NEXT(bp, b_freelist);
1968 * Check to see if a block is currently memory resident.
1971 incore(struct vnode * vp, daddr_t blkno)
1976 bp = gbincore(vp, blkno);
1982 * Returns true if no I/O is needed to access the associated VM object.
1983 * This is like incore except it also hunts around in the VM system for
1986 * Note that we ignore vm_page_free() races from interrupts against our
1987 * lookup, since if the caller is not protected our return value will not
1988 * be any more valid then otherwise once we splx().
1991 inmem(struct vnode * vp, daddr_t blkno)
1994 vm_offset_t toff, tinc, size;
1998 if (incore(vp, blkno))
2000 if (vp->v_mount == NULL)
2002 if (VOP_GETVOBJECT(vp, &obj) != 0 || (vp->v_flag & VOBJBUF) == 0)
2006 if (size > vp->v_mount->mnt_stat.f_iosize)
2007 size = vp->v_mount->mnt_stat.f_iosize;
2008 off = (vm_ooffset_t)blkno * (vm_ooffset_t)vp->v_mount->mnt_stat.f_iosize;
2010 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2011 m = vm_page_lookup(obj, OFF_TO_IDX(off + toff));
2015 if (tinc > PAGE_SIZE - ((toff + off) & PAGE_MASK))
2016 tinc = PAGE_SIZE - ((toff + off) & PAGE_MASK);
2017 if (vm_page_is_valid(m,
2018 (vm_offset_t) ((toff + off) & PAGE_MASK), tinc) == 0)
2027 * Sets the dirty range for a buffer based on the status of the dirty
2028 * bits in the pages comprising the buffer.
2030 * The range is limited to the size of the buffer.
2032 * This routine is primarily used by NFS, but is generalized for the
2036 vfs_setdirty(struct buf *bp)
2042 * Degenerate case - empty buffer
2045 if (bp->b_bufsize == 0)
2049 * We qualify the scan for modified pages on whether the
2050 * object has been flushed yet. The OBJ_WRITEABLE flag
2051 * is not cleared simply by protecting pages off.
2054 if ((bp->b_flags & B_VMIO) == 0)
2057 object = bp->b_xio.xio_pages[0]->object;
2059 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2060 printf("Warning: object %p writeable but not mightbedirty\n", object);
2061 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2062 printf("Warning: object %p mightbedirty but not writeable\n", object);
2064 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2065 vm_offset_t boffset;
2066 vm_offset_t eoffset;
2069 * test the pages to see if they have been modified directly
2070 * by users through the VM system.
2072 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2073 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2074 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2078 * Calculate the encompassing dirty range, boffset and eoffset,
2079 * (eoffset - boffset) bytes.
2082 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2083 if (bp->b_xio.xio_pages[i]->dirty)
2086 boffset = (i << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2088 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2089 if (bp->b_xio.xio_pages[i]->dirty) {
2093 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_offset & PAGE_MASK);
2096 * Fit it to the buffer.
2099 if (eoffset > bp->b_bcount)
2100 eoffset = bp->b_bcount;
2103 * If we have a good dirty range, merge with the existing
2107 if (boffset < eoffset) {
2108 if (bp->b_dirtyoff > boffset)
2109 bp->b_dirtyoff = boffset;
2110 if (bp->b_dirtyend < eoffset)
2111 bp->b_dirtyend = eoffset;
2119 * Get a block given a specified block and offset into a file/device.
2120 * The buffers B_DONE bit will be cleared on return, making it almost
2121 * ready for an I/O initiation. B_INVAL may or may not be set on
2122 * return. The caller should clear B_INVAL prior to initiating a
2125 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2126 * an existing buffer.
2128 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2129 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2130 * and then cleared based on the backing VM. If the previous buffer is
2131 * non-0-sized but invalid, B_CACHE will be cleared.
2133 * If getblk() must create a new buffer, the new buffer is returned with
2134 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2135 * case it is returned with B_INVAL clear and B_CACHE set based on the
2138 * getblk() also forces a VOP_BWRITE() for any B_DELWRI buffer whos
2139 * B_CACHE bit is clear.
2141 * What this means, basically, is that the caller should use B_CACHE to
2142 * determine whether the buffer is fully valid or not and should clear
2143 * B_INVAL prior to issuing a read. If the caller intends to validate
2144 * the buffer by loading its data area with something, the caller needs
2145 * to clear B_INVAL. If the caller does this without issuing an I/O,
2146 * the caller should set B_CACHE ( as an optimization ), else the caller
2147 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2148 * a write attempt or if it was a successfull read. If the caller
2149 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2150 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2153 getblk(struct vnode * vp, daddr_t blkno, int size, int slpflag, int slptimeo)
2157 struct bufhashhdr *bh;
2159 if (size > MAXBSIZE)
2160 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2165 * Block if we are low on buffers. Certain processes are allowed
2166 * to completely exhaust the buffer cache.
2168 * If this check ever becomes a bottleneck it may be better to
2169 * move it into the else, when gbincore() fails. At the moment
2170 * it isn't a problem.
2172 * XXX remove, we cannot afford to block anywhere if holding a vnode
2173 * lock in low-memory situation, so take it to the max.
2175 if (numfreebuffers == 0) {
2178 needsbuffer |= VFS_BIO_NEED_ANY;
2179 tsleep(&needsbuffer, slpflag, "newbuf", slptimeo);
2182 if ((bp = gbincore(vp, blkno))) {
2184 * Buffer is in-core. If the buffer is not busy, it must
2188 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2189 if (BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL,
2190 "getblk", slpflag, slptimeo) == ENOLCK)
2193 return (struct buf *) NULL;
2197 * The buffer is locked. B_CACHE is cleared if the buffer is
2198 * invalid. Ohterwise, for a non-VMIO buffer, B_CACHE is set
2199 * and for a VMIO buffer B_CACHE is adjusted according to the
2202 if (bp->b_flags & B_INVAL)
2203 bp->b_flags &= ~B_CACHE;
2204 else if ((bp->b_flags & (B_VMIO | B_INVAL)) == 0)
2205 bp->b_flags |= B_CACHE;
2209 * check for size inconsistancies for non-VMIO case.
2212 if (bp->b_bcount != size) {
2213 if ((bp->b_flags & B_VMIO) == 0 ||
2214 (size > bp->b_kvasize)) {
2215 if (bp->b_flags & B_DELWRI) {
2216 bp->b_flags |= B_NOCACHE;
2217 VOP_BWRITE(bp->b_vp, bp);
2219 if ((bp->b_flags & B_VMIO) &&
2220 (LIST_FIRST(&bp->b_dep) == NULL)) {
2221 bp->b_flags |= B_RELBUF;
2224 bp->b_flags |= B_NOCACHE;
2225 VOP_BWRITE(bp->b_vp, bp);
2233 * If the size is inconsistant in the VMIO case, we can resize
2234 * the buffer. This might lead to B_CACHE getting set or
2235 * cleared. If the size has not changed, B_CACHE remains
2236 * unchanged from its previous state.
2239 if (bp->b_bcount != size)
2242 KASSERT(bp->b_offset != NOOFFSET,
2243 ("getblk: no buffer offset"));
2246 * A buffer with B_DELWRI set and B_CACHE clear must
2247 * be committed before we can return the buffer in
2248 * order to prevent the caller from issuing a read
2249 * ( due to B_CACHE not being set ) and overwriting
2252 * Most callers, including NFS and FFS, need this to
2253 * operate properly either because they assume they
2254 * can issue a read if B_CACHE is not set, or because
2255 * ( for example ) an uncached B_DELWRI might loop due
2256 * to softupdates re-dirtying the buffer. In the latter
2257 * case, B_CACHE is set after the first write completes,
2258 * preventing further loops.
2260 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2261 * above while extending the buffer, we cannot allow the
2262 * buffer to remain with B_CACHE set after the write
2263 * completes or it will represent a corrupt state. To
2264 * deal with this we set B_NOCACHE to scrap the buffer
2267 * We might be able to do something fancy, like setting
2268 * B_CACHE in bwrite() except if B_DELWRI is already set,
2269 * so the below call doesn't set B_CACHE, but that gets real
2270 * confusing. This is much easier.
2273 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2274 bp->b_flags |= B_NOCACHE;
2275 VOP_BWRITE(bp->b_vp, bp);
2280 bp->b_flags &= ~B_DONE;
2283 * Buffer is not in-core, create new buffer. The buffer
2284 * returned by getnewbuf() is locked. Note that the returned
2285 * buffer is also considered valid (not marked B_INVAL).
2287 int bsize, maxsize, vmio;
2290 if (vn_isdisk(vp, NULL))
2292 else if (vp->v_mountedhere)
2293 bsize = vp->v_mountedhere->mnt_stat.f_iosize;
2294 else if (vp->v_mount)
2295 bsize = vp->v_mount->mnt_stat.f_iosize;
2299 offset = (off_t)blkno * bsize;
2300 vmio = (VOP_GETVOBJECT(vp, NULL) == 0) && (vp->v_flag & VOBJBUF);
2301 maxsize = vmio ? size + (offset & PAGE_MASK) : size;
2302 maxsize = imax(maxsize, bsize);
2304 if ((bp = getnewbuf(slpflag, slptimeo, size, maxsize)) == NULL) {
2305 if (slpflag || slptimeo) {
2313 * This code is used to make sure that a buffer is not
2314 * created while the getnewbuf routine is blocked.
2315 * This can be a problem whether the vnode is locked or not.
2316 * If the buffer is created out from under us, we have to
2317 * throw away the one we just created. There is now window
2318 * race because we are safely running at splbio() from the
2319 * point of the duplicate buffer creation through to here,
2320 * and we've locked the buffer.
2322 if (gbincore(vp, blkno)) {
2323 bp->b_flags |= B_INVAL;
2329 * Insert the buffer into the hash, so that it can
2330 * be found by incore.
2332 bp->b_blkno = bp->b_lblkno = blkno;
2333 bp->b_offset = offset;
2336 LIST_REMOVE(bp, b_hash);
2337 bh = bufhash(vp, blkno);
2338 LIST_INSERT_HEAD(bh, bp, b_hash);
2341 * set B_VMIO bit. allocbuf() the buffer bigger. Since the
2342 * buffer size starts out as 0, B_CACHE will be set by
2343 * allocbuf() for the VMIO case prior to it testing the
2344 * backing store for validity.
2348 bp->b_flags |= B_VMIO;
2349 #if defined(VFS_BIO_DEBUG)
2350 if (vn_canvmio(vp) != TRUE)
2351 printf("getblk: vmioing file type %d???\n", vp->v_type);
2354 bp->b_flags &= ~B_VMIO;
2360 bp->b_flags &= ~B_DONE;
2366 * Get an empty, disassociated buffer of given size. The buffer is initially
2369 * spl protection is not required for the allocbuf() call because races are
2379 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2382 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0);
2385 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2391 * This code constitutes the buffer memory from either anonymous system
2392 * memory (in the case of non-VMIO operations) or from an associated
2393 * VM object (in the case of VMIO operations). This code is able to
2394 * resize a buffer up or down.
2396 * Note that this code is tricky, and has many complications to resolve
2397 * deadlock or inconsistant data situations. Tread lightly!!!
2398 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2399 * the caller. Calling this code willy nilly can result in the loss of data.
2401 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2402 * B_CACHE for the non-VMIO case.
2404 * This routine does not need to be called at splbio() but you must own the
2408 allocbuf(struct buf *bp, int size)
2410 int newbsize, mbsize;
2413 if (BUF_REFCNT(bp) == 0)
2414 panic("allocbuf: buffer not busy");
2416 if (bp->b_kvasize < size)
2417 panic("allocbuf: buffer too small");
2419 if ((bp->b_flags & B_VMIO) == 0) {
2423 * Just get anonymous memory from the kernel. Don't
2424 * mess with B_CACHE.
2426 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2427 #if !defined(NO_B_MALLOC)
2428 if (bp->b_flags & B_MALLOC)
2432 newbsize = round_page(size);
2434 if (newbsize < bp->b_bufsize) {
2435 #if !defined(NO_B_MALLOC)
2437 * malloced buffers are not shrunk
2439 if (bp->b_flags & B_MALLOC) {
2441 bp->b_bcount = size;
2443 free(bp->b_data, M_BIOBUF);
2444 if (bp->b_bufsize) {
2445 bufmallocspace -= bp->b_bufsize;
2449 bp->b_data = bp->b_kvabase;
2451 bp->b_flags &= ~B_MALLOC;
2458 (vm_offset_t) bp->b_data + newbsize,
2459 (vm_offset_t) bp->b_data + bp->b_bufsize);
2460 } else if (newbsize > bp->b_bufsize) {
2461 #if !defined(NO_B_MALLOC)
2463 * We only use malloced memory on the first allocation.
2464 * and revert to page-allocated memory when the buffer
2467 if ( (bufmallocspace < maxbufmallocspace) &&
2468 (bp->b_bufsize == 0) &&
2469 (mbsize <= PAGE_SIZE/2)) {
2471 bp->b_data = malloc(mbsize, M_BIOBUF, M_WAITOK);
2472 bp->b_bufsize = mbsize;
2473 bp->b_bcount = size;
2474 bp->b_flags |= B_MALLOC;
2475 bufmallocspace += mbsize;
2481 #if !defined(NO_B_MALLOC)
2483 * If the buffer is growing on its other-than-first allocation,
2484 * then we revert to the page-allocation scheme.
2486 if (bp->b_flags & B_MALLOC) {
2487 origbuf = bp->b_data;
2488 origbufsize = bp->b_bufsize;
2489 bp->b_data = bp->b_kvabase;
2490 if (bp->b_bufsize) {
2491 bufmallocspace -= bp->b_bufsize;
2495 bp->b_flags &= ~B_MALLOC;
2496 newbsize = round_page(newbsize);
2501 (vm_offset_t) bp->b_data + bp->b_bufsize,
2502 (vm_offset_t) bp->b_data + newbsize);
2503 #if !defined(NO_B_MALLOC)
2505 bcopy(origbuf, bp->b_data, origbufsize);
2506 free(origbuf, M_BIOBUF);
2514 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2515 desiredpages = (size == 0) ? 0 :
2516 num_pages((bp->b_offset & PAGE_MASK) + newbsize);
2518 #if !defined(NO_B_MALLOC)
2519 if (bp->b_flags & B_MALLOC)
2520 panic("allocbuf: VMIO buffer can't be malloced");
2523 * Set B_CACHE initially if buffer is 0 length or will become
2526 if (size == 0 || bp->b_bufsize == 0)
2527 bp->b_flags |= B_CACHE;
2529 if (newbsize < bp->b_bufsize) {
2531 * DEV_BSIZE aligned new buffer size is less then the
2532 * DEV_BSIZE aligned existing buffer size. Figure out
2533 * if we have to remove any pages.
2535 if (desiredpages < bp->b_xio.xio_npages) {
2536 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2538 * the page is not freed here -- it
2539 * is the responsibility of
2540 * vnode_pager_setsize
2542 m = bp->b_xio.xio_pages[i];
2543 KASSERT(m != bogus_page,
2544 ("allocbuf: bogus page found"));
2545 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2548 bp->b_xio.xio_pages[i] = NULL;
2549 vm_page_unwire(m, 0);
2551 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2552 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2553 bp->b_xio.xio_npages = desiredpages;
2555 } else if (size > bp->b_bcount) {
2557 * We are growing the buffer, possibly in a
2558 * byte-granular fashion.
2567 * Step 1, bring in the VM pages from the object,
2568 * allocating them if necessary. We must clear
2569 * B_CACHE if these pages are not valid for the
2570 * range covered by the buffer.
2572 * spl protection is required to protect against
2573 * interrupts unbusying and freeing pages between
2574 * our vm_page_lookup() and our busycheck/wiring
2578 VOP_GETVOBJECT(vp, &obj);
2581 while (bp->b_xio.xio_npages < desiredpages) {
2585 pi = OFF_TO_IDX(bp->b_offset) + bp->b_xio.xio_npages;
2586 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2588 * note: must allocate system pages
2589 * since blocking here could intefere
2590 * with paging I/O, no matter which
2593 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2596 vm_pageout_deficit += desiredpages -
2597 bp->b_xio.xio_npages;
2601 bp->b_flags &= ~B_CACHE;
2602 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2603 ++bp->b_xio.xio_npages;
2609 * We found a page. If we have to sleep on it,
2610 * retry because it might have gotten freed out
2613 * We can only test PG_BUSY here. Blocking on
2614 * m->busy might lead to a deadlock:
2616 * vm_fault->getpages->cluster_read->allocbuf
2620 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2624 * We have a good page. Should we wakeup the
2627 if ((curthread != pagethread) &&
2628 ((m->queue - m->pc) == PQ_CACHE) &&
2629 ((vmstats.v_free_count + vmstats.v_cache_count) <
2630 (vmstats.v_free_min + vmstats.v_cache_min))) {
2631 pagedaemon_wakeup();
2633 vm_page_flag_clear(m, PG_ZERO);
2635 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2636 ++bp->b_xio.xio_npages;
2641 * Step 2. We've loaded the pages into the buffer,
2642 * we have to figure out if we can still have B_CACHE
2643 * set. Note that B_CACHE is set according to the
2644 * byte-granular range ( bcount and size ), new the
2645 * aligned range ( newbsize ).
2647 * The VM test is against m->valid, which is DEV_BSIZE
2648 * aligned. Needless to say, the validity of the data
2649 * needs to also be DEV_BSIZE aligned. Note that this
2650 * fails with NFS if the server or some other client
2651 * extends the file's EOF. If our buffer is resized,
2652 * B_CACHE may remain set! XXX
2655 toff = bp->b_bcount;
2656 tinc = PAGE_SIZE - ((bp->b_offset + toff) & PAGE_MASK);
2658 while ((bp->b_flags & B_CACHE) && toff < size) {
2661 if (tinc > (size - toff))
2664 pi = ((bp->b_offset & PAGE_MASK) + toff) >>
2672 bp->b_xio.xio_pages[pi]
2679 * Step 3, fixup the KVM pmap. Remember that
2680 * bp->b_data is relative to bp->b_offset, but
2681 * bp->b_offset may be offset into the first page.
2684 bp->b_data = (caddr_t)
2685 trunc_page((vm_offset_t)bp->b_data);
2687 (vm_offset_t)bp->b_data,
2688 bp->b_xio.xio_pages,
2689 bp->b_xio.xio_npages
2691 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2692 (vm_offset_t)(bp->b_offset & PAGE_MASK));
2695 if (newbsize < bp->b_bufsize)
2697 bp->b_bufsize = newbsize; /* actual buffer allocation */
2698 bp->b_bcount = size; /* requested buffer size */
2705 * Wait for buffer I/O completion, returning error status. The buffer
2706 * is left locked and B_DONE on return. B_EINTR is converted into a EINTR
2707 * error and cleared.
2710 biowait(struct buf * bp)
2715 while ((bp->b_flags & B_DONE) == 0) {
2716 #if defined(NO_SCHEDULE_MODS)
2717 tsleep(bp, 0, "biowait", 0);
2719 if (bp->b_flags & B_READ)
2720 tsleep(bp, 0, "biord", 0);
2722 tsleep(bp, 0, "biowr", 0);
2726 if (bp->b_flags & B_EINTR) {
2727 bp->b_flags &= ~B_EINTR;
2730 if (bp->b_flags & B_ERROR) {
2731 return (bp->b_error ? bp->b_error : EIO);
2740 * Finish I/O on a buffer, optionally calling a completion function.
2741 * This is usually called from an interrupt so process blocking is
2744 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2745 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2746 * assuming B_INVAL is clear.
2748 * For the VMIO case, we set B_CACHE if the op was a read and no
2749 * read error occured, or if the op was a write. B_CACHE is never
2750 * set if the buffer is invalid or otherwise uncacheable.
2752 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2753 * initiator to leave B_INVAL set to brelse the buffer out of existance
2754 * in the biodone routine.
2756 * b_dev is required to be reinitialized prior to the top level strategy
2757 * call in a device stack. To avoid improper reuse, biodone() sets
2761 biodone(struct buf *bp)
2767 KASSERT(BUF_REFCNT(bp) > 0, ("biodone: bp %p not busy %d", bp, BUF_REFCNT(bp)));
2768 KASSERT(!(bp->b_flags & B_DONE), ("biodone: bp %p already done", bp));
2770 bp->b_flags |= B_DONE;
2772 runningbufwakeup(bp);
2774 if (bp->b_flags & B_FREEBUF) {
2780 if ((bp->b_flags & B_READ) == 0) {
2784 /* call optional completion function if requested */
2785 if (bp->b_flags & B_CALL) {
2786 bp->b_flags &= ~B_CALL;
2787 (*bp->b_iodone) (bp);
2791 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
2792 (*bioops.io_complete)(bp);
2794 if (bp->b_flags & B_VMIO) {
2800 struct vnode *vp = bp->b_vp;
2802 error = VOP_GETVOBJECT(vp, &obj);
2804 #if defined(VFS_BIO_DEBUG)
2805 if (vp->v_holdcnt == 0) {
2806 panic("biodone: zero vnode hold count");
2810 panic("biodone: missing VM object");
2813 if ((vp->v_flag & VOBJBUF) == 0) {
2814 panic("biodone: vnode is not setup for merged cache");
2818 foff = bp->b_offset;
2819 KASSERT(bp->b_offset != NOOFFSET,
2820 ("biodone: no buffer offset"));
2823 panic("biodone: no object");
2825 #if defined(VFS_BIO_DEBUG)
2826 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
2827 printf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
2828 obj->paging_in_progress, bp->b_xio.xio_npages);
2833 * Set B_CACHE if the op was a normal read and no error
2834 * occured. B_CACHE is set for writes in the b*write()
2837 iosize = bp->b_bcount - bp->b_resid;
2838 if ((bp->b_flags & (B_READ|B_FREEBUF|B_INVAL|B_NOCACHE|B_ERROR)) == B_READ) {
2839 bp->b_flags |= B_CACHE;
2842 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2846 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
2851 * cleanup bogus pages, restoring the originals. Since
2852 * the originals should still be wired, we don't have
2853 * to worry about interrupt/freeing races destroying
2854 * the VM object association.
2856 m = bp->b_xio.xio_pages[i];
2857 if (m == bogus_page) {
2859 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
2861 panic("biodone: page disappeared");
2862 bp->b_xio.xio_pages[i] = m;
2863 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2864 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
2866 #if defined(VFS_BIO_DEBUG)
2867 if (OFF_TO_IDX(foff) != m->pindex) {
2869 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
2870 (unsigned long)foff, m->pindex);
2875 * In the write case, the valid and clean bits are
2876 * already changed correctly ( see bdwrite() ), so we
2877 * only need to do this here in the read case.
2879 if ((bp->b_flags & B_READ) && !bogusflag && resid > 0) {
2880 vfs_page_set_valid(bp, foff, i, m);
2882 vm_page_flag_clear(m, PG_ZERO);
2885 * when debugging new filesystems or buffer I/O methods, this
2886 * is the most common error that pops up. if you see this, you
2887 * have not set the page busy flag correctly!!!
2890 printf("biodone: page busy < 0, "
2891 "pindex: %d, foff: 0x(%x,%x), "
2892 "resid: %d, index: %d\n",
2893 (int) m->pindex, (int)(foff >> 32),
2894 (int) foff & 0xffffffff, resid, i);
2895 if (!vn_isdisk(vp, NULL))
2896 printf(" iosize: %ld, lblkno: %d, flags: 0x%lx, npages: %d\n",
2897 bp->b_vp->v_mount->mnt_stat.f_iosize,
2899 bp->b_flags, bp->b_xio.xio_npages);
2901 printf(" VDEV, lblkno: %d, flags: 0x%lx, npages: %d\n",
2903 bp->b_flags, bp->b_xio.xio_npages);
2904 printf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
2905 m->valid, m->dirty, m->wire_count);
2906 panic("biodone: page busy < 0");
2908 vm_page_io_finish(m);
2909 vm_object_pip_subtract(obj, 1);
2910 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2914 vm_object_pip_wakeupn(obj, 0);
2918 * For asynchronous completions, release the buffer now. The brelse
2919 * will do a wakeup there if necessary - so no need to do a wakeup
2920 * here in the async case. The sync case always needs to do a wakeup.
2923 if (bp->b_flags & B_ASYNC) {
2924 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
2935 * This routine is called in lieu of iodone in the case of
2936 * incomplete I/O. This keeps the busy status for pages
2940 vfs_unbusy_pages(struct buf *bp)
2944 runningbufwakeup(bp);
2945 if (bp->b_flags & B_VMIO) {
2946 struct vnode *vp = bp->b_vp;
2949 VOP_GETVOBJECT(vp, &obj);
2951 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2952 vm_page_t m = bp->b_xio.xio_pages[i];
2955 * When restoring bogus changes the original pages
2956 * should still be wired, so we are in no danger of
2957 * losing the object association and do not need
2958 * spl protection particularly.
2960 if (m == bogus_page) {
2961 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_offset) + i);
2963 panic("vfs_unbusy_pages: page missing");
2965 bp->b_xio.xio_pages[i] = m;
2966 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
2967 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
2969 vm_object_pip_subtract(obj, 1);
2970 vm_page_flag_clear(m, PG_ZERO);
2971 vm_page_io_finish(m);
2973 vm_object_pip_wakeupn(obj, 0);
2978 * vfs_page_set_valid:
2980 * Set the valid bits in a page based on the supplied offset. The
2981 * range is restricted to the buffer's size.
2983 * This routine is typically called after a read completes.
2986 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
2988 vm_ooffset_t soff, eoff;
2991 * Start and end offsets in buffer. eoff - soff may not cross a
2992 * page boundry or cross the end of the buffer. The end of the
2993 * buffer, in this case, is our file EOF, not the allocation size
2997 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
2998 if (eoff > bp->b_offset + bp->b_bcount)
2999 eoff = bp->b_offset + bp->b_bcount;
3002 * Set valid range. This is typically the entire buffer and thus the
3006 vm_page_set_validclean(
3008 (vm_offset_t) (soff & PAGE_MASK),
3009 (vm_offset_t) (eoff - soff)
3015 * This routine is called before a device strategy routine.
3016 * It is used to tell the VM system that paging I/O is in
3017 * progress, and treat the pages associated with the buffer
3018 * almost as being PG_BUSY. Also the object paging_in_progress
3019 * flag is handled to make sure that the object doesn't become
3022 * Since I/O has not been initiated yet, certain buffer flags
3023 * such as B_ERROR or B_INVAL may be in an inconsistant state
3024 * and should be ignored.
3027 vfs_busy_pages(struct buf *bp, int clear_modify)
3031 if (bp->b_flags & B_VMIO) {
3032 struct vnode *vp = bp->b_vp;
3036 VOP_GETVOBJECT(vp, &obj);
3037 foff = bp->b_offset;
3038 KASSERT(bp->b_offset != NOOFFSET,
3039 ("vfs_busy_pages: no buffer offset"));
3043 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3044 vm_page_t m = bp->b_xio.xio_pages[i];
3045 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3050 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3051 vm_page_t m = bp->b_xio.xio_pages[i];
3053 vm_page_flag_clear(m, PG_ZERO);
3054 if ((bp->b_flags & B_CLUSTER) == 0) {
3055 vm_object_pip_add(obj, 1);
3056 vm_page_io_start(m);
3060 * When readying a buffer for a read ( i.e
3061 * clear_modify == 0 ), it is important to do
3062 * bogus_page replacement for valid pages in
3063 * partially instantiated buffers. Partially
3064 * instantiated buffers can, in turn, occur when
3065 * reconstituting a buffer from its VM backing store
3066 * base. We only have to do this if B_CACHE is
3067 * clear ( which causes the I/O to occur in the
3068 * first place ). The replacement prevents the read
3069 * I/O from overwriting potentially dirty VM-backed
3070 * pages. XXX bogus page replacement is, uh, bogus.
3071 * It may not work properly with small-block devices.
3072 * We need to find a better way.
3075 vm_page_protect(m, VM_PROT_NONE);
3077 vfs_page_set_valid(bp, foff, i, m);
3078 else if (m->valid == VM_PAGE_BITS_ALL &&
3079 (bp->b_flags & B_CACHE) == 0) {
3080 bp->b_xio.xio_pages[i] = bogus_page;
3083 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3086 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3087 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3091 * This is the easiest place to put the process accounting for the I/O
3097 if ((p = curthread->td_proc) != NULL) {
3098 if (bp->b_flags & B_READ)
3099 p->p_stats->p_ru.ru_inblock++;
3101 p->p_stats->p_ru.ru_oublock++;
3107 * Tell the VM system that the pages associated with this buffer
3108 * are clean. This is used for delayed writes where the data is
3109 * going to go to disk eventually without additional VM intevention.
3111 * Note that while we only really need to clean through to b_bcount, we
3112 * just go ahead and clean through to b_bufsize.
3115 vfs_clean_pages(struct buf *bp)
3119 if (bp->b_flags & B_VMIO) {
3122 foff = bp->b_offset;
3123 KASSERT(bp->b_offset != NOOFFSET,
3124 ("vfs_clean_pages: no buffer offset"));
3125 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3126 vm_page_t m = bp->b_xio.xio_pages[i];
3127 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3128 vm_ooffset_t eoff = noff;
3130 if (eoff > bp->b_offset + bp->b_bufsize)
3131 eoff = bp->b_offset + bp->b_bufsize;
3132 vfs_page_set_valid(bp, foff, i, m);
3133 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3140 * vfs_bio_set_validclean:
3142 * Set the range within the buffer to valid and clean. The range is
3143 * relative to the beginning of the buffer, b_offset. Note that b_offset
3144 * itself may be offset from the beginning of the first page.
3148 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3150 if (bp->b_flags & B_VMIO) {
3155 * Fixup base to be relative to beginning of first page.
3156 * Set initial n to be the maximum number of bytes in the
3157 * first page that can be validated.
3160 base += (bp->b_offset & PAGE_MASK);
3161 n = PAGE_SIZE - (base & PAGE_MASK);
3163 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3164 vm_page_t m = bp->b_xio.xio_pages[i];
3169 vm_page_set_validclean(m, base & PAGE_MASK, n);
3180 * clear a buffer. This routine essentially fakes an I/O, so we need
3181 * to clear B_ERROR and B_INVAL.
3183 * Note that while we only theoretically need to clear through b_bcount,
3184 * we go ahead and clear through b_bufsize.
3188 vfs_bio_clrbuf(struct buf *bp)
3192 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3193 bp->b_flags &= ~(B_INVAL|B_ERROR);
3194 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3195 (bp->b_offset & PAGE_MASK) == 0) {
3196 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3197 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3201 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3202 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3203 bzero(bp->b_data, bp->b_bufsize);
3204 bp->b_xio.xio_pages[0]->valid |= mask;
3209 ea = sa = bp->b_data;
3210 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3211 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3212 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3213 ea = (caddr_t)(vm_offset_t)ulmin(
3214 (u_long)(vm_offset_t)ea,
3215 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3216 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3217 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3219 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3220 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3224 for (; sa < ea; sa += DEV_BSIZE, j++) {
3225 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3226 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3227 bzero(sa, DEV_BSIZE);
3230 bp->b_xio.xio_pages[i]->valid |= mask;
3231 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3240 * vm_hold_load_pages and vm_hold_unload pages get pages into
3241 * a buffers address space. The pages are anonymous and are
3242 * not associated with a file object.
3245 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3251 to = round_page(to);
3252 from = round_page(from);
3253 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3255 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3260 * note: must allocate system pages since blocking here
3261 * could intefere with paging I/O, no matter which
3264 p = vm_page_alloc(kernel_object,
3265 ((pg - VM_MIN_KERNEL_ADDRESS) >> PAGE_SHIFT),
3266 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3268 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3273 p->valid = VM_PAGE_BITS_ALL;
3274 vm_page_flag_clear(p, PG_ZERO);
3275 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3276 bp->b_xio.xio_pages[index] = p;
3279 bp->b_xio.xio_npages = index;
3283 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3287 int index, newnpages;
3289 from = round_page(from);
3290 to = round_page(to);
3291 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3293 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3294 p = bp->b_xio.xio_pages[index];
3295 if (p && (index < bp->b_xio.xio_npages)) {
3297 printf("vm_hold_free_pages: blkno: %d, lblkno: %d\n",
3298 bp->b_blkno, bp->b_lblkno);
3300 bp->b_xio.xio_pages[index] = NULL;
3303 vm_page_unwire(p, 0);
3307 bp->b_xio.xio_npages = newnpages;
3311 * Map an IO request into kernel virtual address space.
3313 * All requests are (re)mapped into kernel VA space.
3314 * Notice that we use b_bufsize for the size of the buffer
3315 * to be mapped. b_bcount might be modified by the driver.
3318 vmapbuf(struct buf *bp)
3320 caddr_t addr, v, kva;
3326 if ((bp->b_flags & B_PHYS) == 0)
3328 if (bp->b_bufsize < 0)
3330 for (v = bp->b_saveaddr,
3331 addr = (caddr_t)trunc_page((vm_offset_t)bp->b_data),
3333 addr < bp->b_data + bp->b_bufsize;
3334 addr += PAGE_SIZE, v += PAGE_SIZE, pidx++) {
3336 * Do the vm_fault if needed; do the copy-on-write thing
3337 * when reading stuff off device into memory.
3340 i = vm_fault_quick((addr >= bp->b_data) ? addr : bp->b_data,
3341 (bp->b_flags&B_READ)?(VM_PROT_READ|VM_PROT_WRITE):VM_PROT_READ);
3343 for (i = 0; i < pidx; ++i) {
3344 vm_page_unhold(bp->b_xio.xio_pages[i]);
3345 bp->b_xio.xio_pages[i] = NULL;
3351 * WARNING! If sparc support is MFCd in the future this will
3352 * have to be changed from pmap_kextract() to pmap_extract()
3356 #error "If MFCing sparc support use pmap_extract"
3358 pa = pmap_kextract((vm_offset_t)addr);
3360 printf("vmapbuf: warning, race against user address during I/O");
3363 m = PHYS_TO_VM_PAGE(pa);
3365 bp->b_xio.xio_pages[pidx] = m;
3367 if (pidx > btoc(MAXPHYS))
3368 panic("vmapbuf: mapped more than MAXPHYS");
3369 pmap_qenter((vm_offset_t)bp->b_saveaddr, bp->b_xio.xio_pages, pidx);
3371 kva = bp->b_saveaddr;
3372 bp->b_xio.xio_npages = pidx;
3373 bp->b_saveaddr = bp->b_data;
3374 bp->b_data = kva + (((vm_offset_t) bp->b_data) & PAGE_MASK);
3379 * Free the io map PTEs associated with this IO operation.
3380 * We also invalidate the TLB entries and restore the original b_addr.
3383 vunmapbuf(struct buf *bp)
3389 if ((bp->b_flags & B_PHYS) == 0)
3392 npages = bp->b_xio.xio_npages;
3393 pmap_qremove(trunc_page((vm_offset_t)bp->b_data),
3395 m = bp->b_xio.xio_pages;
3396 for (pidx = 0; pidx < npages; pidx++)
3397 vm_page_unhold(*m++);
3399 bp->b_data = bp->b_saveaddr;
3402 #include "opt_ddb.h"
3404 #include <ddb/ddb.h>
3406 DB_SHOW_COMMAND(buffer, db_show_buffer)
3409 struct buf *bp = (struct buf *)addr;
3412 db_printf("usage: show buffer <addr>\n");
3416 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3417 db_printf("b_error = %d, b_bufsize = %ld, b_bcount = %ld, "
3418 "b_resid = %ld\nb_dev = (%d,%d), b_data = %p, "
3419 "b_blkno = %d, b_pblkno = %d\n",
3420 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3421 major(bp->b_dev), minor(bp->b_dev),
3422 bp->b_data, bp->b_blkno, bp->b_pblkno);
3423 if (bp->b_xio.xio_npages) {
3425 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3426 bp->b_xio.xio_npages);
3427 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3429 m = bp->b_xio.xio_pages[i];
3430 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3431 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3432 if ((i + 1) < bp->b_xio.xio_npages)