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