Fix some IO sequencing performance issues and reformulate the strategy
[dfdiff.git] / sys / kern / vfs_bio.c
blob09c6331ee2dfc6faae7e9141a12688c7c7523690
1 /*
2 * Copyright (c) 1994,1997 John S. Dyson
3 * All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
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
12 * John S. Dyson.
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.99 2008/04/22 18:46:51 dillon Exp $
19 * this file contains a new buffer I/O scheme implementing a coherent
20 * VM object and buffer cache scheme. Pains have been taken to make
21 * sure that the performance degradation associated with schemes such
22 * as this is not realized.
24 * Author: John S. Dyson
25 * Significant help during the development and debugging phases
26 * had been provided by David Greenman, also of the FreeBSD core team.
28 * see man buf(9) for more info.
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/buf.h>
34 #include <sys/conf.h>
35 #include <sys/eventhandler.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/proc.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>
47 #include <sys/proc.h>
48 #include <vm/vm.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 <sys/buf2.h>
58 #include <sys/thread2.h>
59 #include <sys/spinlock2.h>
60 #include <vm/vm_page2.h>
62 #include "opt_ddb.h"
63 #ifdef DDB
64 #include <ddb/ddb.h>
65 #endif
68 * Buffer queues.
70 enum bufq_type {
71 BQUEUE_NONE, /* not on any queue */
72 BQUEUE_LOCKED, /* locked buffers */
73 BQUEUE_CLEAN, /* non-B_DELWRI buffers */
74 BQUEUE_DIRTY, /* B_DELWRI buffers */
75 BQUEUE_DIRTY_HW, /* B_DELWRI buffers - heavy weight */
76 BQUEUE_EMPTYKVA, /* empty buffer headers with KVA assignment */
77 BQUEUE_EMPTY, /* empty buffer headers */
79 BUFFER_QUEUES /* number of buffer queues */
82 typedef enum bufq_type bufq_type_t;
84 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
86 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
88 struct buf *buf; /* buffer header pool */
90 static void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
91 vm_offset_t to);
92 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
93 vm_offset_t to);
94 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
95 int pageno, vm_page_t m);
96 static void vfs_clean_pages(struct buf *bp);
97 static void vfs_setdirty(struct buf *bp);
98 static void vfs_vmio_release(struct buf *bp);
99 static int flushbufqueues(bufq_type_t q);
101 static void buf_daemon(void);
102 static void buf_daemon_hw(void);
104 * bogus page -- for I/O to/from partially complete buffers
105 * this is a temporary solution to the problem, but it is not
106 * really that bad. it would be better to split the buffer
107 * for input in the case of buffers partially already in memory,
108 * but the code is intricate enough already.
110 vm_page_t bogus_page;
111 int runningbufspace;
114 * These are all static, but make the ones we export globals so we do
115 * not need to use compiler magic.
117 int bufspace, maxbufspace,
118 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
119 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
120 static int lorunningspace, hirunningspace, runningbufreq;
121 int numdirtybuffers, numdirtybuffershw, lodirtybuffers, hidirtybuffers;
122 static int numfreebuffers, lofreebuffers, hifreebuffers;
123 static int getnewbufcalls;
124 static int getnewbufrestarts;
126 static int needsbuffer; /* locked by needsbuffer_spin */
127 static int bd_request; /* locked by needsbuffer_spin */
128 static int bd_request_hw; /* locked by needsbuffer_spin */
129 static struct spinlock needsbuffer_spin;
132 * Sysctls for operational control of the buffer cache.
134 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
135 "Number of dirty buffers to flush before bufdaemon becomes inactive");
136 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
137 "High watermark used to trigger explicit flushing of dirty buffers");
138 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
139 "Low watermark for special reserve in low-memory situations");
140 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
141 "High watermark for special reserve in low-memory situations");
142 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
143 "Minimum amount of buffer space required for active I/O");
144 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
145 "Maximum amount of buffer space to usable for active I/O");
147 * Sysctls determining current state of the buffer cache.
149 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
150 "Pending number of dirty buffers (all)");
151 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffershw, CTLFLAG_RD, &numdirtybuffershw, 0,
152 "Pending number of dirty buffers (heavy weight)");
153 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
154 "Number of free buffers on the buffer cache free list");
155 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
156 "I/O bytes currently in progress due to asynchronous writes");
157 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
158 "Hard limit on maximum amount of memory usable for buffer space");
159 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
160 "Soft limit on maximum amount of memory usable for buffer space");
161 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
162 "Minimum amount of memory to reserve for system buffer space");
163 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
164 "Amount of memory available for buffers");
165 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
166 0, "Maximum amount of memory reserved for buffers using malloc");
167 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
168 "Amount of memory left for buffers using malloc-scheme");
169 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
170 "New buffer header acquisition requests");
171 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
172 0, "New buffer header acquisition restarts");
173 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
174 "Buffer acquisition restarts due to fragmented buffer map");
175 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
176 "Amount of time KVA space was deallocated in an arbitrary buffer");
177 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
178 "Amount of time buffer re-use operations were successful");
179 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
180 "sizeof(struct buf)");
182 char *buf_wmesg = BUF_WMESG;
184 extern int vm_swap_size;
186 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
187 #define VFS_BIO_NEED_DIRTYFLUSH 0x02 /* waiting for dirty buffer flush */
188 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
189 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
192 * numdirtywakeup:
194 * If someone is blocked due to there being too many dirty buffers,
195 * and numdirtybuffers is now reasonable, wake them up.
197 static __inline void
198 numdirtywakeup(void)
200 if (numdirtybuffers <= (lodirtybuffers + hidirtybuffers) / 2) {
201 if (needsbuffer & VFS_BIO_NEED_DIRTYFLUSH) {
202 spin_lock_wr(&needsbuffer_spin);
203 needsbuffer &= ~VFS_BIO_NEED_DIRTYFLUSH;
204 spin_unlock_wr(&needsbuffer_spin);
205 wakeup(&needsbuffer);
211 * bufspacewakeup:
213 * Called when buffer space is potentially available for recovery.
214 * getnewbuf() will block on this flag when it is unable to free
215 * sufficient buffer space. Buffer space becomes recoverable when
216 * bp's get placed back in the queues.
219 static __inline void
220 bufspacewakeup(void)
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 spin_lock_wr(&needsbuffer_spin);
229 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
230 spin_unlock_wr(&needsbuffer_spin);
231 wakeup(&needsbuffer);
236 * runningbufwakeup:
238 * Accounting for I/O in progress.
241 static __inline void
242 runningbufwakeup(struct buf *bp)
244 if (bp->b_runningbufspace) {
245 runningbufspace -= bp->b_runningbufspace;
246 bp->b_runningbufspace = 0;
247 if (runningbufreq && runningbufspace <= lorunningspace) {
248 runningbufreq = 0;
249 wakeup(&runningbufreq);
255 * bufcountwakeup:
257 * Called when a buffer has been added to one of the free queues to
258 * account for the buffer and to wakeup anyone waiting for free buffers.
259 * This typically occurs when large amounts of metadata are being handled
260 * by the buffer cache ( else buffer space runs out first, usually ).
263 static __inline void
264 bufcountwakeup(void)
266 ++numfreebuffers;
267 if (needsbuffer) {
268 spin_lock_wr(&needsbuffer_spin);
269 needsbuffer &= ~VFS_BIO_NEED_ANY;
270 if (numfreebuffers >= hifreebuffers)
271 needsbuffer &= ~VFS_BIO_NEED_FREE;
272 spin_unlock_wr(&needsbuffer_spin);
273 wakeup(&needsbuffer);
278 * waitrunningbufspace()
280 * runningbufspace is a measure of the amount of I/O currently
281 * running. This routine is used in async-write situations to
282 * prevent creating huge backups of pending writes to a device.
283 * Only asynchronous writes are governed by this function.
285 * Reads will adjust runningbufspace, but will not block based on it.
286 * The read load has a side effect of reducing the allowed write load.
288 * This does NOT turn an async write into a sync write. It waits
289 * for earlier writes to complete and generally returns before the
290 * caller's write has reached the device.
292 static __inline void
293 waitrunningbufspace(void)
295 if (runningbufspace > hirunningspace) {
296 crit_enter();
297 while (runningbufspace > hirunningspace) {
298 ++runningbufreq;
299 tsleep(&runningbufreq, 0, "wdrain", 0);
301 crit_exit();
306 * vfs_buf_test_cache:
308 * Called when a buffer is extended. This function clears the B_CACHE
309 * bit if the newly extended portion of the buffer does not contain
310 * valid data.
312 static __inline__
313 void
314 vfs_buf_test_cache(struct buf *bp,
315 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
316 vm_page_t m)
318 if (bp->b_flags & B_CACHE) {
319 int base = (foff + off) & PAGE_MASK;
320 if (vm_page_is_valid(m, base, size) == 0)
321 bp->b_flags &= ~B_CACHE;
326 * bd_wakeup:
328 * Wake up the buffer daemon if the number of outstanding dirty buffers
329 * is above specified threshold 'dirtybuflevel'.
331 * The buffer daemons are explicitly woken up when (a) the pending number
332 * of dirty buffers exceeds the recovery and stall mid-point value,
333 * (b) during bwillwrite() or (c) buf freelist was exhausted.
335 * The buffer daemons will generally not stop flushing until the dirty
336 * buffer count goes below lodirtybuffers.
338 static __inline__
339 void
340 bd_wakeup(int dirtybuflevel)
342 if (bd_request == 0 && numdirtybuffers >= dirtybuflevel) {
343 spin_lock_wr(&needsbuffer_spin);
344 bd_request = 1;
345 spin_unlock_wr(&needsbuffer_spin);
346 wakeup(&bd_request);
348 if (bd_request_hw == 0 && numdirtybuffershw >= dirtybuflevel) {
349 spin_lock_wr(&needsbuffer_spin);
350 bd_request_hw = 1;
351 spin_unlock_wr(&needsbuffer_spin);
352 wakeup(&bd_request_hw);
357 * bd_speedup:
359 * Speed up the buffer cache flushing process.
362 static __inline__
363 void
364 bd_speedup(void)
366 bd_wakeup(1);
370 * bufinit:
372 * Load time initialisation of the buffer cache, called from machine
373 * dependant initialization code.
375 void
376 bufinit(void)
378 struct buf *bp;
379 vm_offset_t bogus_offset;
380 int i;
382 spin_init(&needsbuffer_spin);
384 /* next, make a null set of free lists */
385 for (i = 0; i < BUFFER_QUEUES; i++)
386 TAILQ_INIT(&bufqueues[i]);
388 /* finally, initialize each buffer header and stick on empty q */
389 for (i = 0; i < nbuf; i++) {
390 bp = &buf[i];
391 bzero(bp, sizeof *bp);
392 bp->b_flags = B_INVAL; /* we're just an empty header */
393 bp->b_cmd = BUF_CMD_DONE;
394 bp->b_qindex = BQUEUE_EMPTY;
395 initbufbio(bp);
396 xio_init(&bp->b_xio);
397 buf_dep_init(bp);
398 BUF_LOCKINIT(bp);
399 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
403 * maxbufspace is the absolute maximum amount of buffer space we are
404 * allowed to reserve in KVM and in real terms. The absolute maximum
405 * is nominally used by buf_daemon. hibufspace is the nominal maximum
406 * used by most other processes. The differential is required to
407 * ensure that buf_daemon is able to run when other processes might
408 * be blocked waiting for buffer space.
410 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
411 * this may result in KVM fragmentation which is not handled optimally
412 * by the system.
414 maxbufspace = nbuf * BKVASIZE;
415 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
416 lobufspace = hibufspace - MAXBSIZE;
418 lorunningspace = 512 * 1024;
419 hirunningspace = 1024 * 1024;
422 * Limit the amount of malloc memory since it is wired permanently into
423 * the kernel space. Even though this is accounted for in the buffer
424 * allocation, we don't want the malloced region to grow uncontrolled.
425 * The malloc scheme improves memory utilization significantly on average
426 * (small) directories.
428 maxbufmallocspace = hibufspace / 20;
431 * Reduce the chance of a deadlock occuring by limiting the number
432 * of delayed-write dirty buffers we allow to stack up.
434 hidirtybuffers = nbuf / 4 + 20;
435 numdirtybuffers = 0;
436 numdirtybuffershw = 0;
438 * To support extreme low-memory systems, make sure hidirtybuffers cannot
439 * eat up all available buffer space. This occurs when our minimum cannot
440 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
441 * BKVASIZE'd (8K) buffers.
443 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
444 hidirtybuffers >>= 1;
446 lodirtybuffers = hidirtybuffers / 2;
449 * Try to keep the number of free buffers in the specified range,
450 * and give special processes (e.g. like buf_daemon) access to an
451 * emergency reserve.
453 lofreebuffers = nbuf / 18 + 5;
454 hifreebuffers = 2 * lofreebuffers;
455 numfreebuffers = nbuf;
458 * Maximum number of async ops initiated per buf_daemon loop. This is
459 * somewhat of a hack at the moment, we really need to limit ourselves
460 * based on the number of bytes of I/O in-transit that were initiated
461 * from buf_daemon.
464 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
465 bogus_page = vm_page_alloc(&kernel_object,
466 (bogus_offset >> PAGE_SHIFT),
467 VM_ALLOC_NORMAL);
468 vmstats.v_wire_count++;
473 * Initialize the embedded bio structures
475 void
476 initbufbio(struct buf *bp)
478 bp->b_bio1.bio_buf = bp;
479 bp->b_bio1.bio_prev = NULL;
480 bp->b_bio1.bio_offset = NOOFFSET;
481 bp->b_bio1.bio_next = &bp->b_bio2;
482 bp->b_bio1.bio_done = NULL;
484 bp->b_bio2.bio_buf = bp;
485 bp->b_bio2.bio_prev = &bp->b_bio1;
486 bp->b_bio2.bio_offset = NOOFFSET;
487 bp->b_bio2.bio_next = NULL;
488 bp->b_bio2.bio_done = NULL;
492 * Reinitialize the embedded bio structures as well as any additional
493 * translation cache layers.
495 void
496 reinitbufbio(struct buf *bp)
498 struct bio *bio;
500 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
501 bio->bio_done = NULL;
502 bio->bio_offset = NOOFFSET;
507 * Push another BIO layer onto an existing BIO and return it. The new
508 * BIO layer may already exist, holding cached translation data.
510 struct bio *
511 push_bio(struct bio *bio)
513 struct bio *nbio;
515 if ((nbio = bio->bio_next) == NULL) {
516 int index = bio - &bio->bio_buf->b_bio_array[0];
517 if (index >= NBUF_BIO - 1) {
518 panic("push_bio: too many layers bp %p\n",
519 bio->bio_buf);
521 nbio = &bio->bio_buf->b_bio_array[index + 1];
522 bio->bio_next = nbio;
523 nbio->bio_prev = bio;
524 nbio->bio_buf = bio->bio_buf;
525 nbio->bio_offset = NOOFFSET;
526 nbio->bio_done = NULL;
527 nbio->bio_next = NULL;
529 KKASSERT(nbio->bio_done == NULL);
530 return(nbio);
533 void
534 pop_bio(struct bio *bio)
536 /* NOP */
539 void
540 clearbiocache(struct bio *bio)
542 while (bio) {
543 bio->bio_offset = NOOFFSET;
544 bio = bio->bio_next;
549 * bfreekva:
551 * Free the KVA allocation for buffer 'bp'.
553 * Must be called from a critical section as this is the only locking for
554 * buffer_map.
556 * Since this call frees up buffer space, we call bufspacewakeup().
558 static void
559 bfreekva(struct buf *bp)
561 int count;
563 if (bp->b_kvasize) {
564 ++buffreekvacnt;
565 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
566 vm_map_lock(&buffer_map);
567 bufspace -= bp->b_kvasize;
568 vm_map_delete(&buffer_map,
569 (vm_offset_t) bp->b_kvabase,
570 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
571 &count
573 vm_map_unlock(&buffer_map);
574 vm_map_entry_release(count);
575 bp->b_kvasize = 0;
576 bufspacewakeup();
581 * bremfree:
583 * Remove the buffer from the appropriate free list.
585 void
586 bremfree(struct buf *bp)
588 int old_qindex;
590 crit_enter();
591 old_qindex = bp->b_qindex;
593 if (bp->b_qindex != BQUEUE_NONE) {
594 KASSERT(BUF_REFCNTNB(bp) == 1,
595 ("bremfree: bp %p not locked",bp));
596 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
597 bp->b_qindex = BQUEUE_NONE;
598 } else {
599 if (BUF_REFCNTNB(bp) <= 1)
600 panic("bremfree: removing a buffer not on a queue");
604 * Fixup numfreebuffers count. If the buffer is invalid or not
605 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
606 * the buffer was free and we must decrement numfreebuffers.
608 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
609 switch(old_qindex) {
610 case BQUEUE_DIRTY:
611 case BQUEUE_DIRTY_HW:
612 case BQUEUE_CLEAN:
613 case BQUEUE_EMPTY:
614 case BQUEUE_EMPTYKVA:
615 --numfreebuffers;
616 break;
617 default:
618 break;
621 crit_exit();
626 * bread:
628 * Get a buffer with the specified data. Look in the cache first. We
629 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
630 * is set, the buffer is valid and we do not have to do anything ( see
631 * getblk() ).
634 bread(struct vnode *vp, off_t loffset, int size, struct buf **bpp)
636 struct buf *bp;
638 bp = getblk(vp, loffset, size, 0, 0);
639 *bpp = bp;
641 /* if not found in cache, do some I/O */
642 if ((bp->b_flags & B_CACHE) == 0) {
643 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
644 bp->b_flags &= ~(B_ERROR | B_INVAL);
645 bp->b_cmd = BUF_CMD_READ;
646 vfs_busy_pages(vp, bp);
647 vn_strategy(vp, &bp->b_bio1);
648 return (biowait(bp));
650 return (0);
654 * breadn:
656 * Operates like bread, but also starts asynchronous I/O on
657 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
658 * to initiating I/O . If B_CACHE is set, the buffer is valid
659 * and we do not have to do anything.
662 breadn(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
663 int *rabsize, int cnt, struct buf **bpp)
665 struct buf *bp, *rabp;
666 int i;
667 int rv = 0, readwait = 0;
669 *bpp = bp = getblk(vp, loffset, size, 0, 0);
671 /* if not found in cache, do some I/O */
672 if ((bp->b_flags & B_CACHE) == 0) {
673 bp->b_flags &= ~(B_ERROR | B_INVAL);
674 bp->b_cmd = BUF_CMD_READ;
675 vfs_busy_pages(vp, bp);
676 vn_strategy(vp, &bp->b_bio1);
677 ++readwait;
680 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
681 if (inmem(vp, *raoffset))
682 continue;
683 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
685 if ((rabp->b_flags & B_CACHE) == 0) {
686 rabp->b_flags |= B_ASYNC;
687 rabp->b_flags &= ~(B_ERROR | B_INVAL);
688 rabp->b_cmd = BUF_CMD_READ;
689 vfs_busy_pages(vp, rabp);
690 BUF_KERNPROC(rabp);
691 vn_strategy(vp, &rabp->b_bio1);
692 } else {
693 brelse(rabp);
697 if (readwait) {
698 rv = biowait(bp);
700 return (rv);
704 * bwrite:
706 * Write, release buffer on completion. (Done by iodone
707 * if async). Do not bother writing anything if the buffer
708 * is invalid.
710 * Note that we set B_CACHE here, indicating that buffer is
711 * fully valid and thus cacheable. This is true even of NFS
712 * now so we set it generally. This could be set either here
713 * or in biodone() since the I/O is synchronous. We put it
714 * here.
717 bwrite(struct buf *bp)
719 int oldflags;
721 if (bp->b_flags & B_INVAL) {
722 brelse(bp);
723 return (0);
726 oldflags = bp->b_flags;
728 if (BUF_REFCNTNB(bp) == 0)
729 panic("bwrite: buffer is not busy???");
730 crit_enter();
732 /* Mark the buffer clean */
733 bundirty(bp);
735 bp->b_flags &= ~B_ERROR;
736 bp->b_flags |= B_CACHE;
737 bp->b_cmd = BUF_CMD_WRITE;
738 vfs_busy_pages(bp->b_vp, bp);
741 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
742 * valid for vnode-backed buffers.
744 bp->b_runningbufspace = bp->b_bufsize;
745 runningbufspace += bp->b_runningbufspace;
747 crit_exit();
748 if (oldflags & B_ASYNC)
749 BUF_KERNPROC(bp);
750 vn_strategy(bp->b_vp, &bp->b_bio1);
752 if ((oldflags & B_ASYNC) == 0) {
753 int rtval = biowait(bp);
754 brelse(bp);
755 return (rtval);
757 return (0);
761 * bdwrite:
763 * Delayed write. (Buffer is marked dirty). Do not bother writing
764 * anything if the buffer is marked invalid.
766 * Note that since the buffer must be completely valid, we can safely
767 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
768 * biodone() in order to prevent getblk from writing the buffer
769 * out synchronously.
771 void
772 bdwrite(struct buf *bp)
774 if (BUF_REFCNTNB(bp) == 0)
775 panic("bdwrite: buffer is not busy");
777 if (bp->b_flags & B_INVAL) {
778 brelse(bp);
779 return;
781 bdirty(bp);
784 * Set B_CACHE, indicating that the buffer is fully valid. This is
785 * true even of NFS now.
787 bp->b_flags |= B_CACHE;
790 * This bmap keeps the system from needing to do the bmap later,
791 * perhaps when the system is attempting to do a sync. Since it
792 * is likely that the indirect block -- or whatever other datastructure
793 * that the filesystem needs is still in memory now, it is a good
794 * thing to do this. Note also, that if the pageout daemon is
795 * requesting a sync -- there might not be enough memory to do
796 * the bmap then... So, this is important to do.
798 if (bp->b_bio2.bio_offset == NOOFFSET) {
799 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
800 NULL, NULL);
804 * Set the *dirty* buffer range based upon the VM system dirty pages.
806 vfs_setdirty(bp);
809 * We need to do this here to satisfy the vnode_pager and the
810 * pageout daemon, so that it thinks that the pages have been
811 * "cleaned". Note that since the pages are in a delayed write
812 * buffer -- the VFS layer "will" see that the pages get written
813 * out on the next sync, or perhaps the cluster will be completed.
815 vfs_clean_pages(bp);
816 bqrelse(bp);
819 * Wakeup the buffer flushing daemon if we have a lot of dirty
820 * buffers (midpoint between our recovery point and our stall
821 * point).
823 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
826 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
827 * due to the softdep code.
832 * bdirty:
834 * Turn buffer into delayed write request by marking it B_DELWRI.
835 * B_RELBUF and B_NOCACHE must be cleared.
837 * We reassign the buffer to itself to properly update it in the
838 * dirty/clean lists.
840 * Since the buffer is not on a queue, we do not update the
841 * numfreebuffers count.
843 * Must be called from a critical section.
844 * The buffer must be on BQUEUE_NONE.
846 void
847 bdirty(struct buf *bp)
849 KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
850 if (bp->b_flags & B_NOCACHE) {
851 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
852 bp->b_flags &= ~B_NOCACHE;
854 if (bp->b_flags & B_INVAL) {
855 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
857 bp->b_flags &= ~B_RELBUF;
859 if ((bp->b_flags & B_DELWRI) == 0) {
860 bp->b_flags |= B_DELWRI;
861 reassignbuf(bp);
862 ++numdirtybuffers;
863 if (bp->b_flags & B_HEAVY)
864 ++numdirtybuffershw;
865 bd_wakeup((lodirtybuffers + hidirtybuffers) / 2);
870 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
871 * needs to be flushed with a different buf_daemon thread to avoid
872 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
874 void
875 bheavy(struct buf *bp)
877 if ((bp->b_flags & B_HEAVY) == 0) {
878 bp->b_flags |= B_HEAVY;
879 if (bp->b_flags & B_DELWRI)
880 ++numdirtybuffershw;
885 * bundirty:
887 * Clear B_DELWRI for buffer.
889 * Since the buffer is not on a queue, we do not update the numfreebuffers
890 * count.
892 * Must be called from a critical section.
894 * The buffer is typically on BQUEUE_NONE but there is one case in
895 * brelse() that calls this function after placing the buffer on
896 * a different queue.
899 void
900 bundirty(struct buf *bp)
902 if (bp->b_flags & B_DELWRI) {
903 bp->b_flags &= ~B_DELWRI;
904 reassignbuf(bp);
905 --numdirtybuffers;
906 if (bp->b_flags & B_HEAVY)
907 --numdirtybuffershw;
908 numdirtywakeup();
911 * Since it is now being written, we can clear its deferred write flag.
913 bp->b_flags &= ~B_DEFERRED;
917 * bawrite:
919 * Asynchronous write. Start output on a buffer, but do not wait for
920 * it to complete. The buffer is released when the output completes.
922 * bwrite() ( or the VOP routine anyway ) is responsible for handling
923 * B_INVAL buffers. Not us.
925 void
926 bawrite(struct buf *bp)
928 bp->b_flags |= B_ASYNC;
929 bwrite(bp);
933 * bowrite:
935 * Ordered write. Start output on a buffer, and flag it so that the
936 * device will write it in the order it was queued. The buffer is
937 * released when the output completes. bwrite() ( or the VOP routine
938 * anyway ) is responsible for handling B_INVAL buffers.
941 bowrite(struct buf *bp)
943 bp->b_flags |= B_ORDERED | B_ASYNC;
944 return (bwrite(bp));
948 * bwillwrite:
950 * Called prior to the locking of any vnodes when we are expecting to
951 * write. We do not want to starve the buffer cache with too many
952 * dirty buffers so we block here. By blocking prior to the locking
953 * of any vnodes we attempt to avoid the situation where a locked vnode
954 * prevents the various system daemons from flushing related buffers.
956 void
957 bwillwrite(void)
959 if (numdirtybuffers >= hidirtybuffers / 2) {
960 bd_wakeup(1);
961 while (numdirtybuffers >= hidirtybuffers) {
962 bd_wakeup(1);
963 spin_lock_wr(&needsbuffer_spin);
964 if (numdirtybuffers >= hidirtybuffers) {
965 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
966 msleep(&needsbuffer, &needsbuffer_spin, 0,
967 "flswai", 0);
969 spin_unlock_wr(&needsbuffer_spin);
972 #if 0
973 /* FUTURE - maybe */
974 else if (numdirtybuffershw > hidirtybuffers / 2) {
975 bd_wakeup(1);
977 while (numdirtybuffershw > hidirtybuffers) {
978 needsbuffer |= VFS_BIO_NEED_DIRTYFLUSH;
979 tsleep(&needsbuffer, slpflags, "newbuf",
980 slptimeo);
983 #endif
987 * buf_dirty_count_severe:
989 * Return true if we have too many dirty buffers.
992 buf_dirty_count_severe(void)
994 return(numdirtybuffers >= hidirtybuffers);
998 * brelse:
1000 * Release a busy buffer and, if requested, free its resources. The
1001 * buffer will be stashed in the appropriate bufqueue[] allowing it
1002 * to be accessed later as a cache entity or reused for other purposes.
1004 void
1005 brelse(struct buf *bp)
1007 #ifdef INVARIANTS
1008 int saved_flags = bp->b_flags;
1009 #endif
1011 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1013 crit_enter();
1016 * If B_NOCACHE is set we are being asked to destroy the buffer and
1017 * its backing store. Clear B_DELWRI.
1019 * B_NOCACHE is set in two cases: (1) when the caller really wants
1020 * to destroy the buffer and backing store and (2) when the caller
1021 * wants to destroy the buffer and backing store after a write
1022 * completes.
1024 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1025 bundirty(bp);
1028 if (bp->b_flags & B_LOCKED)
1029 bp->b_flags &= ~B_ERROR;
1032 * If a write error occurs and the caller does not want to throw
1033 * away the buffer, redirty the buffer. This will also clear
1034 * B_NOCACHE.
1036 if (bp->b_cmd == BUF_CMD_WRITE &&
1037 (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
1039 * Failed write, redirty. Must clear B_ERROR to prevent
1040 * pages from being scrapped. If B_INVAL is set then
1041 * this case is not run and the next case is run to
1042 * destroy the buffer. B_INVAL can occur if the buffer
1043 * is outside the range supported by the underlying device.
1045 bp->b_flags &= ~B_ERROR;
1046 bdirty(bp);
1047 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1048 (bp->b_bufsize <= 0) || bp->b_cmd == BUF_CMD_FREEBLKS) {
1050 * Either a failed I/O or we were asked to free or not
1051 * cache the buffer.
1053 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1054 * buffer cannot be immediately freed.
1056 bp->b_flags |= B_INVAL;
1057 if (LIST_FIRST(&bp->b_dep) != NULL)
1058 buf_deallocate(bp);
1059 if (bp->b_flags & B_DELWRI) {
1060 --numdirtybuffers;
1061 if (bp->b_flags & B_HEAVY)
1062 --numdirtybuffershw;
1063 numdirtywakeup();
1065 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1069 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1070 * If vfs_vmio_release() is called with either bit set, the
1071 * underlying pages may wind up getting freed causing a previous
1072 * write (bdwrite()) to get 'lost' because pages associated with
1073 * a B_DELWRI bp are marked clean. Pages associated with a
1074 * B_LOCKED buffer may be mapped by the filesystem.
1076 * If we want to release the buffer ourselves (rather then the
1077 * originator asking us to release it), give the originator a
1078 * chance to countermand the release by setting B_LOCKED.
1080 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1081 * if B_DELWRI is set.
1083 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1084 * on pages to return pages to the VM page queues.
1086 if (bp->b_flags & (B_DELWRI | B_LOCKED)) {
1087 bp->b_flags &= ~B_RELBUF;
1088 } else if (vm_page_count_severe()) {
1089 if (LIST_FIRST(&bp->b_dep) != NULL)
1090 buf_deallocate(bp);
1091 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1092 bp->b_flags &= ~B_RELBUF;
1093 else
1094 bp->b_flags |= B_RELBUF;
1098 * At this point destroying the buffer is governed by the B_INVAL
1099 * or B_RELBUF flags.
1101 bp->b_cmd = BUF_CMD_DONE;
1104 * VMIO buffer rundown. Make sure the VM page array is restored
1105 * after an I/O may have replaces some of the pages with bogus pages
1106 * in order to not destroy dirty pages in a fill-in read.
1108 * Note that due to the code above, if a buffer is marked B_DELWRI
1109 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1110 * B_INVAL may still be set, however.
1112 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1113 * but not the backing store. B_NOCACHE will destroy the backing
1114 * store.
1116 * Note that dirty NFS buffers contain byte-granular write ranges
1117 * and should not be destroyed w/ B_INVAL even if the backing store
1118 * is left intact.
1120 if (bp->b_flags & B_VMIO) {
1122 * Rundown for VMIO buffers which are not dirty NFS buffers.
1124 int i, j, resid;
1125 vm_page_t m;
1126 off_t foff;
1127 vm_pindex_t poff;
1128 vm_object_t obj;
1129 struct vnode *vp;
1131 vp = bp->b_vp;
1134 * Get the base offset and length of the buffer. Note that
1135 * in the VMIO case if the buffer block size is not
1136 * page-aligned then b_data pointer may not be page-aligned.
1137 * But our b_xio.xio_pages array *IS* page aligned.
1139 * block sizes less then DEV_BSIZE (usually 512) are not
1140 * supported due to the page granularity bits (m->valid,
1141 * m->dirty, etc...).
1143 * See man buf(9) for more information
1146 resid = bp->b_bufsize;
1147 foff = bp->b_loffset;
1149 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1150 m = bp->b_xio.xio_pages[i];
1151 vm_page_flag_clear(m, PG_ZERO);
1153 * If we hit a bogus page, fixup *all* of them
1154 * now. Note that we left these pages wired
1155 * when we removed them so they had better exist,
1156 * and they cannot be ripped out from under us so
1157 * no critical section protection is necessary.
1159 if (m == bogus_page) {
1160 obj = vp->v_object;
1161 poff = OFF_TO_IDX(bp->b_loffset);
1163 for (j = i; j < bp->b_xio.xio_npages; j++) {
1164 vm_page_t mtmp;
1166 mtmp = bp->b_xio.xio_pages[j];
1167 if (mtmp == bogus_page) {
1168 mtmp = vm_page_lookup(obj, poff + j);
1169 if (!mtmp) {
1170 panic("brelse: page missing");
1172 bp->b_xio.xio_pages[j] = mtmp;
1176 if ((bp->b_flags & B_INVAL) == 0) {
1177 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1178 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1180 m = bp->b_xio.xio_pages[i];
1184 * Invalidate the backing store if B_NOCACHE is set
1185 * (e.g. used with vinvalbuf()). If this is NFS
1186 * we impose a requirement that the block size be
1187 * a multiple of PAGE_SIZE and create a temporary
1188 * hack to basically invalidate the whole page. The
1189 * problem is that NFS uses really odd buffer sizes
1190 * especially when tracking piecemeal writes and
1191 * it also vinvalbuf()'s a lot, which would result
1192 * in only partial page validation and invalidation
1193 * here. If the file page is mmap()'d, however,
1194 * all the valid bits get set so after we invalidate
1195 * here we would end up with weird m->valid values
1196 * like 0xfc. nfs_getpages() can't handle this so
1197 * we clear all the valid bits for the NFS case
1198 * instead of just some of them.
1200 * The real bug is the VM system having to set m->valid
1201 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1202 * itself is an artifact of the whole 512-byte
1203 * granular mess that exists to support odd block
1204 * sizes and UFS meta-data block sizes (e.g. 6144).
1205 * A complete rewrite is required.
1207 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1208 int poffset = foff & PAGE_MASK;
1209 int presid;
1211 presid = PAGE_SIZE - poffset;
1212 if (bp->b_vp->v_tag == VT_NFS &&
1213 bp->b_vp->v_type == VREG) {
1214 ; /* entire page */
1215 } else if (presid > resid) {
1216 presid = resid;
1218 KASSERT(presid >= 0, ("brelse: extra page"));
1219 vm_page_set_invalid(m, poffset, presid);
1221 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1222 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1224 if (bp->b_flags & (B_INVAL | B_RELBUF))
1225 vfs_vmio_release(bp);
1226 } else {
1228 * Rundown for non-VMIO buffers.
1230 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1231 #if 0
1232 if (bp->b_vp)
1233 kprintf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1234 #endif
1235 if (bp->b_bufsize)
1236 allocbuf(bp, 0);
1237 if (bp->b_vp)
1238 brelvp(bp);
1242 if (bp->b_qindex != BQUEUE_NONE)
1243 panic("brelse: free buffer onto another queue???");
1244 if (BUF_REFCNTNB(bp) > 1) {
1245 /* Temporary panic to verify exclusive locking */
1246 /* This panic goes away when we allow shared refs */
1247 panic("brelse: multiple refs");
1248 /* do not release to free list */
1249 BUF_UNLOCK(bp);
1250 crit_exit();
1251 return;
1255 * Figure out the correct queue to place the cleaned up buffer on.
1256 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1257 * disassociated from their vnode.
1259 if (bp->b_flags & B_LOCKED) {
1261 * Buffers that are locked are placed in the locked queue
1262 * immediately, regardless of their state.
1264 bp->b_qindex = BQUEUE_LOCKED;
1265 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1266 } else if (bp->b_bufsize == 0) {
1268 * Buffers with no memory. Due to conditionals near the top
1269 * of brelse() such buffers should probably already be
1270 * marked B_INVAL and disassociated from their vnode.
1272 bp->b_flags |= B_INVAL;
1273 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1274 KKASSERT((bp->b_flags & B_HASHED) == 0);
1275 if (bp->b_kvasize) {
1276 bp->b_qindex = BQUEUE_EMPTYKVA;
1277 } else {
1278 bp->b_qindex = BQUEUE_EMPTY;
1280 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1281 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1283 * Buffers with junk contents. Again these buffers had better
1284 * already be disassociated from their vnode.
1286 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1287 KKASSERT((bp->b_flags & B_HASHED) == 0);
1288 bp->b_flags |= B_INVAL;
1289 bp->b_qindex = BQUEUE_CLEAN;
1290 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1291 } else {
1293 * Remaining buffers. These buffers are still associated with
1294 * their vnode.
1296 switch(bp->b_flags & (B_DELWRI|B_HEAVY|B_AGE)) {
1297 case B_DELWRI | B_AGE:
1298 bp->b_qindex = BQUEUE_DIRTY;
1299 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1300 break;
1301 case B_DELWRI:
1302 bp->b_qindex = BQUEUE_DIRTY;
1303 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1304 break;
1305 case B_DELWRI | B_HEAVY | B_AGE:
1306 bp->b_qindex = BQUEUE_DIRTY_HW;
1307 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_DIRTY_HW], bp,
1308 b_freelist);
1309 break;
1310 case B_DELWRI | B_HEAVY:
1311 bp->b_qindex = BQUEUE_DIRTY_HW;
1312 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1313 b_freelist);
1314 break;
1315 case B_HEAVY | B_AGE:
1316 case B_AGE:
1317 bp->b_qindex = BQUEUE_CLEAN;
1318 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1319 break;
1320 default:
1321 bp->b_qindex = BQUEUE_CLEAN;
1322 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1323 break;
1328 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1329 * on the correct queue.
1331 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1332 bundirty(bp);
1335 * Fixup numfreebuffers count. The bp is on an appropriate queue
1336 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1337 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1338 * if B_INVAL is set ).
1340 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1341 bufcountwakeup();
1344 * Something we can maybe free or reuse
1346 if (bp->b_bufsize || bp->b_kvasize)
1347 bufspacewakeup();
1350 * Clean up temporary flags and unlock the buffer.
1352 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF |
1353 B_DIRECT);
1354 BUF_UNLOCK(bp);
1355 crit_exit();
1359 * bqrelse:
1361 * Release a buffer back to the appropriate queue but do not try to free
1362 * it. The buffer is expected to be used again soon.
1364 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1365 * biodone() to requeue an async I/O on completion. It is also used when
1366 * known good buffers need to be requeued but we think we may need the data
1367 * again soon.
1369 * XXX we should be able to leave the B_RELBUF hint set on completion.
1371 void
1372 bqrelse(struct buf *bp)
1374 crit_enter();
1376 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1378 if (bp->b_qindex != BQUEUE_NONE)
1379 panic("bqrelse: free buffer onto another queue???");
1380 if (BUF_REFCNTNB(bp) > 1) {
1381 /* do not release to free list */
1382 panic("bqrelse: multiple refs");
1383 BUF_UNLOCK(bp);
1384 crit_exit();
1385 return;
1387 if (bp->b_flags & B_LOCKED) {
1389 * Locked buffers are released to the locked queue. However,
1390 * if the buffer is dirty it will first go into the dirty
1391 * queue and later on after the I/O completes successfully it
1392 * will be released to the locked queue.
1394 bp->b_flags &= ~B_ERROR;
1395 bp->b_qindex = BQUEUE_LOCKED;
1396 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1397 } else if (bp->b_flags & B_DELWRI) {
1398 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1399 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1400 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1401 } else if (vm_page_count_severe()) {
1403 * We are too low on memory, we have to try to free the
1404 * buffer (most importantly: the wired pages making up its
1405 * backing store) *now*.
1407 crit_exit();
1408 brelse(bp);
1409 return;
1410 } else {
1411 bp->b_qindex = BQUEUE_CLEAN;
1412 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1415 if ((bp->b_flags & B_LOCKED) == 0 &&
1416 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1417 bufcountwakeup();
1421 * Something we can maybe free or reuse.
1423 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1424 bufspacewakeup();
1427 * Final cleanup and unlock. Clear bits that are only used while a
1428 * buffer is actively locked.
1430 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_AGE | B_RELBUF);
1431 BUF_UNLOCK(bp);
1432 crit_exit();
1436 * vfs_vmio_release:
1438 * Return backing pages held by the buffer 'bp' back to the VM system
1439 * if possible. The pages are freed if they are no longer valid or
1440 * attempt to free if it was used for direct I/O otherwise they are
1441 * sent to the page cache.
1443 * Pages that were marked busy are left alone and skipped.
1445 * The KVA mapping (b_data) for the underlying pages is removed by
1446 * this function.
1448 static void
1449 vfs_vmio_release(struct buf *bp)
1451 int i;
1452 vm_page_t m;
1454 crit_enter();
1455 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1456 m = bp->b_xio.xio_pages[i];
1457 bp->b_xio.xio_pages[i] = NULL;
1459 * In order to keep page LRU ordering consistent, put
1460 * everything on the inactive queue.
1462 vm_page_unwire(m, 0);
1464 * We don't mess with busy pages, it is
1465 * the responsibility of the process that
1466 * busied the pages to deal with them.
1468 if ((m->flags & PG_BUSY) || (m->busy != 0))
1469 continue;
1471 if (m->wire_count == 0) {
1472 vm_page_flag_clear(m, PG_ZERO);
1474 * Might as well free the page if we can and it has
1475 * no valid data. We also free the page if the
1476 * buffer was used for direct I/O.
1478 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1479 m->hold_count == 0) {
1480 vm_page_busy(m);
1481 vm_page_protect(m, VM_PROT_NONE);
1482 vm_page_free(m);
1483 } else if (bp->b_flags & B_DIRECT) {
1484 vm_page_try_to_free(m);
1485 } else if (vm_page_count_severe()) {
1486 vm_page_try_to_cache(m);
1490 crit_exit();
1491 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1492 if (bp->b_bufsize) {
1493 bufspacewakeup();
1494 bp->b_bufsize = 0;
1496 bp->b_xio.xio_npages = 0;
1497 bp->b_flags &= ~B_VMIO;
1498 if (bp->b_vp)
1499 brelvp(bp);
1503 * vfs_bio_awrite:
1505 * Implement clustered async writes for clearing out B_DELWRI buffers.
1506 * This is much better then the old way of writing only one buffer at
1507 * a time. Note that we may not be presented with the buffers in the
1508 * correct order, so we search for the cluster in both directions.
1510 * The buffer is locked on call.
1513 vfs_bio_awrite(struct buf *bp)
1515 int i;
1516 int j;
1517 off_t loffset = bp->b_loffset;
1518 struct vnode *vp = bp->b_vp;
1519 int nbytes;
1520 struct buf *bpa;
1521 int nwritten;
1522 int size;
1524 crit_enter();
1526 * right now we support clustered writing only to regular files. If
1527 * we find a clusterable block we could be in the middle of a cluster
1528 * rather then at the beginning.
1530 * NOTE: b_bio1 contains the logical loffset and is aliased
1531 * to b_loffset. b_bio2 contains the translated block number.
1533 if ((vp->v_type == VREG) &&
1534 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1535 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1537 size = vp->v_mount->mnt_stat.f_iosize;
1539 for (i = size; i < MAXPHYS; i += size) {
1540 if ((bpa = findblk(vp, loffset + i)) &&
1541 BUF_REFCNT(bpa) == 0 &&
1542 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1543 (B_DELWRI | B_CLUSTEROK)) &&
1544 (bpa->b_bufsize == size)) {
1545 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1546 (bpa->b_bio2.bio_offset !=
1547 bp->b_bio2.bio_offset + i))
1548 break;
1549 } else {
1550 break;
1553 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1554 if ((bpa = findblk(vp, loffset - j)) &&
1555 BUF_REFCNT(bpa) == 0 &&
1556 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1557 (B_DELWRI | B_CLUSTEROK)) &&
1558 (bpa->b_bufsize == size)) {
1559 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1560 (bpa->b_bio2.bio_offset !=
1561 bp->b_bio2.bio_offset - j))
1562 break;
1563 } else {
1564 break;
1567 j -= size;
1568 nbytes = (i + j);
1570 * this is a possible cluster write
1572 if (nbytes != size) {
1573 BUF_UNLOCK(bp);
1574 nwritten = cluster_wbuild(vp, size,
1575 loffset - j, nbytes);
1576 crit_exit();
1577 return nwritten;
1581 bremfree(bp);
1582 bp->b_flags |= B_ASYNC;
1584 crit_exit();
1586 * default (old) behavior, writing out only one block
1588 * XXX returns b_bufsize instead of b_bcount for nwritten?
1590 nwritten = bp->b_bufsize;
1591 bwrite(bp);
1593 return nwritten;
1597 * getnewbuf:
1599 * Find and initialize a new buffer header, freeing up existing buffers
1600 * in the bufqueues as necessary. The new buffer is returned locked.
1602 * Important: B_INVAL is not set. If the caller wishes to throw the
1603 * buffer away, the caller must set B_INVAL prior to calling brelse().
1605 * We block if:
1606 * We have insufficient buffer headers
1607 * We have insufficient buffer space
1608 * buffer_map is too fragmented ( space reservation fails )
1609 * If we have to flush dirty buffers ( but we try to avoid this )
1611 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1612 * Instead we ask the buf daemon to do it for us. We attempt to
1613 * avoid piecemeal wakeups of the pageout daemon.
1616 static struct buf *
1617 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1619 struct buf *bp;
1620 struct buf *nbp;
1621 int defrag = 0;
1622 int nqindex;
1623 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1624 static int flushingbufs;
1627 * We can't afford to block since we might be holding a vnode lock,
1628 * which may prevent system daemons from running. We deal with
1629 * low-memory situations by proactively returning memory and running
1630 * async I/O rather then sync I/O.
1633 ++getnewbufcalls;
1634 --getnewbufrestarts;
1635 restart:
1636 ++getnewbufrestarts;
1639 * Setup for scan. If we do not have enough free buffers,
1640 * we setup a degenerate case that immediately fails. Note
1641 * that if we are specially marked process, we are allowed to
1642 * dip into our reserves.
1644 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1646 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1647 * However, there are a number of cases (defragging, reusing, ...)
1648 * where we cannot backup.
1650 nqindex = BQUEUE_EMPTYKVA;
1651 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1653 if (nbp == NULL) {
1655 * If no EMPTYKVA buffers and we are either
1656 * defragging or reusing, locate a CLEAN buffer
1657 * to free or reuse. If bufspace useage is low
1658 * skip this step so we can allocate a new buffer.
1660 if (defrag || bufspace >= lobufspace) {
1661 nqindex = BQUEUE_CLEAN;
1662 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1666 * If we could not find or were not allowed to reuse a
1667 * CLEAN buffer, check to see if it is ok to use an EMPTY
1668 * buffer. We can only use an EMPTY buffer if allocating
1669 * its KVA would not otherwise run us out of buffer space.
1671 if (nbp == NULL && defrag == 0 &&
1672 bufspace + maxsize < hibufspace) {
1673 nqindex = BQUEUE_EMPTY;
1674 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1679 * Run scan, possibly freeing data and/or kva mappings on the fly
1680 * depending.
1683 while ((bp = nbp) != NULL) {
1684 int qindex = nqindex;
1687 * Calculate next bp ( we can only use it if we do not block
1688 * or do other fancy things ).
1690 if ((nbp = TAILQ_NEXT(bp, b_freelist)) == NULL) {
1691 switch(qindex) {
1692 case BQUEUE_EMPTY:
1693 nqindex = BQUEUE_EMPTYKVA;
1694 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1695 break;
1696 /* fall through */
1697 case BQUEUE_EMPTYKVA:
1698 nqindex = BQUEUE_CLEAN;
1699 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1700 break;
1701 /* fall through */
1702 case BQUEUE_CLEAN:
1704 * nbp is NULL.
1706 break;
1711 * Sanity Checks
1713 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1716 * Note: we no longer distinguish between VMIO and non-VMIO
1717 * buffers.
1720 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1723 * If we are defragging then we need a buffer with
1724 * b_kvasize != 0. XXX this situation should no longer
1725 * occur, if defrag is non-zero the buffer's b_kvasize
1726 * should also be non-zero at this point. XXX
1728 if (defrag && bp->b_kvasize == 0) {
1729 kprintf("Warning: defrag empty buffer %p\n", bp);
1730 continue;
1734 * Start freeing the bp. This is somewhat involved. nbp
1735 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1736 * on the clean list must be disassociated from their
1737 * current vnode. Buffers on the empty[kva] lists have
1738 * already been disassociated.
1741 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1742 kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1743 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1744 goto restart;
1746 if (bp->b_qindex != qindex) {
1747 kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1748 BUF_UNLOCK(bp);
1749 goto restart;
1751 bremfree(bp);
1754 * Dependancies must be handled before we disassociate the
1755 * vnode.
1757 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1758 * be immediately disassociated. HAMMER then becomes
1759 * responsible for releasing the buffer.
1761 if (LIST_FIRST(&bp->b_dep) != NULL) {
1762 buf_deallocate(bp);
1763 if (bp->b_flags & B_LOCKED) {
1764 bqrelse(bp);
1765 goto restart;
1767 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1770 if (qindex == BQUEUE_CLEAN) {
1771 if (bp->b_flags & B_VMIO) {
1772 bp->b_flags &= ~B_ASYNC;
1773 vfs_vmio_release(bp);
1775 if (bp->b_vp)
1776 brelvp(bp);
1780 * NOTE: nbp is now entirely invalid. We can only restart
1781 * the scan from this point on.
1783 * Get the rest of the buffer freed up. b_kva* is still
1784 * valid after this operation.
1787 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1788 KKASSERT((bp->b_flags & B_HASHED) == 0);
1791 * critical section protection is not required when
1792 * scrapping a buffer's contents because it is already
1793 * wired.
1795 if (bp->b_bufsize)
1796 allocbuf(bp, 0);
1798 bp->b_flags = B_BNOCLIP;
1799 bp->b_cmd = BUF_CMD_DONE;
1800 bp->b_vp = NULL;
1801 bp->b_error = 0;
1802 bp->b_resid = 0;
1803 bp->b_bcount = 0;
1804 bp->b_xio.xio_npages = 0;
1805 bp->b_dirtyoff = bp->b_dirtyend = 0;
1806 reinitbufbio(bp);
1807 buf_dep_init(bp);
1808 if (blkflags & GETBLK_BHEAVY)
1809 bp->b_flags |= B_HEAVY;
1812 * If we are defragging then free the buffer.
1814 if (defrag) {
1815 bp->b_flags |= B_INVAL;
1816 bfreekva(bp);
1817 brelse(bp);
1818 defrag = 0;
1819 goto restart;
1823 * If we are overcomitted then recover the buffer and its
1824 * KVM space. This occurs in rare situations when multiple
1825 * processes are blocked in getnewbuf() or allocbuf().
1827 if (bufspace >= hibufspace)
1828 flushingbufs = 1;
1829 if (flushingbufs && bp->b_kvasize != 0) {
1830 bp->b_flags |= B_INVAL;
1831 bfreekva(bp);
1832 brelse(bp);
1833 goto restart;
1835 if (bufspace < lobufspace)
1836 flushingbufs = 0;
1837 break;
1841 * If we exhausted our list, sleep as appropriate. We may have to
1842 * wakeup various daemons and write out some dirty buffers.
1844 * Generally we are sleeping due to insufficient buffer space.
1847 if (bp == NULL) {
1848 int flags;
1849 char *waitmsg;
1851 if (defrag) {
1852 flags = VFS_BIO_NEED_BUFSPACE;
1853 waitmsg = "nbufkv";
1854 } else if (bufspace >= hibufspace) {
1855 waitmsg = "nbufbs";
1856 flags = VFS_BIO_NEED_BUFSPACE;
1857 } else {
1858 waitmsg = "newbuf";
1859 flags = VFS_BIO_NEED_ANY;
1862 needsbuffer |= flags;
1863 bd_speedup(); /* heeeelp */
1864 while (needsbuffer & flags) {
1865 if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
1866 return (NULL);
1868 } else {
1870 * We finally have a valid bp. We aren't quite out of the
1871 * woods, we still have to reserve kva space. In order
1872 * to keep fragmentation sane we only allocate kva in
1873 * BKVASIZE chunks.
1875 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1877 if (maxsize != bp->b_kvasize) {
1878 vm_offset_t addr = 0;
1879 int count;
1881 bfreekva(bp);
1883 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1884 vm_map_lock(&buffer_map);
1886 if (vm_map_findspace(&buffer_map,
1887 vm_map_min(&buffer_map), maxsize,
1888 maxsize, &addr)) {
1890 * Uh oh. Buffer map is too fragmented. We
1891 * must defragment the map.
1893 vm_map_unlock(&buffer_map);
1894 vm_map_entry_release(count);
1895 ++bufdefragcnt;
1896 defrag = 1;
1897 bp->b_flags |= B_INVAL;
1898 brelse(bp);
1899 goto restart;
1901 if (addr) {
1902 vm_map_insert(&buffer_map, &count,
1903 NULL, 0,
1904 addr, addr + maxsize,
1905 VM_MAPTYPE_NORMAL,
1906 VM_PROT_ALL, VM_PROT_ALL,
1907 MAP_NOFAULT);
1909 bp->b_kvabase = (caddr_t) addr;
1910 bp->b_kvasize = maxsize;
1911 bufspace += bp->b_kvasize;
1912 ++bufreusecnt;
1914 vm_map_unlock(&buffer_map);
1915 vm_map_entry_release(count);
1917 bp->b_data = bp->b_kvabase;
1919 return(bp);
1923 * buf_daemon:
1925 * Buffer flushing daemon. Buffers are normally flushed by the
1926 * update daemon but if it cannot keep up this process starts to
1927 * take the load in an attempt to prevent getnewbuf() from blocking.
1929 * Once a flush is initiated it does not stop until the number
1930 * of buffers falls below lodirtybuffers, but we will wake up anyone
1931 * waiting at the mid-point.
1934 static struct thread *bufdaemon_td;
1935 static struct thread *bufdaemonhw_td;
1937 static struct kproc_desc buf_kp = {
1938 "bufdaemon",
1939 buf_daemon,
1940 &bufdaemon_td
1942 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
1943 kproc_start, &buf_kp)
1945 static struct kproc_desc bufhw_kp = {
1946 "bufdaemon_hw",
1947 buf_daemon_hw,
1948 &bufdaemonhw_td
1950 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
1951 kproc_start, &bufhw_kp)
1953 static void
1954 buf_daemon(void)
1957 * This process needs to be suspended prior to shutdown sync.
1959 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1960 bufdaemon_td, SHUTDOWN_PRI_LAST);
1963 * This process is allowed to take the buffer cache to the limit
1965 crit_enter();
1967 for (;;) {
1968 kproc_suspend_loop();
1971 * Do the flush. Limit the amount of in-transit I/O we
1972 * allow to build up, otherwise we would completely saturate
1973 * the I/O system. Wakeup any waiting processes before we
1974 * normally would so they can run in parallel with our drain.
1976 while (numdirtybuffers > lodirtybuffers) {
1977 if (flushbufqueues(BQUEUE_DIRTY) == 0)
1978 break;
1979 waitrunningbufspace();
1980 numdirtywakeup();
1982 numdirtywakeup();
1985 * Only clear bd_request if we have reached our low water
1986 * mark. The buf_daemon normally waits 5 seconds and
1987 * then incrementally flushes any dirty buffers that have
1988 * built up, within reason.
1990 * If we were unable to hit our low water mark and couldn't
1991 * find any flushable buffers, we sleep half a second.
1992 * Otherwise we loop immediately.
1994 if (numdirtybuffers <= lodirtybuffers) {
1996 * We reached our low water mark, reset the
1997 * request and sleep until we are needed again.
1998 * The sleep is just so the suspend code works.
2000 spin_lock_wr(&needsbuffer_spin);
2001 bd_request = 0;
2002 msleep(&bd_request, &needsbuffer_spin, 0,
2003 "psleep", hz);
2004 spin_unlock_wr(&needsbuffer_spin);
2005 } else {
2007 * We couldn't find any flushable dirty buffers but
2008 * still have too many dirty buffers, we
2009 * have to sleep and try again. (rare)
2011 tsleep(&bd_request, 0, "qsleep", hz / 2);
2016 static void
2017 buf_daemon_hw(void)
2020 * This process needs to be suspended prior to shutdown sync.
2022 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2023 bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2026 * This process is allowed to take the buffer cache to the limit
2028 crit_enter();
2030 for (;;) {
2031 kproc_suspend_loop();
2034 * Do the flush. Limit the amount of in-transit I/O we
2035 * allow to build up, otherwise we would completely saturate
2036 * the I/O system. Wakeup any waiting processes before we
2037 * normally would so they can run in parallel with our drain.
2039 while (numdirtybuffershw > lodirtybuffers) {
2040 if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2041 break;
2042 waitrunningbufspace();
2043 numdirtywakeup();
2047 * Only clear bd_request if we have reached our low water
2048 * mark. The buf_daemon normally waits 5 seconds and
2049 * then incrementally flushes any dirty buffers that have
2050 * built up, within reason.
2052 * If we were unable to hit our low water mark and couldn't
2053 * find any flushable buffers, we sleep half a second.
2054 * Otherwise we loop immediately.
2056 if (numdirtybuffershw <= lodirtybuffers) {
2058 * We reached our low water mark, reset the
2059 * request and sleep until we are needed again.
2060 * The sleep is just so the suspend code works.
2062 spin_lock_wr(&needsbuffer_spin);
2063 bd_request_hw = 0;
2064 msleep(&bd_request_hw, &needsbuffer_spin, 0,
2065 "psleep", hz);
2066 spin_unlock_wr(&needsbuffer_spin);
2067 } else {
2069 * We couldn't find any flushable dirty buffers but
2070 * still have too many dirty buffers, we
2071 * have to sleep and try again. (rare)
2073 tsleep(&bd_request_hw, 0, "qsleep", hz / 2);
2079 * flushbufqueues:
2081 * Try to flush a buffer in the dirty queue. We must be careful to
2082 * free up B_INVAL buffers instead of write them, which NFS is
2083 * particularly sensitive to.
2086 static int
2087 flushbufqueues(bufq_type_t q)
2089 struct buf *bp;
2090 int r = 0;
2092 bp = TAILQ_FIRST(&bufqueues[q]);
2094 while (bp) {
2095 KASSERT((bp->b_flags & B_DELWRI),
2096 ("unexpected clean buffer %p", bp));
2097 if (bp->b_flags & B_DELWRI) {
2098 if (bp->b_flags & B_INVAL) {
2099 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2100 panic("flushbufqueues: locked buf");
2101 bremfree(bp);
2102 brelse(bp);
2103 ++r;
2104 break;
2106 if (LIST_FIRST(&bp->b_dep) != NULL &&
2107 (bp->b_flags & B_DEFERRED) == 0 &&
2108 buf_countdeps(bp, 0)) {
2109 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2110 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2111 b_freelist);
2112 bp->b_flags |= B_DEFERRED;
2113 bp = TAILQ_FIRST(&bufqueues[q]);
2114 continue;
2118 * Only write it out if we can successfully lock
2119 * it. If the buffer has a dependancy,
2120 * buf_checkwrite must also return 0.
2122 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2123 if (LIST_FIRST(&bp->b_dep) != NULL &&
2124 buf_checkwrite(bp)) {
2125 bremfree(bp);
2126 brelse(bp);
2127 } else {
2128 vfs_bio_awrite(bp);
2130 ++r;
2131 break;
2134 bp = TAILQ_NEXT(bp, b_freelist);
2136 return (r);
2140 * inmem:
2142 * Returns true if no I/O is needed to access the associated VM object.
2143 * This is like findblk except it also hunts around in the VM system for
2144 * the data.
2146 * Note that we ignore vm_page_free() races from interrupts against our
2147 * lookup, since if the caller is not protected our return value will not
2148 * be any more valid then otherwise once we exit the critical section.
2151 inmem(struct vnode *vp, off_t loffset)
2153 vm_object_t obj;
2154 vm_offset_t toff, tinc, size;
2155 vm_page_t m;
2157 if (findblk(vp, loffset))
2158 return 1;
2159 if (vp->v_mount == NULL)
2160 return 0;
2161 if ((obj = vp->v_object) == NULL)
2162 return 0;
2164 size = PAGE_SIZE;
2165 if (size > vp->v_mount->mnt_stat.f_iosize)
2166 size = vp->v_mount->mnt_stat.f_iosize;
2168 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2169 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2170 if (m == NULL)
2171 return 0;
2172 tinc = size;
2173 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2174 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2175 if (vm_page_is_valid(m,
2176 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2177 return 0;
2179 return 1;
2183 * vfs_setdirty:
2185 * Sets the dirty range for a buffer based on the status of the dirty
2186 * bits in the pages comprising the buffer.
2188 * The range is limited to the size of the buffer.
2190 * This routine is primarily used by NFS, but is generalized for the
2191 * B_VMIO case.
2193 static void
2194 vfs_setdirty(struct buf *bp)
2196 int i;
2197 vm_object_t object;
2200 * Degenerate case - empty buffer
2203 if (bp->b_bufsize == 0)
2204 return;
2207 * We qualify the scan for modified pages on whether the
2208 * object has been flushed yet. The OBJ_WRITEABLE flag
2209 * is not cleared simply by protecting pages off.
2212 if ((bp->b_flags & B_VMIO) == 0)
2213 return;
2215 object = bp->b_xio.xio_pages[0]->object;
2217 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2218 kprintf("Warning: object %p writeable but not mightbedirty\n", object);
2219 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2220 kprintf("Warning: object %p mightbedirty but not writeable\n", object);
2222 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2223 vm_offset_t boffset;
2224 vm_offset_t eoffset;
2227 * test the pages to see if they have been modified directly
2228 * by users through the VM system.
2230 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2231 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2232 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2236 * Calculate the encompassing dirty range, boffset and eoffset,
2237 * (eoffset - boffset) bytes.
2240 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2241 if (bp->b_xio.xio_pages[i]->dirty)
2242 break;
2244 boffset = (i << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2246 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2247 if (bp->b_xio.xio_pages[i]->dirty) {
2248 break;
2251 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2254 * Fit it to the buffer.
2257 if (eoffset > bp->b_bcount)
2258 eoffset = bp->b_bcount;
2261 * If we have a good dirty range, merge with the existing
2262 * dirty range.
2265 if (boffset < eoffset) {
2266 if (bp->b_dirtyoff > boffset)
2267 bp->b_dirtyoff = boffset;
2268 if (bp->b_dirtyend < eoffset)
2269 bp->b_dirtyend = eoffset;
2275 * findblk:
2277 * Locate and return the specified buffer, or NULL if the buffer does
2278 * not exist. Do not attempt to lock the buffer or manipulate it in
2279 * any way. The caller must validate that the correct buffer has been
2280 * obtain after locking it.
2282 struct buf *
2283 findblk(struct vnode *vp, off_t loffset)
2285 struct buf *bp;
2287 crit_enter();
2288 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2289 crit_exit();
2290 return(bp);
2294 * getblk:
2296 * Get a block given a specified block and offset into a file/device.
2297 * B_INVAL may or may not be set on return. The caller should clear
2298 * B_INVAL prior to initiating a READ.
2300 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2301 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2302 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2303 * without doing any of those things the system will likely believe
2304 * the buffer to be valid (especially if it is not B_VMIO), and the
2305 * next getblk() will return the buffer with B_CACHE set.
2307 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2308 * an existing buffer.
2310 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2311 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2312 * and then cleared based on the backing VM. If the previous buffer is
2313 * non-0-sized but invalid, B_CACHE will be cleared.
2315 * If getblk() must create a new buffer, the new buffer is returned with
2316 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2317 * case it is returned with B_INVAL clear and B_CACHE set based on the
2318 * backing VM.
2320 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2321 * B_CACHE bit is clear.
2323 * What this means, basically, is that the caller should use B_CACHE to
2324 * determine whether the buffer is fully valid or not and should clear
2325 * B_INVAL prior to issuing a read. If the caller intends to validate
2326 * the buffer by loading its data area with something, the caller needs
2327 * to clear B_INVAL. If the caller does this without issuing an I/O,
2328 * the caller should set B_CACHE ( as an optimization ), else the caller
2329 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2330 * a write attempt or if it was a successfull read. If the caller
2331 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2332 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2334 * getblk flags:
2336 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2337 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2339 struct buf *
2340 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2342 struct buf *bp;
2343 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2345 if (size > MAXBSIZE)
2346 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2347 if (vp->v_object == NULL)
2348 panic("getblk: vnode %p has no object!", vp);
2350 crit_enter();
2351 loop:
2352 if ((bp = findblk(vp, loffset))) {
2354 * The buffer was found in the cache, but we need to lock it.
2355 * Even with LK_NOWAIT the lockmgr may break our critical
2356 * section, so double-check the validity of the buffer
2357 * once the lock has been obtained.
2359 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2360 int lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2361 if (blkflags & GETBLK_PCATCH)
2362 lkflags |= LK_PCATCH;
2363 if (BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo) ==
2364 ENOLCK) {
2365 goto loop;
2367 crit_exit();
2368 return (NULL);
2372 * Once the buffer has been locked, make sure we didn't race
2373 * a buffer recyclement. Buffers that are no longer hashed
2374 * will have b_vp == NULL, so this takes care of that check
2375 * as well.
2377 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2378 kprintf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp, vp, loffset);
2379 BUF_UNLOCK(bp);
2380 goto loop;
2384 * All vnode-based buffers must be backed by a VM object.
2386 KKASSERT(bp->b_flags & B_VMIO);
2387 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2390 * Make sure that B_INVAL buffers do not have a cached
2391 * block number translation.
2393 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2394 kprintf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp, vp, loffset);
2395 clearbiocache(&bp->b_bio2);
2399 * The buffer is locked. B_CACHE is cleared if the buffer is
2400 * invalid.
2402 if (bp->b_flags & B_INVAL)
2403 bp->b_flags &= ~B_CACHE;
2404 bremfree(bp);
2407 * Any size inconsistancy with a dirty buffer or a buffer
2408 * with a softupdates dependancy must be resolved. Resizing
2409 * the buffer in such circumstances can lead to problems.
2411 if (size != bp->b_bcount) {
2412 if (bp->b_flags & B_DELWRI) {
2413 bp->b_flags |= B_NOCACHE;
2414 bwrite(bp);
2415 } else if (LIST_FIRST(&bp->b_dep)) {
2416 bp->b_flags |= B_NOCACHE;
2417 bwrite(bp);
2418 } else {
2419 bp->b_flags |= B_RELBUF;
2420 brelse(bp);
2422 goto loop;
2424 KKASSERT(size <= bp->b_kvasize);
2425 KASSERT(bp->b_loffset != NOOFFSET,
2426 ("getblk: no buffer offset"));
2429 * A buffer with B_DELWRI set and B_CACHE clear must
2430 * be committed before we can return the buffer in
2431 * order to prevent the caller from issuing a read
2432 * ( due to B_CACHE not being set ) and overwriting
2433 * it.
2435 * Most callers, including NFS and FFS, need this to
2436 * operate properly either because they assume they
2437 * can issue a read if B_CACHE is not set, or because
2438 * ( for example ) an uncached B_DELWRI might loop due
2439 * to softupdates re-dirtying the buffer. In the latter
2440 * case, B_CACHE is set after the first write completes,
2441 * preventing further loops.
2443 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2444 * above while extending the buffer, we cannot allow the
2445 * buffer to remain with B_CACHE set after the write
2446 * completes or it will represent a corrupt state. To
2447 * deal with this we set B_NOCACHE to scrap the buffer
2448 * after the write.
2450 * We might be able to do something fancy, like setting
2451 * B_CACHE in bwrite() except if B_DELWRI is already set,
2452 * so the below call doesn't set B_CACHE, but that gets real
2453 * confusing. This is much easier.
2456 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2457 bp->b_flags |= B_NOCACHE;
2458 bwrite(bp);
2459 goto loop;
2461 crit_exit();
2462 } else {
2464 * Buffer is not in-core, create new buffer. The buffer
2465 * returned by getnewbuf() is locked. Note that the returned
2466 * buffer is also considered valid (not marked B_INVAL).
2468 * Calculating the offset for the I/O requires figuring out
2469 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2470 * the mount's f_iosize otherwise. If the vnode does not
2471 * have an associated mount we assume that the passed size is
2472 * the block size.
2474 * Note that vn_isdisk() cannot be used here since it may
2475 * return a failure for numerous reasons. Note that the
2476 * buffer size may be larger then the block size (the caller
2477 * will use block numbers with the proper multiple). Beware
2478 * of using any v_* fields which are part of unions. In
2479 * particular, in DragonFly the mount point overloading
2480 * mechanism uses the namecache only and the underlying
2481 * directory vnode is not a special case.
2483 int bsize, maxsize;
2485 if (vp->v_type == VBLK || vp->v_type == VCHR)
2486 bsize = DEV_BSIZE;
2487 else if (vp->v_mount)
2488 bsize = vp->v_mount->mnt_stat.f_iosize;
2489 else
2490 bsize = size;
2492 maxsize = size + (loffset & PAGE_MASK);
2493 maxsize = imax(maxsize, bsize);
2495 if ((bp = getnewbuf(blkflags, slptimeo, size, maxsize)) == NULL) {
2496 if (slpflags || slptimeo) {
2497 crit_exit();
2498 return NULL;
2500 goto loop;
2504 * This code is used to make sure that a buffer is not
2505 * created while the getnewbuf routine is blocked.
2506 * This can be a problem whether the vnode is locked or not.
2507 * If the buffer is created out from under us, we have to
2508 * throw away the one we just created. There is no window
2509 * race because we are safely running in a critical section
2510 * from the point of the duplicate buffer creation through
2511 * to here, and we've locked the buffer.
2513 if (findblk(vp, loffset)) {
2514 bp->b_flags |= B_INVAL;
2515 brelse(bp);
2516 goto loop;
2520 * Insert the buffer into the hash, so that it can
2521 * be found by findblk().
2523 * Make sure the translation layer has been cleared.
2525 bp->b_loffset = loffset;
2526 bp->b_bio2.bio_offset = NOOFFSET;
2527 /* bp->b_bio2.bio_next = NULL; */
2529 bgetvp(vp, bp);
2532 * All vnode-based buffers must be backed by a VM object.
2534 KKASSERT(vp->v_object != NULL);
2535 bp->b_flags |= B_VMIO;
2536 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2538 allocbuf(bp, size);
2540 crit_exit();
2542 return (bp);
2546 * regetblk(bp)
2548 * Reacquire a buffer that was previously released to the locked queue,
2549 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2550 * set B_LOCKED (which handles the acquisition race).
2552 * To this end, either B_LOCKED must be set or the dependancy list must be
2553 * non-empty.
2555 void
2556 regetblk(struct buf *bp)
2558 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2559 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2560 crit_enter();
2561 bremfree(bp);
2562 crit_exit();
2566 * geteblk:
2568 * Get an empty, disassociated buffer of given size. The buffer is
2569 * initially set to B_INVAL.
2571 * critical section protection is not required for the allocbuf()
2572 * call because races are impossible here.
2574 struct buf *
2575 geteblk(int size)
2577 struct buf *bp;
2578 int maxsize;
2580 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2582 crit_enter();
2583 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2585 crit_exit();
2586 allocbuf(bp, size);
2587 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2588 return (bp);
2593 * allocbuf:
2595 * This code constitutes the buffer memory from either anonymous system
2596 * memory (in the case of non-VMIO operations) or from an associated
2597 * VM object (in the case of VMIO operations). This code is able to
2598 * resize a buffer up or down.
2600 * Note that this code is tricky, and has many complications to resolve
2601 * deadlock or inconsistant data situations. Tread lightly!!!
2602 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2603 * the caller. Calling this code willy nilly can result in the loss of data.
2605 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2606 * B_CACHE for the non-VMIO case.
2608 * This routine does not need to be called from a critical section but you
2609 * must own the buffer.
2612 allocbuf(struct buf *bp, int size)
2614 int newbsize, mbsize;
2615 int i;
2617 if (BUF_REFCNT(bp) == 0)
2618 panic("allocbuf: buffer not busy");
2620 if (bp->b_kvasize < size)
2621 panic("allocbuf: buffer too small");
2623 if ((bp->b_flags & B_VMIO) == 0) {
2624 caddr_t origbuf;
2625 int origbufsize;
2627 * Just get anonymous memory from the kernel. Don't
2628 * mess with B_CACHE.
2630 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2631 if (bp->b_flags & B_MALLOC)
2632 newbsize = mbsize;
2633 else
2634 newbsize = round_page(size);
2636 if (newbsize < bp->b_bufsize) {
2638 * Malloced buffers are not shrunk
2640 if (bp->b_flags & B_MALLOC) {
2641 if (newbsize) {
2642 bp->b_bcount = size;
2643 } else {
2644 kfree(bp->b_data, M_BIOBUF);
2645 if (bp->b_bufsize) {
2646 bufmallocspace -= bp->b_bufsize;
2647 bufspacewakeup();
2648 bp->b_bufsize = 0;
2650 bp->b_data = bp->b_kvabase;
2651 bp->b_bcount = 0;
2652 bp->b_flags &= ~B_MALLOC;
2654 return 1;
2656 vm_hold_free_pages(
2658 (vm_offset_t) bp->b_data + newbsize,
2659 (vm_offset_t) bp->b_data + bp->b_bufsize);
2660 } else if (newbsize > bp->b_bufsize) {
2662 * We only use malloced memory on the first allocation.
2663 * and revert to page-allocated memory when the buffer
2664 * grows.
2666 if ((bufmallocspace < maxbufmallocspace) &&
2667 (bp->b_bufsize == 0) &&
2668 (mbsize <= PAGE_SIZE/2)) {
2670 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
2671 bp->b_bufsize = mbsize;
2672 bp->b_bcount = size;
2673 bp->b_flags |= B_MALLOC;
2674 bufmallocspace += mbsize;
2675 return 1;
2677 origbuf = NULL;
2678 origbufsize = 0;
2680 * If the buffer is growing on its other-than-first
2681 * allocation, then we revert to the page-allocation
2682 * scheme.
2684 if (bp->b_flags & B_MALLOC) {
2685 origbuf = bp->b_data;
2686 origbufsize = bp->b_bufsize;
2687 bp->b_data = bp->b_kvabase;
2688 if (bp->b_bufsize) {
2689 bufmallocspace -= bp->b_bufsize;
2690 bufspacewakeup();
2691 bp->b_bufsize = 0;
2693 bp->b_flags &= ~B_MALLOC;
2694 newbsize = round_page(newbsize);
2696 vm_hold_load_pages(
2698 (vm_offset_t) bp->b_data + bp->b_bufsize,
2699 (vm_offset_t) bp->b_data + newbsize);
2700 if (origbuf) {
2701 bcopy(origbuf, bp->b_data, origbufsize);
2702 kfree(origbuf, M_BIOBUF);
2705 } else {
2706 vm_page_t m;
2707 int desiredpages;
2709 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2710 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
2711 newbsize + PAGE_MASK) >> PAGE_SHIFT;
2712 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
2714 if (bp->b_flags & B_MALLOC)
2715 panic("allocbuf: VMIO buffer can't be malloced");
2717 * Set B_CACHE initially if buffer is 0 length or will become
2718 * 0-length.
2720 if (size == 0 || bp->b_bufsize == 0)
2721 bp->b_flags |= B_CACHE;
2723 if (newbsize < bp->b_bufsize) {
2725 * DEV_BSIZE aligned new buffer size is less then the
2726 * DEV_BSIZE aligned existing buffer size. Figure out
2727 * if we have to remove any pages.
2729 if (desiredpages < bp->b_xio.xio_npages) {
2730 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2732 * the page is not freed here -- it
2733 * is the responsibility of
2734 * vnode_pager_setsize
2736 m = bp->b_xio.xio_pages[i];
2737 KASSERT(m != bogus_page,
2738 ("allocbuf: bogus page found"));
2739 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2742 bp->b_xio.xio_pages[i] = NULL;
2743 vm_page_unwire(m, 0);
2745 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2746 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2747 bp->b_xio.xio_npages = desiredpages;
2749 } else if (size > bp->b_bcount) {
2751 * We are growing the buffer, possibly in a
2752 * byte-granular fashion.
2754 struct vnode *vp;
2755 vm_object_t obj;
2756 vm_offset_t toff;
2757 vm_offset_t tinc;
2760 * Step 1, bring in the VM pages from the object,
2761 * allocating them if necessary. We must clear
2762 * B_CACHE if these pages are not valid for the
2763 * range covered by the buffer.
2765 * critical section protection is required to protect
2766 * against interrupts unbusying and freeing pages
2767 * between our vm_page_lookup() and our
2768 * busycheck/wiring call.
2770 vp = bp->b_vp;
2771 obj = vp->v_object;
2773 crit_enter();
2774 while (bp->b_xio.xio_npages < desiredpages) {
2775 vm_page_t m;
2776 vm_pindex_t pi;
2778 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
2779 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2781 * note: must allocate system pages
2782 * since blocking here could intefere
2783 * with paging I/O, no matter which
2784 * process we are.
2786 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2787 if (m == NULL) {
2788 vm_wait();
2789 vm_pageout_deficit += desiredpages -
2790 bp->b_xio.xio_npages;
2791 } else {
2792 vm_page_wire(m);
2793 vm_page_wakeup(m);
2794 bp->b_flags &= ~B_CACHE;
2795 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2796 ++bp->b_xio.xio_npages;
2798 continue;
2802 * We found a page. If we have to sleep on it,
2803 * retry because it might have gotten freed out
2804 * from under us.
2806 * We can only test PG_BUSY here. Blocking on
2807 * m->busy might lead to a deadlock:
2809 * vm_fault->getpages->cluster_read->allocbuf
2813 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2814 continue;
2817 * We have a good page. Should we wakeup the
2818 * page daemon?
2820 if ((curthread != pagethread) &&
2821 ((m->queue - m->pc) == PQ_CACHE) &&
2822 ((vmstats.v_free_count + vmstats.v_cache_count) <
2823 (vmstats.v_free_min + vmstats.v_cache_min))) {
2824 pagedaemon_wakeup();
2826 vm_page_flag_clear(m, PG_ZERO);
2827 vm_page_wire(m);
2828 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2829 ++bp->b_xio.xio_npages;
2831 crit_exit();
2834 * Step 2. We've loaded the pages into the buffer,
2835 * we have to figure out if we can still have B_CACHE
2836 * set. Note that B_CACHE is set according to the
2837 * byte-granular range ( bcount and size ), not the
2838 * aligned range ( newbsize ).
2840 * The VM test is against m->valid, which is DEV_BSIZE
2841 * aligned. Needless to say, the validity of the data
2842 * needs to also be DEV_BSIZE aligned. Note that this
2843 * fails with NFS if the server or some other client
2844 * extends the file's EOF. If our buffer is resized,
2845 * B_CACHE may remain set! XXX
2848 toff = bp->b_bcount;
2849 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
2851 while ((bp->b_flags & B_CACHE) && toff < size) {
2852 vm_pindex_t pi;
2854 if (tinc > (size - toff))
2855 tinc = size - toff;
2857 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
2858 PAGE_SHIFT;
2860 vfs_buf_test_cache(
2861 bp,
2862 bp->b_loffset,
2863 toff,
2864 tinc,
2865 bp->b_xio.xio_pages[pi]
2867 toff += tinc;
2868 tinc = PAGE_SIZE;
2872 * Step 3, fixup the KVM pmap. Remember that
2873 * bp->b_data is relative to bp->b_loffset, but
2874 * bp->b_loffset may be offset into the first page.
2877 bp->b_data = (caddr_t)
2878 trunc_page((vm_offset_t)bp->b_data);
2879 pmap_qenter(
2880 (vm_offset_t)bp->b_data,
2881 bp->b_xio.xio_pages,
2882 bp->b_xio.xio_npages
2884 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2885 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
2888 if (newbsize < bp->b_bufsize)
2889 bufspacewakeup();
2890 bp->b_bufsize = newbsize; /* actual buffer allocation */
2891 bp->b_bcount = size; /* requested buffer size */
2892 return 1;
2896 * biowait:
2898 * Wait for buffer I/O completion, returning error status. The buffer
2899 * is left locked on return. B_EINTR is converted into an EINTR error
2900 * and cleared.
2902 * NOTE! The original b_cmd is lost on return, since b_cmd will be
2903 * set to BUF_CMD_DONE.
2906 biowait(struct buf *bp)
2908 crit_enter();
2909 while (bp->b_cmd != BUF_CMD_DONE) {
2910 if (bp->b_cmd == BUF_CMD_READ)
2911 tsleep(bp, 0, "biord", 0);
2912 else
2913 tsleep(bp, 0, "biowr", 0);
2915 crit_exit();
2916 if (bp->b_flags & B_EINTR) {
2917 bp->b_flags &= ~B_EINTR;
2918 return (EINTR);
2920 if (bp->b_flags & B_ERROR) {
2921 return (bp->b_error ? bp->b_error : EIO);
2922 } else {
2923 return (0);
2928 * This associates a tracking count with an I/O. vn_strategy() and
2929 * dev_dstrategy() do this automatically but there are a few cases
2930 * where a vnode or device layer is bypassed when a block translation
2931 * is cached. In such cases bio_start_transaction() may be called on
2932 * the bypassed layers so the system gets an I/O in progress indication
2933 * for those higher layers.
2935 void
2936 bio_start_transaction(struct bio *bio, struct bio_track *track)
2938 bio->bio_track = track;
2939 atomic_add_int(&track->bk_active, 1);
2943 * Initiate I/O on a vnode.
2945 void
2946 vn_strategy(struct vnode *vp, struct bio *bio)
2948 struct bio_track *track;
2950 KKASSERT(bio->bio_buf->b_cmd != BUF_CMD_DONE);
2951 if (bio->bio_buf->b_cmd == BUF_CMD_READ)
2952 track = &vp->v_track_read;
2953 else
2954 track = &vp->v_track_write;
2955 bio->bio_track = track;
2956 atomic_add_int(&track->bk_active, 1);
2957 vop_strategy(*vp->v_ops, vp, bio);
2962 * biodone:
2964 * Finish I/O on a buffer, optionally calling a completion function.
2965 * This is usually called from an interrupt so process blocking is
2966 * not allowed.
2968 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2969 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2970 * assuming B_INVAL is clear.
2972 * For the VMIO case, we set B_CACHE if the op was a read and no
2973 * read error occured, or if the op was a write. B_CACHE is never
2974 * set if the buffer is invalid or otherwise uncacheable.
2976 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2977 * initiator to leave B_INVAL set to brelse the buffer out of existance
2978 * in the biodone routine.
2980 void
2981 biodone(struct bio *bio)
2983 struct buf *bp = bio->bio_buf;
2984 buf_cmd_t cmd;
2986 crit_enter();
2988 KASSERT(BUF_REFCNTNB(bp) > 0,
2989 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
2990 KASSERT(bp->b_cmd != BUF_CMD_DONE,
2991 ("biodone: bp %p already done!", bp));
2993 runningbufwakeup(bp);
2996 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
2998 while (bio) {
2999 biodone_t *done_func;
3000 struct bio_track *track;
3003 * BIO tracking. Most but not all BIOs are tracked.
3005 if ((track = bio->bio_track) != NULL) {
3006 atomic_subtract_int(&track->bk_active, 1);
3007 if (track->bk_active < 0) {
3008 panic("biodone: bad active count bio %p\n",
3009 bio);
3011 if (track->bk_waitflag) {
3012 track->bk_waitflag = 0;
3013 wakeup(track);
3015 bio->bio_track = NULL;
3019 * A bio_done function terminates the loop. The function
3020 * will be responsible for any further chaining and/or
3021 * buffer management.
3023 * WARNING! The done function can deallocate the buffer!
3025 if ((done_func = bio->bio_done) != NULL) {
3026 bio->bio_done = NULL;
3027 done_func(bio);
3028 crit_exit();
3029 return;
3031 bio = bio->bio_prev;
3034 cmd = bp->b_cmd;
3035 bp->b_cmd = BUF_CMD_DONE;
3038 * Only reads and writes are processed past this point.
3040 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3041 brelse(bp);
3042 crit_exit();
3043 return;
3047 * Warning: softupdates may re-dirty the buffer.
3049 if (LIST_FIRST(&bp->b_dep) != NULL)
3050 buf_complete(bp);
3052 if (bp->b_flags & B_VMIO) {
3053 int i;
3054 vm_ooffset_t foff;
3055 vm_page_t m;
3056 vm_object_t obj;
3057 int iosize;
3058 struct vnode *vp = bp->b_vp;
3060 obj = vp->v_object;
3062 #if defined(VFS_BIO_DEBUG)
3063 if (vp->v_auxrefs == 0)
3064 panic("biodone: zero vnode hold count");
3065 if ((vp->v_flag & VOBJBUF) == 0)
3066 panic("biodone: vnode is not setup for merged cache");
3067 #endif
3069 foff = bp->b_loffset;
3070 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3071 KASSERT(obj != NULL, ("biodone: missing VM object"));
3073 #if defined(VFS_BIO_DEBUG)
3074 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3075 kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3076 obj->paging_in_progress, bp->b_xio.xio_npages);
3078 #endif
3081 * Set B_CACHE if the op was a normal read and no error
3082 * occured. B_CACHE is set for writes in the b*write()
3083 * routines.
3085 iosize = bp->b_bcount - bp->b_resid;
3086 if (cmd == BUF_CMD_READ && (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3087 bp->b_flags |= B_CACHE;
3090 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3091 int bogusflag = 0;
3092 int resid;
3094 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3095 if (resid > iosize)
3096 resid = iosize;
3099 * cleanup bogus pages, restoring the originals. Since
3100 * the originals should still be wired, we don't have
3101 * to worry about interrupt/freeing races destroying
3102 * the VM object association.
3104 m = bp->b_xio.xio_pages[i];
3105 if (m == bogus_page) {
3106 bogusflag = 1;
3107 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3108 if (m == NULL)
3109 panic("biodone: page disappeared");
3110 bp->b_xio.xio_pages[i] = m;
3111 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3112 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3114 #if defined(VFS_BIO_DEBUG)
3115 if (OFF_TO_IDX(foff) != m->pindex) {
3116 kprintf(
3117 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3118 (unsigned long)foff, m->pindex);
3120 #endif
3123 * In the write case, the valid and clean bits are
3124 * already changed correctly ( see bdwrite() ), so we
3125 * only need to do this here in the read case.
3127 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3128 vfs_page_set_valid(bp, foff, i, m);
3130 vm_page_flag_clear(m, PG_ZERO);
3133 * when debugging new filesystems or buffer I/O methods, this
3134 * is the most common error that pops up. if you see this, you
3135 * have not set the page busy flag correctly!!!
3137 if (m->busy == 0) {
3138 kprintf("biodone: page busy < 0, "
3139 "pindex: %d, foff: 0x(%x,%x), "
3140 "resid: %d, index: %d\n",
3141 (int) m->pindex, (int)(foff >> 32),
3142 (int) foff & 0xffffffff, resid, i);
3143 if (!vn_isdisk(vp, NULL))
3144 kprintf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
3145 bp->b_vp->v_mount->mnt_stat.f_iosize,
3146 bp->b_loffset,
3147 bp->b_flags, bp->b_xio.xio_npages);
3148 else
3149 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3150 bp->b_loffset,
3151 bp->b_flags, bp->b_xio.xio_npages);
3152 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3153 m->valid, m->dirty, m->wire_count);
3154 panic("biodone: page busy < 0");
3156 vm_page_io_finish(m);
3157 vm_object_pip_subtract(obj, 1);
3158 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3159 iosize -= resid;
3161 if (obj)
3162 vm_object_pip_wakeupn(obj, 0);
3166 * For asynchronous completions, release the buffer now. The brelse
3167 * will do a wakeup there if necessary - so no need to do a wakeup
3168 * here in the async case. The sync case always needs to do a wakeup.
3171 if (bp->b_flags & B_ASYNC) {
3172 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3173 brelse(bp);
3174 else
3175 bqrelse(bp);
3176 } else {
3177 wakeup(bp);
3179 crit_exit();
3183 * vfs_unbusy_pages:
3185 * This routine is called in lieu of iodone in the case of
3186 * incomplete I/O. This keeps the busy status for pages
3187 * consistant.
3189 void
3190 vfs_unbusy_pages(struct buf *bp)
3192 int i;
3194 runningbufwakeup(bp);
3195 if (bp->b_flags & B_VMIO) {
3196 struct vnode *vp = bp->b_vp;
3197 vm_object_t obj;
3199 obj = vp->v_object;
3201 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3202 vm_page_t m = bp->b_xio.xio_pages[i];
3205 * When restoring bogus changes the original pages
3206 * should still be wired, so we are in no danger of
3207 * losing the object association and do not need
3208 * critical section protection particularly.
3210 if (m == bogus_page) {
3211 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3212 if (!m) {
3213 panic("vfs_unbusy_pages: page missing");
3215 bp->b_xio.xio_pages[i] = m;
3216 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3217 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3219 vm_object_pip_subtract(obj, 1);
3220 vm_page_flag_clear(m, PG_ZERO);
3221 vm_page_io_finish(m);
3223 vm_object_pip_wakeupn(obj, 0);
3228 * vfs_page_set_valid:
3230 * Set the valid bits in a page based on the supplied offset. The
3231 * range is restricted to the buffer's size.
3233 * This routine is typically called after a read completes.
3235 static void
3236 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3238 vm_ooffset_t soff, eoff;
3241 * Start and end offsets in buffer. eoff - soff may not cross a
3242 * page boundry or cross the end of the buffer. The end of the
3243 * buffer, in this case, is our file EOF, not the allocation size
3244 * of the buffer.
3246 soff = off;
3247 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3248 if (eoff > bp->b_loffset + bp->b_bcount)
3249 eoff = bp->b_loffset + bp->b_bcount;
3252 * Set valid range. This is typically the entire buffer and thus the
3253 * entire page.
3255 if (eoff > soff) {
3256 vm_page_set_validclean(
3258 (vm_offset_t) (soff & PAGE_MASK),
3259 (vm_offset_t) (eoff - soff)
3265 * vfs_busy_pages:
3267 * This routine is called before a device strategy routine.
3268 * It is used to tell the VM system that paging I/O is in
3269 * progress, and treat the pages associated with the buffer
3270 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3271 * flag is handled to make sure that the object doesn't become
3272 * inconsistant.
3274 * Since I/O has not been initiated yet, certain buffer flags
3275 * such as B_ERROR or B_INVAL may be in an inconsistant state
3276 * and should be ignored.
3278 void
3279 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3281 int i, bogus;
3282 struct lwp *lp = curthread->td_lwp;
3285 * The buffer's I/O command must already be set. If reading,
3286 * B_CACHE must be 0 (double check against callers only doing
3287 * I/O when B_CACHE is 0).
3289 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3290 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3292 if (bp->b_flags & B_VMIO) {
3293 vm_object_t obj;
3294 vm_ooffset_t foff;
3296 obj = vp->v_object;
3297 foff = bp->b_loffset;
3298 KASSERT(bp->b_loffset != NOOFFSET,
3299 ("vfs_busy_pages: no buffer offset"));
3300 vfs_setdirty(bp);
3302 retry:
3303 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3304 vm_page_t m = bp->b_xio.xio_pages[i];
3305 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3306 goto retry;
3309 bogus = 0;
3310 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3311 vm_page_t m = bp->b_xio.xio_pages[i];
3313 vm_page_flag_clear(m, PG_ZERO);
3314 if ((bp->b_flags & B_CLUSTER) == 0) {
3315 vm_object_pip_add(obj, 1);
3316 vm_page_io_start(m);
3320 * When readying a vnode-backed buffer for a write
3321 * we must zero-fill any invalid portions of the
3322 * backing VM pages.
3324 * When readying a vnode-backed buffer for a read
3325 * we must replace any dirty pages with a bogus
3326 * page so we do not destroy dirty data when
3327 * filling in gaps. Dirty pages might not
3328 * necessarily be marked dirty yet, so use m->valid
3329 * as a reasonable test.
3331 * Bogus page replacement is, uh, bogus. We need
3332 * to find a better way.
3334 vm_page_protect(m, VM_PROT_NONE);
3335 if (bp->b_cmd == BUF_CMD_WRITE) {
3336 vfs_page_set_valid(bp, foff, i, m);
3337 } else if (m->valid == VM_PAGE_BITS_ALL) {
3338 bp->b_xio.xio_pages[i] = bogus_page;
3339 bogus++;
3341 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3343 if (bogus)
3344 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3345 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3349 * This is the easiest place to put the process accounting for the I/O
3350 * for now.
3352 if (lp != NULL) {
3353 if (bp->b_cmd == BUF_CMD_READ)
3354 lp->lwp_ru.ru_inblock++;
3355 else
3356 lp->lwp_ru.ru_oublock++;
3361 * vfs_clean_pages:
3363 * Tell the VM system that the pages associated with this buffer
3364 * are clean. This is used for delayed writes where the data is
3365 * going to go to disk eventually without additional VM intevention.
3367 * Note that while we only really need to clean through to b_bcount, we
3368 * just go ahead and clean through to b_bufsize.
3370 static void
3371 vfs_clean_pages(struct buf *bp)
3373 int i;
3375 if (bp->b_flags & B_VMIO) {
3376 vm_ooffset_t foff;
3378 foff = bp->b_loffset;
3379 KASSERT(foff != NOOFFSET, ("vfs_clean_pages: no buffer offset"));
3380 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3381 vm_page_t m = bp->b_xio.xio_pages[i];
3382 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3383 vm_ooffset_t eoff = noff;
3385 if (eoff > bp->b_loffset + bp->b_bufsize)
3386 eoff = bp->b_loffset + bp->b_bufsize;
3387 vfs_page_set_valid(bp, foff, i, m);
3388 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3389 foff = noff;
3395 * vfs_bio_set_validclean:
3397 * Set the range within the buffer to valid and clean. The range is
3398 * relative to the beginning of the buffer, b_loffset. Note that
3399 * b_loffset itself may be offset from the beginning of the first page.
3402 void
3403 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3405 if (bp->b_flags & B_VMIO) {
3406 int i;
3407 int n;
3410 * Fixup base to be relative to beginning of first page.
3411 * Set initial n to be the maximum number of bytes in the
3412 * first page that can be validated.
3415 base += (bp->b_loffset & PAGE_MASK);
3416 n = PAGE_SIZE - (base & PAGE_MASK);
3418 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3419 vm_page_t m = bp->b_xio.xio_pages[i];
3421 if (n > size)
3422 n = size;
3424 vm_page_set_validclean(m, base & PAGE_MASK, n);
3425 base += n;
3426 size -= n;
3427 n = PAGE_SIZE;
3433 * vfs_bio_clrbuf:
3435 * Clear a buffer. This routine essentially fakes an I/O, so we need
3436 * to clear B_ERROR and B_INVAL.
3438 * Note that while we only theoretically need to clear through b_bcount,
3439 * we go ahead and clear through b_bufsize.
3442 void
3443 vfs_bio_clrbuf(struct buf *bp)
3445 int i, mask = 0;
3446 caddr_t sa, ea;
3447 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3448 bp->b_flags &= ~(B_INVAL|B_ERROR);
3449 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3450 (bp->b_loffset & PAGE_MASK) == 0) {
3451 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3452 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3453 bp->b_resid = 0;
3454 return;
3456 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3457 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3458 bzero(bp->b_data, bp->b_bufsize);
3459 bp->b_xio.xio_pages[0]->valid |= mask;
3460 bp->b_resid = 0;
3461 return;
3464 ea = sa = bp->b_data;
3465 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3466 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3467 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3468 ea = (caddr_t)(vm_offset_t)ulmin(
3469 (u_long)(vm_offset_t)ea,
3470 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3471 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3472 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3473 continue;
3474 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3475 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3476 bzero(sa, ea - sa);
3478 } else {
3479 for (; sa < ea; sa += DEV_BSIZE, j++) {
3480 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3481 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3482 bzero(sa, DEV_BSIZE);
3485 bp->b_xio.xio_pages[i]->valid |= mask;
3486 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3488 bp->b_resid = 0;
3489 } else {
3490 clrbuf(bp);
3495 * vm_hold_load_pages:
3497 * Load pages into the buffer's address space. The pages are
3498 * allocated from the kernel object in order to reduce interference
3499 * with the any VM paging I/O activity. The range of loaded
3500 * pages will be wired.
3502 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3503 * retrieve the full range (to - from) of pages.
3506 void
3507 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3509 vm_offset_t pg;
3510 vm_page_t p;
3511 int index;
3513 to = round_page(to);
3514 from = round_page(from);
3515 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3517 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3519 tryagain:
3522 * Note: must allocate system pages since blocking here
3523 * could intefere with paging I/O, no matter which
3524 * process we are.
3526 p = vm_page_alloc(&kernel_object,
3527 (pg >> PAGE_SHIFT),
3528 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3529 if (!p) {
3530 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3531 vm_wait();
3532 goto tryagain;
3534 vm_page_wire(p);
3535 p->valid = VM_PAGE_BITS_ALL;
3536 vm_page_flag_clear(p, PG_ZERO);
3537 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3538 bp->b_xio.xio_pages[index] = p;
3539 vm_page_wakeup(p);
3541 bp->b_xio.xio_npages = index;
3545 * vm_hold_free_pages:
3547 * Return pages associated with the buffer back to the VM system.
3549 * The range of pages underlying the buffer's address space will
3550 * be unmapped and un-wired.
3552 void
3553 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3555 vm_offset_t pg;
3556 vm_page_t p;
3557 int index, newnpages;
3559 from = round_page(from);
3560 to = round_page(to);
3561 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3563 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3564 p = bp->b_xio.xio_pages[index];
3565 if (p && (index < bp->b_xio.xio_npages)) {
3566 if (p->busy) {
3567 kprintf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3568 bp->b_bio2.bio_offset, bp->b_loffset);
3570 bp->b_xio.xio_pages[index] = NULL;
3571 pmap_kremove(pg);
3572 vm_page_busy(p);
3573 vm_page_unwire(p, 0);
3574 vm_page_free(p);
3577 bp->b_xio.xio_npages = newnpages;
3581 * vmapbuf:
3583 * Map a user buffer into KVM via a pbuf. On return the buffer's
3584 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3585 * initialized.
3588 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
3590 caddr_t addr;
3591 vm_offset_t va;
3592 vm_page_t m;
3593 int vmprot;
3594 int error;
3595 int pidx;
3596 int i;
3599 * bp had better have a command and it better be a pbuf.
3601 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3602 KKASSERT(bp->b_flags & B_PAGING);
3604 if (bytes < 0)
3605 return (-1);
3608 * Map the user data into KVM. Mappings have to be page-aligned.
3610 addr = (caddr_t)trunc_page((vm_offset_t)udata);
3611 pidx = 0;
3613 vmprot = VM_PROT_READ;
3614 if (bp->b_cmd == BUF_CMD_READ)
3615 vmprot |= VM_PROT_WRITE;
3617 while (addr < udata + bytes) {
3619 * Do the vm_fault if needed; do the copy-on-write thing
3620 * when reading stuff off device into memory.
3622 * vm_fault_page*() returns a held VM page.
3624 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
3625 va = trunc_page(va);
3627 m = vm_fault_page_quick(va, vmprot, &error);
3628 if (m == NULL) {
3629 for (i = 0; i < pidx; ++i) {
3630 vm_page_unhold(bp->b_xio.xio_pages[i]);
3631 bp->b_xio.xio_pages[i] = NULL;
3633 return(-1);
3635 bp->b_xio.xio_pages[pidx] = m;
3636 addr += PAGE_SIZE;
3637 ++pidx;
3641 * Map the page array and set the buffer fields to point to
3642 * the mapped data buffer.
3644 if (pidx > btoc(MAXPHYS))
3645 panic("vmapbuf: mapped more than MAXPHYS");
3646 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
3648 bp->b_xio.xio_npages = pidx;
3649 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
3650 bp->b_bcount = bytes;
3651 bp->b_bufsize = bytes;
3652 return(0);
3656 * vunmapbuf:
3658 * Free the io map PTEs associated with this IO operation.
3659 * We also invalidate the TLB entries and restore the original b_addr.
3661 void
3662 vunmapbuf(struct buf *bp)
3664 int pidx;
3665 int npages;
3667 KKASSERT(bp->b_flags & B_PAGING);
3669 npages = bp->b_xio.xio_npages;
3670 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3671 for (pidx = 0; pidx < npages; ++pidx) {
3672 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
3673 bp->b_xio.xio_pages[pidx] = NULL;
3675 bp->b_xio.xio_npages = 0;
3676 bp->b_data = bp->b_kvabase;
3680 * Scan all buffers in the system and issue the callback.
3683 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
3685 int count = 0;
3686 int error;
3687 int n;
3689 for (n = 0; n < nbuf; ++n) {
3690 if ((error = callback(&buf[n], info)) < 0) {
3691 count = error;
3692 break;
3694 count += error;
3696 return (count);
3700 * print out statistics from the current status of the buffer pool
3701 * this can be toggeled by the system control option debug.syncprt
3703 #ifdef DEBUG
3704 void
3705 vfs_bufstats(void)
3707 int i, j, count;
3708 struct buf *bp;
3709 struct bqueues *dp;
3710 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3711 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3713 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3714 count = 0;
3715 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3716 counts[j] = 0;
3717 crit_enter();
3718 TAILQ_FOREACH(bp, dp, b_freelist) {
3719 counts[bp->b_bufsize/PAGE_SIZE]++;
3720 count++;
3722 crit_exit();
3723 kprintf("%s: total-%d", bname[i], count);
3724 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3725 if (counts[j] != 0)
3726 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
3727 kprintf("\n");
3730 #endif
3732 #ifdef DDB
3734 DB_SHOW_COMMAND(buffer, db_show_buffer)
3736 /* get args */
3737 struct buf *bp = (struct buf *)addr;
3739 if (!have_addr) {
3740 db_printf("usage: show buffer <addr>\n");
3741 return;
3744 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3745 db_printf("b_cmd = %d\n", bp->b_cmd);
3746 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3747 "b_resid = %d\n, b_data = %p, "
3748 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3749 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3750 bp->b_data, bp->b_bio2.bio_offset, (bp->b_bio2.bio_next ? bp->b_bio2.bio_next->bio_offset : (off_t)-1));
3751 if (bp->b_xio.xio_npages) {
3752 int i;
3753 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3754 bp->b_xio.xio_npages);
3755 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3756 vm_page_t m;
3757 m = bp->b_xio.xio_pages[i];
3758 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3759 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3760 if ((i + 1) < bp->b_xio.xio_npages)
3761 db_printf(",");
3763 db_printf("\n");
3766 #endif /* DDB */