kernel - repurpose buffer cache entries under heavy I/O loads
[dragonfly.git] / sys / kern / vfs_bio.c
blobfd8e1de4dea22b91ef80d5d503eeab2e24782a46
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_EMPTY, /* empty buffer headers */
82 BUFFER_QUEUES /* number of buffer queues */
85 typedef enum bufq_type bufq_type_t;
87 #define BD_WAKE_SIZE 16384
88 #define BD_WAKE_MASK (BD_WAKE_SIZE - 1)
90 TAILQ_HEAD(bqueues, buf);
92 struct bufpcpu {
93 struct spinlock spin;
94 struct bqueues bufqueues[BUFFER_QUEUES];
95 } __cachealign;
97 struct bufpcpu bufpcpu[MAXCPU];
99 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
101 struct buf *buf; /* buffer header pool */
103 static void vfs_clean_pages(struct buf *bp);
104 static void vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m);
105 #if 0
106 static void vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m);
107 #endif
108 static void vfs_vmio_release(struct buf *bp);
109 static int flushbufqueues(struct buf *marker, bufq_type_t q);
110 static void repurposebuf(struct buf *bp, int size);
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; /* atomic ops */
132 long maxbufspace;
133 static long bufmallocspace; /* atomic ops */
134 long maxbufmallocspace, lobufspace, hibufspace;
135 static long lorunningspace;
136 static long hirunningspace;
137 static long dirtykvaspace; /* atomic */
138 long dirtybufspace; /* atomic (global for systat) */
139 static long dirtybufcount; /* atomic */
140 static long dirtybufspacehw; /* atomic */
141 static long dirtybufcounthw; /* atomic */
142 static long runningbufspace; /* atomic */
143 static long runningbufcount; /* atomic */
144 static long repurposedspace;
145 long lodirtybufspace;
146 long hidirtybufspace;
147 static int getnewbufcalls;
148 static int recoverbufcalls;
149 static int needsbuffer; /* atomic */
150 static int runningbufreq; /* atomic */
151 static int bd_request; /* atomic */
152 static int bd_request_hw; /* atomic */
153 static u_int bd_wake_ary[BD_WAKE_SIZE];
154 static u_int bd_wake_index;
155 static u_int vm_cycle_point = 40; /* 23-36 will migrate more act->inact */
156 static int debug_commit;
157 static int debug_bufbio;
158 static long bufcache_bw = 200 * 1024 * 1024;
159 static long bufcache_bw_accum;
160 static int bufcache_bw_ticks;
162 static struct thread *bufdaemon_td;
163 static struct thread *bufdaemonhw_td;
164 static u_int lowmempgallocs;
165 static u_int lowmempgfails;
166 static u_int flushperqueue = 1024;
169 * Sysctls for operational control of the buffer cache.
171 SYSCTL_UINT(_vfs, OID_AUTO, flushperqueue, CTLFLAG_RW, &flushperqueue, 0,
172 "Number of buffers to flush from each per-cpu queue");
173 SYSCTL_LONG(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
174 "Number of dirty buffers to flush before bufdaemon becomes inactive");
175 SYSCTL_LONG(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
176 "High watermark used to trigger explicit flushing of dirty buffers");
177 SYSCTL_LONG(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
178 "Minimum amount of buffer space required for active I/O");
179 SYSCTL_LONG(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
180 "Maximum amount of buffer space to usable for active I/O");
181 SYSCTL_LONG(_vfs, OID_AUTO, bufcache_bw, CTLFLAG_RW, &bufcache_bw, 0,
182 "Buffer-cache -> VM page cache transfer bandwidth");
183 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgallocs, CTLFLAG_RW, &lowmempgallocs, 0,
184 "Page allocations done during periods of very low free memory");
185 SYSCTL_UINT(_vfs, OID_AUTO, lowmempgfails, CTLFLAG_RW, &lowmempgfails, 0,
186 "Page allocations which failed during periods of very low free memory");
187 SYSCTL_UINT(_vfs, OID_AUTO, vm_cycle_point, CTLFLAG_RW, &vm_cycle_point, 0,
188 "Recycle pages to active or inactive queue transition pt 0-64");
190 * Sysctls determining current state of the buffer cache.
192 SYSCTL_LONG(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
193 "Total number of buffers in buffer cache");
194 SYSCTL_LONG(_vfs, OID_AUTO, dirtykvaspace, CTLFLAG_RD, &dirtykvaspace, 0,
195 "KVA reserved by dirty buffers (all)");
196 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
197 "Pending bytes of dirty buffers (all)");
198 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
199 "Pending bytes of dirty buffers (heavy weight)");
200 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
201 "Pending number of dirty buffers");
202 SYSCTL_LONG(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
203 "Pending number of dirty buffers (heavy weight)");
204 SYSCTL_LONG(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
205 "I/O bytes currently in progress due to asynchronous writes");
206 SYSCTL_LONG(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
207 "I/O buffers currently in progress due to asynchronous writes");
208 SYSCTL_LONG(_vfs, OID_AUTO, repurposedspace, CTLFLAG_RD, &repurposedspace, 0,
209 "Buffer-cache memory repurposed in-place");
210 SYSCTL_LONG(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
211 "Hard limit on maximum amount of memory usable for buffer space");
212 SYSCTL_LONG(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
213 "Soft limit on maximum amount of memory usable for buffer space");
214 SYSCTL_LONG(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
215 "Minimum amount of memory to reserve for system buffer space");
216 SYSCTL_LONG(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
217 "Amount of memory available for buffers");
218 SYSCTL_LONG(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
219 0, "Maximum amount of memory reserved for buffers using malloc");
220 SYSCTL_LONG(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
221 "Amount of memory left for buffers using malloc-scheme");
222 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
223 "New buffer header acquisition requests");
224 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
225 "Recover VM space in an emergency");
226 SYSCTL_INT(_vfs, OID_AUTO, debug_commit, CTLFLAG_RW, &debug_commit, 0, "");
227 SYSCTL_INT(_vfs, OID_AUTO, debug_bufbio, CTLFLAG_RW, &debug_bufbio, 0, "");
228 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
229 "sizeof(struct buf)");
231 char *buf_wmesg = BUF_WMESG;
233 #define VFS_BIO_NEED_ANY 0x01 /* any freeable buffer */
234 #define VFS_BIO_NEED_UNUSED02 0x02
235 #define VFS_BIO_NEED_UNUSED04 0x04
236 #define VFS_BIO_NEED_BUFSPACE 0x08 /* wait for buf space, lo hysteresis */
239 * Called when buffer space is potentially available for recovery.
240 * getnewbuf() will block on this flag when it is unable to free
241 * sufficient buffer space. Buffer space becomes recoverable when
242 * bp's get placed back in the queues.
244 static __inline void
245 bufspacewakeup(void)
248 * If someone is waiting for BUF space, wake them up. Even
249 * though we haven't freed the kva space yet, the waiting
250 * process will be able to now.
252 for (;;) {
253 int flags = needsbuffer;
254 cpu_ccfence();
255 if ((flags & VFS_BIO_NEED_BUFSPACE) == 0)
256 break;
257 if (atomic_cmpset_int(&needsbuffer, flags,
258 flags & ~VFS_BIO_NEED_BUFSPACE)) {
259 wakeup(&needsbuffer);
260 break;
262 /* retry */
267 * runningbufwakeup:
269 * Accounting for I/O in progress.
272 static __inline void
273 runningbufwakeup(struct buf *bp)
275 long totalspace;
276 long flags;
278 if ((totalspace = bp->b_runningbufspace) != 0) {
279 atomic_add_long(&runningbufspace, -totalspace);
280 atomic_add_long(&runningbufcount, -1);
281 bp->b_runningbufspace = 0;
284 * see waitrunningbufspace() for limit test.
286 for (;;) {
287 flags = runningbufreq;
288 cpu_ccfence();
289 if (flags == 0)
290 break;
291 if (atomic_cmpset_int(&runningbufreq, flags, 0)) {
292 wakeup(&runningbufreq);
293 break;
295 /* retry */
297 bd_signal(totalspace);
302 * bufcountwakeup:
304 * Called when a buffer has been added to one of the free queues to
305 * account for the buffer and to wakeup anyone waiting for free buffers.
306 * This typically occurs when large amounts of metadata are being handled
307 * by the buffer cache ( else buffer space runs out first, usually ).
309 static __inline void
310 bufcountwakeup(void)
312 long flags;
314 for (;;) {
315 flags = needsbuffer;
316 if (flags == 0)
317 break;
318 if (atomic_cmpset_int(&needsbuffer, flags,
319 (flags & ~VFS_BIO_NEED_ANY))) {
320 wakeup(&needsbuffer);
321 break;
323 /* retry */
328 * waitrunningbufspace()
330 * If runningbufspace exceeds 4/6 hirunningspace we block until
331 * runningbufspace drops to 3/6 hirunningspace. We also block if another
332 * thread blocked here in order to be fair, even if runningbufspace
333 * is now lower than the limit.
335 * The caller may be using this function to block in a tight loop, we
336 * must block while runningbufspace is greater than at least
337 * hirunningspace * 3 / 6.
339 void
340 waitrunningbufspace(void)
342 long limit = hirunningspace * 4 / 6;
343 long flags;
345 while (runningbufspace > limit || runningbufreq) {
346 tsleep_interlock(&runningbufreq, 0);
347 flags = atomic_fetchadd_int(&runningbufreq, 1);
348 if (runningbufspace > limit || flags)
349 tsleep(&runningbufreq, PINTERLOCKED, "wdrn1", hz);
354 * buf_dirty_count_severe:
356 * Return true if we have too many dirty buffers.
359 buf_dirty_count_severe(void)
361 return (runningbufspace + dirtykvaspace >= hidirtybufspace ||
362 dirtybufcount >= nbuf / 2);
366 * Return true if the amount of running I/O is severe and BIOQ should
367 * start bursting.
370 buf_runningbufspace_severe(void)
372 return (runningbufspace >= hirunningspace * 4 / 6);
376 * vfs_buf_test_cache:
378 * Called when a buffer is extended. This function clears the B_CACHE
379 * bit if the newly extended portion of the buffer does not contain
380 * valid data.
382 * NOTE! Dirty VM pages are not processed into dirty (B_DELWRI) buffer
383 * cache buffers. The VM pages remain dirty, as someone had mmap()'d
384 * them while a clean buffer was present.
386 static __inline__
387 void
388 vfs_buf_test_cache(struct buf *bp,
389 vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
390 vm_page_t m)
392 if (bp->b_flags & B_CACHE) {
393 int base = (foff + off) & PAGE_MASK;
394 if (vm_page_is_valid(m, base, size) == 0)
395 bp->b_flags &= ~B_CACHE;
400 * bd_speedup()
402 * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
403 * low water mark.
405 static __inline__
406 void
407 bd_speedup(void)
409 if (dirtykvaspace < lodirtybufspace && dirtybufcount < nbuf / 2)
410 return;
412 if (bd_request == 0 &&
413 (dirtykvaspace > lodirtybufspace / 2 ||
414 dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
415 if (atomic_fetchadd_int(&bd_request, 1) == 0)
416 wakeup(&bd_request);
418 if (bd_request_hw == 0 &&
419 (dirtykvaspace > lodirtybufspace / 2 ||
420 dirtybufcounthw >= nbuf / 2)) {
421 if (atomic_fetchadd_int(&bd_request_hw, 1) == 0)
422 wakeup(&bd_request_hw);
427 * bd_heatup()
429 * Get the buf_daemon heated up when the number of running and dirty
430 * buffers exceeds the mid-point.
432 * Return the total number of dirty bytes past the second mid point
433 * as a measure of how much excess dirty data there is in the system.
435 long
436 bd_heatup(void)
438 long mid1;
439 long mid2;
440 long totalspace;
442 mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
444 totalspace = runningbufspace + dirtykvaspace;
445 if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
446 bd_speedup();
447 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
448 if (totalspace >= mid2)
449 return(totalspace - mid2);
451 return(0);
455 * bd_wait()
457 * Wait for the buffer cache to flush (totalspace) bytes worth of
458 * buffers, then return.
460 * Regardless this function blocks while the number of dirty buffers
461 * exceeds hidirtybufspace.
463 void
464 bd_wait(long totalspace)
466 u_int i;
467 u_int j;
468 u_int mi;
469 int count;
471 if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
472 return;
474 while (totalspace > 0) {
475 bd_heatup();
478 * Order is important. Suppliers adjust bd_wake_index after
479 * updating runningbufspace/dirtykvaspace. We want to fetch
480 * bd_wake_index before accessing. Any error should thus
481 * be in our favor.
483 i = atomic_fetchadd_int(&bd_wake_index, 0);
484 if (totalspace > runningbufspace + dirtykvaspace)
485 totalspace = runningbufspace + dirtykvaspace;
486 count = totalspace / MAXBSIZE;
487 if (count >= BD_WAKE_SIZE / 2)
488 count = BD_WAKE_SIZE / 2;
489 i = i + count;
490 mi = i & BD_WAKE_MASK;
493 * This is not a strict interlock, so we play a bit loose
494 * with locking access to dirtybufspace*. We have to re-check
495 * bd_wake_index to ensure that it hasn't passed us.
497 tsleep_interlock(&bd_wake_ary[mi], 0);
498 atomic_add_int(&bd_wake_ary[mi], 1);
499 j = atomic_fetchadd_int(&bd_wake_index, 0);
500 if ((int)(i - j) >= 0)
501 tsleep(&bd_wake_ary[mi], PINTERLOCKED, "flstik", hz);
503 totalspace = runningbufspace + dirtykvaspace - hidirtybufspace;
508 * bd_signal()
510 * This function is called whenever runningbufspace or dirtykvaspace
511 * is reduced. Track threads waiting for run+dirty buffer I/O
512 * complete.
514 static void
515 bd_signal(long totalspace)
517 u_int i;
519 if (totalspace > 0) {
520 if (totalspace > MAXBSIZE * BD_WAKE_SIZE)
521 totalspace = MAXBSIZE * BD_WAKE_SIZE;
522 while (totalspace > 0) {
523 i = atomic_fetchadd_int(&bd_wake_index, 1);
524 i &= BD_WAKE_MASK;
525 if (atomic_readandclear_int(&bd_wake_ary[i]))
526 wakeup(&bd_wake_ary[i]);
527 totalspace -= MAXBSIZE;
533 * BIO tracking support routines.
535 * Release a ref on a bio_track. Wakeup requests are atomically released
536 * along with the last reference so bk_active will never wind up set to
537 * only 0x80000000.
539 static
540 void
541 bio_track_rel(struct bio_track *track)
543 int active;
544 int desired;
547 * Shortcut
549 active = track->bk_active;
550 if (active == 1 && atomic_cmpset_int(&track->bk_active, 1, 0))
551 return;
554 * Full-on. Note that the wait flag is only atomically released on
555 * the 1->0 count transition.
557 * We check for a negative count transition using bit 30 since bit 31
558 * has a different meaning.
560 for (;;) {
561 desired = (active & 0x7FFFFFFF) - 1;
562 if (desired)
563 desired |= active & 0x80000000;
564 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
565 if (desired & 0x40000000)
566 panic("bio_track_rel: bad count: %p", track);
567 if (active & 0x80000000)
568 wakeup(track);
569 break;
571 active = track->bk_active;
576 * Wait for the tracking count to reach 0.
578 * Use atomic ops such that the wait flag is only set atomically when
579 * bk_active is non-zero.
582 bio_track_wait(struct bio_track *track, int slp_flags, int slp_timo)
584 int active;
585 int desired;
586 int error;
589 * Shortcut
591 if (track->bk_active == 0)
592 return(0);
595 * Full-on. Note that the wait flag may only be atomically set if
596 * the active count is non-zero.
598 * NOTE: We cannot optimize active == desired since a wakeup could
599 * clear active prior to our tsleep_interlock().
601 error = 0;
602 while ((active = track->bk_active) != 0) {
603 cpu_ccfence();
604 desired = active | 0x80000000;
605 tsleep_interlock(track, slp_flags);
606 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
607 error = tsleep(track, slp_flags | PINTERLOCKED,
608 "trwait", slp_timo);
609 if (error)
610 break;
613 return (error);
617 * bufinit:
619 * Load time initialisation of the buffer cache, called from machine
620 * dependant initialization code.
622 static
623 void
624 bufinit(void *dummy __unused)
626 struct bufpcpu *pcpu;
627 struct buf *bp;
628 vm_offset_t bogus_offset;
629 int i;
630 int j;
631 long n;
633 /* next, make a null set of free lists */
634 for (i = 0; i < ncpus; ++i) {
635 pcpu = &bufpcpu[i];
636 spin_init(&pcpu->spin, "bufinit");
637 for (j = 0; j < BUFFER_QUEUES; j++)
638 TAILQ_INIT(&pcpu->bufqueues[j]);
642 * Finally, initialize each buffer header and stick on empty q.
643 * Each buffer gets its own KVA reservation.
645 i = 0;
646 pcpu = &bufpcpu[i];
648 for (n = 0; n < nbuf; n++) {
649 bp = &buf[n];
650 bzero(bp, sizeof *bp);
651 bp->b_flags = B_INVAL; /* we're just an empty header */
652 bp->b_cmd = BUF_CMD_DONE;
653 bp->b_qindex = BQUEUE_EMPTY;
654 bp->b_qcpu = i;
655 bp->b_kvabase = (void *)(vm_map_min(&buffer_map) +
656 MAXBSIZE * n);
657 bp->b_kvasize = MAXBSIZE;
658 initbufbio(bp);
659 xio_init(&bp->b_xio);
660 buf_dep_init(bp);
661 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
662 bp, b_freelist);
664 i = (i + 1) % ncpus;
665 pcpu = &bufpcpu[i];
669 * maxbufspace is the absolute maximum amount of buffer space we are
670 * allowed to reserve in KVM and in real terms. The absolute maximum
671 * is nominally used by buf_daemon. hibufspace is the nominal maximum
672 * used by most other processes. The differential is required to
673 * ensure that buf_daemon is able to run when other processes might
674 * be blocked waiting for buffer space.
676 * Calculate hysteresis (lobufspace, hibufspace). Don't make it
677 * too large or we might lockup a cpu for too long a period of
678 * time in our tight loop.
680 maxbufspace = nbuf * NBUFCALCSIZE;
681 hibufspace = lmax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
682 lobufspace = hibufspace * 7 / 8;
683 if (hibufspace - lobufspace > 64 * 1024 * 1024)
684 lobufspace = hibufspace - 64 * 1024 * 1024;
685 if (lobufspace > hibufspace - MAXBSIZE)
686 lobufspace = hibufspace - MAXBSIZE;
688 lorunningspace = 512 * 1024;
689 /* hirunningspace -- see below */
692 * Limit the amount of malloc memory since it is wired permanently
693 * into the kernel space. Even though this is accounted for in
694 * the buffer allocation, we don't want the malloced region to grow
695 * uncontrolled. The malloc scheme improves memory utilization
696 * significantly on average (small) directories.
698 maxbufmallocspace = hibufspace / 20;
701 * Reduce the chance of a deadlock occuring by limiting the number
702 * of delayed-write dirty buffers we allow to stack up.
704 * We don't want too much actually queued to the device at once
705 * (XXX this needs to be per-mount!), because the buffers will
706 * wind up locked for a very long period of time while the I/O
707 * drains.
709 hidirtybufspace = hibufspace / 2; /* dirty + running */
710 hirunningspace = hibufspace / 16; /* locked & queued to device */
711 if (hirunningspace < 1024 * 1024)
712 hirunningspace = 1024 * 1024;
714 dirtykvaspace = 0;
715 dirtybufspace = 0;
716 dirtybufspacehw = 0;
718 lodirtybufspace = hidirtybufspace / 2;
721 * Maximum number of async ops initiated per buf_daemon loop. This is
722 * somewhat of a hack at the moment, we really need to limit ourselves
723 * based on the number of bytes of I/O in-transit that were initiated
724 * from buf_daemon.
727 bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
728 vm_object_hold(&kernel_object);
729 bogus_page = vm_page_alloc(&kernel_object,
730 (bogus_offset >> PAGE_SHIFT),
731 VM_ALLOC_NORMAL);
732 vm_object_drop(&kernel_object);
733 vmstats.v_wire_count++;
737 SYSINIT(do_bufinit, SI_BOOT2_MACHDEP, SI_ORDER_FIRST, bufinit, NULL);
740 * Initialize the embedded bio structures, typically used by
741 * deprecated code which tries to allocate its own struct bufs.
743 void
744 initbufbio(struct buf *bp)
746 bp->b_bio1.bio_buf = bp;
747 bp->b_bio1.bio_prev = NULL;
748 bp->b_bio1.bio_offset = NOOFFSET;
749 bp->b_bio1.bio_next = &bp->b_bio2;
750 bp->b_bio1.bio_done = NULL;
751 bp->b_bio1.bio_flags = 0;
753 bp->b_bio2.bio_buf = bp;
754 bp->b_bio2.bio_prev = &bp->b_bio1;
755 bp->b_bio2.bio_offset = NOOFFSET;
756 bp->b_bio2.bio_next = NULL;
757 bp->b_bio2.bio_done = NULL;
758 bp->b_bio2.bio_flags = 0;
760 BUF_LOCKINIT(bp);
764 * Reinitialize the embedded bio structures as well as any additional
765 * translation cache layers.
767 void
768 reinitbufbio(struct buf *bp)
770 struct bio *bio;
772 for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
773 bio->bio_done = NULL;
774 bio->bio_offset = NOOFFSET;
779 * Undo the effects of an initbufbio().
781 void
782 uninitbufbio(struct buf *bp)
784 dsched_buf_exit(bp);
785 BUF_LOCKFREE(bp);
789 * Push another BIO layer onto an existing BIO and return it. The new
790 * BIO layer may already exist, holding cached translation data.
792 struct bio *
793 push_bio(struct bio *bio)
795 struct bio *nbio;
797 if ((nbio = bio->bio_next) == NULL) {
798 int index = bio - &bio->bio_buf->b_bio_array[0];
799 if (index >= NBUF_BIO - 1) {
800 panic("push_bio: too many layers %d for bp %p",
801 index, bio->bio_buf);
803 nbio = &bio->bio_buf->b_bio_array[index + 1];
804 bio->bio_next = nbio;
805 nbio->bio_prev = bio;
806 nbio->bio_buf = bio->bio_buf;
807 nbio->bio_offset = NOOFFSET;
808 nbio->bio_done = NULL;
809 nbio->bio_next = NULL;
811 KKASSERT(nbio->bio_done == NULL);
812 return(nbio);
816 * Pop a BIO translation layer, returning the previous layer. The
817 * must have been previously pushed.
819 struct bio *
820 pop_bio(struct bio *bio)
822 return(bio->bio_prev);
825 void
826 clearbiocache(struct bio *bio)
828 while (bio) {
829 bio->bio_offset = NOOFFSET;
830 bio = bio->bio_next;
835 * Remove the buffer from the appropriate free list.
836 * (caller must be locked)
838 static __inline void
839 _bremfree(struct buf *bp)
841 struct bufpcpu *pcpu = &bufpcpu[bp->b_qcpu];
843 if (bp->b_qindex != BQUEUE_NONE) {
844 KASSERT(BUF_REFCNTNB(bp) == 1,
845 ("bremfree: bp %p not locked",bp));
846 TAILQ_REMOVE(&pcpu->bufqueues[bp->b_qindex], bp, b_freelist);
847 bp->b_qindex = BQUEUE_NONE;
848 } else {
849 if (BUF_REFCNTNB(bp) <= 1)
850 panic("bremfree: removing a buffer not on a queue");
855 * bremfree() - must be called with a locked buffer
857 void
858 bremfree(struct buf *bp)
860 struct bufpcpu *pcpu = &bufpcpu[bp->b_qcpu];
862 spin_lock(&pcpu->spin);
863 _bremfree(bp);
864 spin_unlock(&pcpu->spin);
868 * bremfree_locked - must be called with pcpu->spin locked
870 static void
871 bremfree_locked(struct buf *bp)
873 _bremfree(bp);
877 * This version of bread issues any required I/O asyncnronously and
878 * makes a callback on completion.
880 * The callback must check whether BIO_DONE is set in the bio and issue
881 * the bpdone(bp, 0) if it isn't. The callback is responsible for clearing
882 * BIO_DONE and disposing of the I/O (bqrelse()ing it).
884 void
885 breadcb(struct vnode *vp, off_t loffset, int size,
886 void (*func)(struct bio *), void *arg)
888 struct buf *bp;
890 bp = getblk(vp, loffset, size, 0, 0);
892 /* if not found in cache, do some I/O */
893 if ((bp->b_flags & B_CACHE) == 0) {
894 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
895 bp->b_cmd = BUF_CMD_READ;
896 bp->b_bio1.bio_done = func;
897 bp->b_bio1.bio_caller_info1.ptr = arg;
898 vfs_busy_pages(vp, bp);
899 BUF_KERNPROC(bp);
900 vn_strategy(vp, &bp->b_bio1);
901 } else if (func) {
903 * Since we are issuing the callback synchronously it cannot
904 * race the BIO_DONE, so no need for atomic ops here.
906 /*bp->b_bio1.bio_done = func;*/
907 bp->b_bio1.bio_caller_info1.ptr = arg;
908 bp->b_bio1.bio_flags |= BIO_DONE;
909 func(&bp->b_bio1);
910 } else {
911 bqrelse(bp);
916 * breadnx() - Terminal function for bread() and breadn().
918 * This function will start asynchronous I/O on read-ahead blocks as well
919 * as satisfy the primary request.
921 * We must clear B_ERROR and B_INVAL prior to initiating I/O. If B_CACHE is
922 * set, the buffer is valid and we do not have to do anything.
925 breadnx(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
926 int *rabsize, int cnt, struct buf **bpp)
928 struct buf *bp, *rabp;
929 int i;
930 int rv = 0, readwait = 0;
932 if (*bpp)
933 bp = *bpp;
934 else
935 *bpp = bp = getblk(vp, loffset, size, 0, 0);
937 /* if not found in cache, do some I/O */
938 if ((bp->b_flags & B_CACHE) == 0) {
939 bp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
940 bp->b_cmd = BUF_CMD_READ;
941 bp->b_bio1.bio_done = biodone_sync;
942 bp->b_bio1.bio_flags |= BIO_SYNC;
943 vfs_busy_pages(vp, bp);
944 vn_strategy(vp, &bp->b_bio1);
945 ++readwait;
948 for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
949 if (inmem(vp, *raoffset))
950 continue;
951 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
953 if ((rabp->b_flags & B_CACHE) == 0) {
954 rabp->b_flags &= ~(B_ERROR | B_EINTR | B_INVAL);
955 rabp->b_cmd = BUF_CMD_READ;
956 vfs_busy_pages(vp, rabp);
957 BUF_KERNPROC(rabp);
958 vn_strategy(vp, &rabp->b_bio1);
959 } else {
960 brelse(rabp);
963 if (readwait)
964 rv = biowait(&bp->b_bio1, "biord");
965 return (rv);
969 * bwrite:
971 * Synchronous write, waits for completion.
973 * Write, release buffer on completion. (Done by iodone
974 * if async). Do not bother writing anything if the buffer
975 * is invalid.
977 * Note that we set B_CACHE here, indicating that buffer is
978 * fully valid and thus cacheable. This is true even of NFS
979 * now so we set it generally. This could be set either here
980 * or in biodone() since the I/O is synchronous. We put it
981 * here.
984 bwrite(struct buf *bp)
986 int error;
988 if (bp->b_flags & B_INVAL) {
989 brelse(bp);
990 return (0);
992 if (BUF_REFCNTNB(bp) == 0)
993 panic("bwrite: buffer is not busy???");
996 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
997 * call because it will remove the buffer from the vnode's
998 * dirty buffer list prematurely and possibly cause filesystem
999 * checks to race buffer flushes. This is now handled in
1000 * bpdone().
1002 * bundirty(bp); REMOVED
1005 bp->b_flags &= ~(B_ERROR | B_EINTR);
1006 bp->b_flags |= B_CACHE;
1007 bp->b_cmd = BUF_CMD_WRITE;
1008 bp->b_bio1.bio_done = biodone_sync;
1009 bp->b_bio1.bio_flags |= BIO_SYNC;
1010 vfs_busy_pages(bp->b_vp, bp);
1013 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1014 * valid for vnode-backed buffers.
1016 bsetrunningbufspace(bp, bp->b_bufsize);
1017 vn_strategy(bp->b_vp, &bp->b_bio1);
1018 error = biowait(&bp->b_bio1, "biows");
1019 brelse(bp);
1021 return (error);
1025 * bawrite:
1027 * Asynchronous write. Start output on a buffer, but do not wait for
1028 * it to complete. The buffer is released when the output completes.
1030 * bwrite() ( or the VOP routine anyway ) is responsible for handling
1031 * B_INVAL buffers. Not us.
1033 void
1034 bawrite(struct buf *bp)
1036 if (bp->b_flags & B_INVAL) {
1037 brelse(bp);
1038 return;
1040 if (BUF_REFCNTNB(bp) == 0)
1041 panic("bawrite: buffer is not busy???");
1044 * NOTE: We no longer mark the buffer clear prior to the vn_strategy()
1045 * call because it will remove the buffer from the vnode's
1046 * dirty buffer list prematurely and possibly cause filesystem
1047 * checks to race buffer flushes. This is now handled in
1048 * bpdone().
1050 * bundirty(bp); REMOVED
1052 bp->b_flags &= ~(B_ERROR | B_EINTR);
1053 bp->b_flags |= B_CACHE;
1054 bp->b_cmd = BUF_CMD_WRITE;
1055 KKASSERT(bp->b_bio1.bio_done == NULL);
1056 vfs_busy_pages(bp->b_vp, bp);
1059 * Normal bwrites pipeline writes. NOTE: b_bufsize is only
1060 * valid for vnode-backed buffers.
1062 bsetrunningbufspace(bp, bp->b_bufsize);
1063 BUF_KERNPROC(bp);
1064 vn_strategy(bp->b_vp, &bp->b_bio1);
1068 * bowrite:
1070 * Ordered write. Start output on a buffer, and flag it so that the
1071 * device will write it in the order it was queued. The buffer is
1072 * released when the output completes. bwrite() ( or the VOP routine
1073 * anyway ) is responsible for handling B_INVAL buffers.
1076 bowrite(struct buf *bp)
1078 bp->b_flags |= B_ORDERED;
1079 bawrite(bp);
1080 return (0);
1084 * bdwrite:
1086 * Delayed write. (Buffer is marked dirty). Do not bother writing
1087 * anything if the buffer is marked invalid.
1089 * Note that since the buffer must be completely valid, we can safely
1090 * set B_CACHE. In fact, we have to set B_CACHE here rather then in
1091 * biodone() in order to prevent getblk from writing the buffer
1092 * out synchronously.
1094 void
1095 bdwrite(struct buf *bp)
1097 if (BUF_REFCNTNB(bp) == 0)
1098 panic("bdwrite: buffer is not busy");
1100 if (bp->b_flags & B_INVAL) {
1101 brelse(bp);
1102 return;
1104 bdirty(bp);
1106 dsched_buf_enter(bp); /* might stack */
1109 * Set B_CACHE, indicating that the buffer is fully valid. This is
1110 * true even of NFS now.
1112 bp->b_flags |= B_CACHE;
1115 * This bmap keeps the system from needing to do the bmap later,
1116 * perhaps when the system is attempting to do a sync. Since it
1117 * is likely that the indirect block -- or whatever other datastructure
1118 * that the filesystem needs is still in memory now, it is a good
1119 * thing to do this. Note also, that if the pageout daemon is
1120 * requesting a sync -- there might not be enough memory to do
1121 * the bmap then... So, this is important to do.
1123 if (bp->b_bio2.bio_offset == NOOFFSET) {
1124 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
1125 NULL, NULL, BUF_CMD_WRITE);
1129 * Because the underlying pages may still be mapped and
1130 * writable trying to set the dirty buffer (b_dirtyoff/end)
1131 * range here will be inaccurate.
1133 * However, we must still clean the pages to satisfy the
1134 * vnode_pager and pageout daemon, so they think the pages
1135 * have been "cleaned". What has really occured is that
1136 * they've been earmarked for later writing by the buffer
1137 * cache.
1139 * So we get the b_dirtyoff/end update but will not actually
1140 * depend on it (NFS that is) until the pages are busied for
1141 * writing later on.
1143 vfs_clean_pages(bp);
1144 bqrelse(bp);
1147 * note: we cannot initiate I/O from a bdwrite even if we wanted to,
1148 * due to the softdep code.
1153 * Fake write - return pages to VM system as dirty, leave the buffer clean.
1154 * This is used by tmpfs.
1156 * It is important for any VFS using this routine to NOT use it for
1157 * IO_SYNC or IO_ASYNC operations which occur when the system really
1158 * wants to flush VM pages to backing store.
1160 void
1161 buwrite(struct buf *bp)
1163 vm_page_t m;
1164 int i;
1167 * Only works for VMIO buffers. If the buffer is already
1168 * marked for delayed-write we can't avoid the bdwrite().
1170 if ((bp->b_flags & B_VMIO) == 0 || (bp->b_flags & B_DELWRI)) {
1171 bdwrite(bp);
1172 return;
1176 * Mark as needing a commit.
1178 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1179 m = bp->b_xio.xio_pages[i];
1180 vm_page_need_commit(m);
1182 bqrelse(bp);
1186 * bdirty:
1188 * Turn buffer into delayed write request by marking it B_DELWRI.
1189 * B_RELBUF and B_NOCACHE must be cleared.
1191 * We reassign the buffer to itself to properly update it in the
1192 * dirty/clean lists.
1194 * Must be called from a critical section.
1195 * The buffer must be on BQUEUE_NONE.
1197 void
1198 bdirty(struct buf *bp)
1200 KASSERT(bp->b_qindex == BQUEUE_NONE,
1201 ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
1202 if (bp->b_flags & B_NOCACHE) {
1203 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
1204 bp->b_flags &= ~B_NOCACHE;
1206 if (bp->b_flags & B_INVAL) {
1207 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
1209 bp->b_flags &= ~B_RELBUF;
1211 if ((bp->b_flags & B_DELWRI) == 0) {
1212 lwkt_gettoken(&bp->b_vp->v_token);
1213 bp->b_flags |= B_DELWRI;
1214 reassignbuf(bp);
1215 lwkt_reltoken(&bp->b_vp->v_token);
1217 atomic_add_long(&dirtybufcount, 1);
1218 atomic_add_long(&dirtykvaspace, bp->b_kvasize);
1219 atomic_add_long(&dirtybufspace, bp->b_bufsize);
1220 if (bp->b_flags & B_HEAVY) {
1221 atomic_add_long(&dirtybufcounthw, 1);
1222 atomic_add_long(&dirtybufspacehw, bp->b_bufsize);
1224 bd_heatup();
1229 * Set B_HEAVY, indicating that this is a heavy-weight buffer that
1230 * needs to be flushed with a different buf_daemon thread to avoid
1231 * deadlocks. B_HEAVY also imposes restrictions in getnewbuf().
1233 void
1234 bheavy(struct buf *bp)
1236 if ((bp->b_flags & B_HEAVY) == 0) {
1237 bp->b_flags |= B_HEAVY;
1238 if (bp->b_flags & B_DELWRI) {
1239 atomic_add_long(&dirtybufcounthw, 1);
1240 atomic_add_long(&dirtybufspacehw, bp->b_bufsize);
1246 * bundirty:
1248 * Clear B_DELWRI for buffer.
1250 * Must be called from a critical section.
1252 * The buffer is typically on BQUEUE_NONE but there is one case in
1253 * brelse() that calls this function after placing the buffer on
1254 * a different queue.
1256 void
1257 bundirty(struct buf *bp)
1259 if (bp->b_flags & B_DELWRI) {
1260 lwkt_gettoken(&bp->b_vp->v_token);
1261 bp->b_flags &= ~B_DELWRI;
1262 reassignbuf(bp);
1263 lwkt_reltoken(&bp->b_vp->v_token);
1265 atomic_add_long(&dirtybufcount, -1);
1266 atomic_add_long(&dirtykvaspace, -bp->b_kvasize);
1267 atomic_add_long(&dirtybufspace, -bp->b_bufsize);
1268 if (bp->b_flags & B_HEAVY) {
1269 atomic_add_long(&dirtybufcounthw, -1);
1270 atomic_add_long(&dirtybufspacehw, -bp->b_bufsize);
1272 bd_signal(bp->b_bufsize);
1275 * Since it is now being written, we can clear its deferred write flag.
1277 bp->b_flags &= ~B_DEFERRED;
1281 * Set the b_runningbufspace field, used to track how much I/O is
1282 * in progress at any given moment.
1284 void
1285 bsetrunningbufspace(struct buf *bp, int bytes)
1287 bp->b_runningbufspace = bytes;
1288 if (bytes) {
1289 atomic_add_long(&runningbufspace, bytes);
1290 atomic_add_long(&runningbufcount, 1);
1295 * brelse:
1297 * Release a busy buffer and, if requested, free its resources. The
1298 * buffer will be stashed in the appropriate bufqueue[] allowing it
1299 * to be accessed later as a cache entity or reused for other purposes.
1301 void
1302 brelse(struct buf *bp)
1304 struct bufpcpu *pcpu;
1305 #ifdef INVARIANTS
1306 int saved_flags = bp->b_flags;
1307 #endif
1309 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1310 ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1313 * If B_NOCACHE is set we are being asked to destroy the buffer and
1314 * its backing store. Clear B_DELWRI.
1316 * B_NOCACHE is set in two cases: (1) when the caller really wants
1317 * to destroy the buffer and backing store and (2) when the caller
1318 * wants to destroy the buffer and backing store after a write
1319 * completes.
1321 if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1322 bundirty(bp);
1325 if ((bp->b_flags & (B_INVAL | B_DELWRI)) == B_DELWRI) {
1327 * A re-dirtied buffer is only subject to destruction
1328 * by B_INVAL. B_ERROR and B_NOCACHE are ignored.
1330 /* leave buffer intact */
1331 } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1332 (bp->b_bufsize <= 0)) {
1334 * Either a failed read or we were asked to free or not
1335 * cache the buffer. This path is reached with B_DELWRI
1336 * set only if B_INVAL is already set. B_NOCACHE governs
1337 * backing store destruction.
1339 * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1340 * buffer cannot be immediately freed.
1342 bp->b_flags |= B_INVAL;
1343 if (LIST_FIRST(&bp->b_dep) != NULL)
1344 buf_deallocate(bp);
1345 if (bp->b_flags & B_DELWRI) {
1346 atomic_add_long(&dirtybufcount, -1);
1347 atomic_add_long(&dirtykvaspace, -bp->b_kvasize);
1348 atomic_add_long(&dirtybufspace, -bp->b_bufsize);
1349 if (bp->b_flags & B_HEAVY) {
1350 atomic_add_long(&dirtybufcounthw, -1);
1351 atomic_add_long(&dirtybufspacehw,
1352 -bp->b_bufsize);
1354 bd_signal(bp->b_bufsize);
1356 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1360 * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set,
1361 * or if b_refs is non-zero.
1363 * If vfs_vmio_release() is called with either bit set, the
1364 * underlying pages may wind up getting freed causing a previous
1365 * write (bdwrite()) to get 'lost' because pages associated with
1366 * a B_DELWRI bp are marked clean. Pages associated with a
1367 * B_LOCKED buffer may be mapped by the filesystem.
1369 * If we want to release the buffer ourselves (rather then the
1370 * originator asking us to release it), give the originator a
1371 * chance to countermand the release by setting B_LOCKED.
1373 * We still allow the B_INVAL case to call vfs_vmio_release(), even
1374 * if B_DELWRI is set.
1376 * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1377 * on pages to return pages to the VM page queues.
1379 if ((bp->b_flags & (B_DELWRI | B_LOCKED)) || bp->b_refs) {
1380 bp->b_flags &= ~B_RELBUF;
1381 } else if (vm_page_count_min(0)) {
1382 if (LIST_FIRST(&bp->b_dep) != NULL)
1383 buf_deallocate(bp); /* can set B_LOCKED */
1384 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1385 bp->b_flags &= ~B_RELBUF;
1386 else
1387 bp->b_flags |= B_RELBUF;
1391 * Make sure b_cmd is clear. It may have already been cleared by
1392 * biodone().
1394 * At this point destroying the buffer is governed by the B_INVAL
1395 * or B_RELBUF flags.
1397 bp->b_cmd = BUF_CMD_DONE;
1398 dsched_buf_exit(bp);
1401 * VMIO buffer rundown. Make sure the VM page array is restored
1402 * after an I/O may have replaces some of the pages with bogus pages
1403 * in order to not destroy dirty pages in a fill-in read.
1405 * Note that due to the code above, if a buffer is marked B_DELWRI
1406 * then the B_RELBUF and B_NOCACHE bits will always be clear.
1407 * B_INVAL may still be set, however.
1409 * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1410 * but not the backing store. B_NOCACHE will destroy the backing
1411 * store.
1413 * Note that dirty NFS buffers contain byte-granular write ranges
1414 * and should not be destroyed w/ B_INVAL even if the backing store
1415 * is left intact.
1417 if (bp->b_flags & B_VMIO) {
1419 * Rundown for VMIO buffers which are not dirty NFS buffers.
1421 int i, j, resid;
1422 vm_page_t m;
1423 off_t foff;
1424 vm_pindex_t poff;
1425 vm_object_t obj;
1426 struct vnode *vp;
1428 vp = bp->b_vp;
1431 * Get the base offset and length of the buffer. Note that
1432 * in the VMIO case if the buffer block size is not
1433 * page-aligned then b_data pointer may not be page-aligned.
1434 * But our b_xio.xio_pages array *IS* page aligned.
1436 * block sizes less then DEV_BSIZE (usually 512) are not
1437 * supported due to the page granularity bits (m->valid,
1438 * m->dirty, etc...).
1440 * See man buf(9) for more information
1443 resid = bp->b_bufsize;
1444 foff = bp->b_loffset;
1446 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1447 m = bp->b_xio.xio_pages[i];
1448 vm_page_flag_clear(m, PG_ZERO);
1450 * If we hit a bogus page, fixup *all* of them
1451 * now. Note that we left these pages wired
1452 * when we removed them so they had better exist,
1453 * and they cannot be ripped out from under us so
1454 * no critical section protection is necessary.
1456 if (m == bogus_page) {
1457 obj = vp->v_object;
1458 poff = OFF_TO_IDX(bp->b_loffset);
1460 vm_object_hold(obj);
1461 for (j = i; j < bp->b_xio.xio_npages; j++) {
1462 vm_page_t mtmp;
1464 mtmp = bp->b_xio.xio_pages[j];
1465 if (mtmp == bogus_page) {
1466 mtmp = vm_page_lookup(obj, poff + j);
1467 if (!mtmp) {
1468 panic("brelse: page missing");
1470 bp->b_xio.xio_pages[j] = mtmp;
1473 bp->b_flags &= ~B_HASBOGUS;
1474 vm_object_drop(obj);
1476 if ((bp->b_flags & B_INVAL) == 0) {
1477 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1478 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1480 m = bp->b_xio.xio_pages[i];
1484 * Invalidate the backing store if B_NOCACHE is set
1485 * (e.g. used with vinvalbuf()). If this is NFS
1486 * we impose a requirement that the block size be
1487 * a multiple of PAGE_SIZE and create a temporary
1488 * hack to basically invalidate the whole page. The
1489 * problem is that NFS uses really odd buffer sizes
1490 * especially when tracking piecemeal writes and
1491 * it also vinvalbuf()'s a lot, which would result
1492 * in only partial page validation and invalidation
1493 * here. If the file page is mmap()'d, however,
1494 * all the valid bits get set so after we invalidate
1495 * here we would end up with weird m->valid values
1496 * like 0xfc. nfs_getpages() can't handle this so
1497 * we clear all the valid bits for the NFS case
1498 * instead of just some of them.
1500 * The real bug is the VM system having to set m->valid
1501 * to VM_PAGE_BITS_ALL for faulted-in pages, which
1502 * itself is an artifact of the whole 512-byte
1503 * granular mess that exists to support odd block
1504 * sizes and UFS meta-data block sizes (e.g. 6144).
1505 * A complete rewrite is required.
1507 * XXX
1509 if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1510 int poffset = foff & PAGE_MASK;
1511 int presid;
1513 presid = PAGE_SIZE - poffset;
1514 if (bp->b_vp->v_tag == VT_NFS &&
1515 bp->b_vp->v_type == VREG) {
1516 ; /* entire page */
1517 } else if (presid > resid) {
1518 presid = resid;
1520 KASSERT(presid >= 0, ("brelse: extra page"));
1521 vm_page_set_invalid(m, poffset, presid);
1524 * Also make sure any swap cache is removed
1525 * as it is now stale (HAMMER in particular
1526 * uses B_NOCACHE to deal with buffer
1527 * aliasing).
1529 swap_pager_unswapped(m);
1531 resid -= PAGE_SIZE - (foff & PAGE_MASK);
1532 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1534 if (bp->b_flags & (B_INVAL | B_RELBUF))
1535 vfs_vmio_release(bp);
1536 } else {
1538 * Rundown for non-VMIO buffers.
1540 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1541 if (bp->b_bufsize)
1542 allocbuf(bp, 0);
1543 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1544 if (bp->b_vp)
1545 brelvp(bp);
1549 if (bp->b_qindex != BQUEUE_NONE)
1550 panic("brelse: free buffer onto another queue???");
1551 if (BUF_REFCNTNB(bp) > 1) {
1552 /* Temporary panic to verify exclusive locking */
1553 /* This panic goes away when we allow shared refs */
1554 panic("brelse: multiple refs");
1555 /* NOT REACHED */
1556 return;
1560 * Figure out the correct queue to place the cleaned up buffer on.
1561 * Buffers placed in the EMPTY or EMPTYKVA had better already be
1562 * disassociated from their vnode.
1564 * Return the buffer to its original pcpu area
1566 pcpu = &bufpcpu[bp->b_qcpu];
1567 spin_lock(&pcpu->spin);
1569 if (bp->b_flags & B_LOCKED) {
1571 * Buffers that are locked are placed in the locked queue
1572 * immediately, regardless of their state.
1574 bp->b_qindex = BQUEUE_LOCKED;
1575 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1576 bp, b_freelist);
1577 } else if (bp->b_bufsize == 0) {
1579 * Buffers with no memory. Due to conditionals near the top
1580 * of brelse() such buffers should probably already be
1581 * marked B_INVAL and disassociated from their vnode.
1583 bp->b_flags |= B_INVAL;
1584 KASSERT(bp->b_vp == NULL,
1585 ("bp1 %p flags %08x/%08x vnode %p "
1586 "unexpectededly still associated!",
1587 bp, saved_flags, bp->b_flags, bp->b_vp));
1588 KKASSERT((bp->b_flags & B_HASHED) == 0);
1589 bp->b_qindex = BQUEUE_EMPTY;
1590 TAILQ_INSERT_HEAD(&pcpu->bufqueues[bp->b_qindex],
1591 bp, b_freelist);
1592 } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) {
1594 * Buffers with junk contents. Again these buffers had better
1595 * already be disassociated from their vnode.
1597 KASSERT(bp->b_vp == NULL,
1598 ("bp2 %p flags %08x/%08x vnode %p unexpectededly "
1599 "still associated!",
1600 bp, saved_flags, bp->b_flags, bp->b_vp));
1601 KKASSERT((bp->b_flags & B_HASHED) == 0);
1602 bp->b_flags |= B_INVAL;
1603 bp->b_qindex = BQUEUE_CLEAN;
1604 TAILQ_INSERT_HEAD(&pcpu->bufqueues[bp->b_qindex],
1605 bp, b_freelist);
1606 } else {
1608 * Remaining buffers. These buffers are still associated with
1609 * their vnode.
1611 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1612 case B_DELWRI:
1613 bp->b_qindex = BQUEUE_DIRTY;
1614 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1615 bp, b_freelist);
1616 break;
1617 case B_DELWRI | B_HEAVY:
1618 bp->b_qindex = BQUEUE_DIRTY_HW;
1619 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1620 bp, b_freelist);
1621 break;
1622 default:
1624 * NOTE: Buffers are always placed at the end of the
1625 * queue. If B_AGE is not set the buffer will cycle
1626 * through the queue twice.
1628 bp->b_qindex = BQUEUE_CLEAN;
1629 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1630 bp, b_freelist);
1631 break;
1634 spin_unlock(&pcpu->spin);
1637 * If B_INVAL, clear B_DELWRI. We've already placed the buffer
1638 * on the correct queue but we have not yet unlocked it.
1640 if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1641 bundirty(bp);
1644 * The bp is on an appropriate queue unless locked. If it is not
1645 * locked or dirty we can wakeup threads waiting for buffer space.
1647 * We've already handled the B_INVAL case ( B_DELWRI will be clear
1648 * if B_INVAL is set ).
1650 if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1651 bufcountwakeup();
1654 * Something we can maybe free or reuse
1656 if (bp->b_bufsize || bp->b_kvasize)
1657 bufspacewakeup();
1660 * Clean up temporary flags and unlock the buffer.
1662 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF | B_DIRECT);
1663 BUF_UNLOCK(bp);
1667 * bqrelse:
1669 * Release a buffer back to the appropriate queue but do not try to free
1670 * it. The buffer is expected to be used again soon.
1672 * bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1673 * biodone() to requeue an async I/O on completion. It is also used when
1674 * known good buffers need to be requeued but we think we may need the data
1675 * again soon.
1677 * XXX we should be able to leave the B_RELBUF hint set on completion.
1679 void
1680 bqrelse(struct buf *bp)
1682 struct bufpcpu *pcpu;
1684 KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)),
1685 ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1687 if (bp->b_qindex != BQUEUE_NONE)
1688 panic("bqrelse: free buffer onto another queue???");
1689 if (BUF_REFCNTNB(bp) > 1) {
1690 /* do not release to free list */
1691 panic("bqrelse: multiple refs");
1692 return;
1695 buf_act_advance(bp);
1697 pcpu = &bufpcpu[bp->b_qcpu];
1698 spin_lock(&pcpu->spin);
1700 if (bp->b_flags & B_LOCKED) {
1702 * Locked buffers are released to the locked queue. However,
1703 * if the buffer is dirty it will first go into the dirty
1704 * queue and later on after the I/O completes successfully it
1705 * will be released to the locked queue.
1707 bp->b_qindex = BQUEUE_LOCKED;
1708 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1709 bp, b_freelist);
1710 } else if (bp->b_flags & B_DELWRI) {
1711 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1712 BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1713 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1714 bp, b_freelist);
1715 } else if (vm_page_count_min(0)) {
1717 * We are too low on memory, we have to try to free the
1718 * buffer (most importantly: the wired pages making up its
1719 * backing store) *now*.
1721 spin_unlock(&pcpu->spin);
1722 brelse(bp);
1723 return;
1724 } else {
1725 bp->b_qindex = BQUEUE_CLEAN;
1726 TAILQ_INSERT_TAIL(&pcpu->bufqueues[bp->b_qindex],
1727 bp, b_freelist);
1729 spin_unlock(&pcpu->spin);
1732 * We have now placed the buffer on the proper queue, but have yet
1733 * to unlock it.
1735 if ((bp->b_flags & B_LOCKED) == 0 &&
1736 ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1737 bufcountwakeup();
1741 * Something we can maybe free or reuse.
1743 if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1744 bufspacewakeup();
1747 * Final cleanup and unlock. Clear bits that are only used while a
1748 * buffer is actively locked.
1750 bp->b_flags &= ~(B_ORDERED | B_NOCACHE | B_RELBUF);
1751 dsched_buf_exit(bp);
1752 BUF_UNLOCK(bp);
1756 * Hold a buffer, preventing it from being reused. This will prevent
1757 * normal B_RELBUF operations on the buffer but will not prevent B_INVAL
1758 * operations. If a B_INVAL operation occurs the buffer will remain held
1759 * but the underlying pages may get ripped out.
1761 * These functions are typically used in VOP_READ/VOP_WRITE functions
1762 * to hold a buffer during a copyin or copyout, preventing deadlocks
1763 * or recursive lock panics when read()/write() is used over mmap()'d
1764 * space.
1766 * NOTE: bqhold() requires that the buffer be locked at the time of the
1767 * hold. bqdrop() has no requirements other than the buffer having
1768 * previously been held.
1770 void
1771 bqhold(struct buf *bp)
1773 atomic_add_int(&bp->b_refs, 1);
1776 void
1777 bqdrop(struct buf *bp)
1779 KKASSERT(bp->b_refs > 0);
1780 atomic_add_int(&bp->b_refs, -1);
1784 * Return backing pages held by the buffer 'bp' back to the VM system.
1785 * This routine is called when the bp is invalidated, released, or
1786 * reused.
1788 * The KVA mapping (b_data) for the underlying pages is removed by
1789 * this function.
1791 * WARNING! This routine is integral to the low memory critical path
1792 * when a buffer is B_RELBUF'd. If the system has a severe page
1793 * deficit we need to get the page(s) onto the PQ_FREE or PQ_CACHE
1794 * queues so they can be reused in the current pageout daemon
1795 * pass.
1797 static void
1798 vfs_vmio_release(struct buf *bp)
1800 int i;
1801 vm_page_t m;
1803 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1804 m = bp->b_xio.xio_pages[i];
1805 bp->b_xio.xio_pages[i] = NULL;
1808 * We need to own the page in order to safely unwire it.
1810 vm_page_busy_wait(m, FALSE, "vmiopg");
1813 * The VFS is telling us this is not a meta-data buffer
1814 * even if it is backed by a block device.
1816 if (bp->b_flags & B_NOTMETA)
1817 vm_page_flag_set(m, PG_NOTMETA);
1820 * This is a very important bit of code. We try to track
1821 * VM page use whether the pages are wired into the buffer
1822 * cache or not. While wired into the buffer cache the
1823 * bp tracks the act_count.
1825 * We can choose to place unwired pages on the inactive
1826 * queue (0) or active queue (1). If we place too many
1827 * on the active queue the queue will cycle the act_count
1828 * on pages we'd like to keep, just from single-use pages
1829 * (such as when doing a tar-up or file scan).
1831 if (bp->b_act_count < vm_cycle_point)
1832 vm_page_unwire(m, 0);
1833 else
1834 vm_page_unwire(m, 1);
1837 * If the wire_count has dropped to 0 we may need to take
1838 * further action before unbusying the page.
1840 * WARNING: vm_page_try_*() also checks PG_NEED_COMMIT for us.
1842 if (m->wire_count == 0) {
1843 vm_page_flag_clear(m, PG_ZERO);
1845 if (bp->b_flags & B_DIRECT) {
1847 * Attempt to free the page if B_DIRECT is
1848 * set, the caller does not desire the page
1849 * to be cached.
1851 vm_page_wakeup(m);
1852 vm_page_try_to_free(m);
1853 } else if ((bp->b_flags & B_NOTMETA) ||
1854 vm_page_count_min(0)) {
1856 * Attempt to move the page to PQ_CACHE
1857 * if B_NOTMETA is set. This flag is set
1858 * by HAMMER to remove one of the two pages
1859 * present when double buffering is enabled.
1861 * Attempt to move the page to PQ_CACHE
1862 * If we have a severe page deficit. This
1863 * will cause buffer cache operations related
1864 * to pageouts to recycle the related pages
1865 * in order to avoid a low memory deadlock.
1867 m->act_count = bp->b_act_count;
1868 vm_page_wakeup(m);
1869 vm_page_try_to_cache(m);
1870 } else {
1872 * Nominal case, leave the page on the
1873 * queue the original unwiring placed it on
1874 * (active or inactive).
1876 m->act_count = bp->b_act_count;
1877 vm_page_wakeup(m);
1879 } else {
1880 vm_page_wakeup(m);
1884 pmap_qremove(trunc_page((vm_offset_t) bp->b_data),
1885 bp->b_xio.xio_npages);
1886 if (bp->b_bufsize) {
1887 atomic_add_long(&bufspace, -bp->b_bufsize);
1888 bp->b_bufsize = 0;
1889 bufspacewakeup();
1891 bp->b_xio.xio_npages = 0;
1892 bp->b_flags &= ~B_VMIO;
1893 KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1894 if (bp->b_vp)
1895 brelvp(bp);
1899 * Find and initialize a new buffer header, freeing up existing buffers
1900 * in the bufqueues as necessary. The new buffer is returned locked.
1902 * If repurpose is non-NULL getnewbuf() is allowed to re-purpose an existing
1903 * buffer. The buffer will be disassociated, its page and page mappings
1904 * left intact, and returned with *repurpose set to 1. Else *repurpose is set
1905 * to 0. If 1, the caller must repurpose the underlying VM pages.
1907 * If repurpose is NULL getnewbuf() is not allowed to re-purpose an
1908 * existing buffer. That is, it must completely initialize the returned
1909 * buffer.
1911 * Important: B_INVAL is not set. If the caller wishes to throw the
1912 * buffer away, the caller must set B_INVAL prior to calling brelse().
1914 * We block if:
1915 * We have insufficient buffer headers
1916 * We have insufficient buffer space
1918 * To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1919 * Instead we ask the buf daemon to do it for us. We attempt to
1920 * avoid piecemeal wakeups of the pageout daemon.
1922 struct buf *
1923 getnewbuf(int blkflags, int slptimeo, int size, int maxsize,
1924 struct vm_object **repurposep)
1926 struct bufpcpu *pcpu;
1927 struct buf *bp;
1928 struct buf *nbp;
1929 int nqindex;
1930 int nqcpu;
1931 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1932 int maxloops = 200000;
1933 int restart_reason = 0;
1934 struct buf *restart_bp = NULL;
1935 static char flushingbufs[MAXCPU];
1936 char *flushingp;
1939 * We can't afford to block since we might be holding a vnode lock,
1940 * which may prevent system daemons from running. We deal with
1941 * low-memory situations by proactively returning memory and running
1942 * async I/O rather then sync I/O.
1945 ++getnewbufcalls;
1946 nqcpu = mycpu->gd_cpuid;
1947 flushingp = &flushingbufs[nqcpu];
1948 restart:
1949 if (bufspace < lobufspace)
1950 *flushingp = 0;
1952 if (debug_bufbio && --maxloops == 0)
1953 panic("getnewbuf, excessive loops on cpu %d restart %d (%p)",
1954 mycpu->gd_cpuid, restart_reason, restart_bp);
1957 * Setup for scan. If we do not have enough free buffers,
1958 * we setup a degenerate case that immediately fails. Note
1959 * that if we are specially marked process, we are allowed to
1960 * dip into our reserves.
1962 * The scanning sequence is nominally: EMPTY->CLEAN
1964 pcpu = &bufpcpu[nqcpu];
1965 spin_lock(&pcpu->spin);
1968 * Determine if repurposing should be disallowed. Generally speaking
1969 * do not repurpose buffers if the buffer cache hasn't capped. Also
1970 * control repurposing based on buffer-cache -> main-memory bandwidth.
1971 * That is, we want to recycle buffers normally up until the buffer
1972 * cache bandwidth (new-buffer bw) exceeds bufcache_bw.
1974 * (This is heuristical, SMP collisions are ok)
1976 if (repurposep) {
1977 int delta = ticks - bufcache_bw_ticks;
1978 if (delta < 0 || delta >= hz) {
1979 atomic_swap_long(&bufcache_bw_accum, 0);
1980 atomic_swap_int(&bufcache_bw_ticks, ticks);
1982 atomic_add_long(&bufcache_bw_accum, size);
1983 if (bufspace < lobufspace) {
1984 repurposep = NULL;
1985 } else if (bufcache_bw_accum < bufcache_bw) {
1986 repurposep = NULL;
1991 * Prime the scan for this cpu. Locate the first buffer to
1992 * check. If we are flushing buffers we must skip the
1993 * EMPTY queue.
1995 nqindex = BQUEUE_EMPTY;
1996 nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_EMPTY]);
1997 if (nbp == NULL || *flushingp || repurposep) {
1998 nqindex = BQUEUE_CLEAN;
1999 nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_CLEAN]);
2003 * Run scan, possibly freeing data and/or kva mappings on the fly,
2004 * depending.
2006 * WARNING! spin is held!
2008 while ((bp = nbp) != NULL) {
2009 int qindex = nqindex;
2011 nbp = TAILQ_NEXT(bp, b_freelist);
2014 * BQUEUE_CLEAN - B_AGE special case. If not set the bp
2015 * cycles through the queue twice before being selected.
2017 if (qindex == BQUEUE_CLEAN &&
2018 (bp->b_flags & B_AGE) == 0 && nbp) {
2019 bp->b_flags |= B_AGE;
2020 TAILQ_REMOVE(&pcpu->bufqueues[qindex],
2021 bp, b_freelist);
2022 TAILQ_INSERT_TAIL(&pcpu->bufqueues[qindex],
2023 bp, b_freelist);
2024 continue;
2028 * Calculate next bp ( we can only use it if we do not block
2029 * or do other fancy things ).
2031 if (nbp == NULL) {
2032 switch(qindex) {
2033 case BQUEUE_EMPTY:
2034 nqindex = BQUEUE_CLEAN;
2035 if ((nbp = TAILQ_FIRST(&pcpu->bufqueues[BQUEUE_CLEAN])))
2036 break;
2037 /* fall through */
2038 case BQUEUE_CLEAN:
2040 * nbp is NULL.
2042 break;
2047 * Sanity Checks
2049 KASSERT(bp->b_qindex == qindex,
2050 ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
2053 * Note: we no longer distinguish between VMIO and non-VMIO
2054 * buffers.
2056 KASSERT((bp->b_flags & B_DELWRI) == 0,
2057 ("delwri buffer %p found in queue %d", bp, qindex));
2060 * Do not try to reuse a buffer with a non-zero b_refs.
2061 * This is an unsynchronized test. A synchronized test
2062 * is also performed after we lock the buffer.
2064 if (bp->b_refs)
2065 continue;
2068 * Start freeing the bp. This is somewhat involved. nbp
2069 * remains valid only for BQUEUE_EMPTY bp's. Buffers
2070 * on the clean list must be disassociated from their
2071 * current vnode. Buffers on the empty lists have
2072 * already been disassociated.
2074 * b_refs is checked after locking along with queue changes.
2075 * We must check here to deal with zero->nonzero transitions
2076 * made by the owner of the buffer lock, which is used by
2077 * VFS's to hold the buffer while issuing an unlocked
2078 * uiomove()s. We cannot invalidate the buffer's pages
2079 * for this case. Once we successfully lock a buffer the
2080 * only 0->1 transitions of b_refs will occur via findblk().
2082 * We must also check for queue changes after successful
2083 * locking as the current lock holder may dispose of the
2084 * buffer and change its queue.
2086 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2087 spin_unlock(&pcpu->spin);
2088 tsleep(&bd_request, 0, "gnbxxx", (hz + 99) / 100);
2089 restart_reason = 1;
2090 restart_bp = bp;
2091 goto restart;
2093 if (bp->b_qindex != qindex || bp->b_refs) {
2094 spin_unlock(&pcpu->spin);
2095 BUF_UNLOCK(bp);
2096 restart_reason = 2;
2097 restart_bp = bp;
2098 goto restart;
2100 bremfree_locked(bp);
2101 spin_unlock(&pcpu->spin);
2104 * Dependancies must be handled before we disassociate the
2105 * vnode.
2107 * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2108 * be immediately disassociated. HAMMER then becomes
2109 * responsible for releasing the buffer.
2111 * NOTE: spin is UNLOCKED now.
2113 if (LIST_FIRST(&bp->b_dep) != NULL) {
2114 buf_deallocate(bp);
2115 if (bp->b_flags & B_LOCKED) {
2116 bqrelse(bp);
2117 restart_reason = 3;
2118 restart_bp = bp;
2119 goto restart;
2121 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2125 * CLEAN buffers have content or associations that must be
2126 * cleaned out if not repurposing.
2128 if (qindex == BQUEUE_CLEAN) {
2129 if (bp->b_flags & B_VMIO) {
2130 if (repurposep && bp->b_bufsize &&
2131 (bp->b_flags & (B_DELWRI | B_MALLOC)) == 0) {
2132 *repurposep = bp->b_vp->v_object;
2133 vm_object_hold(*repurposep);
2134 } else {
2135 vfs_vmio_release(bp);
2138 if (bp->b_vp)
2139 brelvp(bp);
2143 * NOTE: nbp is now entirely invalid. We can only restart
2144 * the scan from this point on.
2146 * Get the rest of the buffer freed up. b_kva* is still
2147 * valid after this operation.
2149 KASSERT(bp->b_vp == NULL,
2150 ("bp3 %p flags %08x vnode %p qindex %d "
2151 "unexpectededly still associated!",
2152 bp, bp->b_flags, bp->b_vp, qindex));
2153 KKASSERT((bp->b_flags & B_HASHED) == 0);
2155 if (repurposep == NULL || *repurposep == NULL) {
2156 if (bp->b_bufsize)
2157 allocbuf(bp, 0);
2160 if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN | B_HASHED)) {
2161 kprintf("getnewbuf: caught bug vp queue "
2162 "%p/%08x qidx %d\n",
2163 bp, bp->b_flags, qindex);
2164 brelvp(bp);
2166 bp->b_flags = B_BNOCLIP;
2167 bp->b_cmd = BUF_CMD_DONE;
2168 bp->b_vp = NULL;
2169 bp->b_error = 0;
2170 bp->b_resid = 0;
2171 bp->b_bcount = 0;
2172 if (repurposep == NULL || *repurposep == NULL)
2173 bp->b_xio.xio_npages = 0;
2174 bp->b_dirtyoff = bp->b_dirtyend = 0;
2175 bp->b_act_count = ACT_INIT;
2176 reinitbufbio(bp);
2177 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2178 buf_dep_init(bp);
2179 if (blkflags & GETBLK_BHEAVY)
2180 bp->b_flags |= B_HEAVY;
2182 if (bufspace >= hibufspace)
2183 *flushingp = 1;
2184 if (bufspace < lobufspace)
2185 *flushingp = 0;
2186 if (*flushingp) {
2187 if (repurposep && *repurposep != NULL) {
2188 bp->b_flags |= B_VMIO;
2189 vfs_vmio_release(bp);
2190 if (bp->b_bufsize)
2191 allocbuf(bp, 0);
2192 vm_object_drop(*repurposep);
2193 *repurposep = NULL;
2195 bp->b_flags |= B_INVAL;
2196 brelse(bp);
2197 restart_reason = 5;
2198 restart_bp = bp;
2199 goto restart;
2203 * b_refs can transition to a non-zero value while we hold
2204 * the buffer locked due to a findblk(). Our brelvp() above
2205 * interlocked any future possible transitions due to
2206 * findblk()s.
2208 * If we find b_refs to be non-zero we can destroy the
2209 * buffer's contents but we cannot yet reuse the buffer.
2211 if (bp->b_refs) {
2212 if (repurposep && *repurposep != NULL) {
2213 bp->b_flags |= B_VMIO;
2214 vfs_vmio_release(bp);
2215 if (bp->b_bufsize)
2216 allocbuf(bp, 0);
2217 vm_object_drop(*repurposep);
2218 *repurposep = NULL;
2220 bp->b_flags |= B_INVAL;
2221 brelse(bp);
2222 restart_reason = 6;
2223 restart_bp = bp;
2225 goto restart;
2229 * We found our buffer!
2231 break;
2235 * If we exhausted our list, iterate other cpus. If that fails,
2236 * sleep as appropriate. We may have to wakeup various daemons
2237 * and write out some dirty buffers.
2239 * Generally we are sleeping due to insufficient buffer space.
2241 * NOTE: spin is held if bp is NULL, else it is not held.
2243 if (bp == NULL) {
2244 int flags;
2245 char *waitmsg;
2247 spin_unlock(&pcpu->spin);
2249 nqcpu = (nqcpu + 1) % ncpus;
2250 if (nqcpu != mycpu->gd_cpuid) {
2251 restart_reason = 7;
2252 restart_bp = bp;
2253 goto restart;
2256 if (bufspace >= hibufspace) {
2257 waitmsg = "bufspc";
2258 flags = VFS_BIO_NEED_BUFSPACE;
2259 } else {
2260 waitmsg = "newbuf";
2261 flags = VFS_BIO_NEED_ANY;
2264 bd_speedup(); /* heeeelp */
2265 atomic_set_int(&needsbuffer, flags);
2266 while (needsbuffer & flags) {
2267 int value;
2269 tsleep_interlock(&needsbuffer, 0);
2270 value = atomic_fetchadd_int(&needsbuffer, 0);
2271 if (value & flags) {
2272 if (tsleep(&needsbuffer, PINTERLOCKED|slpflags,
2273 waitmsg, slptimeo)) {
2274 return (NULL);
2278 } else {
2280 * We finally have a valid bp. Reset b_data.
2282 * (spin is not held)
2284 bp->b_data = bp->b_kvabase;
2286 return(bp);
2290 * buf_daemon:
2292 * Buffer flushing daemon. Buffers are normally flushed by the
2293 * update daemon but if it cannot keep up this process starts to
2294 * take the load in an attempt to prevent getnewbuf() from blocking.
2296 * Once a flush is initiated it does not stop until the number
2297 * of buffers falls below lodirtybuffers, but we will wake up anyone
2298 * waiting at the mid-point.
2300 static struct kproc_desc buf_kp = {
2301 "bufdaemon",
2302 buf_daemon,
2303 &bufdaemon_td
2305 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2306 kproc_start, &buf_kp);
2308 static struct kproc_desc bufhw_kp = {
2309 "bufdaemon_hw",
2310 buf_daemon_hw,
2311 &bufdaemonhw_td
2313 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2314 kproc_start, &bufhw_kp);
2316 static void
2317 buf_daemon1(struct thread *td, int queue, int (*buf_limit_fn)(long),
2318 int *bd_req)
2320 long limit;
2321 struct buf *marker;
2323 marker = kmalloc(sizeof(*marker), M_BIOBUF, M_WAITOK | M_ZERO);
2324 marker->b_flags |= B_MARKER;
2325 marker->b_qindex = BQUEUE_NONE;
2326 marker->b_qcpu = 0;
2329 * This process needs to be suspended prior to shutdown sync.
2331 EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2332 td, SHUTDOWN_PRI_LAST);
2333 curthread->td_flags |= TDF_SYSTHREAD;
2336 * This process is allowed to take the buffer cache to the limit
2338 for (;;) {
2339 kproc_suspend_loop();
2342 * Do the flush as long as the number of dirty buffers
2343 * (including those running) exceeds lodirtybufspace.
2345 * When flushing limit running I/O to hirunningspace
2346 * Do the flush. Limit the amount of in-transit I/O we
2347 * allow to build up, otherwise we would completely saturate
2348 * the I/O system. Wakeup any waiting processes before we
2349 * normally would so they can run in parallel with our drain.
2351 * Our aggregate normal+HW lo water mark is lodirtybufspace,
2352 * but because we split the operation into two threads we
2353 * have to cut it in half for each thread.
2355 waitrunningbufspace();
2356 limit = lodirtybufspace / 2;
2357 while (buf_limit_fn(limit)) {
2358 if (flushbufqueues(marker, queue) == 0)
2359 break;
2360 if (runningbufspace < hirunningspace)
2361 continue;
2362 waitrunningbufspace();
2366 * We reached our low water mark, reset the
2367 * request and sleep until we are needed again.
2368 * The sleep is just so the suspend code works.
2370 tsleep_interlock(bd_req, 0);
2371 if (atomic_swap_int(bd_req, 0) == 0)
2372 tsleep(bd_req, PINTERLOCKED, "psleep", hz);
2374 /* NOT REACHED */
2375 /*kfree(marker, M_BIOBUF);*/
2378 static int
2379 buf_daemon_limit(long limit)
2381 return (runningbufspace + dirtykvaspace > limit ||
2382 dirtybufcount - dirtybufcounthw >= nbuf / 2);
2385 static int
2386 buf_daemon_hw_limit(long limit)
2388 return (runningbufspace + dirtykvaspace > limit ||
2389 dirtybufcounthw >= nbuf / 2);
2392 static void
2393 buf_daemon(void)
2395 buf_daemon1(bufdaemon_td, BQUEUE_DIRTY, buf_daemon_limit,
2396 &bd_request);
2399 static void
2400 buf_daemon_hw(void)
2402 buf_daemon1(bufdaemonhw_td, BQUEUE_DIRTY_HW, buf_daemon_hw_limit,
2403 &bd_request_hw);
2407 * Flush up to (flushperqueue) buffers in the dirty queue. Each cpu has a
2408 * localized version of the queue. Each call made to this function iterates
2409 * to another cpu. It is desireable to flush several buffers from the same
2410 * cpu's queue at once, as these are likely going to be linear.
2412 * We must be careful to free up B_INVAL buffers instead of write them, which
2413 * NFS is particularly sensitive to.
2415 * B_RELBUF may only be set by VFSs. We do set B_AGE to indicate that we
2416 * really want to try to get the buffer out and reuse it due to the write
2417 * load on the machine.
2419 * We must lock the buffer in order to check its validity before we can mess
2420 * with its contents. spin isn't enough.
2422 static int
2423 flushbufqueues(struct buf *marker, bufq_type_t q)
2425 struct bufpcpu *pcpu;
2426 struct buf *bp;
2427 int r = 0;
2428 u_int loops = flushperqueue;
2429 int lcpu = marker->b_qcpu;
2431 KKASSERT(marker->b_qindex == BQUEUE_NONE);
2432 KKASSERT(marker->b_flags & B_MARKER);
2434 again:
2436 * Spinlock needed to perform operations on the queue and may be
2437 * held through a non-blocking BUF_LOCK(), but cannot be held when
2438 * BUF_UNLOCK()ing or through any other major operation.
2440 pcpu = &bufpcpu[marker->b_qcpu];
2441 spin_lock(&pcpu->spin);
2442 marker->b_qindex = q;
2443 TAILQ_INSERT_HEAD(&pcpu->bufqueues[q], marker, b_freelist);
2444 bp = marker;
2446 while ((bp = TAILQ_NEXT(bp, b_freelist)) != NULL) {
2448 * NOTE: spinlock is always held at the top of the loop
2450 if (bp->b_flags & B_MARKER)
2451 continue;
2452 if ((bp->b_flags & B_DELWRI) == 0) {
2453 kprintf("Unexpected clean buffer %p\n", bp);
2454 continue;
2456 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
2457 continue;
2458 KKASSERT(bp->b_qcpu == marker->b_qcpu && bp->b_qindex == q);
2461 * Once the buffer is locked we will have no choice but to
2462 * unlock the spinlock around a later BUF_UNLOCK and re-set
2463 * bp = marker when looping. Move the marker now to make
2464 * things easier.
2466 TAILQ_REMOVE(&pcpu->bufqueues[q], marker, b_freelist);
2467 TAILQ_INSERT_AFTER(&pcpu->bufqueues[q], bp, marker, b_freelist);
2470 * Must recheck B_DELWRI after successfully locking
2471 * the buffer.
2473 if ((bp->b_flags & B_DELWRI) == 0) {
2474 spin_unlock(&pcpu->spin);
2475 BUF_UNLOCK(bp);
2476 spin_lock(&pcpu->spin);
2477 bp = marker;
2478 continue;
2482 * Remove the buffer from its queue. We still own the
2483 * spinlock here.
2485 _bremfree(bp);
2488 * Disposing of an invalid buffer counts as a flush op
2490 if (bp->b_flags & B_INVAL) {
2491 spin_unlock(&pcpu->spin);
2492 brelse(bp);
2493 goto doloop;
2497 * Release the spinlock for the more complex ops we
2498 * are now going to do.
2500 spin_unlock(&pcpu->spin);
2501 lwkt_yield();
2504 * This is a bit messy
2506 if (LIST_FIRST(&bp->b_dep) != NULL &&
2507 (bp->b_flags & B_DEFERRED) == 0 &&
2508 buf_countdeps(bp, 0)) {
2509 spin_lock(&pcpu->spin);
2510 TAILQ_INSERT_TAIL(&pcpu->bufqueues[q], bp, b_freelist);
2511 bp->b_qindex = q;
2512 bp->b_flags |= B_DEFERRED;
2513 spin_unlock(&pcpu->spin);
2514 BUF_UNLOCK(bp);
2515 spin_lock(&pcpu->spin);
2516 bp = marker;
2517 continue;
2521 * spinlock not held here.
2523 * If the buffer has a dependancy, buf_checkwrite() must
2524 * also return 0 for us to be able to initate the write.
2526 * If the buffer is flagged B_ERROR it may be requeued
2527 * over and over again, we try to avoid a live lock.
2529 if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
2530 brelse(bp);
2531 } else if (bp->b_flags & B_ERROR) {
2532 tsleep(bp, 0, "bioer", 1);
2533 bp->b_flags &= ~B_AGE;
2534 cluster_awrite(bp);
2535 } else {
2536 bp->b_flags |= B_AGE;
2537 cluster_awrite(bp);
2539 /* bp invalid but needs to be NULL-tested if we break out */
2540 doloop:
2541 spin_lock(&pcpu->spin);
2542 ++r;
2543 if (--loops == 0)
2544 break;
2545 bp = marker;
2547 /* bp is invalid here but can be NULL-tested to advance */
2549 TAILQ_REMOVE(&pcpu->bufqueues[q], marker, b_freelist);
2550 marker->b_qindex = BQUEUE_NONE;
2551 spin_unlock(&pcpu->spin);
2554 * Advance the marker to be fair.
2556 marker->b_qcpu = (marker->b_qcpu + 1) % ncpus;
2557 if (bp == NULL) {
2558 if (marker->b_qcpu != lcpu)
2559 goto again;
2562 return (r);
2566 * inmem:
2568 * Returns true if no I/O is needed to access the associated VM object.
2569 * This is like findblk except it also hunts around in the VM system for
2570 * the data.
2572 * Note that we ignore vm_page_free() races from interrupts against our
2573 * lookup, since if the caller is not protected our return value will not
2574 * be any more valid then otherwise once we exit the critical section.
2577 inmem(struct vnode *vp, off_t loffset)
2579 vm_object_t obj;
2580 vm_offset_t toff, tinc, size;
2581 vm_page_t m;
2582 int res = 1;
2584 if (findblk(vp, loffset, FINDBLK_TEST))
2585 return 1;
2586 if (vp->v_mount == NULL)
2587 return 0;
2588 if ((obj = vp->v_object) == NULL)
2589 return 0;
2591 size = PAGE_SIZE;
2592 if (size > vp->v_mount->mnt_stat.f_iosize)
2593 size = vp->v_mount->mnt_stat.f_iosize;
2595 vm_object_hold(obj);
2596 for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2597 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2598 if (m == NULL) {
2599 res = 0;
2600 break;
2602 tinc = size;
2603 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2604 tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2605 if (vm_page_is_valid(m,
2606 (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0) {
2607 res = 0;
2608 break;
2611 vm_object_drop(obj);
2612 return (res);
2616 * findblk:
2618 * Locate and return the specified buffer. Unless flagged otherwise,
2619 * a locked buffer will be returned if it exists or NULL if it does not.
2621 * findblk()'d buffers are still on the bufqueues and if you intend
2622 * to use your (locked NON-TEST) buffer you need to bremfree(bp)
2623 * and possibly do other stuff to it.
2625 * FINDBLK_TEST - Do not lock the buffer. The caller is responsible
2626 * for locking the buffer and ensuring that it remains
2627 * the desired buffer after locking.
2629 * FINDBLK_NBLOCK - Lock the buffer non-blocking. If we are unable
2630 * to acquire the lock we return NULL, even if the
2631 * buffer exists.
2633 * FINDBLK_REF - Returns the buffer ref'd, which prevents normal
2634 * reuse by getnewbuf() but does not prevent
2635 * disassociation (B_INVAL). Used to avoid deadlocks
2636 * against random (vp,loffset)s due to reassignment.
2638 * (0) - Lock the buffer blocking.
2640 struct buf *
2641 findblk(struct vnode *vp, off_t loffset, int flags)
2643 struct buf *bp;
2644 int lkflags;
2646 lkflags = LK_EXCLUSIVE;
2647 if (flags & FINDBLK_NBLOCK)
2648 lkflags |= LK_NOWAIT;
2650 for (;;) {
2652 * Lookup. Ref the buf while holding v_token to prevent
2653 * reuse (but does not prevent diassociation).
2655 lwkt_gettoken_shared(&vp->v_token);
2656 bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2657 if (bp == NULL) {
2658 lwkt_reltoken(&vp->v_token);
2659 return(NULL);
2661 bqhold(bp);
2662 lwkt_reltoken(&vp->v_token);
2665 * If testing only break and return bp, do not lock.
2667 if (flags & FINDBLK_TEST)
2668 break;
2671 * Lock the buffer, return an error if the lock fails.
2672 * (only FINDBLK_NBLOCK can cause the lock to fail).
2674 if (BUF_LOCK(bp, lkflags)) {
2675 atomic_subtract_int(&bp->b_refs, 1);
2676 /* bp = NULL; not needed */
2677 return(NULL);
2681 * Revalidate the locked buf before allowing it to be
2682 * returned.
2684 if (bp->b_vp == vp && bp->b_loffset == loffset)
2685 break;
2686 atomic_subtract_int(&bp->b_refs, 1);
2687 BUF_UNLOCK(bp);
2691 * Success
2693 if ((flags & FINDBLK_REF) == 0)
2694 atomic_subtract_int(&bp->b_refs, 1);
2695 return(bp);
2699 * getcacheblk:
2701 * Similar to getblk() except only returns the buffer if it is
2702 * B_CACHE and requires no other manipulation. Otherwise NULL
2703 * is returned. NULL is also returned if GETBLK_NOWAIT is set
2704 * and the getblk() would block.
2706 * If B_RAM is set the buffer might be just fine, but we return
2707 * NULL anyway because we want the code to fall through to the
2708 * cluster read to issue more read-aheads. Otherwise read-ahead breaks.
2710 * If blksize is 0 the buffer cache buffer must already be fully
2711 * cached.
2713 * If blksize is non-zero getblk() will be used, allowing a buffer
2714 * to be reinstantiated from its VM backing store. The buffer must
2715 * still be fully cached after reinstantiation to be returned.
2717 struct buf *
2718 getcacheblk(struct vnode *vp, off_t loffset, int blksize, int blkflags)
2720 struct buf *bp;
2721 int fndflags = (blkflags & GETBLK_NOWAIT) ? FINDBLK_NBLOCK : 0;
2723 if (blksize) {
2724 bp = getblk(vp, loffset, blksize, blkflags, 0);
2725 if (bp) {
2726 if ((bp->b_flags & (B_INVAL | B_CACHE)) == B_CACHE) {
2727 bp->b_flags &= ~B_AGE;
2728 if (bp->b_flags & B_RAM) {
2729 bqrelse(bp);
2730 bp = NULL;
2732 } else {
2733 brelse(bp);
2734 bp = NULL;
2737 } else {
2738 bp = findblk(vp, loffset, fndflags);
2739 if (bp) {
2740 if ((bp->b_flags & (B_INVAL | B_CACHE | B_RAM)) ==
2741 B_CACHE) {
2742 bp->b_flags &= ~B_AGE;
2743 bremfree(bp);
2744 } else {
2745 BUF_UNLOCK(bp);
2746 bp = NULL;
2750 return (bp);
2754 * getblk:
2756 * Get a block given a specified block and offset into a file/device.
2757 * B_INVAL may or may not be set on return. The caller should clear
2758 * B_INVAL prior to initiating a READ.
2760 * IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2761 * IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2762 * OR SET B_INVAL BEFORE RETIRING IT. If you retire a getblk'd buffer
2763 * without doing any of those things the system will likely believe
2764 * the buffer to be valid (especially if it is not B_VMIO), and the
2765 * next getblk() will return the buffer with B_CACHE set.
2767 * For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2768 * an existing buffer.
2770 * For a VMIO buffer, B_CACHE is modified according to the backing VM.
2771 * If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2772 * and then cleared based on the backing VM. If the previous buffer is
2773 * non-0-sized but invalid, B_CACHE will be cleared.
2775 * If getblk() must create a new buffer, the new buffer is returned with
2776 * both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2777 * case it is returned with B_INVAL clear and B_CACHE set based on the
2778 * backing VM.
2780 * getblk() also forces a bwrite() for any B_DELWRI buffer whos
2781 * B_CACHE bit is clear.
2783 * What this means, basically, is that the caller should use B_CACHE to
2784 * determine whether the buffer is fully valid or not and should clear
2785 * B_INVAL prior to issuing a read. If the caller intends to validate
2786 * the buffer by loading its data area with something, the caller needs
2787 * to clear B_INVAL. If the caller does this without issuing an I/O,
2788 * the caller should set B_CACHE ( as an optimization ), else the caller
2789 * should issue the I/O and biodone() will set B_CACHE if the I/O was
2790 * a write attempt or if it was a successfull read. If the caller
2791 * intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2792 * prior to issuing the READ. biodone() will *not* clear B_INVAL.
2794 * getblk flags:
2796 * GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2797 * GETBLK_BHEAVY - heavy-weight buffer cache buffer
2799 struct buf *
2800 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2802 struct buf *bp;
2803 int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2804 int error;
2805 int lkflags;
2807 if (size > MAXBSIZE)
2808 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2809 if (vp->v_object == NULL)
2810 panic("getblk: vnode %p has no object!", vp);
2812 loop:
2813 if ((bp = findblk(vp, loffset, FINDBLK_REF | FINDBLK_TEST)) != NULL) {
2815 * The buffer was found in the cache, but we need to lock it.
2816 * We must acquire a ref on the bp to prevent reuse, but
2817 * this will not prevent disassociation (brelvp()) so we
2818 * must recheck (vp,loffset) after acquiring the lock.
2820 * Without the ref the buffer could potentially be reused
2821 * before we acquire the lock and create a deadlock
2822 * situation between the thread trying to reuse the buffer
2823 * and us due to the fact that we would wind up blocking
2824 * on a random (vp,loffset).
2826 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2827 if (blkflags & GETBLK_NOWAIT) {
2828 bqdrop(bp);
2829 return(NULL);
2831 lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2832 if (blkflags & GETBLK_PCATCH)
2833 lkflags |= LK_PCATCH;
2834 error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2835 if (error) {
2836 bqdrop(bp);
2837 if (error == ENOLCK)
2838 goto loop;
2839 return (NULL);
2841 /* buffer may have changed on us */
2843 bqdrop(bp);
2846 * Once the buffer has been locked, make sure we didn't race
2847 * a buffer recyclement. Buffers that are no longer hashed
2848 * will have b_vp == NULL, so this takes care of that check
2849 * as well.
2851 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2852 #if 0
2853 kprintf("Warning buffer %p (vp %p loffset %lld) "
2854 "was recycled\n",
2855 bp, vp, (long long)loffset);
2856 #endif
2857 BUF_UNLOCK(bp);
2858 goto loop;
2862 * If SZMATCH any pre-existing buffer must be of the requested
2863 * size or NULL is returned. The caller absolutely does not
2864 * want getblk() to bwrite() the buffer on a size mismatch.
2866 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2867 BUF_UNLOCK(bp);
2868 return(NULL);
2872 * All vnode-based buffers must be backed by a VM object.
2874 KKASSERT(bp->b_flags & B_VMIO);
2875 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2876 bp->b_flags &= ~B_AGE;
2879 * Make sure that B_INVAL buffers do not have a cached
2880 * block number translation.
2882 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2883 kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2884 " did not have cleared bio_offset cache\n",
2885 bp, vp, (long long)loffset);
2886 clearbiocache(&bp->b_bio2);
2890 * The buffer is locked. B_CACHE is cleared if the buffer is
2891 * invalid.
2893 if (bp->b_flags & B_INVAL)
2894 bp->b_flags &= ~B_CACHE;
2895 bremfree(bp);
2898 * Any size inconsistancy with a dirty buffer or a buffer
2899 * with a softupdates dependancy must be resolved. Resizing
2900 * the buffer in such circumstances can lead to problems.
2902 * Dirty or dependant buffers are written synchronously.
2903 * Other types of buffers are simply released and
2904 * reconstituted as they may be backed by valid, dirty VM
2905 * pages (but not marked B_DELWRI).
2907 * NFS NOTE: NFS buffers which straddle EOF are oddly-sized
2908 * and may be left over from a prior truncation (and thus
2909 * no longer represent the actual EOF point), so we
2910 * definitely do not want to B_NOCACHE the backing store.
2912 if (size != bp->b_bcount) {
2913 if (bp->b_flags & B_DELWRI) {
2914 bp->b_flags |= B_RELBUF;
2915 bwrite(bp);
2916 } else if (LIST_FIRST(&bp->b_dep)) {
2917 bp->b_flags |= B_RELBUF;
2918 bwrite(bp);
2919 } else {
2920 bp->b_flags |= B_RELBUF;
2921 brelse(bp);
2923 goto loop;
2925 KKASSERT(size <= bp->b_kvasize);
2926 KASSERT(bp->b_loffset != NOOFFSET,
2927 ("getblk: no buffer offset"));
2930 * A buffer with B_DELWRI set and B_CACHE clear must
2931 * be committed before we can return the buffer in
2932 * order to prevent the caller from issuing a read
2933 * ( due to B_CACHE not being set ) and overwriting
2934 * it.
2936 * Most callers, including NFS and FFS, need this to
2937 * operate properly either because they assume they
2938 * can issue a read if B_CACHE is not set, or because
2939 * ( for example ) an uncached B_DELWRI might loop due
2940 * to softupdates re-dirtying the buffer. In the latter
2941 * case, B_CACHE is set after the first write completes,
2942 * preventing further loops.
2944 * NOTE! b*write() sets B_CACHE. If we cleared B_CACHE
2945 * above while extending the buffer, we cannot allow the
2946 * buffer to remain with B_CACHE set after the write
2947 * completes or it will represent a corrupt state. To
2948 * deal with this we set B_NOCACHE to scrap the buffer
2949 * after the write.
2951 * XXX Should this be B_RELBUF instead of B_NOCACHE?
2952 * I'm not even sure this state is still possible
2953 * now that getblk() writes out any dirty buffers
2954 * on size changes.
2956 * We might be able to do something fancy, like setting
2957 * B_CACHE in bwrite() except if B_DELWRI is already set,
2958 * so the below call doesn't set B_CACHE, but that gets real
2959 * confusing. This is much easier.
2962 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2963 kprintf("getblk: Warning, bp %p loff=%jx DELWRI set "
2964 "and CACHE clear, b_flags %08x\n",
2965 bp, (uintmax_t)bp->b_loffset, bp->b_flags);
2966 bp->b_flags |= B_NOCACHE;
2967 bwrite(bp);
2968 goto loop;
2970 } else {
2972 * Buffer is not in-core, create new buffer. The buffer
2973 * returned by getnewbuf() is locked. Note that the returned
2974 * buffer is also considered valid (not marked B_INVAL).
2976 * Calculating the offset for the I/O requires figuring out
2977 * the block size. We use DEV_BSIZE for VBLK or VCHR and
2978 * the mount's f_iosize otherwise. If the vnode does not
2979 * have an associated mount we assume that the passed size is
2980 * the block size.
2982 * Note that vn_isdisk() cannot be used here since it may
2983 * return a failure for numerous reasons. Note that the
2984 * buffer size may be larger then the block size (the caller
2985 * will use block numbers with the proper multiple). Beware
2986 * of using any v_* fields which are part of unions. In
2987 * particular, in DragonFly the mount point overloading
2988 * mechanism uses the namecache only and the underlying
2989 * directory vnode is not a special case.
2991 int bsize, maxsize;
2992 vm_object_t repurpose;
2994 if (vp->v_type == VBLK || vp->v_type == VCHR)
2995 bsize = DEV_BSIZE;
2996 else if (vp->v_mount)
2997 bsize = vp->v_mount->mnt_stat.f_iosize;
2998 else
2999 bsize = size;
3001 maxsize = size + (loffset & PAGE_MASK);
3002 maxsize = imax(maxsize, bsize);
3003 repurpose = NULL;
3006 * Allow repurposing. The returned buffer may contain VM
3007 * pages associated with its previous incarnation. These
3008 * pages must be repurposed for the new buffer (hopefully
3009 * without disturbing the KVM mapping).
3011 * WARNING! If repurpose != NULL on return, the buffer will
3012 * still contain some data from its prior
3013 * incarnation. We MUST properly dispose of this
3014 * data.
3016 bp = getnewbuf(blkflags, slptimeo, size, maxsize, &repurpose);
3017 if (bp == NULL) {
3018 if (slpflags || slptimeo)
3019 return NULL;
3020 goto loop;
3024 * Atomically insert the buffer into the hash, so that it can
3025 * be found by findblk().
3027 * If bgetvp() returns non-zero a collision occured, and the
3028 * bp will not be associated with the vnode.
3030 * Make sure the translation layer has been cleared.
3032 bp->b_loffset = loffset;
3033 bp->b_bio2.bio_offset = NOOFFSET;
3034 /* bp->b_bio2.bio_next = NULL; */
3036 if (bgetvp(vp, bp, size)) {
3037 if (repurpose) {
3038 bp->b_flags |= B_VMIO;
3039 repurposebuf(bp, 0);
3040 vm_object_drop(repurpose);
3042 bp->b_flags |= B_INVAL;
3043 brelse(bp);
3044 goto loop;
3048 * All vnode-based buffers must be backed by a VM object.
3050 KKASSERT(vp->v_object != NULL);
3051 bp->b_flags |= B_VMIO;
3052 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3055 * If we allowed repurposing of the buffer it will contain
3056 * free-but-held vm_page's, already kmapped, that can be
3057 * repurposed. The repurposebuf() code handles reassigning
3058 * those pages to the new (object, offsets) and dealing with
3059 * the case where the pages already exist.
3061 if (repurpose) {
3062 repurposebuf(bp, size);
3063 vm_object_drop(repurpose);
3064 } else {
3065 allocbuf(bp, size);
3068 return (bp);
3072 * regetblk(bp)
3074 * Reacquire a buffer that was previously released to the locked queue,
3075 * or reacquire a buffer which is interlocked by having bioops->io_deallocate
3076 * set B_LOCKED (which handles the acquisition race).
3078 * To this end, either B_LOCKED must be set or the dependancy list must be
3079 * non-empty.
3081 void
3082 regetblk(struct buf *bp)
3084 KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
3085 BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
3086 bremfree(bp);
3090 * geteblk:
3092 * Get an empty, disassociated buffer of given size. The buffer is
3093 * initially set to B_INVAL.
3095 * critical section protection is not required for the allocbuf()
3096 * call because races are impossible here.
3098 struct buf *
3099 geteblk(int size)
3101 struct buf *bp;
3103 while ((bp = getnewbuf(0, 0, size, MAXBSIZE, NULL)) == NULL)
3105 allocbuf(bp, size);
3106 bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
3108 return (bp);
3112 * allocbuf:
3114 * This code constitutes the buffer memory from either anonymous system
3115 * memory (in the case of non-VMIO operations) or from an associated
3116 * VM object (in the case of VMIO operations). This code is able to
3117 * resize a buffer up or down.
3119 * Note that this code is tricky, and has many complications to resolve
3120 * deadlock or inconsistant data situations. Tread lightly!!!
3121 * There are B_CACHE and B_DELWRI interactions that must be dealt with by
3122 * the caller. Calling this code willy nilly can result in the loss of
3123 * data.
3125 * allocbuf() only adjusts B_CACHE for VMIO buffers. getblk() deals with
3126 * B_CACHE for the non-VMIO case.
3128 * This routine does not need to be called from a critical section but you
3129 * must own the buffer.
3131 void
3132 allocbuf(struct buf *bp, int size)
3134 int newbsize, mbsize;
3135 int i;
3137 if (BUF_REFCNT(bp) == 0)
3138 panic("allocbuf: buffer not busy");
3140 if (bp->b_kvasize < size)
3141 panic("allocbuf: buffer too small");
3143 if ((bp->b_flags & B_VMIO) == 0) {
3144 caddr_t origbuf;
3145 int origbufsize;
3147 * Just get anonymous memory from the kernel. Don't
3148 * mess with B_CACHE.
3150 mbsize = roundup2(size, DEV_BSIZE);
3151 if (bp->b_flags & B_MALLOC)
3152 newbsize = mbsize;
3153 else
3154 newbsize = round_page(size);
3156 if (newbsize < bp->b_bufsize) {
3158 * Malloced buffers are not shrunk
3160 if (bp->b_flags & B_MALLOC) {
3161 if (newbsize) {
3162 bp->b_bcount = size;
3163 } else {
3164 kfree(bp->b_data, M_BIOBUF);
3165 if (bp->b_bufsize) {
3166 atomic_subtract_long(&bufmallocspace, bp->b_bufsize);
3167 bp->b_bufsize = 0;
3168 bufspacewakeup();
3170 bp->b_data = bp->b_kvabase;
3171 bp->b_bcount = 0;
3172 bp->b_flags &= ~B_MALLOC;
3174 return;
3176 vm_hold_free_pages(
3178 (vm_offset_t) bp->b_data + newbsize,
3179 (vm_offset_t) bp->b_data + bp->b_bufsize);
3180 } else if (newbsize > bp->b_bufsize) {
3182 * We only use malloced memory on the first allocation.
3183 * and revert to page-allocated memory when the buffer
3184 * grows.
3186 if ((bufmallocspace < maxbufmallocspace) &&
3187 (bp->b_bufsize == 0) &&
3188 (mbsize <= PAGE_SIZE/2)) {
3190 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
3191 bp->b_bufsize = mbsize;
3192 bp->b_bcount = size;
3193 bp->b_flags |= B_MALLOC;
3194 atomic_add_long(&bufmallocspace, mbsize);
3195 return;
3197 origbuf = NULL;
3198 origbufsize = 0;
3200 * If the buffer is growing on its other-than-first
3201 * allocation, then we revert to the page-allocation
3202 * scheme.
3204 if (bp->b_flags & B_MALLOC) {
3205 origbuf = bp->b_data;
3206 origbufsize = bp->b_bufsize;
3207 bp->b_data = bp->b_kvabase;
3208 if (bp->b_bufsize) {
3209 atomic_subtract_long(&bufmallocspace,
3210 bp->b_bufsize);
3211 bp->b_bufsize = 0;
3212 bufspacewakeup();
3214 bp->b_flags &= ~B_MALLOC;
3215 newbsize = round_page(newbsize);
3217 vm_hold_load_pages(
3219 (vm_offset_t) bp->b_data + bp->b_bufsize,
3220 (vm_offset_t) bp->b_data + newbsize);
3221 if (origbuf) {
3222 bcopy(origbuf, bp->b_data, origbufsize);
3223 kfree(origbuf, M_BIOBUF);
3226 } else {
3227 vm_page_t m;
3228 int desiredpages;
3230 newbsize = roundup2(size, DEV_BSIZE);
3231 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3232 newbsize + PAGE_MASK) >> PAGE_SHIFT;
3233 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
3235 if (bp->b_flags & B_MALLOC)
3236 panic("allocbuf: VMIO buffer can't be malloced");
3238 * Set B_CACHE initially if buffer is 0 length or will become
3239 * 0-length.
3241 if (size == 0 || bp->b_bufsize == 0)
3242 bp->b_flags |= B_CACHE;
3244 if (newbsize < bp->b_bufsize) {
3246 * DEV_BSIZE aligned new buffer size is less then the
3247 * DEV_BSIZE aligned existing buffer size. Figure out
3248 * if we have to remove any pages.
3250 if (desiredpages < bp->b_xio.xio_npages) {
3251 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
3253 * the page is not freed here -- it
3254 * is the responsibility of
3255 * vnode_pager_setsize
3257 m = bp->b_xio.xio_pages[i];
3258 KASSERT(m != bogus_page,
3259 ("allocbuf: bogus page found"));
3260 vm_page_busy_wait(m, TRUE, "biodep");
3261 bp->b_xio.xio_pages[i] = NULL;
3262 vm_page_unwire(m, 0);
3263 vm_page_wakeup(m);
3265 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
3266 (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
3267 bp->b_xio.xio_npages = desiredpages;
3269 } else if (size > bp->b_bcount) {
3271 * We are growing the buffer, possibly in a
3272 * byte-granular fashion.
3274 struct vnode *vp;
3275 vm_object_t obj;
3276 vm_offset_t toff;
3277 vm_offset_t tinc;
3280 * Step 1, bring in the VM pages from the object,
3281 * allocating them if necessary. We must clear
3282 * B_CACHE if these pages are not valid for the
3283 * range covered by the buffer.
3285 vp = bp->b_vp;
3286 obj = vp->v_object;
3288 vm_object_hold(obj);
3289 while (bp->b_xio.xio_npages < desiredpages) {
3290 vm_page_t m;
3291 vm_pindex_t pi;
3292 int error;
3294 pi = OFF_TO_IDX(bp->b_loffset) +
3295 bp->b_xio.xio_npages;
3298 * Blocking on m->busy might lead to a
3299 * deadlock:
3301 * vm_fault->getpages->cluster_read->allocbuf
3303 m = vm_page_lookup_busy_try(obj, pi, FALSE,
3304 &error);
3305 if (error) {
3306 vm_page_sleep_busy(m, FALSE, "pgtblk");
3307 continue;
3309 if (m == NULL) {
3311 * note: must allocate system pages
3312 * since blocking here could intefere
3313 * with paging I/O, no matter which
3314 * process we are.
3316 m = bio_page_alloc(bp, obj, pi, desiredpages - bp->b_xio.xio_npages);
3317 if (m) {
3318 vm_page_wire(m);
3319 vm_page_flag_clear(m, PG_ZERO);
3320 vm_page_wakeup(m);
3321 bp->b_flags &= ~B_CACHE;
3322 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3323 ++bp->b_xio.xio_npages;
3325 continue;
3329 * We found a page and were able to busy it.
3331 vm_page_flag_clear(m, PG_ZERO);
3332 vm_page_wire(m);
3333 vm_page_wakeup(m);
3334 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3335 ++bp->b_xio.xio_npages;
3336 if (bp->b_act_count < m->act_count)
3337 bp->b_act_count = m->act_count;
3339 vm_object_drop(obj);
3342 * Step 2. We've loaded the pages into the buffer,
3343 * we have to figure out if we can still have B_CACHE
3344 * set. Note that B_CACHE is set according to the
3345 * byte-granular range ( bcount and size ), not the
3346 * aligned range ( newbsize ).
3348 * The VM test is against m->valid, which is DEV_BSIZE
3349 * aligned. Needless to say, the validity of the data
3350 * needs to also be DEV_BSIZE aligned. Note that this
3351 * fails with NFS if the server or some other client
3352 * extends the file's EOF. If our buffer is resized,
3353 * B_CACHE may remain set! XXX
3356 toff = bp->b_bcount;
3357 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3359 while ((bp->b_flags & B_CACHE) && toff < size) {
3360 vm_pindex_t pi;
3362 if (tinc > (size - toff))
3363 tinc = size - toff;
3365 pi = ((bp->b_loffset & PAGE_MASK) + toff) >>
3366 PAGE_SHIFT;
3368 vfs_buf_test_cache(
3369 bp,
3370 bp->b_loffset,
3371 toff,
3372 tinc,
3373 bp->b_xio.xio_pages[pi]
3375 toff += tinc;
3376 tinc = PAGE_SIZE;
3380 * Step 3, fixup the KVM pmap. Remember that
3381 * bp->b_data is relative to bp->b_loffset, but
3382 * bp->b_loffset may be offset into the first page.
3384 bp->b_data = (caddr_t)
3385 trunc_page((vm_offset_t)bp->b_data);
3386 pmap_qenter((vm_offset_t)bp->b_data,
3387 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3388 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3389 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3391 atomic_add_long(&bufspace, newbsize - bp->b_bufsize);
3394 /* adjust space use on already-dirty buffer */
3395 if (bp->b_flags & B_DELWRI) {
3396 /* dirtykvaspace unchanged */
3397 atomic_add_long(&dirtybufspace, newbsize - bp->b_bufsize);
3398 if (bp->b_flags & B_HEAVY) {
3399 atomic_add_long(&dirtybufspacehw,
3400 newbsize - bp->b_bufsize);
3403 bp->b_bufsize = newbsize; /* actual buffer allocation */
3404 bp->b_bcount = size; /* requested buffer size */
3405 bufspacewakeup();
3409 * repurposebuf() (VMIO only)
3411 * This performs a function similar to allocbuf() but the passed-in buffer
3412 * may contain some detrius from its previous incarnation in the form of
3413 * the page array. We try to repurpose the underlying pages.
3415 * This code is nominally called to recycle buffer cache buffers AND (if
3416 * they are clean) to also recycle their underlying pages. We currently
3417 * can only recycle unmapped, clean pages. The code is called when buffer
3418 * cache 'newbuf' bandwidth exceeds (bufrate_cache) bytes per second.
3420 static
3421 void
3422 repurposebuf(struct buf *bp, int size)
3424 int newbsize;
3425 int desiredpages;
3426 vm_offset_t toff;
3427 vm_offset_t tinc;
3428 vm_object_t obj;
3429 vm_page_t m;
3430 int i;
3431 int must_reenter = 0;
3432 long deaccumulate = 0;
3435 KKASSERT((bp->b_flags & (B_VMIO | B_DELWRI | B_MALLOC)) == B_VMIO);
3436 if (BUF_REFCNT(bp) == 0)
3437 panic("repurposebuf: buffer not busy");
3439 if (bp->b_kvasize < size)
3440 panic("repurposebuf: buffer too small");
3442 newbsize = roundup2(size, DEV_BSIZE);
3443 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
3444 newbsize + PAGE_MASK) >> PAGE_SHIFT;
3445 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
3448 * Buffer starts out 0-length with B_CACHE set. We will clear
3449 * As we check the backing store we will clear B_CACHE if necessary.
3451 atomic_add_long(&bufspace, newbsize - bp->b_bufsize);
3452 bp->b_bufsize = 0;
3453 bp->b_bcount = 0;
3454 bp->b_flags |= B_CACHE;
3456 if (desiredpages) {
3457 obj = bp->b_vp->v_object;
3458 vm_object_hold(obj);
3459 } else {
3460 obj = NULL;
3464 * Step 1, bring in the VM pages from the object, repurposing or
3465 * allocating them if necessary. We must clear B_CACHE if these
3466 * pages are not valid for the range covered by the buffer.
3468 * We are growing the buffer, possibly in a byte-granular fashion.
3470 for (i = 0; i < desiredpages; ++i) {
3471 vm_pindex_t pi;
3472 int error;
3473 int iswired;
3475 pi = OFF_TO_IDX(bp->b_loffset) + i;
3478 * Blocking on m->busy might lead to a
3479 * deadlock:
3481 * vm_fault->getpages->cluster_read->allocbuf
3483 m = (i < bp->b_xio.xio_npages) ? bp->b_xio.xio_pages[i] : NULL;
3484 bp->b_xio.xio_pages[i] = NULL;
3485 KASSERT(m != bogus_page, ("repurposebuf: bogus page found"));
3486 m = vm_page_repurpose(obj, pi, FALSE, &error, m,
3487 &must_reenter, &iswired);
3489 if (error) {
3490 vm_page_sleep_busy(m, FALSE, "pgtblk");
3491 --i; /* retry */
3492 continue;
3494 if (m == NULL) {
3496 * note: must allocate system pages
3497 * since blocking here could intefere
3498 * with paging I/O, no matter which
3499 * process we are.
3501 must_reenter = 1;
3502 m = bio_page_alloc(bp, obj, pi, desiredpages - i);
3503 if (m) {
3504 vm_page_wire(m);
3505 vm_page_flag_clear(m, PG_ZERO);
3506 vm_page_wakeup(m);
3507 bp->b_flags &= ~B_CACHE;
3508 bp->b_xio.xio_pages[i] = m;
3509 if (m->valid)
3510 deaccumulate += PAGE_SIZE;
3511 } else {
3512 --i; /* retry */
3514 continue;
3516 if (m->valid)
3517 deaccumulate += PAGE_SIZE;
3520 * We found a page and were able to busy it.
3522 vm_page_flag_clear(m, PG_ZERO);
3523 if (!iswired)
3524 vm_page_wire(m);
3525 vm_page_wakeup(m);
3526 bp->b_xio.xio_pages[i] = m;
3527 if (bp->b_act_count < m->act_count)
3528 bp->b_act_count = m->act_count;
3530 if (desiredpages)
3531 vm_object_drop(obj);
3534 * Even though its a new buffer, any pages already in the VM
3535 * page cache should not count towards I/O bandwidth.
3537 if (deaccumulate)
3538 atomic_add_long(&bufcache_bw_accum, -deaccumulate);
3541 * Clean-up any loose pages.
3543 while (i < bp->b_xio.xio_npages) {
3544 m = bp->b_xio.xio_pages[i];
3545 KASSERT(m != bogus_page, ("repurposebuf: bogus page found"));
3546 vm_page_busy_wait(m, TRUE, "biodep");
3547 bp->b_xio.xio_pages[i] = NULL;
3548 vm_page_unwire(m, 0);
3549 vm_page_wakeup(m);
3550 ++i;
3552 if (desiredpages < bp->b_xio.xio_npages) {
3553 pmap_qremove((vm_offset_t)trunc_page((vm_offset_t)bp->b_data) +
3554 (desiredpages << PAGE_SHIFT),
3555 (bp->b_xio.xio_npages - desiredpages));
3557 bp->b_xio.xio_npages = desiredpages;
3560 * Step 2. We've loaded the pages into the buffer,
3561 * we have to figure out if we can still have B_CACHE
3562 * set. Note that B_CACHE is set according to the
3563 * byte-granular range ( bcount and size ), not the
3564 * aligned range ( newbsize ).
3566 * The VM test is against m->valid, which is DEV_BSIZE
3567 * aligned. Needless to say, the validity of the data
3568 * needs to also be DEV_BSIZE aligned. Note that this
3569 * fails with NFS if the server or some other client
3570 * extends the file's EOF. If our buffer is resized,
3571 * B_CACHE may remain set! XXX
3573 toff = bp->b_bcount;
3574 tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3576 while ((bp->b_flags & B_CACHE) && toff < size) {
3577 vm_pindex_t pi;
3579 if (tinc > (size - toff))
3580 tinc = size - toff;
3582 pi = ((bp->b_loffset & PAGE_MASK) + toff) >> PAGE_SHIFT;
3584 vfs_buf_test_cache(bp, bp->b_loffset, toff,
3585 tinc, bp->b_xio.xio_pages[pi]);
3586 toff += tinc;
3587 tinc = PAGE_SIZE;
3591 * Step 3, fixup the KVM pmap. Remember that
3592 * bp->b_data is relative to bp->b_loffset, but
3593 * bp->b_loffset may be offset into the first page.
3595 bp->b_data = (caddr_t)trunc_page((vm_offset_t)bp->b_data);
3596 if (must_reenter) {
3597 pmap_qenter((vm_offset_t)bp->b_data,
3598 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3599 } else {
3600 atomic_add_long(&repurposedspace, newbsize);
3602 bp->b_data = (caddr_t)((vm_offset_t)bp->b_data |
3603 (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3605 if (newbsize < bp->b_bufsize)
3606 bufspacewakeup();
3607 bp->b_bufsize = newbsize; /* actual buffer allocation */
3608 bp->b_bcount = size; /* requested buffer size */
3612 * biowait:
3614 * Wait for buffer I/O completion, returning error status. B_EINTR
3615 * is converted into an EINTR error but not cleared (since a chain
3616 * of biowait() calls may occur).
3618 * On return bpdone() will have been called but the buffer will remain
3619 * locked and will not have been brelse()'d.
3621 * NOTE! If a timeout is specified and ETIMEDOUT occurs the I/O is
3622 * likely still in progress on return.
3624 * NOTE! This operation is on a BIO, not a BUF.
3626 * NOTE! BIO_DONE is cleared by vn_strategy()
3628 static __inline int
3629 _biowait(struct bio *bio, const char *wmesg, int to)
3631 struct buf *bp = bio->bio_buf;
3632 u_int32_t flags;
3633 u_int32_t nflags;
3634 int error;
3636 KKASSERT(bio == &bp->b_bio1);
3637 for (;;) {
3638 flags = bio->bio_flags;
3639 if (flags & BIO_DONE)
3640 break;
3641 nflags = flags | BIO_WANT;
3642 tsleep_interlock(bio, 0);
3643 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
3644 if (wmesg)
3645 error = tsleep(bio, PINTERLOCKED, wmesg, to);
3646 else if (bp->b_cmd == BUF_CMD_READ)
3647 error = tsleep(bio, PINTERLOCKED, "biord", to);
3648 else
3649 error = tsleep(bio, PINTERLOCKED, "biowr", to);
3650 if (error) {
3651 kprintf("tsleep error biowait %d\n", error);
3652 return (error);
3658 * Finish up.
3660 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
3661 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
3662 if (bp->b_flags & B_EINTR)
3663 return (EINTR);
3664 if (bp->b_flags & B_ERROR)
3665 return (bp->b_error ? bp->b_error : EIO);
3666 return (0);
3670 biowait(struct bio *bio, const char *wmesg)
3672 return(_biowait(bio, wmesg, 0));
3676 biowait_timeout(struct bio *bio, const char *wmesg, int to)
3678 return(_biowait(bio, wmesg, to));
3682 * This associates a tracking count with an I/O. vn_strategy() and
3683 * dev_dstrategy() do this automatically but there are a few cases
3684 * where a vnode or device layer is bypassed when a block translation
3685 * is cached. In such cases bio_start_transaction() may be called on
3686 * the bypassed layers so the system gets an I/O in progress indication
3687 * for those higher layers.
3689 void
3690 bio_start_transaction(struct bio *bio, struct bio_track *track)
3692 bio->bio_track = track;
3693 bio_track_ref(track);
3694 dsched_buf_enter(bio->bio_buf); /* might stack */
3698 * Initiate I/O on a vnode.
3700 * SWAPCACHE OPERATION:
3702 * Real buffer cache buffers have a non-NULL bp->b_vp. Unfortunately
3703 * devfs also uses b_vp for fake buffers so we also have to check
3704 * that B_PAGING is 0. In this case the passed 'vp' is probably the
3705 * underlying block device. The swap assignments are related to the
3706 * buffer cache buffer's b_vp, not the passed vp.
3708 * The passed vp == bp->b_vp only in the case where the strategy call
3709 * is made on the vp itself for its own buffers (a regular file or
3710 * block device vp). The filesystem usually then re-calls vn_strategy()
3711 * after translating the request to an underlying device.
3713 * Cluster buffers set B_CLUSTER and the passed vp is the vp of the
3714 * underlying buffer cache buffers.
3716 * We can only deal with page-aligned buffers at the moment, because
3717 * we can't tell what the real dirty state for pages straddling a buffer
3718 * are.
3720 * In order to call swap_pager_strategy() we must provide the VM object
3721 * and base offset for the underlying buffer cache pages so it can find
3722 * the swap blocks.
3724 void
3725 vn_strategy(struct vnode *vp, struct bio *bio)
3727 struct bio_track *track;
3728 struct buf *bp = bio->bio_buf;
3730 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3733 * Set when an I/O is issued on the bp. Cleared by consumers
3734 * (aka HAMMER), allowing the consumer to determine if I/O had
3735 * actually occurred.
3737 bp->b_flags |= B_IOISSUED;
3740 * Handle the swap cache intercept.
3742 if (vn_cache_strategy(vp, bio))
3743 return;
3746 * Otherwise do the operation through the filesystem
3748 if (bp->b_cmd == BUF_CMD_READ)
3749 track = &vp->v_track_read;
3750 else
3751 track = &vp->v_track_write;
3752 KKASSERT((bio->bio_flags & BIO_DONE) == 0);
3753 bio->bio_track = track;
3754 bio_track_ref(track);
3755 dsched_buf_enter(bp); /* might stack */
3756 vop_strategy(*vp->v_ops, vp, bio);
3759 static void vn_cache_strategy_callback(struct bio *bio);
3762 vn_cache_strategy(struct vnode *vp, struct bio *bio)
3764 struct buf *bp = bio->bio_buf;
3765 struct bio *nbio;
3766 vm_object_t object;
3767 vm_page_t m;
3768 int i;
3771 * Stop using swapcache if paniced, dumping, or dumped
3773 if (panicstr || dumping)
3774 return(0);
3777 * Is this buffer cache buffer suitable for reading from
3778 * the swap cache?
3780 if (vm_swapcache_read_enable == 0 ||
3781 bp->b_cmd != BUF_CMD_READ ||
3782 ((bp->b_flags & B_CLUSTER) == 0 &&
3783 (bp->b_vp == NULL || (bp->b_flags & B_PAGING))) ||
3784 ((int)bp->b_loffset & PAGE_MASK) != 0 ||
3785 (bp->b_bcount & PAGE_MASK) != 0) {
3786 return(0);
3790 * Figure out the original VM object (it will match the underlying
3791 * VM pages). Note that swap cached data uses page indices relative
3792 * to that object, not relative to bio->bio_offset.
3794 if (bp->b_flags & B_CLUSTER)
3795 object = vp->v_object;
3796 else
3797 object = bp->b_vp->v_object;
3800 * In order to be able to use the swap cache all underlying VM
3801 * pages must be marked as such, and we can't have any bogus pages.
3803 for (i = 0; i < bp->b_xio.xio_npages; ++i) {
3804 m = bp->b_xio.xio_pages[i];
3805 if ((m->flags & PG_SWAPPED) == 0)
3806 break;
3807 if (m == bogus_page)
3808 break;
3812 * If we are good then issue the I/O using swap_pager_strategy().
3814 * We can only do this if the buffer actually supports object-backed
3815 * I/O. If it doesn't npages will be 0.
3817 if (i && i == bp->b_xio.xio_npages) {
3818 m = bp->b_xio.xio_pages[0];
3819 nbio = push_bio(bio);
3820 nbio->bio_done = vn_cache_strategy_callback;
3821 nbio->bio_offset = ptoa(m->pindex);
3822 KKASSERT(m->object == object);
3823 swap_pager_strategy(object, nbio);
3824 return(1);
3826 return(0);
3830 * This is a bit of a hack but since the vn_cache_strategy() function can
3831 * override a VFS's strategy function we must make sure that the bio, which
3832 * is probably bio2, doesn't leak an unexpected offset value back to the
3833 * filesystem. The filesystem (e.g. UFS) might otherwise assume that the
3834 * bio went through its own file strategy function and the the bio2 offset
3835 * is a cached disk offset when, in fact, it isn't.
3837 static void
3838 vn_cache_strategy_callback(struct bio *bio)
3840 bio->bio_offset = NOOFFSET;
3841 biodone(pop_bio(bio));
3845 * bpdone:
3847 * Finish I/O on a buffer after all BIOs have been processed.
3848 * Called when the bio chain is exhausted or by biowait. If called
3849 * by biowait, elseit is typically 0.
3851 * bpdone is also responsible for setting B_CACHE in a B_VMIO bp.
3852 * In a non-VMIO bp, B_CACHE will be set on the next getblk()
3853 * assuming B_INVAL is clear.
3855 * For the VMIO case, we set B_CACHE if the op was a read and no
3856 * read error occured, or if the op was a write. B_CACHE is never
3857 * set if the buffer is invalid or otherwise uncacheable.
3859 * bpdone does not mess with B_INVAL, allowing the I/O routine or the
3860 * initiator to leave B_INVAL set to brelse the buffer out of existance
3861 * in the biodone routine.
3863 * bpdone is responsible for calling bundirty() on the buffer after a
3864 * successful write. We previously did this prior to initiating the
3865 * write under the assumption that the buffer might be dirtied again
3866 * while the write was in progress, however doing it before-hand creates
3867 * a race condition prior to the call to vn_strategy() where the
3868 * filesystem may not be aware that a dirty buffer is present.
3869 * It should not be possible for the buffer or its underlying pages to
3870 * be redirtied prior to bpdone()'s unbusying of the underlying VM
3871 * pages.
3873 void
3874 bpdone(struct buf *bp, int elseit)
3876 buf_cmd_t cmd;
3878 KASSERT(BUF_REFCNTNB(bp) > 0,
3879 ("bpdone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3880 KASSERT(bp->b_cmd != BUF_CMD_DONE,
3881 ("bpdone: bp %p already done!", bp));
3884 * No more BIOs are left. All completion functions have been dealt
3885 * with, now we clean up the buffer.
3887 cmd = bp->b_cmd;
3888 bp->b_cmd = BUF_CMD_DONE;
3891 * Only reads and writes are processed past this point.
3893 if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3894 if (cmd == BUF_CMD_FREEBLKS)
3895 bp->b_flags |= B_NOCACHE;
3896 if (elseit)
3897 brelse(bp);
3898 return;
3902 * A failed write must re-dirty the buffer unless B_INVAL
3903 * was set.
3905 * A successful write must clear the dirty flag. This is done after
3906 * the write to ensure that the buffer remains on the vnode's dirty
3907 * list for filesystem interlocks / checks until the write is actually
3908 * complete. HAMMER2 is sensitive to this issue.
3910 * Only applicable to normal buffers (with VPs). vinum buffers may
3911 * not have a vp.
3913 * Must be done prior to calling buf_complete() as the callback might
3914 * re-dirty the buffer.
3916 if (cmd == BUF_CMD_WRITE) {
3917 if ((bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
3918 bp->b_flags &= ~B_NOCACHE;
3919 if (bp->b_vp)
3920 bdirty(bp);
3921 } else {
3922 if (bp->b_vp)
3923 bundirty(bp);
3928 * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3929 * a lot worse. XXX - move this above the clearing of b_cmd
3931 if (LIST_FIRST(&bp->b_dep) != NULL)
3932 buf_complete(bp);
3934 if (bp->b_flags & B_VMIO) {
3935 int i;
3936 vm_ooffset_t foff;
3937 vm_page_t m;
3938 vm_object_t obj;
3939 int iosize;
3940 struct vnode *vp = bp->b_vp;
3942 obj = vp->v_object;
3944 #if defined(VFS_BIO_DEBUG)
3945 if (vp->v_auxrefs == 0)
3946 panic("bpdone: zero vnode hold count");
3947 if ((vp->v_flag & VOBJBUF) == 0)
3948 panic("bpdone: vnode is not setup for merged cache");
3949 #endif
3951 foff = bp->b_loffset;
3952 KASSERT(foff != NOOFFSET, ("bpdone: no buffer offset"));
3953 KASSERT(obj != NULL, ("bpdone: missing VM object"));
3955 #if defined(VFS_BIO_DEBUG)
3956 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3957 kprintf("bpdone: paging in progress(%d) < "
3958 "bp->b_xio.xio_npages(%d)\n",
3959 obj->paging_in_progress,
3960 bp->b_xio.xio_npages);
3962 #endif
3965 * Set B_CACHE if the op was a normal read and no error
3966 * occured. B_CACHE is set for writes in the b*write()
3967 * routines.
3969 iosize = bp->b_bcount - bp->b_resid;
3970 if (cmd == BUF_CMD_READ &&
3971 (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3972 bp->b_flags |= B_CACHE;
3975 vm_object_hold(obj);
3976 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3977 int bogusflag = 0;
3978 int resid;
3980 resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3981 if (resid > iosize)
3982 resid = iosize;
3985 * cleanup bogus pages, restoring the originals. Since
3986 * the originals should still be wired, we don't have
3987 * to worry about interrupt/freeing races destroying
3988 * the VM object association.
3990 m = bp->b_xio.xio_pages[i];
3991 if (m == bogus_page) {
3992 bogusflag = 1;
3993 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3994 if (m == NULL)
3995 panic("bpdone: page disappeared");
3996 bp->b_xio.xio_pages[i] = m;
3997 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3998 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
4000 #if defined(VFS_BIO_DEBUG)
4001 if (OFF_TO_IDX(foff) != m->pindex) {
4002 kprintf("bpdone: foff(%lu)/m->pindex(%ld) "
4003 "mismatch\n",
4004 (unsigned long)foff, (long)m->pindex);
4006 #endif
4009 * In the write case, the valid and clean bits are
4010 * already changed correctly (see bdwrite()), so we
4011 * only need to do this here in the read case.
4013 vm_page_busy_wait(m, FALSE, "bpdpgw");
4014 if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
4015 vfs_clean_one_page(bp, i, m);
4017 vm_page_flag_clear(m, PG_ZERO);
4020 * when debugging new filesystems or buffer I/O
4021 * methods, this is the most common error that pops
4022 * up. if you see this, you have not set the page
4023 * busy flag correctly!!!
4025 if (m->busy == 0) {
4026 kprintf("bpdone: page busy < 0, "
4027 "pindex: %d, foff: 0x(%x,%x), "
4028 "resid: %d, index: %d\n",
4029 (int) m->pindex, (int)(foff >> 32),
4030 (int) foff & 0xffffffff, resid, i);
4031 if (!vn_isdisk(vp, NULL))
4032 kprintf(" iosize: %ld, loffset: %lld, "
4033 "flags: 0x%08x, npages: %d\n",
4034 bp->b_vp->v_mount->mnt_stat.f_iosize,
4035 (long long)bp->b_loffset,
4036 bp->b_flags, bp->b_xio.xio_npages);
4037 else
4038 kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
4039 (long long)bp->b_loffset,
4040 bp->b_flags, bp->b_xio.xio_npages);
4041 kprintf(" valid: 0x%x, dirty: 0x%x, "
4042 "wired: %d\n",
4043 m->valid, m->dirty,
4044 m->wire_count);
4045 panic("bpdone: page busy < 0");
4047 vm_page_io_finish(m);
4048 vm_page_wakeup(m);
4049 vm_object_pip_wakeup(obj);
4050 foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
4051 iosize -= resid;
4053 bp->b_flags &= ~B_HASBOGUS;
4054 vm_object_drop(obj);
4058 * Finish up by releasing the buffer. There are no more synchronous
4059 * or asynchronous completions, those were handled by bio_done
4060 * callbacks.
4062 if (elseit) {
4063 if (bp->b_flags & (B_NOCACHE|B_INVAL|B_ERROR|B_RELBUF))
4064 brelse(bp);
4065 else
4066 bqrelse(bp);
4071 * Normal biodone.
4073 void
4074 biodone(struct bio *bio)
4076 struct buf *bp = bio->bio_buf;
4078 runningbufwakeup(bp);
4081 * Run up the chain of BIO's. Leave b_cmd intact for the duration.
4083 while (bio) {
4084 biodone_t *done_func;
4085 struct bio_track *track;
4088 * BIO tracking. Most but not all BIOs are tracked.
4090 if ((track = bio->bio_track) != NULL) {
4091 bio_track_rel(track);
4092 bio->bio_track = NULL;
4096 * A bio_done function terminates the loop. The function
4097 * will be responsible for any further chaining and/or
4098 * buffer management.
4100 * WARNING! The done function can deallocate the buffer!
4102 if ((done_func = bio->bio_done) != NULL) {
4103 bio->bio_done = NULL;
4104 done_func(bio);
4105 return;
4107 bio = bio->bio_prev;
4111 * If we've run out of bio's do normal [a]synchronous completion.
4113 bpdone(bp, 1);
4117 * Synchronous biodone - this terminates a synchronous BIO.
4119 * bpdone() is called with elseit=FALSE, leaving the buffer completed
4120 * but still locked. The caller must brelse() the buffer after waiting
4121 * for completion.
4123 void
4124 biodone_sync(struct bio *bio)
4126 struct buf *bp = bio->bio_buf;
4127 int flags;
4128 int nflags;
4130 KKASSERT(bio == &bp->b_bio1);
4131 bpdone(bp, 0);
4133 for (;;) {
4134 flags = bio->bio_flags;
4135 nflags = (flags | BIO_DONE) & ~BIO_WANT;
4137 if (atomic_cmpset_int(&bio->bio_flags, flags, nflags)) {
4138 if (flags & BIO_WANT)
4139 wakeup(bio);
4140 break;
4146 * vfs_unbusy_pages:
4148 * This routine is called in lieu of iodone in the case of
4149 * incomplete I/O. This keeps the busy status for pages
4150 * consistant.
4152 void
4153 vfs_unbusy_pages(struct buf *bp)
4155 int i;
4157 runningbufwakeup(bp);
4159 if (bp->b_flags & B_VMIO) {
4160 struct vnode *vp = bp->b_vp;
4161 vm_object_t obj;
4163 obj = vp->v_object;
4164 vm_object_hold(obj);
4166 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4167 vm_page_t m = bp->b_xio.xio_pages[i];
4170 * When restoring bogus changes the original pages
4171 * should still be wired, so we are in no danger of
4172 * losing the object association and do not need
4173 * critical section protection particularly.
4175 if (m == bogus_page) {
4176 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
4177 if (!m) {
4178 panic("vfs_unbusy_pages: page missing");
4180 bp->b_xio.xio_pages[i] = m;
4181 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4182 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
4184 vm_page_busy_wait(m, FALSE, "bpdpgw");
4185 vm_page_flag_clear(m, PG_ZERO);
4186 vm_page_io_finish(m);
4187 vm_page_wakeup(m);
4188 vm_object_pip_wakeup(obj);
4190 bp->b_flags &= ~B_HASBOGUS;
4191 vm_object_drop(obj);
4196 * vfs_busy_pages:
4198 * This routine is called before a device strategy routine.
4199 * It is used to tell the VM system that paging I/O is in
4200 * progress, and treat the pages associated with the buffer
4201 * almost as being PG_BUSY. Also the object 'paging_in_progress'
4202 * flag is handled to make sure that the object doesn't become
4203 * inconsistant.
4205 * Since I/O has not been initiated yet, certain buffer flags
4206 * such as B_ERROR or B_INVAL may be in an inconsistant state
4207 * and should be ignored.
4209 void
4210 vfs_busy_pages(struct vnode *vp, struct buf *bp)
4212 int i, bogus;
4213 struct lwp *lp = curthread->td_lwp;
4216 * The buffer's I/O command must already be set. If reading,
4217 * B_CACHE must be 0 (double check against callers only doing
4218 * I/O when B_CACHE is 0).
4220 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4221 KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
4223 if (bp->b_flags & B_VMIO) {
4224 vm_object_t obj;
4226 obj = vp->v_object;
4227 KASSERT(bp->b_loffset != NOOFFSET,
4228 ("vfs_busy_pages: no buffer offset"));
4231 * Busy all the pages. We have to busy them all at once
4232 * to avoid deadlocks.
4234 retry:
4235 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4236 vm_page_t m = bp->b_xio.xio_pages[i];
4238 if (vm_page_busy_try(m, FALSE)) {
4239 vm_page_sleep_busy(m, FALSE, "vbpage");
4240 while (--i >= 0)
4241 vm_page_wakeup(bp->b_xio.xio_pages[i]);
4242 goto retry;
4247 * Setup for I/O, soft-busy the page right now because
4248 * the next loop may block.
4250 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4251 vm_page_t m = bp->b_xio.xio_pages[i];
4253 vm_page_flag_clear(m, PG_ZERO);
4254 if ((bp->b_flags & B_CLUSTER) == 0) {
4255 vm_object_pip_add(obj, 1);
4256 vm_page_io_start(m);
4261 * Adjust protections for I/O and do bogus-page mapping.
4262 * Assume that vm_page_protect() can block (it can block
4263 * if VM_PROT_NONE, don't take any chances regardless).
4265 * In particular note that for writes we must incorporate
4266 * page dirtyness from the VM system into the buffer's
4267 * dirty range.
4269 * For reads we theoretically must incorporate page dirtyness
4270 * from the VM system to determine if the page needs bogus
4271 * replacement, but we shortcut the test by simply checking
4272 * that all m->valid bits are set, indicating that the page
4273 * is fully valid and does not need to be re-read. For any
4274 * VM system dirtyness the page will also be fully valid
4275 * since it was mapped at one point.
4277 bogus = 0;
4278 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4279 vm_page_t m = bp->b_xio.xio_pages[i];
4281 vm_page_flag_clear(m, PG_ZERO); /* XXX */
4282 if (bp->b_cmd == BUF_CMD_WRITE) {
4284 * When readying a vnode-backed buffer for
4285 * a write we must zero-fill any invalid
4286 * portions of the backing VM pages, mark
4287 * it valid and clear related dirty bits.
4289 * vfs_clean_one_page() incorporates any
4290 * VM dirtyness and updates the b_dirtyoff
4291 * range (after we've made the page RO).
4293 * It is also expected that the pmap modified
4294 * bit has already been cleared by the
4295 * vm_page_protect(). We may not be able
4296 * to clear all dirty bits for a page if it
4297 * was also memory mapped (NFS).
4299 * Finally be sure to unassign any swap-cache
4300 * backing store as it is now stale.
4302 vm_page_protect(m, VM_PROT_READ);
4303 vfs_clean_one_page(bp, i, m);
4304 swap_pager_unswapped(m);
4305 } else if (m->valid == VM_PAGE_BITS_ALL) {
4307 * When readying a vnode-backed buffer for
4308 * read we must replace any dirty pages with
4309 * a bogus page so dirty data is not destroyed
4310 * when filling gaps.
4312 * To avoid testing whether the page is
4313 * dirty we instead test that the page was
4314 * at some point mapped (m->valid fully
4315 * valid) with the understanding that
4316 * this also covers the dirty case.
4318 bp->b_xio.xio_pages[i] = bogus_page;
4319 bp->b_flags |= B_HASBOGUS;
4320 bogus++;
4321 } else if (m->valid & m->dirty) {
4323 * This case should not occur as partial
4324 * dirtyment can only happen if the buffer
4325 * is B_CACHE, and this code is not entered
4326 * if the buffer is B_CACHE.
4328 kprintf("Warning: vfs_busy_pages - page not "
4329 "fully valid! loff=%jx bpf=%08x "
4330 "idx=%d val=%02x dir=%02x\n",
4331 (uintmax_t)bp->b_loffset, bp->b_flags,
4332 i, m->valid, m->dirty);
4333 vm_page_protect(m, VM_PROT_NONE);
4334 } else {
4336 * The page is not valid and can be made
4337 * part of the read.
4339 vm_page_protect(m, VM_PROT_NONE);
4341 vm_page_wakeup(m);
4343 if (bogus) {
4344 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
4345 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
4350 * This is the easiest place to put the process accounting for the I/O
4351 * for now.
4353 if (lp != NULL) {
4354 if (bp->b_cmd == BUF_CMD_READ)
4355 lp->lwp_ru.ru_inblock++;
4356 else
4357 lp->lwp_ru.ru_oublock++;
4362 * Tell the VM system that the pages associated with this buffer
4363 * are clean. This is used for delayed writes where the data is
4364 * going to go to disk eventually without additional VM intevention.
4366 * NOTE: While we only really need to clean through to b_bcount, we
4367 * just go ahead and clean through to b_bufsize.
4369 static void
4370 vfs_clean_pages(struct buf *bp)
4372 vm_page_t m;
4373 int i;
4375 if ((bp->b_flags & B_VMIO) == 0)
4376 return;
4378 KASSERT(bp->b_loffset != NOOFFSET,
4379 ("vfs_clean_pages: no buffer offset"));
4381 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4382 m = bp->b_xio.xio_pages[i];
4383 vfs_clean_one_page(bp, i, m);
4388 * vfs_clean_one_page:
4390 * Set the valid bits and clear the dirty bits in a page within a
4391 * buffer. The range is restricted to the buffer's size and the
4392 * buffer's logical offset might index into the first page.
4394 * The caller has busied or soft-busied the page and it is not mapped,
4395 * test and incorporate the dirty bits into b_dirtyoff/end before
4396 * clearing them. Note that we need to clear the pmap modified bits
4397 * after determining the the page was dirty, vm_page_set_validclean()
4398 * does not do it for us.
4400 * This routine is typically called after a read completes (dirty should
4401 * be zero in that case as we are not called on bogus-replace pages),
4402 * or before a write is initiated.
4404 static void
4405 vfs_clean_one_page(struct buf *bp, int pageno, vm_page_t m)
4407 int bcount;
4408 int xoff;
4409 int soff;
4410 int eoff;
4413 * Calculate offset range within the page but relative to buffer's
4414 * loffset. loffset might be offset into the first page.
4416 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
4417 bcount = bp->b_bcount + xoff; /* offset adjusted */
4419 if (pageno == 0) {
4420 soff = xoff;
4421 eoff = PAGE_SIZE;
4422 } else {
4423 soff = (pageno << PAGE_SHIFT);
4424 eoff = soff + PAGE_SIZE;
4426 if (eoff > bcount)
4427 eoff = bcount;
4428 if (soff >= eoff)
4429 return;
4432 * Test dirty bits and adjust b_dirtyoff/end.
4434 * If dirty pages are incorporated into the bp any prior
4435 * B_NEEDCOMMIT state (NFS) must be cleared because the
4436 * caller has not taken into account the new dirty data.
4438 * If the page was memory mapped the dirty bits might go beyond the
4439 * end of the buffer, but we can't really make the assumption that
4440 * a file EOF straddles the buffer (even though this is the case for
4441 * NFS if B_NEEDCOMMIT is also set). So for the purposes of clearing
4442 * B_NEEDCOMMIT we only test the dirty bits covered by the buffer.
4443 * This also saves some console spam.
4445 * When clearing B_NEEDCOMMIT we must also clear B_CLUSTEROK,
4446 * NFS can handle huge commits but not huge writes.
4448 vm_page_test_dirty(m);
4449 if (m->dirty) {
4450 if ((bp->b_flags & B_NEEDCOMMIT) &&
4451 (m->dirty & vm_page_bits(soff & PAGE_MASK, eoff - soff))) {
4452 if (debug_commit)
4453 kprintf("Warning: vfs_clean_one_page: bp %p "
4454 "loff=%jx,%d flgs=%08x clr B_NEEDCOMMIT"
4455 " cmd %d vd %02x/%02x x/s/e %d %d %d "
4456 "doff/end %d %d\n",
4457 bp, (uintmax_t)bp->b_loffset, bp->b_bcount,
4458 bp->b_flags, bp->b_cmd,
4459 m->valid, m->dirty, xoff, soff, eoff,
4460 bp->b_dirtyoff, bp->b_dirtyend);
4461 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
4462 if (debug_commit)
4463 print_backtrace(-1);
4466 * Only clear the pmap modified bits if ALL the dirty bits
4467 * are set, otherwise the system might mis-clear portions
4468 * of a page.
4470 if (m->dirty == VM_PAGE_BITS_ALL &&
4471 (bp->b_flags & B_NEEDCOMMIT) == 0) {
4472 pmap_clear_modify(m);
4474 if (bp->b_dirtyoff > soff - xoff)
4475 bp->b_dirtyoff = soff - xoff;
4476 if (bp->b_dirtyend < eoff - xoff)
4477 bp->b_dirtyend = eoff - xoff;
4481 * Set related valid bits, clear related dirty bits.
4482 * Does not mess with the pmap modified bit.
4484 * WARNING! We cannot just clear all of m->dirty here as the
4485 * buffer cache buffers may use a DEV_BSIZE'd aligned
4486 * block size, or have an odd size (e.g. NFS at file EOF).
4487 * The putpages code can clear m->dirty to 0.
4489 * If a VOP_WRITE generates a buffer cache buffer which
4490 * covers the same space as mapped writable pages the
4491 * buffer flush might not be able to clear all the dirty
4492 * bits and still require a putpages from the VM system
4493 * to finish it off.
4495 * WARNING! vm_page_set_validclean() currently assumes vm_token
4496 * is held. The page might not be busied (bdwrite() case).
4497 * XXX remove this comment once we've validated that this
4498 * is no longer an issue.
4500 vm_page_set_validclean(m, soff & PAGE_MASK, eoff - soff);
4503 #if 0
4505 * Similar to vfs_clean_one_page() but sets the bits to valid and dirty.
4506 * The page data is assumed to be valid (there is no zeroing here).
4508 static void
4509 vfs_dirty_one_page(struct buf *bp, int pageno, vm_page_t m)
4511 int bcount;
4512 int xoff;
4513 int soff;
4514 int eoff;
4517 * Calculate offset range within the page but relative to buffer's
4518 * loffset. loffset might be offset into the first page.
4520 xoff = (int)bp->b_loffset & PAGE_MASK; /* loffset offset into pg 0 */
4521 bcount = bp->b_bcount + xoff; /* offset adjusted */
4523 if (pageno == 0) {
4524 soff = xoff;
4525 eoff = PAGE_SIZE;
4526 } else {
4527 soff = (pageno << PAGE_SHIFT);
4528 eoff = soff + PAGE_SIZE;
4530 if (eoff > bcount)
4531 eoff = bcount;
4532 if (soff >= eoff)
4533 return;
4534 vm_page_set_validdirty(m, soff & PAGE_MASK, eoff - soff);
4536 #endif
4539 * vfs_bio_clrbuf:
4541 * Clear a buffer. This routine essentially fakes an I/O, so we need
4542 * to clear B_ERROR and B_INVAL.
4544 * Note that while we only theoretically need to clear through b_bcount,
4545 * we go ahead and clear through b_bufsize.
4548 void
4549 vfs_bio_clrbuf(struct buf *bp)
4551 int i, mask = 0;
4552 caddr_t sa, ea;
4553 if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
4554 bp->b_flags &= ~(B_INVAL | B_EINTR | B_ERROR);
4555 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
4556 (bp->b_loffset & PAGE_MASK) == 0) {
4557 mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
4558 if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
4559 bp->b_resid = 0;
4560 return;
4562 if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
4563 ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
4564 bzero(bp->b_data, bp->b_bufsize);
4565 bp->b_xio.xio_pages[0]->valid |= mask;
4566 bp->b_resid = 0;
4567 return;
4570 sa = bp->b_data;
4571 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
4572 int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
4573 ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
4574 ea = (caddr_t)(vm_offset_t)ulmin(
4575 (u_long)(vm_offset_t)ea,
4576 (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
4577 mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
4578 if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
4579 continue;
4580 if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
4581 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
4582 bzero(sa, ea - sa);
4584 } else {
4585 for (; sa < ea; sa += DEV_BSIZE, j++) {
4586 if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
4587 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
4588 bzero(sa, DEV_BSIZE);
4591 bp->b_xio.xio_pages[i]->valid |= mask;
4592 vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
4594 bp->b_resid = 0;
4595 } else {
4596 clrbuf(bp);
4601 * vm_hold_load_pages:
4603 * Load pages into the buffer's address space. The pages are
4604 * allocated from the kernel object in order to reduce interference
4605 * with the any VM paging I/O activity. The range of loaded
4606 * pages will be wired.
4608 * If a page cannot be allocated, the 'pagedaemon' is woken up to
4609 * retrieve the full range (to - from) of pages.
4611 void
4612 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4614 vm_offset_t pg;
4615 vm_page_t p;
4616 int index;
4618 to = round_page(to);
4619 from = round_page(from);
4620 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4622 pg = from;
4623 while (pg < to) {
4625 * Note: must allocate system pages since blocking here
4626 * could intefere with paging I/O, no matter which
4627 * process we are.
4629 vm_object_hold(&kernel_object);
4630 p = bio_page_alloc(bp, &kernel_object, pg >> PAGE_SHIFT,
4631 (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
4632 vm_object_drop(&kernel_object);
4633 if (p) {
4634 vm_page_wire(p);
4635 p->valid = VM_PAGE_BITS_ALL;
4636 vm_page_flag_clear(p, PG_ZERO);
4637 pmap_kenter_noinval(pg, VM_PAGE_TO_PHYS(p));
4638 bp->b_xio.xio_pages[index] = p;
4639 vm_page_wakeup(p);
4641 pg += PAGE_SIZE;
4642 ++index;
4645 pmap_invalidate_range(&kernel_pmap, from, to);
4646 bp->b_xio.xio_npages = index;
4650 * Allocate a page for a buffer cache buffer.
4652 * If NULL is returned the caller is expected to retry (typically check if
4653 * the page already exists on retry before trying to allocate one).
4655 * NOTE! Low-memory handling is dealt with in b[q]relse(), not here. This
4656 * function will use the system reserve with the hope that the page
4657 * allocations can be returned to PQ_CACHE/PQ_FREE when the caller
4658 * is done with the buffer.
4660 * NOTE! However, TMPFS is a special case because flushing a dirty buffer
4661 * to TMPFS doesn't clean the page. For TMPFS, only the pagedaemon
4662 * is capable of retiring pages (to swap). For TMPFS we don't dig
4663 * into the system reserve because doing so could stall out pretty
4664 * much every process running on the system.
4666 static
4667 vm_page_t
4668 bio_page_alloc(struct buf *bp, vm_object_t obj, vm_pindex_t pg, int deficit)
4670 int vmflags = VM_ALLOC_NORMAL | VM_ALLOC_NULL_OK;
4671 vm_page_t p;
4673 ASSERT_LWKT_TOKEN_HELD(vm_object_token(obj));
4676 * Try a normal allocation first.
4678 p = vm_page_alloc(obj, pg, vmflags);
4679 if (p)
4680 return(p);
4681 if (vm_page_lookup(obj, pg))
4682 return(NULL);
4683 vm_pageout_deficit += deficit;
4686 * Try again, digging into the system reserve.
4688 * Trying to recover pages from the buffer cache here can deadlock
4689 * against other threads trying to busy underlying pages so we
4690 * depend on the code in brelse() and bqrelse() to free/cache the
4691 * underlying buffer cache pages when memory is low.
4693 if (curthread->td_flags & TDF_SYSTHREAD)
4694 vmflags |= VM_ALLOC_SYSTEM | VM_ALLOC_INTERRUPT;
4695 else if (bp->b_vp && bp->b_vp->v_tag == VT_TMPFS)
4696 vmflags |= 0;
4697 else
4698 vmflags |= VM_ALLOC_SYSTEM;
4700 /*recoverbufpages();*/
4701 p = vm_page_alloc(obj, pg, vmflags);
4702 if (p)
4703 return(p);
4704 if (vm_page_lookup(obj, pg))
4705 return(NULL);
4708 * Wait for memory to free up and try again
4710 if (vm_page_count_severe())
4711 ++lowmempgallocs;
4712 vm_wait(hz / 20 + 1);
4714 p = vm_page_alloc(obj, pg, vmflags);
4715 if (p)
4716 return(p);
4717 if (vm_page_lookup(obj, pg))
4718 return(NULL);
4721 * Ok, now we are really in trouble.
4724 static struct krate biokrate = { .freq = 1 };
4725 krateprintf(&biokrate,
4726 "Warning: bio_page_alloc: memory exhausted "
4727 "during buffer cache page allocation from %s\n",
4728 curthread->td_comm);
4730 if (curthread->td_flags & TDF_SYSTHREAD)
4731 vm_wait(hz / 20 + 1);
4732 else
4733 vm_wait(hz / 2 + 1);
4734 return (NULL);
4738 * vm_hold_free_pages:
4740 * Return pages associated with the buffer back to the VM system.
4742 * The range of pages underlying the buffer's address space will
4743 * be unmapped and un-wired.
4745 void
4746 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
4748 vm_offset_t pg;
4749 vm_page_t p;
4750 int index, newnpages;
4752 from = round_page(from);
4753 to = round_page(to);
4754 index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
4755 newnpages = index;
4757 for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
4758 p = bp->b_xio.xio_pages[index];
4759 if (p && (index < bp->b_xio.xio_npages)) {
4760 if (p->busy) {
4761 kprintf("vm_hold_free_pages: doffset: %lld, "
4762 "loffset: %lld\n",
4763 (long long)bp->b_bio2.bio_offset,
4764 (long long)bp->b_loffset);
4766 bp->b_xio.xio_pages[index] = NULL;
4767 pmap_kremove_noinval(pg);
4768 vm_page_busy_wait(p, FALSE, "vmhldpg");
4769 vm_page_unwire(p, 0);
4770 vm_page_free(p);
4773 pmap_invalidate_range(&kernel_pmap, from, to);
4774 bp->b_xio.xio_npages = newnpages;
4778 * vmapbuf:
4780 * Map a user buffer into KVM via a pbuf. On return the buffer's
4781 * b_data, b_bufsize, and b_bcount will be set, and its XIO page array
4782 * initialized.
4785 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
4787 caddr_t addr;
4788 vm_offset_t va;
4789 vm_page_t m;
4790 int vmprot;
4791 int error;
4792 int pidx;
4793 int i;
4796 * bp had better have a command and it better be a pbuf.
4798 KKASSERT(bp->b_cmd != BUF_CMD_DONE);
4799 KKASSERT(bp->b_flags & B_PAGING);
4800 KKASSERT(bp->b_kvabase);
4802 if (bytes < 0)
4803 return (-1);
4806 * Map the user data into KVM. Mappings have to be page-aligned.
4808 addr = (caddr_t)trunc_page((vm_offset_t)udata);
4809 pidx = 0;
4811 vmprot = VM_PROT_READ;
4812 if (bp->b_cmd == BUF_CMD_READ)
4813 vmprot |= VM_PROT_WRITE;
4815 while (addr < udata + bytes) {
4817 * Do the vm_fault if needed; do the copy-on-write thing
4818 * when reading stuff off device into memory.
4820 * vm_fault_page*() returns a held VM page.
4822 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
4823 va = trunc_page(va);
4825 m = vm_fault_page_quick(va, vmprot, &error);
4826 if (m == NULL) {
4827 for (i = 0; i < pidx; ++i) {
4828 vm_page_unhold(bp->b_xio.xio_pages[i]);
4829 bp->b_xio.xio_pages[i] = NULL;
4831 return(-1);
4833 bp->b_xio.xio_pages[pidx] = m;
4834 addr += PAGE_SIZE;
4835 ++pidx;
4839 * Map the page array and set the buffer fields to point to
4840 * the mapped data buffer.
4842 if (pidx > btoc(MAXPHYS))
4843 panic("vmapbuf: mapped more than MAXPHYS");
4844 pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
4846 bp->b_xio.xio_npages = pidx;
4847 bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
4848 bp->b_bcount = bytes;
4849 bp->b_bufsize = bytes;
4851 return(0);
4855 * vunmapbuf:
4857 * Free the io map PTEs associated with this IO operation.
4858 * We also invalidate the TLB entries and restore the original b_addr.
4860 void
4861 vunmapbuf(struct buf *bp)
4863 int pidx;
4864 int npages;
4866 KKASSERT(bp->b_flags & B_PAGING);
4868 npages = bp->b_xio.xio_npages;
4869 pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
4870 for (pidx = 0; pidx < npages; ++pidx) {
4871 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
4872 bp->b_xio.xio_pages[pidx] = NULL;
4874 bp->b_xio.xio_npages = 0;
4875 bp->b_data = bp->b_kvabase;
4879 * Scan all buffers in the system and issue the callback.
4882 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
4884 int count = 0;
4885 int error;
4886 long n;
4888 for (n = 0; n < nbuf; ++n) {
4889 if ((error = callback(&buf[n], info)) < 0) {
4890 count = error;
4891 break;
4893 count += error;
4895 return (count);
4899 * nestiobuf_iodone: biodone callback for nested buffers and propagate
4900 * completion to the master buffer.
4902 static void
4903 nestiobuf_iodone(struct bio *bio)
4905 struct bio *mbio;
4906 struct buf *mbp, *bp;
4907 struct devstat *stats;
4908 int error;
4909 int donebytes;
4911 bp = bio->bio_buf;
4912 mbio = bio->bio_caller_info1.ptr;
4913 stats = bio->bio_caller_info2.ptr;
4914 mbp = mbio->bio_buf;
4916 KKASSERT(bp->b_bcount <= bp->b_bufsize);
4917 KKASSERT(mbp != bp);
4919 error = bp->b_error;
4920 if (bp->b_error == 0 &&
4921 (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) {
4923 * Not all got transfered, raise an error. We have no way to
4924 * propagate these conditions to mbp.
4926 error = EIO;
4929 donebytes = bp->b_bufsize;
4931 relpbuf(bp, NULL);
4933 nestiobuf_done(mbio, donebytes, error, stats);
4936 void
4937 nestiobuf_done(struct bio *mbio, int donebytes, int error, struct devstat *stats)
4939 struct buf *mbp;
4941 mbp = mbio->bio_buf;
4943 KKASSERT((int)(intptr_t)mbio->bio_driver_info > 0);
4946 * If an error occured, propagate it to the master buffer.
4948 * Several biodone()s may wind up running concurrently so
4949 * use an atomic op to adjust b_flags.
4951 if (error) {
4952 mbp->b_error = error;
4953 atomic_set_int(&mbp->b_flags, B_ERROR);
4957 * Decrement the operations in progress counter and terminate the
4958 * I/O if this was the last bit.
4960 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4961 mbp->b_resid = 0;
4962 if (stats)
4963 devstat_end_transaction_buf(stats, mbp);
4964 biodone(mbio);
4969 * Initialize a nestiobuf for use. Set an initial count of 1 to prevent
4970 * the mbio from being biodone()'d while we are still adding sub-bios to
4971 * it.
4973 void
4974 nestiobuf_init(struct bio *bio)
4976 bio->bio_driver_info = (void *)1;
4980 * The BIOs added to the nestedio have already been started, remove the
4981 * count that placeheld our mbio and biodone() it if the count would
4982 * transition to 0.
4984 void
4985 nestiobuf_start(struct bio *mbio)
4987 struct buf *mbp = mbio->bio_buf;
4990 * Decrement the operations in progress counter and terminate the
4991 * I/O if this was the last bit.
4993 if (atomic_fetchadd_int((int *)&mbio->bio_driver_info, -1) == 1) {
4994 if (mbp->b_flags & B_ERROR)
4995 mbp->b_resid = mbp->b_bcount;
4996 else
4997 mbp->b_resid = 0;
4998 biodone(mbio);
5003 * Set an intermediate error prior to calling nestiobuf_start()
5005 void
5006 nestiobuf_error(struct bio *mbio, int error)
5008 struct buf *mbp = mbio->bio_buf;
5010 if (error) {
5011 mbp->b_error = error;
5012 atomic_set_int(&mbp->b_flags, B_ERROR);
5017 * nestiobuf_add: setup a "nested" buffer.
5019 * => 'mbp' is a "master" buffer which is being divided into sub pieces.
5020 * => 'bp' should be a buffer allocated by getiobuf.
5021 * => 'offset' is a byte offset in the master buffer.
5022 * => 'size' is a size in bytes of this nested buffer.
5024 void
5025 nestiobuf_add(struct bio *mbio, struct buf *bp, int offset, size_t size, struct devstat *stats)
5027 struct buf *mbp = mbio->bio_buf;
5028 struct vnode *vp = mbp->b_vp;
5030 KKASSERT(mbp->b_bcount >= offset + size);
5032 atomic_add_int((int *)&mbio->bio_driver_info, 1);
5034 /* kernel needs to own the lock for it to be released in biodone */
5035 BUF_KERNPROC(bp);
5036 bp->b_vp = vp;
5037 bp->b_cmd = mbp->b_cmd;
5038 bp->b_bio1.bio_done = nestiobuf_iodone;
5039 bp->b_data = (char *)mbp->b_data + offset;
5040 bp->b_resid = bp->b_bcount = size;
5041 bp->b_bufsize = bp->b_bcount;
5043 bp->b_bio1.bio_track = NULL;
5044 bp->b_bio1.bio_caller_info1.ptr = mbio;
5045 bp->b_bio1.bio_caller_info2.ptr = stats;
5048 #ifdef DDB
5050 DB_SHOW_COMMAND(buffer, db_show_buffer)
5052 /* get args */
5053 struct buf *bp = (struct buf *)addr;
5055 if (!have_addr) {
5056 db_printf("usage: show buffer <addr>\n");
5057 return;
5060 db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
5061 db_printf("b_cmd = %d\n", bp->b_cmd);
5062 db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
5063 "b_resid = %d\n, b_data = %p, "
5064 "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
5065 bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
5066 bp->b_data,
5067 (long long)bp->b_bio2.bio_offset,
5068 (long long)(bp->b_bio2.bio_next ?
5069 bp->b_bio2.bio_next->bio_offset : (off_t)-1));
5070 if (bp->b_xio.xio_npages) {
5071 int i;
5072 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
5073 bp->b_xio.xio_npages);
5074 for (i = 0; i < bp->b_xio.xio_npages; i++) {
5075 vm_page_t m;
5076 m = bp->b_xio.xio_pages[i];
5077 db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
5078 (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
5079 if ((i + 1) < bp->b_xio.xio_npages)
5080 db_printf(",");
5082 db_printf("\n");
5085 #endif /* DDB */