2 * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3 * Copyright 2015 Toomas Soome <tsoome@me.com>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 #include <sys/cdefs.h>
29 #include <sys/param.h>
30 __FBSDID("$FreeBSD$");
33 * Simple hashed block cache
36 #include <sys/stdint.h>
42 #include "bootstrap.h"
44 /* #define BCACHE_DEBUG */
47 # define DPRINTF(fmt, args...) printf("%s: " fmt "\n" , __func__ , ## args)
49 # define DPRINTF(fmt, args...) ((void)0)
59 * bcache per device node. cache is allocated on device first open and freed
60 * on last close, to save memory. The issue there is the size; biosdisk
61 * supports up to 31 (0x1f) devices. Classic setup would use single disk
62 * to boot from, but this has changed with zfs.
65 struct bcachectl *bcache_ctl;
71 static u_int bcache_total_nblks; /* set by bcache_init */
72 static u_int bcache_blksize; /* set by bcache_init */
73 static u_int bcache_numdev; /* set by bcache_add_dev */
75 static u_int bcache_units; /* number of devices with cache */
76 static u_int bcache_unit_nblks; /* nblocks per unit */
77 static u_int bcache_hits;
78 static u_int bcache_misses;
79 static u_int bcache_ops;
80 static u_int bcache_bypasses;
81 static u_int bcache_bcount;
82 static u_int bcache_rablks;
84 #define BHASH(bc, blkno) ((blkno) & ((bc)->bcache_nblks - 1))
85 #define BCACHE_LOOKUP(bc, blkno) \
86 ((bc)->bcache_ctl[BHASH((bc), (blkno))].bc_blkno != (blkno))
87 #define BCACHE_READAHEAD 256
88 #define BCACHE_MINREADAHEAD 32
90 static void bcache_invalidate(struct bcache *bc, daddr_t blkno);
91 static void bcache_insert(struct bcache *bc, daddr_t blkno);
92 static void bcache_free_instance(struct bcache *bc);
95 * Initialise the cache for (nblks) of (bsize).
98 bcache_init(size_t nblks, size_t bsize)
100 /* set up control data */
101 bcache_total_nblks = nblks;
102 bcache_blksize = bsize;
106 * add number of devices to bcache. we have to divide cache space
107 * between the devices, so bcache_add_dev() can be used to set up the
108 * number. The issue is, we need to get the number before actual allocations.
109 * bcache_add_dev() is supposed to be called from device init() call, so the
110 * assumption is, devsw dv_init is called for plain devices first, and
114 bcache_add_dev(int devices)
116 bcache_numdev += devices;
120 bcache_allocate(void)
123 struct bcache *bc = malloc(sizeof (struct bcache));
124 int disks = bcache_numdev;
127 disks = 1; /* safe guard */
135 * the bcache block count must be power of 2 for hash function
137 i = fls(disks) - 1; /* highbit - 1 */
138 if (disks > (1 << i)) /* next power of 2 */
141 bc->bcache_nblks = bcache_total_nblks >> i;
142 bcache_unit_nblks = bc->bcache_nblks;
143 bc->bcache_data = malloc(bc->bcache_nblks * bcache_blksize);
144 if (bc->bcache_data == NULL) {
145 /* dont error out yet. fall back to 32 blocks and try again */
146 bc->bcache_nblks = 32;
147 bc->bcache_data = malloc(bc->bcache_nblks * bcache_blksize +
151 bc->bcache_ctl = malloc(bc->bcache_nblks * sizeof(struct bcachectl));
153 if ((bc->bcache_data == NULL) || (bc->bcache_ctl == NULL)) {
154 bcache_free_instance(bc);
159 /* Flush the cache */
160 for (i = 0; i < bc->bcache_nblks; i++) {
161 bc->bcache_ctl[i].bc_count = -1;
162 bc->bcache_ctl[i].bc_blkno = -1;
165 bc->ra = BCACHE_READAHEAD; /* optimistic read ahead */
170 bcache_free(void *cache)
172 struct bcache *bc = cache;
177 bcache_free_instance(bc);
182 * Handle a write request; write directly to the disk, and populate the
183 * cache with the new values.
186 write_strategy(void *devdata, int rw, daddr_t blk, size_t size,
187 char *buf, size_t *rsize)
189 struct bcache_devdata *dd = (struct bcache_devdata *)devdata;
190 struct bcache *bc = dd->dv_cache;
193 nblk = size / bcache_blksize;
195 /* Invalidate the blocks being written */
196 for (i = 0; i < nblk; i++) {
197 bcache_invalidate(bc, blk + i);
200 /* Write the blocks */
201 return (dd->dv_strategy(dd->dv_devdata, rw, blk, size, buf, rsize));
205 * Handle a read request; fill in parts of the request that can
206 * be satisfied by the cache, use the supplied strategy routine to do
207 * device I/O and then use the I/O results to populate the cache.
210 read_strategy(void *devdata, int rw, daddr_t blk, size_t size,
211 char *buf, size_t *rsize)
213 struct bcache_devdata *dd = (struct bcache_devdata *)devdata;
214 struct bcache *bc = dd->dv_cache;
215 size_t i, nblk, p_size, r_size, complete, ra;
228 nblk = size / bcache_blksize;
229 if (nblk == 0 && size != 0)
234 /* Satisfy any cache hits up front, break on first miss */
235 for (i = 0; i < nblk; i++) {
236 if (BCACHE_LOOKUP(bc, (daddr_t)(blk + i))) {
237 bcache_misses += (nblk - i);
239 if (nblk - i > BCACHE_MINREADAHEAD && bc->ra > BCACHE_MINREADAHEAD)
240 bc->ra >>= 1; /* reduce read ahead */
247 if (complete) { /* whole set was in cache, return it */
248 if (bc->ra < BCACHE_READAHEAD)
249 bc->ra <<= 1; /* increase read ahead */
250 bcopy(bc->bcache_data + (bcache_blksize * BHASH(bc, blk)), buf, size);
255 * Fill in any misses. From check we have i pointing to first missing
256 * block, read in all remaining blocks + readahead.
257 * We have space at least for nblk - i before bcache wraps.
260 p_buf = bc->bcache_data + (bcache_blksize * BHASH(bc, p_blk));
261 r_size = bc->bcache_nblks - BHASH(bc, p_blk); /* remaining blocks */
263 p_size = MIN(r_size, nblk - i); /* read at least those blocks */
266 * The read ahead size setup.
267 * While the read ahead can save us IO, it also can complicate things:
268 * 1. We do not want to read ahead by wrapping around the
269 * bcache end - this would complicate the cache management.
270 * 2. We are using bc->ra as dynamic hint for read ahead size,
271 * detected cache hits will increase the read-ahead block count, and
272 * misses will decrease, see the code above.
273 * 3. The bcache is sized by 512B blocks, however, the underlying device
274 * may have a larger sector size, and we should perform the IO by
275 * taking into account these larger sector sizes. We could solve this by
276 * passing the sector size to bcache_allocate(), or by using ioctl(), but
277 * in this version we are using the constant, 16 blocks, and are rounding
278 * read ahead block count down to multiple of 16.
279 * Using the constant has two reasons, we are not entirely sure if the
280 * BIOS disk interface is providing the correct value for sector size.
281 * And secondly, this way we get the most conservative setup for the ra.
283 * The selection of multiple of 16 blocks (8KB) is quite arbitrary, however,
284 * we want to cover CDs (2K) and 4K disks.
285 * bcache_allocate() will always fall back to a minimum of 32 blocks.
286 * Our choice of 16 read ahead blocks will always fit inside the bcache.
289 if ((rw & F_NORA) == F_NORA)
292 ra = bc->bcache_nblks - BHASH(bc, p_blk + p_size);
294 if (ra != 0 && ra != bc->bcache_nblks) { /* do we have RA space? */
295 ra = MIN(bc->ra, ra - 1);
296 ra = rounddown(ra, 16); /* multiple of 16 blocks */
300 /* invalidate bcache */
301 for (i = 0; i < p_size; i++) {
302 bcache_invalidate(bc, p_blk + i);
307 * with read-ahead, it may happen we are attempting to read past
308 * disk end, as bcache has no information about disk size.
309 * in such case we should get partial read if some blocks can be
310 * read or error, if no blocks can be read.
311 * in either case we should return the data in bcache and only
312 * return error if there is no data.
315 result = dd->dv_strategy(dd->dv_devdata, rw, p_blk,
316 p_size * bcache_blksize, p_buf, &r_size);
318 r_size /= bcache_blksize;
319 for (i = 0; i < r_size; i++)
320 bcache_insert(bc, p_blk + i);
322 /* update ra statistics */
325 bcache_rablks += (p_size - r_size);
330 /* check how much data can we copy */
331 for (i = 0; i < nblk; i++) {
332 if (BCACHE_LOOKUP(bc, (daddr_t)(blk + i)))
336 if (size > i * bcache_blksize)
337 size = i * bcache_blksize;
340 bcopy(bc->bcache_data + (bcache_blksize * BHASH(bc, blk)), buf, size);
345 if ((result == 0) && (rsize != NULL))
351 * Requests larger than 1/2 cache size will be bypassed and go
352 * directly to the disk. XXX tune this.
355 bcache_strategy(void *devdata, int rw, daddr_t blk, size_t size,
356 char *buf, size_t *rsize)
358 struct bcache_devdata *dd = (struct bcache_devdata *)devdata;
359 struct bcache *bc = dd->dv_cache;
360 u_int bcache_nblks = 0;
362 size_t csize, isize, total;
367 bcache_nblks = bc->bcache_nblks;
369 /* bypass large requests, or when the cache is inactive */
371 ((size * 2 / bcache_blksize) > bcache_nblks)) {
372 DPRINTF("bypass %zu from %qu", size / bcache_blksize, blk);
375 return (dd->dv_strategy(dd->dv_devdata, rw, blk, size, buf, rsize));
378 switch (rw & F_MASK) {
380 nblk = size / bcache_blksize;
381 if (size != 0 && nblk == 0)
382 nblk++; /* read at least one block */
387 cblk = bcache_nblks - BHASH(bc, blk); /* # of blocks left */
388 cblk = MIN(cblk, nblk);
390 if (size <= bcache_blksize)
393 csize = cblk * bcache_blksize;
395 ret = read_strategy(devdata, rw, blk, csize, buf+total, &isize);
398 * we may have error from read ahead, if we have read some data
399 * return partial read.
401 if (ret != 0 || isize == 0) {
406 blk += isize / bcache_blksize;
409 nblk = size / bcache_blksize;
417 return write_strategy(devdata, F_WRITE, blk, size, buf, rsize);
423 * Free allocated bcache instance
426 bcache_free_instance(struct bcache *bc)
429 free(bc->bcache_ctl);
430 free(bc->bcache_data);
436 * Insert a block into the cache.
439 bcache_insert(struct bcache *bc, daddr_t blkno)
443 cand = BHASH(bc, blkno);
445 DPRINTF("insert blk %llu -> %u # %d", blkno, cand, bcache_bcount);
446 bc->bcache_ctl[cand].bc_blkno = blkno;
447 bc->bcache_ctl[cand].bc_count = bcache_bcount++;
451 * Invalidate a block from the cache.
454 bcache_invalidate(struct bcache *bc, daddr_t blkno)
458 i = BHASH(bc, blkno);
459 if (bc->bcache_ctl[i].bc_blkno == blkno) {
460 bc->bcache_ctl[i].bc_count = -1;
461 bc->bcache_ctl[i].bc_blkno = -1;
462 DPRINTF("invalidate blk %llu", blkno);
467 COMMAND_SET(bcachestat, "bcachestat", "get disk block cache stats", command_bcache);
470 command_bcache(int argc, char *argv[] __unused)
473 command_errmsg = "wrong number of arguments";
477 printf("\ncache blocks: %u\n", bcache_total_nblks);
478 printf("cache blocksz: %u\n", bcache_blksize);
479 printf("cache readahead: %u\n", bcache_rablks);
480 printf("unit cache blocks: %u\n", bcache_unit_nblks);
481 printf("cached units: %u\n", bcache_units);
482 printf("%u ops %d bypasses %u hits %u misses\n", bcache_ops,
483 bcache_bypasses, bcache_hits, bcache_misses);