xref: /openbsd-src/sys/kern/vfs_bio.c (revision 4b70baf6e17fc8b27fc1f7fa7929335753fa94c3)
1 /*	$OpenBSD: vfs_bio.c,v 1.188 2019/02/17 22:17:28 tedu Exp $	*/
2 /*	$NetBSD: vfs_bio.c,v 1.44 1996/06/11 11:15:36 pk Exp $	*/
3 
4 /*
5  * Copyright (c) 1994 Christopher G. Demetriou
6  * Copyright (c) 1982, 1986, 1989, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  * (c) UNIX System Laboratories, Inc.
9  * All or some portions of this file are derived from material licensed
10  * to the University of California by American Telephone and Telegraph
11  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
12  * the permission of UNIX System Laboratories, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)vfs_bio.c	8.6 (Berkeley) 1/11/94
39  */
40 
41 /*
42  * Some references:
43  *	Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
44  *	Leffler, et al.: The Design and Implementation of the 4.3BSD
45  *		UNIX Operating System (Addison Welley, 1989)
46  */
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/proc.h>
51 #include <sys/buf.h>
52 #include <sys/vnode.h>
53 #include <sys/mount.h>
54 #include <sys/malloc.h>
55 #include <sys/pool.h>
56 #include <sys/resourcevar.h>
57 #include <sys/conf.h>
58 #include <sys/kernel.h>
59 #include <sys/specdev.h>
60 #include <uvm/uvm_extern.h>
61 
62 /* XXX Should really be in buf.h, but for uvm_constraint_range.. */
63 int	buf_realloc_pages(struct buf *, struct uvm_constraint_range *, int);
64 
65 struct uvm_constraint_range high_constraint;
66 int fliphigh;
67 
68 int nobuffers;
69 int needbuffer;
70 struct bio_ops bioops;
71 
72 /* private bufcache functions */
73 void bufcache_init(void);
74 void bufcache_adjust(void);
75 struct buf *bufcache_gethighcleanbuf(void);
76 struct buf *bufcache_getdmacleanbuf(void);
77 
78 /*
79  * Buffer pool for I/O buffers.
80  */
81 struct pool bufpool;
82 struct bufhead bufhead = LIST_HEAD_INITIALIZER(bufhead);
83 void buf_put(struct buf *);
84 
85 struct buf *bio_doread(struct vnode *, daddr_t, int, int);
86 struct buf *buf_get(struct vnode *, daddr_t, size_t);
87 void bread_cluster_callback(struct buf *);
88 
89 struct bcachestats bcstats;  /* counters */
90 long lodirtypages;      /* dirty page count low water mark */
91 long hidirtypages;      /* dirty page count high water mark */
92 long targetpages;   	/* target number of pages for cache size */
93 long buflowpages;	/* smallest size cache allowed */
94 long bufhighpages; 	/* largest size cache allowed */
95 long bufbackpages; 	/* minimum number of pages we shrink when asked to */
96 
97 vsize_t bufkvm;
98 
99 struct proc *cleanerproc;
100 int bd_req;			/* Sleep point for cleaner daemon. */
101 
102 #define NUM_CACHES 2
103 #define DMA_CACHE 0
104 struct bufcache cleancache[NUM_CACHES];
105 struct bufqueue dirtyqueue;
106 
107 void
108 buf_put(struct buf *bp)
109 {
110 	splassert(IPL_BIO);
111 
112 #ifdef DIAGNOSTIC
113 	if (bp->b_pobj != NULL)
114 		KASSERT(bp->b_bufsize > 0);
115 	if (ISSET(bp->b_flags, B_DELWRI))
116 		panic("buf_put: releasing dirty buffer");
117 	if (bp->b_freelist.tqe_next != NOLIST &&
118 	    bp->b_freelist.tqe_next != (void *)-1)
119 		panic("buf_put: still on the free list");
120 	if (bp->b_vnbufs.le_next != NOLIST &&
121 	    bp->b_vnbufs.le_next != (void *)-1)
122 		panic("buf_put: still on the vnode list");
123 	if (!LIST_EMPTY(&bp->b_dep))
124 		panic("buf_put: b_dep is not empty");
125 #endif
126 
127 	LIST_REMOVE(bp, b_list);
128 	bcstats.numbufs--;
129 
130 	if (buf_dealloc_mem(bp) != 0)
131 		return;
132 	pool_put(&bufpool, bp);
133 }
134 
135 /*
136  * Initialize buffers and hash links for buffers.
137  */
138 void
139 bufinit(void)
140 {
141 	u_int64_t dmapages;
142 	u_int64_t highpages;
143 
144 	dmapages = uvm_pagecount(&dma_constraint);
145 	/* take away a guess at how much of this the kernel will consume */
146 	dmapages -= (atop(physmem) - atop(uvmexp.free));
147 
148 	/* See if we have memory above the dma accessible region. */
149 	high_constraint.ucr_low = dma_constraint.ucr_high;
150 	high_constraint.ucr_high = no_constraint.ucr_high;
151 	if (high_constraint.ucr_low != high_constraint.ucr_high)
152 		high_constraint.ucr_low++;
153 	highpages = uvm_pagecount(&high_constraint);
154 
155 	/*
156 	 * Do we have any significant amount of high memory above
157 	 * the DMA region? if so enable moving buffers there, if not,
158 	 * don't bother.
159 	 */
160 	if (highpages > dmapages / 4)
161 		fliphigh = 1;
162 	else
163 		fliphigh = 0;
164 
165 	/*
166 	 * If MD code doesn't say otherwise, use up to 10% of DMA'able
167 	 * memory for buffers.
168 	 */
169 	if (bufcachepercent == 0)
170 		bufcachepercent = 10;
171 
172 	/*
173 	 * XXX these values and their same use in kern_sysctl
174 	 * need to move into buf.h
175 	 */
176 	KASSERT(bufcachepercent <= 90);
177 	KASSERT(bufcachepercent >= 5);
178 	if (bufpages == 0)
179 		bufpages = dmapages * bufcachepercent / 100;
180 	if (bufpages < BCACHE_MIN)
181 		bufpages = BCACHE_MIN;
182 	KASSERT(bufpages < dmapages);
183 
184 	bufhighpages = bufpages;
185 
186 	/*
187 	 * Set the base backoff level for the buffer cache.  We will
188 	 * not allow uvm to steal back more than this number of pages.
189 	 */
190 	buflowpages = dmapages * 5 / 100;
191 	if (buflowpages < BCACHE_MIN)
192 		buflowpages = BCACHE_MIN;
193 
194 	/*
195 	 * set bufbackpages to 100 pages, or 10 percent of the low water mark
196 	 * if we don't have that many pages.
197 	 */
198 
199 	bufbackpages = buflowpages * 10 / 100;
200 	if (bufbackpages > 100)
201 		bufbackpages = 100;
202 
203 	/*
204 	 * If the MD code does not say otherwise, reserve 10% of kva
205 	 * space for mapping buffers.
206 	 */
207 	if (bufkvm == 0)
208 		bufkvm = VM_KERNEL_SPACE_SIZE / 10;
209 
210 	/*
211 	 * Don't use more than twice the amount of bufpages for mappings.
212 	 * It's twice since we map things sparsely.
213 	 */
214 	if (bufkvm > bufpages * PAGE_SIZE)
215 		bufkvm = bufpages * PAGE_SIZE;
216 	/*
217 	 * Round bufkvm to MAXPHYS because we allocate chunks of va space
218 	 * in MAXPHYS chunks.
219 	 */
220 	bufkvm &= ~(MAXPHYS - 1);
221 
222 	pool_init(&bufpool, sizeof(struct buf), 0, IPL_BIO, 0, "bufpl", NULL);
223 
224 	bufcache_init();
225 
226 	/*
227 	 * hmm - bufkvm is an argument because it's static, while
228 	 * bufpages is global because it can change while running.
229  	 */
230 	buf_mem_init(bufkvm);
231 
232 	/*
233 	 * Set the dirty page high water mark to be less than the low
234 	 * water mark for pages in the buffer cache. This ensures we
235 	 * can always back off by throwing away clean pages, and give
236 	 * ourselves a chance to write out the dirty pages eventually.
237 	 */
238 	hidirtypages = (buflowpages / 4) * 3;
239 	lodirtypages = buflowpages / 2;
240 
241 	/*
242 	 * We are allowed to use up to the reserve.
243 	 */
244 	targetpages = bufpages - RESERVE_PAGES;
245 }
246 
247 /*
248  * Change cachepct
249  */
250 void
251 bufadjust(int newbufpages)
252 {
253 	struct buf *bp;
254 	int s;
255 
256 	if (newbufpages < buflowpages)
257 		newbufpages = buflowpages;
258 
259 	s = splbio();
260 	bufpages = newbufpages;
261 
262 	/*
263 	 * We are allowed to use up to the reserve
264 	 */
265 	targetpages = bufpages - RESERVE_PAGES;
266 
267 	/*
268 	 * Shrinking the cache happens here only if someone has manually
269 	 * adjusted bufcachepercent - or the pagedaemon has told us
270 	 * to give back memory *now* - so we give it all back.
271 	 */
272 	while ((bp = bufcache_getdmacleanbuf()) &&
273 	    (bcstats.dmapages > targetpages)) {
274 		bufcache_take(bp);
275 		if (bp->b_vp) {
276 			RBT_REMOVE(buf_rb_bufs, &bp->b_vp->v_bufs_tree, bp);
277 			brelvp(bp);
278 		}
279 		buf_put(bp);
280 	}
281 	bufcache_adjust();
282 
283 	/*
284 	 * Wake up the cleaner if we have lots of dirty pages,
285 	 * or if we are getting low on buffer cache kva.
286 	 */
287 	if ((UNCLEAN_PAGES >= hidirtypages) ||
288 	    bcstats.kvaslots_avail <= 2 * RESERVE_SLOTS)
289 		wakeup(&bd_req);
290 
291 	splx(s);
292 }
293 
294 /*
295  * Make the buffer cache back off from cachepct.
296  */
297 int
298 bufbackoff(struct uvm_constraint_range *range, long size)
299 {
300 	/*
301 	 * Back off "size" buffer cache pages. Called by the page
302 	 * daemon to consume buffer cache pages rather than scanning.
303 	 *
304 	 * It returns 0 to the pagedaemon to indicate that it has
305 	 * succeeded in freeing enough pages. It returns -1 to
306 	 * indicate that it could not and the pagedaemon should take
307 	 * other measures.
308 	 *
309 	 */
310 	long pdelta, oldbufpages;
311 
312 	/*
313 	 * If we will accept high memory for this backoff
314 	 * try to steal it from the high memory buffer cache.
315 	 */
316 	if (range->ucr_high > dma_constraint.ucr_high) {
317 		struct buf *bp;
318 		int64_t start = bcstats.numbufpages, recovered = 0;
319 		int s = splbio();
320 
321 		while ((recovered < size) &&
322 		    (bp = bufcache_gethighcleanbuf())) {
323 			bufcache_take(bp);
324 			if (bp->b_vp) {
325 				RBT_REMOVE(buf_rb_bufs,
326 				    &bp->b_vp->v_bufs_tree, bp);
327 				brelvp(bp);
328 			}
329 			buf_put(bp);
330 			recovered = start - bcstats.numbufpages;
331 		}
332 		bufcache_adjust();
333 		splx(s);
334 
335 		/* If we got enough, return success */
336 		if (recovered >= size)
337 			return 0;
338 
339 		/*
340 		 * If we needed only memory above DMA,
341 		 * return failure
342 		 */
343 		if (range->ucr_low > dma_constraint.ucr_high)
344 			return -1;
345 
346 		/* Otherwise get the rest from DMA */
347 		size -= recovered;
348 	}
349 
350 	/*
351 	 * XXX Otherwise do the dma memory cache dance. this needs
352 	 * refactoring later to get rid of 'bufpages'
353 	 */
354 
355 	/*
356 	 * Back off by at least bufbackpages. If the page daemon gave us
357 	 * a larger size, back off by that much.
358 	 */
359 	pdelta = (size > bufbackpages) ? size : bufbackpages;
360 
361 	if (bufpages <= buflowpages)
362 		return(-1);
363 	if (bufpages - pdelta < buflowpages)
364 		pdelta = bufpages - buflowpages;
365 	oldbufpages = bufpages;
366 	bufadjust(bufpages - pdelta);
367 	if (oldbufpages - bufpages < size)
368 		return (-1); /* we did not free what we were asked */
369 	else
370 		return(0);
371 }
372 
373 
374 /*
375  * Opportunistically flip a buffer into high memory. Will move the buffer
376  * if memory is available without sleeping, and return 0, otherwise will
377  * fail and return -1 with the buffer unchanged.
378  */
379 
380 int
381 buf_flip_high(struct buf *bp)
382 {
383 	int s;
384 	int ret = -1;
385 
386 	KASSERT(ISSET(bp->b_flags, B_BC));
387 	KASSERT(ISSET(bp->b_flags, B_DMA));
388 	KASSERT(bp->cache == DMA_CACHE);
389 	KASSERT(fliphigh);
390 
391 	/* Attempt to move the buffer to high memory if we can */
392 	s = splbio();
393 	if (buf_realloc_pages(bp, &high_constraint, UVM_PLA_NOWAIT) == 0) {
394 		KASSERT(!ISSET(bp->b_flags, B_DMA));
395 		bcstats.highflips++;
396 		ret = 0;
397 	} else
398 		bcstats.highflops++;
399 	splx(s);
400 
401 	return ret;
402 }
403 
404 /*
405  * Flip a buffer to dma reachable memory, when we need it there for
406  * I/O. This can sleep since it will wait for memory alloacation in the
407  * DMA reachable area since we have to have the buffer there to proceed.
408  */
409 void
410 buf_flip_dma(struct buf *bp)
411 {
412 	KASSERT(ISSET(bp->b_flags, B_BC));
413 	KASSERT(ISSET(bp->b_flags, B_BUSY));
414 	KASSERT(bp->cache < NUM_CACHES);
415 
416 	if (!ISSET(bp->b_flags, B_DMA)) {
417 		int s = splbio();
418 
419 		/* move buf to dma reachable memory */
420 		(void) buf_realloc_pages(bp, &dma_constraint, UVM_PLA_WAITOK);
421 		KASSERT(ISSET(bp->b_flags, B_DMA));
422 		bcstats.dmaflips++;
423 		splx(s);
424 	}
425 
426 	if (bp->cache > DMA_CACHE) {
427 		CLR(bp->b_flags, B_COLD);
428 		CLR(bp->b_flags, B_WARM);
429 		bp->cache = DMA_CACHE;
430 	}
431 }
432 
433 struct buf *
434 bio_doread(struct vnode *vp, daddr_t blkno, int size, int async)
435 {
436 	struct buf *bp;
437 	struct mount *mp;
438 
439 	bp = getblk(vp, blkno, size, 0, 0);
440 
441 	/*
442 	 * If buffer does not have valid data, start a read.
443 	 * Note that if buffer is B_INVAL, getblk() won't return it.
444 	 * Therefore, it's valid if its I/O has completed or been delayed.
445 	 */
446 	if (!ISSET(bp->b_flags, (B_DONE | B_DELWRI))) {
447 		SET(bp->b_flags, B_READ | async);
448 		bcstats.pendingreads++;
449 		bcstats.numreads++;
450 		VOP_STRATEGY(bp);
451 		/* Pay for the read. */
452 		curproc->p_ru.ru_inblock++;			/* XXX */
453 	} else if (async) {
454 		brelse(bp);
455 	}
456 
457 	mp = vp->v_type == VBLK? vp->v_specmountpoint : vp->v_mount;
458 
459 	/*
460 	 * Collect statistics on synchronous and asynchronous reads.
461 	 * Reads from block devices are charged to their associated
462 	 * filesystem (if any).
463 	 */
464 	if (mp != NULL) {
465 		if (async == 0)
466 			mp->mnt_stat.f_syncreads++;
467 		else
468 			mp->mnt_stat.f_asyncreads++;
469 	}
470 
471 	return (bp);
472 }
473 
474 /*
475  * Read a disk block.
476  * This algorithm described in Bach (p.54).
477  */
478 int
479 bread(struct vnode *vp, daddr_t blkno, int size, struct buf **bpp)
480 {
481 	struct buf *bp;
482 
483 	/* Get buffer for block. */
484 	bp = *bpp = bio_doread(vp, blkno, size, 0);
485 
486 	/* Wait for the read to complete, and return result. */
487 	return (biowait(bp));
488 }
489 
490 /*
491  * Read-ahead multiple disk blocks. The first is sync, the rest async.
492  * Trivial modification to the breada algorithm presented in Bach (p.55).
493  */
494 int
495 breadn(struct vnode *vp, daddr_t blkno, int size, daddr_t rablks[],
496     int rasizes[], int nrablks, struct buf **bpp)
497 {
498 	struct buf *bp;
499 	int i;
500 
501 	bp = *bpp = bio_doread(vp, blkno, size, 0);
502 
503 	/*
504 	 * For each of the read-ahead blocks, start a read, if necessary.
505 	 */
506 	for (i = 0; i < nrablks; i++) {
507 		/* If it's in the cache, just go on to next one. */
508 		if (incore(vp, rablks[i]))
509 			continue;
510 
511 		/* Get a buffer for the read-ahead block */
512 		(void) bio_doread(vp, rablks[i], rasizes[i], B_ASYNC);
513 	}
514 
515 	/* Otherwise, we had to start a read for it; wait until it's valid. */
516 	return (biowait(bp));
517 }
518 
519 /*
520  * Called from interrupt context.
521  */
522 void
523 bread_cluster_callback(struct buf *bp)
524 {
525 	struct buf **xbpp = bp->b_saveaddr;
526 	int i;
527 
528 	if (xbpp[1] != NULL) {
529 		size_t newsize = xbpp[1]->b_bufsize;
530 
531 		/*
532 		 * Shrink this buffer's mapping to only cover its part of
533 		 * the total I/O.
534 		 */
535 		buf_fix_mapping(bp, newsize);
536 		bp->b_bcount = newsize;
537 	}
538 
539 	/* Invalidate read-ahead buffers if read short */
540 	if (bp->b_resid > 0) {
541 		for (i = 1; xbpp[i] != NULL; i++)
542 			continue;
543 		for (i = i - 1; i != 0; i--) {
544 			if (xbpp[i]->b_bufsize <= bp->b_resid) {
545 				bp->b_resid -= xbpp[i]->b_bufsize;
546 				SET(xbpp[i]->b_flags, B_INVAL);
547 			} else if (bp->b_resid > 0) {
548 				bp->b_resid = 0;
549 				SET(xbpp[i]->b_flags, B_INVAL);
550 			} else
551 				break;
552 		}
553 	}
554 
555 	for (i = 1; xbpp[i] != NULL; i++) {
556 		if (ISSET(bp->b_flags, B_ERROR))
557 			SET(xbpp[i]->b_flags, B_INVAL | B_ERROR);
558 		biodone(xbpp[i]);
559 	}
560 
561 	free(xbpp, M_TEMP, (i + 1) * sizeof(*xbpp));
562 
563 	if (ISSET(bp->b_flags, B_ASYNC)) {
564 		brelse(bp);
565 	} else {
566 		CLR(bp->b_flags, B_WANTED);
567 		wakeup(bp);
568 	}
569 }
570 
571 /*
572  * Read-ahead multiple disk blocks, but make sure only one (big) I/O
573  * request is sent to the disk.
574  * XXX This should probably be dropped and breadn should instead be optimized
575  * XXX to do fewer I/O requests.
576  */
577 int
578 bread_cluster(struct vnode *vp, daddr_t blkno, int size, struct buf **rbpp)
579 {
580 	struct buf *bp, **xbpp;
581 	int howmany, maxra, i, inc;
582 	daddr_t sblkno;
583 
584 	*rbpp = bio_doread(vp, blkno, size, 0);
585 
586 	/*
587 	 * If the buffer is in the cache skip any I/O operation.
588 	 */
589 	if (ISSET((*rbpp)->b_flags, B_CACHE))
590 		goto out;
591 
592 	if (size != round_page(size))
593 		goto out;
594 
595 	if (VOP_BMAP(vp, blkno + 1, NULL, &sblkno, &maxra))
596 		goto out;
597 
598 	maxra++;
599 	if (sblkno == -1 || maxra < 2)
600 		goto out;
601 
602 	howmany = MAXPHYS / size;
603 	if (howmany > maxra)
604 		howmany = maxra;
605 
606 	xbpp = mallocarray(howmany + 1, sizeof(*xbpp), M_TEMP, M_NOWAIT);
607 	if (xbpp == NULL)
608 		goto out;
609 
610 	for (i = howmany - 1; i >= 0; i--) {
611 		size_t sz;
612 
613 		/*
614 		 * First buffer allocates big enough size to cover what
615 		 * all the other buffers need.
616 		 */
617 		sz = i == 0 ? howmany * size : 0;
618 
619 		xbpp[i] = buf_get(vp, blkno + i + 1, sz);
620 		if (xbpp[i] == NULL) {
621 			for (++i; i < howmany; i++) {
622 				SET(xbpp[i]->b_flags, B_INVAL);
623 				brelse(xbpp[i]);
624 			}
625 			free(xbpp, M_TEMP, (howmany + 1) * sizeof(*xbpp));
626 			goto out;
627 		}
628 	}
629 
630 	bp = xbpp[0];
631 
632 	xbpp[howmany] = NULL;
633 
634 	inc = btodb(size);
635 
636 	for (i = 1; i < howmany; i++) {
637 		bcstats.pendingreads++;
638 		bcstats.numreads++;
639                 /*
640                 * We set B_DMA here because bp above will be B_DMA,
641                 * and we are playing buffer slice-n-dice games from
642                 * the memory allocated in bp.
643                 */
644 		SET(xbpp[i]->b_flags, B_DMA | B_READ | B_ASYNC);
645 		xbpp[i]->b_blkno = sblkno + (i * inc);
646 		xbpp[i]->b_bufsize = xbpp[i]->b_bcount = size;
647 		xbpp[i]->b_data = NULL;
648 		xbpp[i]->b_pobj = bp->b_pobj;
649 		xbpp[i]->b_poffs = bp->b_poffs + (i * size);
650 	}
651 
652 	KASSERT(bp->b_lblkno == blkno + 1);
653 	KASSERT(bp->b_vp == vp);
654 
655 	bp->b_blkno = sblkno;
656 	SET(bp->b_flags, B_READ | B_ASYNC | B_CALL);
657 
658 	bp->b_saveaddr = (void *)xbpp;
659 	bp->b_iodone = bread_cluster_callback;
660 
661 	bcstats.pendingreads++;
662 	bcstats.numreads++;
663 	VOP_STRATEGY(bp);
664 	curproc->p_ru.ru_inblock++;
665 
666 out:
667 	return (biowait(*rbpp));
668 }
669 
670 /*
671  * Block write.  Described in Bach (p.56)
672  */
673 int
674 bwrite(struct buf *bp)
675 {
676 	int rv, async, wasdelayed, s;
677 	struct vnode *vp;
678 	struct mount *mp;
679 
680 	vp = bp->b_vp;
681 	if (vp != NULL)
682 		mp = vp->v_type == VBLK? vp->v_specmountpoint : vp->v_mount;
683 	else
684 		mp = NULL;
685 
686 	/*
687 	 * Remember buffer type, to switch on it later.  If the write was
688 	 * synchronous, but the file system was mounted with MNT_ASYNC,
689 	 * convert it to a delayed write.
690 	 * XXX note that this relies on delayed tape writes being converted
691 	 * to async, not sync writes (which is safe, but ugly).
692 	 */
693 	async = ISSET(bp->b_flags, B_ASYNC);
694 	if (!async && mp && ISSET(mp->mnt_flag, MNT_ASYNC)) {
695 		bdwrite(bp);
696 		return (0);
697 	}
698 
699 	/*
700 	 * Collect statistics on synchronous and asynchronous writes.
701 	 * Writes to block devices are charged to their associated
702 	 * filesystem (if any).
703 	 */
704 	if (mp != NULL) {
705 		if (async)
706 			mp->mnt_stat.f_asyncwrites++;
707 		else
708 			mp->mnt_stat.f_syncwrites++;
709 	}
710 	bcstats.pendingwrites++;
711 	bcstats.numwrites++;
712 
713 	wasdelayed = ISSET(bp->b_flags, B_DELWRI);
714 	CLR(bp->b_flags, (B_READ | B_DONE | B_ERROR | B_DELWRI));
715 
716 	s = splbio();
717 
718 	/*
719 	 * If not synchronous, pay for the I/O operation and make
720 	 * sure the buf is on the correct vnode queue.  We have
721 	 * to do this now, because if we don't, the vnode may not
722 	 * be properly notified that its I/O has completed.
723 	 */
724 	if (wasdelayed) {
725 		reassignbuf(bp);
726 	} else
727 		curproc->p_ru.ru_oublock++;
728 
729 
730 	/* Initiate disk write.  Make sure the appropriate party is charged. */
731 	bp->b_vp->v_numoutput++;
732 	splx(s);
733 	buf_flip_dma(bp);
734 	SET(bp->b_flags, B_WRITEINPROG);
735 	VOP_STRATEGY(bp);
736 
737 	/*
738 	 * If the queue is above the high water mark, wait till
739 	 * the number of outstanding write bufs drops below the low
740 	 * water mark.
741 	 */
742 	if (bp->b_bq)
743 		bufq_wait(bp->b_bq);
744 
745 	if (async)
746 		return (0);
747 
748 	/*
749 	 * If I/O was synchronous, wait for it to complete.
750 	 */
751 	rv = biowait(bp);
752 
753 	/* Release the buffer. */
754 	brelse(bp);
755 
756 	return (rv);
757 }
758 
759 
760 /*
761  * Delayed write.
762  *
763  * The buffer is marked dirty, but is not queued for I/O.
764  * This routine should be used when the buffer is expected
765  * to be modified again soon, typically a small write that
766  * partially fills a buffer.
767  *
768  * NB: magnetic tapes cannot be delayed; they must be
769  * written in the order that the writes are requested.
770  *
771  * Described in Leffler, et al. (pp. 208-213).
772  */
773 void
774 bdwrite(struct buf *bp)
775 {
776 	int s;
777 
778 	/*
779 	 * If the block hasn't been seen before:
780 	 *	(1) Mark it as having been seen,
781 	 *	(2) Charge for the write.
782 	 *	(3) Make sure it's on its vnode's correct block list,
783 	 *	(4) If a buffer is rewritten, move it to end of dirty list
784 	 */
785 	if (!ISSET(bp->b_flags, B_DELWRI)) {
786 		SET(bp->b_flags, B_DELWRI);
787 		s = splbio();
788 		buf_flip_dma(bp);
789 		reassignbuf(bp);
790 		splx(s);
791 		curproc->p_ru.ru_oublock++;		/* XXX */
792 	}
793 
794 	/* The "write" is done, so mark and release the buffer. */
795 	CLR(bp->b_flags, B_NEEDCOMMIT);
796 	SET(bp->b_flags, B_DONE);
797 	brelse(bp);
798 }
799 
800 /*
801  * Asynchronous block write; just an asynchronous bwrite().
802  */
803 void
804 bawrite(struct buf *bp)
805 {
806 
807 	SET(bp->b_flags, B_ASYNC);
808 	VOP_BWRITE(bp);
809 }
810 
811 /*
812  * Must be called at splbio()
813  */
814 void
815 buf_dirty(struct buf *bp)
816 {
817 	splassert(IPL_BIO);
818 
819 #ifdef DIAGNOSTIC
820 	if (!ISSET(bp->b_flags, B_BUSY))
821 		panic("Trying to dirty buffer on freelist!");
822 #endif
823 
824 	if (ISSET(bp->b_flags, B_DELWRI) == 0) {
825 		SET(bp->b_flags, B_DELWRI);
826 		buf_flip_dma(bp);
827 		reassignbuf(bp);
828 	}
829 }
830 
831 /*
832  * Must be called at splbio()
833  */
834 void
835 buf_undirty(struct buf *bp)
836 {
837 	splassert(IPL_BIO);
838 
839 #ifdef DIAGNOSTIC
840 	if (!ISSET(bp->b_flags, B_BUSY))
841 		panic("Trying to undirty buffer on freelist!");
842 #endif
843 	if (ISSET(bp->b_flags, B_DELWRI)) {
844 		CLR(bp->b_flags, B_DELWRI);
845 		reassignbuf(bp);
846 	}
847 }
848 
849 /*
850  * Release a buffer on to the free lists.
851  * Described in Bach (p. 46).
852  */
853 void
854 brelse(struct buf *bp)
855 {
856 	int s;
857 
858 	s = splbio();
859 
860 	if (bp->b_data != NULL)
861 		KASSERT(bp->b_bufsize > 0);
862 
863 	/*
864 	 * Determine which queue the buffer should be on, then put it there.
865 	 */
866 
867 	/* If it's not cacheable, or an error, mark it invalid. */
868 	if (ISSET(bp->b_flags, (B_NOCACHE|B_ERROR)))
869 		SET(bp->b_flags, B_INVAL);
870 	/* If it's a write error, also mark the vnode as damaged. */
871 	if (ISSET(bp->b_flags, B_ERROR) && !ISSET(bp->b_flags, B_READ)) {
872 		if (bp->b_vp && bp->b_vp->v_type == VREG)
873 			SET(bp->b_vp->v_bioflag, VBIOERROR);
874 	}
875 
876 	if (ISSET(bp->b_flags, B_INVAL)) {
877 		/*
878 		 * If the buffer is invalid, free it now rather than leaving
879 		 * it in a queue and wasting memory.
880 		 */
881 		if (LIST_FIRST(&bp->b_dep) != NULL)
882 			buf_deallocate(bp);
883 
884 		if (ISSET(bp->b_flags, B_DELWRI)) {
885 			CLR(bp->b_flags, B_DELWRI);
886 		}
887 
888 		if (bp->b_vp) {
889 			RBT_REMOVE(buf_rb_bufs, &bp->b_vp->v_bufs_tree, bp);
890 			brelvp(bp);
891 		}
892 		bp->b_vp = NULL;
893 
894 		/*
895 		 * Wake up any processes waiting for _this_ buffer to
896 		 * become free. They are not allowed to grab it
897 		 * since it will be freed. But the only sleeper is
898 		 * getblk and it will restart the operation after
899 		 * sleep.
900 		 */
901 		if (ISSET(bp->b_flags, B_WANTED)) {
902 			CLR(bp->b_flags, B_WANTED);
903 			wakeup(bp);
904 		}
905 		buf_put(bp);
906 	} else {
907 		/*
908 		 * It has valid data.  Put it on the end of the appropriate
909 		 * queue, so that it'll stick around for as long as possible.
910 		 */
911 		bufcache_release(bp);
912 
913 		/* Unlock the buffer. */
914 		CLR(bp->b_flags, (B_AGE | B_ASYNC | B_NOCACHE | B_DEFERRED));
915 		buf_release(bp);
916 
917 		/* Wake up any processes waiting for _this_ buffer to
918 		 * become free. */
919 		if (ISSET(bp->b_flags, B_WANTED)) {
920 			CLR(bp->b_flags, B_WANTED);
921 			wakeup(bp);
922 		}
923 	}
924 
925 	/* Wake up syncer and cleaner processes waiting for buffers. */
926 	if (nobuffers) {
927 		nobuffers = 0;
928 		wakeup(&nobuffers);
929 	}
930 
931 	/* Wake up any processes waiting for any buffer to become free. */
932 	if (needbuffer && bcstats.dmapages < targetpages &&
933 	    bcstats.kvaslots_avail > RESERVE_SLOTS) {
934 		needbuffer = 0;
935 		wakeup(&needbuffer);
936 	}
937 
938 	splx(s);
939 }
940 
941 /*
942  * Determine if a block is in the cache. Just look on what would be its hash
943  * chain. If it's there, return a pointer to it, unless it's marked invalid.
944  */
945 struct buf *
946 incore(struct vnode *vp, daddr_t blkno)
947 {
948 	struct buf *bp;
949 	struct buf b;
950 	int s;
951 
952 	s = splbio();
953 
954 	/* Search buf lookup tree */
955 	b.b_lblkno = blkno;
956 	bp = RBT_FIND(buf_rb_bufs, &vp->v_bufs_tree, &b);
957 	if (bp != NULL && ISSET(bp->b_flags, B_INVAL))
958 		bp = NULL;
959 
960 	splx(s);
961 	return (bp);
962 }
963 
964 /*
965  * Get a block of requested size that is associated with
966  * a given vnode and block offset. If it is found in the
967  * block cache, mark it as having been found, make it busy
968  * and return it. Otherwise, return an empty block of the
969  * correct size. It is up to the caller to ensure that the
970  * cached blocks be of the correct size.
971  */
972 struct buf *
973 getblk(struct vnode *vp, daddr_t blkno, int size, int slpflag, int slptimeo)
974 {
975 	struct buf *bp;
976 	struct buf b;
977 	int s, error;
978 
979 	/*
980 	 * XXX
981 	 * The following is an inlined version of 'incore()', but with
982 	 * the 'invalid' test moved to after the 'busy' test.  It's
983 	 * necessary because there are some cases in which the NFS
984 	 * code sets B_INVAL prior to writing data to the server, but
985 	 * in which the buffers actually contain valid data.  In this
986 	 * case, we can't allow the system to allocate a new buffer for
987 	 * the block until the write is finished.
988 	 */
989 start:
990 	s = splbio();
991 	b.b_lblkno = blkno;
992 	bp = RBT_FIND(buf_rb_bufs, &vp->v_bufs_tree, &b);
993 	if (bp != NULL) {
994 		if (ISSET(bp->b_flags, B_BUSY)) {
995 			SET(bp->b_flags, B_WANTED);
996 			error = tsleep(bp, slpflag | (PRIBIO + 1), "getblk",
997 			    slptimeo);
998 			splx(s);
999 			if (error)
1000 				return (NULL);
1001 			goto start;
1002 		}
1003 
1004 		if (!ISSET(bp->b_flags, B_INVAL)) {
1005 			bcstats.cachehits++;
1006 			SET(bp->b_flags, B_CACHE);
1007 			bufcache_take(bp);
1008 			buf_acquire(bp);
1009 			splx(s);
1010 			return (bp);
1011 		}
1012 	}
1013 	splx(s);
1014 
1015 	if ((bp = buf_get(vp, blkno, size)) == NULL)
1016 		goto start;
1017 
1018 	return (bp);
1019 }
1020 
1021 /*
1022  * Get an empty, disassociated buffer of given size.
1023  */
1024 struct buf *
1025 geteblk(size_t size)
1026 {
1027 	struct buf *bp;
1028 
1029 	while ((bp = buf_get(NULL, 0, size)) == NULL)
1030 		continue;
1031 
1032 	return (bp);
1033 }
1034 
1035 /*
1036  * Allocate a buffer.
1037  * If vp is given, put it into the buffer cache for that vnode.
1038  * If size != 0, allocate memory and call buf_map().
1039  * If there is already a buffer for the given vnode/blkno, return NULL.
1040  */
1041 struct buf *
1042 buf_get(struct vnode *vp, daddr_t blkno, size_t size)
1043 {
1044 	struct buf *bp;
1045 	int poolwait = size == 0 ? PR_NOWAIT : PR_WAITOK;
1046 	int npages;
1047 	int s;
1048 
1049 	s = splbio();
1050 	if (size) {
1051 		/*
1052 		 * Wake up the cleaner if we have lots of dirty pages,
1053 		 * or if we are getting low on buffer cache kva.
1054 		 */
1055 		if (UNCLEAN_PAGES >= hidirtypages ||
1056 			bcstats.kvaslots_avail <= 2 * RESERVE_SLOTS)
1057 			wakeup(&bd_req);
1058 
1059 		npages = atop(round_page(size));
1060 
1061 		/*
1062 		 * if our cache has been previously shrunk,
1063 		 * allow it to grow again with use up to
1064 		 * bufhighpages (cachepercent)
1065 		 */
1066 		if (bufpages < bufhighpages)
1067 			bufadjust(bufhighpages);
1068 
1069 		/*
1070 		 * If we would go over the page target with our
1071 		 * new allocation, free enough buffers first
1072 		 * to stay at the target with our new allocation.
1073 		 */
1074 		while ((bcstats.dmapages + npages > targetpages) &&
1075 		    (bp = bufcache_getdmacleanbuf())) {
1076 			bufcache_take(bp);
1077 			if (bp->b_vp) {
1078 				RBT_REMOVE(buf_rb_bufs,
1079 				    &bp->b_vp->v_bufs_tree, bp);
1080 				brelvp(bp);
1081 			}
1082 			buf_put(bp);
1083 		}
1084 
1085 		/*
1086 		 * If we get here, we tried to free the world down
1087 		 * above, and couldn't get down - Wake the cleaner
1088 		 * and wait for it to push some buffers out.
1089 		 */
1090 		if ((bcstats.dmapages + npages > targetpages ||
1091 		    bcstats.kvaslots_avail <= RESERVE_SLOTS) &&
1092 		    curproc != syncerproc && curproc != cleanerproc) {
1093 			wakeup(&bd_req);
1094 			needbuffer++;
1095 			tsleep(&needbuffer, PRIBIO, "needbuffer", 0);
1096 			splx(s);
1097 			return (NULL);
1098 		}
1099 		if (bcstats.dmapages + npages > bufpages) {
1100 			/* cleaner or syncer */
1101 			nobuffers = 1;
1102 			tsleep(&nobuffers, PRIBIO, "nobuffers", 0);
1103 			splx(s);
1104 			return (NULL);
1105 		}
1106 	}
1107 
1108 	bp = pool_get(&bufpool, poolwait|PR_ZERO);
1109 
1110 	if (bp == NULL) {
1111 		splx(s);
1112 		return (NULL);
1113 	}
1114 
1115 	bp->b_freelist.tqe_next = NOLIST;
1116 	bp->b_dev = NODEV;
1117 	LIST_INIT(&bp->b_dep);
1118 	bp->b_bcount = size;
1119 
1120 	buf_acquire_nomap(bp);
1121 
1122 	if (vp != NULL) {
1123 		/*
1124 		 * We insert the buffer into the hash with B_BUSY set
1125 		 * while we allocate pages for it. This way any getblk
1126 		 * that happens while we allocate pages will wait for
1127 		 * this buffer instead of starting its own buf_get.
1128 		 *
1129 		 * But first, we check if someone beat us to it.
1130 		 */
1131 		if (incore(vp, blkno)) {
1132 			pool_put(&bufpool, bp);
1133 			splx(s);
1134 			return (NULL);
1135 		}
1136 
1137 		bp->b_blkno = bp->b_lblkno = blkno;
1138 		bgetvp(vp, bp);
1139 		if (RBT_INSERT(buf_rb_bufs, &vp->v_bufs_tree, bp))
1140 			panic("buf_get: dup lblk vp %p bp %p", vp, bp);
1141 	} else {
1142 		bp->b_vnbufs.le_next = NOLIST;
1143 		SET(bp->b_flags, B_INVAL);
1144 		bp->b_vp = NULL;
1145 	}
1146 
1147 	LIST_INSERT_HEAD(&bufhead, bp, b_list);
1148 	bcstats.numbufs++;
1149 
1150 	if (size) {
1151 		buf_alloc_pages(bp, round_page(size));
1152 		KASSERT(ISSET(bp->b_flags, B_DMA));
1153 		buf_map(bp);
1154 	}
1155 
1156 	SET(bp->b_flags, B_BC);
1157 	splx(s);
1158 
1159 	return (bp);
1160 }
1161 
1162 /*
1163  * Buffer cleaning daemon.
1164  */
1165 void
1166 buf_daemon(void *arg)
1167 {
1168 	struct buf *bp = NULL;
1169 	int s, pushed = 0;
1170 
1171 	s = splbio();
1172 	for (;;) {
1173 		if (bp == NULL || (pushed >= 16 &&
1174 		    UNCLEAN_PAGES < hidirtypages &&
1175 		    bcstats.kvaslots_avail > 2 * RESERVE_SLOTS)){
1176 			pushed = 0;
1177 			/*
1178 			 * Wake up anyone who was waiting for buffers
1179 			 * to be released.
1180 			 */
1181 			if (needbuffer) {
1182 				needbuffer = 0;
1183 				wakeup(&needbuffer);
1184 			}
1185 			tsleep(&bd_req, PRIBIO - 7, "cleaner", 0);
1186 		}
1187 
1188 		while ((bp = bufcache_getdirtybuf())) {
1189 
1190 			if (UNCLEAN_PAGES < lodirtypages &&
1191 			    bcstats.kvaslots_avail > 2 * RESERVE_SLOTS &&
1192 			    pushed >= 16)
1193 				break;
1194 
1195 			bufcache_take(bp);
1196 			buf_acquire(bp);
1197 			splx(s);
1198 
1199 			if (ISSET(bp->b_flags, B_INVAL)) {
1200 				brelse(bp);
1201 				s = splbio();
1202 				continue;
1203 			}
1204 #ifdef DIAGNOSTIC
1205 			if (!ISSET(bp->b_flags, B_DELWRI))
1206 				panic("Clean buffer on dirty queue");
1207 #endif
1208 			if (LIST_FIRST(&bp->b_dep) != NULL &&
1209 			    !ISSET(bp->b_flags, B_DEFERRED) &&
1210 			    buf_countdeps(bp, 0, 0)) {
1211 				SET(bp->b_flags, B_DEFERRED);
1212 				s = splbio();
1213 				bufcache_release(bp);
1214 				buf_release(bp);
1215 				continue;
1216 			}
1217 
1218 			bawrite(bp);
1219 			pushed++;
1220 
1221 			sched_pause(yield);
1222 
1223 			s = splbio();
1224 		}
1225 	}
1226 }
1227 
1228 /*
1229  * Wait for operations on the buffer to complete.
1230  * When they do, extract and return the I/O's error value.
1231  */
1232 int
1233 biowait(struct buf *bp)
1234 {
1235 	int s;
1236 
1237 	KASSERT(!(bp->b_flags & B_ASYNC));
1238 
1239 	s = splbio();
1240 	while (!ISSET(bp->b_flags, B_DONE))
1241 		tsleep(bp, PRIBIO + 1, "biowait", 0);
1242 	splx(s);
1243 
1244 	/* check for interruption of I/O (e.g. via NFS), then errors. */
1245 	if (ISSET(bp->b_flags, B_EINTR)) {
1246 		CLR(bp->b_flags, B_EINTR);
1247 		return (EINTR);
1248 	}
1249 
1250 	if (ISSET(bp->b_flags, B_ERROR))
1251 		return (bp->b_error ? bp->b_error : EIO);
1252 	else
1253 		return (0);
1254 }
1255 
1256 /*
1257  * Mark I/O complete on a buffer.
1258  *
1259  * If a callback has been requested, e.g. the pageout
1260  * daemon, do so. Otherwise, awaken waiting processes.
1261  *
1262  * [ Leffler, et al., says on p.247:
1263  *	"This routine wakes up the blocked process, frees the buffer
1264  *	for an asynchronous write, or, for a request by the pagedaemon
1265  *	process, invokes a procedure specified in the buffer structure" ]
1266  *
1267  * In real life, the pagedaemon (or other system processes) wants
1268  * to do async stuff to, and doesn't want the buffer brelse()'d.
1269  * (for swap pager, that puts swap buffers on the free lists (!!!),
1270  * for the vn device, that puts malloc'd buffers on the free lists!)
1271  *
1272  * Must be called at splbio().
1273  */
1274 void
1275 biodone(struct buf *bp)
1276 {
1277 	splassert(IPL_BIO);
1278 
1279 	if (ISSET(bp->b_flags, B_DONE))
1280 		panic("biodone already");
1281 	SET(bp->b_flags, B_DONE);		/* note that it's done */
1282 
1283 	if (bp->b_bq)
1284 		bufq_done(bp->b_bq, bp);
1285 
1286 	if (LIST_FIRST(&bp->b_dep) != NULL)
1287 		buf_complete(bp);
1288 
1289 	if (!ISSET(bp->b_flags, B_READ)) {
1290 		CLR(bp->b_flags, B_WRITEINPROG);
1291 		vwakeup(bp->b_vp);
1292 	}
1293 	if (bcstats.numbufs &&
1294 	    (!(ISSET(bp->b_flags, B_RAW) || ISSET(bp->b_flags, B_PHYS)))) {
1295 		if (!ISSET(bp->b_flags, B_READ)) {
1296 			bcstats.pendingwrites--;
1297 		} else
1298 			bcstats.pendingreads--;
1299 	}
1300 	if (ISSET(bp->b_flags, B_CALL)) {	/* if necessary, call out */
1301 		CLR(bp->b_flags, B_CALL);	/* but note callout done */
1302 		(*bp->b_iodone)(bp);
1303 	} else {
1304 		if (ISSET(bp->b_flags, B_ASYNC)) {/* if async, release it */
1305 			brelse(bp);
1306 		} else {			/* or just wakeup the buffer */
1307 			CLR(bp->b_flags, B_WANTED);
1308 			wakeup(bp);
1309 		}
1310 	}
1311 }
1312 
1313 #ifdef DDB
1314 void	bcstats_print(int (*)(const char *, ...)
1315     __attribute__((__format__(__kprintf__,1,2))));
1316 /*
1317  * bcstats_print: ddb hook to print interesting buffer cache counters
1318  */
1319 void
1320 bcstats_print(
1321     int (*pr)(const char *, ...) __attribute__((__format__(__kprintf__,1,2))))
1322 {
1323 	(*pr)("Current Buffer Cache status:\n");
1324 	(*pr)("numbufs %lld busymapped %lld, delwri %lld\n",
1325 	    bcstats.numbufs, bcstats.busymapped, bcstats.delwribufs);
1326 	(*pr)("kvaslots %lld avail kva slots %lld\n",
1327 	    bcstats.kvaslots, bcstats.kvaslots_avail);
1328     	(*pr)("bufpages %lld, dmapages %lld, dirtypages %lld\n",
1329 	    bcstats.numbufpages, bcstats.dmapages, bcstats.numdirtypages);
1330 	(*pr)("pendingreads %lld, pendingwrites %lld\n",
1331 	    bcstats.pendingreads, bcstats.pendingwrites);
1332 	(*pr)("highflips %lld, highflops %lld, dmaflips %lld\n",
1333 	    bcstats.highflips, bcstats.highflops, bcstats.dmaflips);
1334 }
1335 #endif
1336 
1337 void
1338 buf_adjcnt(struct buf *bp, long ncount)
1339 {
1340 	KASSERT(ncount <= bp->b_bufsize);
1341 	bp->b_bcount = ncount;
1342 }
1343 
1344 /* bufcache freelist code below */
1345 /*
1346  * Copyright (c) 2014 Ted Unangst <tedu@openbsd.org>
1347  *
1348  * Permission to use, copy, modify, and distribute this software for any
1349  * purpose with or without fee is hereby granted, provided that the above
1350  * copyright notice and this permission notice appear in all copies.
1351  *
1352  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
1353  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
1354  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
1355  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1356  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
1357  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1358  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1359  */
1360 
1361 /*
1362  * The code below implements a variant of the 2Q buffer cache algorithm by
1363  * Johnson and Shasha.
1364  *
1365  * General Outline
1366  * We divide the buffer cache into three working sets: current, previous,
1367  * and long term. Each list is itself LRU and buffers get promoted and moved
1368  * around between them. A buffer starts its life in the current working set.
1369  * As time passes and newer buffers push it out, it will turn into the previous
1370  * working set and is subject to recycling. But if it's accessed again from
1371  * the previous working set, that's an indication that it's actually in the
1372  * long term working set, so we promote it there. The separation of current
1373  * and previous working sets prevents us from promoting a buffer that's only
1374  * temporarily hot to the long term cache.
1375  *
1376  * The objective is to provide scan resistance by making the long term
1377  * working set ineligible for immediate recycling, even as the current
1378  * working set is rapidly turned over.
1379  *
1380  * Implementation
1381  * The code below identifies the current, previous, and long term sets as
1382  * hotqueue, coldqueue, and warmqueue. The hot and warm queues are capped at
1383  * 1/3 of the total clean pages, after which point they start pushing their
1384  * oldest buffers into coldqueue.
1385  * A buf always starts out with neither WARM or COLD flags set (implying HOT).
1386  * When released, it will be returned to the tail of the hotqueue list.
1387  * When the hotqueue gets too large, the oldest hot buf will be moved to the
1388  * coldqueue, with the B_COLD flag set. When a cold buf is released, we set
1389  * the B_WARM flag and put it onto the warmqueue. Warm bufs are also
1390  * directly returned to the end of the warmqueue. As with the hotqueue, when
1391  * the warmqueue grows too large, B_WARM bufs are moved onto the coldqueue.
1392  *
1393  * Note that this design does still support large working sets, greater
1394  * than the cap of hotqueue or warmqueue would imply. The coldqueue is still
1395  * cached and has no maximum length. The hot and warm queues form a Y feeding
1396  * into the coldqueue. Moving bufs between queues is constant time, so this
1397  * design decays to one long warm->cold queue.
1398  *
1399  * In the 2Q paper, hotqueue and coldqueue are A1in and A1out. The warmqueue
1400  * is Am. We always cache pages, as opposed to pointers to pages for A1.
1401  *
1402  * This implementation adds support for multiple 2q caches.
1403  *
1404  * If we have more than one 2q cache, as bufs fall off the cold queue
1405  * for recyclying, bufs that have been warm before (which retain the
1406  * B_WARM flag in addition to B_COLD) can be put into the hot queue of
1407  * a second level 2Q cache. buffers which are only B_COLD are
1408  * recycled. Bufs falling off the last cache's cold queue are always
1409  * recycled.
1410  *
1411  */
1412 
1413 /*
1414  * this function is called when a hot or warm queue may have exceeded its
1415  * size limit. it will move a buf to the coldqueue.
1416  */
1417 int chillbufs(struct
1418     bufcache *cache, struct bufqueue *queue, int64_t *queuepages);
1419 
1420 void
1421 bufcache_init(void)
1422 {
1423 	int i;
1424 	for (i=0; i < NUM_CACHES; i++) {
1425 		TAILQ_INIT(&cleancache[i].hotqueue);
1426 		TAILQ_INIT(&cleancache[i].coldqueue);
1427 		TAILQ_INIT(&cleancache[i].warmqueue);
1428 	}
1429 	TAILQ_INIT(&dirtyqueue);
1430 }
1431 
1432 /*
1433  * if the buffer caches have shrunk, we may need to rebalance our queues.
1434  */
1435 void
1436 bufcache_adjust(void)
1437 {
1438 	int i;
1439 	for (i=0; i < NUM_CACHES; i++) {
1440 		while (chillbufs(&cleancache[i], &cleancache[i].warmqueue,
1441 		    &cleancache[i].warmbufpages) ||
1442 		    chillbufs(&cleancache[i], &cleancache[i].hotqueue,
1443 		    &cleancache[i].hotbufpages))
1444 			continue;
1445 	}
1446 }
1447 
1448 /*
1449  * Get a clean buffer from the cache. if "discard" is set do not promote
1450  * previously warm buffers as normal, because we are tossing everything
1451  * away such as in a hibernation
1452  */
1453 struct buf *
1454 bufcache_getcleanbuf(int cachenum, int discard)
1455 {
1456 	struct buf *bp = NULL;
1457 	struct bufcache *cache = &cleancache[cachenum];
1458 
1459 	splassert(IPL_BIO);
1460 
1461 	/* try  cold queue */
1462 	while ((bp = TAILQ_FIRST(&cache->coldqueue))) {
1463 		if ((!discard) &&
1464 		    cachenum < NUM_CACHES - 1 && ISSET(bp->b_flags, B_WARM)) {
1465 			int64_t pages = atop(bp->b_bufsize);
1466 			struct bufcache *newcache;
1467 
1468 			KASSERT(bp->cache == cachenum);
1469 
1470 			/*
1471 			 * If this buffer was warm before, move it to
1472 			 * the hot queue in the next cache
1473 			 */
1474 
1475 			if (fliphigh) {
1476 				/*
1477 				 * If we are in the DMA cache, try to flip the
1478 				 * buffer up high to move it on to the other
1479 				 * caches. if we can't move the buffer to high
1480 				 * memory without sleeping, we give it up and
1481 				 * return it rather than fight for more memory
1482 				 * against non buffer cache competitors.
1483 				 */
1484 				SET(bp->b_flags, B_BUSY);
1485 				if (bp->cache == 0 && buf_flip_high(bp) == -1) {
1486 					CLR(bp->b_flags, B_BUSY);
1487 					return bp;
1488 				}
1489 				CLR(bp->b_flags, B_BUSY);
1490 			}
1491 
1492 			/* Move the buffer to the hot queue in the next cache */
1493 			TAILQ_REMOVE(&cache->coldqueue, bp, b_freelist);
1494 			CLR(bp->b_flags, B_WARM);
1495 			CLR(bp->b_flags, B_COLD);
1496 			bp->cache++;
1497 			newcache= &cleancache[bp->cache];
1498 			newcache->cachepages += pages;
1499 			newcache->hotbufpages += pages;
1500 			chillbufs(newcache, &newcache->hotqueue,
1501 			    &newcache->hotbufpages);
1502 			TAILQ_INSERT_TAIL(&newcache->hotqueue, bp, b_freelist);
1503 		}
1504 		else
1505 			/* buffer is cold - give it up */
1506 			return bp;
1507 	}
1508 	if ((bp = TAILQ_FIRST(&cache->warmqueue)))
1509 		return bp;
1510 	if ((bp = TAILQ_FIRST(&cache->hotqueue)))
1511  		return bp;
1512 	return bp;
1513 }
1514 
1515 struct buf *
1516 bufcache_getcleanbuf_range(int start, int end, int discard)
1517 {
1518 	int i, j = start, q = end;
1519 	struct buf *bp = NULL;
1520 
1521 	/*
1522 	 * XXX in theory we could promote warm buffers into a previous queue
1523 	 * so in the pathological case of where we go through all the caches
1524 	 * without getting a buffer we have to start at the beginning again.
1525 	 */
1526 	while (j <= q)	{
1527 		for (i = q; i >= j; i--)
1528 			if ((bp = bufcache_getcleanbuf(i, discard)))
1529 				return(bp);
1530 		j++;
1531 	}
1532 	return bp;
1533 }
1534 
1535 struct buf *
1536 bufcache_gethighcleanbuf(void)
1537 {
1538 	if (!fliphigh)
1539 		return NULL;
1540 	return bufcache_getcleanbuf_range(DMA_CACHE + 1, NUM_CACHES - 1, 0);
1541 }
1542 
1543 struct buf *
1544 bufcache_getdmacleanbuf(void)
1545 {
1546 	if (fliphigh)
1547 		return bufcache_getcleanbuf_range(DMA_CACHE, DMA_CACHE, 0);
1548 	return bufcache_getcleanbuf_range(DMA_CACHE, NUM_CACHES - 1, 0);
1549 }
1550 
1551 struct buf *
1552 bufcache_getdirtybuf(void)
1553 {
1554 	return TAILQ_FIRST(&dirtyqueue);
1555 }
1556 
1557 void
1558 bufcache_take(struct buf *bp)
1559 {
1560 	struct bufqueue *queue;
1561 	int64_t pages;
1562 
1563 	splassert(IPL_BIO);
1564 	KASSERT(ISSET(bp->b_flags, B_BC));
1565 	KASSERT(bp->cache >= DMA_CACHE);
1566 	KASSERT((bp->cache < NUM_CACHES));
1567 
1568 	pages = atop(bp->b_bufsize);
1569 	struct bufcache *cache = &cleancache[bp->cache];
1570 	if (!ISSET(bp->b_flags, B_DELWRI)) {
1571                 if (ISSET(bp->b_flags, B_COLD)) {
1572 			queue = &cache->coldqueue;
1573 		} else if (ISSET(bp->b_flags, B_WARM)) {
1574 			queue = &cache->warmqueue;
1575 			cache->warmbufpages -= pages;
1576 		} else {
1577 			queue = &cache->hotqueue;
1578 			cache->hotbufpages -= pages;
1579 		}
1580 		bcstats.numcleanpages -= pages;
1581 		cache->cachepages -= pages;
1582 	} else {
1583 		queue = &dirtyqueue;
1584 		bcstats.numdirtypages -= pages;
1585 		bcstats.delwribufs--;
1586 	}
1587 	TAILQ_REMOVE(queue, bp, b_freelist);
1588 }
1589 
1590 /* move buffers from a hot or warm queue to a cold queue in a cache */
1591 int
1592 chillbufs(struct bufcache *cache, struct bufqueue *queue, int64_t *queuepages)
1593 {
1594 	struct buf *bp;
1595 	int64_t limit, pages;
1596 
1597 	/*
1598 	 * We limit the hot queue to be small, with a max of 4096 pages.
1599 	 * We limit the warm queue to half the cache size.
1600 	 *
1601 	 * We impose a minimum size of 96 to prevent too much "wobbling".
1602 	 */
1603 	if (queue == &cache->hotqueue)
1604 		limit = min(cache->cachepages / 20, 4096);
1605 	else if (queue == &cache->warmqueue)
1606 		limit = (cache->cachepages / 2);
1607 	else
1608 		panic("chillbufs: invalid queue");
1609 
1610 	if (*queuepages > 96 && *queuepages > limit) {
1611 		bp = TAILQ_FIRST(queue);
1612 		if (!bp)
1613 			panic("inconsistent bufpage counts");
1614 		pages = atop(bp->b_bufsize);
1615 		*queuepages -= pages;
1616 		TAILQ_REMOVE(queue, bp, b_freelist);
1617 		/* we do not clear B_WARM */
1618 		SET(bp->b_flags, B_COLD);
1619 		TAILQ_INSERT_TAIL(&cache->coldqueue, bp, b_freelist);
1620 		return 1;
1621 	}
1622 	return 0;
1623 }
1624 
1625 void
1626 bufcache_release(struct buf *bp)
1627 {
1628 	struct bufqueue *queue;
1629 	int64_t pages;
1630 	struct bufcache *cache = &cleancache[bp->cache];
1631 
1632 	pages = atop(bp->b_bufsize);
1633 	KASSERT(ISSET(bp->b_flags, B_BC));
1634 	if (fliphigh) {
1635 		if (ISSET(bp->b_flags, B_DMA) && bp->cache > 0)
1636 			panic("B_DMA buffer release from cache %d",
1637 			    bp->cache);
1638 		else if ((!ISSET(bp->b_flags, B_DMA)) && bp->cache == 0)
1639 			panic("Non B_DMA buffer release from cache %d",
1640 			    bp->cache);
1641 	}
1642 
1643 	if (!ISSET(bp->b_flags, B_DELWRI)) {
1644 		int64_t *queuepages;
1645 		if (ISSET(bp->b_flags, B_WARM | B_COLD)) {
1646 			SET(bp->b_flags, B_WARM);
1647 			CLR(bp->b_flags, B_COLD);
1648 			queue = &cache->warmqueue;
1649 			queuepages = &cache->warmbufpages;
1650 		} else {
1651 			queue = &cache->hotqueue;
1652 			queuepages = &cache->hotbufpages;
1653 		}
1654 		*queuepages += pages;
1655 		bcstats.numcleanpages += pages;
1656 		cache->cachepages += pages;
1657 		chillbufs(cache, queue, queuepages);
1658 	} else {
1659 		queue = &dirtyqueue;
1660 		bcstats.numdirtypages += pages;
1661 		bcstats.delwribufs++;
1662 	}
1663 	TAILQ_INSERT_TAIL(queue, bp, b_freelist);
1664 }
1665 
1666 #ifdef HIBERNATE
1667 /*
1668  * Nuke the buffer cache from orbit when hibernating. We do not want to save
1669  * any clean cache pages to swap and read them back. the original disk files
1670  * are just as good.
1671  */
1672 void
1673 hibernate_suspend_bufcache(void)
1674 {
1675 	struct buf *bp;
1676 	int s;
1677 
1678 	s = splbio();
1679 	/* Chuck away all the cache pages.. discard bufs, do not promote */
1680 	while ((bp = bufcache_getcleanbuf_range(DMA_CACHE, NUM_CACHES - 1, 1))) {
1681 		bufcache_take(bp);
1682 		if (bp->b_vp) {
1683 			RBT_REMOVE(buf_rb_bufs, &bp->b_vp->v_bufs_tree, bp);
1684 			brelvp(bp);
1685 		}
1686 		buf_put(bp);
1687 	}
1688 	splx(s);
1689 }
1690 
1691 void
1692 hibernate_resume_bufcache(void)
1693 {
1694 	/* XXX Nothing needed here for now */
1695 }
1696 #endif /* HIBERNATE */
1697