2 * Copyright (c) 2011-2014 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@dragonflybsd.org>
6 * by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
18 * 3. Neither the name of The DragonFly Project nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific, prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/fcntl.h>
41 #include <sys/namei.h>
42 #include <sys/mount.h>
43 #include <sys/vnode.h>
44 #include <sys/mountctl.h>
48 #define FREEMAP_DEBUG 0
50 struct hammer2_fiterate {
57 typedef struct hammer2_fiterate hammer2_fiterate_t;
59 static int hammer2_freemap_try_alloc(hammer2_chain_t **parentp,
60 hammer2_blockref_t *bref, int radix,
61 hammer2_fiterate_t *iter, hammer2_tid_t mtid);
62 static void hammer2_freemap_init(hammer2_dev_t *hmp,
63 hammer2_key_t key, hammer2_chain_t *chain);
64 static int hammer2_bmap_alloc(hammer2_dev_t *hmp,
65 hammer2_bmap_data_t *bmap, uint16_t class,
66 int n, int sub_key, int radix, hammer2_key_t *basep);
67 static int hammer2_freemap_iterate(hammer2_chain_t **parentp,
68 hammer2_chain_t **chainp,
69 hammer2_fiterate_t *iter);
73 hammer2_freemapradix(int radix)
79 * Calculate the device offset for the specified FREEMAP_NODE or FREEMAP_LEAF
80 * bref. Return a combined media offset and physical size radix. Freemap
81 * chains use fixed storage offsets in the 4MB reserved area at the
82 * beginning of each 2GB zone
84 * XXX I made a mistake and made the reserved area begin at each LEVEL1 zone,
85 * which is on a 1GB demark. This will eat a little more space but for
86 * now we retain compatibility and make FMZONEBASE every 1GB
88 * (see same thing in hammer2_bulkfree.c near the top, as well as in
91 * Rotate between four possibilities. Theoretically this means we have three
92 * good freemaps in case of a crash which we can use as a base for the fixup
95 #define H2FMZONEBASE(key) ((key) & ~HAMMER2_FREEMAP_LEVEL1_MASK)
96 #define H2FMBASE(key, radix) ((key) & ~(((hammer2_off_t)1 << (radix)) - 1))
97 #define H2FMSHIFT(radix) ((hammer2_off_t)1 << (radix))
101 hammer2_freemap_reserve(hammer2_chain_t *chain, int radix)
103 hammer2_blockref_t *bref = &chain->bref;
110 * Physical allocation size.
112 bytes = (size_t)1 << radix;
115 * Calculate block selection index 0..7 of current block. If this
116 * is the first allocation of the block (verses a modification of an
117 * existing block), we use index 0, otherwise we use the next rotating
120 if ((bref->data_off & ~HAMMER2_OFF_MASK_RADIX) == 0) {
123 off = bref->data_off & ~HAMMER2_OFF_MASK_RADIX &
124 (((hammer2_off_t)1 <<
125 HAMMER2_FREEMAP_LEVEL1_RADIX) - 1);
126 off = off / HAMMER2_PBUFSIZE;
127 KKASSERT(off >= HAMMER2_ZONE_FREEMAP_00 &&
128 off < HAMMER2_ZONE_FREEMAP_END);
129 index = (int)(off - HAMMER2_ZONE_FREEMAP_00) /
130 HAMMER2_ZONE_FREEMAP_INC;
131 KKASSERT(index >= 0 && index < HAMMER2_NFREEMAPS);
132 if (++index == HAMMER2_NFREEMAPS)
137 * Calculate the block offset of the reserved block. This will
138 * point into the 4MB reserved area at the base of the appropriate
139 * 2GB zone, once added to the FREEMAP_x selection above.
141 index_inc = index * HAMMER2_ZONE_FREEMAP_INC;
143 switch(bref->keybits) {
144 /* case HAMMER2_FREEMAP_LEVEL6_RADIX: not applicable */
145 case HAMMER2_FREEMAP_LEVEL5_RADIX: /* 2EB */
146 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
147 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
148 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL5_RADIX) +
149 (index_inc + HAMMER2_ZONE_FREEMAP_00 +
150 HAMMER2_ZONEFM_LEVEL5) * HAMMER2_PBUFSIZE;
152 case HAMMER2_FREEMAP_LEVEL4_RADIX: /* 2EB */
153 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
154 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
155 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL4_RADIX) +
156 (index_inc + HAMMER2_ZONE_FREEMAP_00 +
157 HAMMER2_ZONEFM_LEVEL4) * HAMMER2_PBUFSIZE;
159 case HAMMER2_FREEMAP_LEVEL3_RADIX: /* 2PB */
160 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
161 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
162 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL3_RADIX) +
163 (index_inc + HAMMER2_ZONE_FREEMAP_00 +
164 HAMMER2_ZONEFM_LEVEL3) * HAMMER2_PBUFSIZE;
166 case HAMMER2_FREEMAP_LEVEL2_RADIX: /* 2TB */
167 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
168 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
169 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL2_RADIX) +
170 (index_inc + HAMMER2_ZONE_FREEMAP_00 +
171 HAMMER2_ZONEFM_LEVEL2) * HAMMER2_PBUFSIZE;
173 case HAMMER2_FREEMAP_LEVEL1_RADIX: /* 2GB */
174 KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
175 KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
176 off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
177 (index_inc + HAMMER2_ZONE_FREEMAP_00 +
178 HAMMER2_ZONEFM_LEVEL1) * HAMMER2_PBUFSIZE;
181 panic("freemap: bad radix(2) %p %d\n", bref, bref->keybits);
183 off = (hammer2_off_t)-1;
186 bref->data_off = off | radix;
188 kprintf("FREEMAP BLOCK TYPE %d %016jx/%d DATA_OFF=%016jx\n",
189 bref->type, bref->key, bref->keybits, bref->data_off);
195 * Normal freemap allocator
197 * Use available hints to allocate space using the freemap. Create missing
198 * freemap infrastructure on-the-fly as needed (including marking initial
199 * allocations using the iterator as allocated, instantiating new 2GB zones,
200 * and dealing with the end-of-media edge case).
202 * ip and bpref are only used as a heuristic to determine locality of
203 * reference. bref->key may also be used heuristically.
205 * This function is a NOP if bytes is 0.
208 hammer2_freemap_alloc(hammer2_chain_t *chain, size_t bytes)
210 hammer2_dev_t *hmp = chain->hmp;
211 hammer2_blockref_t *bref = &chain->bref;
212 hammer2_chain_t *parent;
217 hammer2_fiterate_t iter;
220 * If allocating or downsizing to zero we just get rid of whatever
224 chain->bref.data_off = 0;
228 mtid = hammer2_trans_sub(hmp->spmp);
231 * Validate the allocation size. It must be a power of 2.
233 * For now require that the caller be aware of the minimum
236 radix = hammer2_getradix(bytes);
237 KKASSERT((size_t)1 << radix == bytes);
239 if (bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
240 bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
242 * Freemap blocks themselves are assigned from the reserve
243 * area, not allocated from the freemap.
245 error = hammer2_freemap_reserve(chain, radix);
250 KKASSERT(bytes >= HAMMER2_ALLOC_MIN && bytes <= HAMMER2_ALLOC_MAX);
253 * Calculate the starting point for our allocation search.
255 * Each freemap leaf is dedicated to a specific freemap_radix.
256 * The freemap_radix can be more fine-grained than the device buffer
257 * radix which results in inodes being grouped together in their
258 * own segment, terminal-data (16K or less) and initial indirect
259 * block being grouped together, and then full-indirect and full-data
260 * blocks (64K) being grouped together.
262 * The single most important aspect of this is the inode grouping
263 * because that is what allows 'find' and 'ls' and other filesystem
264 * topology operations to run fast.
267 if (bref->data_off & ~HAMMER2_OFF_MASK_RADIX)
268 bpref = bref->data_off & ~HAMMER2_OFF_MASK_RADIX;
269 else if (trans->tmp_bpref)
270 bpref = trans->tmp_bpref;
271 else if (trans->tmp_ip)
272 bpref = trans->tmp_ip->chain->bref.data_off;
276 * Heuristic tracking index. We would like one for each distinct
277 * bref type if possible. heur_freemap[] has room for two classes
278 * for each type. At a minimum we have to break-up our heuristic
279 * by device block sizes.
281 hindex = hammer2_devblkradix(radix) - HAMMER2_MINIORADIX;
282 KKASSERT(hindex < HAMMER2_FREEMAP_HEUR_NRADIX);
283 hindex += bref->type * HAMMER2_FREEMAP_HEUR_NRADIX;
284 hindex &= HAMMER2_FREEMAP_HEUR_TYPES * HAMMER2_FREEMAP_HEUR_NRADIX - 1;
285 KKASSERT(hindex < HAMMER2_FREEMAP_HEUR_SIZE);
287 iter.bpref = hmp->heur_freemap[hindex];
288 iter.relaxed = hmp->freemap_relaxed;
291 * Make sure bpref is in-bounds. It's ok if bpref covers a zone's
292 * reserved area, the try code will iterate past it.
294 if (iter.bpref > hmp->voldata.volu_size)
295 iter.bpref = hmp->voldata.volu_size - 1;
298 * Iterate the freemap looking for free space before and after.
300 parent = &hmp->fchain;
301 hammer2_chain_ref(parent);
302 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
303 error = HAMMER2_ERROR_EAGAIN;
304 iter.bnext = iter.bpref;
307 while (error == HAMMER2_ERROR_EAGAIN) {
308 error = hammer2_freemap_try_alloc(&parent, bref, radix,
311 hmp->freemap_relaxed |= iter.relaxed; /* heuristical, SMP race ok */
312 hmp->heur_freemap[hindex] = iter.bnext;
313 hammer2_chain_unlock(parent);
314 hammer2_chain_drop(parent);
320 hammer2_freemap_try_alloc(hammer2_chain_t **parentp,
321 hammer2_blockref_t *bref, int radix,
322 hammer2_fiterate_t *iter, hammer2_tid_t mtid)
324 hammer2_dev_t *hmp = (*parentp)->hmp;
325 hammer2_off_t l0size;
326 hammer2_off_t l1size;
327 hammer2_off_t l1mask;
328 hammer2_key_t key_dummy;
329 hammer2_chain_t *chain;
336 * Calculate the number of bytes being allocated, the number
337 * of contiguous bits of bitmap being allocated, and the bitmap
340 * WARNING! cpu hardware may mask bits == 64 -> 0 and blow up the
343 bytes = (size_t)1 << radix;
344 class = (bref->type << 8) | hammer2_devblkradix(radix);
347 * Lookup the level1 freemap chain, creating and initializing one
348 * if necessary. Intermediate levels will be created automatically
349 * when necessary by hammer2_chain_create().
351 key = H2FMBASE(iter->bnext, HAMMER2_FREEMAP_LEVEL1_RADIX);
352 l0size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
353 l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
356 chain = hammer2_chain_lookup(parentp, &key_dummy, key, key + l1mask,
358 HAMMER2_LOOKUP_ALWAYS |
359 HAMMER2_LOOKUP_MATCHIND);
363 * Create the missing leaf, be sure to initialize
364 * the auxillary freemap tracking information in
365 * the bref.check.freemap structure.
368 kprintf("freemap create L1 @ %016jx bpref %016jx\n",
371 error = hammer2_chain_create(parentp, &chain,
372 hmp->spmp, HAMMER2_METH_DEFAULT,
373 key, HAMMER2_FREEMAP_LEVEL1_RADIX,
374 HAMMER2_BREF_TYPE_FREEMAP_LEAF,
375 HAMMER2_FREEMAP_LEVELN_PSIZE,
377 KKASSERT(error == 0);
379 hammer2_chain_modify(chain, mtid, 0, 0);
380 bzero(&chain->data->bmdata[0],
381 HAMMER2_FREEMAP_LEVELN_PSIZE);
382 chain->bref.check.freemap.bigmask = (uint32_t)-1;
383 chain->bref.check.freemap.avail = l1size;
384 /* bref.methods should already be inherited */
386 hammer2_freemap_init(hmp, key, chain);
388 } else if (chain->error) {
390 * Error during lookup.
392 kprintf("hammer2_freemap_try_alloc: %016jx: error %s\n",
393 (intmax_t)bref->data_off,
394 hammer2_error_str(chain->error));
395 error = HAMMER2_ERROR_EIO;
396 } else if ((chain->bref.check.freemap.bigmask &
397 ((size_t)1 << radix)) == 0) {
399 * Already flagged as not having enough space
401 error = HAMMER2_ERROR_ENOSPC;
404 * Modify existing chain to setup for adjustment.
406 hammer2_chain_modify(chain, mtid, 0, 0);
413 hammer2_bmap_data_t *bmap;
414 hammer2_key_t base_key;
419 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
420 start = (int)((iter->bnext - key) >>
421 HAMMER2_FREEMAP_LEVEL0_RADIX);
422 KKASSERT(start >= 0 && start < HAMMER2_FREEMAP_COUNT);
423 hammer2_chain_modify(chain, mtid, 0, 0);
425 error = HAMMER2_ERROR_ENOSPC;
426 for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
429 if (start + count >= HAMMER2_FREEMAP_COUNT &&
435 * Calculate bmap pointer from thart starting index
438 * NOTE: bmap pointer is invalid if n >= FREEMAP_COUNT.
441 bmap = &chain->data->bmdata[n];
443 if (n >= HAMMER2_FREEMAP_COUNT) {
445 } else if (bmap->avail) {
447 } else if (radix < HAMMER2_FREEMAP_BLOCK_RADIX &&
448 (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK)) {
455 * Try to allocate from a matching freemap class
456 * superblock. If we are in relaxed mode we allocate
457 * from any freemap class superblock.
460 (bmap->class == 0 || bmap->class == class ||
462 base_key = key + n * l0size;
463 error = hammer2_bmap_alloc(hmp, bmap,
468 if (error != HAMMER2_ERROR_ENOSPC) {
475 * Calculate bmap pointer from thart starting index
476 * backwards (locality).
478 * Must recalculate after potentially having called
479 * hammer2_bmap_alloc() above in case chain was
482 * NOTE: bmap pointer is invalid if n < 0.
485 bmap = &chain->data->bmdata[n];
488 } else if (bmap->avail) {
490 } else if (radix < HAMMER2_FREEMAP_BLOCK_RADIX &&
491 (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK)) {
498 * Try to allocate from a matching freemap class
499 * superblock. If we are in relaxed mode we allocate
500 * from any freemap class superblock.
503 (bmap->class == 0 || bmap->class == class ||
505 base_key = key + n * l0size;
506 error = hammer2_bmap_alloc(hmp, bmap,
511 if (error != HAMMER2_ERROR_ENOSPC) {
519 * We only know for sure that we can clear the bitmap bit
520 * if we scanned the entire array (start == 0).
522 if (error == HAMMER2_ERROR_ENOSPC && start == 0) {
523 chain->bref.check.freemap.bigmask &=
524 (uint32_t)~((size_t)1 << radix);
526 /* XXX also scan down from original count */
531 * Assert validity. Must be beyond the static allocator used
532 * by newfs_hammer2 (and thus also beyond the aux area),
533 * not go past the volume size, and must not be in the
534 * reserved segment area for a zone.
536 KKASSERT(key >= hmp->voldata.allocator_beg &&
537 key + bytes <= hmp->voldata.volu_size);
538 KKASSERT((key & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
539 bref->data_off = key | radix;
542 * Record dedupability. The dedup bits are cleared
543 * when bulkfree transitions the freemap from 11->10,
544 * and asserted to be clear on the 10->00 transition.
546 * We must record the bitmask with the chain locked
547 * at the time we set the allocation bits to avoid
550 if (bref->type == HAMMER2_BREF_TYPE_DATA)
551 hammer2_io_dedup_set(hmp, bref);
553 kprintf("alloc cp=%p %016jx %016jx using %016jx\n",
555 bref->key, bref->data_off, chain->bref.data_off);
557 } else if (error == HAMMER2_ERROR_ENOSPC) {
559 * Return EAGAIN with next iteration in iter->bnext, or
560 * return ENOSPC if the allocation map has been exhausted.
562 error = hammer2_freemap_iterate(parentp, &chain, iter);
569 hammer2_chain_unlock(chain);
570 hammer2_chain_drop(chain);
576 * Allocate (1<<radix) bytes from the bmap whos base data offset is (*basep).
578 * If the linear iterator is mid-block we use it directly (the bitmap should
579 * already be marked allocated), otherwise we search for a block in the
580 * bitmap that fits the allocation request.
582 * A partial bitmap allocation sets the minimum bitmap granularity (16KB)
583 * to fully allocated and adjusts the linear allocator to allow the
584 * remaining space to be allocated.
586 * sub_key is the lower 32 bits of the chain->bref.key for the chain whos
587 * bref is being allocated. If the radix represents an allocation >= 16KB
588 * (aka HAMMER2_FREEMAP_BLOCK_RADIX) we try to use this key to select the
589 * blocks directly out of the bmap.
593 hammer2_bmap_alloc(hammer2_dev_t *hmp, hammer2_bmap_data_t *bmap,
594 uint16_t class, int n, int sub_key,
595 int radix, hammer2_key_t *basep)
600 hammer2_bitmap_t bmmask;
606 * Take into account 2-bits per block when calculating bmradix.
608 size = (size_t)1 << radix;
610 if (radix <= HAMMER2_FREEMAP_BLOCK_RADIX) {
612 /* (16K) 2 bits per allocation block */
614 bmradix = (hammer2_bitmap_t)2 <<
615 (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
616 /* (32K-256K) 4, 8, 16, 32 bits per allocation block */
620 * Use the linear iterator to pack small allocations, otherwise
621 * fall-back to finding a free 16KB chunk. The linear iterator
622 * is only valid when *NOT* on a freemap chunking boundary (16KB).
623 * If it is the bitmap must be scanned. It can become invalid
624 * once we pack to the boundary. We adjust it after a bitmap
625 * allocation only for sub-16KB allocations (so the perfectly good
626 * previous value can still be used for fragments when 16KB+
627 * allocations are made inbetween fragmentary allocations).
629 * Beware of hardware artifacts when bmradix == 64 (intermediate
630 * result can wind up being '1' instead of '0' if hardware masks
633 * NOTE: j needs to be even in the j= calculation. As an artifact
634 * of the /2 division, our bitmask has to clear bit 0.
636 * NOTE: TODO this can leave little unallocatable fragments lying
639 if (((uint32_t)bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) + size <=
640 HAMMER2_FREEMAP_BLOCK_SIZE &&
641 (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) &&
642 bmap->linear < HAMMER2_SEGSIZE) {
644 * Use linear iterator if it is not block-aligned to avoid
647 KKASSERT(bmap->linear >= 0 &&
648 bmap->linear + size <= HAMMER2_SEGSIZE &&
649 (bmap->linear & (HAMMER2_ALLOC_MIN - 1)) == 0);
650 offset = bmap->linear;
651 i = offset / (HAMMER2_SEGSIZE / 8);
652 j = (offset / (HAMMER2_FREEMAP_BLOCK_SIZE / 2)) & 30;
653 bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
654 HAMMER2_BMAP_ALLONES :
655 ((hammer2_bitmap_t)1 << bmradix) - 1;
657 bmap->linear = offset + size;
660 * Try to index a starting point based on sub_key. This
661 * attempts to restore sequential block ordering on-disk
662 * whenever possible, even if data is committed out of
665 * i - Index bitmapq[], full data range represented is
668 * j - Index within bitmapq[i], full data range represented is
669 * HAMMER2_BMAP_INDEX_SIZE.
677 case HAMMER2_BREF_TYPE_DATA:
678 if (radix >= HAMMER2_FREEMAP_BLOCK_RADIX) {
679 i = (sub_key & HAMMER2_BMAP_MASK) /
680 (HAMMER2_BMAP_SIZE / HAMMER2_BMAP_ELEMENTS);
681 j = (sub_key & HAMMER2_BMAP_INDEX_MASK) /
682 (HAMMER2_BMAP_INDEX_SIZE /
683 HAMMER2_BMAP_BLOCKS_PER_ELEMENT);
687 case HAMMER2_BREF_TYPE_INODE:
693 KKASSERT(i < HAMMER2_BMAP_ELEMENTS &&
694 j < 2 * HAMMER2_BMAP_BLOCKS_PER_ELEMENT);
695 KKASSERT(j + bmradix <= HAMMER2_BMAP_BITS_PER_ELEMENT);
696 bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
697 HAMMER2_BMAP_ALLONES :
698 ((hammer2_bitmap_t)1 << bmradix) - 1;
701 if ((bmap->bitmapq[i] & bmmask) == 0)
706 * General element scan.
708 * WARNING: (j) is iterating a bit index (by 2's)
710 for (i = 0; i < HAMMER2_BMAP_ELEMENTS; ++i) {
711 bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
712 HAMMER2_BMAP_ALLONES :
713 ((hammer2_bitmap_t)1 << bmradix) - 1;
715 j < HAMMER2_BMAP_BITS_PER_ELEMENT;
717 if ((bmap->bitmapq[i] & bmmask) == 0)
722 /*fragments might remain*/
723 /*KKASSERT(bmap->avail == 0);*/
724 return (HAMMER2_ERROR_ENOSPC);
726 offset = i * (HAMMER2_SEGSIZE / HAMMER2_BMAP_ELEMENTS) +
727 (j * (HAMMER2_FREEMAP_BLOCK_SIZE / 2));
728 if (size & HAMMER2_FREEMAP_BLOCK_MASK)
729 bmap->linear = offset + size;
732 /* 8 x (64/2) -> 256 x 16K -> 4MB */
733 KKASSERT(i >= 0 && i < HAMMER2_BMAP_ELEMENTS);
736 * Optimize the buffer cache to avoid unnecessary read-before-write
739 * The device block size could be larger than the allocation size
740 * so the actual bitmap test is somewhat more involved. We have
741 * to use a compatible buffer size for this operation.
743 if ((bmap->bitmapq[i] & bmmask) == 0 &&
744 hammer2_devblksize(size) != size) {
745 size_t psize = hammer2_devblksize(size);
746 hammer2_off_t pmask = (hammer2_off_t)psize - 1;
747 int pbmradix = (hammer2_bitmap_t)2 <<
748 (hammer2_devblkradix(radix) -
749 HAMMER2_FREEMAP_BLOCK_RADIX);
750 hammer2_bitmap_t pbmmask;
751 int pradix = hammer2_getradix(psize);
753 pbmmask = (pbmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
754 HAMMER2_BMAP_ALLONES :
755 ((hammer2_bitmap_t)1 << pbmradix) - 1;
756 while ((pbmmask & bmmask) == 0)
757 pbmmask <<= pbmradix;
760 kprintf("%016jx mask %016jx %016jx %016jx (%zd/%zd)\n",
761 *basep + offset, bmap->bitmapq[i],
762 pbmmask, bmmask, size, psize);
765 if ((bmap->bitmapq[i] & pbmmask) == 0) {
768 hammer2_io_newnz(hmp, class >> 8,
769 (*basep + (offset & ~pmask)) |
770 pradix, psize, &dio);
771 hammer2_io_putblk(&dio);
777 * When initializing a new inode segment also attempt to initialize
778 * an adjacent segment. Be careful not to index beyond the array
781 * We do this to try to localize inode accesses to improve
782 * directory scan rates. XXX doesn't improve scan rates.
784 if (size == HAMMER2_INODE_BYTES) {
786 if (bmap[-1].radix == 0 && bmap[-1].avail)
787 bmap[-1].radix = radix;
789 if (bmap[1].radix == 0 && bmap[1].avail)
790 bmap[1].radix = radix;
795 * Calculate the bitmap-granular change in bgsize for the volume
796 * header. We cannot use the fine-grained change here because
797 * the bulkfree code can't undo it. If the bitmap element is already
798 * marked allocated it has already been accounted for.
800 if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
801 if (bmap->bitmapq[i] & bmmask)
804 bgsize = HAMMER2_FREEMAP_BLOCK_SIZE;
810 * Adjust the bitmap, set the class (it might have been 0),
811 * and available bytes, update the allocation offset (*basep)
812 * from the L0 base to the actual offset.
814 * Do not override the class if doing a relaxed class allocation.
816 * avail must reflect the bitmap-granular availability. The allocator
817 * tests will also check the linear iterator.
819 bmap->bitmapq[i] |= bmmask;
820 if (bmap->class == 0)
822 bmap->avail -= bgsize;
826 * Adjust the volume header's allocator_free parameter. This
827 * parameter has to be fixed up by bulkfree which has no way to
828 * figure out sub-16K chunking, so it must be adjusted by the
829 * bitmap-granular size.
832 hammer2_voldata_lock(hmp);
833 hammer2_voldata_modify(hmp);
834 hmp->voldata.allocator_free -= bgsize;
835 hammer2_voldata_unlock(hmp);
842 * Initialize a freemap for the storage area (in bytes) that begins at (key).
846 hammer2_freemap_init(hammer2_dev_t *hmp, hammer2_key_t key,
847 hammer2_chain_t *chain)
849 hammer2_off_t l1size;
852 hammer2_bmap_data_t *bmap;
856 * LEVEL1 is 1GB, there are two level1 1GB freemaps per 2GB zone.
858 l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
861 * Calculate the portion of the 1GB map that should be initialized
862 * as free. Portions below or after will be initialized as allocated.
863 * SEGMASK-align the areas so we don't have to worry about sub-scans
864 * or endianess when using memset.
866 * WARNING! It is possible for lokey to be larger than hikey if the
867 * entire 2GB segment is within the static allocation.
870 * (1) Ensure that all statically allocated space from newfs_hammer2
871 * is marked allocated, and take it up to the level1 base for
874 lokey = (hmp->voldata.allocator_beg + HAMMER2_SEGMASK64) &
876 if (lokey < H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX))
877 lokey = H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX);
880 * (2) Ensure that the reserved area is marked allocated (typically
881 * the first 4MB of each 2GB area being represented). Since
882 * each LEAF represents 1GB of storage and the zone is 2GB, we
883 * have to adjust lowkey upward every other LEAF sequentially.
885 if (lokey < H2FMZONEBASE(key) + HAMMER2_ZONE_SEG64)
886 lokey = H2FMZONEBASE(key) + HAMMER2_ZONE_SEG64;
889 * (3) Ensure that any trailing space at the end-of-volume is marked
892 hikey = key + H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
893 if (hikey > hmp->voldata.volu_size) {
894 hikey = hmp->voldata.volu_size & ~HAMMER2_SEGMASK64;
898 * Heuristic highest possible value
900 chain->bref.check.freemap.avail =
901 H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
902 bmap = &chain->data->bmdata[0];
905 * Initialize bitmap (bzero'd by caller)
907 for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
908 if (key < lokey || key >= hikey) {
909 memset(bmap->bitmapq, -1,
910 sizeof(bmap->bitmapq));
912 bmap->linear = HAMMER2_SEGSIZE;
913 chain->bref.check.freemap.avail -=
914 H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
916 bmap->avail = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
918 key += H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
924 * The current Level 1 freemap has been exhausted, iterate to the next
925 * one, return ENOSPC if no freemaps remain.
927 * At least two loops are required. If we are not in relaxed mode and
928 * we run out of storage we enter relaxed mode and do a third loop.
929 * The relaxed mode is recorded back in the hmp so once we enter the mode
930 * we remain relaxed until stuff begins to get freed and only do 2 loops.
932 * XXX this should rotate back to the beginning to handle freed-up space
933 * XXX or use intermediate entries to locate free space. TODO
936 hammer2_freemap_iterate(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
937 hammer2_fiterate_t *iter)
939 hammer2_dev_t *hmp = (*parentp)->hmp;
941 iter->bnext &= ~(H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX) - 1);
942 iter->bnext += H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
943 if (iter->bnext >= hmp->voldata.volu_size) {
945 if (++iter->loops >= 2) {
946 if (iter->relaxed == 0)
949 return (HAMMER2_ERROR_ENOSPC);
952 return(HAMMER2_ERROR_EAGAIN);
956 * Adjust the bit-pattern for data in the freemap bitmap according to
957 * (how). This code is called from on-mount recovery to fixup (mark
958 * as allocated) blocks whos freemap upates might not have been committed
959 * in the last crash and is used by the bulk freemap scan to stage frees.
961 * WARNING! Cannot be called with a empty-data bref (radix == 0).
963 * XXX currently disabled when how == 0 (the normal real-time case). At
964 * the moment we depend on the bulk freescan to actually free blocks. It
965 * will still call this routine with a non-zero how to stage possible frees
966 * and to do the actual free.
969 hammer2_freemap_adjust(hammer2_dev_t *hmp, hammer2_blockref_t *bref,
972 hammer2_off_t data_off = bref->data_off;
973 hammer2_chain_t *chain;
974 hammer2_chain_t *parent;
975 hammer2_bmap_data_t *bmap;
977 hammer2_key_t key_dummy;
978 hammer2_off_t l0size;
979 hammer2_off_t l1size;
980 hammer2_off_t l1mask;
982 hammer2_bitmap_t *bitmap;
983 const hammer2_bitmap_t bmmask00 = 0;
984 hammer2_bitmap_t bmmask01;
985 hammer2_bitmap_t bmmask10;
986 hammer2_bitmap_t bmmask11;
996 KKASSERT(how == HAMMER2_FREEMAP_DORECOVER);
998 mtid = hammer2_trans_sub(hmp->spmp);
1000 radix = (int)data_off & HAMMER2_OFF_MASK_RADIX;
1001 KKASSERT(radix != 0);
1002 data_off &= ~HAMMER2_OFF_MASK_RADIX;
1003 KKASSERT(radix <= HAMMER2_RADIX_MAX);
1006 bytes = (size_t)1 << radix;
1009 class = (bref->type << 8) | hammer2_devblkradix(radix);
1012 * We can't adjust the freemap for data allocations made by
1015 if (data_off < hmp->voldata.allocator_beg)
1018 KKASSERT((data_off & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
1021 * Lookup the level1 freemap chain. The chain must exist.
1023 key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL1_RADIX);
1024 l0size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
1025 l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
1026 l1mask = l1size - 1;
1028 parent = &hmp->fchain;
1029 hammer2_chain_ref(parent);
1030 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1032 chain = hammer2_chain_lookup(&parent, &key_dummy, key, key + l1mask,
1034 HAMMER2_LOOKUP_ALWAYS |
1035 HAMMER2_LOOKUP_MATCHIND);
1038 * Stop early if we are trying to free something but no leaf exists.
1040 if (chain == NULL && how != HAMMER2_FREEMAP_DORECOVER) {
1041 kprintf("hammer2_freemap_adjust: %016jx: no chain\n",
1042 (intmax_t)bref->data_off);
1046 kprintf("hammer2_freemap_adjust: %016jx: error %s\n",
1047 (intmax_t)bref->data_off,
1048 hammer2_error_str(chain->error));
1049 hammer2_chain_unlock(chain);
1050 hammer2_chain_drop(chain);
1056 * Create any missing leaf(s) if we are doing a recovery (marking
1057 * the block(s) as being allocated instead of being freed). Be sure
1058 * to initialize the auxillary freemap tracking info in the
1059 * bref.check.freemap structure.
1061 if (chain == NULL && how == HAMMER2_FREEMAP_DORECOVER) {
1062 error = hammer2_chain_create(&parent, &chain,
1063 hmp->spmp, HAMMER2_METH_DEFAULT,
1064 key, HAMMER2_FREEMAP_LEVEL1_RADIX,
1065 HAMMER2_BREF_TYPE_FREEMAP_LEAF,
1066 HAMMER2_FREEMAP_LEVELN_PSIZE,
1069 if (hammer2_debug & 0x0040) {
1070 kprintf("fixup create chain %p %016jx:%d\n",
1071 chain, chain->bref.key, chain->bref.keybits);
1075 error = hammer2_chain_modify(chain, mtid, 0, 0);
1076 KKASSERT(error == 0);
1077 bzero(&chain->data->bmdata[0],
1078 HAMMER2_FREEMAP_LEVELN_PSIZE);
1079 chain->bref.check.freemap.bigmask = (uint32_t)-1;
1080 chain->bref.check.freemap.avail = l1size;
1081 /* bref.methods should already be inherited */
1083 hammer2_freemap_init(hmp, key, chain);
1085 /* XXX handle error */
1089 kprintf("FREEMAP ADJUST TYPE %d %016jx/%d DATA_OFF=%016jx\n",
1090 chain->bref.type, chain->bref.key,
1091 chain->bref.keybits, chain->bref.data_off);
1095 * Calculate the bitmask (runs in 2-bit pairs).
1097 start = ((int)(data_off >> HAMMER2_FREEMAP_BLOCK_RADIX) & 15) * 2;
1098 bmmask01 = (hammer2_bitmap_t)1 << start;
1099 bmmask10 = (hammer2_bitmap_t)2 << start;
1100 bmmask11 = (hammer2_bitmap_t)3 << start;
1103 * Fixup the bitmap. Partial blocks cannot be fully freed unless
1104 * a bulk scan is able to roll them up.
1106 if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
1108 if (how == HAMMER2_FREEMAP_DOREALFREE)
1109 how = HAMMER2_FREEMAP_DOMAYFREE;
1111 count = 1 << (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
1115 * [re]load the bmap and bitmap pointers. Each bmap entry covers
1116 * a 4MB swath. The bmap itself (LEVEL1) covers 2GB.
1118 * Be sure to reset the linear iterator to ensure that the adjustment
1122 bmap = &chain->data->bmdata[(int)(data_off >> HAMMER2_SEGRADIX) &
1123 (HAMMER2_FREEMAP_COUNT - 1)];
1124 bitmap = &bmap->bitmapq[(int)(data_off >> (HAMMER2_SEGRADIX - 3)) & 7];
1131 if (how == HAMMER2_FREEMAP_DORECOVER) {
1133 * Recovery request, mark as allocated.
1135 if ((*bitmap & bmmask11) != bmmask11) {
1136 if (modified == 0) {
1137 hammer2_chain_modify(chain, mtid, 0, 0);
1141 if ((*bitmap & bmmask11) == bmmask00) {
1143 HAMMER2_FREEMAP_BLOCK_SIZE;
1144 bgsize += HAMMER2_FREEMAP_BLOCK_SIZE;
1146 if (bmap->class == 0)
1147 bmap->class = class;
1148 *bitmap |= bmmask11;
1149 if (hammer2_debug & 0x0040) {
1150 kprintf("hammer2_freemap_recover: "
1152 "block=%016jx/%zd\n",
1153 bref->type, data_off, bytes);
1157 kprintf("hammer2_freemap_recover: good "
1158 "type=%02x block=%016jx/%zd\n",
1159 bref->type, data_off, bytes);
1165 * XXX this stuff doesn't work, avail is miscalculated and
1166 * code 10 means something else now.
1168 else if ((*bitmap & bmmask11) == bmmask11) {
1170 * Mayfree/Realfree request and bitmap is currently
1171 * marked as being fully allocated.
1174 hammer2_chain_modify(chain, 0);
1178 if (how == HAMMER2_FREEMAP_DOREALFREE)
1179 *bitmap &= ~bmmask11;
1181 *bitmap = (*bitmap & ~bmmask11) | bmmask10;
1182 } else if ((*bitmap & bmmask11) == bmmask10) {
1184 * Mayfree/Realfree request and bitmap is currently
1185 * marked as being possibly freeable.
1187 if (how == HAMMER2_FREEMAP_DOREALFREE) {
1189 hammer2_chain_modify(chain, 0);
1193 *bitmap &= ~bmmask11;
1197 * 01 - Not implemented, currently illegal state
1198 * 00 - Not allocated at all, illegal free.
1200 panic("hammer2_freemap_adjust: "
1201 "Illegal state %08x(%08x)",
1202 *bitmap, *bitmap & bmmask11);
1210 #if HAMMER2_BMAP_ELEMENTS != 8
1211 #error "hammer2_freemap.c: HAMMER2_BMAP_ELEMENTS expected to be 8"
1213 if (how == HAMMER2_FREEMAP_DOREALFREE && modified) {
1214 bmap->avail += 1 << radix;
1215 KKASSERT(bmap->avail <= HAMMER2_SEGSIZE);
1216 if (bmap->avail == HAMMER2_SEGSIZE &&
1217 bmap->bitmapq[0] == 0 &&
1218 bmap->bitmapq[1] == 0 &&
1219 bmap->bitmapq[2] == 0 &&
1220 bmap->bitmapq[3] == 0 &&
1221 bmap->bitmapq[4] == 0 &&
1222 bmap->bitmapq[5] == 0 &&
1223 bmap->bitmapq[6] == 0 &&
1224 bmap->bitmapq[7] == 0) {
1225 key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL0_RADIX);
1226 kprintf("Freeseg %016jx\n", (intmax_t)key);
1232 * chain->bref.check.freemap.bigmask (XXX)
1234 * Setting bigmask is a hint to the allocation code that there might
1235 * be something allocatable. We also set this in recovery... it
1236 * doesn't hurt and we might want to use the hint for other validation
1237 * operations later on.
1239 * We could calculate the largest possible allocation and set the
1240 * radii that could fit, but its easier just to set bigmask to -1.
1243 chain->bref.check.freemap.bigmask = -1;
1244 hmp->freemap_relaxed = 0; /* reset heuristic */
1247 hammer2_chain_unlock(chain);
1248 hammer2_chain_drop(chain);
1250 hammer2_chain_unlock(parent);
1251 hammer2_chain_drop(parent);
1254 hammer2_voldata_lock(hmp);
1255 hammer2_voldata_modify(hmp);
1256 hmp->voldata.allocator_free -= bgsize;
1257 hammer2_voldata_unlock(hmp);
1262 * Validate the freemap, in three stages.
1264 * stage-1 ALLOCATED -> POSSIBLY FREE
1265 * POSSIBLY FREE -> POSSIBLY FREE (type corrected)
1267 * This transitions bitmap entries from ALLOCATED to POSSIBLY FREE.
1268 * The POSSIBLY FREE state does not mean that a block is actually free
1269 * and may be transitioned back to ALLOCATED in stage-2.
1271 * This is typically done during normal filesystem operations when
1272 * something is deleted or a block is replaced.
1274 * This is done by bulkfree in-bulk after a memory-bounded meta-data
1275 * scan to try to determine what might be freeable.
1277 * This can be done unconditionally through a freemap scan when the
1278 * intention is to brute-force recover the proper state of the freemap.
1280 * stage-2 POSSIBLY FREE -> ALLOCATED (scan metadata topology)
1282 * This is done by bulkfree during a meta-data scan to ensure that
1283 * all blocks still actually allocated by the filesystem are marked
1286 * NOTE! Live filesystem transitions to POSSIBLY FREE can occur while
1287 * the bulkfree stage-2 and stage-3 is running. The live filesystem
1288 * will use the alternative POSSIBLY FREE type (2) to prevent
1289 * stage-3 from improperly transitioning unvetted possibly-free
1292 * stage-3 POSSIBLY FREE (type 1) -> FREE (scan freemap)
1294 * This is done by bulkfree to finalize POSSIBLY FREE states.