]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/boot/common/bcache.c
MFV r313676: libpcap 1.8.1
[FreeBSD/FreeBSD.git] / sys / boot / common / bcache.c
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * Copyright 2015 Toomas Soome <tsoome@me.com>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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.
14  *
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
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 #include <sys/param.h>
30 __FBSDID("$FreeBSD$");
31
32 /*
33  * Simple hashed block cache
34  */
35
36 #include <sys/stdint.h>
37
38 #include <stand.h>
39 #include <string.h>
40 #include <strings.h>
41
42 #include "bootstrap.h"
43
44 /* #define BCACHE_DEBUG */
45
46 #ifdef BCACHE_DEBUG
47 # define DEBUG(fmt, args...)    printf("%s: " fmt "\n" , __func__ , ## args)
48 #else
49 # define DEBUG(fmt, args...)
50 #endif
51
52 struct bcachectl
53 {
54     daddr_t     bc_blkno;
55     int         bc_count;
56 };
57
58 /*
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.
63  */
64 struct bcache {
65     struct bcachectl    *bcache_ctl;
66     caddr_t             bcache_data;
67     size_t              bcache_nblks;
68     size_t              ra;
69 };
70
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 */
74 /* statistics */
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;
83
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
89 #define BCACHE_MARKER           0xdeadbeef
90
91 static void     bcache_invalidate(struct bcache *bc, daddr_t blkno);
92 static void     bcache_insert(struct bcache *bc, daddr_t blkno);
93 static void     bcache_free_instance(struct bcache *bc);
94
95 /*
96  * Initialise the cache for (nblks) of (bsize).
97  */
98 void
99 bcache_init(size_t nblks, size_t bsize)
100 {
101     /* set up control data */
102     bcache_total_nblks = nblks;
103     bcache_blksize = bsize;
104 }
105
106 /*
107  * add number of devices to bcache. we have to divide cache space
108  * between the devices, so bcache_add_dev() can be used to set up the
109  * number. The issue is, we need to get the number before actual allocations.
110  * bcache_add_dev() is supposed to be called from device init() call, so the
111  * assumption is, devsw dv_init is called for plain devices first, and
112  * for zfs, last.
113  */
114 void
115 bcache_add_dev(int devices)
116 {
117     bcache_numdev += devices;
118 }
119
120 void *
121 bcache_allocate(void)
122 {
123     u_int i;
124     struct bcache *bc = malloc(sizeof (struct bcache));
125     int disks = bcache_numdev;
126     uint32_t *marker;
127
128     if (disks == 0)
129         disks = 1;      /* safe guard */
130
131     if (bc == NULL) {
132         errno = ENOMEM;
133         return (bc);
134     }
135
136     /*
137      * the bcache block count must be power of 2 for hash function
138      */
139     i = fls(disks) - 1;         /* highbit - 1 */
140     if (disks > (1 << i))       /* next power of 2 */
141         i++;
142
143     bc->bcache_nblks = bcache_total_nblks >> i;
144     bcache_unit_nblks = bc->bcache_nblks;
145     bc->bcache_data = malloc(bc->bcache_nblks * bcache_blksize +
146         sizeof(uint32_t));
147     if (bc->bcache_data == NULL) {
148         /* dont error out yet. fall back to 32 blocks and try again */
149         bc->bcache_nblks = 32;
150         bc->bcache_data = malloc(bc->bcache_nblks * bcache_blksize +
151         sizeof(uint32_t));
152     }
153
154     bc->bcache_ctl = malloc(bc->bcache_nblks * sizeof(struct bcachectl));
155
156     if ((bc->bcache_data == NULL) || (bc->bcache_ctl == NULL)) {
157         bcache_free_instance(bc);
158         errno = ENOMEM;
159         return (NULL);
160     }
161     /* Insert cache end marker. */
162     marker = (uint32_t *)(bc->bcache_data + bc->bcache_nblks * bcache_blksize);
163     *marker = BCACHE_MARKER;
164
165     /* Flush the cache */
166     for (i = 0; i < bc->bcache_nblks; i++) {
167         bc->bcache_ctl[i].bc_count = -1;
168         bc->bcache_ctl[i].bc_blkno = -1;
169     }
170     bcache_units++;
171     bc->ra = BCACHE_READAHEAD;  /* optimistic read ahead */
172     return (bc);
173 }
174
175 void
176 bcache_free(void *cache)
177 {
178     struct bcache *bc = cache;
179
180     if (bc == NULL)
181         return;
182
183     bcache_free_instance(bc);
184     bcache_units--;
185 }
186
187 /*
188  * Handle a write request; write directly to the disk, and populate the
189  * cache with the new values.
190  */
191 static int
192 write_strategy(void *devdata, int rw, daddr_t blk, size_t size,
193     char *buf, size_t *rsize)
194 {
195     struct bcache_devdata       *dd = (struct bcache_devdata *)devdata;
196     struct bcache               *bc = dd->dv_cache;
197     daddr_t                     i, nblk;
198
199     nblk = size / bcache_blksize;
200
201     /* Invalidate the blocks being written */
202     for (i = 0; i < nblk; i++) {
203         bcache_invalidate(bc, blk + i);
204     }
205
206     /* Write the blocks */
207     return (dd->dv_strategy(dd->dv_devdata, rw, blk, size, buf, rsize));
208 }
209
210 /*
211  * Handle a read request; fill in parts of the request that can
212  * be satisfied by the cache, use the supplied strategy routine to do
213  * device I/O and then use the I/O results to populate the cache. 
214  */
215 static int
216 read_strategy(void *devdata, int rw, daddr_t blk, size_t size,
217     char *buf, size_t *rsize)
218 {
219     struct bcache_devdata       *dd = (struct bcache_devdata *)devdata;
220     struct bcache               *bc = dd->dv_cache;
221     size_t                      i, nblk, p_size, r_size, complete, ra;
222     int                         result;
223     daddr_t                     p_blk;
224     caddr_t                     p_buf;
225     uint32_t                    *marker;
226
227     if (bc == NULL) {
228         errno = ENODEV;
229         return (-1);
230     }
231
232     marker = (uint32_t *)(bc->bcache_data + bc->bcache_nblks * bcache_blksize);
233
234     if (rsize != NULL)
235         *rsize = 0;
236
237     nblk = size / bcache_blksize;
238     if (nblk == 0 && size != 0)
239         nblk++;
240     result = 0;
241     complete = 1;
242
243     /* Satisfy any cache hits up front, break on first miss */
244     for (i = 0; i < nblk; i++) {
245         if (BCACHE_LOOKUP(bc, (daddr_t)(blk + i))) {
246             bcache_misses += (nblk - i);
247             complete = 0;
248             if (nblk - i > BCACHE_MINREADAHEAD && bc->ra > BCACHE_MINREADAHEAD)
249                 bc->ra >>= 1;   /* reduce read ahead */
250             break;
251         } else {
252             bcache_hits++;
253         }
254     }
255
256    if (complete) {      /* whole set was in cache, return it */
257         if (bc->ra < BCACHE_READAHEAD)
258                 bc->ra <<= 1;   /* increase read ahead */
259         bcopy(bc->bcache_data + (bcache_blksize * BHASH(bc, blk)), buf, size);
260         goto done;
261    }
262
263     /*
264      * Fill in any misses. From check we have i pointing to first missing
265      * block, read in all remaining blocks + readahead.
266      * We have space at least for nblk - i before bcache wraps.
267      */
268     p_blk = blk + i;
269     p_buf = bc->bcache_data + (bcache_blksize * BHASH(bc, p_blk));
270     r_size = bc->bcache_nblks - BHASH(bc, p_blk); /* remaining blocks */
271
272     p_size = MIN(r_size, nblk - i);     /* read at least those blocks */
273
274     /*
275      * The read ahead size setup.
276      * While the read ahead can save us IO, it also can complicate things:
277      * 1. We do not want to read ahead by wrapping around the
278      * bcache end - this would complicate the cache management.
279      * 2. We are using bc->ra as dynamic hint for read ahead size,
280      * detected cache hits will increase the read-ahead block count, and
281      * misses will decrease, see the code above.
282      * 3. The bcache is sized by 512B blocks, however, the underlying device
283      * may have a larger sector size, and we should perform the IO by
284      * taking into account these larger sector sizes. We could solve this by
285      * passing the sector size to bcache_allocate(), or by using ioctl(), but
286      * in this version we are using the constant, 16 blocks, and are rounding
287      * read ahead block count down to multiple of 16.
288      * Using the constant has two reasons, we are not entirely sure if the
289      * BIOS disk interface is providing the correct value for sector size.
290      * And secondly, this way we get the most conservative setup for the ra.
291      *
292      * The selection of multiple of 16 blocks (8KB) is quite arbitrary, however,
293      * we want to cover CDs (2K) and 4K disks.
294      * bcache_allocate() will always fall back to a minimum of 32 blocks.
295      * Our choice of 16 read ahead blocks will always fit inside the bcache.
296      */
297
298     ra = bc->bcache_nblks - BHASH(bc, p_blk + p_size);
299     if (ra != 0 && ra != bc->bcache_nblks) { /* do we have RA space? */
300         ra = MIN(bc->ra, ra - 1);
301         ra = rounddown(ra, 16);         /* multiple of 16 blocks */
302         p_size += ra;
303     }
304
305     /* invalidate bcache */
306     for (i = 0; i < p_size; i++) {
307         bcache_invalidate(bc, p_blk + i);
308     }
309
310     r_size = 0;
311     /*
312      * with read-ahead, it may happen we are attempting to read past
313      * disk end, as bcache has no information about disk size.
314      * in such case we should get partial read if some blocks can be
315      * read or error, if no blocks can be read.
316      * in either case we should return the data in bcache and only
317      * return error if there is no data.
318      */
319     result = dd->dv_strategy(dd->dv_devdata, rw, p_blk,
320         p_size * bcache_blksize, p_buf, &r_size);
321
322     r_size /= bcache_blksize;
323     for (i = 0; i < r_size; i++)
324         bcache_insert(bc, p_blk + i);
325
326     /* update ra statistics */
327     if (r_size != 0) {
328         if (r_size < p_size)
329             bcache_rablks += (p_size - r_size);
330         else
331             bcache_rablks += ra;
332     }
333
334     /* check how much data can we copy */
335     for (i = 0; i < nblk; i++) {
336         if (BCACHE_LOOKUP(bc, (daddr_t)(blk + i)))
337             break;
338     }
339
340     if (size > i * bcache_blksize)
341         size = i * bcache_blksize;
342
343     if (size != 0) {
344         bcopy(bc->bcache_data + (bcache_blksize * BHASH(bc, blk)), buf, size);
345         result = 0;
346     }
347
348     if (*marker != BCACHE_MARKER) {
349         printf("BUG: bcache corruption detected: nblks: %zu p_blk: %lu, "
350             "p_size: %zu, ra: %zu\n", bc->bcache_nblks,
351             (long unsigned)BHASH(bc, p_blk), p_size, ra);
352     }
353
354  done:
355     if ((result == 0) && (rsize != NULL))
356         *rsize = size;
357     return(result);
358 }
359
360 /* 
361  * Requests larger than 1/2 cache size will be bypassed and go
362  * directly to the disk.  XXX tune this.
363  */
364 int
365 bcache_strategy(void *devdata, int rw, daddr_t blk, size_t size,
366     char *buf, size_t *rsize)
367 {
368     struct bcache_devdata       *dd = (struct bcache_devdata *)devdata;
369     struct bcache               *bc = dd->dv_cache;
370     u_int bcache_nblks = 0;
371     int nblk, cblk, ret;
372     size_t csize, isize, total;
373
374     bcache_ops++;
375
376     if (bc != NULL)
377         bcache_nblks = bc->bcache_nblks;
378
379     /* bypass large requests, or when the cache is inactive */
380     if (bc == NULL ||
381         ((size * 2 / bcache_blksize) > bcache_nblks)) {
382         DEBUG("bypass %zu from %qu", size / bcache_blksize, blk);
383         bcache_bypasses++;
384         return (dd->dv_strategy(dd->dv_devdata, rw, blk, size, buf, rsize));
385     }
386
387     switch (rw) {
388     case F_READ:
389         nblk = size / bcache_blksize;
390         if (size != 0 && nblk == 0)
391             nblk++;     /* read at least one block */
392
393         ret = 0;
394         total = 0;
395         while(size) {
396             cblk = bcache_nblks - BHASH(bc, blk); /* # of blocks left */
397             cblk = MIN(cblk, nblk);
398
399             if (size <= bcache_blksize)
400                 csize = size;
401             else
402                 csize = cblk * bcache_blksize;
403
404             ret = read_strategy(devdata, rw, blk, csize, buf+total, &isize);
405
406             /*
407              * we may have error from read ahead, if we have read some data
408              * return partial read.
409              */
410             if (ret != 0 || isize == 0) {
411                 if (total != 0)
412                     ret = 0;
413                 break;
414             }
415             blk += isize / bcache_blksize;
416             total += isize;
417             size -= isize;
418             nblk = size / bcache_blksize;
419         }
420
421         if (rsize)
422             *rsize = total;
423
424         return (ret);
425     case F_WRITE:
426         return write_strategy(devdata, rw, blk, size, buf, rsize);
427     }
428     return -1;
429 }
430
431 /*
432  * Free allocated bcache instance
433  */
434 static void
435 bcache_free_instance(struct bcache *bc)
436 {
437     if (bc != NULL) {
438         if (bc->bcache_ctl)
439             free(bc->bcache_ctl);
440         if (bc->bcache_data)
441             free(bc->bcache_data);
442         free(bc);
443     }
444 }
445
446 /*
447  * Insert a block into the cache.
448  */
449 static void
450 bcache_insert(struct bcache *bc, daddr_t blkno)
451 {
452     u_int       cand;
453     
454     cand = BHASH(bc, blkno);
455
456     DEBUG("insert blk %llu -> %u # %d", blkno, cand, bcache_bcount);
457     bc->bcache_ctl[cand].bc_blkno = blkno;
458     bc->bcache_ctl[cand].bc_count = bcache_bcount++;
459 }
460
461 /*
462  * Invalidate a block from the cache.
463  */
464 static void
465 bcache_invalidate(struct bcache *bc, daddr_t blkno)
466 {
467     u_int       i;
468     
469     i = BHASH(bc, blkno);
470     if (bc->bcache_ctl[i].bc_blkno == blkno) {
471         bc->bcache_ctl[i].bc_count = -1;
472         bc->bcache_ctl[i].bc_blkno = -1;
473         DEBUG("invalidate blk %llu", blkno);
474     }
475 }
476
477 #ifndef BOOT2
478 COMMAND_SET(bcachestat, "bcachestat", "get disk block cache stats", command_bcache);
479
480 static int
481 command_bcache(int argc, char *argv[])
482 {
483     if (argc != 1) {
484         command_errmsg = "wrong number of arguments";
485         return(CMD_ERROR);
486     }
487
488     printf("\ncache blocks: %d\n", bcache_total_nblks);
489     printf("cache blocksz: %d\n", bcache_blksize);
490     printf("cache readahead: %d\n", bcache_rablks);
491     printf("unit cache blocks: %d\n", bcache_unit_nblks);
492     printf("cached units: %d\n", bcache_units);
493     printf("%d ops  %d bypasses  %d hits  %d misses\n", bcache_ops,
494         bcache_bypasses, bcache_hits, bcache_misses);
495     return(CMD_OK);
496 }
497 #endif