Replace the bwillwrite() subsystem to make it more fair to processes.
[dragonfly.git] / sys / kern / vfs_bio.c
blobfe31828169ed01b2d31f2106003db3b80a62fb18
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.106 2008/06/28 17:59:49 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 #define BD_WAKE_SIZE 128
85 #define BD_WAKE_MASK (BD_WAKE_SIZE - 1)
87 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
89 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
91 struct buf *buf; /* buffer header pool */
93 static void vm_hold_free_pages(struct buf *bp, vm_offset_t from,
94 vm_offset_t to);
95 static void vm_hold_load_pages(struct buf *bp, vm_offset_t from,
96 vm_offset_t to);
97 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
98 int pageno, vm_page_t m);
99 static void vfs_clean_pages(struct buf *bp);
100 static void vfs_setdirty(struct buf *bp);
101 static void vfs_vmio_release(struct buf *bp);
102 static int flushbufqueues(bufq_type_t q);
104 static void bd_signal(void);
105 static void buf_daemon(void);
106 static void buf_daemon_hw(void);
109 * bogus page -- for I/O to/from partially complete buffers
110 * this is a temporary solution to the problem, but it is not
111 * really that bad. it would be better to split the buffer
112 * for input in the case of buffers partially already in memory,
113 * but the code is intricate enough already.
115 vm_page_t bogus_page;
118 * These are all static, but make the ones we export globals so we do
119 * not need to use compiler magic.
121 int bufspace, maxbufspace,
122 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
123 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
124 static int lorunningspace, hirunningspace, runningbufreq;
125 int numdirtybuffers, numdirtybuffershw, lodirtybuffers, hidirtybuffers;
126 int runningbufspace, runningbufcount;
127 static int numfreebuffers, lofreebuffers, hifreebuffers;
128 static int getnewbufcalls;
129 static int getnewbufrestarts;
130 static int needsbuffer; /* locked by needsbuffer_spin */
131 static int bd_request; /* locked by needsbuffer_spin */
132 static int bd_request_hw; /* locked by needsbuffer_spin */
133 static u_int bd_wake_ary[BD_WAKE_SIZE];
134 static u_int bd_wake_index;
135 static struct spinlock needsbuffer_spin;
138 * Sysctls for operational control of the buffer cache.
140 SYSCTL_INT(_vfs, OID_AUTO, lodirtybuffers, CTLFLAG_RW, &lodirtybuffers, 0,
141 "Number of dirty buffers to flush before bufdaemon becomes inactive");
142 SYSCTL_INT(_vfs, OID_AUTO, hidirtybuffers, CTLFLAG_RW, &hidirtybuffers, 0,
143 "High watermark used to trigger explicit flushing of dirty buffers");
144 SYSCTL_INT(_vfs, OID_AUTO, lofreebuffers, CTLFLAG_RW, &lofreebuffers, 0,
145 "Low watermark for special reserve in low-memory situations");
146 SYSCTL_INT(_vfs, OID_AUTO, hifreebuffers, CTLFLAG_RW, &hifreebuffers, 0,
147 "High watermark for special reserve in low-memory situations");
148 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
149 "Minimum amount of buffer space required for active I/O");
150 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
151 "Maximum amount of buffer space to usable for active I/O");
153 * Sysctls determining current state of the buffer cache.
155 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
156 "Total number of buffers in buffer cache");
157 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffers, CTLFLAG_RD, &numdirtybuffers, 0,
158 "Pending number of dirty buffers (all)");
159 SYSCTL_INT(_vfs, OID_AUTO, numdirtybuffershw, CTLFLAG_RD, &numdirtybuffershw, 0,
160 "Pending number of dirty buffers (heavy weight)");
161 SYSCTL_INT(_vfs, OID_AUTO, numfreebuffers, CTLFLAG_RD, &numfreebuffers, 0,
162 "Number of free buffers on the buffer cache free list");
163 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
164 "I/O bytes currently in progress due to asynchronous writes");
165 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
166 "I/O buffers currently in progress due to asynchronous writes");
167 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
168 "Hard limit on maximum amount of memory usable for buffer space");
169 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
170 "Soft limit on maximum amount of memory usable for buffer space");
171 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
172 "Minimum amount of memory to reserve for system buffer space");
173 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
174 "Amount of memory available for buffers");
175 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
176 0, "Maximum amount of memory reserved for buffers using malloc");
177 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
178 "Amount of memory left for buffers using malloc-scheme");
179 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
180 "New buffer header acquisition requests");
181 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
182 0, "New buffer header acquisition restarts");
183 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
184 "Buffer acquisition restarts due to fragmented buffer map");
185 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
186 "Amount of time KVA space was deallocated in an arbitrary buffer");
187 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
188 "Amount of time buffer re-use operations were successful");
189 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
190 "sizeof(struct buf)");
192 char *buf_wmesg = BUF_WMESG;
194 extern int vm_swap_size;
196 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
197 #define VFS_BIO_NEED_UNUSED02 0x02
198 #define VFS_BIO_NEED_FREE 0x04 /* wait for free bufs, hi hysteresis */
199 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
202 * bufspacewakeup:
204 * Called when buffer space is potentially available for recovery.
205 * getnewbuf() will block on this flag when it is unable to free
206 * sufficient buffer space. Buffer space becomes recoverable when
207 * bp's get placed back in the queues.
210 static __inline void
211 bufspacewakeup(void)
214 * If someone is waiting for BUF space, wake them up. Even
215 * though we haven't freed the kva space yet, the waiting
216 * process will be able to now.
218 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
219 spin_lock_wr(&needsbuffer_spin);
220 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
221 spin_unlock_wr(&needsbuffer_spin);
222 wakeup(&needsbuffer);
227 * runningbufwakeup:
229 * Accounting for I/O in progress.
232 static __inline void
233 runningbufwakeup(struct buf *bp)
235 if (bp->b_runningbufspace) {
236 runningbufspace -= bp->b_runningbufspace;
237 --runningbufcount;
238 bp->b_runningbufspace = 0;
239 if (runningbufreq && runningbufspace <= lorunningspace) {
240 runningbufreq = 0;
241 wakeup(&runningbufreq);
243 bd_signal();
248 * bufcountwakeup:
250 * Called when a buffer has been added to one of the free queues to
251 * account for the buffer and to wakeup anyone waiting for free buffers.
252 * This typically occurs when large amounts of metadata are being handled
253 * by the buffer cache ( else buffer space runs out first, usually ).
256 static __inline void
257 bufcountwakeup(void)
259 ++numfreebuffers;
260 if (needsbuffer) {
261 spin_lock_wr(&needsbuffer_spin);
262 needsbuffer &= ~VFS_BIO_NEED_ANY;
263 if (numfreebuffers >= hifreebuffers)
264 needsbuffer &= ~VFS_BIO_NEED_FREE;
265 spin_unlock_wr(&needsbuffer_spin);
266 wakeup(&needsbuffer);
271 * waitrunningbufspace()
273 * runningbufspace is a measure of the amount of I/O currently
274 * running. This routine is used in async-write situations to
275 * prevent creating huge backups of pending writes to a device.
276 * Only asynchronous writes are governed by this function.
278 * Reads will adjust runningbufspace, but will not block based on it.
279 * The read load has a side effect of reducing the allowed write load.
281 * This does NOT turn an async write into a sync write. It waits
282 * for earlier writes to complete and generally returns before the
283 * caller's write has reached the device.
285 static __inline void
286 waitrunningbufspace(void)
288 if (runningbufspace > hirunningspace) {
289 crit_enter();
290 while (runningbufspace > hirunningspace) {
291 ++runningbufreq;
292 tsleep(&runningbufreq, 0, "wdrain", 0);
294 crit_exit();
299 * vfs_buf_test_cache:
301 * Called when a buffer is extended. This function clears the B_CACHE
302 * bit if the newly extended portion of the buffer does not contain
303 * valid data.
305 static __inline__
306 void
307 vfs_buf_test_cache(struct buf *bp,
308 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
309 vm_page_t m)
311 if (bp->b_flags & B_CACHE) {
312 int base = (foff + off) & PAGE_MASK;
313 if (vm_page_is_valid(m, base, size) == 0)
314 bp->b_flags &= ~B_CACHE;
319 * bd_speedup:
321 * Unconditionally speed-up the buf_daemon
323 static __inline__
324 void
325 bd_speedup(void)
327 if (bd_request == 0 && numdirtybuffers) {
328 spin_lock_wr(&needsbuffer_spin);
329 bd_request = 1;
330 spin_unlock_wr(&needsbuffer_spin);
331 wakeup(&bd_request);
333 if (bd_request_hw == 0 && numdirtybuffershw) {
334 spin_lock_wr(&needsbuffer_spin);
335 bd_request_hw = 1;
336 spin_unlock_wr(&needsbuffer_spin);
337 wakeup(&bd_request_hw);
342 * bd_heatup()
344 * Get the buf_daemon heated up when the number of running and dirty
345 * buffers exceeds the mid-point.
348 bd_heatup(void)
350 int mid1;
351 int mid2;
352 int count;
354 mid1 = lodirtybuffers + (hidirtybuffers - lodirtybuffers) / 2;
356 count = runningbufcount + numdirtybuffers;
357 if (count >= mid1) {
358 bd_speedup();
359 mid2 = mid1 + (hidirtybuffers - mid1) / 2;
360 if (count >= mid2)
361 return(count - mid2);
363 return(0);
367 * bd_wait()
369 * Wait for the buffer cache to flush (count) buffers, then return.
371 * Regardless this function blocks while the number of dirty buffers
372 * exceeds hidirtybuffers.
374 void
375 bd_wait(int count)
377 u_int i;
379 while (count > 0) {
380 bd_heatup();
381 crit_enter();
382 if (count > runningbufcount + numdirtybuffers)
383 count = runningbufcount + numdirtybuffers;
384 if (count >= BD_WAKE_SIZE)
385 count = BD_WAKE_SIZE - 1;
386 i = (bd_wake_index + count) & BD_WAKE_MASK;
387 ++bd_wake_ary[i];
388 tsleep(&bd_wake_ary[i], 0, "flstik", hz);
389 crit_exit();
391 count = runningbufcount + numdirtybuffers - hidirtybuffers;
396 * bd_signal()
398 * This function is called whenever runningbufcount or numdirtybuffers
399 * is decremented. Track threads waiting for run+dirty buffer I/O
400 * complete.
402 static void
403 bd_signal(void)
405 u_int i;
407 i = atomic_fetchadd_int(&bd_wake_index, 1);
408 i &= BD_WAKE_MASK;
409 if (bd_wake_ary[i]) {
410 bd_wake_ary[i] = 0;
411 wakeup(&bd_wake_ary[i]);
416 * bufinit:
418 * Load time initialisation of the buffer cache, called from machine
419 * dependant initialization code.
421 void
422 bufinit(void)
424 struct buf *bp;
425 vm_offset_t bogus_offset;
426 int i;
428 spin_init(&needsbuffer_spin);
430 /* next, make a null set of free lists */
431 for (i = 0; i < BUFFER_QUEUES; i++)
432 TAILQ_INIT(&bufqueues[i]);
434 /* finally, initialize each buffer header and stick on empty q */
435 for (i = 0; i < nbuf; i++) {
436 bp = &buf[i];
437 bzero(bp, sizeof *bp);
438 bp->b_flags = B_INVAL; /* we're just an empty header */
439 bp->b_cmd = BUF_CMD_DONE;
440 bp->b_qindex = BQUEUE_EMPTY;
441 initbufbio(bp);
442 xio_init(&bp->b_xio);
443 buf_dep_init(bp);
444 BUF_LOCKINIT(bp);
445 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
449 * maxbufspace is the absolute maximum amount of buffer space we are
450 * allowed to reserve in KVM and in real terms. The absolute maximum
451 * is nominally used by buf_daemon. hibufspace is the nominal maximum
452 * used by most other processes. The differential is required to
453 * ensure that buf_daemon is able to run when other processes might
454 * be blocked waiting for buffer space.
456 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
457 * this may result in KVM fragmentation which is not handled optimally
458 * by the system.
460 maxbufspace = nbuf * BKVASIZE;
461 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
462 lobufspace = hibufspace - MAXBSIZE;
464 lorunningspace = 512 * 1024;
465 hirunningspace = 1024 * 1024;
468 * Limit the amount of malloc memory since it is wired permanently into
469 * the kernel space. Even though this is accounted for in the buffer
470 * allocation, we don't want the malloced region to grow uncontrolled.
471 * The malloc scheme improves memory utilization significantly on average
472 * (small) directories.
474 maxbufmallocspace = hibufspace / 20;
477 * Reduce the chance of a deadlock occuring by limiting the number
478 * of delayed-write dirty buffers we allow to stack up.
480 hidirtybuffers = nbuf / 4 + 20;
481 numdirtybuffers = 0;
482 numdirtybuffershw = 0;
484 * To support extreme low-memory systems, make sure hidirtybuffers cannot
485 * eat up all available buffer space. This occurs when our minimum cannot
486 * be met. We try to size hidirtybuffers to 3/4 our buffer space assuming
487 * BKVASIZE'd (8K) buffers.
489 while (hidirtybuffers * BKVASIZE > 3 * hibufspace / 4) {
490 hidirtybuffers >>= 1;
492 lodirtybuffers = hidirtybuffers / 2;
495 * Try to keep the number of free buffers in the specified range,
496 * and give special processes (e.g. like buf_daemon) access to an
497 * emergency reserve.
499 lofreebuffers = nbuf / 18 + 5;
500 hifreebuffers = 2 * lofreebuffers;
501 numfreebuffers = nbuf;
504 * Maximum number of async ops initiated per buf_daemon loop. This is
505 * somewhat of a hack at the moment, we really need to limit ourselves
506 * based on the number of bytes of I/O in-transit that were initiated
507 * from buf_daemon.
510 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
511 bogus_page = vm_page_alloc(&kernel_object,
512 (bogus_offset >> PAGE_SHIFT),
513 VM_ALLOC_NORMAL);
514 vmstats.v_wire_count++;
519 * Initialize the embedded bio structures
521 void
522 initbufbio(struct buf *bp)
524 bp->b_bio1.bio_buf = bp;
525 bp->b_bio1.bio_prev = NULL;
526 bp->b_bio1.bio_offset = NOOFFSET;
527 bp->b_bio1.bio_next = &bp->b_bio2;
528 bp->b_bio1.bio_done = NULL;
530 bp->b_bio2.bio_buf = bp;
531 bp->b_bio2.bio_prev = &bp->b_bio1;
532 bp->b_bio2.bio_offset = NOOFFSET;
533 bp->b_bio2.bio_next = NULL;
534 bp->b_bio2.bio_done = NULL;
538 * Reinitialize the embedded bio structures as well as any additional
539 * translation cache layers.
541 void
542 reinitbufbio(struct buf *bp)
544 struct bio *bio;
546 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
547 bio->bio_done = NULL;
548 bio->bio_offset = NOOFFSET;
553 * Push another BIO layer onto an existing BIO and return it. The new
554 * BIO layer may already exist, holding cached translation data.
556 struct bio *
557 push_bio(struct bio *bio)
559 struct bio *nbio;
561 if ((nbio = bio->bio_next) == NULL) {
562 int index = bio - &bio->bio_buf->b_bio_array[0];
563 if (index >= NBUF_BIO - 1) {
564 panic("push_bio: too many layers bp %p\n",
565 bio->bio_buf);
567 nbio = &bio->bio_buf->b_bio_array[index + 1];
568 bio->bio_next = nbio;
569 nbio->bio_prev = bio;
570 nbio->bio_buf = bio->bio_buf;
571 nbio->bio_offset = NOOFFSET;
572 nbio->bio_done = NULL;
573 nbio->bio_next = NULL;
575 KKASSERT(nbio->bio_done == NULL);
576 return(nbio);
579 void
580 pop_bio(struct bio *bio)
582 /* NOP */
585 void
586 clearbiocache(struct bio *bio)
588 while (bio) {
589 bio->bio_offset = NOOFFSET;
590 bio = bio->bio_next;
595 * bfreekva:
597 * Free the KVA allocation for buffer 'bp'.
599 * Must be called from a critical section as this is the only locking for
600 * buffer_map.
602 * Since this call frees up buffer space, we call bufspacewakeup().
604 static void
605 bfreekva(struct buf *bp)
607 int count;
609 if (bp->b_kvasize) {
610 ++buffreekvacnt;
611 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
612 vm_map_lock(&buffer_map);
613 bufspace -= bp->b_kvasize;
614 vm_map_delete(&buffer_map,
615 (vm_offset_t) bp->b_kvabase,
616 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
617 &count
619 vm_map_unlock(&buffer_map);
620 vm_map_entry_release(count);
621 bp->b_kvasize = 0;
622 bufspacewakeup();
627 * bremfree:
629 * Remove the buffer from the appropriate free list.
631 void
632 bremfree(struct buf *bp)
634 int old_qindex;
636 crit_enter();
637 old_qindex = bp->b_qindex;
639 if (bp->b_qindex != BQUEUE_NONE) {
640 KASSERT(BUF_REFCNTNB(bp) == 1,
641 ("bremfree: bp %p not locked",bp));
642 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
643 bp->b_qindex = BQUEUE_NONE;
644 } else {
645 if (BUF_REFCNTNB(bp) <= 1)
646 panic("bremfree: removing a buffer not on a queue");
650 * Fixup numfreebuffers count. If the buffer is invalid or not
651 * delayed-write, and it was on the EMPTY, LRU, or AGE queues,
652 * the buffer was free and we must decrement numfreebuffers.
654 if ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0) {
655 switch(old_qindex) {
656 case BQUEUE_DIRTY:
657 case BQUEUE_DIRTY_HW:
658 case BQUEUE_CLEAN:
659 case BQUEUE_EMPTY:
660 case BQUEUE_EMPTYKVA:
661 --numfreebuffers;
662 break;
663 default:
664 break;
667 crit_exit();
672 * bread:
674 * Get a buffer with the specified data. Look in the cache first. We
675 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
676 * is set, the buffer is valid and we do not have to do anything ( see
677 * getblk() ).
680 bread(struct vnode *vp, off_t loffset, int size, struct buf **bpp)
682 struct buf *bp;
684 bp = getblk(vp, loffset, size, 0, 0);
685 *bpp = bp;
687 /* if not found in cache, do some I/O */
688 if ((bp->b_flags & B_CACHE) == 0) {
689 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
690 bp->b_flags &= ~(B_ERROR | B_INVAL);
691 bp->b_cmd = BUF_CMD_READ;
692 vfs_busy_pages(vp, bp);
693 vn_strategy(vp, &bp->b_bio1);
694 return (biowait(bp));
696 return (0);
700 * breadn:
702 * Operates like bread, but also starts asynchronous I/O on
703 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
704 * to initiating I/O . If B_CACHE is set, the buffer is valid
705 * and we do not have to do anything.
708 breadn(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
709 int *rabsize, int cnt, struct buf **bpp)
711 struct buf *bp, *rabp;
712 int i;
713 int rv = 0, readwait = 0;
715 *bpp = bp = getblk(vp, loffset, size, 0, 0);
717 /* if not found in cache, do some I/O */
718 if ((bp->b_flags & B_CACHE) == 0) {
719 bp->b_flags &= ~(B_ERROR | B_INVAL);
720 bp->b_cmd = BUF_CMD_READ;
721 vfs_busy_pages(vp, bp);
722 vn_strategy(vp, &bp->b_bio1);
723 ++readwait;
726 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
727 if (inmem(vp, *raoffset))
728 continue;
729 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
731 if ((rabp->b_flags & B_CACHE) == 0) {
732 rabp->b_flags |= B_ASYNC;
733 rabp->b_flags &= ~(B_ERROR | B_INVAL);
734 rabp->b_cmd = BUF_CMD_READ;
735 vfs_busy_pages(vp, rabp);
736 BUF_KERNPROC(rabp);
737 vn_strategy(vp, &rabp->b_bio1);
738 } else {
739 brelse(rabp);
743 if (readwait) {
744 rv = biowait(bp);
746 return (rv);
750 * bwrite:
752 * Write, release buffer on completion. (Done by iodone
753 * if async). Do not bother writing anything if the buffer
754 * is invalid.
756 * Note that we set B_CACHE here, indicating that buffer is
757 * fully valid and thus cacheable. This is true even of NFS
758 * now so we set it generally. This could be set either here
759 * or in biodone() since the I/O is synchronous. We put it
760 * here.
763 bwrite(struct buf *bp)
765 int oldflags;
767 if (bp->b_flags & B_INVAL) {
768 brelse(bp);
769 return (0);
772 oldflags = bp->b_flags;
774 if (BUF_REFCNTNB(bp) == 0)
775 panic("bwrite: buffer is not busy???");
776 crit_enter();
778 /* Mark the buffer clean */
779 bundirty(bp);
781 bp->b_flags &= ~B_ERROR;
782 bp->b_flags |= B_CACHE;
783 bp->b_cmd = BUF_CMD_WRITE;
784 vfs_busy_pages(bp->b_vp, bp);
787 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
788 * valid for vnode-backed buffers.
790 bp->b_runningbufspace = bp->b_bufsize;
791 if (bp->b_runningbufspace) {
792 runningbufspace += bp->b_runningbufspace;
793 ++runningbufcount;
796 crit_exit();
797 if (oldflags & B_ASYNC)
798 BUF_KERNPROC(bp);
799 vn_strategy(bp->b_vp, &bp->b_bio1);
801 if ((oldflags & B_ASYNC) == 0) {
802 int rtval = biowait(bp);
803 brelse(bp);
804 return (rtval);
806 return (0);
810 * bdwrite:
812 * Delayed write. (Buffer is marked dirty). Do not bother writing
813 * anything if the buffer is marked invalid.
815 * Note that since the buffer must be completely valid, we can safely
816 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
817 * biodone() in order to prevent getblk from writing the buffer
818 * out synchronously.
820 void
821 bdwrite(struct buf *bp)
823 if (BUF_REFCNTNB(bp) == 0)
824 panic("bdwrite: buffer is not busy");
826 if (bp->b_flags & B_INVAL) {
827 brelse(bp);
828 return;
830 bdirty(bp);
833 * Set B_CACHE, indicating that the buffer is fully valid. This is
834 * true even of NFS now.
836 bp->b_flags |= B_CACHE;
839 * This bmap keeps the system from needing to do the bmap later,
840 * perhaps when the system is attempting to do a sync. Since it
841 * is likely that the indirect block -- or whatever other datastructure
842 * that the filesystem needs is still in memory now, it is a good
843 * thing to do this. Note also, that if the pageout daemon is
844 * requesting a sync -- there might not be enough memory to do
845 * the bmap then... So, this is important to do.
847 if (bp->b_bio2.bio_offset == NOOFFSET) {
848 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
849 NULL, NULL, BUF_CMD_WRITE);
853 * Set the *dirty* buffer range based upon the VM system dirty pages.
855 vfs_setdirty(bp);
858 * We need to do this here to satisfy the vnode_pager and the
859 * pageout daemon, so that it thinks that the pages have been
860 * "cleaned". Note that since the pages are in a delayed write
861 * buffer -- the VFS layer "will" see that the pages get written
862 * out on the next sync, or perhaps the cluster will be completed.
864 vfs_clean_pages(bp);
865 bqrelse(bp);
868 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
869 * due to the softdep code.
874 * bdirty:
876 * Turn buffer into delayed write request by marking it B_DELWRI.
877 * B_RELBUF and B_NOCACHE must be cleared.
879 * We reassign the buffer to itself to properly update it in the
880 * dirty/clean lists.
882 * Since the buffer is not on a queue, we do not update the
883 * numfreebuffers count.
885 * Must be called from a critical section.
886 * The buffer must be on BQUEUE_NONE.
888 void
889 bdirty(struct buf *bp)
891 KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
892 if (bp->b_flags & B_NOCACHE) {
893 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
894 bp->b_flags &= ~B_NOCACHE;
896 if (bp->b_flags & B_INVAL) {
897 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
899 bp->b_flags &= ~B_RELBUF;
901 if ((bp->b_flags & B_DELWRI) == 0) {
902 bp->b_flags |= B_DELWRI;
903 reassignbuf(bp);
904 ++numdirtybuffers;
905 if (bp->b_flags & B_HEAVY)
906 ++numdirtybuffershw;
907 bd_heatup();
912 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
913 * needs to be flushed with a different buf_daemon thread to avoid
914 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
916 void
917 bheavy(struct buf *bp)
919 if ((bp->b_flags & B_HEAVY) == 0) {
920 bp->b_flags |= B_HEAVY;
921 if (bp->b_flags & B_DELWRI)
922 ++numdirtybuffershw;
927 * bundirty:
929 * Clear B_DELWRI for buffer.
931 * Since the buffer is not on a queue, we do not update the numfreebuffers
932 * count.
934 * Must be called from a critical section.
936 * The buffer is typically on BQUEUE_NONE but there is one case in
937 * brelse() that calls this function after placing the buffer on
938 * a different queue.
941 void
942 bundirty(struct buf *bp)
944 if (bp->b_flags & B_DELWRI) {
945 bp->b_flags &= ~B_DELWRI;
946 reassignbuf(bp);
947 --numdirtybuffers;
948 if (bp->b_flags & B_HEAVY)
949 --numdirtybuffershw;
950 bd_signal();
953 * Since it is now being written, we can clear its deferred write flag.
955 bp->b_flags &= ~B_DEFERRED;
959 * bawrite:
961 * Asynchronous write. Start output on a buffer, but do not wait for
962 * it to complete. The buffer is released when the output completes.
964 * bwrite() ( or the VOP routine anyway ) is responsible for handling
965 * B_INVAL buffers. Not us.
967 void
968 bawrite(struct buf *bp)
970 bp->b_flags |= B_ASYNC;
971 bwrite(bp);
975 * bowrite:
977 * Ordered write. Start output on a buffer, and flag it so that the
978 * device will write it in the order it was queued. The buffer is
979 * released when the output completes. bwrite() ( or the VOP routine
980 * anyway ) is responsible for handling B_INVAL buffers.
983 bowrite(struct buf *bp)
985 bp->b_flags |= B_ORDERED | B_ASYNC;
986 return (bwrite(bp));
990 * buf_dirty_count_severe:
992 * Return true if we have too many dirty buffers.
995 buf_dirty_count_severe(void)
997 return(runningbufcount + numdirtybuffers >= hidirtybuffers);
1001 * brelse:
1003 * Release a busy buffer and, if requested, free its resources. The
1004 * buffer will be stashed in the appropriate bufqueue[] allowing it
1005 * to be accessed later as a cache entity or reused for other purposes.
1007 void
1008 brelse(struct buf *bp)
1010 #ifdef INVARIANTS
1011 int saved_flags = bp->b_flags;
1012 #endif
1014 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1016 crit_enter();
1019 * If B_NOCACHE is set we are being asked to destroy the buffer and
1020 * its backing store. Clear B_DELWRI.
1022 * B_NOCACHE is set in two cases: (1) when the caller really wants
1023 * to destroy the buffer and backing store and (2) when the caller
1024 * wants to destroy the buffer and backing store after a write
1025 * completes.
1027 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1028 bundirty(bp);
1031 if (bp->b_flags & B_LOCKED)
1032 bp->b_flags &= ~B_ERROR;
1035 * If a write error occurs and the caller does not want to throw
1036 * away the buffer, redirty the buffer. This will also clear
1037 * B_NOCACHE.
1039 if (bp->b_cmd == BUF_CMD_WRITE &&
1040 (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
1042 * Failed write, redirty. Must clear B_ERROR to prevent
1043 * pages from being scrapped. If B_INVAL is set then
1044 * this case is not run and the next case is run to
1045 * destroy the buffer. B_INVAL can occur if the buffer
1046 * is outside the range supported by the underlying device.
1048 bp->b_flags &= ~B_ERROR;
1049 bdirty(bp);
1050 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1051 (bp->b_bufsize <= 0) || bp->b_cmd == BUF_CMD_FREEBLKS) {
1053 * Either a failed I/O or we were asked to free or not
1054 * cache the buffer.
1056 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1057 * buffer cannot be immediately freed.
1059 bp->b_flags |= B_INVAL;
1060 if (LIST_FIRST(&bp->b_dep) != NULL)
1061 buf_deallocate(bp);
1062 if (bp->b_flags & B_DELWRI) {
1063 --numdirtybuffers;
1064 if (bp->b_flags & B_HEAVY)
1065 --numdirtybuffershw;
1066 bd_signal();
1068 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1072 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1073 * If vfs_vmio_release() is called with either bit set, the
1074 * underlying pages may wind up getting freed causing a previous
1075 * write (bdwrite()) to get 'lost' because pages associated with
1076 * a B_DELWRI bp are marked clean. Pages associated with a
1077 * B_LOCKED buffer may be mapped by the filesystem.
1079 * If we want to release the buffer ourselves (rather then the
1080 * originator asking us to release it), give the originator a
1081 * chance to countermand the release by setting B_LOCKED.
1083 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1084 * if B_DELWRI is set.
1086 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1087 * on pages to return pages to the VM page queues.
1089 if (bp->b_flags & (B_DELWRI | B_LOCKED)) {
1090 bp->b_flags &= ~B_RELBUF;
1091 } else if (vm_page_count_severe()) {
1092 if (LIST_FIRST(&bp->b_dep) != NULL)
1093 buf_deallocate(bp);
1094 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1095 bp->b_flags &= ~B_RELBUF;
1096 else
1097 bp->b_flags |= B_RELBUF;
1101 * At this point destroying the buffer is governed by the B_INVAL
1102 * or B_RELBUF flags.
1104 bp->b_cmd = BUF_CMD_DONE;
1107 * VMIO buffer rundown. Make sure the VM page array is restored
1108 * after an I/O may have replaces some of the pages with bogus pages
1109 * in order to not destroy dirty pages in a fill-in read.
1111 * Note that due to the code above, if a buffer is marked B_DELWRI
1112 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1113 * B_INVAL may still be set, however.
1115 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1116 * but not the backing store. B_NOCACHE will destroy the backing
1117 * store.
1119 * Note that dirty NFS buffers contain byte-granular write ranges
1120 * and should not be destroyed w/ B_INVAL even if the backing store
1121 * is left intact.
1123 if (bp->b_flags & B_VMIO) {
1125 * Rundown for VMIO buffers which are not dirty NFS buffers.
1127 int i, j, resid;
1128 vm_page_t m;
1129 off_t foff;
1130 vm_pindex_t poff;
1131 vm_object_t obj;
1132 struct vnode *vp;
1134 vp = bp->b_vp;
1137 * Get the base offset and length of the buffer. Note that
1138 * in the VMIO case if the buffer block size is not
1139 * page-aligned then b_data pointer may not be page-aligned.
1140 * But our b_xio.xio_pages array *IS* page aligned.
1142 * block sizes less then DEV_BSIZE (usually 512) are not
1143 * supported due to the page granularity bits (m->valid,
1144 * m->dirty, etc...).
1146 * See man buf(9) for more information
1149 resid = bp->b_bufsize;
1150 foff = bp->b_loffset;
1152 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1153 m = bp->b_xio.xio_pages[i];
1154 vm_page_flag_clear(m, PG_ZERO);
1156 * If we hit a bogus page, fixup *all* of them
1157 * now. Note that we left these pages wired
1158 * when we removed them so they had better exist,
1159 * and they cannot be ripped out from under us so
1160 * no critical section protection is necessary.
1162 if (m == bogus_page) {
1163 obj = vp->v_object;
1164 poff = OFF_TO_IDX(bp->b_loffset);
1166 for (j = i; j < bp->b_xio.xio_npages; j++) {
1167 vm_page_t mtmp;
1169 mtmp = bp->b_xio.xio_pages[j];
1170 if (mtmp == bogus_page) {
1171 mtmp = vm_page_lookup(obj, poff + j);
1172 if (!mtmp) {
1173 panic("brelse: page missing");
1175 bp->b_xio.xio_pages[j] = mtmp;
1179 if ((bp->b_flags & B_INVAL) == 0) {
1180 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1181 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1183 m = bp->b_xio.xio_pages[i];
1187 * Invalidate the backing store if B_NOCACHE is set
1188 * (e.g. used with vinvalbuf()). If this is NFS
1189 * we impose a requirement that the block size be
1190 * a multiple of PAGE_SIZE and create a temporary
1191 * hack to basically invalidate the whole page. The
1192 * problem is that NFS uses really odd buffer sizes
1193 * especially when tracking piecemeal writes and
1194 * it also vinvalbuf()'s a lot, which would result
1195 * in only partial page validation and invalidation
1196 * here. If the file page is mmap()'d, however,
1197 * all the valid bits get set so after we invalidate
1198 * here we would end up with weird m->valid values
1199 * like 0xfc. nfs_getpages() can't handle this so
1200 * we clear all the valid bits for the NFS case
1201 * instead of just some of them.
1203 * The real bug is the VM system having to set m->valid
1204 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1205 * itself is an artifact of the whole 512-byte
1206 * granular mess that exists to support odd block
1207 * sizes and UFS meta-data block sizes (e.g. 6144).
1208 * A complete rewrite is required.
1210 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1211 int poffset = foff & PAGE_MASK;
1212 int presid;
1214 presid = PAGE_SIZE - poffset;
1215 if (bp->b_vp->v_tag == VT_NFS &&
1216 bp->b_vp->v_type == VREG) {
1217 ; /* entire page */
1218 } else if (presid > resid) {
1219 presid = resid;
1221 KASSERT(presid >= 0, ("brelse: extra page"));
1222 vm_page_set_invalid(m, poffset, presid);
1224 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1225 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1227 if (bp->b_flags & (B_INVAL | B_RELBUF))
1228 vfs_vmio_release(bp);
1229 } else {
1231 * Rundown for non-VMIO buffers.
1233 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1234 #if 0
1235 if (bp->b_vp)
1236 kprintf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1237 #endif
1238 if (bp->b_bufsize)
1239 allocbuf(bp, 0);
1240 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1241 if (bp->b_vp)
1242 brelvp(bp);
1246 if (bp->b_qindex != BQUEUE_NONE)
1247 panic("brelse: free buffer onto another queue???");
1248 if (BUF_REFCNTNB(bp) > 1) {
1249 /* Temporary panic to verify exclusive locking */
1250 /* This panic goes away when we allow shared refs */
1251 panic("brelse: multiple refs");
1252 /* do not release to free list */
1253 BUF_UNLOCK(bp);
1254 crit_exit();
1255 return;
1259 * Figure out the correct queue to place the cleaned up buffer on.
1260 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1261 * disassociated from their vnode.
1263 if (bp->b_flags & B_LOCKED) {
1265 * Buffers that are locked are placed in the locked queue
1266 * immediately, regardless of their state.
1268 bp->b_qindex = BQUEUE_LOCKED;
1269 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1270 } else if (bp->b_bufsize == 0) {
1272 * Buffers with no memory. Due to conditionals near the top
1273 * of brelse() such buffers should probably already be
1274 * marked B_INVAL and disassociated from their vnode.
1276 bp->b_flags |= B_INVAL;
1277 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1278 KKASSERT((bp->b_flags & B_HASHED) == 0);
1279 if (bp->b_kvasize) {
1280 bp->b_qindex = BQUEUE_EMPTYKVA;
1281 } else {
1282 bp->b_qindex = BQUEUE_EMPTY;
1284 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1285 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1287 * Buffers with junk contents. Again these buffers had better
1288 * already be disassociated from their vnode.
1290 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1291 KKASSERT((bp->b_flags & B_HASHED) == 0);
1292 bp->b_flags |= B_INVAL;
1293 bp->b_qindex = BQUEUE_CLEAN;
1294 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1295 } else {
1297 * Remaining buffers. These buffers are still associated with
1298 * their vnode.
1300 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
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:
1306 bp->b_qindex = BQUEUE_DIRTY_HW;
1307 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1308 b_freelist);
1309 break;
1310 default:
1312 * NOTE: Buffers are always placed at the end of the
1313 * queue. If B_AGE is not set the buffer will cycle
1314 * through the queue twice.
1316 bp->b_qindex = BQUEUE_CLEAN;
1317 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1318 break;
1323 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1324 * on the correct queue.
1326 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1327 bundirty(bp);
1330 * Fixup numfreebuffers count. The bp is on an appropriate queue
1331 * unless locked. We then bump numfreebuffers if it is not B_DELWRI.
1332 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1333 * if B_INVAL is set ).
1335 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1336 bufcountwakeup();
1339 * Something we can maybe free or reuse
1341 if (bp->b_bufsize || bp->b_kvasize)
1342 bufspacewakeup();
1345 * Clean up temporary flags and unlock the buffer.
1347 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_RELBUF | B_DIRECT);
1348 BUF_UNLOCK(bp);
1349 crit_exit();
1353 * bqrelse:
1355 * Release a buffer back to the appropriate queue but do not try to free
1356 * it. The buffer is expected to be used again soon.
1358 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1359 * biodone() to requeue an async I/O on completion. It is also used when
1360 * known good buffers need to be requeued but we think we may need the data
1361 * again soon.
1363 * XXX we should be able to leave the B_RELBUF hint set on completion.
1365 void
1366 bqrelse(struct buf *bp)
1368 crit_enter();
1370 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1372 if (bp->b_qindex != BQUEUE_NONE)
1373 panic("bqrelse: free buffer onto another queue???");
1374 if (BUF_REFCNTNB(bp) > 1) {
1375 /* do not release to free list */
1376 panic("bqrelse: multiple refs");
1377 BUF_UNLOCK(bp);
1378 crit_exit();
1379 return;
1381 if (bp->b_flags & B_LOCKED) {
1383 * Locked buffers are released to the locked queue. However,
1384 * if the buffer is dirty it will first go into the dirty
1385 * queue and later on after the I/O completes successfully it
1386 * will be released to the locked queue.
1388 bp->b_flags &= ~B_ERROR;
1389 bp->b_qindex = BQUEUE_LOCKED;
1390 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1391 } else if (bp->b_flags & B_DELWRI) {
1392 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1393 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1394 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1395 } else if (vm_page_count_severe()) {
1397 * We are too low on memory, we have to try to free the
1398 * buffer (most importantly: the wired pages making up its
1399 * backing store) *now*.
1401 crit_exit();
1402 brelse(bp);
1403 return;
1404 } else {
1405 bp->b_qindex = BQUEUE_CLEAN;
1406 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1409 if ((bp->b_flags & B_LOCKED) == 0 &&
1410 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1411 bufcountwakeup();
1415 * Something we can maybe free or reuse.
1417 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1418 bufspacewakeup();
1421 * Final cleanup and unlock. Clear bits that are only used while a
1422 * buffer is actively locked.
1424 bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_RELBUF);
1425 BUF_UNLOCK(bp);
1426 crit_exit();
1430 * vfs_vmio_release:
1432 * Return backing pages held by the buffer 'bp' back to the VM system
1433 * if possible. The pages are freed if they are no longer valid or
1434 * attempt to free if it was used for direct I/O otherwise they are
1435 * sent to the page cache.
1437 * Pages that were marked busy are left alone and skipped.
1439 * The KVA mapping (b_data) for the underlying pages is removed by
1440 * this function.
1442 static void
1443 vfs_vmio_release(struct buf *bp)
1445 int i;
1446 vm_page_t m;
1448 crit_enter();
1449 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1450 m = bp->b_xio.xio_pages[i];
1451 bp->b_xio.xio_pages[i] = NULL;
1453 * In order to keep page LRU ordering consistent, put
1454 * everything on the inactive queue.
1456 vm_page_unwire(m, 0);
1458 * We don't mess with busy pages, it is
1459 * the responsibility of the process that
1460 * busied the pages to deal with them.
1462 if ((m->flags & PG_BUSY) || (m->busy != 0))
1463 continue;
1465 if (m->wire_count == 0) {
1466 vm_page_flag_clear(m, PG_ZERO);
1468 * Might as well free the page if we can and it has
1469 * no valid data. We also free the page if the
1470 * buffer was used for direct I/O.
1472 if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1473 m->hold_count == 0) {
1474 vm_page_busy(m);
1475 vm_page_protect(m, VM_PROT_NONE);
1476 vm_page_free(m);
1477 } else if (bp->b_flags & B_DIRECT) {
1478 vm_page_try_to_free(m);
1479 } else if (vm_page_count_severe()) {
1480 vm_page_try_to_cache(m);
1484 crit_exit();
1485 pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1486 if (bp->b_bufsize) {
1487 bufspacewakeup();
1488 bp->b_bufsize = 0;
1490 bp->b_xio.xio_npages = 0;
1491 bp->b_flags &= ~B_VMIO;
1492 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1493 if (bp->b_vp)
1494 brelvp(bp);
1498 * vfs_bio_awrite:
1500 * Implement clustered async writes for clearing out B_DELWRI buffers.
1501 * This is much better then the old way of writing only one buffer at
1502 * a time. Note that we may not be presented with the buffers in the
1503 * correct order, so we search for the cluster in both directions.
1505 * The buffer is locked on call.
1508 vfs_bio_awrite(struct buf *bp)
1510 int i;
1511 int j;
1512 off_t loffset = bp->b_loffset;
1513 struct vnode *vp = bp->b_vp;
1514 int nbytes;
1515 struct buf *bpa;
1516 int nwritten;
1517 int size;
1519 crit_enter();
1521 * right now we support clustered writing only to regular files. If
1522 * we find a clusterable block we could be in the middle of a cluster
1523 * rather then at the beginning.
1525 * NOTE: b_bio1 contains the logical loffset and is aliased
1526 * to b_loffset. b_bio2 contains the translated block number.
1528 if ((vp->v_type == VREG) &&
1529 (vp->v_mount != 0) && /* Only on nodes that have the size info */
1530 (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1532 size = vp->v_mount->mnt_stat.f_iosize;
1534 for (i = size; i < MAXPHYS; i += size) {
1535 if ((bpa = findblk(vp, loffset + i)) &&
1536 BUF_REFCNT(bpa) == 0 &&
1537 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1538 (B_DELWRI | B_CLUSTEROK)) &&
1539 (bpa->b_bufsize == size)) {
1540 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1541 (bpa->b_bio2.bio_offset !=
1542 bp->b_bio2.bio_offset + i))
1543 break;
1544 } else {
1545 break;
1548 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1549 if ((bpa = findblk(vp, loffset - j)) &&
1550 BUF_REFCNT(bpa) == 0 &&
1551 ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1552 (B_DELWRI | B_CLUSTEROK)) &&
1553 (bpa->b_bufsize == size)) {
1554 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1555 (bpa->b_bio2.bio_offset !=
1556 bp->b_bio2.bio_offset - j))
1557 break;
1558 } else {
1559 break;
1562 j -= size;
1563 nbytes = (i + j);
1565 * this is a possible cluster write
1567 if (nbytes != size) {
1568 BUF_UNLOCK(bp);
1569 nwritten = cluster_wbuild(vp, size,
1570 loffset - j, nbytes);
1571 crit_exit();
1572 return nwritten;
1576 bremfree(bp);
1577 bp->b_flags |= B_ASYNC;
1579 crit_exit();
1581 * default (old) behavior, writing out only one block
1583 * XXX returns b_bufsize instead of b_bcount for nwritten?
1585 nwritten = bp->b_bufsize;
1586 bwrite(bp);
1588 return nwritten;
1592 * getnewbuf:
1594 * Find and initialize a new buffer header, freeing up existing buffers
1595 * in the bufqueues as necessary. The new buffer is returned locked.
1597 * Important: B_INVAL is not set. If the caller wishes to throw the
1598 * buffer away, the caller must set B_INVAL prior to calling brelse().
1600 * We block if:
1601 * We have insufficient buffer headers
1602 * We have insufficient buffer space
1603 * buffer_map is too fragmented ( space reservation fails )
1604 * If we have to flush dirty buffers ( but we try to avoid this )
1606 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1607 * Instead we ask the buf daemon to do it for us. We attempt to
1608 * avoid piecemeal wakeups of the pageout daemon.
1611 static struct buf *
1612 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1614 struct buf *bp;
1615 struct buf *nbp;
1616 int defrag = 0;
1617 int nqindex;
1618 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1619 static int flushingbufs;
1622 * We can't afford to block since we might be holding a vnode lock,
1623 * which may prevent system daemons from running. We deal with
1624 * low-memory situations by proactively returning memory and running
1625 * async I/O rather then sync I/O.
1628 ++getnewbufcalls;
1629 --getnewbufrestarts;
1630 restart:
1631 ++getnewbufrestarts;
1634 * Setup for scan. If we do not have enough free buffers,
1635 * we setup a degenerate case that immediately fails. Note
1636 * that if we are specially marked process, we are allowed to
1637 * dip into our reserves.
1639 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1641 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1642 * However, there are a number of cases (defragging, reusing, ...)
1643 * where we cannot backup.
1645 nqindex = BQUEUE_EMPTYKVA;
1646 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1648 if (nbp == NULL) {
1650 * If no EMPTYKVA buffers and we are either
1651 * defragging or reusing, locate a CLEAN buffer
1652 * to free or reuse. If bufspace useage is low
1653 * skip this step so we can allocate a new buffer.
1655 if (defrag || bufspace >= lobufspace) {
1656 nqindex = BQUEUE_CLEAN;
1657 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1661 * If we could not find or were not allowed to reuse a
1662 * CLEAN buffer, check to see if it is ok to use an EMPTY
1663 * buffer. We can only use an EMPTY buffer if allocating
1664 * its KVA would not otherwise run us out of buffer space.
1666 if (nbp == NULL && defrag == 0 &&
1667 bufspace + maxsize < hibufspace) {
1668 nqindex = BQUEUE_EMPTY;
1669 nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1674 * Run scan, possibly freeing data and/or kva mappings on the fly
1675 * depending.
1678 while ((bp = nbp) != NULL) {
1679 int qindex = nqindex;
1681 nbp = TAILQ_NEXT(bp, b_freelist);
1684 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
1685 * cycles through the queue twice before being selected.
1687 if (qindex == BQUEUE_CLEAN &&
1688 (bp->b_flags & B_AGE) == 0 && nbp) {
1689 bp->b_flags |= B_AGE;
1690 TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
1691 TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
1692 continue;
1696 * Calculate next bp ( we can only use it if we do not block
1697 * or do other fancy things ).
1699 if (nbp == NULL) {
1700 switch(qindex) {
1701 case BQUEUE_EMPTY:
1702 nqindex = BQUEUE_EMPTYKVA;
1703 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1704 break;
1705 /* fall through */
1706 case BQUEUE_EMPTYKVA:
1707 nqindex = BQUEUE_CLEAN;
1708 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1709 break;
1710 /* fall through */
1711 case BQUEUE_CLEAN:
1713 * nbp is NULL.
1715 break;
1720 * Sanity Checks
1722 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1725 * Note: we no longer distinguish between VMIO and non-VMIO
1726 * buffers.
1729 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1732 * If we are defragging then we need a buffer with
1733 * b_kvasize != 0. XXX this situation should no longer
1734 * occur, if defrag is non-zero the buffer's b_kvasize
1735 * should also be non-zero at this point. XXX
1737 if (defrag && bp->b_kvasize == 0) {
1738 kprintf("Warning: defrag empty buffer %p\n", bp);
1739 continue;
1743 * Start freeing the bp. This is somewhat involved. nbp
1744 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
1745 * on the clean list must be disassociated from their
1746 * current vnode. Buffers on the empty[kva] lists have
1747 * already been disassociated.
1750 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1751 kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1752 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1753 goto restart;
1755 if (bp->b_qindex != qindex) {
1756 kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1757 BUF_UNLOCK(bp);
1758 goto restart;
1760 bremfree(bp);
1763 * Dependancies must be handled before we disassociate the
1764 * vnode.
1766 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1767 * be immediately disassociated. HAMMER then becomes
1768 * responsible for releasing the buffer.
1770 if (LIST_FIRST(&bp->b_dep) != NULL) {
1771 buf_deallocate(bp);
1772 if (bp->b_flags & B_LOCKED) {
1773 bqrelse(bp);
1774 goto restart;
1776 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1779 if (qindex == BQUEUE_CLEAN) {
1780 if (bp->b_flags & B_VMIO) {
1781 bp->b_flags &= ~B_ASYNC;
1782 vfs_vmio_release(bp);
1784 if (bp->b_vp)
1785 brelvp(bp);
1789 * NOTE: nbp is now entirely invalid. We can only restart
1790 * the scan from this point on.
1792 * Get the rest of the buffer freed up. b_kva* is still
1793 * valid after this operation.
1796 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1797 KKASSERT((bp->b_flags & B_HASHED) == 0);
1800 * critical section protection is not required when
1801 * scrapping a buffer's contents because it is already
1802 * wired.
1804 if (bp->b_bufsize)
1805 allocbuf(bp, 0);
1807 bp->b_flags = B_BNOCLIP;
1808 bp->b_cmd = BUF_CMD_DONE;
1809 bp->b_vp = NULL;
1810 bp->b_error = 0;
1811 bp->b_resid = 0;
1812 bp->b_bcount = 0;
1813 bp->b_xio.xio_npages = 0;
1814 bp->b_dirtyoff = bp->b_dirtyend = 0;
1815 reinitbufbio(bp);
1816 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1817 buf_dep_init(bp);
1818 if (blkflags & GETBLK_BHEAVY)
1819 bp->b_flags |= B_HEAVY;
1822 * If we are defragging then free the buffer.
1824 if (defrag) {
1825 bp->b_flags |= B_INVAL;
1826 bfreekva(bp);
1827 brelse(bp);
1828 defrag = 0;
1829 goto restart;
1833 * If we are overcomitted then recover the buffer and its
1834 * KVM space. This occurs in rare situations when multiple
1835 * processes are blocked in getnewbuf() or allocbuf().
1837 if (bufspace >= hibufspace)
1838 flushingbufs = 1;
1839 if (flushingbufs && bp->b_kvasize != 0) {
1840 bp->b_flags |= B_INVAL;
1841 bfreekva(bp);
1842 brelse(bp);
1843 goto restart;
1845 if (bufspace < lobufspace)
1846 flushingbufs = 0;
1847 break;
1851 * If we exhausted our list, sleep as appropriate. We may have to
1852 * wakeup various daemons and write out some dirty buffers.
1854 * Generally we are sleeping due to insufficient buffer space.
1857 if (bp == NULL) {
1858 int flags;
1859 char *waitmsg;
1861 if (defrag) {
1862 flags = VFS_BIO_NEED_BUFSPACE;
1863 waitmsg = "nbufkv";
1864 } else if (bufspace >= hibufspace) {
1865 waitmsg = "nbufbs";
1866 flags = VFS_BIO_NEED_BUFSPACE;
1867 } else {
1868 waitmsg = "newbuf";
1869 flags = VFS_BIO_NEED_ANY;
1872 needsbuffer |= flags;
1873 bd_speedup(); /* heeeelp */
1874 while (needsbuffer & flags) {
1875 if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
1876 return (NULL);
1878 } else {
1880 * We finally have a valid bp. We aren't quite out of the
1881 * woods, we still have to reserve kva space. In order
1882 * to keep fragmentation sane we only allocate kva in
1883 * BKVASIZE chunks.
1885 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1887 if (maxsize != bp->b_kvasize) {
1888 vm_offset_t addr = 0;
1889 int count;
1891 bfreekva(bp);
1893 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1894 vm_map_lock(&buffer_map);
1896 if (vm_map_findspace(&buffer_map,
1897 vm_map_min(&buffer_map), maxsize,
1898 maxsize, &addr)) {
1900 * Uh oh. Buffer map is too fragmented. We
1901 * must defragment the map.
1903 vm_map_unlock(&buffer_map);
1904 vm_map_entry_release(count);
1905 ++bufdefragcnt;
1906 defrag = 1;
1907 bp->b_flags |= B_INVAL;
1908 brelse(bp);
1909 goto restart;
1911 if (addr) {
1912 vm_map_insert(&buffer_map, &count,
1913 NULL, 0,
1914 addr, addr + maxsize,
1915 VM_MAPTYPE_NORMAL,
1916 VM_PROT_ALL, VM_PROT_ALL,
1917 MAP_NOFAULT);
1919 bp->b_kvabase = (caddr_t) addr;
1920 bp->b_kvasize = maxsize;
1921 bufspace += bp->b_kvasize;
1922 ++bufreusecnt;
1924 vm_map_unlock(&buffer_map);
1925 vm_map_entry_release(count);
1927 bp->b_data = bp->b_kvabase;
1929 return(bp);
1933 * buf_daemon:
1935 * Buffer flushing daemon. Buffers are normally flushed by the
1936 * update daemon but if it cannot keep up this process starts to
1937 * take the load in an attempt to prevent getnewbuf() from blocking.
1939 * Once a flush is initiated it does not stop until the number
1940 * of buffers falls below lodirtybuffers, but we will wake up anyone
1941 * waiting at the mid-point.
1944 static struct thread *bufdaemon_td;
1945 static struct thread *bufdaemonhw_td;
1947 static struct kproc_desc buf_kp = {
1948 "bufdaemon",
1949 buf_daemon,
1950 &bufdaemon_td
1952 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
1953 kproc_start, &buf_kp)
1955 static struct kproc_desc bufhw_kp = {
1956 "bufdaemon_hw",
1957 buf_daemon_hw,
1958 &bufdaemonhw_td
1960 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
1961 kproc_start, &bufhw_kp)
1963 static void
1964 buf_daemon(void)
1967 * This process needs to be suspended prior to shutdown sync.
1969 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
1970 bufdaemon_td, SHUTDOWN_PRI_LAST);
1973 * This process is allowed to take the buffer cache to the limit
1975 crit_enter();
1977 for (;;) {
1978 kproc_suspend_loop();
1981 * Do the flush. Limit the amount of in-transit I/O we
1982 * allow to build up, otherwise we would completely saturate
1983 * the I/O system. Wakeup any waiting processes before we
1984 * normally would so they can run in parallel with our drain.
1986 while (numdirtybuffers > lodirtybuffers) {
1987 if (flushbufqueues(BQUEUE_DIRTY) == 0)
1988 break;
1989 waitrunningbufspace();
1991 if (runningbufcount + numdirtybuffers > lodirtybuffers) {
1992 waitrunningbufspace();
1996 * Only clear bd_request if we have reached our low water
1997 * mark. The buf_daemon normally waits 5 seconds and
1998 * then incrementally flushes any dirty buffers that have
1999 * built up, within reason.
2001 * If we were unable to hit our low water mark and couldn't
2002 * find any flushable buffers, we sleep half a second.
2003 * Otherwise we loop immediately.
2005 if (runningbufcount + numdirtybuffers <= lodirtybuffers) {
2007 * We reached our low water mark, reset the
2008 * request and sleep until we are needed again.
2009 * The sleep is just so the suspend code works.
2011 spin_lock_wr(&needsbuffer_spin);
2012 bd_request = 0;
2013 msleep(&bd_request, &needsbuffer_spin, 0,
2014 "psleep", hz);
2015 spin_unlock_wr(&needsbuffer_spin);
2016 } else {
2018 * We couldn't find any flushable dirty buffers but
2019 * still have too many dirty buffers, we
2020 * have to sleep and try again. (rare)
2022 tsleep(&bd_request, 0, "qsleep", hz / 2);
2027 static void
2028 buf_daemon_hw(void)
2031 * This process needs to be suspended prior to shutdown sync.
2033 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2034 bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2037 * This process is allowed to take the buffer cache to the limit
2039 crit_enter();
2041 for (;;) {
2042 kproc_suspend_loop();
2045 * Do the flush. Limit the amount of in-transit I/O we
2046 * allow to build up, otherwise we would completely saturate
2047 * the I/O system. Wakeup any waiting processes before we
2048 * normally would so they can run in parallel with our drain.
2050 while (numdirtybuffershw > lodirtybuffers) {
2051 if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2052 break;
2053 waitrunningbufspace();
2055 if (runningbufcount + numdirtybuffershw > lodirtybuffers) {
2056 waitrunningbufspace();
2060 * Only clear bd_request if we have reached our low water
2061 * mark. The buf_daemon normally waits 5 seconds and
2062 * then incrementally flushes any dirty buffers that have
2063 * built up, within reason.
2065 * If we were unable to hit our low water mark and couldn't
2066 * find any flushable buffers, we sleep half a second.
2067 * Otherwise we loop immediately.
2069 if (runningbufcount + numdirtybuffershw <= lodirtybuffers) {
2071 * We reached our low water mark, reset the
2072 * request and sleep until we are needed again.
2073 * The sleep is just so the suspend code works.
2075 spin_lock_wr(&needsbuffer_spin);
2076 bd_request_hw = 0;
2077 msleep(&bd_request_hw, &needsbuffer_spin, 0,
2078 "psleep", hz);
2079 spin_unlock_wr(&needsbuffer_spin);
2080 } else {
2082 * We couldn't find any flushable dirty buffers but
2083 * still have too many dirty buffers, we
2084 * have to sleep and try again. (rare)
2086 tsleep(&bd_request_hw, 0, "qsleep", hz / 2);
2092 * flushbufqueues:
2094 * Try to flush a buffer in the dirty queue. We must be careful to
2095 * free up B_INVAL buffers instead of write them, which NFS is
2096 * particularly sensitive to.
2098 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate
2099 * that we really want to try to get the buffer out and reuse it
2100 * due to the write load on the machine.
2103 static int
2104 flushbufqueues(bufq_type_t q)
2106 struct buf *bp;
2107 int r = 0;
2109 bp = TAILQ_FIRST(&bufqueues[q]);
2111 while (bp) {
2112 KASSERT((bp->b_flags & B_DELWRI),
2113 ("unexpected clean buffer %p", bp));
2115 if (bp->b_flags & B_DELWRI) {
2116 if (bp->b_flags & B_INVAL) {
2117 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2118 panic("flushbufqueues: locked buf");
2119 bremfree(bp);
2120 brelse(bp);
2121 ++r;
2122 break;
2124 if (LIST_FIRST(&bp->b_dep) != NULL &&
2125 (bp->b_flags & B_DEFERRED) == 0 &&
2126 buf_countdeps(bp, 0)) {
2127 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2128 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2129 b_freelist);
2130 bp->b_flags |= B_DEFERRED;
2131 bp = TAILQ_FIRST(&bufqueues[q]);
2132 continue;
2136 * Only write it out if we can successfully lock
2137 * it. If the buffer has a dependancy,
2138 * buf_checkwrite must also return 0.
2140 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2141 if (LIST_FIRST(&bp->b_dep) != NULL &&
2142 buf_checkwrite(bp)) {
2143 bremfree(bp);
2144 brelse(bp);
2145 } else {
2146 bp->b_flags |= B_AGE;
2147 vfs_bio_awrite(bp);
2149 ++r;
2150 break;
2153 bp = TAILQ_NEXT(bp, b_freelist);
2155 return (r);
2159 * inmem:
2161 * Returns true if no I/O is needed to access the associated VM object.
2162 * This is like findblk except it also hunts around in the VM system for
2163 * the data.
2165 * Note that we ignore vm_page_free() races from interrupts against our
2166 * lookup, since if the caller is not protected our return value will not
2167 * be any more valid then otherwise once we exit the critical section.
2170 inmem(struct vnode *vp, off_t loffset)
2172 vm_object_t obj;
2173 vm_offset_t toff, tinc, size;
2174 vm_page_t m;
2176 if (findblk(vp, loffset))
2177 return 1;
2178 if (vp->v_mount == NULL)
2179 return 0;
2180 if ((obj = vp->v_object) == NULL)
2181 return 0;
2183 size = PAGE_SIZE;
2184 if (size > vp->v_mount->mnt_stat.f_iosize)
2185 size = vp->v_mount->mnt_stat.f_iosize;
2187 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2188 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2189 if (m == NULL)
2190 return 0;
2191 tinc = size;
2192 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2193 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2194 if (vm_page_is_valid(m,
2195 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2196 return 0;
2198 return 1;
2202 * vfs_setdirty:
2204 * Sets the dirty range for a buffer based on the status of the dirty
2205 * bits in the pages comprising the buffer.
2207 * The range is limited to the size of the buffer.
2209 * This routine is primarily used by NFS, but is generalized for the
2210 * B_VMIO case.
2212 static void
2213 vfs_setdirty(struct buf *bp)
2215 int i;
2216 vm_object_t object;
2219 * Degenerate case - empty buffer
2222 if (bp->b_bufsize == 0)
2223 return;
2226 * We qualify the scan for modified pages on whether the
2227 * object has been flushed yet. The OBJ_WRITEABLE flag
2228 * is not cleared simply by protecting pages off.
2231 if ((bp->b_flags & B_VMIO) == 0)
2232 return;
2234 object = bp->b_xio.xio_pages[0]->object;
2236 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2237 kprintf("Warning: object %p writeable but not mightbedirty\n", object);
2238 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2239 kprintf("Warning: object %p mightbedirty but not writeable\n", object);
2241 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2242 vm_offset_t boffset;
2243 vm_offset_t eoffset;
2246 * test the pages to see if they have been modified directly
2247 * by users through the VM system.
2249 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2250 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2251 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2255 * Calculate the encompassing dirty range, boffset and eoffset,
2256 * (eoffset - boffset) bytes.
2259 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2260 if (bp->b_xio.xio_pages[i]->dirty)
2261 break;
2263 boffset = (i << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2265 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2266 if (bp->b_xio.xio_pages[i]->dirty) {
2267 break;
2270 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2273 * Fit it to the buffer.
2276 if (eoffset > bp->b_bcount)
2277 eoffset = bp->b_bcount;
2280 * If we have a good dirty range, merge with the existing
2281 * dirty range.
2284 if (boffset < eoffset) {
2285 if (bp->b_dirtyoff > boffset)
2286 bp->b_dirtyoff = boffset;
2287 if (bp->b_dirtyend < eoffset)
2288 bp->b_dirtyend = eoffset;
2294 * findblk:
2296 * Locate and return the specified buffer, or NULL if the buffer does
2297 * not exist. Do not attempt to lock the buffer or manipulate it in
2298 * any way. The caller must validate that the correct buffer has been
2299 * obtain after locking it.
2301 struct buf *
2302 findblk(struct vnode *vp, off_t loffset)
2304 struct buf *bp;
2306 crit_enter();
2307 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2308 crit_exit();
2309 return(bp);
2313 * getblk:
2315 * Get a block given a specified block and offset into a file/device.
2316 * B_INVAL may or may not be set on return. The caller should clear
2317 * B_INVAL prior to initiating a READ.
2319 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2320 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2321 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2322 * without doing any of those things the system will likely believe
2323 * the buffer to be valid (especially if it is not B_VMIO), and the
2324 * next getblk() will return the buffer with B_CACHE set.
2326 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2327 * an existing buffer.
2329 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2330 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2331 * and then cleared based on the backing VM. If the previous buffer is
2332 * non-0-sized but invalid, B_CACHE will be cleared.
2334 * If getblk() must create a new buffer, the new buffer is returned with
2335 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2336 * case it is returned with B_INVAL clear and B_CACHE set based on the
2337 * backing VM.
2339 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2340 * B_CACHE bit is clear.
2342 * What this means, basically, is that the caller should use B_CACHE to
2343 * determine whether the buffer is fully valid or not and should clear
2344 * B_INVAL prior to issuing a read. If the caller intends to validate
2345 * the buffer by loading its data area with something, the caller needs
2346 * to clear B_INVAL. If the caller does this without issuing an I/O,
2347 * the caller should set B_CACHE ( as an optimization ), else the caller
2348 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2349 * a write attempt or if it was a successfull read. If the caller
2350 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2351 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2353 * getblk flags:
2355 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2356 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2358 struct buf *
2359 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2361 struct buf *bp;
2362 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2363 int error;
2365 if (size > MAXBSIZE)
2366 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2367 if (vp->v_object == NULL)
2368 panic("getblk: vnode %p has no object!", vp);
2370 crit_enter();
2371 loop:
2372 if ((bp = findblk(vp, loffset))) {
2374 * The buffer was found in the cache, but we need to lock it.
2375 * Even with LK_NOWAIT the lockmgr may break our critical
2376 * section, so double-check the validity of the buffer
2377 * once the lock has been obtained.
2379 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2380 int lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2381 if (blkflags & GETBLK_PCATCH)
2382 lkflags |= LK_PCATCH;
2383 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2384 if (error) {
2385 if (error == ENOLCK)
2386 goto loop;
2387 crit_exit();
2388 return (NULL);
2393 * Once the buffer has been locked, make sure we didn't race
2394 * a buffer recyclement. Buffers that are no longer hashed
2395 * will have b_vp == NULL, so this takes care of that check
2396 * as well.
2398 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2399 kprintf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp, vp, loffset);
2400 BUF_UNLOCK(bp);
2401 goto loop;
2405 * All vnode-based buffers must be backed by a VM object.
2407 KKASSERT(bp->b_flags & B_VMIO);
2408 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2409 bp->b_flags &= ~B_AGE;
2412 * Make sure that B_INVAL buffers do not have a cached
2413 * block number translation.
2415 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2416 kprintf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp, vp, loffset);
2417 clearbiocache(&bp->b_bio2);
2421 * The buffer is locked. B_CACHE is cleared if the buffer is
2422 * invalid.
2424 if (bp->b_flags & B_INVAL)
2425 bp->b_flags &= ~B_CACHE;
2426 bremfree(bp);
2429 * Any size inconsistancy with a dirty buffer or a buffer
2430 * with a softupdates dependancy must be resolved. Resizing
2431 * the buffer in such circumstances can lead to problems.
2433 if (size != bp->b_bcount) {
2434 if (bp->b_flags & B_DELWRI) {
2435 bp->b_flags |= B_NOCACHE;
2436 bwrite(bp);
2437 } else if (LIST_FIRST(&bp->b_dep)) {
2438 bp->b_flags |= B_NOCACHE;
2439 bwrite(bp);
2440 } else {
2441 bp->b_flags |= B_RELBUF;
2442 brelse(bp);
2444 goto loop;
2446 KKASSERT(size <= bp->b_kvasize);
2447 KASSERT(bp->b_loffset != NOOFFSET,
2448 ("getblk: no buffer offset"));
2451 * A buffer with B_DELWRI set and B_CACHE clear must
2452 * be committed before we can return the buffer in
2453 * order to prevent the caller from issuing a read
2454 * ( due to B_CACHE not being set ) and overwriting
2455 * it.
2457 * Most callers, including NFS and FFS, need this to
2458 * operate properly either because they assume they
2459 * can issue a read if B_CACHE is not set, or because
2460 * ( for example ) an uncached B_DELWRI might loop due
2461 * to softupdates re-dirtying the buffer. In the latter
2462 * case, B_CACHE is set after the first write completes,
2463 * preventing further loops.
2465 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2466 * above while extending the buffer, we cannot allow the
2467 * buffer to remain with B_CACHE set after the write
2468 * completes or it will represent a corrupt state. To
2469 * deal with this we set B_NOCACHE to scrap the buffer
2470 * after the write.
2472 * We might be able to do something fancy, like setting
2473 * B_CACHE in bwrite() except if B_DELWRI is already set,
2474 * so the below call doesn't set B_CACHE, but that gets real
2475 * confusing. This is much easier.
2478 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2479 bp->b_flags |= B_NOCACHE;
2480 bwrite(bp);
2481 goto loop;
2483 crit_exit();
2484 } else {
2486 * Buffer is not in-core, create new buffer. The buffer
2487 * returned by getnewbuf() is locked. Note that the returned
2488 * buffer is also considered valid (not marked B_INVAL).
2490 * Calculating the offset for the I/O requires figuring out
2491 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2492 * the mount's f_iosize otherwise. If the vnode does not
2493 * have an associated mount we assume that the passed size is
2494 * the block size.
2496 * Note that vn_isdisk() cannot be used here since it may
2497 * return a failure for numerous reasons. Note that the
2498 * buffer size may be larger then the block size (the caller
2499 * will use block numbers with the proper multiple). Beware
2500 * of using any v_* fields which are part of unions. In
2501 * particular, in DragonFly the mount point overloading
2502 * mechanism uses the namecache only and the underlying
2503 * directory vnode is not a special case.
2505 int bsize, maxsize;
2507 if (vp->v_type == VBLK || vp->v_type == VCHR)
2508 bsize = DEV_BSIZE;
2509 else if (vp->v_mount)
2510 bsize = vp->v_mount->mnt_stat.f_iosize;
2511 else
2512 bsize = size;
2514 maxsize = size + (loffset & PAGE_MASK);
2515 maxsize = imax(maxsize, bsize);
2517 if ((bp = getnewbuf(blkflags, slptimeo, size, maxsize)) == NULL) {
2518 if (slpflags || slptimeo) {
2519 crit_exit();
2520 return NULL;
2522 goto loop;
2526 * This code is used to make sure that a buffer is not
2527 * created while the getnewbuf routine is blocked.
2528 * This can be a problem whether the vnode is locked or not.
2529 * If the buffer is created out from under us, we have to
2530 * throw away the one we just created. There is no window
2531 * race because we are safely running in a critical section
2532 * from the point of the duplicate buffer creation through
2533 * to here, and we've locked the buffer.
2535 if (findblk(vp, loffset)) {
2536 bp->b_flags |= B_INVAL;
2537 brelse(bp);
2538 goto loop;
2542 * Insert the buffer into the hash, so that it can
2543 * be found by findblk().
2545 * Make sure the translation layer has been cleared.
2547 bp->b_loffset = loffset;
2548 bp->b_bio2.bio_offset = NOOFFSET;
2549 /* bp->b_bio2.bio_next = NULL; */
2551 bgetvp(vp, bp);
2554 * All vnode-based buffers must be backed by a VM object.
2556 KKASSERT(vp->v_object != NULL);
2557 bp->b_flags |= B_VMIO;
2558 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2560 allocbuf(bp, size);
2562 crit_exit();
2564 return (bp);
2568 * regetblk(bp)
2570 * Reacquire a buffer that was previously released to the locked queue,
2571 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2572 * set B_LOCKED (which handles the acquisition race).
2574 * To this end, either B_LOCKED must be set or the dependancy list must be
2575 * non-empty.
2577 void
2578 regetblk(struct buf *bp)
2580 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2581 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2582 crit_enter();
2583 bremfree(bp);
2584 crit_exit();
2588 * geteblk:
2590 * Get an empty, disassociated buffer of given size. The buffer is
2591 * initially set to B_INVAL.
2593 * critical section protection is not required for the allocbuf()
2594 * call because races are impossible here.
2596 struct buf *
2597 geteblk(int size)
2599 struct buf *bp;
2600 int maxsize;
2602 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2604 crit_enter();
2605 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2607 crit_exit();
2608 allocbuf(bp, size);
2609 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2610 return (bp);
2615 * allocbuf:
2617 * This code constitutes the buffer memory from either anonymous system
2618 * memory (in the case of non-VMIO operations) or from an associated
2619 * VM object (in the case of VMIO operations). This code is able to
2620 * resize a buffer up or down.
2622 * Note that this code is tricky, and has many complications to resolve
2623 * deadlock or inconsistant data situations. Tread lightly!!!
2624 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2625 * the caller. Calling this code willy nilly can result in the loss of data.
2627 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2628 * B_CACHE for the non-VMIO case.
2630 * This routine does not need to be called from a critical section but you
2631 * must own the buffer.
2634 allocbuf(struct buf *bp, int size)
2636 int newbsize, mbsize;
2637 int i;
2639 if (BUF_REFCNT(bp) == 0)
2640 panic("allocbuf: buffer not busy");
2642 if (bp->b_kvasize < size)
2643 panic("allocbuf: buffer too small");
2645 if ((bp->b_flags & B_VMIO) == 0) {
2646 caddr_t origbuf;
2647 int origbufsize;
2649 * Just get anonymous memory from the kernel. Don't
2650 * mess with B_CACHE.
2652 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2653 if (bp->b_flags & B_MALLOC)
2654 newbsize = mbsize;
2655 else
2656 newbsize = round_page(size);
2658 if (newbsize < bp->b_bufsize) {
2660 * Malloced buffers are not shrunk
2662 if (bp->b_flags & B_MALLOC) {
2663 if (newbsize) {
2664 bp->b_bcount = size;
2665 } else {
2666 kfree(bp->b_data, M_BIOBUF);
2667 if (bp->b_bufsize) {
2668 bufmallocspace -= bp->b_bufsize;
2669 bufspacewakeup();
2670 bp->b_bufsize = 0;
2672 bp->b_data = bp->b_kvabase;
2673 bp->b_bcount = 0;
2674 bp->b_flags &= ~B_MALLOC;
2676 return 1;
2678 vm_hold_free_pages(
2680 (vm_offset_t) bp->b_data + newbsize,
2681 (vm_offset_t) bp->b_data + bp->b_bufsize);
2682 } else if (newbsize > bp->b_bufsize) {
2684 * We only use malloced memory on the first allocation.
2685 * and revert to page-allocated memory when the buffer
2686 * grows.
2688 if ((bufmallocspace < maxbufmallocspace) &&
2689 (bp->b_bufsize == 0) &&
2690 (mbsize <= PAGE_SIZE/2)) {
2692 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
2693 bp->b_bufsize = mbsize;
2694 bp->b_bcount = size;
2695 bp->b_flags |= B_MALLOC;
2696 bufmallocspace += mbsize;
2697 return 1;
2699 origbuf = NULL;
2700 origbufsize = 0;
2702 * If the buffer is growing on its other-than-first
2703 * allocation, then we revert to the page-allocation
2704 * scheme.
2706 if (bp->b_flags & B_MALLOC) {
2707 origbuf = bp->b_data;
2708 origbufsize = bp->b_bufsize;
2709 bp->b_data = bp->b_kvabase;
2710 if (bp->b_bufsize) {
2711 bufmallocspace -= bp->b_bufsize;
2712 bufspacewakeup();
2713 bp->b_bufsize = 0;
2715 bp->b_flags &= ~B_MALLOC;
2716 newbsize = round_page(newbsize);
2718 vm_hold_load_pages(
2720 (vm_offset_t) bp->b_data + bp->b_bufsize,
2721 (vm_offset_t) bp->b_data + newbsize);
2722 if (origbuf) {
2723 bcopy(origbuf, bp->b_data, origbufsize);
2724 kfree(origbuf, M_BIOBUF);
2727 } else {
2728 vm_page_t m;
2729 int desiredpages;
2731 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2732 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
2733 newbsize + PAGE_MASK) >> PAGE_SHIFT;
2734 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
2736 if (bp->b_flags & B_MALLOC)
2737 panic("allocbuf: VMIO buffer can't be malloced");
2739 * Set B_CACHE initially if buffer is 0 length or will become
2740 * 0-length.
2742 if (size == 0 || bp->b_bufsize == 0)
2743 bp->b_flags |= B_CACHE;
2745 if (newbsize < bp->b_bufsize) {
2747 * DEV_BSIZE aligned new buffer size is less then the
2748 * DEV_BSIZE aligned existing buffer size. Figure out
2749 * if we have to remove any pages.
2751 if (desiredpages < bp->b_xio.xio_npages) {
2752 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2754 * the page is not freed here -- it
2755 * is the responsibility of
2756 * vnode_pager_setsize
2758 m = bp->b_xio.xio_pages[i];
2759 KASSERT(m != bogus_page,
2760 ("allocbuf: bogus page found"));
2761 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2764 bp->b_xio.xio_pages[i] = NULL;
2765 vm_page_unwire(m, 0);
2767 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2768 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2769 bp->b_xio.xio_npages = desiredpages;
2771 } else if (size > bp->b_bcount) {
2773 * We are growing the buffer, possibly in a
2774 * byte-granular fashion.
2776 struct vnode *vp;
2777 vm_object_t obj;
2778 vm_offset_t toff;
2779 vm_offset_t tinc;
2782 * Step 1, bring in the VM pages from the object,
2783 * allocating them if necessary. We must clear
2784 * B_CACHE if these pages are not valid for the
2785 * range covered by the buffer.
2787 * critical section protection is required to protect
2788 * against interrupts unbusying and freeing pages
2789 * between our vm_page_lookup() and our
2790 * busycheck/wiring call.
2792 vp = bp->b_vp;
2793 obj = vp->v_object;
2795 crit_enter();
2796 while (bp->b_xio.xio_npages < desiredpages) {
2797 vm_page_t m;
2798 vm_pindex_t pi;
2800 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
2801 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2803 * note: must allocate system pages
2804 * since blocking here could intefere
2805 * with paging I/O, no matter which
2806 * process we are.
2808 m = vm_page_alloc(obj, pi, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
2809 if (m == NULL) {
2810 vm_wait();
2811 vm_pageout_deficit += desiredpages -
2812 bp->b_xio.xio_npages;
2813 } else {
2814 vm_page_wire(m);
2815 vm_page_wakeup(m);
2816 bp->b_flags &= ~B_CACHE;
2817 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2818 ++bp->b_xio.xio_npages;
2820 continue;
2824 * We found a page. If we have to sleep on it,
2825 * retry because it might have gotten freed out
2826 * from under us.
2828 * We can only test PG_BUSY here. Blocking on
2829 * m->busy might lead to a deadlock:
2831 * vm_fault->getpages->cluster_read->allocbuf
2835 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2836 continue;
2839 * We have a good page. Should we wakeup the
2840 * page daemon?
2842 if ((curthread != pagethread) &&
2843 ((m->queue - m->pc) == PQ_CACHE) &&
2844 ((vmstats.v_free_count + vmstats.v_cache_count) <
2845 (vmstats.v_free_min + vmstats.v_cache_min))) {
2846 pagedaemon_wakeup();
2848 vm_page_flag_clear(m, PG_ZERO);
2849 vm_page_wire(m);
2850 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2851 ++bp->b_xio.xio_npages;
2853 crit_exit();
2856 * Step 2. We've loaded the pages into the buffer,
2857 * we have to figure out if we can still have B_CACHE
2858 * set. Note that B_CACHE is set according to the
2859 * byte-granular range ( bcount and size ), not the
2860 * aligned range ( newbsize ).
2862 * The VM test is against m->valid, which is DEV_BSIZE
2863 * aligned. Needless to say, the validity of the data
2864 * needs to also be DEV_BSIZE aligned. Note that this
2865 * fails with NFS if the server or some other client
2866 * extends the file's EOF. If our buffer is resized,
2867 * B_CACHE may remain set! XXX
2870 toff = bp->b_bcount;
2871 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
2873 while ((bp->b_flags & B_CACHE) && toff < size) {
2874 vm_pindex_t pi;
2876 if (tinc > (size - toff))
2877 tinc = size - toff;
2879 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
2880 PAGE_SHIFT;
2882 vfs_buf_test_cache(
2883 bp,
2884 bp->b_loffset,
2885 toff,
2886 tinc,
2887 bp->b_xio.xio_pages[pi]
2889 toff += tinc;
2890 tinc = PAGE_SIZE;
2894 * Step 3, fixup the KVM pmap. Remember that
2895 * bp->b_data is relative to bp->b_loffset, but
2896 * bp->b_loffset may be offset into the first page.
2899 bp->b_data = (caddr_t)
2900 trunc_page((vm_offset_t)bp->b_data);
2901 pmap_qenter(
2902 (vm_offset_t)bp->b_data,
2903 bp->b_xio.xio_pages,
2904 bp->b_xio.xio_npages
2906 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2907 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
2910 if (newbsize < bp->b_bufsize)
2911 bufspacewakeup();
2912 bp->b_bufsize = newbsize; /* actual buffer allocation */
2913 bp->b_bcount = size; /* requested buffer size */
2914 return 1;
2918 * biowait:
2920 * Wait for buffer I/O completion, returning error status. The buffer
2921 * is left locked on return. B_EINTR is converted into an EINTR error
2922 * and cleared.
2924 * NOTE! The original b_cmd is lost on return, since b_cmd will be
2925 * set to BUF_CMD_DONE.
2928 biowait(struct buf *bp)
2930 crit_enter();
2931 while (bp->b_cmd != BUF_CMD_DONE) {
2932 if (bp->b_cmd == BUF_CMD_READ)
2933 tsleep(bp, 0, "biord", 0);
2934 else
2935 tsleep(bp, 0, "biowr", 0);
2937 crit_exit();
2938 if (bp->b_flags & B_EINTR) {
2939 bp->b_flags &= ~B_EINTR;
2940 return (EINTR);
2942 if (bp->b_flags & B_ERROR) {
2943 return (bp->b_error ? bp->b_error : EIO);
2944 } else {
2945 return (0);
2950 * This associates a tracking count with an I/O. vn_strategy() and
2951 * dev_dstrategy() do this automatically but there are a few cases
2952 * where a vnode or device layer is bypassed when a block translation
2953 * is cached. In such cases bio_start_transaction() may be called on
2954 * the bypassed layers so the system gets an I/O in progress indication
2955 * for those higher layers.
2957 void
2958 bio_start_transaction(struct bio *bio, struct bio_track *track)
2960 bio->bio_track = track;
2961 atomic_add_int(&track->bk_active, 1);
2965 * Initiate I/O on a vnode.
2967 void
2968 vn_strategy(struct vnode *vp, struct bio *bio)
2970 struct bio_track *track;
2972 KKASSERT(bio->bio_buf->b_cmd != BUF_CMD_DONE);
2973 if (bio->bio_buf->b_cmd == BUF_CMD_READ)
2974 track = &vp->v_track_read;
2975 else
2976 track = &vp->v_track_write;
2977 bio->bio_track = track;
2978 atomic_add_int(&track->bk_active, 1);
2979 vop_strategy(*vp->v_ops, vp, bio);
2984 * biodone:
2986 * Finish I/O on a buffer, optionally calling a completion function.
2987 * This is usually called from an interrupt so process blocking is
2988 * not allowed.
2990 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
2991 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
2992 * assuming B_INVAL is clear.
2994 * For the VMIO case, we set B_CACHE if the op was a read and no
2995 * read error occured, or if the op was a write. B_CACHE is never
2996 * set if the buffer is invalid or otherwise uncacheable.
2998 * biodone does not mess with B_INVAL, allowing the I/O routine or the
2999 * initiator to leave B_INVAL set to brelse the buffer out of existance
3000 * in the biodone routine.
3002 void
3003 biodone(struct bio *bio)
3005 struct buf *bp = bio->bio_buf;
3006 buf_cmd_t cmd;
3008 crit_enter();
3010 KASSERT(BUF_REFCNTNB(bp) > 0,
3011 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3012 KASSERT(bp->b_cmd != BUF_CMD_DONE,
3013 ("biodone: bp %p already done!", bp));
3015 runningbufwakeup(bp);
3018 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
3020 while (bio) {
3021 biodone_t *done_func;
3022 struct bio_track *track;
3025 * BIO tracking. Most but not all BIOs are tracked.
3027 if ((track = bio->bio_track) != NULL) {
3028 atomic_subtract_int(&track->bk_active, 1);
3029 if (track->bk_active < 0) {
3030 panic("biodone: bad active count bio %p\n",
3031 bio);
3033 if (track->bk_waitflag) {
3034 track->bk_waitflag = 0;
3035 wakeup(track);
3037 bio->bio_track = NULL;
3041 * A bio_done function terminates the loop. The function
3042 * will be responsible for any further chaining and/or
3043 * buffer management.
3045 * WARNING! The done function can deallocate the buffer!
3047 if ((done_func = bio->bio_done) != NULL) {
3048 bio->bio_done = NULL;
3049 done_func(bio);
3050 crit_exit();
3051 return;
3053 bio = bio->bio_prev;
3056 cmd = bp->b_cmd;
3057 bp->b_cmd = BUF_CMD_DONE;
3060 * Only reads and writes are processed past this point.
3062 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3063 brelse(bp);
3064 crit_exit();
3065 return;
3069 * Warning: softupdates may re-dirty the buffer.
3071 if (LIST_FIRST(&bp->b_dep) != NULL)
3072 buf_complete(bp);
3074 if (bp->b_flags & B_VMIO) {
3075 int i;
3076 vm_ooffset_t foff;
3077 vm_page_t m;
3078 vm_object_t obj;
3079 int iosize;
3080 struct vnode *vp = bp->b_vp;
3082 obj = vp->v_object;
3084 #if defined(VFS_BIO_DEBUG)
3085 if (vp->v_auxrefs == 0)
3086 panic("biodone: zero vnode hold count");
3087 if ((vp->v_flag & VOBJBUF) == 0)
3088 panic("biodone: vnode is not setup for merged cache");
3089 #endif
3091 foff = bp->b_loffset;
3092 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3093 KASSERT(obj != NULL, ("biodone: missing VM object"));
3095 #if defined(VFS_BIO_DEBUG)
3096 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3097 kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3098 obj->paging_in_progress, bp->b_xio.xio_npages);
3100 #endif
3103 * Set B_CACHE if the op was a normal read and no error
3104 * occured. B_CACHE is set for writes in the b*write()
3105 * routines.
3107 iosize = bp->b_bcount - bp->b_resid;
3108 if (cmd == BUF_CMD_READ && (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3109 bp->b_flags |= B_CACHE;
3112 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3113 int bogusflag = 0;
3114 int resid;
3116 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3117 if (resid > iosize)
3118 resid = iosize;
3121 * cleanup bogus pages, restoring the originals. Since
3122 * the originals should still be wired, we don't have
3123 * to worry about interrupt/freeing races destroying
3124 * the VM object association.
3126 m = bp->b_xio.xio_pages[i];
3127 if (m == bogus_page) {
3128 bogusflag = 1;
3129 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3130 if (m == NULL)
3131 panic("biodone: page disappeared");
3132 bp->b_xio.xio_pages[i] = m;
3133 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3134 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3136 #if defined(VFS_BIO_DEBUG)
3137 if (OFF_TO_IDX(foff) != m->pindex) {
3138 kprintf(
3139 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3140 (unsigned long)foff, m->pindex);
3142 #endif
3145 * In the write case, the valid and clean bits are
3146 * already changed correctly ( see bdwrite() ), so we
3147 * only need to do this here in the read case.
3149 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3150 vfs_page_set_valid(bp, foff, i, m);
3152 vm_page_flag_clear(m, PG_ZERO);
3155 * when debugging new filesystems or buffer I/O methods, this
3156 * is the most common error that pops up. if you see this, you
3157 * have not set the page busy flag correctly!!!
3159 if (m->busy == 0) {
3160 kprintf("biodone: page busy < 0, "
3161 "pindex: %d, foff: 0x(%x,%x), "
3162 "resid: %d, index: %d\n",
3163 (int) m->pindex, (int)(foff >> 32),
3164 (int) foff & 0xffffffff, resid, i);
3165 if (!vn_isdisk(vp, NULL))
3166 kprintf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
3167 bp->b_vp->v_mount->mnt_stat.f_iosize,
3168 bp->b_loffset,
3169 bp->b_flags, bp->b_xio.xio_npages);
3170 else
3171 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3172 bp->b_loffset,
3173 bp->b_flags, bp->b_xio.xio_npages);
3174 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3175 m->valid, m->dirty, m->wire_count);
3176 panic("biodone: page busy < 0");
3178 vm_page_io_finish(m);
3179 vm_object_pip_subtract(obj, 1);
3180 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3181 iosize -= resid;
3183 if (obj)
3184 vm_object_pip_wakeupn(obj, 0);
3188 * For asynchronous completions, release the buffer now. The brelse
3189 * will do a wakeup there if necessary - so no need to do a wakeup
3190 * here in the async case. The sync case always needs to do a wakeup.
3193 if (bp->b_flags & B_ASYNC) {
3194 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3195 brelse(bp);
3196 else
3197 bqrelse(bp);
3198 } else {
3199 wakeup(bp);
3201 crit_exit();
3205 * vfs_unbusy_pages:
3207 * This routine is called in lieu of iodone in the case of
3208 * incomplete I/O. This keeps the busy status for pages
3209 * consistant.
3211 void
3212 vfs_unbusy_pages(struct buf *bp)
3214 int i;
3216 runningbufwakeup(bp);
3217 if (bp->b_flags & B_VMIO) {
3218 struct vnode *vp = bp->b_vp;
3219 vm_object_t obj;
3221 obj = vp->v_object;
3223 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3224 vm_page_t m = bp->b_xio.xio_pages[i];
3227 * When restoring bogus changes the original pages
3228 * should still be wired, so we are in no danger of
3229 * losing the object association and do not need
3230 * critical section protection particularly.
3232 if (m == bogus_page) {
3233 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3234 if (!m) {
3235 panic("vfs_unbusy_pages: page missing");
3237 bp->b_xio.xio_pages[i] = m;
3238 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3239 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3241 vm_object_pip_subtract(obj, 1);
3242 vm_page_flag_clear(m, PG_ZERO);
3243 vm_page_io_finish(m);
3245 vm_object_pip_wakeupn(obj, 0);
3250 * vfs_page_set_valid:
3252 * Set the valid bits in a page based on the supplied offset. The
3253 * range is restricted to the buffer's size.
3255 * This routine is typically called after a read completes.
3257 static void
3258 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3260 vm_ooffset_t soff, eoff;
3263 * Start and end offsets in buffer. eoff - soff may not cross a
3264 * page boundry or cross the end of the buffer. The end of the
3265 * buffer, in this case, is our file EOF, not the allocation size
3266 * of the buffer.
3268 soff = off;
3269 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3270 if (eoff > bp->b_loffset + bp->b_bcount)
3271 eoff = bp->b_loffset + bp->b_bcount;
3274 * Set valid range. This is typically the entire buffer and thus the
3275 * entire page.
3277 if (eoff > soff) {
3278 vm_page_set_validclean(
3280 (vm_offset_t) (soff & PAGE_MASK),
3281 (vm_offset_t) (eoff - soff)
3287 * vfs_busy_pages:
3289 * This routine is called before a device strategy routine.
3290 * It is used to tell the VM system that paging I/O is in
3291 * progress, and treat the pages associated with the buffer
3292 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3293 * flag is handled to make sure that the object doesn't become
3294 * inconsistant.
3296 * Since I/O has not been initiated yet, certain buffer flags
3297 * such as B_ERROR or B_INVAL may be in an inconsistant state
3298 * and should be ignored.
3300 void
3301 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3303 int i, bogus;
3304 struct lwp *lp = curthread->td_lwp;
3307 * The buffer's I/O command must already be set. If reading,
3308 * B_CACHE must be 0 (double check against callers only doing
3309 * I/O when B_CACHE is 0).
3311 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3312 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3314 if (bp->b_flags & B_VMIO) {
3315 vm_object_t obj;
3316 vm_ooffset_t foff;
3318 obj = vp->v_object;
3319 foff = bp->b_loffset;
3320 KASSERT(bp->b_loffset != NOOFFSET,
3321 ("vfs_busy_pages: no buffer offset"));
3322 vfs_setdirty(bp);
3325 * Loop until none of the pages are busy.
3327 retry:
3328 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3329 vm_page_t m = bp->b_xio.xio_pages[i];
3331 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3332 goto retry;
3336 * Setup for I/O, soft-busy the page right now because
3337 * the next loop may block.
3339 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3340 vm_page_t m = bp->b_xio.xio_pages[i];
3342 vm_page_flag_clear(m, PG_ZERO);
3343 if ((bp->b_flags & B_CLUSTER) == 0) {
3344 vm_object_pip_add(obj, 1);
3345 vm_page_io_start(m);
3350 * Adjust protections for I/O and do bogus-page mapping.
3351 * Assume that vm_page_protect() can block (it can block
3352 * if VM_PROT_NONE, don't take any chances regardless).
3354 bogus = 0;
3355 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3356 vm_page_t m = bp->b_xio.xio_pages[i];
3359 * When readying a vnode-backed buffer for a write
3360 * we must zero-fill any invalid portions of the
3361 * backing VM pages.
3363 * When readying a vnode-backed buffer for a read
3364 * we must replace any dirty pages with a bogus
3365 * page so we do not destroy dirty data when
3366 * filling in gaps. Dirty pages might not
3367 * necessarily be marked dirty yet, so use m->valid
3368 * as a reasonable test.
3370 * Bogus page replacement is, uh, bogus. We need
3371 * to find a better way.
3373 if (bp->b_cmd == BUF_CMD_WRITE) {
3374 vm_page_protect(m, VM_PROT_READ);
3375 vfs_page_set_valid(bp, foff, i, m);
3376 } else if (m->valid == VM_PAGE_BITS_ALL) {
3377 bp->b_xio.xio_pages[i] = bogus_page;
3378 bogus++;
3379 } else {
3380 vm_page_protect(m, VM_PROT_NONE);
3382 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3384 if (bogus)
3385 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3386 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3390 * This is the easiest place to put the process accounting for the I/O
3391 * for now.
3393 if (lp != NULL) {
3394 if (bp->b_cmd == BUF_CMD_READ)
3395 lp->lwp_ru.ru_inblock++;
3396 else
3397 lp->lwp_ru.ru_oublock++;
3402 * vfs_clean_pages:
3404 * Tell the VM system that the pages associated with this buffer
3405 * are clean. This is used for delayed writes where the data is
3406 * going to go to disk eventually without additional VM intevention.
3408 * Note that while we only really need to clean through to b_bcount, we
3409 * just go ahead and clean through to b_bufsize.
3411 static void
3412 vfs_clean_pages(struct buf *bp)
3414 int i;
3416 if (bp->b_flags & B_VMIO) {
3417 vm_ooffset_t foff;
3419 foff = bp->b_loffset;
3420 KASSERT(foff != NOOFFSET, ("vfs_clean_pages: no buffer offset"));
3421 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3422 vm_page_t m = bp->b_xio.xio_pages[i];
3423 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3424 vm_ooffset_t eoff = noff;
3426 if (eoff > bp->b_loffset + bp->b_bufsize)
3427 eoff = bp->b_loffset + bp->b_bufsize;
3428 vfs_page_set_valid(bp, foff, i, m);
3429 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3430 foff = noff;
3436 * vfs_bio_set_validclean:
3438 * Set the range within the buffer to valid and clean. The range is
3439 * relative to the beginning of the buffer, b_loffset. Note that
3440 * b_loffset itself may be offset from the beginning of the first page.
3443 void
3444 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3446 if (bp->b_flags & B_VMIO) {
3447 int i;
3448 int n;
3451 * Fixup base to be relative to beginning of first page.
3452 * Set initial n to be the maximum number of bytes in the
3453 * first page that can be validated.
3456 base += (bp->b_loffset & PAGE_MASK);
3457 n = PAGE_SIZE - (base & PAGE_MASK);
3459 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3460 vm_page_t m = bp->b_xio.xio_pages[i];
3462 if (n > size)
3463 n = size;
3465 vm_page_set_validclean(m, base & PAGE_MASK, n);
3466 base += n;
3467 size -= n;
3468 n = PAGE_SIZE;
3474 * vfs_bio_clrbuf:
3476 * Clear a buffer. This routine essentially fakes an I/O, so we need
3477 * to clear B_ERROR and B_INVAL.
3479 * Note that while we only theoretically need to clear through b_bcount,
3480 * we go ahead and clear through b_bufsize.
3483 void
3484 vfs_bio_clrbuf(struct buf *bp)
3486 int i, mask = 0;
3487 caddr_t sa, ea;
3488 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3489 bp->b_flags &= ~(B_INVAL|B_ERROR);
3490 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3491 (bp->b_loffset & PAGE_MASK) == 0) {
3492 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3493 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3494 bp->b_resid = 0;
3495 return;
3497 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3498 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3499 bzero(bp->b_data, bp->b_bufsize);
3500 bp->b_xio.xio_pages[0]->valid |= mask;
3501 bp->b_resid = 0;
3502 return;
3505 ea = sa = bp->b_data;
3506 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3507 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3508 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3509 ea = (caddr_t)(vm_offset_t)ulmin(
3510 (u_long)(vm_offset_t)ea,
3511 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3512 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3513 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3514 continue;
3515 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3516 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3517 bzero(sa, ea - sa);
3519 } else {
3520 for (; sa < ea; sa += DEV_BSIZE, j++) {
3521 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3522 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3523 bzero(sa, DEV_BSIZE);
3526 bp->b_xio.xio_pages[i]->valid |= mask;
3527 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3529 bp->b_resid = 0;
3530 } else {
3531 clrbuf(bp);
3536 * vm_hold_load_pages:
3538 * Load pages into the buffer's address space. The pages are
3539 * allocated from the kernel object in order to reduce interference
3540 * with the any VM paging I/O activity. The range of loaded
3541 * pages will be wired.
3543 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3544 * retrieve the full range (to - from) of pages.
3547 void
3548 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3550 vm_offset_t pg;
3551 vm_page_t p;
3552 int index;
3554 to = round_page(to);
3555 from = round_page(from);
3556 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3558 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3560 tryagain:
3563 * Note: must allocate system pages since blocking here
3564 * could intefere with paging I/O, no matter which
3565 * process we are.
3567 p = vm_page_alloc(&kernel_object,
3568 (pg >> PAGE_SHIFT),
3569 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3570 if (!p) {
3571 vm_pageout_deficit += (to - from) >> PAGE_SHIFT;
3572 vm_wait();
3573 goto tryagain;
3575 vm_page_wire(p);
3576 p->valid = VM_PAGE_BITS_ALL;
3577 vm_page_flag_clear(p, PG_ZERO);
3578 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3579 bp->b_xio.xio_pages[index] = p;
3580 vm_page_wakeup(p);
3582 bp->b_xio.xio_npages = index;
3586 * vm_hold_free_pages:
3588 * Return pages associated with the buffer back to the VM system.
3590 * The range of pages underlying the buffer's address space will
3591 * be unmapped and un-wired.
3593 void
3594 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3596 vm_offset_t pg;
3597 vm_page_t p;
3598 int index, newnpages;
3600 from = round_page(from);
3601 to = round_page(to);
3602 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3604 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3605 p = bp->b_xio.xio_pages[index];
3606 if (p && (index < bp->b_xio.xio_npages)) {
3607 if (p->busy) {
3608 kprintf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3609 bp->b_bio2.bio_offset, bp->b_loffset);
3611 bp->b_xio.xio_pages[index] = NULL;
3612 pmap_kremove(pg);
3613 vm_page_busy(p);
3614 vm_page_unwire(p, 0);
3615 vm_page_free(p);
3618 bp->b_xio.xio_npages = newnpages;
3622 * vmapbuf:
3624 * Map a user buffer into KVM via a pbuf. On return the buffer's
3625 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3626 * initialized.
3629 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
3631 caddr_t addr;
3632 vm_offset_t va;
3633 vm_page_t m;
3634 int vmprot;
3635 int error;
3636 int pidx;
3637 int i;
3640 * bp had better have a command and it better be a pbuf.
3642 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3643 KKASSERT(bp->b_flags & B_PAGING);
3645 if (bytes < 0)
3646 return (-1);
3649 * Map the user data into KVM. Mappings have to be page-aligned.
3651 addr = (caddr_t)trunc_page((vm_offset_t)udata);
3652 pidx = 0;
3654 vmprot = VM_PROT_READ;
3655 if (bp->b_cmd == BUF_CMD_READ)
3656 vmprot |= VM_PROT_WRITE;
3658 while (addr < udata + bytes) {
3660 * Do the vm_fault if needed; do the copy-on-write thing
3661 * when reading stuff off device into memory.
3663 * vm_fault_page*() returns a held VM page.
3665 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
3666 va = trunc_page(va);
3668 m = vm_fault_page_quick(va, vmprot, &error);
3669 if (m == NULL) {
3670 for (i = 0; i < pidx; ++i) {
3671 vm_page_unhold(bp->b_xio.xio_pages[i]);
3672 bp->b_xio.xio_pages[i] = NULL;
3674 return(-1);
3676 bp->b_xio.xio_pages[pidx] = m;
3677 addr += PAGE_SIZE;
3678 ++pidx;
3682 * Map the page array and set the buffer fields to point to
3683 * the mapped data buffer.
3685 if (pidx > btoc(MAXPHYS))
3686 panic("vmapbuf: mapped more than MAXPHYS");
3687 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
3689 bp->b_xio.xio_npages = pidx;
3690 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
3691 bp->b_bcount = bytes;
3692 bp->b_bufsize = bytes;
3693 return(0);
3697 * vunmapbuf:
3699 * Free the io map PTEs associated with this IO operation.
3700 * We also invalidate the TLB entries and restore the original b_addr.
3702 void
3703 vunmapbuf(struct buf *bp)
3705 int pidx;
3706 int npages;
3708 KKASSERT(bp->b_flags & B_PAGING);
3710 npages = bp->b_xio.xio_npages;
3711 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3712 for (pidx = 0; pidx < npages; ++pidx) {
3713 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
3714 bp->b_xio.xio_pages[pidx] = NULL;
3716 bp->b_xio.xio_npages = 0;
3717 bp->b_data = bp->b_kvabase;
3721 * Scan all buffers in the system and issue the callback.
3724 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
3726 int count = 0;
3727 int error;
3728 int n;
3730 for (n = 0; n < nbuf; ++n) {
3731 if ((error = callback(&buf[n], info)) < 0) {
3732 count = error;
3733 break;
3735 count += error;
3737 return (count);
3741 * print out statistics from the current status of the buffer pool
3742 * this can be toggeled by the system control option debug.syncprt
3744 #ifdef DEBUG
3745 void
3746 vfs_bufstats(void)
3748 int i, j, count;
3749 struct buf *bp;
3750 struct bqueues *dp;
3751 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3752 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3754 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3755 count = 0;
3756 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3757 counts[j] = 0;
3758 crit_enter();
3759 TAILQ_FOREACH(bp, dp, b_freelist) {
3760 counts[bp->b_bufsize/PAGE_SIZE]++;
3761 count++;
3763 crit_exit();
3764 kprintf("%s: total-%d", bname[i], count);
3765 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3766 if (counts[j] != 0)
3767 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
3768 kprintf("\n");
3771 #endif
3773 #ifdef DDB
3775 DB_SHOW_COMMAND(buffer, db_show_buffer)
3777 /* get args */
3778 struct buf *bp = (struct buf *)addr;
3780 if (!have_addr) {
3781 db_printf("usage: show buffer <addr>\n");
3782 return;
3785 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3786 db_printf("b_cmd = %d\n", bp->b_cmd);
3787 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3788 "b_resid = %d\n, b_data = %p, "
3789 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3790 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3791 bp->b_data, bp->b_bio2.bio_offset, (bp->b_bio2.bio_next ? bp->b_bio2.bio_next->bio_offset : (off_t)-1));
3792 if (bp->b_xio.xio_npages) {
3793 int i;
3794 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3795 bp->b_xio.xio_npages);
3796 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3797 vm_page_t m;
3798 m = bp->b_xio.xio_pages[i];
3799 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3800 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3801 if ((i + 1) < bp->b_xio.xio_npages)
3802 db_printf(",");
3804 db_printf("\n");
3807 #endif /* DDB */