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