HAMMER 60I/Many: Mirroring
[dragonfly.git] / sys / kern / vfs_bio.c
blob5435a9ca2c51db8b77325d5a35a1d2b9792605ba
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.111 2008/07/08 03:34:27 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);
103 static vm_page_t bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit);
105 static void bd_signal(int totalspace);
106 static void buf_daemon(void);
107 static void buf_daemon_hw(void);
110 * bogus page -- for I/O to/from partially complete buffers
111 * this is a temporary solution to the problem, but it is not
112 * really that bad. it would be better to split the buffer
113 * for input in the case of buffers partially already in memory,
114 * but the code is intricate enough already.
116 vm_page_t bogus_page;
119 * These are all static, but make the ones we export globals so we do
120 * not need to use compiler magic.
122 int bufspace, maxbufspace,
123 bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
124 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
125 static int lorunningspace, hirunningspace, runningbufreq;
126 int dirtybufspace, dirtybufspacehw, lodirtybufspace, hidirtybufspace;
127 int dirtybufcount, dirtybufcounthw;
128 int runningbufspace, runningbufcount;
129 static int getnewbufcalls;
130 static int getnewbufrestarts;
131 static int recoverbufcalls;
132 static int needsbuffer; /* locked by needsbuffer_spin */
133 static int bd_request; /* locked by needsbuffer_spin */
134 static int bd_request_hw; /* locked by needsbuffer_spin */
135 static u_int bd_wake_ary[BD_WAKE_SIZE];
136 static u_int bd_wake_index;
137 static struct spinlock needsbuffer_spin;
139 static struct thread *bufdaemon_td;
140 static struct thread *bufdaemonhw_td;
144 * Sysctls for operational control of the buffer cache.
146 SYSCTL_INT(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
147 "Number of dirty buffers to flush before bufdaemon becomes inactive");
148 SYSCTL_INT(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
149 "High watermark used to trigger explicit flushing of dirty buffers");
150 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
151 "Minimum amount of buffer space required for active I/O");
152 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
153 "Maximum amount of buffer space to usable for active I/O");
155 * Sysctls determining current state of the buffer cache.
157 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
158 "Total number of buffers in buffer cache");
159 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
160 "Pending bytes of dirty buffers (all)");
161 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
162 "Pending bytes of dirty buffers (heavy weight)");
163 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
164 "Pending number of dirty buffers");
165 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
166 "Pending number of dirty buffers (heavy weight)");
167 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
168 "I/O bytes currently in progress due to asynchronous writes");
169 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
170 "I/O buffers currently in progress due to asynchronous writes");
171 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
172 "Hard limit on maximum amount of memory usable for buffer space");
173 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
174 "Soft limit on maximum amount of memory usable for buffer space");
175 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
176 "Minimum amount of memory to reserve for system buffer space");
177 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
178 "Amount of memory available for buffers");
179 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
180 0, "Maximum amount of memory reserved for buffers using malloc");
181 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
182 "Amount of memory left for buffers using malloc-scheme");
183 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
184 "New buffer header acquisition requests");
185 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
186 0, "New buffer header acquisition restarts");
187 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
188 "Recover VM space in an emergency");
189 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
190 "Buffer acquisition restarts due to fragmented buffer map");
191 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
192 "Amount of time KVA space was deallocated in an arbitrary buffer");
193 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
194 "Amount of time buffer re-use operations were successful");
195 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
196 "sizeof(struct buf)");
198 char *buf_wmesg = BUF_WMESG;
200 extern int vm_swap_size;
202 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
203 #define VFS_BIO_NEED_UNUSED02 0x02
204 #define VFS_BIO_NEED_UNUSED04 0x04
205 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
208 * bufspacewakeup:
210 * Called when buffer space is potentially available for recovery.
211 * getnewbuf() will block on this flag when it is unable to free
212 * sufficient buffer space. Buffer space becomes recoverable when
213 * bp's get placed back in the queues.
216 static __inline void
217 bufspacewakeup(void)
220 * If someone is waiting for BUF space, wake them up. Even
221 * though we haven't freed the kva space yet, the waiting
222 * process will be able to now.
224 if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
225 spin_lock_wr(&needsbuffer_spin);
226 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
227 spin_unlock_wr(&needsbuffer_spin);
228 wakeup(&needsbuffer);
233 * runningbufwakeup:
235 * Accounting for I/O in progress.
238 static __inline void
239 runningbufwakeup(struct buf *bp)
241 int totalspace;
243 if ((totalspace = bp->b_runningbufspace) != 0) {
244 runningbufspace -= totalspace;
245 --runningbufcount;
246 bp->b_runningbufspace = 0;
247 if (runningbufreq && runningbufspace <= lorunningspace) {
248 runningbufreq = 0;
249 wakeup(&runningbufreq);
251 bd_signal(totalspace);
256 * bufcountwakeup:
258 * Called when a buffer has been added to one of the free queues to
259 * account for the buffer and to wakeup anyone waiting for free buffers.
260 * This typically occurs when large amounts of metadata are being handled
261 * by the buffer cache ( else buffer space runs out first, usually ).
264 static __inline void
265 bufcountwakeup(void)
267 if (needsbuffer) {
268 spin_lock_wr(&needsbuffer_spin);
269 needsbuffer &= ~VFS_BIO_NEED_ANY;
270 spin_unlock_wr(&needsbuffer_spin);
271 wakeup(&needsbuffer);
276 * waitrunningbufspace()
278 * Wait for the amount of running I/O to drop to a reasonable level.
280 * The caller may be using this function to block in a tight loop, we
281 * must block of runningbufspace is greater then the passed limit.
282 * And even with that it may not be enough, due to the presence of
283 * B_LOCKED dirty buffers, so also wait for at least one running buffer
284 * to complete.
286 static __inline void
287 waitrunningbufspace(int limit)
289 int lorun;
291 if (lorunningspace < limit)
292 lorun = lorunningspace;
293 else
294 lorun = limit;
296 crit_enter();
297 if (runningbufspace > lorun) {
298 while (runningbufspace > lorun) {
299 ++runningbufreq;
300 tsleep(&runningbufreq, 0, "wdrain", 0);
302 } else if (runningbufspace) {
303 ++runningbufreq;
304 tsleep(&runningbufreq, 0, "wdrain2", 1);
306 crit_exit();
310 * vfs_buf_test_cache:
312 * Called when a buffer is extended. This function clears the B_CACHE
313 * bit if the newly extended portion of the buffer does not contain
314 * valid data.
316 static __inline__
317 void
318 vfs_buf_test_cache(struct buf *bp,
319 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
320 vm_page_t m)
322 if (bp->b_flags & B_CACHE) {
323 int base = (foff + off) & PAGE_MASK;
324 if (vm_page_is_valid(m, base, size) == 0)
325 bp->b_flags &= ~B_CACHE;
330 * bd_speedup()
332 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
333 * low water mark.
335 static __inline__
336 void
337 bd_speedup(void)
339 if (dirtybufspace < lodirtybufspace && dirtybufcount < nbuf / 2)
340 return;
342 if (bd_request == 0 &&
343 (dirtybufspace - dirtybufspacehw > lodirtybufspace / 2 ||
344 dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
345 spin_lock_wr(&needsbuffer_spin);
346 bd_request = 1;
347 spin_unlock_wr(&needsbuffer_spin);
348 wakeup(&bd_request);
350 if (bd_request_hw == 0 &&
351 (dirtybufspacehw > lodirtybufspace / 2 ||
352 dirtybufcounthw >= nbuf / 2)) {
353 spin_lock_wr(&needsbuffer_spin);
354 bd_request_hw = 1;
355 spin_unlock_wr(&needsbuffer_spin);
356 wakeup(&bd_request_hw);
361 * bd_heatup()
363 * Get the buf_daemon heated up when the number of running and dirty
364 * buffers exceeds the mid-point.
367 bd_heatup(void)
369 int mid1;
370 int mid2;
371 int totalspace;
373 mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
375 totalspace = runningbufspace + dirtybufspace;
376 if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
377 bd_speedup();
378 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
379 if (totalspace >= mid2)
380 return(totalspace - mid2);
382 return(0);
386 * bd_wait()
388 * Wait for the buffer cache to flush (totalspace) bytes worth of
389 * buffers, then return.
391 * Regardless this function blocks while the number of dirty buffers
392 * exceeds hidirtybufspace.
394 void
395 bd_wait(int totalspace)
397 u_int i;
398 int count;
400 if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
401 return;
403 while (totalspace > 0) {
404 bd_heatup();
405 crit_enter();
406 if (totalspace > runningbufspace + dirtybufspace)
407 totalspace = runningbufspace + dirtybufspace;
408 count = totalspace / BKVASIZE;
409 if (count >= BD_WAKE_SIZE)
410 count = BD_WAKE_SIZE - 1;
411 i = (bd_wake_index + count) & BD_WAKE_MASK;
412 ++bd_wake_ary[i];
413 tsleep(&bd_wake_ary[i], 0, "flstik", hz);
414 crit_exit();
416 totalspace = runningbufspace + dirtybufspace - hidirtybufspace;
421 * bd_signal()
423 * This function is called whenever runningbufspace or dirtybufspace
424 * is reduced. Track threads waiting for run+dirty buffer I/O
425 * complete.
427 static void
428 bd_signal(int totalspace)
430 u_int i;
432 while (totalspace > 0) {
433 i = atomic_fetchadd_int(&bd_wake_index, 1);
434 i &= BD_WAKE_MASK;
435 if (bd_wake_ary[i]) {
436 bd_wake_ary[i] = 0;
437 wakeup(&bd_wake_ary[i]);
439 totalspace -= BKVASIZE;
444 * bufinit:
446 * Load time initialisation of the buffer cache, called from machine
447 * dependant initialization code.
449 void
450 bufinit(void)
452 struct buf *bp;
453 vm_offset_t bogus_offset;
454 int i;
456 spin_init(&needsbuffer_spin);
458 /* next, make a null set of free lists */
459 for (i = 0; i < BUFFER_QUEUES; i++)
460 TAILQ_INIT(&bufqueues[i]);
462 /* finally, initialize each buffer header and stick on empty q */
463 for (i = 0; i < nbuf; i++) {
464 bp = &buf[i];
465 bzero(bp, sizeof *bp);
466 bp->b_flags = B_INVAL; /* we're just an empty header */
467 bp->b_cmd = BUF_CMD_DONE;
468 bp->b_qindex = BQUEUE_EMPTY;
469 initbufbio(bp);
470 xio_init(&bp->b_xio);
471 buf_dep_init(bp);
472 BUF_LOCKINIT(bp);
473 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
477 * maxbufspace is the absolute maximum amount of buffer space we are
478 * allowed to reserve in KVM and in real terms. The absolute maximum
479 * is nominally used by buf_daemon. hibufspace is the nominal maximum
480 * used by most other processes. The differential is required to
481 * ensure that buf_daemon is able to run when other processes might
482 * be blocked waiting for buffer space.
484 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
485 * this may result in KVM fragmentation which is not handled optimally
486 * by the system.
488 maxbufspace = nbuf * BKVASIZE;
489 hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
490 lobufspace = hibufspace - MAXBSIZE;
492 lorunningspace = 512 * 1024;
493 hirunningspace = 1024 * 1024;
496 * Limit the amount of malloc memory since it is wired permanently
497 * into the kernel space. Even though this is accounted for in
498 * the buffer allocation, we don't want the malloced region to grow
499 * uncontrolled. The malloc scheme improves memory utilization
500 * significantly on average (small) directories.
502 maxbufmallocspace = hibufspace / 20;
505 * Reduce the chance of a deadlock occuring by limiting the number
506 * of delayed-write dirty buffers we allow to stack up.
508 hidirtybufspace = hibufspace / 2;
509 dirtybufspace = 0;
510 dirtybufspacehw = 0;
512 lodirtybufspace = hidirtybufspace / 2;
515 * Maximum number of async ops initiated per buf_daemon loop. This is
516 * somewhat of a hack at the moment, we really need to limit ourselves
517 * based on the number of bytes of I/O in-transit that were initiated
518 * from buf_daemon.
521 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
522 bogus_page = vm_page_alloc(&kernel_object,
523 (bogus_offset >> PAGE_SHIFT),
524 VM_ALLOC_NORMAL);
525 vmstats.v_wire_count++;
530 * Initialize the embedded bio structures
532 void
533 initbufbio(struct buf *bp)
535 bp->b_bio1.bio_buf = bp;
536 bp->b_bio1.bio_prev = NULL;
537 bp->b_bio1.bio_offset = NOOFFSET;
538 bp->b_bio1.bio_next = &bp->b_bio2;
539 bp->b_bio1.bio_done = NULL;
541 bp->b_bio2.bio_buf = bp;
542 bp->b_bio2.bio_prev = &bp->b_bio1;
543 bp->b_bio2.bio_offset = NOOFFSET;
544 bp->b_bio2.bio_next = NULL;
545 bp->b_bio2.bio_done = NULL;
549 * Reinitialize the embedded bio structures as well as any additional
550 * translation cache layers.
552 void
553 reinitbufbio(struct buf *bp)
555 struct bio *bio;
557 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
558 bio->bio_done = NULL;
559 bio->bio_offset = NOOFFSET;
564 * Push another BIO layer onto an existing BIO and return it. The new
565 * BIO layer may already exist, holding cached translation data.
567 struct bio *
568 push_bio(struct bio *bio)
570 struct bio *nbio;
572 if ((nbio = bio->bio_next) == NULL) {
573 int index = bio - &bio->bio_buf->b_bio_array[0];
574 if (index >= NBUF_BIO - 1) {
575 panic("push_bio: too many layers bp %p\n",
576 bio->bio_buf);
578 nbio = &bio->bio_buf->b_bio_array[index + 1];
579 bio->bio_next = nbio;
580 nbio->bio_prev = bio;
581 nbio->bio_buf = bio->bio_buf;
582 nbio->bio_offset = NOOFFSET;
583 nbio->bio_done = NULL;
584 nbio->bio_next = NULL;
586 KKASSERT(nbio->bio_done == NULL);
587 return(nbio);
590 void
591 pop_bio(struct bio *bio)
593 /* NOP */
596 void
597 clearbiocache(struct bio *bio)
599 while (bio) {
600 bio->bio_offset = NOOFFSET;
601 bio = bio->bio_next;
606 * bfreekva:
608 * Free the KVA allocation for buffer 'bp'.
610 * Must be called from a critical section as this is the only locking for
611 * buffer_map.
613 * Since this call frees up buffer space, we call bufspacewakeup().
615 static void
616 bfreekva(struct buf *bp)
618 int count;
620 if (bp->b_kvasize) {
621 ++buffreekvacnt;
622 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
623 vm_map_lock(&buffer_map);
624 bufspace -= bp->b_kvasize;
625 vm_map_delete(&buffer_map,
626 (vm_offset_t) bp->b_kvabase,
627 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
628 &count
630 vm_map_unlock(&buffer_map);
631 vm_map_entry_release(count);
632 bp->b_kvasize = 0;
633 bufspacewakeup();
638 * bremfree:
640 * Remove the buffer from the appropriate free list.
642 void
643 bremfree(struct buf *bp)
645 int old_qindex;
647 crit_enter();
648 old_qindex = bp->b_qindex;
650 if (bp->b_qindex != BQUEUE_NONE) {
651 KASSERT(BUF_REFCNTNB(bp) == 1,
652 ("bremfree: bp %p not locked",bp));
653 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
654 bp->b_qindex = BQUEUE_NONE;
655 } else {
656 if (BUF_REFCNTNB(bp) <= 1)
657 panic("bremfree: removing a buffer not on a queue");
660 crit_exit();
665 * bread:
667 * Get a buffer with the specified data. Look in the cache first. We
668 * must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE
669 * is set, the buffer is valid and we do not have to do anything ( see
670 * getblk() ).
673 bread(struct vnode *vp, off_t loffset, int size, struct buf **bpp)
675 struct buf *bp;
677 bp = getblk(vp, loffset, size, 0, 0);
678 *bpp = bp;
680 /* if not found in cache, do some I/O */
681 if ((bp->b_flags & B_CACHE) == 0) {
682 KASSERT(!(bp->b_flags & B_ASYNC), ("bread: illegal async bp %p", bp));
683 bp->b_flags &= ~(B_ERROR | B_INVAL);
684 bp->b_cmd = BUF_CMD_READ;
685 vfs_busy_pages(vp, bp);
686 vn_strategy(vp, &bp->b_bio1);
687 return (biowait(bp));
689 return (0);
693 * breadn:
695 * Operates like bread, but also starts asynchronous I/O on
696 * read-ahead blocks. We must clear B_ERROR and B_INVAL prior
697 * to initiating I/O . If B_CACHE is set, the buffer is valid
698 * and we do not have to do anything.
701 breadn(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
702 int *rabsize, int cnt, struct buf **bpp)
704 struct buf *bp, *rabp;
705 int i;
706 int rv = 0, readwait = 0;
708 *bpp = bp = getblk(vp, loffset, size, 0, 0);
710 /* if not found in cache, do some I/O */
711 if ((bp->b_flags & B_CACHE) == 0) {
712 bp->b_flags &= ~(B_ERROR | B_INVAL);
713 bp->b_cmd = BUF_CMD_READ;
714 vfs_busy_pages(vp, bp);
715 vn_strategy(vp, &bp->b_bio1);
716 ++readwait;
719 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
720 if (inmem(vp, *raoffset))
721 continue;
722 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
724 if ((rabp->b_flags & B_CACHE) == 0) {
725 rabp->b_flags |= B_ASYNC;
726 rabp->b_flags &= ~(B_ERROR | B_INVAL);
727 rabp->b_cmd = BUF_CMD_READ;
728 vfs_busy_pages(vp, rabp);
729 BUF_KERNPROC(rabp);
730 vn_strategy(vp, &rabp->b_bio1);
731 } else {
732 brelse(rabp);
736 if (readwait) {
737 rv = biowait(bp);
739 return (rv);
743 * bwrite:
745 * Write, release buffer on completion. (Done by iodone
746 * if async). Do not bother writing anything if the buffer
747 * is invalid.
749 * Note that we set B_CACHE here, indicating that buffer is
750 * fully valid and thus cacheable. This is true even of NFS
751 * now so we set it generally. This could be set either here
752 * or in biodone() since the I/O is synchronous. We put it
753 * here.
756 bwrite(struct buf *bp)
758 int oldflags;
760 if (bp->b_flags & B_INVAL) {
761 brelse(bp);
762 return (0);
765 oldflags = bp->b_flags;
767 if (BUF_REFCNTNB(bp) == 0)
768 panic("bwrite: buffer is not busy???");
769 crit_enter();
771 /* Mark the buffer clean */
772 bundirty(bp);
774 bp->b_flags &= ~B_ERROR;
775 bp->b_flags |= B_CACHE;
776 bp->b_cmd = BUF_CMD_WRITE;
777 vfs_busy_pages(bp->b_vp, bp);
780 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
781 * valid for vnode-backed buffers.
783 bp->b_runningbufspace = bp->b_bufsize;
784 if (bp->b_runningbufspace) {
785 runningbufspace += bp->b_runningbufspace;
786 ++runningbufcount;
789 crit_exit();
790 if (oldflags & B_ASYNC)
791 BUF_KERNPROC(bp);
792 vn_strategy(bp->b_vp, &bp->b_bio1);
794 if ((oldflags & B_ASYNC) == 0) {
795 int rtval = biowait(bp);
796 brelse(bp);
797 return (rtval);
799 return (0);
803 * bdwrite:
805 * Delayed write. (Buffer is marked dirty). Do not bother writing
806 * anything if the buffer is marked invalid.
808 * Note that since the buffer must be completely valid, we can safely
809 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
810 * biodone() in order to prevent getblk from writing the buffer
811 * out synchronously.
813 void
814 bdwrite(struct buf *bp)
816 if (BUF_REFCNTNB(bp) == 0)
817 panic("bdwrite: buffer is not busy");
819 if (bp->b_flags & B_INVAL) {
820 brelse(bp);
821 return;
823 bdirty(bp);
826 * Set B_CACHE, indicating that the buffer is fully valid. This is
827 * true even of NFS now.
829 bp->b_flags |= B_CACHE;
832 * This bmap keeps the system from needing to do the bmap later,
833 * perhaps when the system is attempting to do a sync. Since it
834 * is likely that the indirect block -- or whatever other datastructure
835 * that the filesystem needs is still in memory now, it is a good
836 * thing to do this. Note also, that if the pageout daemon is
837 * requesting a sync -- there might not be enough memory to do
838 * the bmap then... So, this is important to do.
840 if (bp->b_bio2.bio_offset == NOOFFSET) {
841 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
842 NULL, NULL, BUF_CMD_WRITE);
846 * Set the *dirty* buffer range based upon the VM system dirty pages.
848 vfs_setdirty(bp);
851 * We need to do this here to satisfy the vnode_pager and the
852 * pageout daemon, so that it thinks that the pages have been
853 * "cleaned". Note that since the pages are in a delayed write
854 * buffer -- the VFS layer "will" see that the pages get written
855 * out on the next sync, or perhaps the cluster will be completed.
857 vfs_clean_pages(bp);
858 bqrelse(bp);
861 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
862 * due to the softdep code.
867 * bdirty:
869 * Turn buffer into delayed write request by marking it B_DELWRI.
870 * B_RELBUF and B_NOCACHE must be cleared.
872 * We reassign the buffer to itself to properly update it in the
873 * dirty/clean lists.
875 * Must be called from a critical section.
876 * The buffer must be on BQUEUE_NONE.
878 void
879 bdirty(struct buf *bp)
881 KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
882 if (bp->b_flags & B_NOCACHE) {
883 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
884 bp->b_flags &= ~B_NOCACHE;
886 if (bp->b_flags & B_INVAL) {
887 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
889 bp->b_flags &= ~B_RELBUF;
891 if ((bp->b_flags & B_DELWRI) == 0) {
892 bp->b_flags |= B_DELWRI;
893 reassignbuf(bp);
894 ++dirtybufcount;
895 dirtybufspace += bp->b_bufsize;
896 if (bp->b_flags & B_HEAVY) {
897 ++dirtybufcounthw;
898 dirtybufspacehw += bp->b_bufsize;
900 bd_heatup();
905 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
906 * needs to be flushed with a different buf_daemon thread to avoid
907 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
909 void
910 bheavy(struct buf *bp)
912 if ((bp->b_flags & B_HEAVY) == 0) {
913 bp->b_flags |= B_HEAVY;
914 if (bp->b_flags & B_DELWRI) {
915 ++dirtybufcounthw;
916 dirtybufspacehw += bp->b_bufsize;
922 * bundirty:
924 * Clear B_DELWRI for buffer.
926 * Must be called from a critical section.
928 * The buffer is typically on BQUEUE_NONE but there is one case in
929 * brelse() that calls this function after placing the buffer on
930 * a different queue.
933 void
934 bundirty(struct buf *bp)
936 if (bp->b_flags & B_DELWRI) {
937 bp->b_flags &= ~B_DELWRI;
938 reassignbuf(bp);
939 --dirtybufcount;
940 dirtybufspace -= bp->b_bufsize;
941 if (bp->b_flags & B_HEAVY) {
942 --dirtybufcounthw;
943 dirtybufspacehw -= bp->b_bufsize;
945 bd_signal(bp->b_bufsize);
948 * Since it is now being written, we can clear its deferred write flag.
950 bp->b_flags &= ~B_DEFERRED;
954 * bawrite:
956 * Asynchronous write. Start output on a buffer, but do not wait for
957 * it to complete. The buffer is released when the output completes.
959 * bwrite() ( or the VOP routine anyway ) is responsible for handling
960 * B_INVAL buffers. Not us.
962 void
963 bawrite(struct buf *bp)
965 bp->b_flags |= B_ASYNC;
966 bwrite(bp);
970 * bowrite:
972 * Ordered write. Start output on a buffer, and flag it so that the
973 * device will write it in the order it was queued. The buffer is
974 * released when the output completes. bwrite() ( or the VOP routine
975 * anyway ) is responsible for handling B_INVAL buffers.
978 bowrite(struct buf *bp)
980 bp->b_flags |= B_ORDERED | B_ASYNC;
981 return (bwrite(bp));
985 * buf_dirty_count_severe:
987 * Return true if we have too many dirty buffers.
990 buf_dirty_count_severe(void)
992 return (runningbufspace + dirtybufspace >= hidirtybufspace ||
993 dirtybufcount >= nbuf / 2);
997 * brelse:
999 * Release a busy buffer and, if requested, free its resources. The
1000 * buffer will be stashed in the appropriate bufqueue[] allowing it
1001 * to be accessed later as a cache entity or reused for other purposes.
1003 void
1004 brelse(struct buf *bp)
1006 #ifdef INVARIANTS
1007 int saved_flags = bp->b_flags;
1008 #endif
1010 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1012 crit_enter();
1015 * If B_NOCACHE is set we are being asked to destroy the buffer and
1016 * its backing store. Clear B_DELWRI.
1018 * B_NOCACHE is set in two cases: (1) when the caller really wants
1019 * to destroy the buffer and backing store and (2) when the caller
1020 * wants to destroy the buffer and backing store after a write
1021 * completes.
1023 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1024 bundirty(bp);
1027 if (bp->b_flags & B_LOCKED)
1028 bp->b_flags &= ~B_ERROR;
1031 * If a write error occurs and the caller does not want to throw
1032 * away the buffer, redirty the buffer. This will also clear
1033 * B_NOCACHE.
1035 if (bp->b_cmd == BUF_CMD_WRITE &&
1036 (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
1038 * Failed write, redirty. Must clear B_ERROR to prevent
1039 * pages from being scrapped. If B_INVAL is set then
1040 * this case is not run and the next case is run to
1041 * destroy the buffer. B_INVAL can occur if the buffer
1042 * is outside the range supported by the underlying device.
1044 bp->b_flags &= ~B_ERROR;
1045 bdirty(bp);
1046 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1047 (bp->b_bufsize <= 0) || bp->b_cmd == BUF_CMD_FREEBLKS) {
1049 * Either a failed I/O or we were asked to free or not
1050 * cache the buffer.
1052 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1053 * buffer cannot be immediately freed.
1055 bp->b_flags |= B_INVAL;
1056 if (LIST_FIRST(&bp->b_dep) != NULL)
1057 buf_deallocate(bp);
1058 if (bp->b_flags & B_DELWRI) {
1059 --dirtybufcount;
1060 dirtybufspace -= bp->b_bufsize;
1061 if (bp->b_flags & B_HEAVY) {
1062 --dirtybufcounthw;
1063 dirtybufspacehw -= bp->b_bufsize;
1065 bd_signal(bp->b_bufsize);
1067 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1071 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1072 * If vfs_vmio_release() is called with either bit set, the
1073 * underlying pages may wind up getting freed causing a previous
1074 * write (bdwrite()) to get 'lost' because pages associated with
1075 * a B_DELWRI bp are marked clean. Pages associated with a
1076 * B_LOCKED buffer may be mapped by the filesystem.
1078 * If we want to release the buffer ourselves (rather then the
1079 * originator asking us to release it), give the originator a
1080 * chance to countermand the release by setting B_LOCKED.
1082 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1083 * if B_DELWRI is set.
1085 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1086 * on pages to return pages to the VM page queues.
1088 if (bp->b_flags & (B_DELWRI | B_LOCKED)) {
1089 bp->b_flags &= ~B_RELBUF;
1090 } else if (vm_page_count_severe()) {
1091 if (LIST_FIRST(&bp->b_dep) != NULL)
1092 buf_deallocate(bp);
1093 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1094 bp->b_flags &= ~B_RELBUF;
1095 else
1096 bp->b_flags |= B_RELBUF;
1100 * At this point destroying the buffer is governed by the B_INVAL
1101 * or B_RELBUF flags.
1103 bp->b_cmd = BUF_CMD_DONE;
1106 * VMIO buffer rundown. Make sure the VM page array is restored
1107 * after an I/O may have replaces some of the pages with bogus pages
1108 * in order to not destroy dirty pages in a fill-in read.
1110 * Note that due to the code above, if a buffer is marked B_DELWRI
1111 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1112 * B_INVAL may still be set, however.
1114 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1115 * but not the backing store. B_NOCACHE will destroy the backing
1116 * store.
1118 * Note that dirty NFS buffers contain byte-granular write ranges
1119 * and should not be destroyed w/ B_INVAL even if the backing store
1120 * is left intact.
1122 if (bp->b_flags & B_VMIO) {
1124 * Rundown for VMIO buffers which are not dirty NFS buffers.
1126 int i, j, resid;
1127 vm_page_t m;
1128 off_t foff;
1129 vm_pindex_t poff;
1130 vm_object_t obj;
1131 struct vnode *vp;
1133 vp = bp->b_vp;
1136 * Get the base offset and length of the buffer. Note that
1137 * in the VMIO case if the buffer block size is not
1138 * page-aligned then b_data pointer may not be page-aligned.
1139 * But our b_xio.xio_pages array *IS* page aligned.
1141 * block sizes less then DEV_BSIZE (usually 512) are not
1142 * supported due to the page granularity bits (m->valid,
1143 * m->dirty, etc...).
1145 * See man buf(9) for more information
1148 resid = bp->b_bufsize;
1149 foff = bp->b_loffset;
1151 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1152 m = bp->b_xio.xio_pages[i];
1153 vm_page_flag_clear(m, PG_ZERO);
1155 * If we hit a bogus page, fixup *all* of them
1156 * now. Note that we left these pages wired
1157 * when we removed them so they had better exist,
1158 * and they cannot be ripped out from under us so
1159 * no critical section protection is necessary.
1161 if (m == bogus_page) {
1162 obj = vp->v_object;
1163 poff = OFF_TO_IDX(bp->b_loffset);
1165 for (j = i; j < bp->b_xio.xio_npages; j++) {
1166 vm_page_t mtmp;
1168 mtmp = bp->b_xio.xio_pages[j];
1169 if (mtmp == bogus_page) {
1170 mtmp = vm_page_lookup(obj, poff + j);
1171 if (!mtmp) {
1172 panic("brelse: page missing");
1174 bp->b_xio.xio_pages[j] = mtmp;
1178 if ((bp->b_flags & B_INVAL) == 0) {
1179 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1180 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1182 m = bp->b_xio.xio_pages[i];
1186 * Invalidate the backing store if B_NOCACHE is set
1187 * (e.g. used with vinvalbuf()). If this is NFS
1188 * we impose a requirement that the block size be
1189 * a multiple of PAGE_SIZE and create a temporary
1190 * hack to basically invalidate the whole page. The
1191 * problem is that NFS uses really odd buffer sizes
1192 * especially when tracking piecemeal writes and
1193 * it also vinvalbuf()'s a lot, which would result
1194 * in only partial page validation and invalidation
1195 * here. If the file page is mmap()'d, however,
1196 * all the valid bits get set so after we invalidate
1197 * here we would end up with weird m->valid values
1198 * like 0xfc. nfs_getpages() can't handle this so
1199 * we clear all the valid bits for the NFS case
1200 * instead of just some of them.
1202 * The real bug is the VM system having to set m->valid
1203 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1204 * itself is an artifact of the whole 512-byte
1205 * granular mess that exists to support odd block
1206 * sizes and UFS meta-data block sizes (e.g. 6144).
1207 * A complete rewrite is required.
1209 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1210 int poffset = foff & PAGE_MASK;
1211 int presid;
1213 presid = PAGE_SIZE - poffset;
1214 if (bp->b_vp->v_tag == VT_NFS &&
1215 bp->b_vp->v_type == VREG) {
1216 ; /* entire page */
1217 } else if (presid > resid) {
1218 presid = resid;
1220 KASSERT(presid >= 0, ("brelse: extra page"));
1221 vm_page_set_invalid(m, poffset, presid);
1223 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1224 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1226 if (bp->b_flags & (B_INVAL | B_RELBUF))
1227 vfs_vmio_release(bp);
1228 } else {
1230 * Rundown for non-VMIO buffers.
1232 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1233 #if 0
1234 if (bp->b_vp)
1235 kprintf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1236 #endif
1237 if (bp->b_bufsize)
1238 allocbuf(bp, 0);
1239 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1240 if (bp->b_vp)
1241 brelvp(bp);
1245 if (bp->b_qindex != BQUEUE_NONE)
1246 panic("brelse: free buffer onto another queue???");
1247 if (BUF_REFCNTNB(bp) > 1) {
1248 /* Temporary panic to verify exclusive locking */
1249 /* This panic goes away when we allow shared refs */
1250 panic("brelse: multiple refs");
1251 /* do not release to free list */
1252 BUF_UNLOCK(bp);
1253 crit_exit();
1254 return;
1258 * Figure out the correct queue to place the cleaned up buffer on.
1259 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1260 * disassociated from their vnode.
1262 if (bp->b_flags & B_LOCKED) {
1264 * Buffers that are locked are placed in the locked queue
1265 * immediately, regardless of their state.
1267 bp->b_qindex = BQUEUE_LOCKED;
1268 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1269 } else if (bp->b_bufsize == 0) {
1271 * Buffers with no memory. Due to conditionals near the top
1272 * of brelse() such buffers should probably already be
1273 * marked B_INVAL and disassociated from their vnode.
1275 bp->b_flags |= B_INVAL;
1276 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1277 KKASSERT((bp->b_flags & B_HASHED) == 0);
1278 if (bp->b_kvasize) {
1279 bp->b_qindex = BQUEUE_EMPTYKVA;
1280 } else {
1281 bp->b_qindex = BQUEUE_EMPTY;
1283 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1284 } else if (bp->b_flags & (B_ERROR | B_INVAL | B_NOCACHE | B_RELBUF)) {
1286 * Buffers with junk contents. Again these buffers had better
1287 * already be disassociated from their vnode.
1289 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1290 KKASSERT((bp->b_flags & B_HASHED) == 0);
1291 bp->b_flags |= B_INVAL;
1292 bp->b_qindex = BQUEUE_CLEAN;
1293 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1294 } else {
1296 * Remaining buffers. These buffers are still associated with
1297 * their vnode.
1299 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1300 case B_DELWRI:
1301 bp->b_qindex = BQUEUE_DIRTY;
1302 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1303 break;
1304 case B_DELWRI | B_HEAVY:
1305 bp->b_qindex = BQUEUE_DIRTY_HW;
1306 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1307 b_freelist);
1308 break;
1309 default:
1311 * NOTE: Buffers are always placed at the end of the
1312 * queue. If B_AGE is not set the buffer will cycle
1313 * through the queue twice.
1315 bp->b_qindex = BQUEUE_CLEAN;
1316 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1317 break;
1322 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1323 * on the correct queue.
1325 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1326 bundirty(bp);
1329 * The bp is on an appropriate queue unless locked. If it is not
1330 * locked or dirty we can wakeup threads waiting for buffer space.
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 * This routine is called in an emergency to recover VM pages from the
1934 * buffer cache by cashing in clean buffers. The idea is to recover
1935 * enough pages to be able to satisfy a stuck bio_page_alloc().
1937 static int
1938 recoverbufpages(void)
1940 struct buf *bp;
1941 int bytes = 0;
1943 ++recoverbufcalls;
1945 while (bytes < MAXBSIZE) {
1946 bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1947 if (bp == NULL)
1948 break;
1951 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
1952 * cycles through the queue twice before being selected.
1954 if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) {
1955 bp->b_flags |= B_AGE;
1956 TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1957 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN],
1958 bp, b_freelist);
1959 continue;
1963 * Sanity Checks
1965 KKASSERT(bp->b_qindex == BQUEUE_CLEAN);
1966 KKASSERT((bp->b_flags & B_DELWRI) == 0);
1969 * Start freeing the bp. This is somewhat involved.
1971 * Buffers on the clean list must be disassociated from
1972 * their current vnode
1975 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1976 kprintf("recoverbufpages: warning, locked buf %p, race corrected\n", bp);
1977 tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1978 continue;
1980 if (bp->b_qindex != BQUEUE_CLEAN) {
1981 kprintf("recoverbufpages: warning, BUF_LOCK blocked unexpectedly on buf %p index %d, race corrected\n", bp, bp->b_qindex);
1982 BUF_UNLOCK(bp);
1983 continue;
1985 bremfree(bp);
1988 * Dependancies must be handled before we disassociate the
1989 * vnode.
1991 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1992 * be immediately disassociated. HAMMER then becomes
1993 * responsible for releasing the buffer.
1995 if (LIST_FIRST(&bp->b_dep) != NULL) {
1996 buf_deallocate(bp);
1997 if (bp->b_flags & B_LOCKED) {
1998 bqrelse(bp);
1999 continue;
2001 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2004 bytes += bp->b_bufsize;
2006 if (bp->b_flags & B_VMIO) {
2007 bp->b_flags &= ~B_ASYNC;
2008 bp->b_flags |= B_DIRECT; /* try to free pages */
2009 vfs_vmio_release(bp);
2011 if (bp->b_vp)
2012 brelvp(bp);
2014 KKASSERT(bp->b_vp == NULL);
2015 KKASSERT((bp->b_flags & B_HASHED) == 0);
2018 * critical section protection is not required when
2019 * scrapping a buffer's contents because it is already
2020 * wired.
2022 if (bp->b_bufsize)
2023 allocbuf(bp, 0);
2025 bp->b_flags = B_BNOCLIP;
2026 bp->b_cmd = BUF_CMD_DONE;
2027 bp->b_vp = NULL;
2028 bp->b_error = 0;
2029 bp->b_resid = 0;
2030 bp->b_bcount = 0;
2031 bp->b_xio.xio_npages = 0;
2032 bp->b_dirtyoff = bp->b_dirtyend = 0;
2033 reinitbufbio(bp);
2034 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2035 buf_dep_init(bp);
2036 bp->b_flags |= B_INVAL;
2037 /* bfreekva(bp); */
2038 brelse(bp);
2040 return(bytes);
2044 * buf_daemon:
2046 * Buffer flushing daemon. Buffers are normally flushed by the
2047 * update daemon but if it cannot keep up this process starts to
2048 * take the load in an attempt to prevent getnewbuf() from blocking.
2050 * Once a flush is initiated it does not stop until the number
2051 * of buffers falls below lodirtybuffers, but we will wake up anyone
2052 * waiting at the mid-point.
2055 static struct kproc_desc buf_kp = {
2056 "bufdaemon",
2057 buf_daemon,
2058 &bufdaemon_td
2060 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2061 kproc_start, &buf_kp)
2063 static struct kproc_desc bufhw_kp = {
2064 "bufdaemon_hw",
2065 buf_daemon_hw,
2066 &bufdaemonhw_td
2068 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2069 kproc_start, &bufhw_kp)
2071 static void
2072 buf_daemon(void)
2074 int limit;
2077 * This process needs to be suspended prior to shutdown sync.
2079 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2080 bufdaemon_td, SHUTDOWN_PRI_LAST);
2081 curthread->td_flags |= TDF_SYSTHREAD;
2084 * This process is allowed to take the buffer cache to the limit
2086 crit_enter();
2088 for (;;) {
2089 kproc_suspend_loop();
2092 * Do the flush. Limit the amount of in-transit I/O we
2093 * allow to build up, otherwise we would completely saturate
2094 * the I/O system. Wakeup any waiting processes before we
2095 * normally would so they can run in parallel with our drain.
2097 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2098 * but because we split the operation into two threads we
2099 * have to cut it in half for each thread.
2101 limit = lodirtybufspace / 2;
2102 waitrunningbufspace(limit);
2103 while (runningbufspace + dirtybufspace > limit ||
2104 dirtybufcount - dirtybufcounthw >= nbuf / 2) {
2105 if (flushbufqueues(BQUEUE_DIRTY) == 0)
2106 break;
2107 waitrunningbufspace(limit);
2111 * We reached our low water mark, reset the
2112 * request and sleep until we are needed again.
2113 * The sleep is just so the suspend code works.
2115 spin_lock_wr(&needsbuffer_spin);
2116 if (bd_request == 0) {
2117 msleep(&bd_request, &needsbuffer_spin, 0,
2118 "psleep", hz);
2120 bd_request = 0;
2121 spin_unlock_wr(&needsbuffer_spin);
2125 static void
2126 buf_daemon_hw(void)
2128 int limit;
2131 * This process needs to be suspended prior to shutdown sync.
2133 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2134 bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2135 curthread->td_flags |= TDF_SYSTHREAD;
2138 * This process is allowed to take the buffer cache to the limit
2140 crit_enter();
2142 for (;;) {
2143 kproc_suspend_loop();
2146 * Do the flush. Limit the amount of in-transit I/O we
2147 * allow to build up, otherwise we would completely saturate
2148 * the I/O system. Wakeup any waiting processes before we
2149 * normally would so they can run in parallel with our drain.
2151 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2152 * but because we split the operation into two threads we
2153 * have to cut it in half for each thread.
2155 limit = lodirtybufspace / 2;
2156 waitrunningbufspace(limit);
2157 while (runningbufspace + dirtybufspacehw > limit ||
2158 dirtybufcounthw >= nbuf / 2) {
2159 if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2160 break;
2161 waitrunningbufspace(limit);
2165 * We reached our low water mark, reset the
2166 * request and sleep until we are needed again.
2167 * The sleep is just so the suspend code works.
2169 spin_lock_wr(&needsbuffer_spin);
2170 if (bd_request_hw == 0) {
2171 msleep(&bd_request_hw, &needsbuffer_spin, 0,
2172 "psleep", hz);
2174 bd_request_hw = 0;
2175 spin_unlock_wr(&needsbuffer_spin);
2180 * flushbufqueues:
2182 * Try to flush a buffer in the dirty queue. We must be careful to
2183 * free up B_INVAL buffers instead of write them, which NFS is
2184 * particularly sensitive to.
2186 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate
2187 * that we really want to try to get the buffer out and reuse it
2188 * due to the write load on the machine.
2191 static int
2192 flushbufqueues(bufq_type_t q)
2194 struct buf *bp;
2195 int r = 0;
2197 bp = TAILQ_FIRST(&bufqueues[q]);
2199 while (bp) {
2200 KASSERT((bp->b_flags & B_DELWRI),
2201 ("unexpected clean buffer %p", bp));
2203 if (bp->b_flags & B_DELWRI) {
2204 if (bp->b_flags & B_INVAL) {
2205 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2206 panic("flushbufqueues: locked buf");
2207 bremfree(bp);
2208 brelse(bp);
2209 ++r;
2210 break;
2212 if (LIST_FIRST(&bp->b_dep) != NULL &&
2213 (bp->b_flags & B_DEFERRED) == 0 &&
2214 buf_countdeps(bp, 0)) {
2215 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2216 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2217 b_freelist);
2218 bp->b_flags |= B_DEFERRED;
2219 bp = TAILQ_FIRST(&bufqueues[q]);
2220 continue;
2224 * Only write it out if we can successfully lock
2225 * it. If the buffer has a dependancy,
2226 * buf_checkwrite must also return 0.
2228 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2229 if (LIST_FIRST(&bp->b_dep) != NULL &&
2230 buf_checkwrite(bp)) {
2231 bremfree(bp);
2232 brelse(bp);
2233 } else {
2234 bp->b_flags |= B_AGE;
2235 vfs_bio_awrite(bp);
2237 ++r;
2238 break;
2241 bp = TAILQ_NEXT(bp, b_freelist);
2243 return (r);
2247 * inmem:
2249 * Returns true if no I/O is needed to access the associated VM object.
2250 * This is like findblk except it also hunts around in the VM system for
2251 * the data.
2253 * Note that we ignore vm_page_free() races from interrupts against our
2254 * lookup, since if the caller is not protected our return value will not
2255 * be any more valid then otherwise once we exit the critical section.
2258 inmem(struct vnode *vp, off_t loffset)
2260 vm_object_t obj;
2261 vm_offset_t toff, tinc, size;
2262 vm_page_t m;
2264 if (findblk(vp, loffset))
2265 return 1;
2266 if (vp->v_mount == NULL)
2267 return 0;
2268 if ((obj = vp->v_object) == NULL)
2269 return 0;
2271 size = PAGE_SIZE;
2272 if (size > vp->v_mount->mnt_stat.f_iosize)
2273 size = vp->v_mount->mnt_stat.f_iosize;
2275 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2276 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2277 if (m == NULL)
2278 return 0;
2279 tinc = size;
2280 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2281 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2282 if (vm_page_is_valid(m,
2283 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2284 return 0;
2286 return 1;
2290 * vfs_setdirty:
2292 * Sets the dirty range for a buffer based on the status of the dirty
2293 * bits in the pages comprising the buffer.
2295 * The range is limited to the size of the buffer.
2297 * This routine is primarily used by NFS, but is generalized for the
2298 * B_VMIO case.
2300 static void
2301 vfs_setdirty(struct buf *bp)
2303 int i;
2304 vm_object_t object;
2307 * Degenerate case - empty buffer
2310 if (bp->b_bufsize == 0)
2311 return;
2314 * We qualify the scan for modified pages on whether the
2315 * object has been flushed yet. The OBJ_WRITEABLE flag
2316 * is not cleared simply by protecting pages off.
2319 if ((bp->b_flags & B_VMIO) == 0)
2320 return;
2322 object = bp->b_xio.xio_pages[0]->object;
2324 if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2325 kprintf("Warning: object %p writeable but not mightbedirty\n", object);
2326 if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2327 kprintf("Warning: object %p mightbedirty but not writeable\n", object);
2329 if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2330 vm_offset_t boffset;
2331 vm_offset_t eoffset;
2334 * test the pages to see if they have been modified directly
2335 * by users through the VM system.
2337 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2338 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2339 vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2343 * Calculate the encompassing dirty range, boffset and eoffset,
2344 * (eoffset - boffset) bytes.
2347 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2348 if (bp->b_xio.xio_pages[i]->dirty)
2349 break;
2351 boffset = (i << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2353 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2354 if (bp->b_xio.xio_pages[i]->dirty) {
2355 break;
2358 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2361 * Fit it to the buffer.
2364 if (eoffset > bp->b_bcount)
2365 eoffset = bp->b_bcount;
2368 * If we have a good dirty range, merge with the existing
2369 * dirty range.
2372 if (boffset < eoffset) {
2373 if (bp->b_dirtyoff > boffset)
2374 bp->b_dirtyoff = boffset;
2375 if (bp->b_dirtyend < eoffset)
2376 bp->b_dirtyend = eoffset;
2382 * findblk:
2384 * Locate and return the specified buffer, or NULL if the buffer does
2385 * not exist. Do not attempt to lock the buffer or manipulate it in
2386 * any way. The caller must validate that the correct buffer has been
2387 * obtain after locking it.
2389 struct buf *
2390 findblk(struct vnode *vp, off_t loffset)
2392 struct buf *bp;
2394 crit_enter();
2395 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2396 crit_exit();
2397 return(bp);
2401 * getblk:
2403 * Get a block given a specified block and offset into a file/device.
2404 * B_INVAL may or may not be set on return. The caller should clear
2405 * B_INVAL prior to initiating a READ.
2407 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2408 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2409 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2410 * without doing any of those things the system will likely believe
2411 * the buffer to be valid (especially if it is not B_VMIO), and the
2412 * next getblk() will return the buffer with B_CACHE set.
2414 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2415 * an existing buffer.
2417 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2418 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2419 * and then cleared based on the backing VM. If the previous buffer is
2420 * non-0-sized but invalid, B_CACHE will be cleared.
2422 * If getblk() must create a new buffer, the new buffer is returned with
2423 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2424 * case it is returned with B_INVAL clear and B_CACHE set based on the
2425 * backing VM.
2427 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2428 * B_CACHE bit is clear.
2430 * What this means, basically, is that the caller should use B_CACHE to
2431 * determine whether the buffer is fully valid or not and should clear
2432 * B_INVAL prior to issuing a read. If the caller intends to validate
2433 * the buffer by loading its data area with something, the caller needs
2434 * to clear B_INVAL. If the caller does this without issuing an I/O,
2435 * the caller should set B_CACHE ( as an optimization ), else the caller
2436 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2437 * a write attempt or if it was a successfull read. If the caller
2438 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2439 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2441 * getblk flags:
2443 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2444 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2446 struct buf *
2447 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2449 struct buf *bp;
2450 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2451 int error;
2453 if (size > MAXBSIZE)
2454 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2455 if (vp->v_object == NULL)
2456 panic("getblk: vnode %p has no object!", vp);
2458 crit_enter();
2459 loop:
2460 if ((bp = findblk(vp, loffset))) {
2462 * The buffer was found in the cache, but we need to lock it.
2463 * Even with LK_NOWAIT the lockmgr may break our critical
2464 * section, so double-check the validity of the buffer
2465 * once the lock has been obtained.
2467 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2468 int lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2469 if (blkflags & GETBLK_PCATCH)
2470 lkflags |= LK_PCATCH;
2471 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2472 if (error) {
2473 if (error == ENOLCK)
2474 goto loop;
2475 crit_exit();
2476 return (NULL);
2481 * Once the buffer has been locked, make sure we didn't race
2482 * a buffer recyclement. Buffers that are no longer hashed
2483 * will have b_vp == NULL, so this takes care of that check
2484 * as well.
2486 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2487 kprintf("Warning buffer %p (vp %p loffset %lld) was recycled\n", bp, vp, loffset);
2488 BUF_UNLOCK(bp);
2489 goto loop;
2493 * All vnode-based buffers must be backed by a VM object.
2495 KKASSERT(bp->b_flags & B_VMIO);
2496 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2497 bp->b_flags &= ~B_AGE;
2500 * Make sure that B_INVAL buffers do not have a cached
2501 * block number translation.
2503 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2504 kprintf("Warning invalid buffer %p (vp %p loffset %lld) did not have cleared bio_offset cache\n", bp, vp, loffset);
2505 clearbiocache(&bp->b_bio2);
2509 * The buffer is locked. B_CACHE is cleared if the buffer is
2510 * invalid.
2512 if (bp->b_flags & B_INVAL)
2513 bp->b_flags &= ~B_CACHE;
2514 bremfree(bp);
2517 * Any size inconsistancy with a dirty buffer or a buffer
2518 * with a softupdates dependancy must be resolved. Resizing
2519 * the buffer in such circumstances can lead to problems.
2521 if (size != bp->b_bcount) {
2522 if (bp->b_flags & B_DELWRI) {
2523 bp->b_flags |= B_NOCACHE;
2524 bwrite(bp);
2525 } else if (LIST_FIRST(&bp->b_dep)) {
2526 bp->b_flags |= B_NOCACHE;
2527 bwrite(bp);
2528 } else {
2529 bp->b_flags |= B_RELBUF;
2530 brelse(bp);
2532 goto loop;
2534 KKASSERT(size <= bp->b_kvasize);
2535 KASSERT(bp->b_loffset != NOOFFSET,
2536 ("getblk: no buffer offset"));
2539 * A buffer with B_DELWRI set and B_CACHE clear must
2540 * be committed before we can return the buffer in
2541 * order to prevent the caller from issuing a read
2542 * ( due to B_CACHE not being set ) and overwriting
2543 * it.
2545 * Most callers, including NFS and FFS, need this to
2546 * operate properly either because they assume they
2547 * can issue a read if B_CACHE is not set, or because
2548 * ( for example ) an uncached B_DELWRI might loop due
2549 * to softupdates re-dirtying the buffer. In the latter
2550 * case, B_CACHE is set after the first write completes,
2551 * preventing further loops.
2553 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2554 * above while extending the buffer, we cannot allow the
2555 * buffer to remain with B_CACHE set after the write
2556 * completes or it will represent a corrupt state. To
2557 * deal with this we set B_NOCACHE to scrap the buffer
2558 * after the write.
2560 * We might be able to do something fancy, like setting
2561 * B_CACHE in bwrite() except if B_DELWRI is already set,
2562 * so the below call doesn't set B_CACHE, but that gets real
2563 * confusing. This is much easier.
2566 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2567 bp->b_flags |= B_NOCACHE;
2568 bwrite(bp);
2569 goto loop;
2571 crit_exit();
2572 } else {
2574 * Buffer is not in-core, create new buffer. The buffer
2575 * returned by getnewbuf() is locked. Note that the returned
2576 * buffer is also considered valid (not marked B_INVAL).
2578 * Calculating the offset for the I/O requires figuring out
2579 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2580 * the mount's f_iosize otherwise. If the vnode does not
2581 * have an associated mount we assume that the passed size is
2582 * the block size.
2584 * Note that vn_isdisk() cannot be used here since it may
2585 * return a failure for numerous reasons. Note that the
2586 * buffer size may be larger then the block size (the caller
2587 * will use block numbers with the proper multiple). Beware
2588 * of using any v_* fields which are part of unions. In
2589 * particular, in DragonFly the mount point overloading
2590 * mechanism uses the namecache only and the underlying
2591 * directory vnode is not a special case.
2593 int bsize, maxsize;
2595 if (vp->v_type == VBLK || vp->v_type == VCHR)
2596 bsize = DEV_BSIZE;
2597 else if (vp->v_mount)
2598 bsize = vp->v_mount->mnt_stat.f_iosize;
2599 else
2600 bsize = size;
2602 maxsize = size + (loffset & PAGE_MASK);
2603 maxsize = imax(maxsize, bsize);
2605 if ((bp = getnewbuf(blkflags, slptimeo, size, maxsize)) == NULL) {
2606 if (slpflags || slptimeo) {
2607 crit_exit();
2608 return NULL;
2610 goto loop;
2614 * This code is used to make sure that a buffer is not
2615 * created while the getnewbuf routine is blocked.
2616 * This can be a problem whether the vnode is locked or not.
2617 * If the buffer is created out from under us, we have to
2618 * throw away the one we just created. There is no window
2619 * race because we are safely running in a critical section
2620 * from the point of the duplicate buffer creation through
2621 * to here, and we've locked the buffer.
2623 if (findblk(vp, loffset)) {
2624 bp->b_flags |= B_INVAL;
2625 brelse(bp);
2626 goto loop;
2630 * Insert the buffer into the hash, so that it can
2631 * be found by findblk().
2633 * Make sure the translation layer has been cleared.
2635 bp->b_loffset = loffset;
2636 bp->b_bio2.bio_offset = NOOFFSET;
2637 /* bp->b_bio2.bio_next = NULL; */
2639 bgetvp(vp, bp);
2642 * All vnode-based buffers must be backed by a VM object.
2644 KKASSERT(vp->v_object != NULL);
2645 bp->b_flags |= B_VMIO;
2646 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2648 allocbuf(bp, size);
2650 crit_exit();
2652 return (bp);
2656 * regetblk(bp)
2658 * Reacquire a buffer that was previously released to the locked queue,
2659 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2660 * set B_LOCKED (which handles the acquisition race).
2662 * To this end, either B_LOCKED must be set or the dependancy list must be
2663 * non-empty.
2665 void
2666 regetblk(struct buf *bp)
2668 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2669 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2670 crit_enter();
2671 bremfree(bp);
2672 crit_exit();
2676 * geteblk:
2678 * Get an empty, disassociated buffer of given size. The buffer is
2679 * initially set to B_INVAL.
2681 * critical section protection is not required for the allocbuf()
2682 * call because races are impossible here.
2684 struct buf *
2685 geteblk(int size)
2687 struct buf *bp;
2688 int maxsize;
2690 maxsize = (size + BKVAMASK) & ~BKVAMASK;
2692 crit_enter();
2693 while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2695 crit_exit();
2696 allocbuf(bp, size);
2697 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2698 return (bp);
2703 * allocbuf:
2705 * This code constitutes the buffer memory from either anonymous system
2706 * memory (in the case of non-VMIO operations) or from an associated
2707 * VM object (in the case of VMIO operations). This code is able to
2708 * resize a buffer up or down.
2710 * Note that this code is tricky, and has many complications to resolve
2711 * deadlock or inconsistant data situations. Tread lightly!!!
2712 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
2713 * the caller. Calling this code willy nilly can result in the loss of data.
2715 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
2716 * B_CACHE for the non-VMIO case.
2718 * This routine does not need to be called from a critical section but you
2719 * must own the buffer.
2722 allocbuf(struct buf *bp, int size)
2724 int newbsize, mbsize;
2725 int i;
2727 if (BUF_REFCNT(bp) == 0)
2728 panic("allocbuf: buffer not busy");
2730 if (bp->b_kvasize < size)
2731 panic("allocbuf: buffer too small");
2733 if ((bp->b_flags & B_VMIO) == 0) {
2734 caddr_t origbuf;
2735 int origbufsize;
2737 * Just get anonymous memory from the kernel. Don't
2738 * mess with B_CACHE.
2740 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2741 if (bp->b_flags & B_MALLOC)
2742 newbsize = mbsize;
2743 else
2744 newbsize = round_page(size);
2746 if (newbsize < bp->b_bufsize) {
2748 * Malloced buffers are not shrunk
2750 if (bp->b_flags & B_MALLOC) {
2751 if (newbsize) {
2752 bp->b_bcount = size;
2753 } else {
2754 kfree(bp->b_data, M_BIOBUF);
2755 if (bp->b_bufsize) {
2756 bufmallocspace -= bp->b_bufsize;
2757 bufspacewakeup();
2758 bp->b_bufsize = 0;
2760 bp->b_data = bp->b_kvabase;
2761 bp->b_bcount = 0;
2762 bp->b_flags &= ~B_MALLOC;
2764 return 1;
2766 vm_hold_free_pages(
2768 (vm_offset_t) bp->b_data + newbsize,
2769 (vm_offset_t) bp->b_data + bp->b_bufsize);
2770 } else if (newbsize > bp->b_bufsize) {
2772 * We only use malloced memory on the first allocation.
2773 * and revert to page-allocated memory when the buffer
2774 * grows.
2776 if ((bufmallocspace < maxbufmallocspace) &&
2777 (bp->b_bufsize == 0) &&
2778 (mbsize <= PAGE_SIZE/2)) {
2780 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
2781 bp->b_bufsize = mbsize;
2782 bp->b_bcount = size;
2783 bp->b_flags |= B_MALLOC;
2784 bufmallocspace += mbsize;
2785 return 1;
2787 origbuf = NULL;
2788 origbufsize = 0;
2790 * If the buffer is growing on its other-than-first
2791 * allocation, then we revert to the page-allocation
2792 * scheme.
2794 if (bp->b_flags & B_MALLOC) {
2795 origbuf = bp->b_data;
2796 origbufsize = bp->b_bufsize;
2797 bp->b_data = bp->b_kvabase;
2798 if (bp->b_bufsize) {
2799 bufmallocspace -= bp->b_bufsize;
2800 bufspacewakeup();
2801 bp->b_bufsize = 0;
2803 bp->b_flags &= ~B_MALLOC;
2804 newbsize = round_page(newbsize);
2806 vm_hold_load_pages(
2808 (vm_offset_t) bp->b_data + bp->b_bufsize,
2809 (vm_offset_t) bp->b_data + newbsize);
2810 if (origbuf) {
2811 bcopy(origbuf, bp->b_data, origbufsize);
2812 kfree(origbuf, M_BIOBUF);
2815 } else {
2816 vm_page_t m;
2817 int desiredpages;
2819 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2820 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
2821 newbsize + PAGE_MASK) >> PAGE_SHIFT;
2822 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
2824 if (bp->b_flags & B_MALLOC)
2825 panic("allocbuf: VMIO buffer can't be malloced");
2827 * Set B_CACHE initially if buffer is 0 length or will become
2828 * 0-length.
2830 if (size == 0 || bp->b_bufsize == 0)
2831 bp->b_flags |= B_CACHE;
2833 if (newbsize < bp->b_bufsize) {
2835 * DEV_BSIZE aligned new buffer size is less then the
2836 * DEV_BSIZE aligned existing buffer size. Figure out
2837 * if we have to remove any pages.
2839 if (desiredpages < bp->b_xio.xio_npages) {
2840 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2842 * the page is not freed here -- it
2843 * is the responsibility of
2844 * vnode_pager_setsize
2846 m = bp->b_xio.xio_pages[i];
2847 KASSERT(m != bogus_page,
2848 ("allocbuf: bogus page found"));
2849 while (vm_page_sleep_busy(m, TRUE, "biodep"))
2852 bp->b_xio.xio_pages[i] = NULL;
2853 vm_page_unwire(m, 0);
2855 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2856 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2857 bp->b_xio.xio_npages = desiredpages;
2859 } else if (size > bp->b_bcount) {
2861 * We are growing the buffer, possibly in a
2862 * byte-granular fashion.
2864 struct vnode *vp;
2865 vm_object_t obj;
2866 vm_offset_t toff;
2867 vm_offset_t tinc;
2870 * Step 1, bring in the VM pages from the object,
2871 * allocating them if necessary. We must clear
2872 * B_CACHE if these pages are not valid for the
2873 * range covered by the buffer.
2875 * critical section protection is required to protect
2876 * against interrupts unbusying and freeing pages
2877 * between our vm_page_lookup() and our
2878 * busycheck/wiring call.
2880 vp = bp->b_vp;
2881 obj = vp->v_object;
2883 crit_enter();
2884 while (bp->b_xio.xio_npages < desiredpages) {
2885 vm_page_t m;
2886 vm_pindex_t pi;
2888 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
2889 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2891 * note: must allocate system pages
2892 * since blocking here could intefere
2893 * with paging I/O, no matter which
2894 * process we are.
2896 m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages);
2897 if (m) {
2898 vm_page_wire(m);
2899 vm_page_wakeup(m);
2900 bp->b_flags &= ~B_CACHE;
2901 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2902 ++bp->b_xio.xio_npages;
2904 continue;
2908 * We found a page. If we have to sleep on it,
2909 * retry because it might have gotten freed out
2910 * from under us.
2912 * We can only test PG_BUSY here. Blocking on
2913 * m->busy might lead to a deadlock:
2915 * vm_fault->getpages->cluster_read->allocbuf
2919 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
2920 continue;
2923 * We have a good page. Should we wakeup the
2924 * page daemon?
2926 if ((curthread != pagethread) &&
2927 ((m->queue - m->pc) == PQ_CACHE) &&
2928 ((vmstats.v_free_count + vmstats.v_cache_count) <
2929 (vmstats.v_free_min + vmstats.v_cache_min))) {
2930 pagedaemon_wakeup();
2932 vm_page_flag_clear(m, PG_ZERO);
2933 vm_page_wire(m);
2934 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
2935 ++bp->b_xio.xio_npages;
2937 crit_exit();
2940 * Step 2. We've loaded the pages into the buffer,
2941 * we have to figure out if we can still have B_CACHE
2942 * set. Note that B_CACHE is set according to the
2943 * byte-granular range ( bcount and size ), not the
2944 * aligned range ( newbsize ).
2946 * The VM test is against m->valid, which is DEV_BSIZE
2947 * aligned. Needless to say, the validity of the data
2948 * needs to also be DEV_BSIZE aligned. Note that this
2949 * fails with NFS if the server or some other client
2950 * extends the file's EOF. If our buffer is resized,
2951 * B_CACHE may remain set! XXX
2954 toff = bp->b_bcount;
2955 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
2957 while ((bp->b_flags & B_CACHE) && toff < size) {
2958 vm_pindex_t pi;
2960 if (tinc > (size - toff))
2961 tinc = size - toff;
2963 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
2964 PAGE_SHIFT;
2966 vfs_buf_test_cache(
2967 bp,
2968 bp->b_loffset,
2969 toff,
2970 tinc,
2971 bp->b_xio.xio_pages[pi]
2973 toff += tinc;
2974 tinc = PAGE_SIZE;
2978 * Step 3, fixup the KVM pmap. Remember that
2979 * bp->b_data is relative to bp->b_loffset, but
2980 * bp->b_loffset may be offset into the first page.
2983 bp->b_data = (caddr_t)
2984 trunc_page((vm_offset_t)bp->b_data);
2985 pmap_qenter(
2986 (vm_offset_t)bp->b_data,
2987 bp->b_xio.xio_pages,
2988 bp->b_xio.xio_npages
2990 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
2991 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
2995 /* adjust space use on already-dirty buffer */
2996 if (bp->b_flags & B_DELWRI) {
2997 dirtybufspace += newbsize - bp->b_bufsize;
2998 if (bp->b_flags & B_HEAVY)
2999 dirtybufspacehw += newbsize - bp->b_bufsize;
3001 if (newbsize < bp->b_bufsize)
3002 bufspacewakeup();
3003 bp->b_bufsize = newbsize; /* actual buffer allocation */
3004 bp->b_bcount = size; /* requested buffer size */
3005 return 1;
3009 * biowait:
3011 * Wait for buffer I/O completion, returning error status. The buffer
3012 * is left locked on return. B_EINTR is converted into an EINTR error
3013 * and cleared.
3015 * NOTE! The original b_cmd is lost on return, since b_cmd will be
3016 * set to BUF_CMD_DONE.
3019 biowait(struct buf *bp)
3021 crit_enter();
3022 while (bp->b_cmd != BUF_CMD_DONE) {
3023 if (bp->b_cmd == BUF_CMD_READ)
3024 tsleep(bp, 0, "biord", 0);
3025 else
3026 tsleep(bp, 0, "biowr", 0);
3028 crit_exit();
3029 if (bp->b_flags & B_EINTR) {
3030 bp->b_flags &= ~B_EINTR;
3031 return (EINTR);
3033 if (bp->b_flags & B_ERROR) {
3034 return (bp->b_error ? bp->b_error : EIO);
3035 } else {
3036 return (0);
3041 * This associates a tracking count with an I/O. vn_strategy() and
3042 * dev_dstrategy() do this automatically but there are a few cases
3043 * where a vnode or device layer is bypassed when a block translation
3044 * is cached. In such cases bio_start_transaction() may be called on
3045 * the bypassed layers so the system gets an I/O in progress indication
3046 * for those higher layers.
3048 void
3049 bio_start_transaction(struct bio *bio, struct bio_track *track)
3051 bio->bio_track = track;
3052 atomic_add_int(&track->bk_active, 1);
3056 * Initiate I/O on a vnode.
3058 void
3059 vn_strategy(struct vnode *vp, struct bio *bio)
3061 struct bio_track *track;
3063 KKASSERT(bio->bio_buf->b_cmd != BUF_CMD_DONE);
3064 if (bio->bio_buf->b_cmd == BUF_CMD_READ)
3065 track = &vp->v_track_read;
3066 else
3067 track = &vp->v_track_write;
3068 bio->bio_track = track;
3069 atomic_add_int(&track->bk_active, 1);
3070 vop_strategy(*vp->v_ops, vp, bio);
3075 * biodone:
3077 * Finish I/O on a buffer, optionally calling a completion function.
3078 * This is usually called from an interrupt so process blocking is
3079 * not allowed.
3081 * biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3082 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3083 * assuming B_INVAL is clear.
3085 * For the VMIO case, we set B_CACHE if the op was a read and no
3086 * read error occured, or if the op was a write. B_CACHE is never
3087 * set if the buffer is invalid or otherwise uncacheable.
3089 * biodone does not mess with B_INVAL, allowing the I/O routine or the
3090 * initiator to leave B_INVAL set to brelse the buffer out of existance
3091 * in the biodone routine.
3093 void
3094 biodone(struct bio *bio)
3096 struct buf *bp = bio->bio_buf;
3097 buf_cmd_t cmd;
3099 crit_enter();
3101 KASSERT(BUF_REFCNTNB(bp) > 0,
3102 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3103 KASSERT(bp->b_cmd != BUF_CMD_DONE,
3104 ("biodone: bp %p already done!", bp));
3106 runningbufwakeup(bp);
3109 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
3111 while (bio) {
3112 biodone_t *done_func;
3113 struct bio_track *track;
3116 * BIO tracking. Most but not all BIOs are tracked.
3118 if ((track = bio->bio_track) != NULL) {
3119 atomic_subtract_int(&track->bk_active, 1);
3120 if (track->bk_active < 0) {
3121 panic("biodone: bad active count bio %p\n",
3122 bio);
3124 if (track->bk_waitflag) {
3125 track->bk_waitflag = 0;
3126 wakeup(track);
3128 bio->bio_track = NULL;
3132 * A bio_done function terminates the loop. The function
3133 * will be responsible for any further chaining and/or
3134 * buffer management.
3136 * WARNING! The done function can deallocate the buffer!
3138 if ((done_func = bio->bio_done) != NULL) {
3139 bio->bio_done = NULL;
3140 done_func(bio);
3141 crit_exit();
3142 return;
3144 bio = bio->bio_prev;
3147 cmd = bp->b_cmd;
3148 bp->b_cmd = BUF_CMD_DONE;
3151 * Only reads and writes are processed past this point.
3153 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3154 brelse(bp);
3155 crit_exit();
3156 return;
3160 * Warning: softupdates may re-dirty the buffer.
3162 if (LIST_FIRST(&bp->b_dep) != NULL)
3163 buf_complete(bp);
3165 if (bp->b_flags & B_VMIO) {
3166 int i;
3167 vm_ooffset_t foff;
3168 vm_page_t m;
3169 vm_object_t obj;
3170 int iosize;
3171 struct vnode *vp = bp->b_vp;
3173 obj = vp->v_object;
3175 #if defined(VFS_BIO_DEBUG)
3176 if (vp->v_auxrefs == 0)
3177 panic("biodone: zero vnode hold count");
3178 if ((vp->v_flag & VOBJBUF) == 0)
3179 panic("biodone: vnode is not setup for merged cache");
3180 #endif
3182 foff = bp->b_loffset;
3183 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3184 KASSERT(obj != NULL, ("biodone: missing VM object"));
3186 #if defined(VFS_BIO_DEBUG)
3187 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3188 kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3189 obj->paging_in_progress, bp->b_xio.xio_npages);
3191 #endif
3194 * Set B_CACHE if the op was a normal read and no error
3195 * occured. B_CACHE is set for writes in the b*write()
3196 * routines.
3198 iosize = bp->b_bcount - bp->b_resid;
3199 if (cmd == BUF_CMD_READ && (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3200 bp->b_flags |= B_CACHE;
3203 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3204 int bogusflag = 0;
3205 int resid;
3207 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3208 if (resid > iosize)
3209 resid = iosize;
3212 * cleanup bogus pages, restoring the originals. Since
3213 * the originals should still be wired, we don't have
3214 * to worry about interrupt/freeing races destroying
3215 * the VM object association.
3217 m = bp->b_xio.xio_pages[i];
3218 if (m == bogus_page) {
3219 bogusflag = 1;
3220 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3221 if (m == NULL)
3222 panic("biodone: page disappeared");
3223 bp->b_xio.xio_pages[i] = m;
3224 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3225 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3227 #if defined(VFS_BIO_DEBUG)
3228 if (OFF_TO_IDX(foff) != m->pindex) {
3229 kprintf(
3230 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3231 (unsigned long)foff, m->pindex);
3233 #endif
3236 * In the write case, the valid and clean bits are
3237 * already changed correctly ( see bdwrite() ), so we
3238 * only need to do this here in the read case.
3240 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3241 vfs_page_set_valid(bp, foff, i, m);
3243 vm_page_flag_clear(m, PG_ZERO);
3246 * when debugging new filesystems or buffer I/O methods, this
3247 * is the most common error that pops up. if you see this, you
3248 * have not set the page busy flag correctly!!!
3250 if (m->busy == 0) {
3251 kprintf("biodone: page busy < 0, "
3252 "pindex: %d, foff: 0x(%x,%x), "
3253 "resid: %d, index: %d\n",
3254 (int) m->pindex, (int)(foff >> 32),
3255 (int) foff & 0xffffffff, resid, i);
3256 if (!vn_isdisk(vp, NULL))
3257 kprintf(" iosize: %ld, loffset: %lld, flags: 0x%08x, npages: %d\n",
3258 bp->b_vp->v_mount->mnt_stat.f_iosize,
3259 bp->b_loffset,
3260 bp->b_flags, bp->b_xio.xio_npages);
3261 else
3262 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3263 bp->b_loffset,
3264 bp->b_flags, bp->b_xio.xio_npages);
3265 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3266 m->valid, m->dirty, m->wire_count);
3267 panic("biodone: page busy < 0");
3269 vm_page_io_finish(m);
3270 vm_object_pip_subtract(obj, 1);
3271 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3272 iosize -= resid;
3274 if (obj)
3275 vm_object_pip_wakeupn(obj, 0);
3279 * For asynchronous completions, release the buffer now. The brelse
3280 * will do a wakeup there if necessary - so no need to do a wakeup
3281 * here in the async case. The sync case always needs to do a wakeup.
3284 if (bp->b_flags & B_ASYNC) {
3285 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3286 brelse(bp);
3287 else
3288 bqrelse(bp);
3289 } else {
3290 wakeup(bp);
3292 crit_exit();
3296 * vfs_unbusy_pages:
3298 * This routine is called in lieu of iodone in the case of
3299 * incomplete I/O. This keeps the busy status for pages
3300 * consistant.
3302 void
3303 vfs_unbusy_pages(struct buf *bp)
3305 int i;
3307 runningbufwakeup(bp);
3308 if (bp->b_flags & B_VMIO) {
3309 struct vnode *vp = bp->b_vp;
3310 vm_object_t obj;
3312 obj = vp->v_object;
3314 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3315 vm_page_t m = bp->b_xio.xio_pages[i];
3318 * When restoring bogus changes the original pages
3319 * should still be wired, so we are in no danger of
3320 * losing the object association and do not need
3321 * critical section protection particularly.
3323 if (m == bogus_page) {
3324 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3325 if (!m) {
3326 panic("vfs_unbusy_pages: page missing");
3328 bp->b_xio.xio_pages[i] = m;
3329 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3330 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3332 vm_object_pip_subtract(obj, 1);
3333 vm_page_flag_clear(m, PG_ZERO);
3334 vm_page_io_finish(m);
3336 vm_object_pip_wakeupn(obj, 0);
3341 * vfs_page_set_valid:
3343 * Set the valid bits in a page based on the supplied offset. The
3344 * range is restricted to the buffer's size.
3346 * This routine is typically called after a read completes.
3348 static void
3349 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3351 vm_ooffset_t soff, eoff;
3354 * Start and end offsets in buffer. eoff - soff may not cross a
3355 * page boundry or cross the end of the buffer. The end of the
3356 * buffer, in this case, is our file EOF, not the allocation size
3357 * of the buffer.
3359 soff = off;
3360 eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3361 if (eoff > bp->b_loffset + bp->b_bcount)
3362 eoff = bp->b_loffset + bp->b_bcount;
3365 * Set valid range. This is typically the entire buffer and thus the
3366 * entire page.
3368 if (eoff > soff) {
3369 vm_page_set_validclean(
3371 (vm_offset_t) (soff & PAGE_MASK),
3372 (vm_offset_t) (eoff - soff)
3378 * vfs_busy_pages:
3380 * This routine is called before a device strategy routine.
3381 * It is used to tell the VM system that paging I/O is in
3382 * progress, and treat the pages associated with the buffer
3383 * almost as being PG_BUSY. Also the object 'paging_in_progress'
3384 * flag is handled to make sure that the object doesn't become
3385 * inconsistant.
3387 * Since I/O has not been initiated yet, certain buffer flags
3388 * such as B_ERROR or B_INVAL may be in an inconsistant state
3389 * and should be ignored.
3391 void
3392 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3394 int i, bogus;
3395 struct lwp *lp = curthread->td_lwp;
3398 * The buffer's I/O command must already be set. If reading,
3399 * B_CACHE must be 0 (double check against callers only doing
3400 * I/O when B_CACHE is 0).
3402 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3403 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3405 if (bp->b_flags & B_VMIO) {
3406 vm_object_t obj;
3407 vm_ooffset_t foff;
3409 obj = vp->v_object;
3410 foff = bp->b_loffset;
3411 KASSERT(bp->b_loffset != NOOFFSET,
3412 ("vfs_busy_pages: no buffer offset"));
3413 vfs_setdirty(bp);
3416 * Loop until none of the pages are busy.
3418 retry:
3419 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3420 vm_page_t m = bp->b_xio.xio_pages[i];
3422 if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3423 goto retry;
3427 * Setup for I/O, soft-busy the page right now because
3428 * the next loop may block.
3430 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3431 vm_page_t m = bp->b_xio.xio_pages[i];
3433 vm_page_flag_clear(m, PG_ZERO);
3434 if ((bp->b_flags & B_CLUSTER) == 0) {
3435 vm_object_pip_add(obj, 1);
3436 vm_page_io_start(m);
3441 * Adjust protections for I/O and do bogus-page mapping.
3442 * Assume that vm_page_protect() can block (it can block
3443 * if VM_PROT_NONE, don't take any chances regardless).
3445 bogus = 0;
3446 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3447 vm_page_t m = bp->b_xio.xio_pages[i];
3450 * When readying a vnode-backed buffer for a write
3451 * we must zero-fill any invalid portions of the
3452 * backing VM pages.
3454 * When readying a vnode-backed buffer for a read
3455 * we must replace any dirty pages with a bogus
3456 * page so we do not destroy dirty data when
3457 * filling in gaps. Dirty pages might not
3458 * necessarily be marked dirty yet, so use m->valid
3459 * as a reasonable test.
3461 * Bogus page replacement is, uh, bogus. We need
3462 * to find a better way.
3464 if (bp->b_cmd == BUF_CMD_WRITE) {
3465 vm_page_protect(m, VM_PROT_READ);
3466 vfs_page_set_valid(bp, foff, i, m);
3467 } else if (m->valid == VM_PAGE_BITS_ALL) {
3468 bp->b_xio.xio_pages[i] = bogus_page;
3469 bogus++;
3470 } else {
3471 vm_page_protect(m, VM_PROT_NONE);
3473 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3475 if (bogus)
3476 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3477 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3481 * This is the easiest place to put the process accounting for the I/O
3482 * for now.
3484 if (lp != NULL) {
3485 if (bp->b_cmd == BUF_CMD_READ)
3486 lp->lwp_ru.ru_inblock++;
3487 else
3488 lp->lwp_ru.ru_oublock++;
3493 * vfs_clean_pages:
3495 * Tell the VM system that the pages associated with this buffer
3496 * are clean. This is used for delayed writes where the data is
3497 * going to go to disk eventually without additional VM intevention.
3499 * Note that while we only really need to clean through to b_bcount, we
3500 * just go ahead and clean through to b_bufsize.
3502 static void
3503 vfs_clean_pages(struct buf *bp)
3505 int i;
3507 if (bp->b_flags & B_VMIO) {
3508 vm_ooffset_t foff;
3510 foff = bp->b_loffset;
3511 KASSERT(foff != NOOFFSET, ("vfs_clean_pages: no buffer offset"));
3512 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3513 vm_page_t m = bp->b_xio.xio_pages[i];
3514 vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3515 vm_ooffset_t eoff = noff;
3517 if (eoff > bp->b_loffset + bp->b_bufsize)
3518 eoff = bp->b_loffset + bp->b_bufsize;
3519 vfs_page_set_valid(bp, foff, i, m);
3520 /* vm_page_clear_dirty(m, foff & PAGE_MASK, eoff - foff); */
3521 foff = noff;
3527 * vfs_bio_set_validclean:
3529 * Set the range within the buffer to valid and clean. The range is
3530 * relative to the beginning of the buffer, b_loffset. Note that
3531 * b_loffset itself may be offset from the beginning of the first page.
3534 void
3535 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3537 if (bp->b_flags & B_VMIO) {
3538 int i;
3539 int n;
3542 * Fixup base to be relative to beginning of first page.
3543 * Set initial n to be the maximum number of bytes in the
3544 * first page that can be validated.
3547 base += (bp->b_loffset & PAGE_MASK);
3548 n = PAGE_SIZE - (base & PAGE_MASK);
3550 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3551 vm_page_t m = bp->b_xio.xio_pages[i];
3553 if (n > size)
3554 n = size;
3556 vm_page_set_validclean(m, base & PAGE_MASK, n);
3557 base += n;
3558 size -= n;
3559 n = PAGE_SIZE;
3565 * vfs_bio_clrbuf:
3567 * Clear a buffer. This routine essentially fakes an I/O, so we need
3568 * to clear B_ERROR and B_INVAL.
3570 * Note that while we only theoretically need to clear through b_bcount,
3571 * we go ahead and clear through b_bufsize.
3574 void
3575 vfs_bio_clrbuf(struct buf *bp)
3577 int i, mask = 0;
3578 caddr_t sa, ea;
3579 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3580 bp->b_flags &= ~(B_INVAL|B_ERROR);
3581 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3582 (bp->b_loffset & PAGE_MASK) == 0) {
3583 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3584 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3585 bp->b_resid = 0;
3586 return;
3588 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3589 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3590 bzero(bp->b_data, bp->b_bufsize);
3591 bp->b_xio.xio_pages[0]->valid |= mask;
3592 bp->b_resid = 0;
3593 return;
3596 ea = sa = bp->b_data;
3597 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3598 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3599 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3600 ea = (caddr_t)(vm_offset_t)ulmin(
3601 (u_long)(vm_offset_t)ea,
3602 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3603 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3604 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3605 continue;
3606 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3607 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3608 bzero(sa, ea - sa);
3610 } else {
3611 for (; sa < ea; sa += DEV_BSIZE, j++) {
3612 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3613 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3614 bzero(sa, DEV_BSIZE);
3617 bp->b_xio.xio_pages[i]->valid |= mask;
3618 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3620 bp->b_resid = 0;
3621 } else {
3622 clrbuf(bp);
3627 * vm_hold_load_pages:
3629 * Load pages into the buffer's address space. The pages are
3630 * allocated from the kernel object in order to reduce interference
3631 * with the any VM paging I/O activity. The range of loaded
3632 * pages will be wired.
3634 * If a page cannot be allocated, the 'pagedaemon' is woken up to
3635 * retrieve the full range (to - from) of pages.
3638 void
3639 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3641 vm_offset_t pg;
3642 vm_page_t p;
3643 int index;
3645 to = round_page(to);
3646 from = round_page(from);
3647 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3649 pg = from;
3650 while (pg < to) {
3652 * Note: must allocate system pages since blocking here
3653 * could intefere with paging I/O, no matter which
3654 * process we are.
3656 p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT,
3657 (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
3658 if (p) {
3659 vm_page_wire(p);
3660 p->valid = VM_PAGE_BITS_ALL;
3661 vm_page_flag_clear(p, PG_ZERO);
3662 pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3663 bp->b_xio.xio_pages[index] = p;
3664 vm_page_wakeup(p);
3666 pg += PAGE_SIZE;
3667 ++index;
3670 bp->b_xio.xio_npages = index;
3674 * Allocate pages for a buffer cache buffer.
3676 * Under extremely severe memory conditions even allocating out of the
3677 * system reserve can fail. If this occurs we must allocate out of the
3678 * interrupt reserve to avoid a deadlock with the pageout daemon.
3680 * The pageout daemon can run (putpages -> VOP_WRITE -> getblk -> allocbuf).
3681 * If the buffer cache's vm_page_alloc() fails a vm_wait() can deadlock
3682 * against the pageout daemon if pages are not freed from other sources.
3684 static
3685 vm_page_t
3686 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit)
3688 vm_page_t p;
3691 * Try a normal allocation, allow use of system reserve.
3693 p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3694 if (p)
3695 return(p);
3698 * The normal allocation failed and we clearly have a page
3699 * deficit. Try to reclaim some clean VM pages directly
3700 * from the buffer cache.
3702 vm_pageout_deficit += deficit;
3703 recoverbufpages();
3706 * We may have blocked, the caller will know what to do if the
3707 * page now exists.
3709 if (vm_page_lookup(obj, pg))
3710 return(NULL);
3713 * Allocate and allow use of the interrupt reserve.
3715 * If after all that we still can't allocate a VM page we are
3716 * in real trouble, but we slog on anyway hoping that the system
3717 * won't deadlock.
3719 p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
3720 VM_ALLOC_INTERRUPT);
3721 if (p) {
3722 if (vm_page_count_severe()) {
3723 kprintf("bio_page_alloc: WARNING emergency page "
3724 "allocation\n");
3725 vm_wait(hz / 20);
3727 } else {
3728 kprintf("bio_page_alloc: WARNING emergency page "
3729 "allocation failed\n");
3730 vm_wait(hz * 5);
3732 return(p);
3736 * vm_hold_free_pages:
3738 * Return pages associated with the buffer back to the VM system.
3740 * The range of pages underlying the buffer's address space will
3741 * be unmapped and un-wired.
3743 void
3744 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3746 vm_offset_t pg;
3747 vm_page_t p;
3748 int index, newnpages;
3750 from = round_page(from);
3751 to = round_page(to);
3752 newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3754 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3755 p = bp->b_xio.xio_pages[index];
3756 if (p && (index < bp->b_xio.xio_npages)) {
3757 if (p->busy) {
3758 kprintf("vm_hold_free_pages: doffset: %lld, loffset: %lld\n",
3759 bp->b_bio2.bio_offset, bp->b_loffset);
3761 bp->b_xio.xio_pages[index] = NULL;
3762 pmap_kremove(pg);
3763 vm_page_busy(p);
3764 vm_page_unwire(p, 0);
3765 vm_page_free(p);
3768 bp->b_xio.xio_npages = newnpages;
3772 * vmapbuf:
3774 * Map a user buffer into KVM via a pbuf. On return the buffer's
3775 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3776 * initialized.
3779 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
3781 caddr_t addr;
3782 vm_offset_t va;
3783 vm_page_t m;
3784 int vmprot;
3785 int error;
3786 int pidx;
3787 int i;
3790 * bp had better have a command and it better be a pbuf.
3792 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3793 KKASSERT(bp->b_flags & B_PAGING);
3795 if (bytes < 0)
3796 return (-1);
3799 * Map the user data into KVM. Mappings have to be page-aligned.
3801 addr = (caddr_t)trunc_page((vm_offset_t)udata);
3802 pidx = 0;
3804 vmprot = VM_PROT_READ;
3805 if (bp->b_cmd == BUF_CMD_READ)
3806 vmprot |= VM_PROT_WRITE;
3808 while (addr < udata + bytes) {
3810 * Do the vm_fault if needed; do the copy-on-write thing
3811 * when reading stuff off device into memory.
3813 * vm_fault_page*() returns a held VM page.
3815 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
3816 va = trunc_page(va);
3818 m = vm_fault_page_quick(va, vmprot, &error);
3819 if (m == NULL) {
3820 for (i = 0; i < pidx; ++i) {
3821 vm_page_unhold(bp->b_xio.xio_pages[i]);
3822 bp->b_xio.xio_pages[i] = NULL;
3824 return(-1);
3826 bp->b_xio.xio_pages[pidx] = m;
3827 addr += PAGE_SIZE;
3828 ++pidx;
3832 * Map the page array and set the buffer fields to point to
3833 * the mapped data buffer.
3835 if (pidx > btoc(MAXPHYS))
3836 panic("vmapbuf: mapped more than MAXPHYS");
3837 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
3839 bp->b_xio.xio_npages = pidx;
3840 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
3841 bp->b_bcount = bytes;
3842 bp->b_bufsize = bytes;
3843 return(0);
3847 * vunmapbuf:
3849 * Free the io map PTEs associated with this IO operation.
3850 * We also invalidate the TLB entries and restore the original b_addr.
3852 void
3853 vunmapbuf(struct buf *bp)
3855 int pidx;
3856 int npages;
3858 KKASSERT(bp->b_flags & B_PAGING);
3860 npages = bp->b_xio.xio_npages;
3861 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3862 for (pidx = 0; pidx < npages; ++pidx) {
3863 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
3864 bp->b_xio.xio_pages[pidx] = NULL;
3866 bp->b_xio.xio_npages = 0;
3867 bp->b_data = bp->b_kvabase;
3871 * Scan all buffers in the system and issue the callback.
3874 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
3876 int count = 0;
3877 int error;
3878 int n;
3880 for (n = 0; n < nbuf; ++n) {
3881 if ((error = callback(&buf[n], info)) < 0) {
3882 count = error;
3883 break;
3885 count += error;
3887 return (count);
3891 * print out statistics from the current status of the buffer pool
3892 * this can be toggeled by the system control option debug.syncprt
3894 #ifdef DEBUG
3895 void
3896 vfs_bufstats(void)
3898 int i, j, count;
3899 struct buf *bp;
3900 struct bqueues *dp;
3901 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
3902 static char *bname[3] = { "LOCKED", "LRU", "AGE" };
3904 for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
3905 count = 0;
3906 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3907 counts[j] = 0;
3908 crit_enter();
3909 TAILQ_FOREACH(bp, dp, b_freelist) {
3910 counts[bp->b_bufsize/PAGE_SIZE]++;
3911 count++;
3913 crit_exit();
3914 kprintf("%s: total-%d", bname[i], count);
3915 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
3916 if (counts[j] != 0)
3917 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
3918 kprintf("\n");
3921 #endif
3923 #ifdef DDB
3925 DB_SHOW_COMMAND(buffer, db_show_buffer)
3927 /* get args */
3928 struct buf *bp = (struct buf *)addr;
3930 if (!have_addr) {
3931 db_printf("usage: show buffer <addr>\n");
3932 return;
3935 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
3936 db_printf("b_cmd = %d\n", bp->b_cmd);
3937 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
3938 "b_resid = %d\n, b_data = %p, "
3939 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
3940 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
3941 bp->b_data, bp->b_bio2.bio_offset, (bp->b_bio2.bio_next ? bp->b_bio2.bio_next->bio_offset : (off_t)-1));
3942 if (bp->b_xio.xio_npages) {
3943 int i;
3944 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
3945 bp->b_xio.xio_npages);
3946 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3947 vm_page_t m;
3948 m = bp->b_xio.xio_pages[i];
3949 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
3950 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
3951 if ((i + 1) < bp->b_xio.xio_npages)
3952 db_printf(",");
3954 db_printf("\n");
3957 #endif /* DDB */