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