vfs_bio.c revision 1.114 1 /* $NetBSD: vfs_bio.c,v 1.114 2004/01/30 11:32:16 tls Exp $ */
2
3 /*-
4 * Copyright (c) 1982, 1986, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
37 */
38
39 /*-
40 * Copyright (c) 1994 Christopher G. Demetriou
41 *
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement:
52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission.
57 *
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
69 *
70 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
71 */
72
73 /*
74 * Some references:
75 * Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
76 * Leffler, et al.: The Design and Implementation of the 4.3BSD
77 * UNIX Operating System (Addison Welley, 1989)
78 */
79
80 #include "opt_bufcache.h"
81 #include "opt_softdep.h"
82
83 #include <sys/cdefs.h>
84 __KERNEL_RCSID(0, "$NetBSD: vfs_bio.c,v 1.114 2004/01/30 11:32:16 tls Exp $");
85
86 #include <sys/param.h>
87 #include <sys/systm.h>
88 #include <sys/kernel.h>
89 #include <sys/proc.h>
90 #include <sys/buf.h>
91 #include <sys/vnode.h>
92 #include <sys/mount.h>
93 #include <sys/malloc.h>
94 #include <sys/resourcevar.h>
95 #include <sys/sysctl.h>
96 #include <sys/conf.h>
97
98 #include <uvm/uvm.h>
99
100 #include <miscfs/specfs/specdev.h>
101
102 #ifndef BUFPAGES
103 # define BUFPAGES 0
104 #endif
105
106 #ifdef BUFCACHE
107 # if (BUFCACHE < 5) || (BUFCACHE > 95)
108 # error BUFCACHE is not between 5 and 95
109 # endif
110 #else
111 # define BUFCACHE 15
112 #endif
113
114 u_int nbuf; /* XXX - for softdep_lockedbufs */
115 u_int bufpages = BUFPAGES; /* optional hardwired count */
116 u_int bufcache = BUFCACHE; /* max % of RAM to use for buffer cache */
117
118
119 /* Macros to clear/set/test flags. */
120 #define SET(t, f) (t) |= (f)
121 #define CLR(t, f) (t) &= ~(f)
122 #define ISSET(t, f) ((t) & (f))
123
124 /*
125 * Definitions for the buffer hash lists.
126 */
127 #define BUFHASH(dvp, lbn) \
128 (&bufhashtbl[(((long)(dvp) >> 8) + (int)(lbn)) & bufhash])
129 LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
130 u_long bufhash;
131 #ifndef SOFTDEP
132 struct bio_ops bioops; /* I/O operation notification */
133 #endif
134
135 /*
136 * Insq/Remq for the buffer hash lists.
137 */
138 #define binshash(bp, dp) LIST_INSERT_HEAD(dp, bp, b_hash)
139 #define bremhash(bp) LIST_REMOVE(bp, b_hash)
140
141 /*
142 * Definitions for the buffer free lists.
143 */
144 #define BQUEUES 3 /* number of free buffer queues */
145
146 #define BQ_LOCKED 0 /* super-blocks &c */
147 #define BQ_LRU 1 /* lru, useful buffers */
148 #define BQ_AGE 2 /* rubbish */
149
150 TAILQ_HEAD(bqueues, buf) bufqueues[BQUEUES];
151 int needbuffer;
152
153 /*
154 * Buffer queue lock.
155 * Take this lock first if also taking some buffer's b_interlock.
156 */
157 struct simplelock bqueue_slock = SIMPLELOCK_INITIALIZER;
158
159 /*
160 * Buffer pool for I/O buffers.
161 */
162 struct pool bufpool;
163
164 /* XXX - somewhat gross.. */
165 #if MAXBSIZE == 0x2000
166 #define NMEMPOOLS 4
167 #elif MAXBSIZE == 0x4000
168 #define NMEMPOOLS 5
169 #elif MAXBSIZE == 0x8000
170 #define NMEMPOOLS 6
171 #else
172 #define NMEMPOOLS 7
173 #endif
174
175 #define MEMPOOL_INDEX_OFFSET 10 /* smallest pool is 1k */
176 #if (1 << (NMEMPOOLS + MEMPOOL_INDEX_OFFSET - 1)) != MAXBSIZE
177 #error update vfs_bio buffer memory parameters
178 #endif
179
180 /* Buffer memory pools */
181 static struct pool bmempools[NMEMPOOLS];
182
183 struct vm_map *buf_map;
184
185 /*
186 * Buffer memory pool allocator.
187 */
188 static void *
189 bufpool_page_alloc(struct pool *pp, int flags)
190 {
191
192 return (void *)uvm_km_kmemalloc1(buf_map,
193 uvm.kernel_object, MAXBSIZE, MAXBSIZE, UVM_UNKNOWN_OFFSET,
194 (flags & PR_WAITOK) ? 0 : UVM_KMF_NOWAIT | UVM_KMF_TRYLOCK);
195 }
196
197 static void
198 bufpool_page_free(struct pool *pp, void *v)
199 {
200 uvm_km_free(buf_map, (vaddr_t)v, MAXBSIZE);
201 }
202
203 static struct pool_allocator bufmempool_allocator = {
204 bufpool_page_alloc, bufpool_page_free, MAXBSIZE,
205 };
206
207 /* Buffer memory management variables */
208 u_long bufmem_valimit;
209 u_long bufmem_hiwater;
210 u_long bufmem_lowater;
211 u_long bufmem;
212
213 /*
214 * MD code can call this to set a hard limit on the amount
215 * of virtual memory used by the buffer cache.
216 */
217 int
218 buf_setvalimit(vsize_t sz)
219 {
220
221 /* We need to accommodate at least NMEMPOOLS of MAXBSIZE each */
222 if (sz < NMEMPOOLS * MAXBSIZE)
223 return EINVAL;
224
225 bufmem_valimit = sz;
226 return 0;
227 }
228
229 static int buf_trim(void);
230
231 /*
232 * bread()/breadn() helper.
233 */
234 static __inline struct buf *bio_doread(struct vnode *, daddr_t, int,
235 struct ucred *, int);
236 int count_lock_queue(void);
237
238 /*
239 * Insq/Remq for the buffer free lists.
240 * Call with buffer queue locked.
241 */
242 #define binsheadfree(bp, dp) TAILQ_INSERT_HEAD(dp, bp, b_freelist)
243 #define binstailfree(bp, dp) TAILQ_INSERT_TAIL(dp, bp, b_freelist)
244
245 #ifdef DEBUG
246 int debug_verify_freelist = 0;
247 static int checkfreelist(struct buf *bp, struct bqueues *dp)
248 {
249 struct buf *b;
250 TAILQ_FOREACH(b, dp, b_freelist) {
251 if (b == bp)
252 return 1;
253 }
254 return 0;
255 }
256 #endif
257
258 void
259 bremfree(struct buf *bp)
260 {
261 struct bqueues *dp = NULL;
262
263 LOCK_ASSERT(simple_lock_held(&bqueue_slock));
264
265 KDASSERT(!debug_verify_freelist ||
266 checkfreelist(bp, &bufqueues[BQ_AGE]) ||
267 checkfreelist(bp, &bufqueues[BQ_LRU]) ||
268 checkfreelist(bp, &bufqueues[BQ_LOCKED]) );
269
270 /*
271 * We only calculate the head of the freelist when removing
272 * the last element of the list as that is the only time that
273 * it is needed (e.g. to reset the tail pointer).
274 *
275 * NB: This makes an assumption about how tailq's are implemented.
276 *
277 * We break the TAILQ abstraction in order to efficiently remove a
278 * buffer from its freelist without having to know exactly which
279 * freelist it is on.
280 */
281 if (TAILQ_NEXT(bp, b_freelist) == NULL) {
282 for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
283 if (dp->tqh_last == &bp->b_freelist.tqe_next)
284 break;
285 if (dp == &bufqueues[BQUEUES])
286 panic("bremfree: lost tail");
287 }
288 TAILQ_REMOVE(dp, bp, b_freelist);
289 }
290
291 u_long
292 buf_memcalc(void)
293 {
294 u_long n;
295
296 /*
297 * Determine the upper bound of memory to use for buffers.
298 *
299 * - If bufpages is specified, use that as the number
300 * pages.
301 *
302 * - Otherwise, use bufcache as the percentage of
303 * physical memory.
304 */
305 if (bufpages != 0) {
306 n = bufpages;
307 } else {
308 if (bufcache < 5) {
309 printf("forcing bufcache %d -> 5", bufcache);
310 bufcache = 5;
311 }
312 if (bufcache > 95) {
313 printf("forcing bufcache %d -> 95", bufcache);
314 bufcache = 95;
315 }
316 n = physmem / 100 * bufcache;
317 }
318
319 n <<= PAGE_SHIFT;
320 if (bufmem_valimit != 0 && n > bufmem_valimit)
321 n = bufmem_valimit;
322
323 return (n);
324 }
325
326 /*
327 * Initialize buffers and hash links for buffers.
328 */
329 void
330 bufinit(void)
331 {
332 struct bqueues *dp;
333 int smallmem;
334 u_int i;
335
336 /*
337 * Initialize buffer cache memory parameters.
338 */
339 bufmem = 0;
340 bufmem_hiwater = buf_memcalc();
341 /* lowater is approx. 2% of memory (with bufcache=15) */
342 bufmem_lowater = (bufmem_hiwater >> 3);
343 if (bufmem_lowater < 64 * 1024)
344 /* Ensure a reasonable minimum value */
345 bufmem_lowater = 64 * 1024;
346
347 if (bufmem_valimit != 0) {
348 vaddr_t minaddr = 0, maxaddr;
349 buf_map = uvm_km_suballoc(kernel_map, &minaddr, &maxaddr,
350 bufmem_valimit, VM_MAP_PAGEABLE,
351 FALSE, 0);
352 if (buf_map == NULL)
353 panic("bufinit: cannot allocate submap");
354 } else
355 buf_map = kernel_map;
356
357 /*
358 * Initialize the buffer pools.
359 */
360 pool_init(&bufpool, sizeof(struct buf), 0, 0, 0, "bufpl", NULL);
361
362 /* On "small" machines use small pool page sizes where possible */
363 smallmem = (physmem < atop(16*1024*1024));
364
365 for (i = 0; i < NMEMPOOLS; i++) {
366 struct pool_allocator *pa;
367 struct pool *pp = &bmempools[i];
368 u_int size = 1 << (i + MEMPOOL_INDEX_OFFSET);
369 char *name = malloc(8, M_TEMP, M_WAITOK);
370 snprintf(name, 8, "buf%dk", 1 << i);
371 pa = (size <= PAGE_SIZE && smallmem)
372 ? &pool_allocator_nointr
373 : &bufmempool_allocator;
374 pool_init(pp, size, 0, 0, PR_IMMEDRELEASE, name, pa);
375 pool_setlowat(pp, 1);
376 }
377
378 /* Initialize the buffer queues */
379 for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
380 TAILQ_INIT(dp);
381
382 /*
383 * Estimate hash table size based on the amount of memory we
384 * intend to use for the buffer cache. The average buffer
385 * size is dependent on our clients (i.e. filesystems).
386 *
387 * For now, use an empirical 3K per buffer.
388 */
389 nbuf = (bufmem_hiwater / 1024) / 3;
390 bufhashtbl = hashinit(nbuf, HASH_LIST, M_CACHE, M_WAITOK, &bufhash);
391 }
392
393 static int
394 buf_lotsfree(void)
395 {
396 int try, thresh;
397
398 if (bufmem < bufmem_lowater) {
399 return 1;
400 }
401
402 try = random() & 0x0000000fL;
403
404 thresh = (16 * bufmem) / bufmem_hiwater;
405
406 if ((try > thresh) && (uvmexp.free > ( 2 * uvmexp.freetarg))) {
407 return 1;
408 }
409
410 return 0;
411 }
412
413 /*
414 * Return estimate of # of buffers we think need to be
415 * released to help resolve low memory conditions.
416 */
417 static int
418 buf_canrelease(void)
419 {
420 int n;
421
422 if (bufmem < bufmem_lowater)
423 return 0;
424
425 n = uvmexp.freetarg - uvmexp.free;
426 if (n < 0)
427 return 0;
428 return 2 * n;
429 }
430
431 /*
432 * Buffer memory allocation helper functions
433 */
434 static __inline u_long
435 buf_mempoolidx(u_long size)
436 {
437 u_int n = 0;
438
439 size -= 1;
440 size >>= MEMPOOL_INDEX_OFFSET;
441 while (size) {
442 size >>= 1;
443 n += 1;
444 }
445 if (n >= NMEMPOOLS)
446 panic("buf mem pool index %d", n);
447 return n;
448 }
449
450 static __inline u_long
451 buf_roundsize(u_long size)
452 {
453 /* Round up to nearest power of 2 */
454 return (1 << (buf_mempoolidx(size) + MEMPOOL_INDEX_OFFSET));
455 }
456
457 static __inline caddr_t
458 buf_malloc(size_t size)
459 {
460 u_int n = buf_mempoolidx(size);
461 caddr_t addr;
462 int s;
463
464 while (1) {
465 addr = pool_get(&bmempools[n], PR_NOWAIT);
466 if (addr != NULL)
467 break;
468
469 /* No memory, see if we can free some. If so, try again */
470 if (buf_drain(1) > 0)
471 continue;
472
473 /* Wait for buffers to arrive on the LRU queue */
474 s = splbio();
475 simple_lock(&bqueue_slock);
476 needbuffer = 1;
477 ltsleep(&needbuffer, PNORELOCK | (PRIBIO+1),
478 "buf_malloc", 0, &bqueue_slock);
479 splx(s);
480 }
481
482 return addr;
483 }
484
485 static void
486 buf_mrelease(caddr_t addr, size_t size)
487 {
488
489 pool_put(&bmempools[buf_mempoolidx(size)], addr);
490 }
491
492
493 static __inline struct buf *
494 bio_doread(struct vnode *vp, daddr_t blkno, int size, struct ucred *cred,
495 int async)
496 {
497 struct buf *bp;
498 struct lwp *l = (curlwp != NULL ? curlwp : &lwp0); /* XXX */
499 struct proc *p = l->l_proc;
500
501 bp = getblk(vp, blkno, size, 0, 0);
502
503 #ifdef DIAGNOSTIC
504 if (bp == NULL) {
505 panic("bio_doread: no such buf");
506 }
507 #endif
508
509 /*
510 * If buffer does not have data valid, start a read.
511 * Note that if buffer is B_INVAL, getblk() won't return it.
512 * Therefore, it's valid if its I/O has completed or been delayed.
513 */
514 if (!ISSET(bp->b_flags, (B_DONE | B_DELWRI))) {
515 /* Start I/O for the buffer. */
516 SET(bp->b_flags, B_READ | async);
517 if (async)
518 BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
519 else
520 BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
521 VOP_STRATEGY(vp, bp);
522
523 /* Pay for the read. */
524 p->p_stats->p_ru.ru_inblock++;
525 } else if (async) {
526 brelse(bp);
527 }
528
529 return (bp);
530 }
531
532 /*
533 * Read a disk block.
534 * This algorithm described in Bach (p.54).
535 */
536 int
537 bread(struct vnode *vp, daddr_t blkno, int size, struct ucred *cred,
538 struct buf **bpp)
539 {
540 struct buf *bp;
541
542 /* Get buffer for block. */
543 bp = *bpp = bio_doread(vp, blkno, size, cred, 0);
544
545 /* Wait for the read to complete, and return result. */
546 return (biowait(bp));
547 }
548
549 /*
550 * Read-ahead multiple disk blocks. The first is sync, the rest async.
551 * Trivial modification to the breada algorithm presented in Bach (p.55).
552 */
553 int
554 breadn(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablks,
555 int *rasizes, int nrablks, struct ucred *cred, struct buf **bpp)
556 {
557 struct buf *bp;
558 int i;
559
560 bp = *bpp = bio_doread(vp, blkno, size, cred, 0);
561
562 /*
563 * For each of the read-ahead blocks, start a read, if necessary.
564 */
565 for (i = 0; i < nrablks; i++) {
566 /* If it's in the cache, just go on to next one. */
567 if (incore(vp, rablks[i]))
568 continue;
569
570 /* Get a buffer for the read-ahead block */
571 (void) bio_doread(vp, rablks[i], rasizes[i], cred, B_ASYNC);
572 }
573
574 /* Otherwise, we had to start a read for it; wait until it's valid. */
575 return (biowait(bp));
576 }
577
578 /*
579 * Read with single-block read-ahead. Defined in Bach (p.55), but
580 * implemented as a call to breadn().
581 * XXX for compatibility with old file systems.
582 */
583 int
584 breada(struct vnode *vp, daddr_t blkno, int size, daddr_t rablkno,
585 int rabsize, struct ucred *cred, struct buf **bpp)
586 {
587
588 return (breadn(vp, blkno, size, &rablkno, &rabsize, 1, cred, bpp));
589 }
590
591 /*
592 * Block write. Described in Bach (p.56)
593 */
594 int
595 bwrite(struct buf *bp)
596 {
597 int rv, sync, wasdelayed, s;
598 struct lwp *l = (curlwp != NULL ? curlwp : &lwp0); /* XXX */
599 struct proc *p = l->l_proc;
600 struct vnode *vp;
601 struct mount *mp;
602
603 KASSERT(ISSET(bp->b_flags, B_BUSY));
604
605 vp = bp->b_vp;
606 if (vp != NULL) {
607 if (vp->v_type == VBLK)
608 mp = vp->v_specmountpoint;
609 else
610 mp = vp->v_mount;
611 } else {
612 mp = NULL;
613 }
614
615 /*
616 * Remember buffer type, to switch on it later. If the write was
617 * synchronous, but the file system was mounted with MNT_ASYNC,
618 * convert it to a delayed write.
619 * XXX note that this relies on delayed tape writes being converted
620 * to async, not sync writes (which is safe, but ugly).
621 */
622 sync = !ISSET(bp->b_flags, B_ASYNC);
623 if (sync && mp != NULL && ISSET(mp->mnt_flag, MNT_ASYNC)) {
624 bdwrite(bp);
625 return (0);
626 }
627
628 /*
629 * Collect statistics on synchronous and asynchronous writes.
630 * Writes to block devices are charged to their associated
631 * filesystem (if any).
632 */
633 if (mp != NULL) {
634 if (sync)
635 mp->mnt_stat.f_syncwrites++;
636 else
637 mp->mnt_stat.f_asyncwrites++;
638 }
639
640 s = splbio();
641 simple_lock(&bp->b_interlock);
642
643 wasdelayed = ISSET(bp->b_flags, B_DELWRI);
644
645 CLR(bp->b_flags, (B_READ | B_DONE | B_ERROR | B_DELWRI));
646
647 /*
648 * Pay for the I/O operation and make sure the buf is on the correct
649 * vnode queue.
650 */
651 if (wasdelayed)
652 reassignbuf(bp, bp->b_vp);
653 else
654 p->p_stats->p_ru.ru_oublock++;
655
656 /* Initiate disk write. Make sure the appropriate party is charged. */
657 V_INCR_NUMOUTPUT(bp->b_vp);
658 simple_unlock(&bp->b_interlock);
659 splx(s);
660
661 if (sync)
662 BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
663 else
664 BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
665
666 VOP_STRATEGY(vp, bp);
667
668 if (sync) {
669 /* If I/O was synchronous, wait for it to complete. */
670 rv = biowait(bp);
671
672 /* Release the buffer. */
673 brelse(bp);
674
675 return (rv);
676 } else {
677 return (0);
678 }
679 }
680
681 int
682 vn_bwrite(void *v)
683 {
684 struct vop_bwrite_args *ap = v;
685
686 return (bwrite(ap->a_bp));
687 }
688
689 /*
690 * Delayed write.
691 *
692 * The buffer is marked dirty, but is not queued for I/O.
693 * This routine should be used when the buffer is expected
694 * to be modified again soon, typically a small write that
695 * partially fills a buffer.
696 *
697 * NB: magnetic tapes cannot be delayed; they must be
698 * written in the order that the writes are requested.
699 *
700 * Described in Leffler, et al. (pp. 208-213).
701 */
702 void
703 bdwrite(struct buf *bp)
704 {
705 struct lwp *l = (curlwp != NULL ? curlwp : &lwp0); /* XXX */
706 struct proc *p = l->l_proc;
707 const struct bdevsw *bdev;
708 int s;
709
710 /* If this is a tape block, write the block now. */
711 bdev = bdevsw_lookup(bp->b_dev);
712 if (bdev != NULL && bdev->d_type == D_TAPE) {
713 bawrite(bp);
714 return;
715 }
716
717 /*
718 * If the block hasn't been seen before:
719 * (1) Mark it as having been seen,
720 * (2) Charge for the write,
721 * (3) Make sure it's on its vnode's correct block list.
722 */
723 s = splbio();
724 simple_lock(&bp->b_interlock);
725
726 KASSERT(ISSET(bp->b_flags, B_BUSY));
727
728 if (!ISSET(bp->b_flags, B_DELWRI)) {
729 SET(bp->b_flags, B_DELWRI);
730 p->p_stats->p_ru.ru_oublock++;
731 reassignbuf(bp, bp->b_vp);
732 }
733
734 /* Otherwise, the "write" is done, so mark and release the buffer. */
735 CLR(bp->b_flags, B_DONE);
736 simple_unlock(&bp->b_interlock);
737 splx(s);
738
739 brelse(bp);
740 }
741
742 /*
743 * Asynchronous block write; just an asynchronous bwrite().
744 */
745 void
746 bawrite(struct buf *bp)
747 {
748 int s;
749
750 s = splbio();
751 simple_lock(&bp->b_interlock);
752
753 KASSERT(ISSET(bp->b_flags, B_BUSY));
754
755 SET(bp->b_flags, B_ASYNC);
756 simple_unlock(&bp->b_interlock);
757 splx(s);
758 VOP_BWRITE(bp);
759 }
760
761 /*
762 * Same as first half of bdwrite, mark buffer dirty, but do not release it.
763 * Call at splbio() and with the buffer interlock locked.
764 * Note: called only from biodone() through ffs softdep's bioops.io_complete()
765 */
766 void
767 bdirty(struct buf *bp)
768 {
769 struct lwp *l = (curlwp != NULL ? curlwp : &lwp0); /* XXX */
770 struct proc *p = l->l_proc;
771
772 LOCK_ASSERT(simple_lock_held(&bp->b_interlock));
773 KASSERT(ISSET(bp->b_flags, B_BUSY));
774
775 CLR(bp->b_flags, B_AGE);
776
777 if (!ISSET(bp->b_flags, B_DELWRI)) {
778 SET(bp->b_flags, B_DELWRI);
779 p->p_stats->p_ru.ru_oublock++;
780 reassignbuf(bp, bp->b_vp);
781 }
782 }
783
784 /*
785 * Release a buffer on to the free lists.
786 * Described in Bach (p. 46).
787 */
788 void
789 brelse(struct buf *bp)
790 {
791 struct bqueues *bufq;
792 int s;
793
794 /* Block disk interrupts. */
795 s = splbio();
796 simple_lock(&bqueue_slock);
797 simple_lock(&bp->b_interlock);
798
799 KASSERT(ISSET(bp->b_flags, B_BUSY));
800 KASSERT(!ISSET(bp->b_flags, B_CALL));
801
802 /* Wake up any processes waiting for any buffer to become free. */
803 if (needbuffer) {
804 needbuffer = 0;
805 wakeup(&needbuffer);
806 }
807
808 /* Wake up any proceeses waiting for _this_ buffer to become free. */
809 if (ISSET(bp->b_flags, B_WANTED)) {
810 CLR(bp->b_flags, B_WANTED|B_AGE);
811 wakeup(bp);
812 }
813
814 /*
815 * Determine which queue the buffer should be on, then put it there.
816 */
817
818 /* If it's locked, don't report an error; try again later. */
819 if (ISSET(bp->b_flags, (B_LOCKED|B_ERROR)) == (B_LOCKED|B_ERROR))
820 CLR(bp->b_flags, B_ERROR);
821
822 /* If it's not cacheable, or an error, mark it invalid. */
823 if (ISSET(bp->b_flags, (B_NOCACHE|B_ERROR)))
824 SET(bp->b_flags, B_INVAL);
825
826 if (ISSET(bp->b_flags, B_VFLUSH)) {
827 /*
828 * This is a delayed write buffer that was just flushed to
829 * disk. It is still on the LRU queue. If it's become
830 * invalid, then we need to move it to a different queue;
831 * otherwise leave it in its current position.
832 */
833 CLR(bp->b_flags, B_VFLUSH);
834 if (!ISSET(bp->b_flags, B_ERROR|B_INVAL|B_LOCKED|B_AGE)) {
835 KDASSERT(!debug_verify_freelist || checkfreelist(bp, &bufqueues[BQ_LRU]));
836 goto already_queued;
837 } else {
838 bremfree(bp);
839 }
840 }
841
842 KDASSERT(!debug_verify_freelist || !checkfreelist(bp, &bufqueues[BQ_AGE]));
843 KDASSERT(!debug_verify_freelist || !checkfreelist(bp, &bufqueues[BQ_LRU]));
844 KDASSERT(!debug_verify_freelist || !checkfreelist(bp, &bufqueues[BQ_LOCKED]));
845
846 if ((bp->b_bufsize <= 0) || ISSET(bp->b_flags, B_INVAL)) {
847 /*
848 * If it's invalid or empty, dissociate it from its vnode
849 * and put on the head of the appropriate queue.
850 */
851 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
852 (*bioops.io_deallocate)(bp);
853 CLR(bp->b_flags, B_DONE|B_DELWRI);
854 if (bp->b_vp) {
855 reassignbuf(bp, bp->b_vp);
856 brelvp(bp);
857 }
858 if (bp->b_bufsize <= 0)
859 /* no data */
860 goto already_queued;
861 else
862 /* invalid data */
863 bufq = &bufqueues[BQ_AGE];
864 binsheadfree(bp, bufq);
865 } else {
866 /*
867 * It has valid data. Put it on the end of the appropriate
868 * queue, so that it'll stick around for as long as possible.
869 * If buf is AGE, but has dependencies, must put it on last
870 * bufqueue to be scanned, ie LRU. This protects against the
871 * livelock where BQ_AGE only has buffers with dependencies,
872 * and we thus never get to the dependent buffers in BQ_LRU.
873 */
874 if (ISSET(bp->b_flags, B_LOCKED))
875 /* locked in core */
876 bufq = &bufqueues[BQ_LOCKED];
877 else if (!ISSET(bp->b_flags, B_AGE))
878 /* valid data */
879 bufq = &bufqueues[BQ_LRU];
880 else {
881 /* stale but valid data */
882 int has_deps;
883
884 if (LIST_FIRST(&bp->b_dep) != NULL &&
885 bioops.io_countdeps)
886 has_deps = (*bioops.io_countdeps)(bp, 0);
887 else
888 has_deps = 0;
889 bufq = has_deps ? &bufqueues[BQ_LRU] :
890 &bufqueues[BQ_AGE];
891 }
892 binstailfree(bp, bufq);
893 }
894
895 already_queued:
896 /* Unlock the buffer. */
897 CLR(bp->b_flags, B_AGE|B_ASYNC|B_BUSY|B_NOCACHE);
898 SET(bp->b_flags, B_CACHE);
899
900 /* Allow disk interrupts. */
901 simple_unlock(&bp->b_interlock);
902 simple_unlock(&bqueue_slock);
903 if (bp->b_bufsize <= 0) {
904 #ifdef DEBUG
905 memset((char *)bp, 0, sizeof(*bp));
906 #endif
907 pool_put(&bufpool, bp);
908 }
909 splx(s);
910 }
911
912 /*
913 * Determine if a block is in the cache.
914 * Just look on what would be its hash chain. If it's there, return
915 * a pointer to it, unless it's marked invalid. If it's marked invalid,
916 * we normally don't return the buffer, unless the caller explicitly
917 * wants us to.
918 */
919 struct buf *
920 incore(struct vnode *vp, daddr_t blkno)
921 {
922 struct buf *bp;
923
924 /* Search hash chain */
925 LIST_FOREACH(bp, BUFHASH(vp, blkno), b_hash) {
926 if (bp->b_lblkno == blkno && bp->b_vp == vp &&
927 !ISSET(bp->b_flags, B_INVAL))
928 return (bp);
929 }
930
931 return (NULL);
932 }
933
934 /*
935 * Get a block of requested size that is associated with
936 * a given vnode and block offset. If it is found in the
937 * block cache, mark it as having been found, make it busy
938 * and return it. Otherwise, return an empty block of the
939 * correct size. It is up to the caller to insure that the
940 * cached blocks be of the correct size.
941 */
942 struct buf *
943 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo)
944 {
945 struct buf *bp;
946 int s, err;
947 int preserve;
948
949 start:
950 s = splbio();
951 simple_lock(&bqueue_slock);
952 bp = incore(vp, blkno);
953 if (bp != NULL) {
954 simple_lock(&bp->b_interlock);
955 if (ISSET(bp->b_flags, B_BUSY)) {
956 simple_unlock(&bqueue_slock);
957 if (curproc == uvm.pagedaemon_proc) {
958 simple_unlock(&bp->b_interlock);
959 splx(s);
960 return NULL;
961 }
962 SET(bp->b_flags, B_WANTED);
963 err = ltsleep(bp, slpflag | (PRIBIO + 1) | PNORELOCK,
964 "getblk", slptimeo, &bp->b_interlock);
965 splx(s);
966 if (err)
967 return (NULL);
968 goto start;
969 }
970 #ifdef DIAGNOSTIC
971 if (ISSET(bp->b_flags, B_DONE|B_DELWRI) &&
972 bp->b_bcount < size && vp->v_type != VBLK)
973 panic("getblk: block size invariant failed");
974 #endif
975 SET(bp->b_flags, B_BUSY);
976 bremfree(bp);
977 preserve = 1;
978 } else {
979 if ((bp = getnewbuf(slpflag, slptimeo, 0)) == NULL) {
980 simple_unlock(&bqueue_slock);
981 splx(s);
982 goto start;
983 }
984
985 binshash(bp, BUFHASH(vp, blkno));
986 bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = blkno;
987 bgetvp(vp, bp);
988 preserve = 0;
989 }
990 simple_unlock(&bp->b_interlock);
991 simple_unlock(&bqueue_slock);
992 splx(s);
993 /*
994 * LFS can't track total size of B_LOCKED buffer (locked_queue_bytes)
995 * if we re-size buffers here.
996 */
997 if (ISSET(bp->b_flags, B_LOCKED)) {
998 KASSERT(bp->b_bufsize >= size);
999 } else {
1000 allocbuf(bp, size, preserve);
1001 }
1002 BIO_SETPRIO(bp, BPRIO_DEFAULT);
1003 return (bp);
1004 }
1005
1006 /*
1007 * Get an empty, disassociated buffer of given size.
1008 */
1009 struct buf *
1010 geteblk(int size)
1011 {
1012 struct buf *bp;
1013 int s;
1014
1015 s = splbio();
1016 simple_lock(&bqueue_slock);
1017 while ((bp = getnewbuf(0, 0, 0)) == 0)
1018 ;
1019
1020 SET(bp->b_flags, B_INVAL);
1021 binshash(bp, &invalhash);
1022 simple_unlock(&bqueue_slock);
1023 simple_unlock(&bp->b_interlock);
1024 splx(s);
1025 BIO_SETPRIO(bp, BPRIO_DEFAULT);
1026 allocbuf(bp, size, 0);
1027 return (bp);
1028 }
1029
1030 /*
1031 * Expand or contract the actual memory allocated to a buffer.
1032 *
1033 * If the buffer shrinks, data is lost, so it's up to the
1034 * caller to have written it out *first*; this routine will not
1035 * start a write. If the buffer grows, it's the callers
1036 * responsibility to fill out the buffer's additional contents.
1037 */
1038 void
1039 allocbuf(struct buf *bp, int size, int preserve)
1040 {
1041 vsize_t oldsize, desired_size;
1042 caddr_t addr;
1043 int s, delta;
1044
1045 desired_size = buf_roundsize(size);
1046 if (desired_size > MAXBSIZE)
1047 printf("allocbuf: buffer larger than MAXBSIZE requested");
1048
1049 bp->b_bcount = size;
1050
1051 oldsize = bp->b_bufsize;
1052 if (oldsize == desired_size)
1053 return;
1054
1055 /*
1056 * If we want a buffer of a different size, re-allocate the
1057 * buffer's memory; copy old content only if needed.
1058 */
1059 addr = buf_malloc(desired_size);
1060 if (preserve)
1061 memcpy(addr, bp->b_data, MIN(oldsize,desired_size));
1062 if (bp->b_data != NULL)
1063 buf_mrelease(bp->b_data, oldsize);
1064 bp->b_data = addr;
1065 bp->b_bufsize = desired_size;
1066
1067 /*
1068 * Update overall buffer memory counter (protected by bqueue_slock)
1069 */
1070 delta = (long)desired_size - (long)oldsize;
1071
1072 s = splbio();
1073 simple_lock(&bqueue_slock);
1074 if ((bufmem += delta) > bufmem_hiwater) {
1075 /*
1076 * Need to trim overall memory usage.
1077 */
1078 while (buf_canrelease()) {
1079 if (buf_trim() == 0)
1080 break;
1081 }
1082 }
1083
1084 simple_unlock(&bqueue_slock);
1085 splx(s);
1086 }
1087
1088 /*
1089 * Find a buffer which is available for use.
1090 * Select something from a free list.
1091 * Preference is to AGE list, then LRU list.
1092 *
1093 * Called at splbio and with buffer queues locked.
1094 * Return buffer locked.
1095 */
1096 struct buf *
1097 getnewbuf(int slpflag, int slptimeo, int from_bufq)
1098 {
1099 struct buf *bp;
1100
1101 start:
1102 LOCK_ASSERT(simple_lock_held(&bqueue_slock));
1103
1104 /*
1105 * Get a new buffer from the pool; but use NOWAIT because
1106 * we have the buffer queues locked.
1107 */
1108 if (buf_lotsfree() && !from_bufq &&
1109 (bp = pool_get(&bufpool, PR_NOWAIT)) != NULL) {
1110 memset((char *)bp, 0, sizeof(*bp));
1111 BUF_INIT(bp);
1112 bp->b_dev = NODEV;
1113 bp->b_vnbufs.le_next = NOLIST;
1114 bp->b_flags = B_BUSY;
1115 simple_lock(&bp->b_interlock);
1116 return (bp);
1117 }
1118
1119 if ((bp = TAILQ_FIRST(&bufqueues[BQ_AGE])) != NULL ||
1120 (bp = TAILQ_FIRST(&bufqueues[BQ_LRU])) != NULL) {
1121 simple_lock(&bp->b_interlock);
1122 bremfree(bp);
1123 } else {
1124 /* wait for a free buffer of any kind */
1125 needbuffer = 1;
1126 ltsleep(&needbuffer, slpflag|(PRIBIO+1),
1127 "getnewbuf", slptimeo, &bqueue_slock);
1128 return (NULL);
1129 }
1130
1131 #ifdef DIAGNOSTIC
1132 if (bp->b_bufsize <= 0)
1133 panic("buffer %p: on queue but empty", bp);
1134 #endif
1135
1136 if (ISSET(bp->b_flags, B_VFLUSH)) {
1137 /*
1138 * This is a delayed write buffer being flushed to disk. Make
1139 * sure it gets aged out of the queue when it's finished, and
1140 * leave it off the LRU queue.
1141 */
1142 CLR(bp->b_flags, B_VFLUSH);
1143 SET(bp->b_flags, B_AGE);
1144 simple_unlock(&bp->b_interlock);
1145 goto start;
1146 }
1147
1148 /* Buffer is no longer on free lists. */
1149 SET(bp->b_flags, B_BUSY);
1150
1151 /*
1152 * If buffer was a delayed write, start it and return NULL
1153 * (since we might sleep while starting the write).
1154 */
1155 if (ISSET(bp->b_flags, B_DELWRI)) {
1156 /*
1157 * This buffer has gone through the LRU, so make sure it gets
1158 * reused ASAP.
1159 */
1160 SET(bp->b_flags, B_AGE);
1161 simple_unlock(&bp->b_interlock);
1162 simple_unlock(&bqueue_slock);
1163 bawrite(bp);
1164 simple_lock(&bqueue_slock);
1165 return (NULL);
1166 }
1167
1168 /* disassociate us from our vnode, if we had one... */
1169 if (bp->b_vp)
1170 brelvp(bp);
1171
1172 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_deallocate)
1173 (*bioops.io_deallocate)(bp);
1174
1175 /* clear out various other fields */
1176 bp->b_flags = B_BUSY;
1177 bp->b_dev = NODEV;
1178 bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = 0;
1179 bp->b_iodone = 0;
1180 bp->b_error = 0;
1181 bp->b_resid = 0;
1182 bp->b_bcount = 0;
1183
1184 bremhash(bp);
1185 return (bp);
1186 }
1187
1188 /*
1189 * Attempt to free an aged buffer off the queues.
1190 * Called at splbio and with queue lock held.
1191 * Returns the amount of buffer memory freed.
1192 */
1193 int
1194 buf_trim(void)
1195 {
1196 struct buf *bp;
1197 long size = 0;
1198 int wanted;
1199
1200 /* Instruct getnewbuf() to get buffers off the queues */
1201 if ((bp = getnewbuf(PCATCH, 1, 1)) == NULL)
1202 return 0;
1203
1204 wanted = ISSET(bp->b_flags, B_WANTED);
1205 simple_unlock(&bp->b_interlock);
1206 if (wanted) {
1207 printf("buftrim: got WANTED buffer\n");
1208 SET(bp->b_flags, B_INVAL);
1209 binshash(bp, &invalhash);
1210 simple_unlock(&bqueue_slock);
1211 goto out;
1212 }
1213 size = bp->b_bufsize;
1214 bufmem -= size;
1215 simple_unlock(&bqueue_slock);
1216 if (size > 0) {
1217 buf_mrelease(bp->b_data, size);
1218 bp->b_bcount = bp->b_bufsize = 0;
1219 }
1220
1221 out:
1222 /* brelse() will return the buffer to the global buffer pool */
1223 brelse(bp);
1224 simple_lock(&bqueue_slock);
1225 return size;
1226 }
1227
1228 int
1229 buf_drain(int n)
1230 {
1231 int s, size = 0;
1232
1233 /* If not asked for a specific amount, make our own estimate */
1234 if (n == 0)
1235 n = buf_canrelease();
1236
1237 s = splbio();
1238 simple_lock(&bqueue_slock);
1239 while (size < n && bufmem > bufmem_lowater)
1240 size += buf_trim();
1241
1242 simple_unlock(&bqueue_slock);
1243 splx(s);
1244 return size;
1245 }
1246
1247 /*
1248 * Wait for operations on the buffer to complete.
1249 * When they do, extract and return the I/O's error value.
1250 */
1251 int
1252 biowait(struct buf *bp)
1253 {
1254 int s, error;
1255
1256 s = splbio();
1257 simple_lock(&bp->b_interlock);
1258 while (!ISSET(bp->b_flags, B_DONE | B_DELWRI))
1259 ltsleep(bp, PRIBIO + 1, "biowait", 0, &bp->b_interlock);
1260
1261 /* check for interruption of I/O (e.g. via NFS), then errors. */
1262 if (ISSET(bp->b_flags, B_EINTR)) {
1263 CLR(bp->b_flags, B_EINTR);
1264 error = EINTR;
1265 } else if (ISSET(bp->b_flags, B_ERROR))
1266 error = bp->b_error ? bp->b_error : EIO;
1267 else
1268 error = 0;
1269
1270 simple_unlock(&bp->b_interlock);
1271 splx(s);
1272 return (error);
1273 }
1274
1275 /*
1276 * Mark I/O complete on a buffer.
1277 *
1278 * If a callback has been requested, e.g. the pageout
1279 * daemon, do so. Otherwise, awaken waiting processes.
1280 *
1281 * [ Leffler, et al., says on p.247:
1282 * "This routine wakes up the blocked process, frees the buffer
1283 * for an asynchronous write, or, for a request by the pagedaemon
1284 * process, invokes a procedure specified in the buffer structure" ]
1285 *
1286 * In real life, the pagedaemon (or other system processes) wants
1287 * to do async stuff to, and doesn't want the buffer brelse()'d.
1288 * (for swap pager, that puts swap buffers on the free lists (!!!),
1289 * for the vn device, that puts malloc'd buffers on the free lists!)
1290 */
1291 void
1292 biodone(struct buf *bp)
1293 {
1294 int s = splbio();
1295
1296 simple_lock(&bp->b_interlock);
1297 if (ISSET(bp->b_flags, B_DONE))
1298 panic("biodone already");
1299 SET(bp->b_flags, B_DONE); /* note that it's done */
1300 BIO_SETPRIO(bp, BPRIO_DEFAULT);
1301
1302 if (LIST_FIRST(&bp->b_dep) != NULL && bioops.io_complete)
1303 (*bioops.io_complete)(bp);
1304
1305 if (!ISSET(bp->b_flags, B_READ)) /* wake up reader */
1306 vwakeup(bp);
1307
1308 /*
1309 * If necessary, call out. Unlock the buffer before calling
1310 * iodone() as the buffer isn't valid any more when it return.
1311 */
1312 if (ISSET(bp->b_flags, B_CALL)) {
1313 CLR(bp->b_flags, B_CALL); /* but note callout done */
1314 simple_unlock(&bp->b_interlock);
1315 (*bp->b_iodone)(bp);
1316 } else {
1317 if (ISSET(bp->b_flags, B_ASYNC)) { /* if async, release */
1318 simple_unlock(&bp->b_interlock);
1319 brelse(bp);
1320 } else { /* or just wakeup the buffer */
1321 CLR(bp->b_flags, B_WANTED);
1322 wakeup(bp);
1323 simple_unlock(&bp->b_interlock);
1324 }
1325 }
1326
1327 splx(s);
1328 }
1329
1330 /*
1331 * Return a count of buffers on the "locked" queue.
1332 */
1333 int
1334 count_lock_queue(void)
1335 {
1336 struct buf *bp;
1337 int n = 0;
1338
1339 simple_lock(&bqueue_slock);
1340 TAILQ_FOREACH(bp, &bufqueues[BQ_LOCKED], b_freelist)
1341 n++;
1342 simple_unlock(&bqueue_slock);
1343 return (n);
1344 }
1345
1346 /*
1347 * Wait for all buffers to complete I/O
1348 * Return the number of "stuck" buffers.
1349 */
1350 int
1351 buf_syncwait(void)
1352 {
1353 struct buf *bp;
1354 int iter, nbusy, nbusy_prev = 0, dcount, s, ihash;
1355
1356 dcount = 10000;
1357 for (iter = 0; iter < 20;) {
1358 s = splbio();
1359 simple_lock(&bqueue_slock);
1360 nbusy = 0;
1361 for (ihash = 0; ihash < bufhash+1; ihash++) {
1362 LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
1363 if ((bp->b_flags & (B_BUSY|B_INVAL|B_READ)) == B_BUSY)
1364 nbusy++;
1365 /*
1366 * With soft updates, some buffers that are
1367 * written will be remarked as dirty until other
1368 * buffers are written.
1369 */
1370 if (bp->b_vp && bp->b_vp->v_mount
1371 && (bp->b_vp->v_mount->mnt_flag & MNT_SOFTDEP)
1372 && (bp->b_flags & B_DELWRI)) {
1373 simple_lock(&bp->b_interlock);
1374 bremfree(bp);
1375 bp->b_flags |= B_BUSY;
1376 nbusy++;
1377 simple_unlock(&bp->b_interlock);
1378 simple_unlock(&bqueue_slock);
1379 bawrite(bp);
1380 if (dcount-- <= 0) {
1381 printf("softdep ");
1382 goto fail;
1383 }
1384 simple_lock(&bqueue_slock);
1385 }
1386 }
1387 }
1388
1389 simple_unlock(&bqueue_slock);
1390 splx(s);
1391
1392 if (nbusy == 0)
1393 break;
1394 if (nbusy_prev == 0)
1395 nbusy_prev = nbusy;
1396 printf("%d ", nbusy);
1397 tsleep(&nbusy, PRIBIO, "bflush",
1398 (iter == 0) ? 1 : hz / 25 * iter);
1399 if (nbusy >= nbusy_prev) /* we didn't flush anything */
1400 iter++;
1401 else
1402 nbusy_prev = nbusy;
1403 }
1404
1405 if (nbusy) {
1406 fail:;
1407 #if defined(DEBUG) || defined(DEBUG_HALT_BUSY)
1408 printf("giving up\nPrinting vnodes for busy buffers\n");
1409 for (ihash = 0; ihash < bufhash+1; ihash++) {
1410 LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
1411 if ((bp->b_flags & (B_BUSY|B_INVAL|B_READ)) == B_BUSY)
1412 vprint(NULL, bp->b_vp);
1413 }
1414 }
1415 #endif
1416 }
1417
1418 return nbusy;
1419 }
1420
1421 #define KERN_BUFSLOP 20
1422 static int
1423 sysctl_dobuf(SYSCTLFN_ARGS)
1424 {
1425 struct buf *bp;
1426 char *dp;
1427 u_int i, elem_size;
1428 size_t len, buflen, needed;
1429 int error, s;
1430
1431 dp = oldp;
1432 len = buflen = oldp != NULL ? *oldlenp : 0;
1433 error = 0;
1434 needed = 0;
1435 elem_size = sizeof(struct buf);
1436
1437 s = splbio();
1438 simple_lock(&bqueue_slock);
1439 for (i = 0; i < BQUEUES; i++) {
1440 TAILQ_FOREACH(bp, &bufqueues[i], b_freelist) {
1441 if (len >= elem_size) {
1442 error = copyout(bp, dp, elem_size);
1443 if (error)
1444 goto cleanup;
1445 dp += elem_size;
1446 len -= elem_size;
1447 }
1448 needed += elem_size;
1449 }
1450 }
1451 cleanup:
1452 simple_unlock(&bqueue_slock);
1453 splx(s);
1454
1455 if (oldp != NULL) {
1456 *oldlenp = (char *)dp - (char *)oldp;
1457 if (needed > *oldlenp)
1458 error = ENOMEM;
1459 } else {
1460 needed += KERN_BUFSLOP;
1461 *oldlenp = needed;
1462 }
1463
1464 return (error);
1465 }
1466
1467 static int sysctlnum_bufcache, sysctlnum_bufmemhiwater, sysctlnum_bufmemlowater;
1468
1469 static int
1470 sysctl_bufvm_update(SYSCTLFN_ARGS)
1471 {
1472 int t, error;
1473 struct sysctlnode node;
1474
1475 node = *rnode;
1476 node.sysctl_data = &t;
1477 t = *(int*)rnode->sysctl_data;
1478 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1479 if (error || newp == NULL)
1480 return (error);
1481
1482 if (rnode->sysctl_num == sysctlnum_bufcache) {
1483 if (t < 0 || t > 100)
1484 return (EINVAL);
1485 bufcache = t;
1486 bufmem_hiwater = buf_memcalc();
1487 bufmem_lowater = (bufmem_hiwater >> 3);
1488 if (bufmem_lowater < 64 * 1024)
1489 /* Ensure a reasonable minimum value */
1490 bufmem_lowater = 64 * 1024;
1491
1492 } else if (rnode->sysctl_num == sysctlnum_bufmemlowater) {
1493 bufmem_lowater = t;
1494 } else if (rnode->sysctl_num == sysctlnum_bufmemhiwater) {
1495 bufmem_hiwater = t;
1496 } else
1497 return (EINVAL);
1498
1499 /* Drain until below new high water mark */
1500 while ((t = bufmem - bufmem_hiwater) >= 0) {
1501 if (buf_drain(t / (2*1024)) <= 0)
1502 break;
1503 }
1504
1505 return 0;
1506 }
1507
1508 SYSCTL_SETUP(sysctl_kern_buf_setup, "sysctl kern.buf subtree setup")
1509 {
1510
1511 sysctl_createv(SYSCTL_PERMANENT,
1512 CTLTYPE_NODE, "kern", NULL,
1513 NULL, 0, NULL, 0,
1514 CTL_KERN, CTL_EOL);
1515 sysctl_createv(SYSCTL_PERMANENT,
1516 CTLTYPE_NODE, "buf", NULL,
1517 sysctl_dobuf, 0, NULL, 0,
1518 CTL_KERN, KERN_BUF, CTL_EOL);
1519 }
1520
1521 SYSCTL_SETUP(sysctl_vm_buf_setup, "sysctl vm.buf* subtree setup")
1522 {
1523 struct sysctlnode *rnode;
1524
1525 sysctl_createv(SYSCTL_PERMANENT,
1526 CTLTYPE_NODE, "vm", NULL,
1527 NULL, 0, NULL, 0,
1528 CTL_VM, CTL_EOL);
1529
1530 rnode = NULL;
1531 if (sysctl_createv(SYSCTL_PERMANENT|SYSCTL_READWRITE,
1532 CTLTYPE_INT, "bufcache", &rnode,
1533 sysctl_bufvm_update, 0, &bufcache, 0,
1534 CTL_VM, CTL_CREATE, CTL_EOL) == 0)
1535 sysctlnum_bufcache = rnode->sysctl_num;
1536
1537 rnode = NULL;
1538 if (sysctl_createv(SYSCTL_PERMANENT|SYSCTL_READWRITE,
1539 CTLTYPE_INT, "bufmem_lowater", &rnode,
1540 sysctl_bufvm_update, 0, &bufmem_lowater, 0,
1541 CTL_VM, CTL_CREATE, CTL_EOL) == 0)
1542 sysctlnum_bufmemlowater = rnode->sysctl_num;
1543
1544 rnode = NULL;
1545 if (sysctl_createv(SYSCTL_PERMANENT|SYSCTL_READWRITE,
1546 CTLTYPE_INT, "bufmem_hiwater", &rnode,
1547 sysctl_bufvm_update, 0, &bufmem_hiwater, 0,
1548 CTL_VM, CTL_CREATE, CTL_EOL) == 0)
1549 sysctlnum_bufmemhiwater = rnode->sysctl_num;
1550 }
1551
1552 #ifdef DEBUG
1553 /*
1554 * Print out statistics on the current allocation of the buffer pool.
1555 * Can be enabled to print out on every ``sync'' by setting "syncprt"
1556 * in vfs_syscalls.c using sysctl.
1557 */
1558 void
1559 vfs_bufstats(void)
1560 {
1561 int s, i, j, count;
1562 struct buf *bp;
1563 struct bqueues *dp;
1564 int counts[(MAXBSIZE / PAGE_SIZE) + 1];
1565 static char *bname[BQUEUES] = { "LOCKED", "LRU", "AGE" };
1566
1567 for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
1568 count = 0;
1569 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
1570 counts[j] = 0;
1571 s = splbio();
1572 TAILQ_FOREACH(bp, dp, b_freelist) {
1573 counts[bp->b_bufsize/PAGE_SIZE]++;
1574 count++;
1575 }
1576 splx(s);
1577 printf("%s: total-%d", bname[i], count);
1578 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
1579 if (counts[j] != 0)
1580 printf(", %d-%d", j * PAGE_SIZE, counts[j]);
1581 printf("\n");
1582 }
1583 }
1584 #endif /* DEBUG */
1585