vfs_bio.c revision 1.285 1 /* $NetBSD: vfs_bio.c,v 1.285 2019/12/27 09:41:51 msaitoh Exp $ */
2
3 /*-
4 * Copyright (c) 2007, 2008, 2009, 2019 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Andrew Doran, and by Wasabi Systems, Inc.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*-
33 * Copyright (c) 1982, 1986, 1989, 1993
34 * The Regents of the University of California. All rights reserved.
35 * (c) UNIX System Laboratories, Inc.
36 * All or some portions of this file are derived from material licensed
37 * to the University of California by American Telephone and Telegraph
38 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
39 * the permission of UNIX System Laboratories, Inc.
40 *
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
43 * are met:
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
49 * 3. Neither the name of the University nor the names of its contributors
50 * may be used to endorse or promote products derived from this software
51 * without specific prior written permission.
52 *
53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 * SUCH DAMAGE.
64 *
65 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
66 */
67
68 /*-
69 * Copyright (c) 1994 Christopher G. Demetriou
70 *
71 * Redistribution and use in source and binary forms, with or without
72 * modification, are permitted provided that the following conditions
73 * are met:
74 * 1. Redistributions of source code must retain the above copyright
75 * notice, this list of conditions and the following disclaimer.
76 * 2. Redistributions in binary form must reproduce the above copyright
77 * notice, this list of conditions and the following disclaimer in the
78 * documentation and/or other materials provided with the distribution.
79 * 3. All advertising materials mentioning features or use of this software
80 * must display the following acknowledgement:
81 * This product includes software developed by the University of
82 * California, Berkeley and its contributors.
83 * 4. Neither the name of the University nor the names of its contributors
84 * may be used to endorse or promote products derived from this software
85 * without specific prior written permission.
86 *
87 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
88 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
89 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
90 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
91 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
92 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
93 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
94 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
95 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
96 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
97 * SUCH DAMAGE.
98 *
99 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
100 */
101
102 /*
103 * The buffer cache subsystem.
104 *
105 * Some references:
106 * Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
107 * Leffler, et al.: The Design and Implementation of the 4.3BSD
108 * UNIX Operating System (Addison Welley, 1989)
109 *
110 * Locking
111 *
112 * There are three locks:
113 * - bufcache_lock: protects global buffer cache state.
114 * - BC_BUSY: a long term per-buffer lock.
115 * - buf_t::b_objlock: lock on completion (biowait vs biodone).
116 *
117 * For buffers associated with vnodes (a most common case) b_objlock points
118 * to the vnode_t::v_interlock. Otherwise, it points to generic buffer_lock.
119 *
120 * Lock order:
121 * bufcache_lock ->
122 * buf_t::b_objlock
123 */
124
125 #include <sys/cdefs.h>
126 __KERNEL_RCSID(0, "$NetBSD: vfs_bio.c,v 1.285 2019/12/27 09:41:51 msaitoh Exp $");
127
128 #ifdef _KERNEL_OPT
129 #include "opt_bufcache.h"
130 #include "opt_dtrace.h"
131 #include "opt_biohist.h"
132 #endif
133
134 #include <sys/param.h>
135 #include <sys/systm.h>
136 #include <sys/kernel.h>
137 #include <sys/proc.h>
138 #include <sys/buf.h>
139 #include <sys/vnode.h>
140 #include <sys/mount.h>
141 #include <sys/resourcevar.h>
142 #include <sys/sysctl.h>
143 #include <sys/conf.h>
144 #include <sys/kauth.h>
145 #include <sys/fstrans.h>
146 #include <sys/intr.h>
147 #include <sys/cpu.h>
148 #include <sys/wapbl.h>
149 #include <sys/bitops.h>
150 #include <sys/cprng.h>
151 #include <sys/sdt.h>
152
153 #include <uvm/uvm.h> /* extern struct uvm uvm */
154
155 #include <miscfs/specfs/specdev.h>
156
157 #ifndef BUFPAGES
158 # define BUFPAGES 0
159 #endif
160
161 #ifdef BUFCACHE
162 # if (BUFCACHE < 5) || (BUFCACHE > 95)
163 # error BUFCACHE is not between 5 and 95
164 # endif
165 #else
166 # define BUFCACHE 15
167 #endif
168
169 u_int nbuf; /* desired number of buffer headers */
170 u_int bufpages = BUFPAGES; /* optional hardwired count */
171 u_int bufcache = BUFCACHE; /* max % of RAM to use for buffer cache */
172
173 /*
174 * Definitions for the buffer free lists.
175 */
176 #define BQUEUES 3 /* number of free buffer queues */
177
178 #define BQ_LOCKED 0 /* super-blocks &c */
179 #define BQ_LRU 1 /* lru, useful buffers */
180 #define BQ_AGE 2 /* rubbish */
181
182 struct bqueue {
183 TAILQ_HEAD(, buf) bq_queue;
184 uint64_t bq_bytes;
185 buf_t *bq_marker;
186 };
187 static struct bqueue bufqueues[BQUEUES] __cacheline_aligned;
188
189 /* Function prototypes */
190 static void buf_setwm(void);
191 static int buf_trim(void);
192 static void *bufpool_page_alloc(struct pool *, int);
193 static void bufpool_page_free(struct pool *, void *);
194 static buf_t *bio_doread(struct vnode *, daddr_t, int, int);
195 static buf_t *getnewbuf(int, int, int);
196 static int buf_lotsfree(void);
197 static int buf_canrelease(void);
198 static u_long buf_mempoolidx(u_long);
199 static u_long buf_roundsize(u_long);
200 static void *buf_alloc(size_t);
201 static void buf_mrelease(void *, size_t);
202 static void binsheadfree(buf_t *, struct bqueue *);
203 static void binstailfree(buf_t *, struct bqueue *);
204 #ifdef DEBUG
205 static int checkfreelist(buf_t *, struct bqueue *, int);
206 #endif
207 static void biointr(void *);
208 static void biodone2(buf_t *);
209 static void bref(buf_t *);
210 static void brele(buf_t *);
211 static void sysctl_kern_buf_setup(void);
212 static void sysctl_vm_buf_setup(void);
213
214 /* Initialization for biohist */
215
216 #include <sys/biohist.h>
217
218 BIOHIST_DEFINE(biohist);
219
220 void
221 biohist_init(void)
222 {
223
224 BIOHIST_INIT(biohist, BIOHIST_SIZE);
225 }
226
227 /*
228 * Definitions for the buffer hash lists.
229 */
230 #define BUFHASH(dvp, lbn) \
231 (&bufhashtbl[(((long)(dvp) >> 8) + (int)(lbn)) & bufhash])
232 LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
233 u_long bufhash;
234
235 static kcondvar_t needbuffer_cv;
236
237 /*
238 * Buffer queue lock.
239 */
240 kmutex_t bufcache_lock __cacheline_aligned;
241 kmutex_t buffer_lock __cacheline_aligned;
242
243 /* Software ISR for completed transfers. */
244 static void *biodone_sih;
245
246 /* Buffer pool for I/O buffers. */
247 static pool_cache_t buf_cache;
248 static pool_cache_t bufio_cache;
249
250 #define MEMPOOL_INDEX_OFFSET (ilog2(DEV_BSIZE)) /* smallest pool is 512 bytes */
251 #define NMEMPOOLS (ilog2(MAXBSIZE) - MEMPOOL_INDEX_OFFSET + 1)
252 __CTASSERT((1 << (NMEMPOOLS + MEMPOOL_INDEX_OFFSET - 1)) == MAXBSIZE);
253
254 /* Buffer memory pools */
255 static struct pool bmempools[NMEMPOOLS];
256
257 static struct vm_map *buf_map;
258
259 /*
260 * Buffer memory pool allocator.
261 */
262 static void *
263 bufpool_page_alloc(struct pool *pp, int flags)
264 {
265
266 return (void *)uvm_km_alloc(buf_map,
267 MAXBSIZE, MAXBSIZE,
268 ((flags & PR_WAITOK) ? 0 : UVM_KMF_NOWAIT|UVM_KMF_TRYLOCK)
269 | UVM_KMF_WIRED);
270 }
271
272 static void
273 bufpool_page_free(struct pool *pp, void *v)
274 {
275
276 uvm_km_free(buf_map, (vaddr_t)v, MAXBSIZE, UVM_KMF_WIRED);
277 }
278
279 static struct pool_allocator bufmempool_allocator = {
280 .pa_alloc = bufpool_page_alloc,
281 .pa_free = bufpool_page_free,
282 .pa_pagesz = MAXBSIZE,
283 };
284
285 /* Buffer memory management variables */
286 u_long bufmem_valimit;
287 u_long bufmem_hiwater;
288 u_long bufmem_lowater;
289 u_long bufmem;
290
291 /*
292 * MD code can call this to set a hard limit on the amount
293 * of virtual memory used by the buffer cache.
294 */
295 int
296 buf_setvalimit(vsize_t sz)
297 {
298
299 /* We need to accommodate at least NMEMPOOLS of MAXBSIZE each */
300 if (sz < NMEMPOOLS * MAXBSIZE)
301 return EINVAL;
302
303 bufmem_valimit = sz;
304 return 0;
305 }
306
307 static void
308 buf_setwm(void)
309 {
310
311 bufmem_hiwater = buf_memcalc();
312 /* lowater is approx. 2% of memory (with bufcache = 15) */
313 #define BUFMEM_WMSHIFT 3
314 #define BUFMEM_HIWMMIN (64 * 1024 << BUFMEM_WMSHIFT)
315 if (bufmem_hiwater < BUFMEM_HIWMMIN)
316 /* Ensure a reasonable minimum value */
317 bufmem_hiwater = BUFMEM_HIWMMIN;
318 bufmem_lowater = bufmem_hiwater >> BUFMEM_WMSHIFT;
319 }
320
321 #ifdef DEBUG
322 int debug_verify_freelist = 0;
323 static int
324 checkfreelist(buf_t *bp, struct bqueue *dp, int ison)
325 {
326 buf_t *b;
327
328 if (!debug_verify_freelist)
329 return 1;
330
331 TAILQ_FOREACH(b, &dp->bq_queue, b_freelist) {
332 if (b == bp)
333 return ison ? 1 : 0;
334 }
335
336 return ison ? 0 : 1;
337 }
338 #endif
339
340 /*
341 * Insq/Remq for the buffer hash lists.
342 * Call with buffer queue locked.
343 */
344 static void
345 binsheadfree(buf_t *bp, struct bqueue *dp)
346 {
347
348 KASSERT(mutex_owned(&bufcache_lock));
349 KASSERT(bp->b_freelistindex == -1);
350 TAILQ_INSERT_HEAD(&dp->bq_queue, bp, b_freelist);
351 dp->bq_bytes += bp->b_bufsize;
352 bp->b_freelistindex = dp - bufqueues;
353 }
354
355 static void
356 binstailfree(buf_t *bp, struct bqueue *dp)
357 {
358
359 KASSERT(mutex_owned(&bufcache_lock));
360 KASSERTMSG(bp->b_freelistindex == -1, "double free of buffer? "
361 "bp=%p, b_freelistindex=%d\n", bp, bp->b_freelistindex);
362 TAILQ_INSERT_TAIL(&dp->bq_queue, bp, b_freelist);
363 dp->bq_bytes += bp->b_bufsize;
364 bp->b_freelistindex = dp - bufqueues;
365 }
366
367 void
368 bremfree(buf_t *bp)
369 {
370 struct bqueue *dp;
371 int bqidx = bp->b_freelistindex;
372
373 KASSERT(mutex_owned(&bufcache_lock));
374
375 KASSERT(bqidx != -1);
376 dp = &bufqueues[bqidx];
377 KDASSERT(checkfreelist(bp, dp, 1));
378 KASSERT(dp->bq_bytes >= bp->b_bufsize);
379 TAILQ_REMOVE(&dp->bq_queue, bp, b_freelist);
380 dp->bq_bytes -= bp->b_bufsize;
381
382 /* For the sysctl helper. */
383 if (bp == dp->bq_marker)
384 dp->bq_marker = NULL;
385
386 #if defined(DIAGNOSTIC)
387 bp->b_freelistindex = -1;
388 #endif /* defined(DIAGNOSTIC) */
389 }
390
391 /*
392 * Add a reference to an buffer structure that came from buf_cache.
393 */
394 static inline void
395 bref(buf_t *bp)
396 {
397
398 KASSERT(mutex_owned(&bufcache_lock));
399 KASSERT(bp->b_refcnt > 0);
400
401 bp->b_refcnt++;
402 }
403
404 /*
405 * Free an unused buffer structure that came from buf_cache.
406 */
407 static inline void
408 brele(buf_t *bp)
409 {
410
411 KASSERT(mutex_owned(&bufcache_lock));
412 KASSERT(bp->b_refcnt > 0);
413
414 if (bp->b_refcnt-- == 1) {
415 buf_destroy(bp);
416 #ifdef DEBUG
417 memset((char *)bp, 0, sizeof(*bp));
418 #endif
419 pool_cache_put(buf_cache, bp);
420 }
421 }
422
423 /*
424 * note that for some ports this is used by pmap bootstrap code to
425 * determine kva size.
426 */
427 u_long
428 buf_memcalc(void)
429 {
430 u_long n;
431 vsize_t mapsz = 0;
432
433 /*
434 * Determine the upper bound of memory to use for buffers.
435 *
436 * - If bufpages is specified, use that as the number
437 * pages.
438 *
439 * - Otherwise, use bufcache as the percentage of
440 * physical memory.
441 */
442 if (bufpages != 0) {
443 n = bufpages;
444 } else {
445 if (bufcache < 5) {
446 printf("forcing bufcache %d -> 5", bufcache);
447 bufcache = 5;
448 }
449 if (bufcache > 95) {
450 printf("forcing bufcache %d -> 95", bufcache);
451 bufcache = 95;
452 }
453 if (buf_map != NULL)
454 mapsz = vm_map_max(buf_map) - vm_map_min(buf_map);
455 n = calc_cache_size(mapsz, bufcache,
456 (buf_map != kernel_map) ? 100 : BUFCACHE_VA_MAXPCT)
457 / PAGE_SIZE;
458 }
459
460 n <<= PAGE_SHIFT;
461 if (bufmem_valimit != 0 && n > bufmem_valimit)
462 n = bufmem_valimit;
463
464 return (n);
465 }
466
467 /*
468 * Initialize buffers and hash links for buffers.
469 */
470 void
471 bufinit(void)
472 {
473 struct bqueue *dp;
474 int use_std;
475 u_int i;
476
477 biodone_vfs = biodone;
478
479 mutex_init(&bufcache_lock, MUTEX_DEFAULT, IPL_NONE);
480 mutex_init(&buffer_lock, MUTEX_DEFAULT, IPL_NONE);
481 cv_init(&needbuffer_cv, "needbuf");
482
483 if (bufmem_valimit != 0) {
484 vaddr_t minaddr = 0, maxaddr;
485 buf_map = uvm_km_suballoc(kernel_map, &minaddr, &maxaddr,
486 bufmem_valimit, 0, false, 0);
487 if (buf_map == NULL)
488 panic("bufinit: cannot allocate submap");
489 } else
490 buf_map = kernel_map;
491
492 /*
493 * Initialize buffer cache memory parameters.
494 */
495 bufmem = 0;
496 buf_setwm();
497
498 /* On "small" machines use small pool page sizes where possible */
499 use_std = (physmem < atop(16*1024*1024));
500
501 /*
502 * Also use them on systems that can map the pool pages using
503 * a direct-mapped segment.
504 */
505 #ifdef PMAP_MAP_POOLPAGE
506 use_std = 1;
507 #endif
508
509 buf_cache = pool_cache_init(sizeof(buf_t), 0, 0, 0,
510 "bufpl", NULL, IPL_SOFTBIO, NULL, NULL, NULL);
511 bufio_cache = pool_cache_init(sizeof(buf_t), 0, 0, 0,
512 "biopl", NULL, IPL_BIO, NULL, NULL, NULL);
513
514 for (i = 0; i < NMEMPOOLS; i++) {
515 struct pool_allocator *pa;
516 struct pool *pp = &bmempools[i];
517 u_int size = 1 << (i + MEMPOOL_INDEX_OFFSET);
518 char *name = kmem_alloc(8, KM_SLEEP); /* XXX: never freed */
519 if (__predict_false(size >= 1048576))
520 (void)snprintf(name, 8, "buf%um", size / 1048576);
521 else if (__predict_true(size >= 1024))
522 (void)snprintf(name, 8, "buf%uk", size / 1024);
523 else
524 (void)snprintf(name, 8, "buf%ub", size);
525 pa = (size <= PAGE_SIZE && use_std)
526 ? &pool_allocator_nointr
527 : &bufmempool_allocator;
528 pool_init(pp, size, 0, 0, 0, name, pa, IPL_NONE);
529 pool_setlowat(pp, 1);
530 pool_sethiwat(pp, 1);
531 }
532
533 /* Initialize the buffer queues */
534 for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++) {
535 TAILQ_INIT(&dp->bq_queue);
536 dp->bq_bytes = 0;
537 }
538
539 /*
540 * Estimate hash table size based on the amount of memory we
541 * intend to use for the buffer cache. The average buffer
542 * size is dependent on our clients (i.e. filesystems).
543 *
544 * For now, use an empirical 3K per buffer.
545 */
546 nbuf = (bufmem_hiwater / 1024) / 3;
547 bufhashtbl = hashinit(nbuf, HASH_LIST, true, &bufhash);
548
549 sysctl_kern_buf_setup();
550 sysctl_vm_buf_setup();
551 }
552
553 void
554 bufinit2(void)
555 {
556
557 biodone_sih = softint_establish(SOFTINT_BIO | SOFTINT_MPSAFE, biointr,
558 NULL);
559 if (biodone_sih == NULL)
560 panic("bufinit2: can't establish soft interrupt");
561 }
562
563 static int
564 buf_lotsfree(void)
565 {
566 u_long guess;
567
568 /* Always allocate if less than the low water mark. */
569 if (bufmem < bufmem_lowater)
570 return 1;
571
572 /* Never allocate if greater than the high water mark. */
573 if (bufmem > bufmem_hiwater)
574 return 0;
575
576 /* If there's anything on the AGE list, it should be eaten. */
577 if (TAILQ_FIRST(&bufqueues[BQ_AGE].bq_queue) != NULL)
578 return 0;
579
580 /*
581 * The probabily of getting a new allocation is inversely
582 * proportional to the current size of the cache above
583 * the low water mark. Divide the total first to avoid overflows
584 * in the product.
585 */
586 guess = cprng_fast32() % 16;
587
588 if ((bufmem_hiwater - bufmem_lowater) / 16 * guess >=
589 (bufmem - bufmem_lowater))
590 return 1;
591
592 /* Otherwise don't allocate. */
593 return 0;
594 }
595
596 /*
597 * Return estimate of bytes we think need to be
598 * released to help resolve low memory conditions.
599 *
600 * => called with bufcache_lock held.
601 */
602 static int
603 buf_canrelease(void)
604 {
605 int pagedemand, ninvalid = 0;
606
607 KASSERT(mutex_owned(&bufcache_lock));
608
609 if (bufmem < bufmem_lowater)
610 return 0;
611
612 if (bufmem > bufmem_hiwater)
613 return bufmem - bufmem_hiwater;
614
615 ninvalid += bufqueues[BQ_AGE].bq_bytes;
616
617 pagedemand = uvmexp.freetarg - uvm_free();
618 if (pagedemand < 0)
619 return ninvalid;
620 return MAX(ninvalid, MIN(2 * MAXBSIZE,
621 MIN((bufmem - bufmem_lowater) / 16, pagedemand * PAGE_SIZE)));
622 }
623
624 /*
625 * Buffer memory allocation helper functions
626 */
627 static u_long
628 buf_mempoolidx(u_long size)
629 {
630 u_int n = 0;
631
632 size -= 1;
633 size >>= MEMPOOL_INDEX_OFFSET;
634 while (size) {
635 size >>= 1;
636 n += 1;
637 }
638 if (n >= NMEMPOOLS)
639 panic("buf mem pool index %d", n);
640 return n;
641 }
642
643 static u_long
644 buf_roundsize(u_long size)
645 {
646 /* Round up to nearest power of 2 */
647 return (1 << (buf_mempoolidx(size) + MEMPOOL_INDEX_OFFSET));
648 }
649
650 static void *
651 buf_alloc(size_t size)
652 {
653 u_int n = buf_mempoolidx(size);
654 void *addr;
655
656 while (1) {
657 addr = pool_get(&bmempools[n], PR_NOWAIT);
658 if (addr != NULL)
659 break;
660
661 /* No memory, see if we can free some. If so, try again */
662 mutex_enter(&bufcache_lock);
663 if (buf_drain(1) > 0) {
664 mutex_exit(&bufcache_lock);
665 continue;
666 }
667
668 if (curlwp == uvm.pagedaemon_lwp) {
669 mutex_exit(&bufcache_lock);
670 return NULL;
671 }
672
673 /* Wait for buffers to arrive on the LRU queue */
674 cv_timedwait(&needbuffer_cv, &bufcache_lock, hz / 4);
675 mutex_exit(&bufcache_lock);
676 }
677
678 return addr;
679 }
680
681 static void
682 buf_mrelease(void *addr, size_t size)
683 {
684
685 pool_put(&bmempools[buf_mempoolidx(size)], addr);
686 }
687
688 /*
689 * bread()/breadn() helper.
690 */
691 static buf_t *
692 bio_doread(struct vnode *vp, daddr_t blkno, int size, int async)
693 {
694 buf_t *bp;
695 struct mount *mp;
696
697 bp = getblk(vp, blkno, size, 0, 0);
698
699 /*
700 * getblk() may return NULL if we are the pagedaemon.
701 */
702 if (bp == NULL) {
703 KASSERT(curlwp == uvm.pagedaemon_lwp);
704 return NULL;
705 }
706
707 /*
708 * If buffer does not have data valid, start a read.
709 * Note that if buffer is BC_INVAL, getblk() won't return it.
710 * Therefore, it's valid if its I/O has completed or been delayed.
711 */
712 if (!ISSET(bp->b_oflags, (BO_DONE | BO_DELWRI))) {
713 /* Start I/O for the buffer. */
714 SET(bp->b_flags, B_READ | async);
715 if (async)
716 BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
717 else
718 BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
719 VOP_STRATEGY(vp, bp);
720
721 /* Pay for the read. */
722 curlwp->l_ru.ru_inblock++;
723 } else if (async)
724 brelse(bp, 0);
725
726 if (vp->v_type == VBLK)
727 mp = spec_node_getmountedfs(vp);
728 else
729 mp = vp->v_mount;
730
731 /*
732 * Collect statistics on synchronous and asynchronous reads.
733 * Reads from block devices are charged to their associated
734 * filesystem (if any).
735 */
736 if (mp != NULL) {
737 if (async == 0)
738 mp->mnt_stat.f_syncreads++;
739 else
740 mp->mnt_stat.f_asyncreads++;
741 }
742
743 return (bp);
744 }
745
746 /*
747 * Read a disk block.
748 * This algorithm described in Bach (p.54).
749 */
750 int
751 bread(struct vnode *vp, daddr_t blkno, int size, int flags, buf_t **bpp)
752 {
753 buf_t *bp;
754 int error;
755
756 BIOHIST_FUNC(__func__); BIOHIST_CALLED(biohist);
757
758 /* Get buffer for block. */
759 bp = *bpp = bio_doread(vp, blkno, size, 0);
760 if (bp == NULL)
761 return ENOMEM;
762
763 /* Wait for the read to complete, and return result. */
764 error = biowait(bp);
765 if (error == 0 && (flags & B_MODIFY) != 0)
766 error = fscow_run(bp, true);
767 if (error) {
768 brelse(bp, 0);
769 *bpp = NULL;
770 }
771
772 return error;
773 }
774
775 /*
776 * Read-ahead multiple disk blocks. The first is sync, the rest async.
777 * Trivial modification to the breada algorithm presented in Bach (p.55).
778 */
779 int
780 breadn(struct vnode *vp, daddr_t blkno, int size, daddr_t *rablks,
781 int *rasizes, int nrablks, int flags, buf_t **bpp)
782 {
783 buf_t *bp;
784 int error, i;
785
786 BIOHIST_FUNC(__func__); BIOHIST_CALLED(biohist);
787
788 bp = *bpp = bio_doread(vp, blkno, size, 0);
789 if (bp == NULL)
790 return ENOMEM;
791
792 /*
793 * For each of the read-ahead blocks, start a read, if necessary.
794 */
795 mutex_enter(&bufcache_lock);
796 for (i = 0; i < nrablks; i++) {
797 /* If it's in the cache, just go on to next one. */
798 if (incore(vp, rablks[i]))
799 continue;
800
801 /* Get a buffer for the read-ahead block */
802 mutex_exit(&bufcache_lock);
803 (void) bio_doread(vp, rablks[i], rasizes[i], B_ASYNC);
804 mutex_enter(&bufcache_lock);
805 }
806 mutex_exit(&bufcache_lock);
807
808 /* Otherwise, we had to start a read for it; wait until it's valid. */
809 error = biowait(bp);
810 if (error == 0 && (flags & B_MODIFY) != 0)
811 error = fscow_run(bp, true);
812 if (error) {
813 brelse(bp, 0);
814 *bpp = NULL;
815 }
816
817 return error;
818 }
819
820 /*
821 * Block write. Described in Bach (p.56)
822 */
823 int
824 bwrite(buf_t *bp)
825 {
826 int rv, sync, wasdelayed;
827 struct vnode *vp;
828 struct mount *mp;
829
830 BIOHIST_FUNC(__func__); BIOHIST_CALLARGS(biohist, "bp=%#jx",
831 (uintptr_t)bp, 0, 0, 0);
832
833 KASSERT(ISSET(bp->b_cflags, BC_BUSY));
834 KASSERT(!cv_has_waiters(&bp->b_done));
835
836 vp = bp->b_vp;
837
838 /*
839 * dholland 20160728 AFAICT vp==NULL must be impossible as it
840 * will crash upon reaching VOP_STRATEGY below... see further
841 * analysis on tech-kern.
842 */
843 KASSERTMSG(vp != NULL, "bwrite given buffer with null vnode");
844
845 if (vp != NULL) {
846 KASSERT(bp->b_objlock == vp->v_interlock);
847 if (vp->v_type == VBLK)
848 mp = spec_node_getmountedfs(vp);
849 else
850 mp = vp->v_mount;
851 } else {
852 mp = NULL;
853 }
854
855 if (mp && mp->mnt_wapbl) {
856 if (bp->b_iodone != mp->mnt_wapbl_op->wo_wapbl_biodone) {
857 bdwrite(bp);
858 return 0;
859 }
860 }
861
862 /*
863 * Remember buffer type, to switch on it later. If the write was
864 * synchronous, but the file system was mounted with MNT_ASYNC,
865 * convert it to a delayed write.
866 * XXX note that this relies on delayed tape writes being converted
867 * to async, not sync writes (which is safe, but ugly).
868 */
869 sync = !ISSET(bp->b_flags, B_ASYNC);
870 if (sync && mp != NULL && ISSET(mp->mnt_flag, MNT_ASYNC)) {
871 bdwrite(bp);
872 return (0);
873 }
874
875 /*
876 * Collect statistics on synchronous and asynchronous writes.
877 * Writes to block devices are charged to their associated
878 * filesystem (if any).
879 */
880 if (mp != NULL) {
881 if (sync)
882 mp->mnt_stat.f_syncwrites++;
883 else
884 mp->mnt_stat.f_asyncwrites++;
885 }
886
887 /*
888 * Pay for the I/O operation and make sure the buf is on the correct
889 * vnode queue.
890 */
891 bp->b_error = 0;
892 wasdelayed = ISSET(bp->b_oflags, BO_DELWRI);
893 CLR(bp->b_flags, B_READ);
894 if (wasdelayed) {
895 mutex_enter(&bufcache_lock);
896 mutex_enter(bp->b_objlock);
897 CLR(bp->b_oflags, BO_DONE | BO_DELWRI);
898 reassignbuf(bp, bp->b_vp);
899 /* Wake anyone trying to busy the buffer via vnode's lists. */
900 cv_broadcast(&bp->b_busy);
901 mutex_exit(&bufcache_lock);
902 } else {
903 curlwp->l_ru.ru_oublock++;
904 mutex_enter(bp->b_objlock);
905 CLR(bp->b_oflags, BO_DONE | BO_DELWRI);
906 }
907 if (vp != NULL)
908 vp->v_numoutput++;
909 mutex_exit(bp->b_objlock);
910
911 /* Initiate disk write. */
912 if (sync)
913 BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
914 else
915 BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
916
917 VOP_STRATEGY(vp, bp);
918
919 if (sync) {
920 /* If I/O was synchronous, wait for it to complete. */
921 rv = biowait(bp);
922
923 /* Release the buffer. */
924 brelse(bp, 0);
925
926 return (rv);
927 } else {
928 return (0);
929 }
930 }
931
932 int
933 vn_bwrite(void *v)
934 {
935 struct vop_bwrite_args *ap = v;
936
937 return (bwrite(ap->a_bp));
938 }
939
940 /*
941 * Delayed write.
942 *
943 * The buffer is marked dirty, but is not queued for I/O.
944 * This routine should be used when the buffer is expected
945 * to be modified again soon, typically a small write that
946 * partially fills a buffer.
947 *
948 * NB: magnetic tapes cannot be delayed; they must be
949 * written in the order that the writes are requested.
950 *
951 * Described in Leffler, et al. (pp. 208-213).
952 */
953 void
954 bdwrite(buf_t *bp)
955 {
956
957 BIOHIST_FUNC(__func__); BIOHIST_CALLARGS(biohist, "bp=%#jx",
958 (uintptr_t)bp, 0, 0, 0);
959
960 KASSERT(bp->b_vp == NULL || bp->b_vp->v_tag != VT_UFS ||
961 bp->b_vp->v_type == VBLK || ISSET(bp->b_flags, B_COWDONE));
962 KASSERT(ISSET(bp->b_cflags, BC_BUSY));
963 KASSERT(!cv_has_waiters(&bp->b_done));
964
965 /* If this is a tape block, write the block now. */
966 if (bdev_type(bp->b_dev) == D_TAPE) {
967 bawrite(bp);
968 return;
969 }
970
971 if (wapbl_vphaswapbl(bp->b_vp)) {
972 struct mount *mp = wapbl_vptomp(bp->b_vp);
973
974 if (bp->b_iodone != mp->mnt_wapbl_op->wo_wapbl_biodone) {
975 WAPBL_ADD_BUF(mp, bp);
976 }
977 }
978
979 /*
980 * If the block hasn't been seen before:
981 * (1) Mark it as having been seen,
982 * (2) Charge for the write,
983 * (3) Make sure it's on its vnode's correct block list.
984 */
985 KASSERT(bp->b_vp == NULL || bp->b_objlock == bp->b_vp->v_interlock);
986
987 if (!ISSET(bp->b_oflags, BO_DELWRI)) {
988 mutex_enter(&bufcache_lock);
989 mutex_enter(bp->b_objlock);
990 SET(bp->b_oflags, BO_DELWRI);
991 curlwp->l_ru.ru_oublock++;
992 reassignbuf(bp, bp->b_vp);
993 /* Wake anyone trying to busy the buffer via vnode's lists. */
994 cv_broadcast(&bp->b_busy);
995 mutex_exit(&bufcache_lock);
996 } else {
997 mutex_enter(bp->b_objlock);
998 }
999 /* Otherwise, the "write" is done, so mark and release the buffer. */
1000 CLR(bp->b_oflags, BO_DONE);
1001 mutex_exit(bp->b_objlock);
1002
1003 brelse(bp, 0);
1004 }
1005
1006 /*
1007 * Asynchronous block write; just an asynchronous bwrite().
1008 */
1009 void
1010 bawrite(buf_t *bp)
1011 {
1012
1013 KASSERT(ISSET(bp->b_cflags, BC_BUSY));
1014 KASSERT(bp->b_vp != NULL);
1015
1016 SET(bp->b_flags, B_ASYNC);
1017 VOP_BWRITE(bp->b_vp, bp);
1018 }
1019
1020 /*
1021 * Release a buffer on to the free lists.
1022 * Described in Bach (p. 46).
1023 */
1024 void
1025 brelsel(buf_t *bp, int set)
1026 {
1027 struct bqueue *bufq;
1028 struct vnode *vp;
1029
1030 KASSERT(bp != NULL);
1031 KASSERT(mutex_owned(&bufcache_lock));
1032 KASSERT(!cv_has_waiters(&bp->b_done));
1033 KASSERT(bp->b_refcnt > 0);
1034
1035 SET(bp->b_cflags, set);
1036
1037 KASSERT(ISSET(bp->b_cflags, BC_BUSY));
1038 KASSERT(bp->b_iodone == NULL);
1039
1040 /* Wake up any processes waiting for any buffer to become free. */
1041 cv_signal(&needbuffer_cv);
1042
1043 /* Wake up any proceeses waiting for _this_ buffer to become free */
1044 if (ISSET(bp->b_cflags, BC_WANTED))
1045 CLR(bp->b_cflags, BC_WANTED|BC_AGE);
1046
1047 /* If it's clean clear the copy-on-write flag. */
1048 if (ISSET(bp->b_flags, B_COWDONE)) {
1049 mutex_enter(bp->b_objlock);
1050 if (!ISSET(bp->b_oflags, BO_DELWRI))
1051 CLR(bp->b_flags, B_COWDONE);
1052 mutex_exit(bp->b_objlock);
1053 }
1054
1055 /*
1056 * Determine which queue the buffer should be on, then put it there.
1057 */
1058
1059 /* If it's locked, don't report an error; try again later. */
1060 if (ISSET(bp->b_flags, B_LOCKED))
1061 bp->b_error = 0;
1062
1063 /* If it's not cacheable, or an error, mark it invalid. */
1064 if (ISSET(bp->b_cflags, BC_NOCACHE) || bp->b_error != 0)
1065 SET(bp->b_cflags, BC_INVAL);
1066
1067 if (ISSET(bp->b_cflags, BC_VFLUSH)) {
1068 /*
1069 * This is a delayed write buffer that was just flushed to
1070 * disk. It is still on the LRU queue. If it's become
1071 * invalid, then we need to move it to a different queue;
1072 * otherwise leave it in its current position.
1073 */
1074 CLR(bp->b_cflags, BC_VFLUSH);
1075 if (!ISSET(bp->b_cflags, BC_INVAL|BC_AGE) &&
1076 !ISSET(bp->b_flags, B_LOCKED) && bp->b_error == 0) {
1077 KDASSERT(checkfreelist(bp, &bufqueues[BQ_LRU], 1));
1078 goto already_queued;
1079 } else {
1080 bremfree(bp);
1081 }
1082 }
1083
1084 KDASSERT(checkfreelist(bp, &bufqueues[BQ_AGE], 0));
1085 KDASSERT(checkfreelist(bp, &bufqueues[BQ_LRU], 0));
1086 KDASSERT(checkfreelist(bp, &bufqueues[BQ_LOCKED], 0));
1087
1088 if ((bp->b_bufsize <= 0) || ISSET(bp->b_cflags, BC_INVAL)) {
1089 /*
1090 * If it's invalid or empty, dissociate it from its vnode
1091 * and put on the head of the appropriate queue.
1092 */
1093 if (ISSET(bp->b_flags, B_LOCKED)) {
1094 if (wapbl_vphaswapbl(vp = bp->b_vp)) {
1095 struct mount *mp = wapbl_vptomp(vp);
1096
1097 KASSERT(bp->b_iodone
1098 != mp->mnt_wapbl_op->wo_wapbl_biodone);
1099 WAPBL_REMOVE_BUF(mp, bp);
1100 }
1101 }
1102
1103 mutex_enter(bp->b_objlock);
1104 CLR(bp->b_oflags, BO_DONE|BO_DELWRI);
1105 if ((vp = bp->b_vp) != NULL) {
1106 KASSERT(bp->b_objlock == vp->v_interlock);
1107 reassignbuf(bp, bp->b_vp);
1108 brelvp(bp);
1109 mutex_exit(vp->v_interlock);
1110 } else {
1111 KASSERT(bp->b_objlock == &buffer_lock);
1112 mutex_exit(bp->b_objlock);
1113 }
1114 /* We want to dispose of the buffer, so wake everybody. */
1115 cv_broadcast(&bp->b_busy);
1116 if (bp->b_bufsize <= 0)
1117 /* no data */
1118 goto already_queued;
1119 else
1120 /* invalid data */
1121 bufq = &bufqueues[BQ_AGE];
1122 binsheadfree(bp, bufq);
1123 } else {
1124 /*
1125 * It has valid data. Put it on the end of the appropriate
1126 * queue, so that it'll stick around for as long as possible.
1127 * If buf is AGE, but has dependencies, must put it on last
1128 * bufqueue to be scanned, ie LRU. This protects against the
1129 * livelock where BQ_AGE only has buffers with dependencies,
1130 * and we thus never get to the dependent buffers in BQ_LRU.
1131 */
1132 if (ISSET(bp->b_flags, B_LOCKED)) {
1133 /* locked in core */
1134 bufq = &bufqueues[BQ_LOCKED];
1135 } else if (!ISSET(bp->b_cflags, BC_AGE)) {
1136 /* valid data */
1137 bufq = &bufqueues[BQ_LRU];
1138 } else {
1139 /* stale but valid data */
1140 bufq = &bufqueues[BQ_AGE];
1141 }
1142 binstailfree(bp, bufq);
1143 }
1144 already_queued:
1145 /* Unlock the buffer. */
1146 CLR(bp->b_cflags, BC_AGE|BC_BUSY|BC_NOCACHE);
1147 CLR(bp->b_flags, B_ASYNC);
1148
1149 /*
1150 * Wake only the highest priority waiter on the lock, in order to
1151 * prevent a thundering herd: many LWPs simultaneously awakening and
1152 * competing for the buffer's lock. Testing in 2019 revealed this
1153 * to reduce contention on bufcache_lock tenfold during a kernel
1154 * compile. Elsewhere, when the buffer is changing identity, being
1155 * disposed of, or moving from one list to another, we wake all lock
1156 * requestors.
1157 */
1158 cv_signal(&bp->b_busy);
1159
1160 if (bp->b_bufsize <= 0)
1161 brele(bp);
1162 }
1163
1164 void
1165 brelse(buf_t *bp, int set)
1166 {
1167
1168 mutex_enter(&bufcache_lock);
1169 brelsel(bp, set);
1170 mutex_exit(&bufcache_lock);
1171 }
1172
1173 /*
1174 * Determine if a block is in the cache.
1175 * Just look on what would be its hash chain. If it's there, return
1176 * a pointer to it, unless it's marked invalid. If it's marked invalid,
1177 * we normally don't return the buffer, unless the caller explicitly
1178 * wants us to.
1179 */
1180 buf_t *
1181 incore(struct vnode *vp, daddr_t blkno)
1182 {
1183 buf_t *bp;
1184
1185 KASSERT(mutex_owned(&bufcache_lock));
1186
1187 /* Search hash chain */
1188 LIST_FOREACH(bp, BUFHASH(vp, blkno), b_hash) {
1189 if (bp->b_lblkno == blkno && bp->b_vp == vp &&
1190 !ISSET(bp->b_cflags, BC_INVAL)) {
1191 KASSERT(bp->b_objlock == vp->v_interlock);
1192 return (bp);
1193 }
1194 }
1195
1196 return (NULL);
1197 }
1198
1199 /*
1200 * Get a block of requested size that is associated with
1201 * a given vnode and block offset. If it is found in the
1202 * block cache, mark it as having been found, make it busy
1203 * and return it. Otherwise, return an empty block of the
1204 * correct size. It is up to the caller to insure that the
1205 * cached blocks be of the correct size.
1206 */
1207 buf_t *
1208 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo)
1209 {
1210 int err, preserve;
1211 buf_t *bp;
1212
1213 mutex_enter(&bufcache_lock);
1214 loop:
1215 bp = incore(vp, blkno);
1216 if (bp != NULL) {
1217 err = bbusy(bp, ((slpflag & PCATCH) != 0), slptimeo, NULL);
1218 if (err != 0) {
1219 if (err == EPASSTHROUGH)
1220 goto loop;
1221 mutex_exit(&bufcache_lock);
1222 return (NULL);
1223 }
1224 KASSERT(!cv_has_waiters(&bp->b_done));
1225 #ifdef DIAGNOSTIC
1226 if (ISSET(bp->b_oflags, BO_DONE|BO_DELWRI) &&
1227 bp->b_bcount < size && vp->v_type != VBLK)
1228 panic("getblk: block size invariant failed");
1229 #endif
1230 bremfree(bp);
1231 preserve = 1;
1232 } else {
1233 if ((bp = getnewbuf(slpflag, slptimeo, 0)) == NULL)
1234 goto loop;
1235
1236 if (incore(vp, blkno) != NULL) {
1237 /* The block has come into memory in the meantime. */
1238 brelsel(bp, 0);
1239 goto loop;
1240 }
1241
1242 LIST_INSERT_HEAD(BUFHASH(vp, blkno), bp, b_hash);
1243 bp->b_blkno = bp->b_lblkno = bp->b_rawblkno = blkno;
1244 mutex_enter(vp->v_interlock);
1245 bgetvp(vp, bp);
1246 mutex_exit(vp->v_interlock);
1247 preserve = 0;
1248 }
1249 mutex_exit(&bufcache_lock);
1250
1251 /*
1252 * LFS can't track total size of B_LOCKED buffer (locked_queue_bytes)
1253 * if we re-size buffers here.
1254 */
1255 if (ISSET(bp->b_flags, B_LOCKED)) {
1256 KASSERT(bp->b_bufsize >= size);
1257 } else {
1258 if (allocbuf(bp, size, preserve)) {
1259 mutex_enter(&bufcache_lock);
1260 LIST_REMOVE(bp, b_hash);
1261 brelsel(bp, BC_INVAL);
1262 mutex_exit(&bufcache_lock);
1263 return NULL;
1264 }
1265 }
1266 BIO_SETPRIO(bp, BPRIO_DEFAULT);
1267 return (bp);
1268 }
1269
1270 /*
1271 * Get an empty, disassociated buffer of given size.
1272 */
1273 buf_t *
1274 geteblk(int size)
1275 {
1276 buf_t *bp;
1277 int error __diagused;
1278
1279 mutex_enter(&bufcache_lock);
1280 while ((bp = getnewbuf(0, 0, 0)) == NULL)
1281 ;
1282
1283 SET(bp->b_cflags, BC_INVAL);
1284 LIST_INSERT_HEAD(&invalhash, bp, b_hash);
1285 mutex_exit(&bufcache_lock);
1286 BIO_SETPRIO(bp, BPRIO_DEFAULT);
1287 error = allocbuf(bp, size, 0);
1288 KASSERT(error == 0);
1289 return (bp);
1290 }
1291
1292 /*
1293 * Expand or contract the actual memory allocated to a buffer.
1294 *
1295 * If the buffer shrinks, data is lost, so it's up to the
1296 * caller to have written it out *first*; this routine will not
1297 * start a write. If the buffer grows, it's the callers
1298 * responsibility to fill out the buffer's additional contents.
1299 */
1300 int
1301 allocbuf(buf_t *bp, int size, int preserve)
1302 {
1303 void *addr;
1304 vsize_t oldsize, desired_size;
1305 int oldcount;
1306 int delta;
1307
1308 desired_size = buf_roundsize(size);
1309 if (desired_size > MAXBSIZE)
1310 printf("allocbuf: buffer larger than MAXBSIZE requested");
1311
1312 oldcount = bp->b_bcount;
1313
1314 bp->b_bcount = size;
1315
1316 oldsize = bp->b_bufsize;
1317 if (oldsize == desired_size) {
1318 /*
1319 * Do not short cut the WAPBL resize, as the buffer length
1320 * could still have changed and this would corrupt the
1321 * tracking of the transaction length.
1322 */
1323 goto out;
1324 }
1325
1326 /*
1327 * If we want a buffer of a different size, re-allocate the
1328 * buffer's memory; copy old content only if needed.
1329 */
1330 addr = buf_alloc(desired_size);
1331 if (addr == NULL)
1332 return ENOMEM;
1333 if (preserve)
1334 memcpy(addr, bp->b_data, MIN(oldsize,desired_size));
1335 if (bp->b_data != NULL)
1336 buf_mrelease(bp->b_data, oldsize);
1337 bp->b_data = addr;
1338 bp->b_bufsize = desired_size;
1339
1340 /*
1341 * Update overall buffer memory counter (protected by bufcache_lock)
1342 */
1343 delta = (long)desired_size - (long)oldsize;
1344
1345 mutex_enter(&bufcache_lock);
1346 if ((bufmem += delta) > bufmem_hiwater) {
1347 /*
1348 * Need to trim overall memory usage.
1349 */
1350 while (buf_canrelease()) {
1351 if (curcpu()->ci_schedstate.spc_flags &
1352 SPCF_SHOULDYIELD) {
1353 mutex_exit(&bufcache_lock);
1354 preempt();
1355 mutex_enter(&bufcache_lock);
1356 }
1357 if (buf_trim() == 0)
1358 break;
1359 }
1360 }
1361 mutex_exit(&bufcache_lock);
1362
1363 out:
1364 if (wapbl_vphaswapbl(bp->b_vp))
1365 WAPBL_RESIZE_BUF(wapbl_vptomp(bp->b_vp), bp, oldsize, oldcount);
1366
1367 return 0;
1368 }
1369
1370 /*
1371 * Find a buffer which is available for use.
1372 * Select something from a free list.
1373 * Preference is to AGE list, then LRU list.
1374 *
1375 * Called with the buffer queues locked.
1376 * Return buffer locked.
1377 */
1378 static buf_t *
1379 getnewbuf(int slpflag, int slptimeo, int from_bufq)
1380 {
1381 buf_t *bp;
1382 struct vnode *vp;
1383 struct mount *transmp = NULL;
1384
1385 start:
1386 KASSERT(mutex_owned(&bufcache_lock));
1387
1388 /*
1389 * Get a new buffer from the pool.
1390 */
1391 if (!from_bufq && buf_lotsfree()) {
1392 mutex_exit(&bufcache_lock);
1393 bp = pool_cache_get(buf_cache, PR_NOWAIT);
1394 if (bp != NULL) {
1395 memset((char *)bp, 0, sizeof(*bp));
1396 buf_init(bp);
1397 SET(bp->b_cflags, BC_BUSY); /* mark buffer busy */
1398 mutex_enter(&bufcache_lock);
1399 #if defined(DIAGNOSTIC)
1400 bp->b_freelistindex = -1;
1401 #endif /* defined(DIAGNOSTIC) */
1402 return (bp);
1403 }
1404 mutex_enter(&bufcache_lock);
1405 }
1406
1407 KASSERT(mutex_owned(&bufcache_lock));
1408 if ((bp = TAILQ_FIRST(&bufqueues[BQ_AGE].bq_queue)) != NULL) {
1409 KASSERT(!ISSET(bp->b_oflags, BO_DELWRI));
1410 } else {
1411 TAILQ_FOREACH(bp, &bufqueues[BQ_LRU].bq_queue, b_freelist) {
1412 if (ISSET(bp->b_cflags, BC_VFLUSH) ||
1413 !ISSET(bp->b_oflags, BO_DELWRI))
1414 break;
1415 if (fstrans_start_nowait(bp->b_vp->v_mount) == 0) {
1416 KASSERT(transmp == NULL);
1417 transmp = bp->b_vp->v_mount;
1418 break;
1419 }
1420 }
1421 }
1422 if (bp != NULL) {
1423 KASSERT(!ISSET(bp->b_cflags, BC_BUSY) || ISSET(bp->b_cflags, BC_VFLUSH));
1424 bremfree(bp);
1425
1426 /* Buffer is no longer on free lists. */
1427 SET(bp->b_cflags, BC_BUSY);
1428
1429 /* Wake anyone trying to lock the old identity. */
1430 cv_broadcast(&bp->b_busy);
1431 } else {
1432 /*
1433 * XXX: !from_bufq should be removed.
1434 */
1435 if (!from_bufq || curlwp != uvm.pagedaemon_lwp) {
1436 /* wait for a free buffer of any kind */
1437 if ((slpflag & PCATCH) != 0)
1438 (void)cv_timedwait_sig(&needbuffer_cv,
1439 &bufcache_lock, slptimeo);
1440 else
1441 (void)cv_timedwait(&needbuffer_cv,
1442 &bufcache_lock, slptimeo);
1443 }
1444 return (NULL);
1445 }
1446
1447 #ifdef DIAGNOSTIC
1448 if (bp->b_bufsize <= 0)
1449 panic("buffer %p: on queue but empty", bp);
1450 #endif
1451
1452 if (ISSET(bp->b_cflags, BC_VFLUSH)) {
1453 /*
1454 * This is a delayed write buffer being flushed to disk. Make
1455 * sure it gets aged out of the queue when it's finished, and
1456 * leave it off the LRU queue.
1457 */
1458 CLR(bp->b_cflags, BC_VFLUSH);
1459 SET(bp->b_cflags, BC_AGE);
1460 goto start;
1461 }
1462
1463 KASSERT(ISSET(bp->b_cflags, BC_BUSY));
1464 KASSERT(bp->b_refcnt > 0);
1465 KASSERT(!cv_has_waiters(&bp->b_done));
1466
1467 /*
1468 * If buffer was a delayed write, start it and return NULL
1469 * (since we might sleep while starting the write).
1470 */
1471 if (ISSET(bp->b_oflags, BO_DELWRI)) {
1472 /*
1473 * This buffer has gone through the LRU, so make sure it gets
1474 * reused ASAP.
1475 */
1476 SET(bp->b_cflags, BC_AGE);
1477 mutex_exit(&bufcache_lock);
1478 bawrite(bp);
1479 KASSERT(transmp != NULL);
1480 fstrans_done(transmp);
1481 mutex_enter(&bufcache_lock);
1482 return (NULL);
1483 }
1484
1485 KASSERT(transmp == NULL);
1486
1487 vp = bp->b_vp;
1488
1489 /* clear out various other fields */
1490 bp->b_cflags = BC_BUSY;
1491 bp->b_oflags = 0;
1492 bp->b_flags = 0;
1493 bp->b_dev = NODEV;
1494 bp->b_blkno = 0;
1495 bp->b_lblkno = 0;
1496 bp->b_rawblkno = 0;
1497 bp->b_iodone = 0;
1498 bp->b_error = 0;
1499 bp->b_resid = 0;
1500 bp->b_bcount = 0;
1501
1502 LIST_REMOVE(bp, b_hash);
1503
1504 /* Disassociate us from our vnode, if we had one... */
1505 if (vp != NULL) {
1506 mutex_enter(vp->v_interlock);
1507 brelvp(bp);
1508 mutex_exit(vp->v_interlock);
1509 }
1510
1511 return (bp);
1512 }
1513
1514 /*
1515 * Attempt to free an aged buffer off the queues.
1516 * Called with queue lock held.
1517 * Returns the amount of buffer memory freed.
1518 */
1519 static int
1520 buf_trim(void)
1521 {
1522 buf_t *bp;
1523 long size;
1524
1525 KASSERT(mutex_owned(&bufcache_lock));
1526
1527 /* Instruct getnewbuf() to get buffers off the queues */
1528 if ((bp = getnewbuf(PCATCH, 1, 1)) == NULL)
1529 return 0;
1530
1531 KASSERT((bp->b_cflags & BC_WANTED) == 0);
1532 size = bp->b_bufsize;
1533 bufmem -= size;
1534 if (size > 0) {
1535 buf_mrelease(bp->b_data, size);
1536 bp->b_bcount = bp->b_bufsize = 0;
1537 }
1538 /* brelse() will return the buffer to the global buffer pool */
1539 brelsel(bp, 0);
1540 return size;
1541 }
1542
1543 int
1544 buf_drain(int n)
1545 {
1546 int size = 0, sz;
1547
1548 KASSERT(mutex_owned(&bufcache_lock));
1549
1550 while (size < n && bufmem > bufmem_lowater) {
1551 sz = buf_trim();
1552 if (sz <= 0)
1553 break;
1554 size += sz;
1555 }
1556
1557 return size;
1558 }
1559
1560 SDT_PROVIDER_DEFINE(io);
1561
1562 SDT_PROBE_DEFINE1(io, kernel, , wait__start, "struct buf *"/*bp*/);
1563 SDT_PROBE_DEFINE1(io, kernel, , wait__done, "struct buf *"/*bp*/);
1564
1565 /*
1566 * Wait for operations on the buffer to complete.
1567 * When they do, extract and return the I/O's error value.
1568 */
1569 int
1570 biowait(buf_t *bp)
1571 {
1572
1573 BIOHIST_FUNC(__func__);
1574
1575 KASSERT(ISSET(bp->b_cflags, BC_BUSY));
1576 KASSERT(bp->b_refcnt > 0);
1577
1578 SDT_PROBE1(io, kernel, , wait__start, bp);
1579
1580 mutex_enter(bp->b_objlock);
1581
1582 BIOHIST_CALLARGS(biohist, "bp=%#jx, oflags=0x%jx, ret_addr=%#jx",
1583 (uintptr_t)bp, bp->b_oflags,
1584 (uintptr_t)__builtin_return_address(0), 0);
1585
1586 while (!ISSET(bp->b_oflags, BO_DONE | BO_DELWRI)) {
1587 BIOHIST_LOG(biohist, "waiting bp=%#jx", (uintptr_t)bp, 0, 0, 0);
1588 cv_wait(&bp->b_done, bp->b_objlock);
1589 }
1590 mutex_exit(bp->b_objlock);
1591
1592 SDT_PROBE1(io, kernel, , wait__done, bp);
1593
1594 BIOHIST_LOG(biohist, "return %jd", bp->b_error, 0, 0, 0);
1595
1596 return bp->b_error;
1597 }
1598
1599 /*
1600 * Mark I/O complete on a buffer.
1601 *
1602 * If a callback has been requested, e.g. the pageout
1603 * daemon, do so. Otherwise, awaken waiting processes.
1604 *
1605 * [ Leffler, et al., says on p.247:
1606 * "This routine wakes up the blocked process, frees the buffer
1607 * for an asynchronous write, or, for a request by the pagedaemon
1608 * process, invokes a procedure specified in the buffer structure" ]
1609 *
1610 * In real life, the pagedaemon (or other system processes) wants
1611 * to do async stuff too, and doesn't want the buffer brelse()'d.
1612 * (for swap pager, that puts swap buffers on the free lists (!!!),
1613 * for the vn device, that puts allocated buffers on the free lists!)
1614 */
1615 void
1616 biodone(buf_t *bp)
1617 {
1618 int s;
1619
1620 BIOHIST_FUNC(__func__);
1621
1622 KASSERT(!ISSET(bp->b_oflags, BO_DONE));
1623
1624 if (cpu_intr_p()) {
1625 /* From interrupt mode: defer to a soft interrupt. */
1626 s = splvm();
1627 TAILQ_INSERT_TAIL(&curcpu()->ci_data.cpu_biodone, bp, b_actq);
1628
1629 BIOHIST_CALLARGS(biohist, "bp=%#jx, softint scheduled",
1630 (uintptr_t)bp, 0, 0, 0);
1631 softint_schedule(biodone_sih);
1632 splx(s);
1633 } else {
1634 /* Process now - the buffer may be freed soon. */
1635 biodone2(bp);
1636 }
1637 }
1638
1639 SDT_PROBE_DEFINE1(io, kernel, , done, "struct buf *"/*bp*/);
1640
1641 static void
1642 biodone2(buf_t *bp)
1643 {
1644 void (*callout)(buf_t *);
1645
1646 SDT_PROBE1(io, kernel, ,done, bp);
1647
1648 BIOHIST_FUNC(__func__);
1649 BIOHIST_CALLARGS(biohist, "bp=%#jx", (uintptr_t)bp, 0, 0, 0);
1650
1651 mutex_enter(bp->b_objlock);
1652 /* Note that the transfer is done. */
1653 if (ISSET(bp->b_oflags, BO_DONE))
1654 panic("biodone2 already");
1655 CLR(bp->b_flags, B_COWDONE);
1656 SET(bp->b_oflags, BO_DONE);
1657 BIO_SETPRIO(bp, BPRIO_DEFAULT);
1658
1659 /* Wake up waiting writers. */
1660 if (!ISSET(bp->b_flags, B_READ))
1661 vwakeup(bp);
1662
1663 if ((callout = bp->b_iodone) != NULL) {
1664 BIOHIST_LOG(biohist, "callout %#jx", (uintptr_t)callout,
1665 0, 0, 0);
1666
1667 /* Note callout done, then call out. */
1668 KASSERT(!cv_has_waiters(&bp->b_done));
1669 KERNEL_LOCK(1, NULL); /* XXXSMP */
1670 bp->b_iodone = NULL;
1671 mutex_exit(bp->b_objlock);
1672 (*callout)(bp);
1673 KERNEL_UNLOCK_ONE(NULL); /* XXXSMP */
1674 } else if (ISSET(bp->b_flags, B_ASYNC)) {
1675 /* If async, release. */
1676 BIOHIST_LOG(biohist, "async", 0, 0, 0, 0);
1677 KASSERT(!cv_has_waiters(&bp->b_done));
1678 mutex_exit(bp->b_objlock);
1679 brelse(bp, 0);
1680 } else {
1681 /* Otherwise just wake up waiters in biowait(). */
1682 BIOHIST_LOG(biohist, "wake-up", 0, 0, 0, 0);
1683 cv_broadcast(&bp->b_done);
1684 mutex_exit(bp->b_objlock);
1685 }
1686 }
1687
1688 static void
1689 biointr(void *cookie)
1690 {
1691 struct cpu_info *ci;
1692 buf_t *bp;
1693 int s;
1694
1695 BIOHIST_FUNC(__func__); BIOHIST_CALLED(biohist);
1696
1697 ci = curcpu();
1698
1699 s = splvm();
1700 while (!TAILQ_EMPTY(&ci->ci_data.cpu_biodone)) {
1701 KASSERT(curcpu() == ci);
1702
1703 bp = TAILQ_FIRST(&ci->ci_data.cpu_biodone);
1704 TAILQ_REMOVE(&ci->ci_data.cpu_biodone, bp, b_actq);
1705 splx(s);
1706
1707 BIOHIST_LOG(biohist, "bp=%#jx", (uintptr_t)bp, 0, 0, 0);
1708 biodone2(bp);
1709
1710 s = splvm();
1711 }
1712 splx(s);
1713 }
1714
1715 /*
1716 * Wait for all buffers to complete I/O
1717 * Return the number of "stuck" buffers.
1718 */
1719 int
1720 buf_syncwait(void)
1721 {
1722 buf_t *bp;
1723 int iter, nbusy, nbusy_prev = 0, ihash;
1724
1725 BIOHIST_FUNC(__func__); BIOHIST_CALLED(biohist);
1726
1727 for (iter = 0; iter < 20;) {
1728 mutex_enter(&bufcache_lock);
1729 nbusy = 0;
1730 for (ihash = 0; ihash < bufhash+1; ihash++) {
1731 LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
1732 if ((bp->b_cflags & (BC_BUSY|BC_INVAL)) == BC_BUSY)
1733 nbusy += ((bp->b_flags & B_READ) == 0);
1734 }
1735 }
1736 mutex_exit(&bufcache_lock);
1737
1738 if (nbusy == 0)
1739 break;
1740 if (nbusy_prev == 0)
1741 nbusy_prev = nbusy;
1742 printf("%d ", nbusy);
1743 kpause("bflush", false, MAX(1, hz / 25 * iter), NULL);
1744 if (nbusy >= nbusy_prev) /* we didn't flush anything */
1745 iter++;
1746 else
1747 nbusy_prev = nbusy;
1748 }
1749
1750 if (nbusy) {
1751 #if defined(DEBUG) || defined(DEBUG_HALT_BUSY)
1752 printf("giving up\nPrinting vnodes for busy buffers\n");
1753 for (ihash = 0; ihash < bufhash+1; ihash++) {
1754 LIST_FOREACH(bp, &bufhashtbl[ihash], b_hash) {
1755 if ((bp->b_cflags & (BC_BUSY|BC_INVAL)) == BC_BUSY &&
1756 (bp->b_flags & B_READ) == 0)
1757 vprint(NULL, bp->b_vp);
1758 }
1759 }
1760 #endif
1761 }
1762
1763 return nbusy;
1764 }
1765
1766 static void
1767 sysctl_fillbuf(const buf_t *i, struct buf_sysctl *o)
1768 {
1769 const bool allowaddr = get_expose_address(curproc);
1770
1771 memset(o, 0, sizeof(*o));
1772
1773 o->b_flags = i->b_flags | i->b_cflags | i->b_oflags;
1774 o->b_error = i->b_error;
1775 o->b_prio = i->b_prio;
1776 o->b_dev = i->b_dev;
1777 o->b_bufsize = i->b_bufsize;
1778 o->b_bcount = i->b_bcount;
1779 o->b_resid = i->b_resid;
1780 COND_SET_VALUE(o->b_addr, PTRTOUINT64(i->b_data), allowaddr);
1781 o->b_blkno = i->b_blkno;
1782 o->b_rawblkno = i->b_rawblkno;
1783 COND_SET_VALUE(o->b_iodone, PTRTOUINT64(i->b_iodone), allowaddr);
1784 COND_SET_VALUE(o->b_proc, PTRTOUINT64(i->b_proc), allowaddr);
1785 COND_SET_VALUE(o->b_vp, PTRTOUINT64(i->b_vp), allowaddr);
1786 COND_SET_VALUE(o->b_saveaddr, PTRTOUINT64(i->b_saveaddr), allowaddr);
1787 o->b_lblkno = i->b_lblkno;
1788 }
1789
1790 #define KERN_BUFSLOP 20
1791 static int
1792 sysctl_dobuf(SYSCTLFN_ARGS)
1793 {
1794 buf_t *bp;
1795 struct buf_sysctl bs;
1796 struct bqueue *bq;
1797 char *dp;
1798 u_int i, op, arg;
1799 size_t len, needed, elem_size, out_size;
1800 int error, elem_count, retries;
1801
1802 if (namelen == 1 && name[0] == CTL_QUERY)
1803 return (sysctl_query(SYSCTLFN_CALL(rnode)));
1804
1805 if (namelen != 4)
1806 return (EINVAL);
1807
1808 retries = 100;
1809 retry:
1810 dp = oldp;
1811 len = (oldp != NULL) ? *oldlenp : 0;
1812 op = name[0];
1813 arg = name[1];
1814 elem_size = name[2];
1815 elem_count = name[3];
1816 out_size = MIN(sizeof(bs), elem_size);
1817
1818 /*
1819 * at the moment, these are just "placeholders" to make the
1820 * API for retrieving kern.buf data more extensible in the
1821 * future.
1822 *
1823 * XXX kern.buf currently has "netbsd32" issues. hopefully
1824 * these will be resolved at a later point.
1825 */
1826 if (op != KERN_BUF_ALL || arg != KERN_BUF_ALL ||
1827 elem_size < 1 || elem_count < 0)
1828 return (EINVAL);
1829
1830 error = 0;
1831 needed = 0;
1832 sysctl_unlock();
1833 mutex_enter(&bufcache_lock);
1834 for (i = 0; i < BQUEUES; i++) {
1835 bq = &bufqueues[i];
1836 TAILQ_FOREACH(bp, &bq->bq_queue, b_freelist) {
1837 bq->bq_marker = bp;
1838 if (len >= elem_size && elem_count > 0) {
1839 sysctl_fillbuf(bp, &bs);
1840 mutex_exit(&bufcache_lock);
1841 error = copyout(&bs, dp, out_size);
1842 mutex_enter(&bufcache_lock);
1843 if (error)
1844 break;
1845 if (bq->bq_marker != bp) {
1846 /*
1847 * This sysctl node is only for
1848 * statistics. Retry; if the
1849 * queue keeps changing, then
1850 * bail out.
1851 */
1852 if (retries-- == 0) {
1853 error = EAGAIN;
1854 break;
1855 }
1856 mutex_exit(&bufcache_lock);
1857 sysctl_relock();
1858 goto retry;
1859 }
1860 dp += elem_size;
1861 len -= elem_size;
1862 }
1863 needed += elem_size;
1864 if (elem_count > 0 && elem_count != INT_MAX)
1865 elem_count--;
1866 }
1867 if (error != 0)
1868 break;
1869 }
1870 mutex_exit(&bufcache_lock);
1871 sysctl_relock();
1872
1873 *oldlenp = needed;
1874 if (oldp == NULL)
1875 *oldlenp += KERN_BUFSLOP * sizeof(buf_t);
1876
1877 return (error);
1878 }
1879
1880 static int
1881 sysctl_bufvm_update(SYSCTLFN_ARGS)
1882 {
1883 int error, rv;
1884 struct sysctlnode node;
1885 unsigned int temp_bufcache;
1886 unsigned long temp_water;
1887
1888 /* Take a copy of the supplied node and its data */
1889 node = *rnode;
1890 if (node.sysctl_data == &bufcache) {
1891 node.sysctl_data = &temp_bufcache;
1892 temp_bufcache = *(unsigned int *)rnode->sysctl_data;
1893 } else {
1894 node.sysctl_data = &temp_water;
1895 temp_water = *(unsigned long *)rnode->sysctl_data;
1896 }
1897
1898 /* Update the copy */
1899 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1900 if (error || newp == NULL)
1901 return (error);
1902
1903 if (rnode->sysctl_data == &bufcache) {
1904 if (temp_bufcache > 100)
1905 return (EINVAL);
1906 bufcache = temp_bufcache;
1907 buf_setwm();
1908 } else if (rnode->sysctl_data == &bufmem_lowater) {
1909 if (bufmem_hiwater - temp_water < 16)
1910 return (EINVAL);
1911 bufmem_lowater = temp_water;
1912 } else if (rnode->sysctl_data == &bufmem_hiwater) {
1913 if (temp_water - bufmem_lowater < 16)
1914 return (EINVAL);
1915 bufmem_hiwater = temp_water;
1916 } else
1917 return (EINVAL);
1918
1919 /* Drain until below new high water mark */
1920 sysctl_unlock();
1921 mutex_enter(&bufcache_lock);
1922 while (bufmem > bufmem_hiwater) {
1923 rv = buf_drain((bufmem - bufmem_hiwater) / (2 * 1024));
1924 if (rv <= 0)
1925 break;
1926 }
1927 mutex_exit(&bufcache_lock);
1928 sysctl_relock();
1929
1930 return 0;
1931 }
1932
1933 static struct sysctllog *vfsbio_sysctllog;
1934
1935 static void
1936 sysctl_kern_buf_setup(void)
1937 {
1938
1939 sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1940 CTLFLAG_PERMANENT,
1941 CTLTYPE_NODE, "buf",
1942 SYSCTL_DESCR("Kernel buffer cache information"),
1943 sysctl_dobuf, 0, NULL, 0,
1944 CTL_KERN, KERN_BUF, CTL_EOL);
1945 }
1946
1947 static void
1948 sysctl_vm_buf_setup(void)
1949 {
1950
1951 sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1952 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1953 CTLTYPE_INT, "bufcache",
1954 SYSCTL_DESCR("Percentage of physical memory to use for "
1955 "buffer cache"),
1956 sysctl_bufvm_update, 0, &bufcache, 0,
1957 CTL_VM, CTL_CREATE, CTL_EOL);
1958 sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1959 CTLFLAG_PERMANENT|CTLFLAG_READONLY,
1960 CTLTYPE_LONG, "bufmem",
1961 SYSCTL_DESCR("Amount of kernel memory used by buffer "
1962 "cache"),
1963 NULL, 0, &bufmem, 0,
1964 CTL_VM, CTL_CREATE, CTL_EOL);
1965 sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1966 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1967 CTLTYPE_LONG, "bufmem_lowater",
1968 SYSCTL_DESCR("Minimum amount of kernel memory to "
1969 "reserve for buffer cache"),
1970 sysctl_bufvm_update, 0, &bufmem_lowater, 0,
1971 CTL_VM, CTL_CREATE, CTL_EOL);
1972 sysctl_createv(&vfsbio_sysctllog, 0, NULL, NULL,
1973 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1974 CTLTYPE_LONG, "bufmem_hiwater",
1975 SYSCTL_DESCR("Maximum amount of kernel memory to use "
1976 "for buffer cache"),
1977 sysctl_bufvm_update, 0, &bufmem_hiwater, 0,
1978 CTL_VM, CTL_CREATE, CTL_EOL);
1979 }
1980
1981 #ifdef DEBUG
1982 /*
1983 * Print out statistics on the current allocation of the buffer pool.
1984 * Can be enabled to print out on every ``sync'' by setting "syncprt"
1985 * in vfs_syscalls.c using sysctl.
1986 */
1987 void
1988 vfs_bufstats(void)
1989 {
1990 int i, j, count;
1991 buf_t *bp;
1992 struct bqueue *dp;
1993 int counts[MAXBSIZE / MIN_PAGE_SIZE + 1];
1994 static const char *bname[BQUEUES] = { "LOCKED", "LRU", "AGE" };
1995
1996 for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
1997 count = 0;
1998 memset(counts, 0, sizeof(counts));
1999 TAILQ_FOREACH(bp, &dp->bq_queue, b_freelist) {
2000 counts[bp->b_bufsize / PAGE_SIZE]++;
2001 count++;
2002 }
2003 printf("%s: total-%d", bname[i], count);
2004 for (j = 0; j <= MAXBSIZE / PAGE_SIZE; j++)
2005 if (counts[j] != 0)
2006 printf(", %d-%d", j * PAGE_SIZE, counts[j]);
2007 printf("\n");
2008 }
2009 }
2010 #endif /* DEBUG */
2011
2012 /* ------------------------------ */
2013
2014 buf_t *
2015 getiobuf(struct vnode *vp, bool waitok)
2016 {
2017 buf_t *bp;
2018
2019 bp = pool_cache_get(bufio_cache, (waitok ? PR_WAITOK : PR_NOWAIT));
2020 if (bp == NULL)
2021 return bp;
2022
2023 buf_init(bp);
2024
2025 if ((bp->b_vp = vp) != NULL) {
2026 bp->b_objlock = vp->v_interlock;
2027 } else {
2028 KASSERT(bp->b_objlock == &buffer_lock);
2029 }
2030
2031 return bp;
2032 }
2033
2034 void
2035 putiobuf(buf_t *bp)
2036 {
2037
2038 buf_destroy(bp);
2039 pool_cache_put(bufio_cache, bp);
2040 }
2041
2042 /*
2043 * nestiobuf_iodone: b_iodone callback for nested buffers.
2044 */
2045
2046 void
2047 nestiobuf_iodone(buf_t *bp)
2048 {
2049 buf_t *mbp = bp->b_private;
2050 int error;
2051 int donebytes;
2052
2053 KASSERT(bp->b_bcount <= bp->b_bufsize);
2054 KASSERT(mbp != bp);
2055
2056 error = bp->b_error;
2057 if (bp->b_error == 0 &&
2058 (bp->b_bcount < bp->b_bufsize || bp->b_resid > 0)) {
2059 /*
2060 * Not all got transferred, raise an error. We have no way to
2061 * propagate these conditions to mbp.
2062 */
2063 error = EIO;
2064 }
2065
2066 donebytes = bp->b_bufsize;
2067
2068 putiobuf(bp);
2069 nestiobuf_done(mbp, donebytes, error);
2070 }
2071
2072 /*
2073 * nestiobuf_setup: setup a "nested" buffer.
2074 *
2075 * => 'mbp' is a "master" buffer which is being divided into sub pieces.
2076 * => 'bp' should be a buffer allocated by getiobuf.
2077 * => 'offset' is a byte offset in the master buffer.
2078 * => 'size' is a size in bytes of this nested buffer.
2079 */
2080
2081 void
2082 nestiobuf_setup(buf_t *mbp, buf_t *bp, int offset, size_t size)
2083 {
2084 const int b_pass = mbp->b_flags & (B_READ|B_MEDIA_FLAGS);
2085 struct vnode *vp = mbp->b_vp;
2086
2087 KASSERT(mbp->b_bcount >= offset + size);
2088 bp->b_vp = vp;
2089 bp->b_dev = mbp->b_dev;
2090 bp->b_objlock = mbp->b_objlock;
2091 bp->b_cflags = BC_BUSY;
2092 bp->b_flags = B_ASYNC | b_pass;
2093 bp->b_iodone = nestiobuf_iodone;
2094 bp->b_data = (char *)mbp->b_data + offset;
2095 bp->b_resid = bp->b_bcount = size;
2096 bp->b_bufsize = bp->b_bcount;
2097 bp->b_private = mbp;
2098 BIO_COPYPRIO(bp, mbp);
2099 if (BUF_ISWRITE(bp) && vp != NULL) {
2100 mutex_enter(vp->v_interlock);
2101 vp->v_numoutput++;
2102 mutex_exit(vp->v_interlock);
2103 }
2104 }
2105
2106 /*
2107 * nestiobuf_done: propagate completion to the master buffer.
2108 *
2109 * => 'donebytes' specifies how many bytes in the 'mbp' is completed.
2110 * => 'error' is an errno(2) that 'donebytes' has been completed with.
2111 */
2112
2113 void
2114 nestiobuf_done(buf_t *mbp, int donebytes, int error)
2115 {
2116
2117 if (donebytes == 0) {
2118 return;
2119 }
2120 mutex_enter(mbp->b_objlock);
2121 KASSERT(mbp->b_resid >= donebytes);
2122 mbp->b_resid -= donebytes;
2123 if (error)
2124 mbp->b_error = error;
2125 if (mbp->b_resid == 0) {
2126 if (mbp->b_error)
2127 mbp->b_resid = mbp->b_bcount;
2128 mutex_exit(mbp->b_objlock);
2129 biodone(mbp);
2130 } else
2131 mutex_exit(mbp->b_objlock);
2132 }
2133
2134 void
2135 buf_init(buf_t *bp)
2136 {
2137
2138 cv_init(&bp->b_busy, "biolock");
2139 cv_init(&bp->b_done, "biowait");
2140 bp->b_dev = NODEV;
2141 bp->b_error = 0;
2142 bp->b_flags = 0;
2143 bp->b_cflags = 0;
2144 bp->b_oflags = 0;
2145 bp->b_objlock = &buffer_lock;
2146 bp->b_iodone = NULL;
2147 bp->b_refcnt = 1;
2148 bp->b_dev = NODEV;
2149 bp->b_vnbufs.le_next = NOLIST;
2150 BIO_SETPRIO(bp, BPRIO_DEFAULT);
2151 }
2152
2153 void
2154 buf_destroy(buf_t *bp)
2155 {
2156
2157 cv_destroy(&bp->b_done);
2158 cv_destroy(&bp->b_busy);
2159 }
2160
2161 int
2162 bbusy(buf_t *bp, bool intr, int timo, kmutex_t *interlock)
2163 {
2164 int error;
2165
2166 KASSERT(mutex_owned(&bufcache_lock));
2167
2168 if ((bp->b_cflags & BC_BUSY) != 0) {
2169 if (curlwp == uvm.pagedaemon_lwp)
2170 return EDEADLK;
2171 bp->b_cflags |= BC_WANTED;
2172 bref(bp);
2173 if (interlock != NULL)
2174 mutex_exit(interlock);
2175 if (intr) {
2176 error = cv_timedwait_sig(&bp->b_busy, &bufcache_lock,
2177 timo);
2178 } else {
2179 error = cv_timedwait(&bp->b_busy, &bufcache_lock,
2180 timo);
2181 }
2182 brele(bp);
2183 if (interlock != NULL)
2184 mutex_enter(interlock);
2185 if (error != 0)
2186 return error;
2187 return EPASSTHROUGH;
2188 }
2189 bp->b_cflags |= BC_BUSY;
2190
2191 return 0;
2192 }
2193
2194 /*
2195 * Nothing outside this file should really need to know about nbuf,
2196 * but a few things still want to read it, so give them a way to do that.
2197 */
2198 u_int
2199 buf_nbuf(void)
2200 {
2201
2202 return nbuf;
2203 }
2204