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