]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/subr_blist.c
Merge upstream r4302 to support multiple concurrently valid anchors.
[FreeBSD/FreeBSD.git] / sys / kern / subr_blist.c
1 /*-
2  * Copyright (c) 1998 Matthew Dillon.  All Rights Reserved.
3  * Redistribution and use in source and binary forms, with or without
4  * modification, are permitted provided that the following conditions
5  * are met:
6  * 1. Redistributions of source code must retain the above copyright
7  *    notice, this list of conditions and the following disclaimer.
8  * 2. Redistributions in binary form must reproduce the above copyright
9  *    notice, this list of conditions and the following disclaimer in the
10  *    documentation and/or other materials provided with the distribution.
11  * 3. Neither the name of the University nor the names of its contributors
12  *    may be used to endorse or promote products derived from this software
13  *    without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
16  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
19  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
21  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 /*
28  * BLIST.C -    Bitmap allocator/deallocator, using a radix tree with hinting
29  *
30  *      This module implements a general bitmap allocator/deallocator.  The
31  *      allocator eats around 2 bits per 'block'.  The module does not
32  *      try to interpret the meaning of a 'block' other than to return
33  *      SWAPBLK_NONE on an allocation failure.
34  *
35  *      A radix tree is used to maintain the bitmap.  Two radix constants are
36  *      involved:  One for the bitmaps contained in the leaf nodes (typically
37  *      64), and one for the meta nodes (typically 16).  Both meta and leaf
38  *      nodes have a hint field.  This field gives us a hint as to the largest
39  *      free contiguous range of blocks under the node.  It may contain a
40  *      value that is too high, but will never contain a value that is too
41  *      low.  When the radix tree is searched, allocation failures in subtrees
42  *      update the hint.
43  *
44  *      The radix tree also implements two collapsed states for meta nodes:
45  *      the ALL-ALLOCATED state and the ALL-FREE state.  If a meta node is
46  *      in either of these two states, all information contained underneath
47  *      the node is considered stale.  These states are used to optimize
48  *      allocation and freeing operations.
49  *
50  *      The hinting greatly increases code efficiency for allocations while
51  *      the general radix structure optimizes both allocations and frees.  The
52  *      radix tree should be able to operate well no matter how much
53  *      fragmentation there is and no matter how large a bitmap is used.
54  *
55  *      The blist code wires all necessary memory at creation time.  Neither
56  *      allocations nor frees require interaction with the memory subsystem.
57  *      The non-blocking features of the blist code are used in the swap code
58  *      (vm/swap_pager.c).
59  *
60  *      LAYOUT: The radix tree is laid out recursively using a
61  *      linear array.  Each meta node is immediately followed (laid out
62  *      sequentially in memory) by BLIST_META_RADIX lower level nodes.  This
63  *      is a recursive structure but one that can be easily scanned through
64  *      a very simple 'skip' calculation.  In order to support large radixes,
65  *      portions of the tree may reside outside our memory allocation.  We
66  *      handle this with an early-termination optimization (when bighint is
67  *      set to -1) on the scan.  The memory allocation is only large enough
68  *      to cover the number of blocks requested at creation time even if it
69  *      must be encompassed in larger root-node radix.
70  *
71  *      NOTE: the allocator cannot currently allocate more than
72  *      BLIST_BMAP_RADIX blocks per call.  It will panic with 'allocation too
73  *      large' if you try.  This is an area that could use improvement.  The
74  *      radix is large enough that this restriction does not effect the swap
75  *      system, though.  Currently only the allocation code is affected by
76  *      this algorithmic unfeature.  The freeing code can handle arbitrary
77  *      ranges.
78  *
79  *      This code can be compiled stand-alone for debugging.
80  */
81
82 #include <sys/cdefs.h>
83 __FBSDID("$FreeBSD$");
84
85 #ifdef _KERNEL
86
87 #include <sys/param.h>
88 #include <sys/systm.h>
89 #include <sys/lock.h>
90 #include <sys/kernel.h>
91 #include <sys/blist.h>
92 #include <sys/malloc.h>
93 #include <sys/proc.h>
94 #include <sys/mutex.h>
95
96 #else
97
98 #ifndef BLIST_NO_DEBUG
99 #define BLIST_DEBUG
100 #endif
101
102 #include <sys/types.h>
103 #include <sys/malloc.h>
104 #include <stdio.h>
105 #include <string.h>
106 #include <stdlib.h>
107 #include <stdarg.h>
108 #include <stdbool.h>
109
110 #define bitcount64(x)   __bitcount64((uint64_t)(x))
111 #define malloc(a,b,c)   calloc(a, 1)
112 #define free(a,b)       free(a)
113 #define CTASSERT(expr)
114
115 #include <sys/blist.h>
116
117 void panic(const char *ctl, ...);
118
119 #endif
120
121 /*
122  * static support functions
123  */
124 static daddr_t  blst_leaf_alloc(blmeta_t *scan, daddr_t blk, int count,
125                     daddr_t cursor);
126 static daddr_t  blst_meta_alloc(blmeta_t *scan, daddr_t cursor, daddr_t count,
127                     u_daddr_t radix);
128 static void blst_leaf_free(blmeta_t *scan, daddr_t relblk, int count);
129 static void blst_meta_free(blmeta_t *scan, daddr_t freeBlk, daddr_t count,
130                     u_daddr_t radix);
131 static void blst_copy(blmeta_t *scan, daddr_t blk, daddr_t radix,
132                     blist_t dest, daddr_t count);
133 static daddr_t blst_leaf_fill(blmeta_t *scan, daddr_t blk, int count);
134 static daddr_t blst_meta_fill(blmeta_t *scan, daddr_t allocBlk, daddr_t count,
135                     u_daddr_t radix);
136 static daddr_t  blst_radix_init(blmeta_t *scan, daddr_t radix, daddr_t count);
137 #ifndef _KERNEL
138 static void     blst_radix_print(blmeta_t *scan, daddr_t blk, daddr_t radix,
139                     int tab);
140 #endif
141
142 #ifdef _KERNEL
143 static MALLOC_DEFINE(M_SWAP, "SWAP", "Swap space");
144 #endif
145
146 CTASSERT(BLIST_BMAP_RADIX % BLIST_META_RADIX == 0);
147
148 /*
149  * For a subtree that can represent the state of up to 'radix' blocks, the
150  * number of leaf nodes of the subtree is L=radix/BLIST_BMAP_RADIX.  If 'm'
151  * is short for BLIST_META_RADIX, then for a tree of height h with L=m**h
152  * leaf nodes, the total number of tree nodes is 1 + m + m**2 + ... + m**h,
153  * or, equivalently, (m**(h+1)-1)/(m-1).  This quantity is called 'skip'
154  * in the 'meta' functions that process subtrees.  Since integer division
155  * discards remainders, we can express this computation as
156  * skip = (m * m**h) / (m - 1)
157  * skip = (m * (radix / BLIST_BMAP_RADIX)) / (m - 1)
158  * and since m divides BLIST_BMAP_RADIX, we can simplify further to
159  * skip = (radix / (BLIST_BMAP_RADIX / m)) / (m - 1)
160  * skip = radix / ((BLIST_BMAP_RADIX / m) * (m - 1))
161  * so that simple integer division by a constant can safely be used for the
162  * calculation.
163  */
164 static inline daddr_t
165 radix_to_skip(daddr_t radix)
166 {
167
168         return (radix /
169             ((BLIST_BMAP_RADIX / BLIST_META_RADIX) * (BLIST_META_RADIX - 1)));
170 }
171
172 /*
173  * blist_create() - create a blist capable of handling up to the specified
174  *                  number of blocks
175  *
176  *      blocks - must be greater than 0
177  *      flags  - malloc flags
178  *
179  *      The smallest blist consists of a single leaf node capable of
180  *      managing BLIST_BMAP_RADIX blocks.
181  */
182 blist_t
183 blist_create(daddr_t blocks, int flags)
184 {
185         blist_t bl;
186         daddr_t nodes, radix;
187
188         /*
189          * Calculate the radix field used for scanning.
190          */
191         radix = BLIST_BMAP_RADIX;
192         while (radix < blocks) {
193                 radix *= BLIST_META_RADIX;
194         }
195         nodes = 1 + blst_radix_init(NULL, radix, blocks);
196
197         bl = malloc(sizeof(struct blist), M_SWAP, flags);
198         if (bl == NULL)
199                 return (NULL);
200
201         bl->bl_blocks = blocks;
202         bl->bl_radix = radix;
203         bl->bl_cursor = 0;
204         bl->bl_root = malloc(nodes * sizeof(blmeta_t), M_SWAP, flags);
205         if (bl->bl_root == NULL) {
206                 free(bl, M_SWAP);
207                 return (NULL);
208         }
209         blst_radix_init(bl->bl_root, radix, blocks);
210
211 #if defined(BLIST_DEBUG)
212         printf(
213                 "BLIST representing %lld blocks (%lld MB of swap)"
214                 ", requiring %lldK of ram\n",
215                 (long long)bl->bl_blocks,
216                 (long long)bl->bl_blocks * 4 / 1024,
217                 (long long)(nodes * sizeof(blmeta_t) + 1023) / 1024
218         );
219         printf("BLIST raw radix tree contains %lld records\n",
220             (long long)nodes);
221 #endif
222
223         return (bl);
224 }
225
226 void
227 blist_destroy(blist_t bl)
228 {
229         free(bl->bl_root, M_SWAP);
230         free(bl, M_SWAP);
231 }
232
233 /*
234  * blist_alloc() -   reserve space in the block bitmap.  Return the base
235  *                   of a contiguous region or SWAPBLK_NONE if space could
236  *                   not be allocated.
237  */
238 daddr_t
239 blist_alloc(blist_t bl, daddr_t count)
240 {
241         daddr_t blk;
242
243         /*
244          * This loop iterates at most twice.  An allocation failure in the
245          * first iteration leads to a second iteration only if the cursor was
246          * non-zero.  When the cursor is zero, an allocation failure will
247          * reduce the hint, stopping further iterations.
248          */
249         while (count <= bl->bl_root->bm_bighint) {
250                 blk = blst_meta_alloc(bl->bl_root, bl->bl_cursor, count,
251                     bl->bl_radix);
252                 if (blk != SWAPBLK_NONE) {
253                         bl->bl_cursor = blk + count;
254                         if (bl->bl_cursor == bl->bl_blocks)
255                                 bl->bl_cursor = 0;
256                         return (blk);
257                 } else if (bl->bl_cursor != 0)
258                         bl->bl_cursor = 0;
259         }
260         return (SWAPBLK_NONE);
261 }
262
263 /*
264  * blist_avail() -      return the number of free blocks.
265  */
266 daddr_t
267 blist_avail(blist_t bl)
268 {
269
270         if (bl->bl_radix == BLIST_BMAP_RADIX)
271                 return (bitcount64(bl->bl_root->u.bmu_bitmap));
272         else
273                 return (bl->bl_root->u.bmu_avail);
274 }
275
276 /*
277  * blist_free() -       free up space in the block bitmap.  Return the base
278  *                      of a contiguous region.  Panic if an inconsistancy is
279  *                      found.
280  */
281 void
282 blist_free(blist_t bl, daddr_t blkno, daddr_t count)
283 {
284
285         blst_meta_free(bl->bl_root, blkno, count, bl->bl_radix);
286 }
287
288 /*
289  * blist_fill() -       mark a region in the block bitmap as off-limits
290  *                      to the allocator (i.e. allocate it), ignoring any
291  *                      existing allocations.  Return the number of blocks
292  *                      actually filled that were free before the call.
293  */
294 daddr_t
295 blist_fill(blist_t bl, daddr_t blkno, daddr_t count)
296 {
297
298         return (blst_meta_fill(bl->bl_root, blkno, count, bl->bl_radix));
299 }
300
301 /*
302  * blist_resize() -     resize an existing radix tree to handle the
303  *                      specified number of blocks.  This will reallocate
304  *                      the tree and transfer the previous bitmap to the new
305  *                      one.  When extending the tree you can specify whether
306  *                      the new blocks are to left allocated or freed.
307  */
308 void
309 blist_resize(blist_t *pbl, daddr_t count, int freenew, int flags)
310 {
311     blist_t newbl = blist_create(count, flags);
312     blist_t save = *pbl;
313
314     *pbl = newbl;
315     if (count > save->bl_blocks)
316             count = save->bl_blocks;
317     blst_copy(save->bl_root, 0, save->bl_radix, newbl, count);
318
319     /*
320      * If resizing upwards, should we free the new space or not?
321      */
322     if (freenew && count < newbl->bl_blocks) {
323             blist_free(newbl, count, newbl->bl_blocks - count);
324     }
325     blist_destroy(save);
326 }
327
328 #ifdef BLIST_DEBUG
329
330 /*
331  * blist_print()    - dump radix tree
332  */
333 void
334 blist_print(blist_t bl)
335 {
336         printf("BLIST cursor = %08jx {\n", (uintmax_t)bl->bl_cursor);
337         blst_radix_print(bl->bl_root, 0, bl->bl_radix, 4);
338         printf("}\n");
339 }
340
341 #endif
342
343 /************************************************************************
344  *                        ALLOCATION SUPPORT FUNCTIONS                  *
345  ************************************************************************
346  *
347  *      These support functions do all the actual work.  They may seem
348  *      rather longish, but that's because I've commented them up.  The
349  *      actual code is straight forward.
350  *
351  */
352
353 /*
354  * blist_leaf_alloc() - allocate at a leaf in the radix tree (a bitmap).
355  *
356  *      This is the core of the allocator and is optimized for the
357  *      BLIST_BMAP_RADIX block allocation case.  Otherwise, execution
358  *      time is proportional to log2(count) + log2(BLIST_BMAP_RADIX).
359  */
360 static daddr_t
361 blst_leaf_alloc(blmeta_t *scan, daddr_t blk, int count, daddr_t cursor)
362 {
363         u_daddr_t mask;
364         int count1, hi, lo, mid, num_shifts, range1, range_ext;
365
366         if (count == BLIST_BMAP_RADIX) {
367                 /*
368                  * Optimize allocation of BLIST_BMAP_RADIX bits.  If this wasn't
369                  * a special case, then forming the final value of 'mask' below
370                  * would require special handling to avoid an invalid left shift
371                  * when count equals the number of bits in mask.
372                  */
373                 if (~scan->u.bmu_bitmap != 0) {
374                         scan->bm_bighint = BLIST_BMAP_RADIX - 1;
375                         return (SWAPBLK_NONE);
376                 }
377                 if (cursor != blk)
378                         return (SWAPBLK_NONE);
379                 scan->u.bmu_bitmap = 0;
380                 scan->bm_bighint = 0;
381                 return (blk);
382         }
383         range1 = 0;
384         count1 = count - 1;
385         num_shifts = fls(count1);
386         mask = scan->u.bmu_bitmap;
387         while (mask != 0 && num_shifts > 0) {
388                 /*
389                  * If bit i is set in mask, then bits in [i, i+range1] are set
390                  * in scan->u.bmu_bitmap.  The value of range1 is equal to
391                  * count1 >> num_shifts.  Grow range and reduce num_shifts to 0,
392                  * while preserving these invariants.  The updates to mask leave
393                  * fewer bits set, but each bit that remains set represents a
394                  * longer string of consecutive bits set in scan->u.bmu_bitmap.
395                  */
396                 num_shifts--;
397                 range_ext = range1 + ((count1 >> num_shifts) & 1);
398                 mask &= mask >> range_ext;
399                 range1 += range_ext;
400         }
401         if (mask == 0) {
402                 /*
403                  * Update bighint.  There is no allocation bigger than range1
404                  * available in this leaf.
405                  */
406                 scan->bm_bighint = range1;
407                 return (SWAPBLK_NONE);
408         }
409
410         /*
411          * Discard any candidates that appear before the cursor.
412          */
413         lo = cursor - blk;
414         mask &= ~(u_daddr_t)0 << lo;
415
416         if (mask == 0)
417                 return (SWAPBLK_NONE);
418
419         /*
420          * The least significant set bit in mask marks the start of the first
421          * available range of sufficient size.  Clear all the bits but that one,
422          * and then perform a binary search to find its position.
423          */
424         mask &= -mask;
425         hi = BLIST_BMAP_RADIX - count1;
426         while (lo + 1 < hi) {
427                 mid = (lo + hi) >> 1;
428                 if ((mask >> mid) != 0)
429                         lo = mid;
430                 else
431                         hi = mid;
432         }
433
434         /*
435          * Set in mask exactly the bits being allocated, and clear them from
436          * the set of available bits.
437          */
438         mask = (mask << count) - mask;
439         scan->u.bmu_bitmap &= ~mask;
440         return (blk + lo);
441 }
442
443 /*
444  * blist_meta_alloc() - allocate at a meta in the radix tree.
445  *
446  *      Attempt to allocate at a meta node.  If we can't, we update
447  *      bighint and return a failure.  Updating bighint optimize future
448  *      calls that hit this node.  We have to check for our collapse cases
449  *      and we have a few optimizations strewn in as well.
450  */
451 static daddr_t
452 blst_meta_alloc(blmeta_t *scan, daddr_t cursor, daddr_t count, u_daddr_t radix)
453 {
454         daddr_t blk, i, next_skip, r, skip;
455         int child;
456         bool scan_from_start;
457
458         blk = cursor & -radix;
459         if (radix == BLIST_BMAP_RADIX)
460                 return (blst_leaf_alloc(scan, blk, count, cursor));
461         if (scan->u.bmu_avail < count) {
462                 /*
463                  * The meta node's hint must be too large if the allocation
464                  * exceeds the number of free blocks.  Reduce the hint, and
465                  * return failure.
466                  */
467                 scan->bm_bighint = scan->u.bmu_avail;
468                 return (SWAPBLK_NONE);
469         }
470         skip = radix_to_skip(radix);
471         next_skip = skip / BLIST_META_RADIX;
472
473         /*
474          * An ALL-FREE meta node requires special handling before allocating
475          * any of its blocks.
476          */
477         if (scan->u.bmu_avail == radix) {
478                 radix /= BLIST_META_RADIX;
479
480                 /*
481                  * Reinitialize each of the meta node's children.  An ALL-FREE
482                  * meta node cannot have a terminator in any subtree.
483                  */
484                 for (i = 1; i < skip; i += next_skip) {
485                         if (next_skip == 1)
486                                 scan[i].u.bmu_bitmap = (u_daddr_t)-1;
487                         else
488                                 scan[i].u.bmu_avail = radix;
489                         scan[i].bm_bighint = radix;
490                 }
491         } else {
492                 radix /= BLIST_META_RADIX;
493         }
494
495         if (count > radix) {
496                 /*
497                  * The allocation exceeds the number of blocks that are
498                  * managed by a subtree of this meta node.
499                  */
500                 panic("allocation too large");
501         }
502         scan_from_start = cursor == blk;
503         child = (cursor - blk) / radix;
504         blk += child * radix;
505         for (i = 1 + child * next_skip; i < skip; i += next_skip) {
506                 if (count <= scan[i].bm_bighint) {
507                         /*
508                          * The allocation might fit in the i'th subtree.
509                          */
510                         r = blst_meta_alloc(&scan[i],
511                             cursor > blk ? cursor : blk, count, radix);
512                         if (r != SWAPBLK_NONE) {
513                                 scan->u.bmu_avail -= count;
514                                 return (r);
515                         }
516                 } else if (scan[i].bm_bighint == (daddr_t)-1) {
517                         /*
518                          * Terminator
519                          */
520                         break;
521                 }
522                 blk += radix;
523         }
524
525         /*
526          * We couldn't allocate count in this subtree, update bighint.
527          */
528         if (scan_from_start && scan->bm_bighint >= count)
529                 scan->bm_bighint = count - 1;
530
531         return (SWAPBLK_NONE);
532 }
533
534 /*
535  * BLST_LEAF_FREE() -   free allocated block from leaf bitmap
536  *
537  */
538 static void
539 blst_leaf_free(blmeta_t *scan, daddr_t blk, int count)
540 {
541         /*
542          * free some data in this bitmap
543          *
544          * e.g.
545          *      0000111111111110000
546          *          \_________/\__/
547          *              v        n
548          */
549         int n = blk & (BLIST_BMAP_RADIX - 1);
550         u_daddr_t mask;
551
552         mask = ((u_daddr_t)-1 << n) &
553             ((u_daddr_t)-1 >> (BLIST_BMAP_RADIX - count - n));
554
555         if (scan->u.bmu_bitmap & mask)
556                 panic("blst_radix_free: freeing free block");
557         scan->u.bmu_bitmap |= mask;
558
559         /*
560          * We could probably do a better job here.  We are required to make
561          * bighint at least as large as the biggest contiguous block of
562          * data.  If we just shoehorn it, a little extra overhead will
563          * be incured on the next allocation (but only that one typically).
564          */
565         scan->bm_bighint = BLIST_BMAP_RADIX;
566 }
567
568 /*
569  * BLST_META_FREE() - free allocated blocks from radix tree meta info
570  *
571  *      This support routine frees a range of blocks from the bitmap.
572  *      The range must be entirely enclosed by this radix node.  If a
573  *      meta node, we break the range down recursively to free blocks
574  *      in subnodes (which means that this code can free an arbitrary
575  *      range whereas the allocation code cannot allocate an arbitrary
576  *      range).
577  */
578 static void
579 blst_meta_free(blmeta_t *scan, daddr_t freeBlk, daddr_t count, u_daddr_t radix)
580 {
581         daddr_t blk, i, next_skip, skip, v;
582         int child;
583
584         if (scan->bm_bighint == (daddr_t)-1)
585                 panic("freeing invalid range");
586         if (radix == BLIST_BMAP_RADIX)
587                 return (blst_leaf_free(scan, freeBlk, count));
588         skip = radix_to_skip(radix);
589         next_skip = skip / BLIST_META_RADIX;
590
591         if (scan->u.bmu_avail == 0) {
592                 /*
593                  * ALL-ALLOCATED special case, with possible
594                  * shortcut to ALL-FREE special case.
595                  */
596                 scan->u.bmu_avail = count;
597                 scan->bm_bighint = count;
598
599                 if (count != radix)  {
600                         for (i = 1; i < skip; i += next_skip) {
601                                 if (scan[i].bm_bighint == (daddr_t)-1)
602                                         break;
603                                 scan[i].bm_bighint = 0;
604                                 if (next_skip == 1) {
605                                         scan[i].u.bmu_bitmap = 0;
606                                 } else {
607                                         scan[i].u.bmu_avail = 0;
608                                 }
609                         }
610                         /* fall through */
611                 }
612         } else {
613                 scan->u.bmu_avail += count;
614                 /* scan->bm_bighint = radix; */
615         }
616
617         /*
618          * ALL-FREE special case.
619          */
620
621         if (scan->u.bmu_avail == radix)
622                 return;
623         if (scan->u.bmu_avail > radix)
624                 panic("blst_meta_free: freeing already free blocks (%lld) %lld/%lld",
625                     (long long)count, (long long)scan->u.bmu_avail,
626                     (long long)radix);
627
628         /*
629          * Break the free down into its components
630          */
631
632         blk = freeBlk & -radix;
633         radix /= BLIST_META_RADIX;
634
635         child = (freeBlk - blk) / radix;
636         blk += child * radix;
637         i = 1 + child * next_skip;
638         while (i < skip && blk < freeBlk + count) {
639                 v = blk + radix - freeBlk;
640                 if (v > count)
641                         v = count;
642                 blst_meta_free(&scan[i], freeBlk, v, radix);
643                 if (scan->bm_bighint < scan[i].bm_bighint)
644                         scan->bm_bighint = scan[i].bm_bighint;
645                 count -= v;
646                 freeBlk += v;
647                 blk += radix;
648                 i += next_skip;
649         }
650 }
651
652 /*
653  * BLIST_RADIX_COPY() - copy one radix tree to another
654  *
655  *      Locates free space in the source tree and frees it in the destination
656  *      tree.  The space may not already be free in the destination.
657  */
658 static void
659 blst_copy(blmeta_t *scan, daddr_t blk, daddr_t radix, blist_t dest,
660     daddr_t count)
661 {
662         daddr_t i, next_skip, skip;
663
664         /*
665          * Leaf node
666          */
667
668         if (radix == BLIST_BMAP_RADIX) {
669                 u_daddr_t v = scan->u.bmu_bitmap;
670
671                 if (v == (u_daddr_t)-1) {
672                         blist_free(dest, blk, count);
673                 } else if (v != 0) {
674                         int i;
675
676                         for (i = 0; i < BLIST_BMAP_RADIX && i < count; ++i) {
677                                 if (v & ((u_daddr_t)1 << i))
678                                         blist_free(dest, blk + i, 1);
679                         }
680                 }
681                 return;
682         }
683
684         /*
685          * Meta node
686          */
687
688         if (scan->u.bmu_avail == 0) {
689                 /*
690                  * Source all allocated, leave dest allocated
691                  */
692                 return;
693         }
694         if (scan->u.bmu_avail == radix) {
695                 /*
696                  * Source all free, free entire dest
697                  */
698                 if (count < radix)
699                         blist_free(dest, blk, count);
700                 else
701                         blist_free(dest, blk, radix);
702                 return;
703         }
704
705
706         skip = radix_to_skip(radix);
707         next_skip = skip / BLIST_META_RADIX;
708         radix /= BLIST_META_RADIX;
709
710         for (i = 1; count && i < skip; i += next_skip) {
711                 if (scan[i].bm_bighint == (daddr_t)-1)
712                         break;
713
714                 if (count >= radix) {
715                         blst_copy(&scan[i], blk, radix, dest, radix);
716                         count -= radix;
717                 } else {
718                         if (count) {
719                                 blst_copy(&scan[i], blk, radix, dest, count);
720                         }
721                         count = 0;
722                 }
723                 blk += radix;
724         }
725 }
726
727 /*
728  * BLST_LEAF_FILL() -   allocate specific blocks in leaf bitmap
729  *
730  *      This routine allocates all blocks in the specified range
731  *      regardless of any existing allocations in that range.  Returns
732  *      the number of blocks allocated by the call.
733  */
734 static daddr_t
735 blst_leaf_fill(blmeta_t *scan, daddr_t blk, int count)
736 {
737         int n = blk & (BLIST_BMAP_RADIX - 1);
738         daddr_t nblks;
739         u_daddr_t mask;
740
741         mask = ((u_daddr_t)-1 << n) &
742             ((u_daddr_t)-1 >> (BLIST_BMAP_RADIX - count - n));
743
744         /* Count the number of blocks that we are allocating. */
745         nblks = bitcount64(scan->u.bmu_bitmap & mask);
746
747         scan->u.bmu_bitmap &= ~mask;
748         return (nblks);
749 }
750
751 /*
752  * BLIST_META_FILL() -  allocate specific blocks at a meta node
753  *
754  *      This routine allocates the specified range of blocks,
755  *      regardless of any existing allocations in the range.  The
756  *      range must be within the extent of this node.  Returns the
757  *      number of blocks allocated by the call.
758  */
759 static daddr_t
760 blst_meta_fill(blmeta_t *scan, daddr_t allocBlk, daddr_t count, u_daddr_t radix)
761 {
762         daddr_t blk, i, nblks, next_skip, skip, v;
763         int child;
764
765         if (scan->bm_bighint == (daddr_t)-1)
766                 panic("filling invalid range");
767         if (count > radix) {
768                 /*
769                  * The allocation exceeds the number of blocks that are
770                  * managed by this node.
771                  */
772                 panic("fill too large");
773         }
774         if (radix == BLIST_BMAP_RADIX)
775                 return (blst_leaf_fill(scan, allocBlk, count));
776         if (count == radix || scan->u.bmu_avail == 0)  {
777                 /*
778                  * ALL-ALLOCATED special case
779                  */
780                 nblks = scan->u.bmu_avail;
781                 scan->u.bmu_avail = 0;
782                 scan->bm_bighint = 0;
783                 return (nblks);
784         }
785         skip = radix_to_skip(radix);
786         next_skip = skip / BLIST_META_RADIX;
787         blk = allocBlk & -radix;
788
789         /*
790          * An ALL-FREE meta node requires special handling before allocating
791          * any of its blocks.
792          */
793         if (scan->u.bmu_avail == radix) {
794                 radix /= BLIST_META_RADIX;
795
796                 /*
797                  * Reinitialize each of the meta node's children.  An ALL-FREE
798                  * meta node cannot have a terminator in any subtree.
799                  */
800                 for (i = 1; i < skip; i += next_skip) {
801                         if (next_skip == 1)
802                                 scan[i].u.bmu_bitmap = (u_daddr_t)-1;
803                         else
804                                 scan[i].u.bmu_avail = radix;
805                         scan[i].bm_bighint = radix;
806                 }
807         } else {
808                 radix /= BLIST_META_RADIX;
809         }
810
811         nblks = 0;
812         child = (allocBlk - blk) / radix;
813         blk += child * radix;
814         i = 1 + child * next_skip;
815         while (i < skip && blk < allocBlk + count) {
816                 v = blk + radix - allocBlk;
817                 if (v > count)
818                         v = count;
819                 nblks += blst_meta_fill(&scan[i], allocBlk, v, radix);
820                 count -= v;
821                 allocBlk += v;
822                 blk += radix;
823                 i += next_skip;
824         }
825         scan->u.bmu_avail -= nblks;
826         return (nblks);
827 }
828
829 /*
830  * BLST_RADIX_INIT() - initialize radix tree
831  *
832  *      Initialize our meta structures and bitmaps and calculate the exact
833  *      amount of space required to manage 'count' blocks - this space may
834  *      be considerably less than the calculated radix due to the large
835  *      RADIX values we use.
836  */
837 static daddr_t
838 blst_radix_init(blmeta_t *scan, daddr_t radix, daddr_t count)
839 {
840         daddr_t i, memindex, next_skip, skip;
841
842         memindex = 0;
843
844         /*
845          * Leaf node
846          */
847
848         if (radix == BLIST_BMAP_RADIX) {
849                 if (scan) {
850                         scan->bm_bighint = 0;
851                         scan->u.bmu_bitmap = 0;
852                 }
853                 return (memindex);
854         }
855
856         /*
857          * Meta node.  If allocating the entire object we can special
858          * case it.  However, we need to figure out how much memory
859          * is required to manage 'count' blocks, so we continue on anyway.
860          */
861
862         if (scan) {
863                 scan->bm_bighint = 0;
864                 scan->u.bmu_avail = 0;
865         }
866
867         skip = radix_to_skip(radix);
868         next_skip = skip / BLIST_META_RADIX;
869         radix /= BLIST_META_RADIX;
870
871         for (i = 1; i < skip; i += next_skip) {
872                 if (count >= radix) {
873                         /*
874                          * Allocate the entire object
875                          */
876                         memindex = i +
877                             blst_radix_init(((scan) ? &scan[i] : NULL), radix,
878                             radix);
879                         count -= radix;
880                 } else if (count > 0) {
881                         /*
882                          * Allocate a partial object
883                          */
884                         memindex = i +
885                             blst_radix_init(((scan) ? &scan[i] : NULL), radix,
886                             count);
887                         count = 0;
888                 } else {
889                         /*
890                          * Add terminator and break out
891                          */
892                         if (scan)
893                                 scan[i].bm_bighint = (daddr_t)-1;
894                         break;
895                 }
896         }
897         if (memindex < i)
898                 memindex = i;
899         return (memindex);
900 }
901
902 #ifdef BLIST_DEBUG
903
904 static void
905 blst_radix_print(blmeta_t *scan, daddr_t blk, daddr_t radix, int tab)
906 {
907         daddr_t i, next_skip, skip;
908
909         if (radix == BLIST_BMAP_RADIX) {
910                 printf(
911                     "%*.*s(%08llx,%lld): bitmap %016llx big=%lld\n",
912                     tab, tab, "",
913                     (long long)blk, (long long)radix,
914                     (long long)scan->u.bmu_bitmap,
915                     (long long)scan->bm_bighint
916                 );
917                 return;
918         }
919
920         if (scan->u.bmu_avail == 0) {
921                 printf(
922                     "%*.*s(%08llx,%lld) ALL ALLOCATED\n",
923                     tab, tab, "",
924                     (long long)blk,
925                     (long long)radix
926                 );
927                 return;
928         }
929         if (scan->u.bmu_avail == radix) {
930                 printf(
931                     "%*.*s(%08llx,%lld) ALL FREE\n",
932                     tab, tab, "",
933                     (long long)blk,
934                     (long long)radix
935                 );
936                 return;
937         }
938
939         printf(
940             "%*.*s(%08llx,%lld): subtree (%lld/%lld) big=%lld {\n",
941             tab, tab, "",
942             (long long)blk, (long long)radix,
943             (long long)scan->u.bmu_avail,
944             (long long)radix,
945             (long long)scan->bm_bighint
946         );
947
948         skip = radix_to_skip(radix);
949         next_skip = skip / BLIST_META_RADIX;
950         radix /= BLIST_META_RADIX;
951         tab += 4;
952
953         for (i = 1; i < skip; i += next_skip) {
954                 if (scan[i].bm_bighint == (daddr_t)-1) {
955                         printf(
956                             "%*.*s(%08llx,%lld): Terminator\n",
957                             tab, tab, "",
958                             (long long)blk, (long long)radix
959                         );
960                         break;
961                 }
962                 blst_radix_print(&scan[i], blk, radix, tab);
963                 blk += radix;
964         }
965         tab -= 4;
966
967         printf(
968             "%*.*s}\n",
969             tab, tab, ""
970         );
971 }
972
973 #endif
974
975 #ifdef BLIST_DEBUG
976
977 int
978 main(int ac, char **av)
979 {
980         int size = 1024;
981         int i;
982         blist_t bl;
983
984         for (i = 1; i < ac; ++i) {
985                 const char *ptr = av[i];
986                 if (*ptr != '-') {
987                         size = strtol(ptr, NULL, 0);
988                         continue;
989                 }
990                 ptr += 2;
991                 fprintf(stderr, "Bad option: %s\n", ptr - 2);
992                 exit(1);
993         }
994         bl = blist_create(size, M_WAITOK);
995         blist_free(bl, 0, size);
996
997         for (;;) {
998                 char buf[1024];
999                 long long da = 0;
1000                 long long count = 0;
1001
1002                 printf("%lld/%lld/%lld> ", (long long)blist_avail(bl),
1003                     (long long)size, (long long)bl->bl_radix);
1004                 fflush(stdout);
1005                 if (fgets(buf, sizeof(buf), stdin) == NULL)
1006                         break;
1007                 switch(buf[0]) {
1008                 case 'r':
1009                         if (sscanf(buf + 1, "%lld", &count) == 1) {
1010                                 blist_resize(&bl, count, 1, M_WAITOK);
1011                         } else {
1012                                 printf("?\n");
1013                         }
1014                 case 'p':
1015                         blist_print(bl);
1016                         break;
1017                 case 'a':
1018                         if (sscanf(buf + 1, "%lld", &count) == 1) {
1019                                 daddr_t blk = blist_alloc(bl, count);
1020                                 printf("    R=%08llx\n", (long long)blk);
1021                         } else {
1022                                 printf("?\n");
1023                         }
1024                         break;
1025                 case 'f':
1026                         if (sscanf(buf + 1, "%llx %lld", &da, &count) == 2) {
1027                                 blist_free(bl, da, count);
1028                         } else {
1029                                 printf("?\n");
1030                         }
1031                         break;
1032                 case 'l':
1033                         if (sscanf(buf + 1, "%llx %lld", &da, &count) == 2) {
1034                                 printf("    n=%jd\n",
1035                                     (intmax_t)blist_fill(bl, da, count));
1036                         } else {
1037                                 printf("?\n");
1038                         }
1039                         break;
1040                 case '?':
1041                 case 'h':
1042                         puts(
1043                             "p          -print\n"
1044                             "a %d       -allocate\n"
1045                             "f %x %d    -free\n"
1046                             "l %x %d    -fill\n"
1047                             "r %d       -resize\n"
1048                             "h/?        -help"
1049                         );
1050                         break;
1051                 default:
1052                         printf("?\n");
1053                         break;
1054                 }
1055         }
1056         return(0);
1057 }
1058
1059 void
1060 panic(const char *ctl, ...)
1061 {
1062         va_list va;
1063
1064         va_start(va, ctl);
1065         vfprintf(stderr, ctl, va);
1066         fprintf(stderr, "\n");
1067         va_end(va);
1068         exit(1);
1069 }
1070
1071 #endif