kernel - Refactor Xinvltlb (3)
[dragonfly.git] / sys / kern / vfs_bio.c
blob1a54f4dada5f830d0fab94930c94135d94344189
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 $
18 * this file contains a new buffer I/O scheme implementing a coherent
19 * VM object and buffer cache scheme. Pains have been taken to make
20 * sure that the performance degradation associated with schemes such
21 * as this is not realized.
23 * Author: John S. Dyson
24 * Significant help during the development and debugging phases
25 * had been provided by David Greenman, also of the FreeBSD core team.
27 * see man buf(9) for more info. Note that man buf(9) doesn't reflect
28 * the actual buf/bio implementation in DragonFly.
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/buf.h>
34 #include <sys/conf.h>
35 #include <sys/devicestat.h>
36 #include <sys/eventhandler.h>
37 #include <sys/lock.h>
38 #include <sys/malloc.h>
39 #include <sys/mount.h>
40 #include <sys/kernel.h>
41 #include <sys/kthread.h>
42 #include <sys/proc.h>
43 #include <sys/reboot.h>
44 #include <sys/resourcevar.h>
45 #include <sys/sysctl.h>
46 #include <sys/vmmeter.h>
47 #include <sys/vnode.h>
48 #include <sys/dsched.h>
49 #include <vm/vm.h>
50 #include <vm/vm_param.h>
51 #include <vm/vm_kern.h>
52 #include <vm/vm_pageout.h>
53 #include <vm/vm_page.h>
54 #include <vm/vm_object.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_map.h>
57 #include <vm/vm_pager.h>
58 #include <vm/swap_pager.h>
60 #include <sys/buf2.h>
61 #include <sys/thread2.h>
62 #include <sys/spinlock2.h>
63 #include <sys/mplock2.h>
64 #include <vm/vm_page2.h>
66 #include "opt_ddb.h"
67 #ifdef DDB
68 #include <ddb/ddb.h>
69 #endif
72 * Buffer queues.
74 enum bufq_type {
75 BQUEUE_NONE, /* not on any queue */
76 BQUEUE_LOCKED, /* locked buffers */
77 BQUEUE_CLEAN, /* non-B_DELWRI buffers */
78 BQUEUE_DIRTY, /* B_DELWRI buffers */
79 BQUEUE_DIRTY_HW, /* B_DELWRI buffers - heavy weight */
80 BQUEUE_EMPTYKVA, /* empty buffer headers with KVA assignment */
81 BQUEUE_EMPTY, /* empty buffer headers */
83 BUFFER_QUEUES /* number of buffer queues */
86 typedef enum bufq_type bufq_type_t;
88 #define BD_WAKE_SIZE 16384
89 #define BD_WAKE_MASK (BD_WAKE_SIZE - 1)
91 TAILQ_HEAD(bqueues, buf);
93 struct bufpcpu {
94 struct spinlock spin;
95 struct bqueues bufqueues[BUFFER_QUEUES];
96 } __cachealign;
98 struct bufpcpu bufpcpu[MAXCPU];
100 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
102 struct buf *buf; /* buffer header pool */
104 static void vfs_clean_pages(struct buf *bp);
105 static void vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m);
106 #if 0
107 static void vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m);
108 #endif
109 static void vfs_vmio_release(struct buf *bp);
110 static int flushbufqueues(struct buf *marker, bufq_type_t q);
111 static vm_page_t bio_page_alloc(struct buf *bp, vm_object_t obj,
112 vm_pindex_t pg, int deficit);
114 static void bd_signal(long totalspace);
115 static void buf_daemon(void);
116 static void buf_daemon_hw(void);
119 * bogus page -- for I/O to/from partially complete buffers
120 * this is a temporary solution to the problem, but it is not
121 * really that bad. it would be better to split the buffer
122 * for input in the case of buffers partially already in memory,
123 * but the code is intricate enough already.
125 vm_page_t bogus_page;
128 * These are all static, but make the ones we export globals so we do
129 * not need to use compiler magic.
131 long bufspace; /* locked by buffer_map */
132 long maxbufspace;
133 static long bufmallocspace; /* atomic ops */
134 long maxbufmallocspace, lobufspace, hibufspace;
135 static long bufreusecnt, bufdefragcnt, buffreekvacnt;
136 static long lorunningspace;
137 static long hirunningspace;
138 static long dirtykvaspace; /* atomic */
139 long dirtybufspace; /* atomic (global for systat) */
140 static long dirtybufcount; /* atomic */
141 static long dirtybufspacehw; /* atomic */
142 static long dirtybufcounthw; /* atomic */
143 static long runningbufspace; /* atomic */
144 static long runningbufcount; /* atomic */
145 long lodirtybufspace;
146 long hidirtybufspace;
147 static int getnewbufcalls;
148 static int getnewbufrestarts;
149 static int recoverbufcalls;
150 static int needsbuffer; /* atomic */
151 static int runningbufreq; /* atomic */
152 static int bd_request; /* atomic */
153 static int bd_request_hw; /* atomic */
154 static u_int bd_wake_ary[BD_WAKE_SIZE];
155 static u_int bd_wake_index;
156 static u_int vm_cycle_point = 40; /* 23-36 will migrate more act->inact */
157 static int debug_commit;
158 static int debug_bufbio;
160 static struct thread *bufdaemon_td;
161 static struct thread *bufdaemonhw_td;
162 static u_int lowmempgallocs;
163 static u_int lowmempgfails;
164 static u_int flushperqueue = 1024;
167 * Sysctls for operational control of the buffer cache.
169 SYSCTL_UINT(_vfs, OID_AUTO, flushperqueue, CTLFLAG_RW, &flushperqueue, 0,
170 "Number of buffers to flush from each per-cpu queue");
171 SYSCTL_LONG(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
172 "Number of dirty buffers to flush before bufdaemon becomes inactive");
173 SYSCTL_LONG(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
174 "High watermark used to trigger explicit flushing of dirty buffers");
175 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
176 "Minimum amount of buffer space required for active I/O");
177 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
178 "Maximum amount of buffer space to usable for active I/O");
179 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgallocs, CTLFLAG_RW, &lowmempgallocs, 0,
180 "Page allocations done during periods of very low free memory");
181 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgfails, CTLFLAG_RW, &lowmempgfails, 0,
182 "Page allocations which failed during periods of very low free memory");
183 SYSCTL_UINT(_vfs, OID_AUTO, vm_cycle_point, CTLFLAG_RW, &vm_cycle_point, 0,
184 "Recycle pages to active or inactive queue transition pt 0-64");
186 * Sysctls determining current state of the buffer cache.
188 SYSCTL_LONG(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
189 "Total number of buffers in buffer cache");
190 SYSCTL_LONG(_vfs, OID_AUTO, dirtykvaspace, CTLFLAG_RD, &dirtykvaspace, 0,
191 "KVA reserved by dirty buffers (all)");
192 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
193 "Pending bytes of dirty buffers (all)");
194 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
195 "Pending bytes of dirty buffers (heavy weight)");
196 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
197 "Pending number of dirty buffers");
198 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
199 "Pending number of dirty buffers (heavy weight)");
200 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
201 "I/O bytes currently in progress due to asynchronous writes");
202 SYSCTL_LONG(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
203 "I/O buffers currently in progress due to asynchronous writes");
204 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
205 "Hard limit on maximum amount of memory usable for buffer space");
206 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
207 "Soft limit on maximum amount of memory usable for buffer space");
208 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
209 "Minimum amount of memory to reserve for system buffer space");
210 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
211 "Amount of memory available for buffers");
212 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
213 0, "Maximum amount of memory reserved for buffers using malloc");
214 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
215 "Amount of memory left for buffers using malloc-scheme");
216 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
217 "New buffer header acquisition requests");
218 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
219 0, "New buffer header acquisition restarts");
220 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
221 "Recover VM space in an emergency");
222 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
223 "Buffer acquisition restarts due to fragmented buffer map");
224 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
225 "Amount of time KVA space was deallocated in an arbitrary buffer");
226 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
227 "Amount of time buffer re-use operations were successful");
228 SYSCTL_INT(_vfs, OID_AUTO, debug_commit, CTLFLAG_RW, &debug_commit, 0, "");
229 SYSCTL_INT(_vfs, OID_AUTO, debug_bufbio, CTLFLAG_RW, &debug_bufbio, 0, "");
230 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
231 "sizeof(struct buf)");
233 char *buf_wmesg = BUF_WMESG;
235 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
236 #define VFS_BIO_NEED_UNUSED02 0x02
237 #define VFS_BIO_NEED_UNUSED04 0x04
238 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
241 * bufspacewakeup:
243 * Called when buffer space is potentially available for recovery.
244 * getnewbuf() will block on this flag when it is unable to free
245 * sufficient buffer space. Buffer space becomes recoverable when
246 * bp's get placed back in the queues.
248 static __inline void
249 bufspacewakeup(void)
252 * If someone is waiting for BUF space, wake them up. Even
253 * though we haven't freed the kva space yet, the waiting
254 * process will be able to now.
256 for (;;) {
257 int flags = needsbuffer;
258 cpu_ccfence();
259 if ((flags & VFS_BIO_NEED_BUFSPACE) == 0)
260 break;
261 if (atomic_cmpset_int(&needsbuffer, flags,
262 flags & ~VFS_BIO_NEED_BUFSPACE)) {
263 wakeup(&needsbuffer);
264 break;
266 /* retry */
271 * runningbufwakeup:
273 * Accounting for I/O in progress.
276 static __inline void
277 runningbufwakeup(struct buf *bp)
279 long totalspace;
280 long flags;
282 if ((totalspace = bp->b_runningbufspace) != 0) {
283 atomic_add_long(&runningbufspace, -totalspace);
284 atomic_add_long(&runningbufcount, -1);
285 bp->b_runningbufspace = 0;
288 * see waitrunningbufspace() for limit test.
290 for (;;) {
291 flags = runningbufreq;
292 cpu_ccfence();
293 if (flags == 0)
294 break;
295 if (atomic_cmpset_int(&runningbufreq, flags, 0)) {
296 wakeup(&runningbufreq);
297 break;
299 /* retry */
301 bd_signal(totalspace);
306 * bufcountwakeup:
308 * Called when a buffer has been added to one of the free queues to
309 * account for the buffer and to wakeup anyone waiting for free buffers.
310 * This typically occurs when large amounts of metadata are being handled
311 * by the buffer cache ( else buffer space runs out first, usually ).
313 static __inline void
314 bufcountwakeup(void)
316 long flags;
318 for (;;) {
319 flags = needsbuffer;
320 if (flags == 0)
321 break;
322 if (atomic_cmpset_int(&needsbuffer, flags,
323 (flags & ~VFS_BIO_NEED_ANY))) {
324 wakeup(&needsbuffer);
325 break;
327 /* retry */
332 * waitrunningbufspace()
334 * If runningbufspace exceeds 4/6 hirunningspace we block until
335 * runningbufspace drops to 3/6 hirunningspace. We also block if another
336 * thread blocked here in order to be fair, even if runningbufspace
337 * is now lower than the limit.
339 * The caller may be using this function to block in a tight loop, we
340 * must block while runningbufspace is greater than at least
341 * hirunningspace * 3 / 6.
343 void
344 waitrunningbufspace(void)
346 long limit = hirunningspace * 4 / 6;
347 long flags;
349 while (runningbufspace > limit || runningbufreq) {
350 tsleep_interlock(&runningbufreq, 0);
351 flags = atomic_fetchadd_int(&runningbufreq, 1);
352 if (runningbufspace > limit || flags)
353 tsleep(&runningbufreq, PINTERLOCKED, "wdrn1", hz);
358 * buf_dirty_count_severe:
360 * Return true if we have too many dirty buffers.
363 buf_dirty_count_severe(void)
365 return (runningbufspace + dirtykvaspace >= hidirtybufspace ||
366 dirtybufcount >= nbuf / 2);
370 * Return true if the amount of running I/O is severe and BIOQ should
371 * start bursting.
374 buf_runningbufspace_severe(void)
376 return (runningbufspace >= hirunningspace * 4 / 6);
380 * vfs_buf_test_cache:
382 * Called when a buffer is extended. This function clears the B_CACHE
383 * bit if the newly extended portion of the buffer does not contain
384 * valid data.
386 * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer
387 * cache buffers. The VM pages remain dirty, as someone had mmap()'d
388 * them while a clean buffer was present.
390 static __inline__
391 void
392 vfs_buf_test_cache(struct buf *bp,
393 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
394 vm_page_t m)
396 if (bp->b_flags & B_CACHE) {
397 int base = (foff + off) & PAGE_MASK;
398 if (vm_page_is_valid(m, base, size) == 0)
399 bp->b_flags &= ~B_CACHE;
404 * bd_speedup()
406 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
407 * low water mark.
409 static __inline__
410 void
411 bd_speedup(void)
413 if (dirtykvaspace < lodirtybufspace && dirtybufcount < nbuf / 2)
414 return;
416 if (bd_request == 0 &&
417 (dirtykvaspace > lodirtybufspace / 2 ||
418 dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
419 if (atomic_fetchadd_int(&bd_request, 1) == 0)
420 wakeup(&bd_request);
422 if (bd_request_hw == 0 &&
423 (dirtykvaspace > lodirtybufspace / 2 ||
424 dirtybufcounthw >= nbuf / 2)) {
425 if (atomic_fetchadd_int(&bd_request_hw, 1) == 0)
426 wakeup(&bd_request_hw);
431 * bd_heatup()
433 * Get the buf_daemon heated up when the number of running and dirty
434 * buffers exceeds the mid-point.
436 * Return the total number of dirty bytes past the second mid point
437 * as a measure of how much excess dirty data there is in the system.
439 long
440 bd_heatup(void)
442 long mid1;
443 long mid2;
444 long totalspace;
446 mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
448 totalspace = runningbufspace + dirtykvaspace;
449 if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
450 bd_speedup();
451 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
452 if (totalspace >= mid2)
453 return(totalspace - mid2);
455 return(0);
459 * bd_wait()
461 * Wait for the buffer cache to flush (totalspace) bytes worth of
462 * buffers, then return.
464 * Regardless this function blocks while the number of dirty buffers
465 * exceeds hidirtybufspace.
467 void
468 bd_wait(long totalspace)
470 u_int i;
471 u_int j;
472 u_int mi;
473 int count;
475 if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
476 return;
478 while (totalspace > 0) {
479 bd_heatup();
482 * Order is important. Suppliers adjust bd_wake_index after
483 * updating runningbufspace/dirtykvaspace. We want to fetch
484 * bd_wake_index before accessing. Any error should thus
485 * be in our favor.
487 i = atomic_fetchadd_int(&bd_wake_index, 0);
488 if (totalspace > runningbufspace + dirtykvaspace)
489 totalspace = runningbufspace + dirtykvaspace;
490 count = totalspace / BKVASIZE;
491 if (count >= BD_WAKE_SIZE / 2)
492 count = BD_WAKE_SIZE / 2;
493 i = i + count;
494 mi = i & BD_WAKE_MASK;
497 * This is not a strict interlock, so we play a bit loose
498 * with locking access to dirtybufspace*. We have to re-check
499 * bd_wake_index to ensure that it hasn't passed us.
501 tsleep_interlock(&bd_wake_ary[mi], 0);
502 atomic_add_int(&bd_wake_ary[mi], 1);
503 j = atomic_fetchadd_int(&bd_wake_index, 0);
504 if ((int)(i - j) >= 0)
505 tsleep(&bd_wake_ary[mi], PINTERLOCKED, "flstik", hz);
507 totalspace = runningbufspace + dirtykvaspace - hidirtybufspace;
512 * bd_signal()
514 * This function is called whenever runningbufspace or dirtykvaspace
515 * is reduced. Track threads waiting for run+dirty buffer I/O
516 * complete.
518 static void
519 bd_signal(long totalspace)
521 u_int i;
523 if (totalspace > 0) {
524 if (totalspace > BKVASIZE * BD_WAKE_SIZE)
525 totalspace = BKVASIZE * BD_WAKE_SIZE;
526 while (totalspace > 0) {
527 i = atomic_fetchadd_int(&bd_wake_index, 1);
528 i &= BD_WAKE_MASK;
529 if (atomic_readandclear_int(&bd_wake_ary[i]))
530 wakeup(&bd_wake_ary[i]);
531 totalspace -= BKVASIZE;
537 * BIO tracking support routines.
539 * Release a ref on a bio_track. Wakeup requests are atomically released
540 * along with the last reference so bk_active will never wind up set to
541 * only 0x80000000.
543 static
544 void
545 bio_track_rel(struct bio_track *track)
547 int active;
548 int desired;
551 * Shortcut
553 active = track->bk_active;
554 if (active == 1 && atomic_cmpset_int(&track->bk_active, 1, 0))
555 return;
558 * Full-on. Note that the wait flag is only atomically released on
559 * the 1->0 count transition.
561 * We check for a negative count transition using bit 30 since bit 31
562 * has a different meaning.
564 for (;;) {
565 desired = (active & 0x7FFFFFFF) - 1;
566 if (desired)
567 desired |= active & 0x80000000;
568 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
569 if (desired & 0x40000000)
570 panic("bio_track_rel: bad count: %p", track);
571 if (active & 0x80000000)
572 wakeup(track);
573 break;
575 active = track->bk_active;
580 * Wait for the tracking count to reach 0.
582 * Use atomic ops such that the wait flag is only set atomically when
583 * bk_active is non-zero.
586 bio_track_wait(struct bio_track *track, int slp_flags, int slp_timo)
588 int active;
589 int desired;
590 int error;
593 * Shortcut
595 if (track->bk_active == 0)
596 return(0);
599 * Full-on. Note that the wait flag may only be atomically set if
600 * the active count is non-zero.
602 * NOTE: We cannot optimize active == desired since a wakeup could
603 * clear active prior to our tsleep_interlock().
605 error = 0;
606 while ((active = track->bk_active) != 0) {
607 cpu_ccfence();
608 desired = active | 0x80000000;
609 tsleep_interlock(track, slp_flags);
610 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
611 error = tsleep(track, slp_flags | PINTERLOCKED,
612 "trwait", slp_timo);
613 if (error)
614 break;
617 return (error);
621 * bufinit:
623 * Load time initialisation of the buffer cache, called from machine
624 * dependant initialization code.
626 static
627 void
628 bufinit(void *dummy __unused)
630 struct bufpcpu *pcpu;
631 struct buf *bp;
632 vm_offset_t bogus_offset;
633 int i;
634 int j;
635 long n;
637 /* next, make a null set of free lists */
638 for (i = 0; i < ncpus; ++i) {
639 pcpu = &bufpcpu[i];
640 spin_init(&pcpu->spin, "bufinit");
641 for (j = 0; j < BUFFER_QUEUES; j++)
642 TAILQ_INIT(&pcpu->bufqueues[j]);
645 /* finally, initialize each buffer header and stick on empty q */
646 i = 0;
647 pcpu = &bufpcpu[i];
649 for (n = 0; n < nbuf; n++) {
650 bp = &buf[n];
651 bzero(bp, sizeof *bp);
652 bp->b_flags = B_INVAL; /* we're just an empty header */
653 bp->b_cmd = BUF_CMD_DONE;
654 bp->b_qindex = BQUEUE_EMPTY;
655 bp->b_qcpu = i;
656 initbufbio(bp);
657 xio_init(&bp->b_xio);
658 buf_dep_init(bp);
659 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
660 bp, b_freelist);
662 i = (i + 1) % ncpus;
663 pcpu = &bufpcpu[i];
667 * maxbufspace is the absolute maximum amount of buffer space we are
668 * allowed to reserve in KVM and in real terms. The absolute maximum
669 * is nominally used by buf_daemon. hibufspace is the nominal maximum
670 * used by most other processes. The differential is required to
671 * ensure that buf_daemon is able to run when other processes might
672 * be blocked waiting for buffer space.
674 * maxbufspace is based on BKVASIZE. Allocating buffers larger then
675 * this may result in KVM fragmentation which is not handled optimally
676 * by the system.
678 maxbufspace = nbuf * BKVASIZE;
679 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
680 lobufspace = hibufspace - MAXBSIZE;
682 lorunningspace = 512 * 1024;
683 /* hirunningspace -- see below */
686 * Limit the amount of malloc memory since it is wired permanently
687 * into the kernel space. Even though this is accounted for in
688 * the buffer allocation, we don't want the malloced region to grow
689 * uncontrolled. The malloc scheme improves memory utilization
690 * significantly on average (small) directories.
692 maxbufmallocspace = hibufspace / 20;
695 * Reduce the chance of a deadlock occuring by limiting the number
696 * of delayed-write dirty buffers we allow to stack up.
698 * We don't want too much actually queued to the device at once
699 * (XXX this needs to be per-mount!), because the buffers will
700 * wind up locked for a very long period of time while the I/O
701 * drains.
703 hidirtybufspace = hibufspace / 2; /* dirty + running */
704 hirunningspace = hibufspace / 16; /* locked & queued to device */
705 if (hirunningspace < 1024 * 1024)
706 hirunningspace = 1024 * 1024;
708 dirtykvaspace = 0;
709 dirtybufspace = 0;
710 dirtybufspacehw = 0;
712 lodirtybufspace = hidirtybufspace / 2;
715 * Maximum number of async ops initiated per buf_daemon loop. This is
716 * somewhat of a hack at the moment, we really need to limit ourselves
717 * based on the number of bytes of I/O in-transit that were initiated
718 * from buf_daemon.
721 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
722 vm_object_hold(&kernel_object);
723 bogus_page = vm_page_alloc(&kernel_object,
724 (bogus_offset >> PAGE_SHIFT),
725 VM_ALLOC_NORMAL);
726 vm_object_drop(&kernel_object);
727 vmstats.v_wire_count++;
731 SYSINIT(do_bufinit, SI_BOOT2_MACHDEP, SI_ORDER_FIRST, bufinit, NULL);
734 * Initialize the embedded bio structures, typically used by
735 * deprecated code which tries to allocate its own struct bufs.
737 void
738 initbufbio(struct buf *bp)
740 bp->b_bio1.bio_buf = bp;
741 bp->b_bio1.bio_prev = NULL;
742 bp->b_bio1.bio_offset = NOOFFSET;
743 bp->b_bio1.bio_next = &bp->b_bio2;
744 bp->b_bio1.bio_done = NULL;
745 bp->b_bio1.bio_flags = 0;
747 bp->b_bio2.bio_buf = bp;
748 bp->b_bio2.bio_prev = &bp->b_bio1;
749 bp->b_bio2.bio_offset = NOOFFSET;
750 bp->b_bio2.bio_next = NULL;
751 bp->b_bio2.bio_done = NULL;
752 bp->b_bio2.bio_flags = 0;
754 BUF_LOCKINIT(bp);
758 * Reinitialize the embedded bio structures as well as any additional
759 * translation cache layers.
761 void
762 reinitbufbio(struct buf *bp)
764 struct bio *bio;
766 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
767 bio->bio_done = NULL;
768 bio->bio_offset = NOOFFSET;
773 * Undo the effects of an initbufbio().
775 void
776 uninitbufbio(struct buf *bp)
778 dsched_buf_exit(bp);
779 BUF_LOCKFREE(bp);
783 * Push another BIO layer onto an existing BIO and return it. The new
784 * BIO layer may already exist, holding cached translation data.
786 struct bio *
787 push_bio(struct bio *bio)
789 struct bio *nbio;
791 if ((nbio = bio->bio_next) == NULL) {
792 int index = bio - &bio->bio_buf->b_bio_array[0];
793 if (index >= NBUF_BIO - 1) {
794 panic("push_bio: too many layers %d for bp %p",
795 index, bio->bio_buf);
797 nbio = &bio->bio_buf->b_bio_array[index + 1];
798 bio->bio_next = nbio;
799 nbio->bio_prev = bio;
800 nbio->bio_buf = bio->bio_buf;
801 nbio->bio_offset = NOOFFSET;
802 nbio->bio_done = NULL;
803 nbio->bio_next = NULL;
805 KKASSERT(nbio->bio_done == NULL);
806 return(nbio);
810 * Pop a BIO translation layer, returning the previous layer. The
811 * must have been previously pushed.
813 struct bio *
814 pop_bio(struct bio *bio)
816 return(bio->bio_prev);
819 void
820 clearbiocache(struct bio *bio)
822 while (bio) {
823 bio->bio_offset = NOOFFSET;
824 bio = bio->bio_next;
829 * bfreekva:
831 * Free the KVA allocation for buffer 'bp'.
833 * Must be called from a critical section as this is the only locking for
834 * buffer_map.
836 * Since this call frees up buffer space, we call bufspacewakeup().
838 static void
839 bfreekva(struct buf *bp)
841 int count;
843 if (bp->b_kvasize) {
844 ++buffreekvacnt;
845 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
846 vm_map_lock(&buffer_map);
847 bufspace -= bp->b_kvasize;
848 vm_map_delete(&buffer_map,
849 (vm_offset_t) bp->b_kvabase,
850 (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
851 &count
853 vm_map_unlock(&buffer_map);
854 vm_map_entry_release(count);
855 bp->b_kvasize = 0;
856 bp->b_kvabase = NULL;
857 bufspacewakeup();
862 * Remove the buffer from the appropriate free list.
863 * (caller must be locked)
865 static __inline void
866 _bremfree(struct buf *bp)
868 struct bufpcpu *pcpu = &bufpcpu[bp->b_qcpu];
870 if (bp->b_qindex != BQUEUE_NONE) {
871 KASSERT(BUF_REFCNTNB(bp) == 1,
872 ("bremfree: bp %p not locked",bp));
873 TAILQ_REMOVE(&pcpu->bufqueues[bp->b_qindex], bp, b_freelist);
874 bp->b_qindex = BQUEUE_NONE;
875 } else {
876 if (BUF_REFCNTNB(bp) <= 1)
877 panic("bremfree: removing a buffer not on a queue");
882 * bremfree() - must be called with a locked buffer
884 void
885 bremfree(struct buf *bp)
887 struct bufpcpu *pcpu = &bufpcpu[bp->b_qcpu];
889 spin_lock(&pcpu->spin);
890 _bremfree(bp);
891 spin_unlock(&pcpu->spin);
895 * bremfree_locked - must be called with pcpu->spin locked
897 static void
898 bremfree_locked(struct buf *bp)
900 _bremfree(bp);
904 * This version of bread issues any required I/O asyncnronously and
905 * makes a callback on completion.
907 * The callback must check whether BIO_DONE is set in the bio and issue
908 * the bpdone(bp, 0) if it isn't. The callback is responsible for clearing
909 * BIO_DONE and disposing of the I/O (bqrelse()ing it).
911 void
912 breadcb(struct vnode *vp, off_t loffset, int size,
913 void (*func)(struct bio *), void *arg)
915 struct buf *bp;
917 bp = getblk(vp, loffset, size, 0, 0);
919 /* if not found in cache, do some I/O */
920 if ((bp->b_flags & B_CACHE) == 0) {
921 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
922 bp->b_cmd = BUF_CMD_READ;
923 bp->b_bio1.bio_done = func;
924 bp->b_bio1.bio_caller_info1.ptr = arg;
925 vfs_busy_pages(vp, bp);
926 BUF_KERNPROC(bp);
927 vn_strategy(vp, &bp->b_bio1);
928 } else if (func) {
930 * Since we are issuing the callback synchronously it cannot
931 * race the BIO_DONE, so no need for atomic ops here.
933 /*bp->b_bio1.bio_done = func;*/
934 bp->b_bio1.bio_caller_info1.ptr = arg;
935 bp->b_bio1.bio_flags |= BIO_DONE;
936 func(&bp->b_bio1);
937 } else {
938 bqrelse(bp);
943 * breadnx() - Terminal function for bread() and breadn().
945 * This function will start asynchronous I/O on read-ahead blocks as well
946 * as satisfy the primary request.
948 * We must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE is
949 * set, the buffer is valid and we do not have to do anything.
952 breadnx(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
953 int *rabsize, int cnt, struct buf **bpp)
955 struct buf *bp, *rabp;
956 int i;
957 int rv = 0, readwait = 0;
959 if (*bpp)
960 bp = *bpp;
961 else
962 *bpp = bp = getblk(vp, loffset, size, 0, 0);
964 /* if not found in cache, do some I/O */
965 if ((bp->b_flags & B_CACHE) == 0) {
966 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
967 bp->b_cmd = BUF_CMD_READ;
968 bp->b_bio1.bio_done = biodone_sync;
969 bp->b_bio1.bio_flags |= BIO_SYNC;
970 vfs_busy_pages(vp, bp);
971 vn_strategy(vp, &bp->b_bio1);
972 ++readwait;
975 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
976 if (inmem(vp, *raoffset))
977 continue;
978 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
980 if ((rabp->b_flags & B_CACHE) == 0) {
981 rabp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
982 rabp->b_cmd = BUF_CMD_READ;
983 vfs_busy_pages(vp, rabp);
984 BUF_KERNPROC(rabp);
985 vn_strategy(vp, &rabp->b_bio1);
986 } else {
987 brelse(rabp);
990 if (readwait)
991 rv = biowait(&bp->b_bio1, "biord");
992 return (rv);
996 * bwrite:
998 * Synchronous write, waits for completion.
1000 * Write, release buffer on completion. (Done by iodone
1001 * if async). Do not bother writing anything if the buffer
1002 * is invalid.
1004 * Note that we set B_CACHE here, indicating that buffer is
1005 * fully valid and thus cacheable. This is true even of NFS
1006 * now so we set it generally. This could be set either here
1007 * or in biodone() since the I/O is synchronous. We put it
1008 * here.
1011 bwrite(struct buf *bp)
1013 int error;
1015 if (bp->b_flags & B_INVAL) {
1016 brelse(bp);
1017 return (0);
1019 if (BUF_REFCNTNB(bp) == 0)
1020 panic("bwrite: buffer is not busy???");
1023 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
1024 * call because it will remove the buffer from the vnode's
1025 * dirty buffer list prematurely and possibly cause filesystem
1026 * checks to race buffer flushes. This is now handled in
1027 * bpdone().
1029 * bundirty(bp); REMOVED
1032 bp->b_flags &= ~(B_ERROR | B_EINTR);
1033 bp->b_flags |= B_CACHE;
1034 bp->b_cmd = BUF_CMD_WRITE;
1035 bp->b_bio1.bio_done = biodone_sync;
1036 bp->b_bio1.bio_flags |= BIO_SYNC;
1037 vfs_busy_pages(bp->b_vp, bp);
1040 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1041 * valid for vnode-backed buffers.
1043 bsetrunningbufspace(bp, bp->b_bufsize);
1044 vn_strategy(bp->b_vp, &bp->b_bio1);
1045 error = biowait(&bp->b_bio1, "biows");
1046 brelse(bp);
1048 return (error);
1052 * bawrite:
1054 * Asynchronous write. Start output on a buffer, but do not wait for
1055 * it to complete. The buffer is released when the output completes.
1057 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1058 * B_INVAL buffers. Not us.
1060 void
1061 bawrite(struct buf *bp)
1063 if (bp->b_flags & B_INVAL) {
1064 brelse(bp);
1065 return;
1067 if (BUF_REFCNTNB(bp) == 0)
1068 panic("bawrite: buffer is not busy???");
1071 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
1072 * call because it will remove the buffer from the vnode's
1073 * dirty buffer list prematurely and possibly cause filesystem
1074 * checks to race buffer flushes. This is now handled in
1075 * bpdone().
1077 * bundirty(bp); REMOVED
1079 bp->b_flags &= ~(B_ERROR | B_EINTR);
1080 bp->b_flags |= B_CACHE;
1081 bp->b_cmd = BUF_CMD_WRITE;
1082 KKASSERT(bp->b_bio1.bio_done == NULL);
1083 vfs_busy_pages(bp->b_vp, bp);
1086 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1087 * valid for vnode-backed buffers.
1089 bsetrunningbufspace(bp, bp->b_bufsize);
1090 BUF_KERNPROC(bp);
1091 vn_strategy(bp->b_vp, &bp->b_bio1);
1095 * bowrite:
1097 * Ordered write. Start output on a buffer, and flag it so that the
1098 * device will write it in the order it was queued. The buffer is
1099 * released when the output completes. bwrite() ( or the VOP routine
1100 * anyway ) is responsible for handling B_INVAL buffers.
1103 bowrite(struct buf *bp)
1105 bp->b_flags |= B_ORDERED;
1106 bawrite(bp);
1107 return (0);
1111 * bdwrite:
1113 * Delayed write. (Buffer is marked dirty). Do not bother writing
1114 * anything if the buffer is marked invalid.
1116 * Note that since the buffer must be completely valid, we can safely
1117 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1118 * biodone() in order to prevent getblk from writing the buffer
1119 * out synchronously.
1121 void
1122 bdwrite(struct buf *bp)
1124 if (BUF_REFCNTNB(bp) == 0)
1125 panic("bdwrite: buffer is not busy");
1127 if (bp->b_flags & B_INVAL) {
1128 brelse(bp);
1129 return;
1131 bdirty(bp);
1133 dsched_buf_enter(bp); /* might stack */
1136 * Set B_CACHE, indicating that the buffer is fully valid. This is
1137 * true even of NFS now.
1139 bp->b_flags |= B_CACHE;
1142 * This bmap keeps the system from needing to do the bmap later,
1143 * perhaps when the system is attempting to do a sync. Since it
1144 * is likely that the indirect block -- or whatever other datastructure
1145 * that the filesystem needs is still in memory now, it is a good
1146 * thing to do this. Note also, that if the pageout daemon is
1147 * requesting a sync -- there might not be enough memory to do
1148 * the bmap then... So, this is important to do.
1150 if (bp->b_bio2.bio_offset == NOOFFSET) {
1151 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
1152 NULL, NULL, BUF_CMD_WRITE);
1156 * Because the underlying pages may still be mapped and
1157 * writable trying to set the dirty buffer (b_dirtyoff/end)
1158 * range here will be inaccurate.
1160 * However, we must still clean the pages to satisfy the
1161 * vnode_pager and pageout daemon, so they think the pages
1162 * have been "cleaned". What has really occured is that
1163 * they've been earmarked for later writing by the buffer
1164 * cache.
1166 * So we get the b_dirtyoff/end update but will not actually
1167 * depend on it (NFS that is) until the pages are busied for
1168 * writing later on.
1170 vfs_clean_pages(bp);
1171 bqrelse(bp);
1174 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1175 * due to the softdep code.
1180 * Fake write - return pages to VM system as dirty, leave the buffer clean.
1181 * This is used by tmpfs.
1183 * It is important for any VFS using this routine to NOT use it for
1184 * IO_SYNC or IO_ASYNC operations which occur when the system really
1185 * wants to flush VM pages to backing store.
1187 void
1188 buwrite(struct buf *bp)
1190 vm_page_t m;
1191 int i;
1194 * Only works for VMIO buffers. If the buffer is already
1195 * marked for delayed-write we can't avoid the bdwrite().
1197 if ((bp->b_flags & B_VMIO) == 0 || (bp->b_flags & B_DELWRI)) {
1198 bdwrite(bp);
1199 return;
1203 * Mark as needing a commit.
1205 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1206 m = bp->b_xio.xio_pages[i];
1207 vm_page_need_commit(m);
1209 bqrelse(bp);
1213 * bdirty:
1215 * Turn buffer into delayed write request by marking it B_DELWRI.
1216 * B_RELBUF and B_NOCACHE must be cleared.
1218 * We reassign the buffer to itself to properly update it in the
1219 * dirty/clean lists.
1221 * Must be called from a critical section.
1222 * The buffer must be on BQUEUE_NONE.
1224 void
1225 bdirty(struct buf *bp)
1227 KASSERT(bp->b_qindex == BQUEUE_NONE,
1228 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1229 if (bp->b_flags & B_NOCACHE) {
1230 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
1231 bp->b_flags &= ~B_NOCACHE;
1233 if (bp->b_flags & B_INVAL) {
1234 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
1236 bp->b_flags &= ~B_RELBUF;
1238 if ((bp->b_flags & B_DELWRI) == 0) {
1239 lwkt_gettoken(&bp->b_vp->v_token);
1240 bp->b_flags |= B_DELWRI;
1241 reassignbuf(bp);
1242 lwkt_reltoken(&bp->b_vp->v_token);
1244 atomic_add_long(&dirtybufcount, 1);
1245 atomic_add_long(&dirtykvaspace, bp->b_kvasize);
1246 atomic_add_long(&dirtybufspace, bp->b_bufsize);
1247 if (bp->b_flags & B_HEAVY) {
1248 atomic_add_long(&dirtybufcounthw, 1);
1249 atomic_add_long(&dirtybufspacehw, bp->b_bufsize);
1251 bd_heatup();
1256 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
1257 * needs to be flushed with a different buf_daemon thread to avoid
1258 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
1260 void
1261 bheavy(struct buf *bp)
1263 if ((bp->b_flags & B_HEAVY) == 0) {
1264 bp->b_flags |= B_HEAVY;
1265 if (bp->b_flags & B_DELWRI) {
1266 atomic_add_long(&dirtybufcounthw, 1);
1267 atomic_add_long(&dirtybufspacehw, bp->b_bufsize);
1273 * bundirty:
1275 * Clear B_DELWRI for buffer.
1277 * Must be called from a critical section.
1279 * The buffer is typically on BQUEUE_NONE but there is one case in
1280 * brelse() that calls this function after placing the buffer on
1281 * a different queue.
1283 void
1284 bundirty(struct buf *bp)
1286 if (bp->b_flags & B_DELWRI) {
1287 lwkt_gettoken(&bp->b_vp->v_token);
1288 bp->b_flags &= ~B_DELWRI;
1289 reassignbuf(bp);
1290 lwkt_reltoken(&bp->b_vp->v_token);
1292 atomic_add_long(&dirtybufcount, -1);
1293 atomic_add_long(&dirtykvaspace, -bp->b_kvasize);
1294 atomic_add_long(&dirtybufspace, -bp->b_bufsize);
1295 if (bp->b_flags & B_HEAVY) {
1296 atomic_add_long(&dirtybufcounthw, -1);
1297 atomic_add_long(&dirtybufspacehw, -bp->b_bufsize);
1299 bd_signal(bp->b_bufsize);
1302 * Since it is now being written, we can clear its deferred write flag.
1304 bp->b_flags &= ~B_DEFERRED;
1308 * Set the b_runningbufspace field, used to track how much I/O is
1309 * in progress at any given moment.
1311 void
1312 bsetrunningbufspace(struct buf *bp, int bytes)
1314 bp->b_runningbufspace = bytes;
1315 if (bytes) {
1316 atomic_add_long(&runningbufspace, bytes);
1317 atomic_add_long(&runningbufcount, 1);
1322 * brelse:
1324 * Release a busy buffer and, if requested, free its resources. The
1325 * buffer will be stashed in the appropriate bufqueue[] allowing it
1326 * to be accessed later as a cache entity or reused for other purposes.
1328 void
1329 brelse(struct buf *bp)
1331 struct bufpcpu *pcpu;
1332 #ifdef INVARIANTS
1333 int saved_flags = bp->b_flags;
1334 #endif
1336 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1337 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1340 * If B_NOCACHE is set we are being asked to destroy the buffer and
1341 * its backing store. Clear B_DELWRI.
1343 * B_NOCACHE is set in two cases: (1) when the caller really wants
1344 * to destroy the buffer and backing store and (2) when the caller
1345 * wants to destroy the buffer and backing store after a write
1346 * completes.
1348 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1349 bundirty(bp);
1352 if ((bp->b_flags & (B_INVAL | B_DELWRI)) == B_DELWRI) {
1354 * A re-dirtied buffer is only subject to destruction
1355 * by B_INVAL. B_ERROR and B_NOCACHE are ignored.
1357 /* leave buffer intact */
1358 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1359 (bp->b_bufsize <= 0)) {
1361 * Either a failed read or we were asked to free or not
1362 * cache the buffer. This path is reached with B_DELWRI
1363 * set only if B_INVAL is already set. B_NOCACHE governs
1364 * backing store destruction.
1366 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1367 * buffer cannot be immediately freed.
1369 bp->b_flags |= B_INVAL;
1370 if (LIST_FIRST(&bp->b_dep) != NULL)
1371 buf_deallocate(bp);
1372 if (bp->b_flags & B_DELWRI) {
1373 atomic_add_long(&dirtybufcount, -1);
1374 atomic_add_long(&dirtykvaspace, -bp->b_kvasize);
1375 atomic_add_long(&dirtybufspace, -bp->b_bufsize);
1376 if (bp->b_flags & B_HEAVY) {
1377 atomic_add_long(&dirtybufcounthw, -1);
1378 atomic_add_long(&dirtybufspacehw,
1379 -bp->b_bufsize);
1381 bd_signal(bp->b_bufsize);
1383 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1387 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set,
1388 * or if b_refs is non-zero.
1390 * If vfs_vmio_release() is called with either bit set, the
1391 * underlying pages may wind up getting freed causing a previous
1392 * write (bdwrite()) to get 'lost' because pages associated with
1393 * a B_DELWRI bp are marked clean. Pages associated with a
1394 * B_LOCKED buffer may be mapped by the filesystem.
1396 * If we want to release the buffer ourselves (rather then the
1397 * originator asking us to release it), give the originator a
1398 * chance to countermand the release by setting B_LOCKED.
1400 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1401 * if B_DELWRI is set.
1403 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1404 * on pages to return pages to the VM page queues.
1406 if ((bp->b_flags & (B_DELWRI | B_LOCKED)) || bp->b_refs) {
1407 bp->b_flags &= ~B_RELBUF;
1408 } else if (vm_page_count_min(0)) {
1409 if (LIST_FIRST(&bp->b_dep) != NULL)
1410 buf_deallocate(bp); /* can set B_LOCKED */
1411 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1412 bp->b_flags &= ~B_RELBUF;
1413 else
1414 bp->b_flags |= B_RELBUF;
1418 * Make sure b_cmd is clear. It may have already been cleared by
1419 * biodone().
1421 * At this point destroying the buffer is governed by the B_INVAL
1422 * or B_RELBUF flags.
1424 bp->b_cmd = BUF_CMD_DONE;
1425 dsched_buf_exit(bp);
1428 * VMIO buffer rundown. Make sure the VM page array is restored
1429 * after an I/O may have replaces some of the pages with bogus pages
1430 * in order to not destroy dirty pages in a fill-in read.
1432 * Note that due to the code above, if a buffer is marked B_DELWRI
1433 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1434 * B_INVAL may still be set, however.
1436 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1437 * but not the backing store. B_NOCACHE will destroy the backing
1438 * store.
1440 * Note that dirty NFS buffers contain byte-granular write ranges
1441 * and should not be destroyed w/ B_INVAL even if the backing store
1442 * is left intact.
1444 if (bp->b_flags & B_VMIO) {
1446 * Rundown for VMIO buffers which are not dirty NFS buffers.
1448 int i, j, resid;
1449 vm_page_t m;
1450 off_t foff;
1451 vm_pindex_t poff;
1452 vm_object_t obj;
1453 struct vnode *vp;
1455 vp = bp->b_vp;
1458 * Get the base offset and length of the buffer. Note that
1459 * in the VMIO case if the buffer block size is not
1460 * page-aligned then b_data pointer may not be page-aligned.
1461 * But our b_xio.xio_pages array *IS* page aligned.
1463 * block sizes less then DEV_BSIZE (usually 512) are not
1464 * supported due to the page granularity bits (m->valid,
1465 * m->dirty, etc...).
1467 * See man buf(9) for more information
1470 resid = bp->b_bufsize;
1471 foff = bp->b_loffset;
1473 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1474 m = bp->b_xio.xio_pages[i];
1475 vm_page_flag_clear(m, PG_ZERO);
1477 * If we hit a bogus page, fixup *all* of them
1478 * now. Note that we left these pages wired
1479 * when we removed them so they had better exist,
1480 * and they cannot be ripped out from under us so
1481 * no critical section protection is necessary.
1483 if (m == bogus_page) {
1484 obj = vp->v_object;
1485 poff = OFF_TO_IDX(bp->b_loffset);
1487 vm_object_hold(obj);
1488 for (j = i; j < bp->b_xio.xio_npages; j++) {
1489 vm_page_t mtmp;
1491 mtmp = bp->b_xio.xio_pages[j];
1492 if (mtmp == bogus_page) {
1493 mtmp = vm_page_lookup(obj, poff + j);
1494 if (!mtmp) {
1495 panic("brelse: page missing");
1497 bp->b_xio.xio_pages[j] = mtmp;
1500 bp->b_flags &= ~B_HASBOGUS;
1501 vm_object_drop(obj);
1503 if ((bp->b_flags & B_INVAL) == 0) {
1504 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1505 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1507 m = bp->b_xio.xio_pages[i];
1511 * Invalidate the backing store if B_NOCACHE is set
1512 * (e.g. used with vinvalbuf()). If this is NFS
1513 * we impose a requirement that the block size be
1514 * a multiple of PAGE_SIZE and create a temporary
1515 * hack to basically invalidate the whole page. The
1516 * problem is that NFS uses really odd buffer sizes
1517 * especially when tracking piecemeal writes and
1518 * it also vinvalbuf()'s a lot, which would result
1519 * in only partial page validation and invalidation
1520 * here. If the file page is mmap()'d, however,
1521 * all the valid bits get set so after we invalidate
1522 * here we would end up with weird m->valid values
1523 * like 0xfc. nfs_getpages() can't handle this so
1524 * we clear all the valid bits for the NFS case
1525 * instead of just some of them.
1527 * The real bug is the VM system having to set m->valid
1528 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1529 * itself is an artifact of the whole 512-byte
1530 * granular mess that exists to support odd block
1531 * sizes and UFS meta-data block sizes (e.g. 6144).
1532 * A complete rewrite is required.
1534 * XXX
1536 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1537 int poffset = foff & PAGE_MASK;
1538 int presid;
1540 presid = PAGE_SIZE - poffset;
1541 if (bp->b_vp->v_tag == VT_NFS &&
1542 bp->b_vp->v_type == VREG) {
1543 ; /* entire page */
1544 } else if (presid > resid) {
1545 presid = resid;
1547 KASSERT(presid >= 0, ("brelse: extra page"));
1548 vm_page_set_invalid(m, poffset, presid);
1551 * Also make sure any swap cache is removed
1552 * as it is now stale (HAMMER in particular
1553 * uses B_NOCACHE to deal with buffer
1554 * aliasing).
1556 swap_pager_unswapped(m);
1558 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1559 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1561 if (bp->b_flags & (B_INVAL | B_RELBUF))
1562 vfs_vmio_release(bp);
1563 } else {
1565 * Rundown for non-VMIO buffers.
1567 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1568 if (bp->b_bufsize)
1569 allocbuf(bp, 0);
1570 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1571 if (bp->b_vp)
1572 brelvp(bp);
1576 if (bp->b_qindex != BQUEUE_NONE)
1577 panic("brelse: free buffer onto another queue???");
1578 if (BUF_REFCNTNB(bp) > 1) {
1579 /* Temporary panic to verify exclusive locking */
1580 /* This panic goes away when we allow shared refs */
1581 panic("brelse: multiple refs");
1582 /* NOT REACHED */
1583 return;
1587 * Figure out the correct queue to place the cleaned up buffer on.
1588 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1589 * disassociated from their vnode.
1591 * Return the buffer to its original pcpu area
1593 pcpu = &bufpcpu[bp->b_qcpu];
1594 spin_lock(&pcpu->spin);
1596 if (bp->b_flags & B_LOCKED) {
1598 * Buffers that are locked are placed in the locked queue
1599 * immediately, regardless of their state.
1601 bp->b_qindex = BQUEUE_LOCKED;
1602 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1603 bp, b_freelist);
1604 } else if (bp->b_bufsize == 0) {
1606 * Buffers with no memory. Due to conditionals near the top
1607 * of brelse() such buffers should probably already be
1608 * marked B_INVAL and disassociated from their vnode.
1610 bp->b_flags |= B_INVAL;
1611 KASSERT(bp->b_vp == NULL,
1612 ("bp1 %p flags %08x/%08x vnode %p "
1613 "unexpectededly still associated!",
1614 bp, saved_flags, bp->b_flags, bp->b_vp));
1615 KKASSERT((bp->b_flags & B_HASHED) == 0);
1616 if (bp->b_kvasize) {
1617 bp->b_qindex = BQUEUE_EMPTYKVA;
1618 } else {
1619 bp->b_qindex = BQUEUE_EMPTY;
1621 TAILQ_INSERT_HEAD(&pcpu->bufqueues[bp->b_qindex],
1622 bp, b_freelist);
1623 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) {
1625 * Buffers with junk contents. Again these buffers had better
1626 * already be disassociated from their vnode.
1628 KASSERT(bp->b_vp == NULL,
1629 ("bp2 %p flags %08x/%08x vnode %p unexpectededly "
1630 "still associated!",
1631 bp, saved_flags, bp->b_flags, bp->b_vp));
1632 KKASSERT((bp->b_flags & B_HASHED) == 0);
1633 bp->b_flags |= B_INVAL;
1634 bp->b_qindex = BQUEUE_CLEAN;
1635 TAILQ_INSERT_HEAD(&pcpu->bufqueues[bp->b_qindex],
1636 bp, b_freelist);
1637 } else {
1639 * Remaining buffers. These buffers are still associated with
1640 * their vnode.
1642 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1643 case B_DELWRI:
1644 bp->b_qindex = BQUEUE_DIRTY;
1645 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1646 bp, b_freelist);
1647 break;
1648 case B_DELWRI | B_HEAVY:
1649 bp->b_qindex = BQUEUE_DIRTY_HW;
1650 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1651 bp, b_freelist);
1652 break;
1653 default:
1655 * NOTE: Buffers are always placed at the end of the
1656 * queue. If B_AGE is not set the buffer will cycle
1657 * through the queue twice.
1659 bp->b_qindex = BQUEUE_CLEAN;
1660 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1661 bp, b_freelist);
1662 break;
1665 spin_unlock(&pcpu->spin);
1668 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1669 * on the correct queue but we have not yet unlocked it.
1671 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1672 bundirty(bp);
1675 * The bp is on an appropriate queue unless locked. If it is not
1676 * locked or dirty we can wakeup threads waiting for buffer space.
1678 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1679 * if B_INVAL is set ).
1681 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1682 bufcountwakeup();
1685 * Something we can maybe free or reuse
1687 if (bp->b_bufsize || bp->b_kvasize)
1688 bufspacewakeup();
1691 * Clean up temporary flags and unlock the buffer.
1693 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF | B_DIRECT);
1694 BUF_UNLOCK(bp);
1698 * bqrelse:
1700 * Release a buffer back to the appropriate queue but do not try to free
1701 * it. The buffer is expected to be used again soon.
1703 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1704 * biodone() to requeue an async I/O on completion. It is also used when
1705 * known good buffers need to be requeued but we think we may need the data
1706 * again soon.
1708 * XXX we should be able to leave the B_RELBUF hint set on completion.
1710 void
1711 bqrelse(struct buf *bp)
1713 struct bufpcpu *pcpu;
1715 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1716 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1718 if (bp->b_qindex != BQUEUE_NONE)
1719 panic("bqrelse: free buffer onto another queue???");
1720 if (BUF_REFCNTNB(bp) > 1) {
1721 /* do not release to free list */
1722 panic("bqrelse: multiple refs");
1723 return;
1726 buf_act_advance(bp);
1728 pcpu = &bufpcpu[bp->b_qcpu];
1729 spin_lock(&pcpu->spin);
1731 if (bp->b_flags & B_LOCKED) {
1733 * Locked buffers are released to the locked queue. However,
1734 * if the buffer is dirty it will first go into the dirty
1735 * queue and later on after the I/O completes successfully it
1736 * will be released to the locked queue.
1738 bp->b_qindex = BQUEUE_LOCKED;
1739 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1740 bp, b_freelist);
1741 } else if (bp->b_flags & B_DELWRI) {
1742 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1743 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1744 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1745 bp, b_freelist);
1746 } else if (vm_page_count_min(0)) {
1748 * We are too low on memory, we have to try to free the
1749 * buffer (most importantly: the wired pages making up its
1750 * backing store) *now*.
1752 spin_unlock(&pcpu->spin);
1753 brelse(bp);
1754 return;
1755 } else {
1756 bp->b_qindex = BQUEUE_CLEAN;
1757 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1758 bp, b_freelist);
1760 spin_unlock(&pcpu->spin);
1763 * We have now placed the buffer on the proper queue, but have yet
1764 * to unlock it.
1766 if ((bp->b_flags & B_LOCKED) == 0 &&
1767 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1768 bufcountwakeup();
1772 * Something we can maybe free or reuse.
1774 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1775 bufspacewakeup();
1778 * Final cleanup and unlock. Clear bits that are only used while a
1779 * buffer is actively locked.
1781 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF);
1782 dsched_buf_exit(bp);
1783 BUF_UNLOCK(bp);
1787 * Hold a buffer, preventing it from being reused. This will prevent
1788 * normal B_RELBUF operations on the buffer but will not prevent B_INVAL
1789 * operations. If a B_INVAL operation occurs the buffer will remain held
1790 * but the underlying pages may get ripped out.
1792 * These functions are typically used in VOP_READ/VOP_WRITE functions
1793 * to hold a buffer during a copyin or copyout, preventing deadlocks
1794 * or recursive lock panics when read()/write() is used over mmap()'d
1795 * space.
1797 * NOTE: bqhold() requires that the buffer be locked at the time of the
1798 * hold. bqdrop() has no requirements other than the buffer having
1799 * previously been held.
1801 void
1802 bqhold(struct buf *bp)
1804 atomic_add_int(&bp->b_refs, 1);
1807 void
1808 bqdrop(struct buf *bp)
1810 KKASSERT(bp->b_refs > 0);
1811 atomic_add_int(&bp->b_refs, -1);
1815 * Return backing pages held by the buffer 'bp' back to the VM system.
1816 * This routine is called when the bp is invalidated, released, or
1817 * reused.
1819 * The KVA mapping (b_data) for the underlying pages is removed by
1820 * this function.
1822 * WARNING! This routine is integral to the low memory critical path
1823 * when a buffer is B_RELBUF'd. If the system has a severe page
1824 * deficit we need to get the page(s) onto the PQ_FREE or PQ_CACHE
1825 * queues so they can be reused in the current pageout daemon
1826 * pass.
1828 static void
1829 vfs_vmio_release(struct buf *bp)
1831 int i;
1832 vm_page_t m;
1834 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1835 m = bp->b_xio.xio_pages[i];
1836 bp->b_xio.xio_pages[i] = NULL;
1839 * We need to own the page in order to safely unwire it.
1841 vm_page_busy_wait(m, FALSE, "vmiopg");
1844 * The VFS is telling us this is not a meta-data buffer
1845 * even if it is backed by a block device.
1847 if (bp->b_flags & B_NOTMETA)
1848 vm_page_flag_set(m, PG_NOTMETA);
1851 * This is a very important bit of code. We try to track
1852 * VM page use whether the pages are wired into the buffer
1853 * cache or not. While wired into the buffer cache the
1854 * bp tracks the act_count.
1856 * We can choose to place unwired pages on the inactive
1857 * queue (0) or active queue (1). If we place too many
1858 * on the active queue the queue will cycle the act_count
1859 * on pages we'd like to keep, just from single-use pages
1860 * (such as when doing a tar-up or file scan).
1862 if (bp->b_act_count < vm_cycle_point)
1863 vm_page_unwire(m, 0);
1864 else
1865 vm_page_unwire(m, 1);
1868 * If the wire_count has dropped to 0 we may need to take
1869 * further action before unbusying the page.
1871 * WARNING: vm_page_try_*() also checks PG_NEED_COMMIT for us.
1873 if (m->wire_count == 0) {
1874 vm_page_flag_clear(m, PG_ZERO);
1876 if (bp->b_flags & B_DIRECT) {
1878 * Attempt to free the page if B_DIRECT is
1879 * set, the caller does not desire the page
1880 * to be cached.
1882 vm_page_wakeup(m);
1883 vm_page_try_to_free(m);
1884 } else if ((bp->b_flags & B_NOTMETA) ||
1885 vm_page_count_min(0)) {
1887 * Attempt to move the page to PQ_CACHE
1888 * if B_NOTMETA is set. This flag is set
1889 * by HAMMER to remove one of the two pages
1890 * present when double buffering is enabled.
1892 * Attempt to move the page to PQ_CACHE
1893 * If we have a severe page deficit. This
1894 * will cause buffer cache operations related
1895 * to pageouts to recycle the related pages
1896 * in order to avoid a low memory deadlock.
1898 m->act_count = bp->b_act_count;
1899 vm_page_wakeup(m);
1900 vm_page_try_to_cache(m);
1901 } else {
1903 * Nominal case, leave the page on the
1904 * queue the original unwiring placed it on
1905 * (active or inactive).
1907 m->act_count = bp->b_act_count;
1908 vm_page_wakeup(m);
1910 } else {
1911 vm_page_wakeup(m);
1915 pmap_qremove(trunc_page((vm_offset_t) bp->b_data),
1916 bp->b_xio.xio_npages);
1917 if (bp->b_bufsize) {
1918 bufspacewakeup();
1919 bp->b_bufsize = 0;
1921 bp->b_xio.xio_npages = 0;
1922 bp->b_flags &= ~B_VMIO;
1923 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1924 if (bp->b_vp)
1925 brelvp(bp);
1929 * Find and initialize a new buffer header, freeing up existing buffers
1930 * in the bufqueues as necessary. The new buffer is returned locked.
1932 * Important: B_INVAL is not set. If the caller wishes to throw the
1933 * buffer away, the caller must set B_INVAL prior to calling brelse().
1935 * We block if:
1936 * We have insufficient buffer headers
1937 * We have insufficient buffer space
1938 * buffer_map is too fragmented ( space reservation fails )
1939 * If we have to flush dirty buffers ( but we try to avoid this )
1941 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1942 * Instead we ask the buf daemon to do it for us. We attempt to
1943 * avoid piecemeal wakeups of the pageout daemon.
1945 struct buf *
1946 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1948 struct bufpcpu *pcpu;
1949 struct buf *bp;
1950 struct buf *nbp;
1951 int defrag = 0;
1952 int nqindex;
1953 int nqcpu;
1954 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1955 int maxloops = 200000;
1956 int restart_reason = 0;
1957 struct buf *restart_bp = NULL;
1958 static int flushingbufs;
1961 * We can't afford to block since we might be holding a vnode lock,
1962 * which may prevent system daemons from running. We deal with
1963 * low-memory situations by proactively returning memory and running
1964 * async I/O rather then sync I/O.
1967 ++getnewbufcalls;
1968 --getnewbufrestarts;
1969 nqcpu = mycpu->gd_cpuid;
1970 restart:
1971 ++getnewbufrestarts;
1973 if (debug_bufbio && --maxloops == 0)
1974 panic("getnewbuf, excessive loops on cpu %d restart %d (%p)",
1975 mycpu->gd_cpuid, restart_reason, restart_bp);
1978 * Setup for scan. If we do not have enough free buffers,
1979 * we setup a degenerate case that immediately fails. Note
1980 * that if we are specially marked process, we are allowed to
1981 * dip into our reserves.
1983 * The scanning sequence is nominally: EMPTY->EMPTYKVA->CLEAN
1985 * We start with EMPTYKVA. If the list is empty we backup to EMPTY.
1986 * However, there are a number of cases (defragging, reusing, ...)
1987 * where we cannot backup.
1989 pcpu = &bufpcpu[nqcpu];
1990 nqindex = BQUEUE_EMPTYKVA;
1991 spin_lock(&pcpu->spin);
1993 nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_EMPTYKVA]);
1995 if (nbp == NULL) {
1997 * If no EMPTYKVA buffers and we are either
1998 * defragging or reusing, locate a CLEAN buffer
1999 * to free or reuse. If bufspace useage is low
2000 * skip this step so we can allocate a new buffer.
2002 if (defrag || bufspace >= lobufspace) {
2003 nqindex = BQUEUE_CLEAN;
2004 nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_CLEAN]);
2008 * If we could not find or were not allowed to reuse a
2009 * CLEAN buffer, check to see if it is ok to use an EMPTY
2010 * buffer. We can only use an EMPTY buffer if allocating
2011 * its KVA would not otherwise run us out of buffer space.
2013 if (nbp == NULL && defrag == 0 &&
2014 bufspace + maxsize < hibufspace) {
2015 nqindex = BQUEUE_EMPTY;
2016 nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_EMPTY]);
2021 * Run scan, possibly freeing data and/or kva mappings on the fly
2022 * depending.
2024 * WARNING! spin is held!
2026 while ((bp = nbp) != NULL) {
2027 int qindex = nqindex;
2029 nbp = TAILQ_NEXT(bp, b_freelist);
2032 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
2033 * cycles through the queue twice before being selected.
2035 if (qindex == BQUEUE_CLEAN &&
2036 (bp->b_flags & B_AGE) == 0 && nbp) {
2037 bp->b_flags |= B_AGE;
2038 TAILQ_REMOVE(&pcpu->bufqueues[qindex],
2039 bp, b_freelist);
2040 TAILQ_INSERT_TAIL(&pcpu->bufqueues[qindex],
2041 bp, b_freelist);
2042 continue;
2046 * Calculate next bp ( we can only use it if we do not block
2047 * or do other fancy things ).
2049 if (nbp == NULL) {
2050 switch(qindex) {
2051 case BQUEUE_EMPTY:
2052 nqindex = BQUEUE_EMPTYKVA;
2053 if ((nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_EMPTYKVA])))
2054 break;
2055 /* fall through */
2056 case BQUEUE_EMPTYKVA:
2057 nqindex = BQUEUE_CLEAN;
2058 if ((nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_CLEAN])))
2059 break;
2060 /* fall through */
2061 case BQUEUE_CLEAN:
2063 * nbp is NULL.
2065 break;
2070 * Sanity Checks
2072 KASSERT(bp->b_qindex == qindex,
2073 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2076 * Note: we no longer distinguish between VMIO and non-VMIO
2077 * buffers.
2079 KASSERT((bp->b_flags & B_DELWRI) == 0,
2080 ("delwri buffer %p found in queue %d", bp, qindex));
2083 * Do not try to reuse a buffer with a non-zero b_refs.
2084 * This is an unsynchronized test. A synchronized test
2085 * is also performed after we lock the buffer.
2087 if (bp->b_refs)
2088 continue;
2091 * If we are defragging then we need a buffer with
2092 * b_kvasize != 0. XXX this situation should no longer
2093 * occur, if defrag is non-zero the buffer's b_kvasize
2094 * should also be non-zero at this point. XXX
2096 if (defrag && bp->b_kvasize == 0) {
2097 kprintf("Warning: defrag empty buffer %p\n", bp);
2098 continue;
2102 * Start freeing the bp. This is somewhat involved. nbp
2103 * remains valid only for BQUEUE_EMPTY[KVA] bp's. Buffers
2104 * on the clean list must be disassociated from their
2105 * current vnode. Buffers on the empty[kva] lists have
2106 * already been disassociated.
2108 * b_refs is checked after locking along with queue changes.
2109 * We must check here to deal with zero->nonzero transitions
2110 * made by the owner of the buffer lock, which is used by
2111 * VFS's to hold the buffer while issuing an unlocked
2112 * uiomove()s. We cannot invalidate the buffer's pages
2113 * for this case. Once we successfully lock a buffer the
2114 * only 0->1 transitions of b_refs will occur via findblk().
2116 * We must also check for queue changes after successful
2117 * locking as the current lock holder may dispose of the
2118 * buffer and change its queue.
2120 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2121 spin_unlock(&pcpu->spin);
2122 tsleep(&bd_request, 0, "gnbxxx", (hz + 99) / 100);
2123 restart_reason = 1;
2124 restart_bp = bp;
2125 goto restart;
2127 if (bp->b_qindex != qindex || bp->b_refs) {
2128 spin_unlock(&pcpu->spin);
2129 BUF_UNLOCK(bp);
2130 restart_reason = 2;
2131 restart_bp = bp;
2132 goto restart;
2134 bremfree_locked(bp);
2135 spin_unlock(&pcpu->spin);
2138 * Dependancies must be handled before we disassociate the
2139 * vnode.
2141 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2142 * be immediately disassociated. HAMMER then becomes
2143 * responsible for releasing the buffer.
2145 * NOTE: spin is UNLOCKED now.
2147 if (LIST_FIRST(&bp->b_dep) != NULL) {
2148 buf_deallocate(bp);
2149 if (bp->b_flags & B_LOCKED) {
2150 bqrelse(bp);
2151 restart_reason = 3;
2152 restart_bp = bp;
2153 goto restart;
2155 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2158 if (qindex == BQUEUE_CLEAN) {
2159 if (bp->b_flags & B_VMIO)
2160 vfs_vmio_release(bp);
2161 if (bp->b_vp)
2162 brelvp(bp);
2166 * NOTE: nbp is now entirely invalid. We can only restart
2167 * the scan from this point on.
2169 * Get the rest of the buffer freed up. b_kva* is still
2170 * valid after this operation.
2172 KASSERT(bp->b_vp == NULL,
2173 ("bp3 %p flags %08x vnode %p qindex %d "
2174 "unexpectededly still associated!",
2175 bp, bp->b_flags, bp->b_vp, qindex));
2176 KKASSERT((bp->b_flags & B_HASHED) == 0);
2179 * critical section protection is not required when
2180 * scrapping a buffer's contents because it is already
2181 * wired.
2183 if (bp->b_bufsize)
2184 allocbuf(bp, 0);
2186 if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN | B_HASHED)) {
2187 kprintf("getnewbuf: caught bug vp queue "
2188 "%p/%08x qidx %d\n",
2189 bp, bp->b_flags, qindex);
2190 brelvp(bp);
2192 bp->b_flags = B_BNOCLIP;
2193 bp->b_cmd = BUF_CMD_DONE;
2194 bp->b_vp = NULL;
2195 bp->b_error = 0;
2196 bp->b_resid = 0;
2197 bp->b_bcount = 0;
2198 bp->b_xio.xio_npages = 0;
2199 bp->b_dirtyoff = bp->b_dirtyend = 0;
2200 bp->b_act_count = ACT_INIT;
2201 reinitbufbio(bp);
2202 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2203 buf_dep_init(bp);
2204 if (blkflags & GETBLK_BHEAVY)
2205 bp->b_flags |= B_HEAVY;
2208 * If we are defragging then free the buffer.
2210 if (defrag) {
2211 bp->b_flags |= B_INVAL;
2212 bfreekva(bp);
2213 brelse(bp);
2214 defrag = 0;
2215 restart_reason = 4;
2216 restart_bp = bp;
2217 goto restart;
2221 * If we are overcomitted then recover the buffer and its
2222 * KVM space. This occurs in rare situations when multiple
2223 * processes are blocked in getnewbuf() or allocbuf().
2225 * On 64-bit systems BKVASIZE == MAXBSIZE and overcommit
2226 * should not be possible.
2228 if (bufspace >= hibufspace)
2229 flushingbufs = 1;
2230 if (BKVASIZE != MAXBSIZE) {
2231 if (flushingbufs && bp->b_kvasize != 0) {
2232 bp->b_flags |= B_INVAL;
2233 bfreekva(bp);
2234 brelse(bp);
2235 restart_reason = 5;
2236 restart_bp = bp;
2237 goto restart;
2240 if (bufspace < lobufspace)
2241 flushingbufs = 0;
2244 * b_refs can transition to a non-zero value while we hold
2245 * the buffer locked due to a findblk(). Our brelvp() above
2246 * interlocked any future possible transitions due to
2247 * findblk()s.
2249 * If we find b_refs to be non-zero we can destroy the
2250 * buffer's contents but we cannot yet reuse the buffer.
2252 if (bp->b_refs) {
2253 bp->b_flags |= B_INVAL;
2254 if (BKVASIZE != MAXBSIZE)
2255 bfreekva(bp);
2256 brelse(bp);
2257 restart_reason = 6;
2258 restart_bp = bp;
2259 goto restart;
2261 break;
2262 /* NOT REACHED, spin not held */
2266 * If we exhausted our list, iterate other cpus. If that fails,
2267 * sleep as appropriate. We may have to wakeup various daemons
2268 * and write out some dirty buffers.
2270 * Generally we are sleeping due to insufficient buffer space.
2272 * NOTE: spin is held if bp is NULL, else it is not held.
2274 if (bp == NULL) {
2275 int flags;
2276 char *waitmsg;
2278 spin_unlock(&pcpu->spin);
2280 nqcpu = (nqcpu + 1) % ncpus;
2281 if (nqcpu != mycpu->gd_cpuid) {
2282 restart_reason = 7;
2283 restart_bp = bp;
2284 goto restart;
2287 if (defrag) {
2288 flags = VFS_BIO_NEED_BUFSPACE;
2289 waitmsg = "nbufkv";
2290 } else if (bufspace >= hibufspace) {
2291 waitmsg = "nbufbs";
2292 flags = VFS_BIO_NEED_BUFSPACE;
2293 } else {
2294 waitmsg = "newbuf";
2295 flags = VFS_BIO_NEED_ANY;
2298 bd_speedup(); /* heeeelp */
2299 atomic_set_int(&needsbuffer, flags);
2300 while (needsbuffer & flags) {
2301 int value;
2303 tsleep_interlock(&needsbuffer, 0);
2304 value = atomic_fetchadd_int(&needsbuffer, 0);
2305 if (value & flags) {
2306 if (tsleep(&needsbuffer, PINTERLOCKED|slpflags,
2307 waitmsg, slptimeo)) {
2308 return (NULL);
2312 } else {
2314 * We finally have a valid bp. We aren't quite out of the
2315 * woods, we still have to reserve kva space. In order
2316 * to keep fragmentation sane we only allocate kva in
2317 * BKVASIZE chunks.
2319 * (spin is not held)
2321 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
2323 if (maxsize != bp->b_kvasize) {
2324 vm_offset_t addr = 0;
2325 int count;
2327 bfreekva(bp);
2329 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2330 vm_map_lock(&buffer_map);
2332 if (vm_map_findspace(&buffer_map,
2333 vm_map_min(&buffer_map), maxsize,
2334 maxsize, 0, &addr)) {
2336 * Uh oh. Buffer map is too fragmented. We
2337 * must defragment the map.
2339 vm_map_unlock(&buffer_map);
2340 vm_map_entry_release(count);
2341 ++bufdefragcnt;
2342 defrag = 1;
2343 bp->b_flags |= B_INVAL;
2344 brelse(bp);
2345 restart_reason = 8;
2346 restart_bp = bp;
2347 goto restart;
2349 if (addr) {
2350 vm_map_insert(&buffer_map, &count,
2351 NULL, NULL,
2352 0, addr, addr + maxsize,
2353 VM_MAPTYPE_NORMAL,
2354 VM_PROT_ALL, VM_PROT_ALL,
2355 MAP_NOFAULT);
2357 bp->b_kvabase = (caddr_t) addr;
2358 bp->b_kvasize = maxsize;
2359 bufspace += bp->b_kvasize;
2360 ++bufreusecnt;
2362 vm_map_unlock(&buffer_map);
2363 vm_map_entry_release(count);
2365 bp->b_data = bp->b_kvabase;
2367 return(bp);
2371 * buf_daemon:
2373 * Buffer flushing daemon. Buffers are normally flushed by the
2374 * update daemon but if it cannot keep up this process starts to
2375 * take the load in an attempt to prevent getnewbuf() from blocking.
2377 * Once a flush is initiated it does not stop until the number
2378 * of buffers falls below lodirtybuffers, but we will wake up anyone
2379 * waiting at the mid-point.
2381 static struct kproc_desc buf_kp = {
2382 "bufdaemon",
2383 buf_daemon,
2384 &bufdaemon_td
2386 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2387 kproc_start, &buf_kp);
2389 static struct kproc_desc bufhw_kp = {
2390 "bufdaemon_hw",
2391 buf_daemon_hw,
2392 &bufdaemonhw_td
2394 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2395 kproc_start, &bufhw_kp);
2397 static void
2398 buf_daemon1(struct thread *td, int queue, int (*buf_limit_fn)(long),
2399 int *bd_req)
2401 long limit;
2402 struct buf *marker;
2404 marker = kmalloc(sizeof(*marker), M_BIOBUF, M_WAITOK | M_ZERO);
2405 marker->b_flags |= B_MARKER;
2406 marker->b_qindex = BQUEUE_NONE;
2407 marker->b_qcpu = 0;
2410 * This process needs to be suspended prior to shutdown sync.
2412 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2413 td, SHUTDOWN_PRI_LAST);
2414 curthread->td_flags |= TDF_SYSTHREAD;
2417 * This process is allowed to take the buffer cache to the limit
2419 for (;;) {
2420 kproc_suspend_loop();
2423 * Do the flush as long as the number of dirty buffers
2424 * (including those running) exceeds lodirtybufspace.
2426 * When flushing limit running I/O to hirunningspace
2427 * Do the flush. Limit the amount of in-transit I/O we
2428 * allow to build up, otherwise we would completely saturate
2429 * the I/O system. Wakeup any waiting processes before we
2430 * normally would so they can run in parallel with our drain.
2432 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2433 * but because we split the operation into two threads we
2434 * have to cut it in half for each thread.
2436 waitrunningbufspace();
2437 limit = lodirtybufspace / 2;
2438 while (buf_limit_fn(limit)) {
2439 if (flushbufqueues(marker, queue) == 0)
2440 break;
2441 if (runningbufspace < hirunningspace)
2442 continue;
2443 waitrunningbufspace();
2447 * We reached our low water mark, reset the
2448 * request and sleep until we are needed again.
2449 * The sleep is just so the suspend code works.
2451 tsleep_interlock(bd_req, 0);
2452 if (atomic_swap_int(bd_req, 0) == 0)
2453 tsleep(bd_req, PINTERLOCKED, "psleep", hz);
2455 /* NOT REACHED */
2456 /*kfree(marker, M_BIOBUF);*/
2459 static int
2460 buf_daemon_limit(long limit)
2462 return (runningbufspace + dirtykvaspace > limit ||
2463 dirtybufcount - dirtybufcounthw >= nbuf / 2);
2466 static int
2467 buf_daemon_hw_limit(long limit)
2469 return (runningbufspace + dirtykvaspace > limit ||
2470 dirtybufcounthw >= nbuf / 2);
2473 static void
2474 buf_daemon(void)
2476 buf_daemon1(bufdaemon_td, BQUEUE_DIRTY, buf_daemon_limit,
2477 &bd_request);
2480 static void
2481 buf_daemon_hw(void)
2483 buf_daemon1(bufdaemonhw_td, BQUEUE_DIRTY_HW, buf_daemon_hw_limit,
2484 &bd_request_hw);
2488 * Flush up to (flushperqueue) buffers in the dirty queue. Each cpu has a
2489 * localized version of the queue. Each call made to this function iterates
2490 * to another cpu. It is desireable to flush several buffers from the same
2491 * cpu's queue at once, as these are likely going to be linear.
2493 * We must be careful to free up B_INVAL buffers instead of write them, which
2494 * NFS is particularly sensitive to.
2496 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate that we
2497 * really want to try to get the buffer out and reuse it due to the write
2498 * load on the machine.
2500 * We must lock the buffer in order to check its validity before we can mess
2501 * with its contents. spin isn't enough.
2503 static int
2504 flushbufqueues(struct buf *marker, bufq_type_t q)
2506 struct bufpcpu *pcpu;
2507 struct buf *bp;
2508 int r = 0;
2509 u_int loops = flushperqueue;
2510 int lcpu = marker->b_qcpu;
2512 KKASSERT(marker->b_qindex == BQUEUE_NONE);
2513 KKASSERT(marker->b_flags & B_MARKER);
2515 again:
2517 * Spinlock needed to perform operations on the queue and may be
2518 * held through a non-blocking BUF_LOCK(), but cannot be held when
2519 * BUF_UNLOCK()ing or through any other major operation.
2521 pcpu = &bufpcpu[marker->b_qcpu];
2522 spin_lock(&pcpu->spin);
2523 marker->b_qindex = q;
2524 TAILQ_INSERT_HEAD(&pcpu->bufqueues[q], marker, b_freelist);
2525 bp = marker;
2527 while ((bp = TAILQ_NEXT(bp, b_freelist)) != NULL) {
2529 * NOTE: spinlock is always held at the top of the loop
2531 if (bp->b_flags & B_MARKER)
2532 continue;
2533 if ((bp->b_flags & B_DELWRI) == 0) {
2534 kprintf("Unexpected clean buffer %p\n", bp);
2535 continue;
2537 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
2538 continue;
2539 KKASSERT(bp->b_qcpu == marker->b_qcpu && bp->b_qindex == q);
2542 * Once the buffer is locked we will have no choice but to
2543 * unlock the spinlock around a later BUF_UNLOCK and re-set
2544 * bp = marker when looping. Move the marker now to make
2545 * things easier.
2547 TAILQ_REMOVE(&pcpu->bufqueues[q], marker, b_freelist);
2548 TAILQ_INSERT_AFTER(&pcpu->bufqueues[q], bp, marker, b_freelist);
2551 * Must recheck B_DELWRI after successfully locking
2552 * the buffer.
2554 if ((bp->b_flags & B_DELWRI) == 0) {
2555 spin_unlock(&pcpu->spin);
2556 BUF_UNLOCK(bp);
2557 spin_lock(&pcpu->spin);
2558 bp = marker;
2559 continue;
2563 * Remove the buffer from its queue. We still own the
2564 * spinlock here.
2566 _bremfree(bp);
2569 * Disposing of an invalid buffer counts as a flush op
2571 if (bp->b_flags & B_INVAL) {
2572 spin_unlock(&pcpu->spin);
2573 brelse(bp);
2574 goto doloop;
2578 * Release the spinlock for the more complex ops we
2579 * are now going to do.
2581 spin_unlock(&pcpu->spin);
2582 lwkt_yield();
2585 * This is a bit messy
2587 if (LIST_FIRST(&bp->b_dep) != NULL &&
2588 (bp->b_flags & B_DEFERRED) == 0 &&
2589 buf_countdeps(bp, 0)) {
2590 spin_lock(&pcpu->spin);
2591 TAILQ_INSERT_TAIL(&pcpu->bufqueues[q], bp, b_freelist);
2592 bp->b_qindex = q;
2593 bp->b_flags |= B_DEFERRED;
2594 spin_unlock(&pcpu->spin);
2595 BUF_UNLOCK(bp);
2596 spin_lock(&pcpu->spin);
2597 bp = marker;
2598 continue;
2602 * spinlock not held here.
2604 * If the buffer has a dependancy, buf_checkwrite() must
2605 * also return 0 for us to be able to initate the write.
2607 * If the buffer is flagged B_ERROR it may be requeued
2608 * over and over again, we try to avoid a live lock.
2610 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
2611 brelse(bp);
2612 } else if (bp->b_flags & B_ERROR) {
2613 tsleep(bp, 0, "bioer", 1);
2614 bp->b_flags &= ~B_AGE;
2615 cluster_awrite(bp);
2616 } else {
2617 bp->b_flags |= B_AGE;
2618 cluster_awrite(bp);
2620 /* bp invalid but needs to be NULL-tested if we break out */
2621 doloop:
2622 spin_lock(&pcpu->spin);
2623 ++r;
2624 if (--loops == 0)
2625 break;
2626 bp = marker;
2628 /* bp is invalid here but can be NULL-tested to advance */
2630 TAILQ_REMOVE(&pcpu->bufqueues[q], marker, b_freelist);
2631 marker->b_qindex = BQUEUE_NONE;
2632 spin_unlock(&pcpu->spin);
2635 * Advance the marker to be fair.
2637 marker->b_qcpu = (marker->b_qcpu + 1) % ncpus;
2638 if (bp == NULL) {
2639 if (marker->b_qcpu != lcpu)
2640 goto again;
2643 return (r);
2647 * inmem:
2649 * Returns true if no I/O is needed to access the associated VM object.
2650 * This is like findblk except it also hunts around in the VM system for
2651 * the data.
2653 * Note that we ignore vm_page_free() races from interrupts against our
2654 * lookup, since if the caller is not protected our return value will not
2655 * be any more valid then otherwise once we exit the critical section.
2658 inmem(struct vnode *vp, off_t loffset)
2660 vm_object_t obj;
2661 vm_offset_t toff, tinc, size;
2662 vm_page_t m;
2663 int res = 1;
2665 if (findblk(vp, loffset, FINDBLK_TEST))
2666 return 1;
2667 if (vp->v_mount == NULL)
2668 return 0;
2669 if ((obj = vp->v_object) == NULL)
2670 return 0;
2672 size = PAGE_SIZE;
2673 if (size > vp->v_mount->mnt_stat.f_iosize)
2674 size = vp->v_mount->mnt_stat.f_iosize;
2676 vm_object_hold(obj);
2677 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2678 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2679 if (m == NULL) {
2680 res = 0;
2681 break;
2683 tinc = size;
2684 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2685 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2686 if (vm_page_is_valid(m,
2687 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0) {
2688 res = 0;
2689 break;
2692 vm_object_drop(obj);
2693 return (res);
2697 * findblk:
2699 * Locate and return the specified buffer. Unless flagged otherwise,
2700 * a locked buffer will be returned if it exists or NULL if it does not.
2702 * findblk()'d buffers are still on the bufqueues and if you intend
2703 * to use your (locked NON-TEST) buffer you need to bremfree(bp)
2704 * and possibly do other stuff to it.
2706 * FINDBLK_TEST - Do not lock the buffer. The caller is responsible
2707 * for locking the buffer and ensuring that it remains
2708 * the desired buffer after locking.
2710 * FINDBLK_NBLOCK - Lock the buffer non-blocking. If we are unable
2711 * to acquire the lock we return NULL, even if the
2712 * buffer exists.
2714 * FINDBLK_REF - Returns the buffer ref'd, which prevents normal
2715 * reuse by getnewbuf() but does not prevent
2716 * disassociation (B_INVAL). Used to avoid deadlocks
2717 * against random (vp,loffset)s due to reassignment.
2719 * (0) - Lock the buffer blocking.
2721 struct buf *
2722 findblk(struct vnode *vp, off_t loffset, int flags)
2724 struct buf *bp;
2725 int lkflags;
2727 lkflags = LK_EXCLUSIVE;
2728 if (flags & FINDBLK_NBLOCK)
2729 lkflags |= LK_NOWAIT;
2731 for (;;) {
2733 * Lookup. Ref the buf while holding v_token to prevent
2734 * reuse (but does not prevent diassociation).
2736 lwkt_gettoken_shared(&vp->v_token);
2737 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2738 if (bp == NULL) {
2739 lwkt_reltoken(&vp->v_token);
2740 return(NULL);
2742 bqhold(bp);
2743 lwkt_reltoken(&vp->v_token);
2746 * If testing only break and return bp, do not lock.
2748 if (flags & FINDBLK_TEST)
2749 break;
2752 * Lock the buffer, return an error if the lock fails.
2753 * (only FINDBLK_NBLOCK can cause the lock to fail).
2755 if (BUF_LOCK(bp, lkflags)) {
2756 atomic_subtract_int(&bp->b_refs, 1);
2757 /* bp = NULL; not needed */
2758 return(NULL);
2762 * Revalidate the locked buf before allowing it to be
2763 * returned.
2765 if (bp->b_vp == vp && bp->b_loffset == loffset)
2766 break;
2767 atomic_subtract_int(&bp->b_refs, 1);
2768 BUF_UNLOCK(bp);
2772 * Success
2774 if ((flags & FINDBLK_REF) == 0)
2775 atomic_subtract_int(&bp->b_refs, 1);
2776 return(bp);
2780 * getcacheblk:
2782 * Similar to getblk() except only returns the buffer if it is
2783 * B_CACHE and requires no other manipulation. Otherwise NULL
2784 * is returned. NULL is also returned if GETBLK_NOWAIT is set
2785 * and the getblk() would block.
2787 * If B_RAM is set the buffer might be just fine, but we return
2788 * NULL anyway because we want the code to fall through to the
2789 * cluster read to issue more read-aheads. Otherwise read-ahead breaks.
2791 * If blksize is 0 the buffer cache buffer must already be fully
2792 * cached.
2794 * If blksize is non-zero getblk() will be used, allowing a buffer
2795 * to be reinstantiated from its VM backing store. The buffer must
2796 * still be fully cached after reinstantiation to be returned.
2798 struct buf *
2799 getcacheblk(struct vnode *vp, off_t loffset, int blksize, int blkflags)
2801 struct buf *bp;
2802 int fndflags = (blkflags & GETBLK_NOWAIT) ? FINDBLK_NBLOCK : 0;
2804 if (blksize) {
2805 bp = getblk(vp, loffset, blksize, blkflags, 0);
2806 if (bp) {
2807 if ((bp->b_flags & (B_INVAL | B_CACHE)) == B_CACHE) {
2808 bp->b_flags &= ~B_AGE;
2809 if (bp->b_flags & B_RAM) {
2810 bqrelse(bp);
2811 bp = NULL;
2813 } else {
2814 brelse(bp);
2815 bp = NULL;
2818 } else {
2819 bp = findblk(vp, loffset, fndflags);
2820 if (bp) {
2821 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) ==
2822 B_CACHE) {
2823 bp->b_flags &= ~B_AGE;
2824 bremfree(bp);
2825 } else {
2826 BUF_UNLOCK(bp);
2827 bp = NULL;
2831 return (bp);
2835 * getblk:
2837 * Get a block given a specified block and offset into a file/device.
2838 * B_INVAL may or may not be set on return. The caller should clear
2839 * B_INVAL prior to initiating a READ.
2841 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2842 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2843 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2844 * without doing any of those things the system will likely believe
2845 * the buffer to be valid (especially if it is not B_VMIO), and the
2846 * next getblk() will return the buffer with B_CACHE set.
2848 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2849 * an existing buffer.
2851 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2852 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2853 * and then cleared based on the backing VM. If the previous buffer is
2854 * non-0-sized but invalid, B_CACHE will be cleared.
2856 * If getblk() must create a new buffer, the new buffer is returned with
2857 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2858 * case it is returned with B_INVAL clear and B_CACHE set based on the
2859 * backing VM.
2861 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2862 * B_CACHE bit is clear.
2864 * What this means, basically, is that the caller should use B_CACHE to
2865 * determine whether the buffer is fully valid or not and should clear
2866 * B_INVAL prior to issuing a read. If the caller intends to validate
2867 * the buffer by loading its data area with something, the caller needs
2868 * to clear B_INVAL. If the caller does this without issuing an I/O,
2869 * the caller should set B_CACHE ( as an optimization ), else the caller
2870 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2871 * a write attempt or if it was a successfull read. If the caller
2872 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2873 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2875 * getblk flags:
2877 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2878 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2880 struct buf *
2881 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2883 struct buf *bp;
2884 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2885 int error;
2886 int lkflags;
2888 if (size > MAXBSIZE)
2889 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2890 if (vp->v_object == NULL)
2891 panic("getblk: vnode %p has no object!", vp);
2893 loop:
2894 if ((bp = findblk(vp, loffset, FINDBLK_REF | FINDBLK_TEST)) != NULL) {
2896 * The buffer was found in the cache, but we need to lock it.
2897 * We must acquire a ref on the bp to prevent reuse, but
2898 * this will not prevent disassociation (brelvp()) so we
2899 * must recheck (vp,loffset) after acquiring the lock.
2901 * Without the ref the buffer could potentially be reused
2902 * before we acquire the lock and create a deadlock
2903 * situation between the thread trying to reuse the buffer
2904 * and us due to the fact that we would wind up blocking
2905 * on a random (vp,loffset).
2907 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2908 if (blkflags & GETBLK_NOWAIT) {
2909 bqdrop(bp);
2910 return(NULL);
2912 lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2913 if (blkflags & GETBLK_PCATCH)
2914 lkflags |= LK_PCATCH;
2915 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2916 if (error) {
2917 bqdrop(bp);
2918 if (error == ENOLCK)
2919 goto loop;
2920 return (NULL);
2922 /* buffer may have changed on us */
2924 bqdrop(bp);
2927 * Once the buffer has been locked, make sure we didn't race
2928 * a buffer recyclement. Buffers that are no longer hashed
2929 * will have b_vp == NULL, so this takes care of that check
2930 * as well.
2932 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2933 #if 0
2934 kprintf("Warning buffer %p (vp %p loffset %lld) "
2935 "was recycled\n",
2936 bp, vp, (long long)loffset);
2937 #endif
2938 BUF_UNLOCK(bp);
2939 goto loop;
2943 * If SZMATCH any pre-existing buffer must be of the requested
2944 * size or NULL is returned. The caller absolutely does not
2945 * want getblk() to bwrite() the buffer on a size mismatch.
2947 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2948 BUF_UNLOCK(bp);
2949 return(NULL);
2953 * All vnode-based buffers must be backed by a VM object.
2955 KKASSERT(bp->b_flags & B_VMIO);
2956 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2957 bp->b_flags &= ~B_AGE;
2960 * Make sure that B_INVAL buffers do not have a cached
2961 * block number translation.
2963 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2964 kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2965 " did not have cleared bio_offset cache\n",
2966 bp, vp, (long long)loffset);
2967 clearbiocache(&bp->b_bio2);
2971 * The buffer is locked. B_CACHE is cleared if the buffer is
2972 * invalid.
2974 if (bp->b_flags & B_INVAL)
2975 bp->b_flags &= ~B_CACHE;
2976 bremfree(bp);
2979 * Any size inconsistancy with a dirty buffer or a buffer
2980 * with a softupdates dependancy must be resolved. Resizing
2981 * the buffer in such circumstances can lead to problems.
2983 * Dirty or dependant buffers are written synchronously.
2984 * Other types of buffers are simply released and
2985 * reconstituted as they may be backed by valid, dirty VM
2986 * pages (but not marked B_DELWRI).
2988 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2989 * and may be left over from a prior truncation (and thus
2990 * no longer represent the actual EOF point), so we
2991 * definitely do not want to B_NOCACHE the backing store.
2993 if (size != bp->b_bcount) {
2994 if (bp->b_flags & B_DELWRI) {
2995 bp->b_flags |= B_RELBUF;
2996 bwrite(bp);
2997 } else if (LIST_FIRST(&bp->b_dep)) {
2998 bp->b_flags |= B_RELBUF;
2999 bwrite(bp);
3000 } else {
3001 bp->b_flags |= B_RELBUF;
3002 brelse(bp);
3004 goto loop;
3006 KKASSERT(size <= bp->b_kvasize);
3007 KASSERT(bp->b_loffset != NOOFFSET,
3008 ("getblk: no buffer offset"));
3011 * A buffer with B_DELWRI set and B_CACHE clear must
3012 * be committed before we can return the buffer in
3013 * order to prevent the caller from issuing a read
3014 * ( due to B_CACHE not being set ) and overwriting
3015 * it.
3017 * Most callers, including NFS and FFS, need this to
3018 * operate properly either because they assume they
3019 * can issue a read if B_CACHE is not set, or because
3020 * ( for example ) an uncached B_DELWRI might loop due
3021 * to softupdates re-dirtying the buffer. In the latter
3022 * case, B_CACHE is set after the first write completes,
3023 * preventing further loops.
3025 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
3026 * above while extending the buffer, we cannot allow the
3027 * buffer to remain with B_CACHE set after the write
3028 * completes or it will represent a corrupt state. To
3029 * deal with this we set B_NOCACHE to scrap the buffer
3030 * after the write.
3032 * XXX Should this be B_RELBUF instead of B_NOCACHE?
3033 * I'm not even sure this state is still possible
3034 * now that getblk() writes out any dirty buffers
3035 * on size changes.
3037 * We might be able to do something fancy, like setting
3038 * B_CACHE in bwrite() except if B_DELWRI is already set,
3039 * so the below call doesn't set B_CACHE, but that gets real
3040 * confusing. This is much easier.
3043 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
3044 kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
3045 "and CACHE clear, b_flags %08x\n",
3046 bp, (uintmax_t)bp->b_loffset, bp->b_flags);
3047 bp->b_flags |= B_NOCACHE;
3048 bwrite(bp);
3049 goto loop;
3051 } else {
3053 * Buffer is not in-core, create new buffer. The buffer
3054 * returned by getnewbuf() is locked. Note that the returned
3055 * buffer is also considered valid (not marked B_INVAL).
3057 * Calculating the offset for the I/O requires figuring out
3058 * the block size. We use DEV_BSIZE for VBLK or VCHR and
3059 * the mount's f_iosize otherwise. If the vnode does not
3060 * have an associated mount we assume that the passed size is
3061 * the block size.
3063 * Note that vn_isdisk() cannot be used here since it may
3064 * return a failure for numerous reasons. Note that the
3065 * buffer size may be larger then the block size (the caller
3066 * will use block numbers with the proper multiple). Beware
3067 * of using any v_* fields which are part of unions. In
3068 * particular, in DragonFly the mount point overloading
3069 * mechanism uses the namecache only and the underlying
3070 * directory vnode is not a special case.
3072 int bsize, maxsize;
3074 if (vp->v_type == VBLK || vp->v_type == VCHR)
3075 bsize = DEV_BSIZE;
3076 else if (vp->v_mount)
3077 bsize = vp->v_mount->mnt_stat.f_iosize;
3078 else
3079 bsize = size;
3081 maxsize = size + (loffset & PAGE_MASK);
3082 maxsize = imax(maxsize, bsize);
3084 bp = getnewbuf(blkflags, slptimeo, size, maxsize);
3085 if (bp == NULL) {
3086 if (slpflags || slptimeo)
3087 return NULL;
3088 goto loop;
3092 * Atomically insert the buffer into the hash, so that it can
3093 * be found by findblk().
3095 * If bgetvp() returns non-zero a collision occured, and the
3096 * bp will not be associated with the vnode.
3098 * Make sure the translation layer has been cleared.
3100 bp->b_loffset = loffset;
3101 bp->b_bio2.bio_offset = NOOFFSET;
3102 /* bp->b_bio2.bio_next = NULL; */
3104 if (bgetvp(vp, bp, size)) {
3105 bp->b_flags |= B_INVAL;
3106 brelse(bp);
3107 goto loop;
3111 * All vnode-based buffers must be backed by a VM object.
3113 KKASSERT(vp->v_object != NULL);
3114 bp->b_flags |= B_VMIO;
3115 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3117 allocbuf(bp, size);
3119 return (bp);
3123 * regetblk(bp)
3125 * Reacquire a buffer that was previously released to the locked queue,
3126 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
3127 * set B_LOCKED (which handles the acquisition race).
3129 * To this end, either B_LOCKED must be set or the dependancy list must be
3130 * non-empty.
3132 void
3133 regetblk(struct buf *bp)
3135 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
3136 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
3137 bremfree(bp);
3141 * geteblk:
3143 * Get an empty, disassociated buffer of given size. The buffer is
3144 * initially set to B_INVAL.
3146 * critical section protection is not required for the allocbuf()
3147 * call because races are impossible here.
3149 struct buf *
3150 geteblk(int size)
3152 struct buf *bp;
3153 int maxsize;
3155 maxsize = (size + BKVAMASK) & ~BKVAMASK;
3157 while ((bp = getnewbuf(0, 0, size, maxsize)) == NULL)
3159 allocbuf(bp, size);
3160 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3161 return (bp);
3166 * allocbuf:
3168 * This code constitutes the buffer memory from either anonymous system
3169 * memory (in the case of non-VMIO operations) or from an associated
3170 * VM object (in the case of VMIO operations). This code is able to
3171 * resize a buffer up or down.
3173 * Note that this code is tricky, and has many complications to resolve
3174 * deadlock or inconsistant data situations. Tread lightly!!!
3175 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3176 * the caller. Calling this code willy nilly can result in the loss of
3177 * data.
3179 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3180 * B_CACHE for the non-VMIO case.
3182 * This routine does not need to be called from a critical section but you
3183 * must own the buffer.
3186 allocbuf(struct buf *bp, int size)
3188 int newbsize, mbsize;
3189 int i;
3191 if (BUF_REFCNT(bp) == 0)
3192 panic("allocbuf: buffer not busy");
3194 if (bp->b_kvasize < size)
3195 panic("allocbuf: buffer too small");
3197 if ((bp->b_flags & B_VMIO) == 0) {
3198 caddr_t origbuf;
3199 int origbufsize;
3201 * Just get anonymous memory from the kernel. Don't
3202 * mess with B_CACHE.
3204 mbsize = roundup2(size, DEV_BSIZE);
3205 if (bp->b_flags & B_MALLOC)
3206 newbsize = mbsize;
3207 else
3208 newbsize = round_page(size);
3210 if (newbsize < bp->b_bufsize) {
3212 * Malloced buffers are not shrunk
3214 if (bp->b_flags & B_MALLOC) {
3215 if (newbsize) {
3216 bp->b_bcount = size;
3217 } else {
3218 kfree(bp->b_data, M_BIOBUF);
3219 if (bp->b_bufsize) {
3220 atomic_subtract_long(&bufmallocspace, bp->b_bufsize);
3221 bufspacewakeup();
3222 bp->b_bufsize = 0;
3224 bp->b_data = bp->b_kvabase;
3225 bp->b_bcount = 0;
3226 bp->b_flags &= ~B_MALLOC;
3228 return 1;
3230 vm_hold_free_pages(
3232 (vm_offset_t) bp->b_data + newbsize,
3233 (vm_offset_t) bp->b_data + bp->b_bufsize);
3234 } else if (newbsize > bp->b_bufsize) {
3236 * We only use malloced memory on the first allocation.
3237 * and revert to page-allocated memory when the buffer
3238 * grows.
3240 if ((bufmallocspace < maxbufmallocspace) &&
3241 (bp->b_bufsize == 0) &&
3242 (mbsize <= PAGE_SIZE/2)) {
3244 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
3245 bp->b_bufsize = mbsize;
3246 bp->b_bcount = size;
3247 bp->b_flags |= B_MALLOC;
3248 atomic_add_long(&bufmallocspace, mbsize);
3249 return 1;
3251 origbuf = NULL;
3252 origbufsize = 0;
3254 * If the buffer is growing on its other-than-first
3255 * allocation, then we revert to the page-allocation
3256 * scheme.
3258 if (bp->b_flags & B_MALLOC) {
3259 origbuf = bp->b_data;
3260 origbufsize = bp->b_bufsize;
3261 bp->b_data = bp->b_kvabase;
3262 if (bp->b_bufsize) {
3263 atomic_subtract_long(&bufmallocspace,
3264 bp->b_bufsize);
3265 bufspacewakeup();
3266 bp->b_bufsize = 0;
3268 bp->b_flags &= ~B_MALLOC;
3269 newbsize = round_page(newbsize);
3271 vm_hold_load_pages(
3273 (vm_offset_t) bp->b_data + bp->b_bufsize,
3274 (vm_offset_t) bp->b_data + newbsize);
3275 if (origbuf) {
3276 bcopy(origbuf, bp->b_data, origbufsize);
3277 kfree(origbuf, M_BIOBUF);
3280 } else {
3281 vm_page_t m;
3282 int desiredpages;
3284 newbsize = roundup2(size, DEV_BSIZE);
3285 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3286 newbsize + PAGE_MASK) >> PAGE_SHIFT;
3287 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
3289 if (bp->b_flags & B_MALLOC)
3290 panic("allocbuf: VMIO buffer can't be malloced");
3292 * Set B_CACHE initially if buffer is 0 length or will become
3293 * 0-length.
3295 if (size == 0 || bp->b_bufsize == 0)
3296 bp->b_flags |= B_CACHE;
3298 if (newbsize < bp->b_bufsize) {
3300 * DEV_BSIZE aligned new buffer size is less then the
3301 * DEV_BSIZE aligned existing buffer size. Figure out
3302 * if we have to remove any pages.
3304 if (desiredpages < bp->b_xio.xio_npages) {
3305 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
3307 * the page is not freed here -- it
3308 * is the responsibility of
3309 * vnode_pager_setsize
3311 m = bp->b_xio.xio_pages[i];
3312 KASSERT(m != bogus_page,
3313 ("allocbuf: bogus page found"));
3314 vm_page_busy_wait(m, TRUE, "biodep");
3315 bp->b_xio.xio_pages[i] = NULL;
3316 vm_page_unwire(m, 0);
3317 vm_page_wakeup(m);
3319 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
3320 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
3321 bp->b_xio.xio_npages = desiredpages;
3323 } else if (size > bp->b_bcount) {
3325 * We are growing the buffer, possibly in a
3326 * byte-granular fashion.
3328 struct vnode *vp;
3329 vm_object_t obj;
3330 vm_offset_t toff;
3331 vm_offset_t tinc;
3334 * Step 1, bring in the VM pages from the object,
3335 * allocating them if necessary. We must clear
3336 * B_CACHE if these pages are not valid for the
3337 * range covered by the buffer.
3339 * critical section protection is required to protect
3340 * against interrupts unbusying and freeing pages
3341 * between our vm_page_lookup() and our
3342 * busycheck/wiring call.
3344 vp = bp->b_vp;
3345 obj = vp->v_object;
3347 vm_object_hold(obj);
3348 while (bp->b_xio.xio_npages < desiredpages) {
3349 vm_page_t m;
3350 vm_pindex_t pi;
3351 int error;
3353 pi = OFF_TO_IDX(bp->b_loffset) +
3354 bp->b_xio.xio_npages;
3357 * Blocking on m->busy might lead to a
3358 * deadlock:
3360 * vm_fault->getpages->cluster_read->allocbuf
3362 m = vm_page_lookup_busy_try(obj, pi, FALSE,
3363 &error);
3364 if (error) {
3365 vm_page_sleep_busy(m, FALSE, "pgtblk");
3366 continue;
3368 if (m == NULL) {
3370 * note: must allocate system pages
3371 * since blocking here could intefere
3372 * with paging I/O, no matter which
3373 * process we are.
3375 m = bio_page_alloc(bp, obj, pi, desiredpages - bp->b_xio.xio_npages);
3376 if (m) {
3377 vm_page_wire(m);
3378 vm_page_flag_clear(m, PG_ZERO);
3379 vm_page_wakeup(m);
3380 bp->b_flags &= ~B_CACHE;
3381 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3382 ++bp->b_xio.xio_npages;
3384 continue;
3388 * We found a page and were able to busy it.
3390 vm_page_flag_clear(m, PG_ZERO);
3391 vm_page_wire(m);
3392 vm_page_wakeup(m);
3393 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3394 ++bp->b_xio.xio_npages;
3395 if (bp->b_act_count < m->act_count)
3396 bp->b_act_count = m->act_count;
3398 vm_object_drop(obj);
3401 * Step 2. We've loaded the pages into the buffer,
3402 * we have to figure out if we can still have B_CACHE
3403 * set. Note that B_CACHE is set according to the
3404 * byte-granular range ( bcount and size ), not the
3405 * aligned range ( newbsize ).
3407 * The VM test is against m->valid, which is DEV_BSIZE
3408 * aligned. Needless to say, the validity of the data
3409 * needs to also be DEV_BSIZE aligned. Note that this
3410 * fails with NFS if the server or some other client
3411 * extends the file's EOF. If our buffer is resized,
3412 * B_CACHE may remain set! XXX
3415 toff = bp->b_bcount;
3416 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3418 while ((bp->b_flags & B_CACHE) && toff < size) {
3419 vm_pindex_t pi;
3421 if (tinc > (size - toff))
3422 tinc = size - toff;
3424 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
3425 PAGE_SHIFT;
3427 vfs_buf_test_cache(
3428 bp,
3429 bp->b_loffset,
3430 toff,
3431 tinc,
3432 bp->b_xio.xio_pages[pi]
3434 toff += tinc;
3435 tinc = PAGE_SIZE;
3439 * Step 3, fixup the KVM pmap. Remember that
3440 * bp->b_data is relative to bp->b_loffset, but
3441 * bp->b_loffset may be offset into the first page.
3444 bp->b_data = (caddr_t)
3445 trunc_page((vm_offset_t)bp->b_data);
3446 pmap_qenter(
3447 (vm_offset_t)bp->b_data,
3448 bp->b_xio.xio_pages,
3449 bp->b_xio.xio_npages
3451 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3452 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3456 /* adjust space use on already-dirty buffer */
3457 if (bp->b_flags & B_DELWRI) {
3458 /* dirtykvaspace unchanged */
3459 atomic_add_long(&dirtybufspace, newbsize - bp->b_bufsize);
3460 if (bp->b_flags & B_HEAVY) {
3461 atomic_add_long(&dirtybufspacehw,
3462 newbsize - bp->b_bufsize);
3465 if (newbsize < bp->b_bufsize)
3466 bufspacewakeup();
3467 bp->b_bufsize = newbsize; /* actual buffer allocation */
3468 bp->b_bcount = size; /* requested buffer size */
3469 return 1;
3473 * biowait:
3475 * Wait for buffer I/O completion, returning error status. B_EINTR
3476 * is converted into an EINTR error but not cleared (since a chain
3477 * of biowait() calls may occur).
3479 * On return bpdone() will have been called but the buffer will remain
3480 * locked and will not have been brelse()'d.
3482 * NOTE! If a timeout is specified and ETIMEDOUT occurs the I/O is
3483 * likely still in progress on return.
3485 * NOTE! This operation is on a BIO, not a BUF.
3487 * NOTE! BIO_DONE is cleared by vn_strategy()
3489 static __inline int
3490 _biowait(struct bio *bio, const char *wmesg, int to)
3492 struct buf *bp = bio->bio_buf;
3493 u_int32_t flags;
3494 u_int32_t nflags;
3495 int error;
3497 KKASSERT(bio == &bp->b_bio1);
3498 for (;;) {
3499 flags = bio->bio_flags;
3500 if (flags & BIO_DONE)
3501 break;
3502 nflags = flags | BIO_WANT;
3503 tsleep_interlock(bio, 0);
3504 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3505 if (wmesg)
3506 error = tsleep(bio, PINTERLOCKED, wmesg, to);
3507 else if (bp->b_cmd == BUF_CMD_READ)
3508 error = tsleep(bio, PINTERLOCKED, "biord", to);
3509 else
3510 error = tsleep(bio, PINTERLOCKED, "biowr", to);
3511 if (error) {
3512 kprintf("tsleep error biowait %d\n", error);
3513 return (error);
3519 * Finish up.
3521 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3522 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
3523 if (bp->b_flags & B_EINTR)
3524 return (EINTR);
3525 if (bp->b_flags & B_ERROR)
3526 return (bp->b_error ? bp->b_error : EIO);
3527 return (0);
3531 biowait(struct bio *bio, const char *wmesg)
3533 return(_biowait(bio, wmesg, 0));
3537 biowait_timeout(struct bio *bio, const char *wmesg, int to)
3539 return(_biowait(bio, wmesg, to));
3543 * This associates a tracking count with an I/O. vn_strategy() and
3544 * dev_dstrategy() do this automatically but there are a few cases
3545 * where a vnode or device layer is bypassed when a block translation
3546 * is cached. In such cases bio_start_transaction() may be called on
3547 * the bypassed layers so the system gets an I/O in progress indication
3548 * for those higher layers.
3550 void
3551 bio_start_transaction(struct bio *bio, struct bio_track *track)
3553 bio->bio_track = track;
3554 bio_track_ref(track);
3555 dsched_buf_enter(bio->bio_buf); /* might stack */
3559 * Initiate I/O on a vnode.
3561 * SWAPCACHE OPERATION:
3563 * Real buffer cache buffers have a non-NULL bp->b_vp. Unfortunately
3564 * devfs also uses b_vp for fake buffers so we also have to check
3565 * that B_PAGING is 0. In this case the passed 'vp' is probably the
3566 * underlying block device. The swap assignments are related to the
3567 * buffer cache buffer's b_vp, not the passed vp.
3569 * The passed vp == bp->b_vp only in the case where the strategy call
3570 * is made on the vp itself for its own buffers (a regular file or
3571 * block device vp). The filesystem usually then re-calls vn_strategy()
3572 * after translating the request to an underlying device.
3574 * Cluster buffers set B_CLUSTER and the passed vp is the vp of the
3575 * underlying buffer cache buffers.
3577 * We can only deal with page-aligned buffers at the moment, because
3578 * we can't tell what the real dirty state for pages straddling a buffer
3579 * are.
3581 * In order to call swap_pager_strategy() we must provide the VM object
3582 * and base offset for the underlying buffer cache pages so it can find
3583 * the swap blocks.
3585 void
3586 vn_strategy(struct vnode *vp, struct bio *bio)
3588 struct bio_track *track;
3589 struct buf *bp = bio->bio_buf;
3591 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3594 * Set when an I/O is issued on the bp. Cleared by consumers
3595 * (aka HAMMER), allowing the consumer to determine if I/O had
3596 * actually occurred.
3598 bp->b_flags |= B_IOISSUED;
3601 * Handle the swap cache intercept.
3603 if (vn_cache_strategy(vp, bio))
3604 return;
3607 * Otherwise do the operation through the filesystem
3609 if (bp->b_cmd == BUF_CMD_READ)
3610 track = &vp->v_track_read;
3611 else
3612 track = &vp->v_track_write;
3613 KKASSERT((bio->bio_flags & BIO_DONE) == 0);
3614 bio->bio_track = track;
3615 bio_track_ref(track);
3616 dsched_buf_enter(bp); /* might stack */
3617 vop_strategy(*vp->v_ops, vp, bio);
3620 static void vn_cache_strategy_callback(struct bio *bio);
3623 vn_cache_strategy(struct vnode *vp, struct bio *bio)
3625 struct buf *bp = bio->bio_buf;
3626 struct bio *nbio;
3627 vm_object_t object;
3628 vm_page_t m;
3629 int i;
3632 * Stop using swapcache if paniced, dumping, or dumped
3634 if (panicstr || dumping)
3635 return(0);
3638 * Is this buffer cache buffer suitable for reading from
3639 * the swap cache?
3641 if (vm_swapcache_read_enable == 0 ||
3642 bp->b_cmd != BUF_CMD_READ ||
3643 ((bp->b_flags & B_CLUSTER) == 0 &&
3644 (bp->b_vp == NULL || (bp->b_flags & B_PAGING))) ||
3645 ((int)bp->b_loffset & PAGE_MASK) != 0 ||
3646 (bp->b_bcount & PAGE_MASK) != 0) {
3647 return(0);
3651 * Figure out the original VM object (it will match the underlying
3652 * VM pages). Note that swap cached data uses page indices relative
3653 * to that object, not relative to bio->bio_offset.
3655 if (bp->b_flags & B_CLUSTER)
3656 object = vp->v_object;
3657 else
3658 object = bp->b_vp->v_object;
3661 * In order to be able to use the swap cache all underlying VM
3662 * pages must be marked as such, and we can't have any bogus pages.
3664 for (i = 0; i < bp->b_xio.xio_npages; ++i) {
3665 m = bp->b_xio.xio_pages[i];
3666 if ((m->flags & PG_SWAPPED) == 0)
3667 break;
3668 if (m == bogus_page)
3669 break;
3673 * If we are good then issue the I/O using swap_pager_strategy().
3675 * We can only do this if the buffer actually supports object-backed
3676 * I/O. If it doesn't npages will be 0.
3678 if (i && i == bp->b_xio.xio_npages) {
3679 m = bp->b_xio.xio_pages[0];
3680 nbio = push_bio(bio);
3681 nbio->bio_done = vn_cache_strategy_callback;
3682 nbio->bio_offset = ptoa(m->pindex);
3683 KKASSERT(m->object == object);
3684 swap_pager_strategy(object, nbio);
3685 return(1);
3687 return(0);
3691 * This is a bit of a hack but since the vn_cache_strategy() function can
3692 * override a VFS's strategy function we must make sure that the bio, which
3693 * is probably bio2, doesn't leak an unexpected offset value back to the
3694 * filesystem. The filesystem (e.g. UFS) might otherwise assume that the
3695 * bio went through its own file strategy function and the the bio2 offset
3696 * is a cached disk offset when, in fact, it isn't.
3698 static void
3699 vn_cache_strategy_callback(struct bio *bio)
3701 bio->bio_offset = NOOFFSET;
3702 biodone(pop_bio(bio));
3706 * bpdone:
3708 * Finish I/O on a buffer after all BIOs have been processed.
3709 * Called when the bio chain is exhausted or by biowait. If called
3710 * by biowait, elseit is typically 0.
3712 * bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3713 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3714 * assuming B_INVAL is clear.
3716 * For the VMIO case, we set B_CACHE if the op was a read and no
3717 * read error occured, or if the op was a write. B_CACHE is never
3718 * set if the buffer is invalid or otherwise uncacheable.
3720 * bpdone does not mess with B_INVAL, allowing the I/O routine or the
3721 * initiator to leave B_INVAL set to brelse the buffer out of existance
3722 * in the biodone routine.
3724 * bpdone is responsible for calling bundirty() on the buffer after a
3725 * successful write. We previously did this prior to initiating the
3726 * write under the assumption that the buffer might be dirtied again
3727 * while the write was in progress, however doing it before-hand creates
3728 * a race condition prior to the call to vn_strategy() where the
3729 * filesystem may not be aware that a dirty buffer is present.
3730 * It should not be possible for the buffer or its underlying pages to
3731 * be redirtied prior to bpdone()'s unbusying of the underlying VM
3732 * pages.
3734 void
3735 bpdone(struct buf *bp, int elseit)
3737 buf_cmd_t cmd;
3739 KASSERT(BUF_REFCNTNB(bp) > 0,
3740 ("bpdone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3741 KASSERT(bp->b_cmd != BUF_CMD_DONE,
3742 ("bpdone: bp %p already done!", bp));
3745 * No more BIOs are left. All completion functions have been dealt
3746 * with, now we clean up the buffer.
3748 cmd = bp->b_cmd;
3749 bp->b_cmd = BUF_CMD_DONE;
3752 * Only reads and writes are processed past this point.
3754 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3755 if (cmd == BUF_CMD_FREEBLKS)
3756 bp->b_flags |= B_NOCACHE;
3757 if (elseit)
3758 brelse(bp);
3759 return;
3763 * A failed write must re-dirty the buffer unless B_INVAL
3764 * was set.
3766 * A successful write must clear the dirty flag. This is done after
3767 * the write to ensure that the buffer remains on the vnode's dirty
3768 * list for filesystem interlocks / checks until the write is actually
3769 * complete. HAMMER2 is sensitive to this issue.
3771 * Only applicable to normal buffers (with VPs). vinum buffers may
3772 * not have a vp.
3774 * Must be done prior to calling buf_complete() as the callback might
3775 * re-dirty the buffer.
3777 if (cmd == BUF_CMD_WRITE) {
3778 if ((bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
3779 bp->b_flags &= ~B_NOCACHE;
3780 if (bp->b_vp)
3781 bdirty(bp);
3782 } else {
3783 if (bp->b_vp)
3784 bundirty(bp);
3789 * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3790 * a lot worse. XXX - move this above the clearing of b_cmd
3792 if (LIST_FIRST(&bp->b_dep) != NULL)
3793 buf_complete(bp);
3795 if (bp->b_flags & B_VMIO) {
3796 int i;
3797 vm_ooffset_t foff;
3798 vm_page_t m;
3799 vm_object_t obj;
3800 int iosize;
3801 struct vnode *vp = bp->b_vp;
3803 obj = vp->v_object;
3805 #if defined(VFS_BIO_DEBUG)
3806 if (vp->v_auxrefs == 0)
3807 panic("bpdone: zero vnode hold count");
3808 if ((vp->v_flag & VOBJBUF) == 0)
3809 panic("bpdone: vnode is not setup for merged cache");
3810 #endif
3812 foff = bp->b_loffset;
3813 KASSERT(foff != NOOFFSET, ("bpdone: no buffer offset"));
3814 KASSERT(obj != NULL, ("bpdone: missing VM object"));
3816 #if defined(VFS_BIO_DEBUG)
3817 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3818 kprintf("bpdone: paging in progress(%d) < "
3819 "bp->b_xio.xio_npages(%d)\n",
3820 obj->paging_in_progress,
3821 bp->b_xio.xio_npages);
3823 #endif
3826 * Set B_CACHE if the op was a normal read and no error
3827 * occured. B_CACHE is set for writes in the b*write()
3828 * routines.
3830 iosize = bp->b_bcount - bp->b_resid;
3831 if (cmd == BUF_CMD_READ &&
3832 (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3833 bp->b_flags |= B_CACHE;
3836 vm_object_hold(obj);
3837 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3838 int bogusflag = 0;
3839 int resid;
3841 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3842 if (resid > iosize)
3843 resid = iosize;
3846 * cleanup bogus pages, restoring the originals. Since
3847 * the originals should still be wired, we don't have
3848 * to worry about interrupt/freeing races destroying
3849 * the VM object association.
3851 m = bp->b_xio.xio_pages[i];
3852 if (m == bogus_page) {
3853 bogusflag = 1;
3854 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3855 if (m == NULL)
3856 panic("bpdone: page disappeared");
3857 bp->b_xio.xio_pages[i] = m;
3858 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3859 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3861 #if defined(VFS_BIO_DEBUG)
3862 if (OFF_TO_IDX(foff) != m->pindex) {
3863 kprintf("bpdone: foff(%lu)/m->pindex(%ld) "
3864 "mismatch\n",
3865 (unsigned long)foff, (long)m->pindex);
3867 #endif
3870 * In the write case, the valid and clean bits are
3871 * already changed correctly (see bdwrite()), so we
3872 * only need to do this here in the read case.
3874 vm_page_busy_wait(m, FALSE, "bpdpgw");
3875 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3876 vfs_clean_one_page(bp, i, m);
3878 vm_page_flag_clear(m, PG_ZERO);
3881 * when debugging new filesystems or buffer I/O
3882 * methods, this is the most common error that pops
3883 * up. if you see this, you have not set the page
3884 * busy flag correctly!!!
3886 if (m->busy == 0) {
3887 kprintf("bpdone: page busy < 0, "
3888 "pindex: %d, foff: 0x(%x,%x), "
3889 "resid: %d, index: %d\n",
3890 (int) m->pindex, (int)(foff >> 32),
3891 (int) foff & 0xffffffff, resid, i);
3892 if (!vn_isdisk(vp, NULL))
3893 kprintf(" iosize: %ld, loffset: %lld, "
3894 "flags: 0x%08x, npages: %d\n",
3895 bp->b_vp->v_mount->mnt_stat.f_iosize,
3896 (long long)bp->b_loffset,
3897 bp->b_flags, bp->b_xio.xio_npages);
3898 else
3899 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3900 (long long)bp->b_loffset,
3901 bp->b_flags, bp->b_xio.xio_npages);
3902 kprintf(" valid: 0x%x, dirty: 0x%x, "
3903 "wired: %d\n",
3904 m->valid, m->dirty,
3905 m->wire_count);
3906 panic("bpdone: page busy < 0");
3908 vm_page_io_finish(m);
3909 vm_page_wakeup(m);
3910 vm_object_pip_wakeup(obj);
3911 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3912 iosize -= resid;
3914 bp->b_flags &= ~B_HASBOGUS;
3915 vm_object_drop(obj);
3919 * Finish up by releasing the buffer. There are no more synchronous
3920 * or asynchronous completions, those were handled by bio_done
3921 * callbacks.
3923 if (elseit) {
3924 if (bp->b_flags & (B_NOCACHE|B_INVAL|B_ERROR|B_RELBUF))
3925 brelse(bp);
3926 else
3927 bqrelse(bp);
3932 * Normal biodone.
3934 void
3935 biodone(struct bio *bio)
3937 struct buf *bp = bio->bio_buf;
3939 runningbufwakeup(bp);
3942 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
3944 while (bio) {
3945 biodone_t *done_func;
3946 struct bio_track *track;
3949 * BIO tracking. Most but not all BIOs are tracked.
3951 if ((track = bio->bio_track) != NULL) {
3952 bio_track_rel(track);
3953 bio->bio_track = NULL;
3957 * A bio_done function terminates the loop. The function
3958 * will be responsible for any further chaining and/or
3959 * buffer management.
3961 * WARNING! The done function can deallocate the buffer!
3963 if ((done_func = bio->bio_done) != NULL) {
3964 bio->bio_done = NULL;
3965 done_func(bio);
3966 return;
3968 bio = bio->bio_prev;
3972 * If we've run out of bio's do normal [a]synchronous completion.
3974 bpdone(bp, 1);
3978 * Synchronous biodone - this terminates a synchronous BIO.
3980 * bpdone() is called with elseit=FALSE, leaving the buffer completed
3981 * but still locked. The caller must brelse() the buffer after waiting
3982 * for completion.
3984 void
3985 biodone_sync(struct bio *bio)
3987 struct buf *bp = bio->bio_buf;
3988 int flags;
3989 int nflags;
3991 KKASSERT(bio == &bp->b_bio1);
3992 bpdone(bp, 0);
3994 for (;;) {
3995 flags = bio->bio_flags;
3996 nflags = (flags | BIO_DONE) & ~BIO_WANT;
3998 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3999 if (flags & BIO_WANT)
4000 wakeup(bio);
4001 break;
4007 * vfs_unbusy_pages:
4009 * This routine is called in lieu of iodone in the case of
4010 * incomplete I/O. This keeps the busy status for pages
4011 * consistant.
4013 void
4014 vfs_unbusy_pages(struct buf *bp)
4016 int i;
4018 runningbufwakeup(bp);
4020 if (bp->b_flags & B_VMIO) {
4021 struct vnode *vp = bp->b_vp;
4022 vm_object_t obj;
4024 obj = vp->v_object;
4025 vm_object_hold(obj);
4027 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4028 vm_page_t m = bp->b_xio.xio_pages[i];
4031 * When restoring bogus changes the original pages
4032 * should still be wired, so we are in no danger of
4033 * losing the object association and do not need
4034 * critical section protection particularly.
4036 if (m == bogus_page) {
4037 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
4038 if (!m) {
4039 panic("vfs_unbusy_pages: page missing");
4041 bp->b_xio.xio_pages[i] = m;
4042 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4043 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
4045 vm_page_busy_wait(m, FALSE, "bpdpgw");
4046 vm_page_flag_clear(m, PG_ZERO);
4047 vm_page_io_finish(m);
4048 vm_page_wakeup(m);
4049 vm_object_pip_wakeup(obj);
4051 bp->b_flags &= ~B_HASBOGUS;
4052 vm_object_drop(obj);
4057 * vfs_busy_pages:
4059 * This routine is called before a device strategy routine.
4060 * It is used to tell the VM system that paging I/O is in
4061 * progress, and treat the pages associated with the buffer
4062 * almost as being PG_BUSY. Also the object 'paging_in_progress'
4063 * flag is handled to make sure that the object doesn't become
4064 * inconsistant.
4066 * Since I/O has not been initiated yet, certain buffer flags
4067 * such as B_ERROR or B_INVAL may be in an inconsistant state
4068 * and should be ignored.
4070 void
4071 vfs_busy_pages(struct vnode *vp, struct buf *bp)
4073 int i, bogus;
4074 struct lwp *lp = curthread->td_lwp;
4077 * The buffer's I/O command must already be set. If reading,
4078 * B_CACHE must be 0 (double check against callers only doing
4079 * I/O when B_CACHE is 0).
4081 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4082 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
4084 if (bp->b_flags & B_VMIO) {
4085 vm_object_t obj;
4087 obj = vp->v_object;
4088 KASSERT(bp->b_loffset != NOOFFSET,
4089 ("vfs_busy_pages: no buffer offset"));
4092 * Busy all the pages. We have to busy them all at once
4093 * to avoid deadlocks.
4095 retry:
4096 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4097 vm_page_t m = bp->b_xio.xio_pages[i];
4099 if (vm_page_busy_try(m, FALSE)) {
4100 vm_page_sleep_busy(m, FALSE, "vbpage");
4101 while (--i >= 0)
4102 vm_page_wakeup(bp->b_xio.xio_pages[i]);
4103 goto retry;
4108 * Setup for I/O, soft-busy the page right now because
4109 * the next loop may block.
4111 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4112 vm_page_t m = bp->b_xio.xio_pages[i];
4114 vm_page_flag_clear(m, PG_ZERO);
4115 if ((bp->b_flags & B_CLUSTER) == 0) {
4116 vm_object_pip_add(obj, 1);
4117 vm_page_io_start(m);
4122 * Adjust protections for I/O and do bogus-page mapping.
4123 * Assume that vm_page_protect() can block (it can block
4124 * if VM_PROT_NONE, don't take any chances regardless).
4126 * In particular note that for writes we must incorporate
4127 * page dirtyness from the VM system into the buffer's
4128 * dirty range.
4130 * For reads we theoretically must incorporate page dirtyness
4131 * from the VM system to determine if the page needs bogus
4132 * replacement, but we shortcut the test by simply checking
4133 * that all m->valid bits are set, indicating that the page
4134 * is fully valid and does not need to be re-read. For any
4135 * VM system dirtyness the page will also be fully valid
4136 * since it was mapped at one point.
4138 bogus = 0;
4139 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4140 vm_page_t m = bp->b_xio.xio_pages[i];
4142 vm_page_flag_clear(m, PG_ZERO); /* XXX */
4143 if (bp->b_cmd == BUF_CMD_WRITE) {
4145 * When readying a vnode-backed buffer for
4146 * a write we must zero-fill any invalid
4147 * portions of the backing VM pages, mark
4148 * it valid and clear related dirty bits.
4150 * vfs_clean_one_page() incorporates any
4151 * VM dirtyness and updates the b_dirtyoff
4152 * range (after we've made the page RO).
4154 * It is also expected that the pmap modified
4155 * bit has already been cleared by the
4156 * vm_page_protect(). We may not be able
4157 * to clear all dirty bits for a page if it
4158 * was also memory mapped (NFS).
4160 * Finally be sure to unassign any swap-cache
4161 * backing store as it is now stale.
4163 vm_page_protect(m, VM_PROT_READ);
4164 vfs_clean_one_page(bp, i, m);
4165 swap_pager_unswapped(m);
4166 } else if (m->valid == VM_PAGE_BITS_ALL) {
4168 * When readying a vnode-backed buffer for
4169 * read we must replace any dirty pages with
4170 * a bogus page so dirty data is not destroyed
4171 * when filling gaps.
4173 * To avoid testing whether the page is
4174 * dirty we instead test that the page was
4175 * at some point mapped (m->valid fully
4176 * valid) with the understanding that
4177 * this also covers the dirty case.
4179 bp->b_xio.xio_pages[i] = bogus_page;
4180 bp->b_flags |= B_HASBOGUS;
4181 bogus++;
4182 } else if (m->valid & m->dirty) {
4184 * This case should not occur as partial
4185 * dirtyment can only happen if the buffer
4186 * is B_CACHE, and this code is not entered
4187 * if the buffer is B_CACHE.
4189 kprintf("Warning: vfs_busy_pages - page not "
4190 "fully valid! loff=%jx bpf=%08x "
4191 "idx=%d val=%02x dir=%02x\n",
4192 (uintmax_t)bp->b_loffset, bp->b_flags,
4193 i, m->valid, m->dirty);
4194 vm_page_protect(m, VM_PROT_NONE);
4195 } else {
4197 * The page is not valid and can be made
4198 * part of the read.
4200 vm_page_protect(m, VM_PROT_NONE);
4202 vm_page_wakeup(m);
4204 if (bogus) {
4205 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4206 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
4211 * This is the easiest place to put the process accounting for the I/O
4212 * for now.
4214 if (lp != NULL) {
4215 if (bp->b_cmd == BUF_CMD_READ)
4216 lp->lwp_ru.ru_inblock++;
4217 else
4218 lp->lwp_ru.ru_oublock++;
4223 * Tell the VM system that the pages associated with this buffer
4224 * are clean. This is used for delayed writes where the data is
4225 * going to go to disk eventually without additional VM intevention.
4227 * NOTE: While we only really need to clean through to b_bcount, we
4228 * just go ahead and clean through to b_bufsize.
4230 static void
4231 vfs_clean_pages(struct buf *bp)
4233 vm_page_t m;
4234 int i;
4236 if ((bp->b_flags & B_VMIO) == 0)
4237 return;
4239 KASSERT(bp->b_loffset != NOOFFSET,
4240 ("vfs_clean_pages: no buffer offset"));
4242 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4243 m = bp->b_xio.xio_pages[i];
4244 vfs_clean_one_page(bp, i, m);
4249 * vfs_clean_one_page:
4251 * Set the valid bits and clear the dirty bits in a page within a
4252 * buffer. The range is restricted to the buffer's size and the
4253 * buffer's logical offset might index into the first page.
4255 * The caller has busied or soft-busied the page and it is not mapped,
4256 * test and incorporate the dirty bits into b_dirtyoff/end before
4257 * clearing them. Note that we need to clear the pmap modified bits
4258 * after determining the the page was dirty, vm_page_set_validclean()
4259 * does not do it for us.
4261 * This routine is typically called after a read completes (dirty should
4262 * be zero in that case as we are not called on bogus-replace pages),
4263 * or before a write is initiated.
4265 static void
4266 vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m)
4268 int bcount;
4269 int xoff;
4270 int soff;
4271 int eoff;
4274 * Calculate offset range within the page but relative to buffer's
4275 * loffset. loffset might be offset into the first page.
4277 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
4278 bcount = bp->b_bcount + xoff; /* offset adjusted */
4280 if (pageno == 0) {
4281 soff = xoff;
4282 eoff = PAGE_SIZE;
4283 } else {
4284 soff = (pageno << PAGE_SHIFT);
4285 eoff = soff + PAGE_SIZE;
4287 if (eoff > bcount)
4288 eoff = bcount;
4289 if (soff >= eoff)
4290 return;
4293 * Test dirty bits and adjust b_dirtyoff/end.
4295 * If dirty pages are incorporated into the bp any prior
4296 * B_NEEDCOMMIT state (NFS) must be cleared because the
4297 * caller has not taken into account the new dirty data.
4299 * If the page was memory mapped the dirty bits might go beyond the
4300 * end of the buffer, but we can't really make the assumption that
4301 * a file EOF straddles the buffer (even though this is the case for
4302 * NFS if B_NEEDCOMMIT is also set). So for the purposes of clearing
4303 * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
4304 * This also saves some console spam.
4306 * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK,
4307 * NFS can handle huge commits but not huge writes.
4309 vm_page_test_dirty(m);
4310 if (m->dirty) {
4311 if ((bp->b_flags & B_NEEDCOMMIT) &&
4312 (m->dirty & vm_page_bits(soff & PAGE_MASK, eoff - soff))) {
4313 if (debug_commit)
4314 kprintf("Warning: vfs_clean_one_page: bp %p "
4315 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT"
4316 " cmd %d vd %02x/%02x x/s/e %d %d %d "
4317 "doff/end %d %d\n",
4318 bp, (uintmax_t)bp->b_loffset, bp->b_bcount,
4319 bp->b_flags, bp->b_cmd,
4320 m->valid, m->dirty, xoff, soff, eoff,
4321 bp->b_dirtyoff, bp->b_dirtyend);
4322 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
4323 if (debug_commit)
4324 print_backtrace(-1);
4327 * Only clear the pmap modified bits if ALL the dirty bits
4328 * are set, otherwise the system might mis-clear portions
4329 * of a page.
4331 if (m->dirty == VM_PAGE_BITS_ALL &&
4332 (bp->b_flags & B_NEEDCOMMIT) == 0) {
4333 pmap_clear_modify(m);
4335 if (bp->b_dirtyoff > soff - xoff)
4336 bp->b_dirtyoff = soff - xoff;
4337 if (bp->b_dirtyend < eoff - xoff)
4338 bp->b_dirtyend = eoff - xoff;
4342 * Set related valid bits, clear related dirty bits.
4343 * Does not mess with the pmap modified bit.
4345 * WARNING! We cannot just clear all of m->dirty here as the
4346 * buffer cache buffers may use a DEV_BSIZE'd aligned
4347 * block size, or have an odd size (e.g. NFS at file EOF).
4348 * The putpages code can clear m->dirty to 0.
4350 * If a VOP_WRITE generates a buffer cache buffer which
4351 * covers the same space as mapped writable pages the
4352 * buffer flush might not be able to clear all the dirty
4353 * bits and still require a putpages from the VM system
4354 * to finish it off.
4356 * WARNING! vm_page_set_validclean() currently assumes vm_token
4357 * is held. The page might not be busied (bdwrite() case).
4358 * XXX remove this comment once we've validated that this
4359 * is no longer an issue.
4361 vm_page_set_validclean(m, soff & PAGE_MASK, eoff - soff);
4364 #if 0
4366 * Similar to vfs_clean_one_page() but sets the bits to valid and dirty.
4367 * The page data is assumed to be valid (there is no zeroing here).
4369 static void
4370 vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m)
4372 int bcount;
4373 int xoff;
4374 int soff;
4375 int eoff;
4378 * Calculate offset range within the page but relative to buffer's
4379 * loffset. loffset might be offset into the first page.
4381 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
4382 bcount = bp->b_bcount + xoff; /* offset adjusted */
4384 if (pageno == 0) {
4385 soff = xoff;
4386 eoff = PAGE_SIZE;
4387 } else {
4388 soff = (pageno << PAGE_SHIFT);
4389 eoff = soff + PAGE_SIZE;
4391 if (eoff > bcount)
4392 eoff = bcount;
4393 if (soff >= eoff)
4394 return;
4395 vm_page_set_validdirty(m, soff & PAGE_MASK, eoff - soff);
4397 #endif
4400 * vfs_bio_clrbuf:
4402 * Clear a buffer. This routine essentially fakes an I/O, so we need
4403 * to clear B_ERROR and B_INVAL.
4405 * Note that while we only theoretically need to clear through b_bcount,
4406 * we go ahead and clear through b_bufsize.
4409 void
4410 vfs_bio_clrbuf(struct buf *bp)
4412 int i, mask = 0;
4413 caddr_t sa, ea;
4414 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
4415 bp->b_flags &= ~(B_INVAL | B_EINTR | B_ERROR);
4416 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4417 (bp->b_loffset & PAGE_MASK) == 0) {
4418 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4419 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
4420 bp->b_resid = 0;
4421 return;
4423 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
4424 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
4425 bzero(bp->b_data, bp->b_bufsize);
4426 bp->b_xio.xio_pages[0]->valid |= mask;
4427 bp->b_resid = 0;
4428 return;
4431 sa = bp->b_data;
4432 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
4433 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
4434 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
4435 ea = (caddr_t)(vm_offset_t)ulmin(
4436 (u_long)(vm_offset_t)ea,
4437 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
4438 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4439 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
4440 continue;
4441 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
4442 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
4443 bzero(sa, ea - sa);
4445 } else {
4446 for (; sa < ea; sa += DEV_BSIZE, j++) {
4447 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
4448 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
4449 bzero(sa, DEV_BSIZE);
4452 bp->b_xio.xio_pages[i]->valid |= mask;
4453 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
4455 bp->b_resid = 0;
4456 } else {
4457 clrbuf(bp);
4462 * vm_hold_load_pages:
4464 * Load pages into the buffer's address space. The pages are
4465 * allocated from the kernel object in order to reduce interference
4466 * with the any VM paging I/O activity. The range of loaded
4467 * pages will be wired.
4469 * If a page cannot be allocated, the 'pagedaemon' is woken up to
4470 * retrieve the full range (to - from) of pages.
4472 void
4473 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4475 vm_offset_t pg;
4476 vm_page_t p;
4477 int index;
4479 to = round_page(to);
4480 from = round_page(from);
4481 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4483 pg = from;
4484 while (pg < to) {
4486 * Note: must allocate system pages since blocking here
4487 * could intefere with paging I/O, no matter which
4488 * process we are.
4490 vm_object_hold(&kernel_object);
4491 p = bio_page_alloc(bp, &kernel_object, pg >> PAGE_SHIFT,
4492 (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
4493 vm_object_drop(&kernel_object);
4494 if (p) {
4495 vm_page_wire(p);
4496 p->valid = VM_PAGE_BITS_ALL;
4497 vm_page_flag_clear(p, PG_ZERO);
4498 pmap_kenter_noinval(pg, VM_PAGE_TO_PHYS(p));
4499 bp->b_xio.xio_pages[index] = p;
4500 vm_page_wakeup(p);
4502 pg += PAGE_SIZE;
4503 ++index;
4506 pmap_invalidate_range(&kernel_pmap, from, to);
4507 bp->b_xio.xio_npages = index;
4511 * Allocate a page for a buffer cache buffer.
4513 * If NULL is returned the caller is expected to retry (typically check if
4514 * the page already exists on retry before trying to allocate one).
4516 * NOTE! Low-memory handling is dealt with in b[q]relse(), not here. This
4517 * function will use the system reserve with the hope that the page
4518 * allocations can be returned to PQ_CACHE/PQ_FREE when the caller
4519 * is done with the buffer.
4521 * NOTE! However, TMPFS is a special case because flushing a dirty buffer
4522 * to TMPFS doesn't clean the page. For TMPFS, only the pagedaemon
4523 * is capable of retiring pages (to swap). For TMPFS we don't dig
4524 * into the system reserve because doing so could stall out pretty
4525 * much every process running on the system.
4527 static
4528 vm_page_t
4529 bio_page_alloc(struct buf *bp, vm_object_t obj, vm_pindex_t pg, int deficit)
4531 int vmflags = VM_ALLOC_NORMAL | VM_ALLOC_NULL_OK;
4532 vm_page_t p;
4534 ASSERT_LWKT_TOKEN_HELD(vm_object_token(obj));
4537 * Try a normal allocation first.
4539 p = vm_page_alloc(obj, pg, vmflags);
4540 if (p)
4541 return(p);
4542 if (vm_page_lookup(obj, pg))
4543 return(NULL);
4544 vm_pageout_deficit += deficit;
4547 * Try again, digging into the system reserve.
4549 * Trying to recover pages from the buffer cache here can deadlock
4550 * against other threads trying to busy underlying pages so we
4551 * depend on the code in brelse() and bqrelse() to free/cache the
4552 * underlying buffer cache pages when memory is low.
4554 if (curthread->td_flags & TDF_SYSTHREAD)
4555 vmflags |= VM_ALLOC_SYSTEM | VM_ALLOC_INTERRUPT;
4556 else if (bp->b_vp && bp->b_vp->v_tag == VT_TMPFS)
4557 vmflags |= 0;
4558 else
4559 vmflags |= VM_ALLOC_SYSTEM;
4561 /*recoverbufpages();*/
4562 p = vm_page_alloc(obj, pg, vmflags);
4563 if (p)
4564 return(p);
4565 if (vm_page_lookup(obj, pg))
4566 return(NULL);
4569 * Wait for memory to free up and try again
4571 if (vm_page_count_severe())
4572 ++lowmempgallocs;
4573 vm_wait(hz / 20 + 1);
4575 p = vm_page_alloc(obj, pg, vmflags);
4576 if (p)
4577 return(p);
4578 if (vm_page_lookup(obj, pg))
4579 return(NULL);
4582 * Ok, now we are really in trouble.
4585 static struct krate biokrate = { .freq = 1 };
4586 krateprintf(&biokrate,
4587 "Warning: bio_page_alloc: memory exhausted "
4588 "during buffer cache page allocation from %s\n",
4589 curthread->td_comm);
4591 if (curthread->td_flags & TDF_SYSTHREAD)
4592 vm_wait(hz / 20 + 1);
4593 else
4594 vm_wait(hz / 2 + 1);
4595 return (NULL);
4599 * vm_hold_free_pages:
4601 * Return pages associated with the buffer back to the VM system.
4603 * The range of pages underlying the buffer's address space will
4604 * be unmapped and un-wired.
4606 void
4607 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4609 vm_offset_t pg;
4610 vm_page_t p;
4611 int index, newnpages;
4613 from = round_page(from);
4614 to = round_page(to);
4615 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4616 newnpages = index;
4618 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4619 p = bp->b_xio.xio_pages[index];
4620 if (p && (index < bp->b_xio.xio_npages)) {
4621 if (p->busy) {
4622 kprintf("vm_hold_free_pages: doffset: %lld, "
4623 "loffset: %lld\n",
4624 (long long)bp->b_bio2.bio_offset,
4625 (long long)bp->b_loffset);
4627 bp->b_xio.xio_pages[index] = NULL;
4628 pmap_kremove_noinval(pg);
4629 vm_page_busy_wait(p, FALSE, "vmhldpg");
4630 vm_page_unwire(p, 0);
4631 vm_page_free(p);
4634 pmap_invalidate_range(&kernel_pmap, from, to);
4635 bp->b_xio.xio_npages = newnpages;
4639 * vmapbuf:
4641 * Map a user buffer into KVM via a pbuf. On return the buffer's
4642 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
4643 * initialized.
4646 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
4648 caddr_t addr;
4649 vm_offset_t va;
4650 vm_page_t m;
4651 int vmprot;
4652 int error;
4653 int pidx;
4654 int i;
4657 * bp had better have a command and it better be a pbuf.
4659 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4660 KKASSERT(bp->b_flags & B_PAGING);
4661 KKASSERT(bp->b_kvabase);
4663 if (bytes < 0)
4664 return (-1);
4667 * Map the user data into KVM. Mappings have to be page-aligned.
4669 addr = (caddr_t)trunc_page((vm_offset_t)udata);
4670 pidx = 0;
4672 vmprot = VM_PROT_READ;
4673 if (bp->b_cmd == BUF_CMD_READ)
4674 vmprot |= VM_PROT_WRITE;
4676 while (addr < udata + bytes) {
4678 * Do the vm_fault if needed; do the copy-on-write thing
4679 * when reading stuff off device into memory.
4681 * vm_fault_page*() returns a held VM page.
4683 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
4684 va = trunc_page(va);
4686 m = vm_fault_page_quick(va, vmprot, &error);
4687 if (m == NULL) {
4688 for (i = 0; i < pidx; ++i) {
4689 vm_page_unhold(bp->b_xio.xio_pages[i]);
4690 bp->b_xio.xio_pages[i] = NULL;
4692 return(-1);
4694 bp->b_xio.xio_pages[pidx] = m;
4695 addr += PAGE_SIZE;
4696 ++pidx;
4700 * Map the page array and set the buffer fields to point to
4701 * the mapped data buffer.
4703 if (pidx > btoc(MAXPHYS))
4704 panic("vmapbuf: mapped more than MAXPHYS");
4705 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
4707 bp->b_xio.xio_npages = pidx;
4708 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
4709 bp->b_bcount = bytes;
4710 bp->b_bufsize = bytes;
4711 return(0);
4715 * vunmapbuf:
4717 * Free the io map PTEs associated with this IO operation.
4718 * We also invalidate the TLB entries and restore the original b_addr.
4720 void
4721 vunmapbuf(struct buf *bp)
4723 int pidx;
4724 int npages;
4726 KKASSERT(bp->b_flags & B_PAGING);
4728 npages = bp->b_xio.xio_npages;
4729 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4730 for (pidx = 0; pidx < npages; ++pidx) {
4731 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
4732 bp->b_xio.xio_pages[pidx] = NULL;
4734 bp->b_xio.xio_npages = 0;
4735 bp->b_data = bp->b_kvabase;
4739 * Scan all buffers in the system and issue the callback.
4742 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
4744 int count = 0;
4745 int error;
4746 long n;
4748 for (n = 0; n < nbuf; ++n) {
4749 if ((error = callback(&buf[n], info)) < 0) {
4750 count = error;
4751 break;
4753 count += error;
4755 return (count);
4759 * nestiobuf_iodone: biodone callback for nested buffers and propagate
4760 * completion to the master buffer.
4762 static void
4763 nestiobuf_iodone(struct bio *bio)
4765 struct bio *mbio;
4766 struct buf *mbp, *bp;
4767 struct devstat *stats;
4768 int error;
4769 int donebytes;
4771 bp = bio->bio_buf;
4772 mbio = bio->bio_caller_info1.ptr;
4773 stats = bio->bio_caller_info2.ptr;
4774 mbp = mbio->bio_buf;
4776 KKASSERT(bp->b_bcount <= bp->b_bufsize);
4777 KKASSERT(mbp != bp);
4779 error = bp->b_error;
4780 if (bp->b_error == 0 &&
4781 (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) {
4783 * Not all got transfered, raise an error. We have no way to
4784 * propagate these conditions to mbp.
4786 error = EIO;
4789 donebytes = bp->b_bufsize;
4791 relpbuf(bp, NULL);
4793 nestiobuf_done(mbio, donebytes, error, stats);
4796 void
4797 nestiobuf_done(struct bio *mbio, int donebytes, int error, struct devstat *stats)
4799 struct buf *mbp;
4801 mbp = mbio->bio_buf;
4803 KKASSERT((int)(intptr_t)mbio->bio_driver_info > 0);
4806 * If an error occured, propagate it to the master buffer.
4808 * Several biodone()s may wind up running concurrently so
4809 * use an atomic op to adjust b_flags.
4811 if (error) {
4812 mbp->b_error = error;
4813 atomic_set_int(&mbp->b_flags, B_ERROR);
4817 * Decrement the operations in progress counter and terminate the
4818 * I/O if this was the last bit.
4820 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4821 mbp->b_resid = 0;
4822 if (stats)
4823 devstat_end_transaction_buf(stats, mbp);
4824 biodone(mbio);
4829 * Initialize a nestiobuf for use. Set an initial count of 1 to prevent
4830 * the mbio from being biodone()'d while we are still adding sub-bios to
4831 * it.
4833 void
4834 nestiobuf_init(struct bio *bio)
4836 bio->bio_driver_info = (void *)1;
4840 * The BIOs added to the nestedio have already been started, remove the
4841 * count that placeheld our mbio and biodone() it if the count would
4842 * transition to 0.
4844 void
4845 nestiobuf_start(struct bio *mbio)
4847 struct buf *mbp = mbio->bio_buf;
4850 * Decrement the operations in progress counter and terminate the
4851 * I/O if this was the last bit.
4853 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4854 if (mbp->b_flags & B_ERROR)
4855 mbp->b_resid = mbp->b_bcount;
4856 else
4857 mbp->b_resid = 0;
4858 biodone(mbio);
4863 * Set an intermediate error prior to calling nestiobuf_start()
4865 void
4866 nestiobuf_error(struct bio *mbio, int error)
4868 struct buf *mbp = mbio->bio_buf;
4870 if (error) {
4871 mbp->b_error = error;
4872 atomic_set_int(&mbp->b_flags, B_ERROR);
4877 * nestiobuf_add: setup a "nested" buffer.
4879 * => 'mbp' is a "master" buffer which is being divided into sub pieces.
4880 * => 'bp' should be a buffer allocated by getiobuf.
4881 * => 'offset' is a byte offset in the master buffer.
4882 * => 'size' is a size in bytes of this nested buffer.
4884 void
4885 nestiobuf_add(struct bio *mbio, struct buf *bp, int offset, size_t size, struct devstat *stats)
4887 struct buf *mbp = mbio->bio_buf;
4888 struct vnode *vp = mbp->b_vp;
4890 KKASSERT(mbp->b_bcount >= offset + size);
4892 atomic_add_int((int *)&mbio->bio_driver_info, 1);
4894 /* kernel needs to own the lock for it to be released in biodone */
4895 BUF_KERNPROC(bp);
4896 bp->b_vp = vp;
4897 bp->b_cmd = mbp->b_cmd;
4898 bp->b_bio1.bio_done = nestiobuf_iodone;
4899 bp->b_data = (char *)mbp->b_data + offset;
4900 bp->b_resid = bp->b_bcount = size;
4901 bp->b_bufsize = bp->b_bcount;
4903 bp->b_bio1.bio_track = NULL;
4904 bp->b_bio1.bio_caller_info1.ptr = mbio;
4905 bp->b_bio1.bio_caller_info2.ptr = stats;
4908 #ifdef DDB
4910 DB_SHOW_COMMAND(buffer, db_show_buffer)
4912 /* get args */
4913 struct buf *bp = (struct buf *)addr;
4915 if (!have_addr) {
4916 db_printf("usage: show buffer <addr>\n");
4917 return;
4920 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4921 db_printf("b_cmd = %d\n", bp->b_cmd);
4922 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
4923 "b_resid = %d\n, b_data = %p, "
4924 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
4925 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4926 bp->b_data,
4927 (long long)bp->b_bio2.bio_offset,
4928 (long long)(bp->b_bio2.bio_next ?
4929 bp->b_bio2.bio_next->bio_offset : (off_t)-1));
4930 if (bp->b_xio.xio_npages) {
4931 int i;
4932 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
4933 bp->b_xio.xio_npages);
4934 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4935 vm_page_t m;
4936 m = bp->b_xio.xio_pages[i];
4937 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4938 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4939 if ((i + 1) < bp->b_xio.xio_npages)
4940 db_printf(",");
4942 db_printf("\n");
4945 #endif /* DDB */