xref: /dragonfly/sys/vfs/hammer2/hammer2_freemap.c (revision 65cc0652)
1 /*
2  * Copyright (c) 2011-2014 The DragonFly Project.  All rights reserved.
3  *
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>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
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
17  *    distribution.
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.
21  *
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
33  * SUCH DAMAGE.
34  */
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/fcntl.h>
39 #include <sys/buf.h>
40 #include <sys/proc.h>
41 #include <sys/namei.h>
42 #include <sys/mount.h>
43 #include <sys/vnode.h>
44 #include <sys/mountctl.h>
45 
46 #include "hammer2.h"
47 
48 #define FREEMAP_DEBUG	0
49 
50 struct hammer2_fiterate {
51 	hammer2_off_t	bpref;
52 	hammer2_off_t	bnext;
53 	int		loops;
54 	int		relaxed;
55 };
56 
57 typedef struct hammer2_fiterate hammer2_fiterate_t;
58 
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);
70 
71 static __inline
72 int
73 hammer2_freemapradix(int radix)
74 {
75 	return(radix);
76 }
77 
78 /*
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
83  *
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
87  *
88  *     (see same thing in hammer2_bulkfree.c near the top, as well as in
89  *     newfs_hammer2).
90  *
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
93  * scan at mount-time.
94  */
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))
98 
99 static
100 int
101 hammer2_freemap_reserve(hammer2_chain_t *chain, int radix)
102 {
103 	hammer2_blockref_t *bref = &chain->bref;
104 	hammer2_off_t off;
105 	int index;
106 	int index_inc;
107 	size_t bytes;
108 
109 	/*
110 	 * Physical allocation size.
111 	 */
112 	bytes = (size_t)1 << radix;
113 
114 	/*
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
118 	 * index.
119 	 */
120 	if ((bref->data_off & ~HAMMER2_OFF_MASK_RADIX) == 0) {
121 		index = 0;
122 	} else {
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)
133 			index = 0;
134 	}
135 
136 	/*
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.
140 	 */
141 	index_inc = index * HAMMER2_ZONE_FREEMAP_INC;
142 
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;
151 		break;
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;
158 		break;
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;
165 		break;
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;
172 		break;
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;
179 		break;
180 	default:
181 		panic("freemap: bad radix(2) %p %d\n", bref, bref->keybits);
182 		/* NOT REACHED */
183 		off = (hammer2_off_t)-1;
184 		break;
185 	}
186 	bref->data_off = off | radix;
187 #if FREEMAP_DEBUG
188 	kprintf("FREEMAP BLOCK TYPE %d %016jx/%d DATA_OFF=%016jx\n",
189 		bref->type, bref->key, bref->keybits, bref->data_off);
190 #endif
191 	return (0);
192 }
193 
194 /*
195  * Normal freemap allocator
196  *
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).
201  *
202  * ip and bpref are only used as a heuristic to determine locality of
203  * reference.  bref->key may also be used heuristically.
204  *
205  * This function is a NOP if bytes is 0.
206  */
207 int
208 hammer2_freemap_alloc(hammer2_chain_t *chain, size_t bytes)
209 {
210 	hammer2_dev_t *hmp = chain->hmp;
211 	hammer2_blockref_t *bref = &chain->bref;
212 	hammer2_chain_t *parent;
213 	hammer2_tid_t mtid;
214 	int radix;
215 	int error;
216 	unsigned int hindex;
217 	hammer2_fiterate_t iter;
218 
219 	/*
220 	 * If allocating or downsizing to zero we just get rid of whatever
221 	 * data_off we had.
222 	 */
223 	if (bytes == 0) {
224 		chain->bref.data_off = 0;
225 		return 0;
226 	}
227 
228 	mtid = hammer2_trans_sub(hmp->spmp);
229 
230 	/*
231 	 * Validate the allocation size.  It must be a power of 2.
232 	 *
233 	 * For now require that the caller be aware of the minimum
234 	 * allocation (1K).
235 	 */
236 	radix = hammer2_getradix(bytes);
237 	KKASSERT((size_t)1 << radix == bytes);
238 
239 	if (bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
240 	    bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
241 		/*
242 		 * Freemap blocks themselves are assigned from the reserve
243 		 * area, not allocated from the freemap.
244 		 */
245 		error = hammer2_freemap_reserve(chain, radix);
246 
247 		return error;
248 	}
249 
250 	KKASSERT(bytes >= HAMMER2_ALLOC_MIN && bytes <= HAMMER2_ALLOC_MAX);
251 
252 	/*
253 	 * Calculate the starting point for our allocation search.
254 	 *
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.
261 	 *
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.
265 	 */
266 #if 0
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;
273 	else
274 #endif
275 	/*
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.
280 	 */
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);
286 
287 	iter.bpref = hmp->heur_freemap[hindex];
288 	iter.relaxed = hmp->freemap_relaxed;
289 
290 	/*
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.
293 	 */
294 	if (iter.bpref > hmp->voldata.volu_size)
295 		iter.bpref = hmp->voldata.volu_size - 1;
296 
297 	/*
298 	 * Iterate the freemap looking for free space before and after.
299 	 */
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;
305 	iter.loops = 0;
306 
307 	while (error == HAMMER2_ERROR_EAGAIN) {
308 		error = hammer2_freemap_try_alloc(&parent, bref, radix,
309 						  &iter, mtid);
310 	}
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);
315 
316 	return (error);
317 }
318 
319 static int
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)
323 {
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;
330 	hammer2_off_t key;
331 	size_t bytes;
332 	uint16_t class;
333 	int error;
334 
335 	/*
336 	 * Calculate the number of bytes being allocated, the number
337 	 * of contiguous bits of bitmap being allocated, and the bitmap
338 	 * mask.
339 	 *
340 	 * WARNING! cpu hardware may mask bits == 64 -> 0 and blow up the
341 	 *	    mask calculation.
342 	 */
343 	bytes = (size_t)1 << radix;
344 	class = (bref->type << 8) | hammer2_devblkradix(radix);
345 
346 	/*
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().
350 	 */
351 	key = H2FMBASE(iter->bnext, HAMMER2_FREEMAP_LEVEL1_RADIX);
352 	l0size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
353 	l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
354 	l1mask = l1size - 1;
355 
356 	chain = hammer2_chain_lookup(parentp, &key_dummy, key, key + l1mask,
357 				     &error,
358 				     HAMMER2_LOOKUP_ALWAYS |
359 				     HAMMER2_LOOKUP_MATCHIND);
360 
361 	if (chain == NULL) {
362 		/*
363 		 * Create the missing leaf, be sure to initialize
364 		 * the auxillary freemap tracking information in
365 		 * the bref.check.freemap structure.
366 		 */
367 #if 0
368 		kprintf("freemap create L1 @ %016jx bpref %016jx\n",
369 			key, iter->bpref);
370 #endif
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,
376 				     mtid, 0, 0);
377 		KKASSERT(error == 0);
378 		if (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 */
385 
386 			hammer2_freemap_init(hmp, key, chain);
387 		}
388 	} else if (chain->error) {
389 		/*
390 		 * Error during lookup.
391 		 */
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) {
398 		/*
399 		 * Already flagged as not having enough space
400 		 */
401 		error = HAMMER2_ERROR_ENOSPC;
402 	} else {
403 		/*
404 		 * Modify existing chain to setup for adjustment.
405 		 */
406 		hammer2_chain_modify(chain, mtid, 0, 0);
407 	}
408 
409 	/*
410 	 * Scan 4MB entries.
411 	 */
412 	if (error == 0) {
413 		hammer2_bmap_data_t *bmap;
414 		hammer2_key_t base_key;
415 		int count;
416 		int start;
417 		int n;
418 
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);
424 
425 		error = HAMMER2_ERROR_ENOSPC;
426 		for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
427 			int availchk;
428 
429 			if (start + count >= HAMMER2_FREEMAP_COUNT &&
430 			    start - count < 0) {
431 				break;
432 			}
433 
434 			/*
435 			 * Calculate bmap pointer from thart starting index
436 			 * forwards.
437 			 *
438 			 * NOTE: bmap pointer is invalid if n >= FREEMAP_COUNT.
439 			 */
440 			n = start + count;
441 			bmap = &chain->data->bmdata[n];
442 
443 			if (n >= HAMMER2_FREEMAP_COUNT) {
444 				availchk = 0;
445 			} else if (bmap->avail) {
446 				availchk = 1;
447 			} else if (radix < HAMMER2_FREEMAP_BLOCK_RADIX &&
448 			          (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK)) {
449 				availchk = 1;
450 			} else {
451 				availchk = 0;
452 			}
453 
454 			/*
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.
458 			 */
459 			if (availchk &&
460 			    (bmap->class == 0 || bmap->class == class ||
461 			     iter->relaxed)) {
462 				base_key = key + n * l0size;
463 				error = hammer2_bmap_alloc(hmp, bmap,
464 							   class, n,
465 							   (int)bref->key,
466 							   radix,
467 							   &base_key);
468 				if (error != HAMMER2_ERROR_ENOSPC) {
469 					key = base_key;
470 					break;
471 				}
472 			}
473 
474 			/*
475 			 * Calculate bmap pointer from thart starting index
476 			 * backwards (locality).
477 			 *
478 			 * Must recalculate after potentially having called
479 			 * hammer2_bmap_alloc() above in case chain was
480 			 * reallocated.
481 			 *
482 			 * NOTE: bmap pointer is invalid if n < 0.
483 			 */
484 			n = start - count;
485 			bmap = &chain->data->bmdata[n];
486 			if (n < 0) {
487 				availchk = 0;
488 			} else if (bmap->avail) {
489 				availchk = 1;
490 			} else if (radix < HAMMER2_FREEMAP_BLOCK_RADIX &&
491 			          (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK)) {
492 				availchk = 1;
493 			} else {
494 				availchk = 0;
495 			}
496 
497 			/*
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.
501 			 */
502 			if (availchk &&
503 			    (bmap->class == 0 || bmap->class == class ||
504 			    iter->relaxed)) {
505 				base_key = key + n * l0size;
506 				error = hammer2_bmap_alloc(hmp, bmap,
507 							   class, n,
508 							   (int)bref->key,
509 							   radix,
510 							   &base_key);
511 				if (error != HAMMER2_ERROR_ENOSPC) {
512 					key = base_key;
513 					break;
514 				}
515 			}
516 		}
517 
518 		/*
519 		 * We only know for sure that we can clear the bitmap bit
520 		 * if we scanned the entire array (start == 0).
521 		 */
522 		if (error == HAMMER2_ERROR_ENOSPC && start == 0) {
523 			chain->bref.check.freemap.bigmask &=
524 				(uint32_t)~((size_t)1 << radix);
525 		}
526 		/* XXX also scan down from original count */
527 	}
528 
529 	if (error == 0) {
530 		/*
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.
535 		 */
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;
540 
541 		/*
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.
545 		 *
546 		 * We must record the bitmask with the chain locked
547 		 * at the time we set the allocation bits to avoid
548 		 * racing a bulkfree.
549 		 */
550 		if (bref->type == HAMMER2_BREF_TYPE_DATA)
551 			hammer2_io_dedup_set(hmp, bref);
552 #if 0
553 		kprintf("alloc cp=%p %016jx %016jx using %016jx\n",
554 			chain,
555 			bref->key, bref->data_off, chain->bref.data_off);
556 #endif
557 	} else if (error == HAMMER2_ERROR_ENOSPC) {
558 		/*
559 		 * Return EAGAIN with next iteration in iter->bnext, or
560 		 * return ENOSPC if the allocation map has been exhausted.
561 		 */
562 		error = hammer2_freemap_iterate(parentp, &chain, iter);
563 	}
564 
565 	/*
566 	 * Cleanup
567 	 */
568 	if (chain) {
569 		hammer2_chain_unlock(chain);
570 		hammer2_chain_drop(chain);
571 	}
572 	return (error);
573 }
574 
575 /*
576  * Allocate (1<<radix) bytes from the bmap whos base data offset is (*basep).
577  *
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.
581  *
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.
585  *
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.
590  */
591 static
592 int
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)
596 {
597 	size_t size;
598 	size_t bgsize;
599 	int bmradix;
600 	hammer2_bitmap_t bmmask;
601 	int offset;
602 	int i;
603 	int j;
604 
605 	/*
606 	 * Take into account 2-bits per block when calculating bmradix.
607 	 */
608 	size = (size_t)1 << radix;
609 
610 	if (radix <= HAMMER2_FREEMAP_BLOCK_RADIX) {
611 		bmradix = 2;
612 		/* (16K) 2 bits per allocation block */
613 	} else {
614 		bmradix = (hammer2_bitmap_t)2 <<
615 			  (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
616 		/* (32K-256K) 4, 8, 16, 32 bits per allocation block */
617 	}
618 
619 	/*
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).
628 	 *
629 	 * Beware of hardware artifacts when bmradix == 64 (intermediate
630 	 * result can wind up being '1' instead of '0' if hardware masks
631 	 * bit-count & 63).
632 	 *
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.
635 	 *
636 	 * NOTE: TODO this can leave little unallocatable fragments lying
637 	 *	 around.
638 	 */
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) {
643 		/*
644 		 * Use linear iterator if it is not block-aligned to avoid
645 		 * wasting space.
646 		 */
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;
656 		bmmask <<= j;
657 		bmap->linear = offset + size;
658 	} else {
659 		/*
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
663 		 * order.
664 		 *
665 		 * i - Index bitmapq[], full data range represented is
666 		 *     HAMMER2_BMAP_SIZE.
667 		 *
668 		 * j - Index within bitmapq[i], full data range represented is
669 		 *     HAMMER2_BMAP_INDEX_SIZE.
670 		 *
671 		 * WARNING!
672 		 */
673 		i = -1;
674 		j = -1;
675 
676 		switch(class >> 8) {
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);
684 				j = j * 2;
685 			}
686 			break;
687 		case HAMMER2_BREF_TYPE_INODE:
688 			break;
689 		default:
690 			break;
691 		}
692 		if (i >= 0) {
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;
699 			bmmask <<= j;
700 
701 			if ((bmap->bitmapq[i] & bmmask) == 0)
702 				goto success;
703 		}
704 
705 		/*
706 		 * General element scan.
707 		 *
708 		 * WARNING: (j) is iterating a bit index (by 2's)
709 		 */
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;
714 			for (j = 0;
715 			     j < HAMMER2_BMAP_BITS_PER_ELEMENT;
716 			     j += bmradix) {
717 				if ((bmap->bitmapq[i] & bmmask) == 0)
718 					goto success;
719 				bmmask <<= bmradix;
720 			}
721 		}
722 		/*fragments might remain*/
723 		/*KKASSERT(bmap->avail == 0);*/
724 		return (HAMMER2_ERROR_ENOSPC);
725 success:
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;
730 	}
731 
732 	/* 8 x (64/2) -> 256 x 16K -> 4MB */
733 	KKASSERT(i >= 0 && i < HAMMER2_BMAP_ELEMENTS);
734 
735 	/*
736 	 * Optimize the buffer cache to avoid unnecessary read-before-write
737 	 * operations.
738 	 *
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.
742 	 */
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);
752 
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;
758 
759 #if 0
760 		kprintf("%016jx mask %016jx %016jx %016jx (%zd/%zd)\n",
761 			*basep + offset, bmap->bitmapq[i],
762 			pbmmask, bmmask, size, psize);
763 #endif
764 
765 		if ((bmap->bitmapq[i] & pbmmask) == 0) {
766 			hammer2_io_t *dio;
767 
768 			hammer2_io_newnz(hmp, class >> 8,
769 					(*basep + (offset & ~pmask)) |
770 					pradix, psize, &dio);
771 			hammer2_io_putblk(&dio);
772 		}
773 	}
774 
775 #if 0
776 	/*
777 	 * When initializing a new inode segment also attempt to initialize
778 	 * an adjacent segment.  Be careful not to index beyond the array
779 	 * bounds.
780 	 *
781 	 * We do this to try to localize inode accesses to improve
782 	 * directory scan rates.  XXX doesn't improve scan rates.
783 	 */
784 	if (size == HAMMER2_INODE_BYTES) {
785 		if (n & 1) {
786 			if (bmap[-1].radix == 0 && bmap[-1].avail)
787 				bmap[-1].radix = radix;
788 		} else {
789 			if (bmap[1].radix == 0 && bmap[1].avail)
790 				bmap[1].radix = radix;
791 		}
792 	}
793 #endif
794 	/*
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.
799 	 */
800 	if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
801 		if (bmap->bitmapq[i] & bmmask)
802 			bgsize = 0;
803 		else
804 			bgsize = HAMMER2_FREEMAP_BLOCK_SIZE;
805 	} else {
806 		bgsize = size;
807 	}
808 
809 	/*
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.
813 	 *
814 	 * Do not override the class if doing a relaxed class allocation.
815 	 *
816 	 * avail must reflect the bitmap-granular availability.  The allocator
817 	 * tests will also check the linear iterator.
818 	 */
819 	bmap->bitmapq[i] |= bmmask;
820 	if (bmap->class == 0)
821 		bmap->class = class;
822 	bmap->avail -= bgsize;
823 	*basep += offset;
824 
825 	/*
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.
830 	 */
831 	if (bgsize) {
832 		hammer2_voldata_lock(hmp);
833 		hammer2_voldata_modify(hmp);
834 		hmp->voldata.allocator_free -= bgsize;
835 		hammer2_voldata_unlock(hmp);
836 	}
837 
838 	return(0);
839 }
840 
841 /*
842  * Initialize a freemap for the storage area (in bytes) that begins at (key).
843  */
844 static
845 void
846 hammer2_freemap_init(hammer2_dev_t *hmp, hammer2_key_t key,
847 		     hammer2_chain_t *chain)
848 {
849 	hammer2_off_t l1size;
850 	hammer2_off_t lokey;
851 	hammer2_off_t hikey;
852 	hammer2_bmap_data_t *bmap;
853 	int count;
854 
855 	/*
856 	 * LEVEL1 is 1GB, there are two level1 1GB freemaps per 2GB zone.
857 	 */
858 	l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
859 
860 	/*
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.
865 	 *
866 	 * WARNING! It is possible for lokey to be larger than hikey if the
867 	 *	    entire 2GB segment is within the static allocation.
868 	 */
869 	/*
870 	 * (1) Ensure that all statically allocated space from newfs_hammer2
871 	 *     is marked allocated, and take it up to the level1 base for
872 	 *     this key.
873 	 */
874 	lokey = (hmp->voldata.allocator_beg + HAMMER2_SEGMASK64) &
875 		~HAMMER2_SEGMASK64;
876 	if (lokey < H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX))
877 		lokey = H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX);
878 
879 	/*
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.
884 	 */
885 	if (lokey < H2FMZONEBASE(key) + HAMMER2_ZONE_SEG64)
886 		lokey = H2FMZONEBASE(key) + HAMMER2_ZONE_SEG64;
887 
888 	/*
889 	 * (3) Ensure that any trailing space at the end-of-volume is marked
890 	 *     allocated.
891 	 */
892 	hikey = key + H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
893 	if (hikey > hmp->voldata.volu_size) {
894 		hikey = hmp->voldata.volu_size & ~HAMMER2_SEGMASK64;
895 	}
896 
897 	/*
898 	 * Heuristic highest possible value
899 	 */
900 	chain->bref.check.freemap.avail =
901 		H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
902 	bmap = &chain->data->bmdata[0];
903 
904 	/*
905 	 * Initialize bitmap (bzero'd by caller)
906 	 */
907 	for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
908 		if (key < lokey || key >= hikey) {
909 			memset(bmap->bitmapq, -1,
910 			       sizeof(bmap->bitmapq));
911 			bmap->avail = 0;
912 			bmap->linear = HAMMER2_SEGSIZE;
913 			chain->bref.check.freemap.avail -=
914 				H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
915 		} else {
916 			bmap->avail = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
917 		}
918 		key += H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
919 		++bmap;
920 	}
921 }
922 
923 /*
924  * The current Level 1 freemap has been exhausted, iterate to the next
925  * one, return ENOSPC if no freemaps remain.
926  *
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.
931  *
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
934  */
935 static int
936 hammer2_freemap_iterate(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
937 			hammer2_fiterate_t *iter)
938 {
939 	hammer2_dev_t *hmp = (*parentp)->hmp;
940 
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) {
944 		iter->bnext = 0;
945 		if (++iter->loops >= 2) {
946 			if (iter->relaxed == 0)
947 				iter->relaxed = 1;
948 			else
949 				return (HAMMER2_ERROR_ENOSPC);
950 		}
951 	}
952 	return(HAMMER2_ERROR_EAGAIN);
953 }
954 
955 /*
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.
960  *
961  * WARNING! Cannot be called with a empty-data bref (radix == 0).
962  *
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.
967  */
968 void
969 hammer2_freemap_adjust(hammer2_dev_t *hmp, hammer2_blockref_t *bref,
970 		       int how)
971 {
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;
976 	hammer2_key_t key;
977 	hammer2_key_t key_dummy;
978 	hammer2_off_t l0size;
979 	hammer2_off_t l1size;
980 	hammer2_off_t l1mask;
981 	hammer2_tid_t mtid;
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;
987 	size_t bytes;
988 	uint16_t class;
989 	int radix;
990 	int start;
991 	int count;
992 	int modified = 0;
993 	int error;
994 	size_t bgsize = 0;
995 
996 	KKASSERT(how == HAMMER2_FREEMAP_DORECOVER);
997 
998 	mtid = hammer2_trans_sub(hmp->spmp);
999 
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);
1004 
1005 	if (radix)
1006 		bytes = (size_t)1 << radix;
1007 	else
1008 		bytes = 0;
1009 	class = (bref->type << 8) | hammer2_devblkradix(radix);
1010 
1011 	/*
1012 	 * We can't adjust the freemap for data allocations made by
1013 	 * newfs_hammer2.
1014 	 */
1015 	if (data_off < hmp->voldata.allocator_beg)
1016 		return;
1017 
1018 	KKASSERT((data_off & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
1019 
1020 	/*
1021 	 * Lookup the level1 freemap chain.  The chain must exist.
1022 	 */
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;
1027 
1028 	parent = &hmp->fchain;
1029 	hammer2_chain_ref(parent);
1030 	hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1031 
1032 	chain = hammer2_chain_lookup(&parent, &key_dummy, key, key + l1mask,
1033 				     &error,
1034 				     HAMMER2_LOOKUP_ALWAYS |
1035 				     HAMMER2_LOOKUP_MATCHIND);
1036 
1037 	/*
1038 	 * Stop early if we are trying to free something but no leaf exists.
1039 	 */
1040 	if (chain == NULL && how != HAMMER2_FREEMAP_DORECOVER) {
1041 		kprintf("hammer2_freemap_adjust: %016jx: no chain\n",
1042 			(intmax_t)bref->data_off);
1043 		goto done;
1044 	}
1045 	if (chain->error) {
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);
1051 		chain = NULL;
1052 		goto done;
1053 	}
1054 
1055 	/*
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.
1060 	 */
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,
1067 				     mtid, 0, 0);
1068 
1069 		if (hammer2_debug & 0x0040) {
1070 			kprintf("fixup create chain %p %016jx:%d\n",
1071 				chain, chain->bref.key, chain->bref.keybits);
1072 		}
1073 
1074 		if (error == 0) {
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 */
1082 
1083 			hammer2_freemap_init(hmp, key, chain);
1084 		}
1085 		/* XXX handle error */
1086 	}
1087 
1088 #if FREEMAP_DEBUG
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);
1092 #endif
1093 
1094 	/*
1095 	 * Calculate the bitmask (runs in 2-bit pairs).
1096 	 */
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;
1101 
1102 	/*
1103 	 * Fixup the bitmap.  Partial blocks cannot be fully freed unless
1104 	 * a bulk scan is able to roll them up.
1105 	 */
1106 	if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
1107 		count = 1;
1108 		if (how == HAMMER2_FREEMAP_DOREALFREE)
1109 			how = HAMMER2_FREEMAP_DOMAYFREE;
1110 	} else {
1111 		count = 1 << (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
1112 	}
1113 
1114 	/*
1115 	 * [re]load the bmap and bitmap pointers.  Each bmap entry covers
1116 	 * a 4MB swath.  The bmap itself (LEVEL1) covers 2GB.
1117 	 *
1118 	 * Be sure to reset the linear iterator to ensure that the adjustment
1119 	 * is not ignored.
1120 	 */
1121 again:
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];
1125 
1126 	if (modified)
1127 		bmap->linear = 0;
1128 
1129 	while (count) {
1130 		KKASSERT(bmmask11);
1131 		if (how == HAMMER2_FREEMAP_DORECOVER) {
1132 			/*
1133 			 * Recovery request, mark as allocated.
1134 			 */
1135 			if ((*bitmap & bmmask11) != bmmask11) {
1136 				if (modified == 0) {
1137 					hammer2_chain_modify(chain, mtid, 0, 0);
1138 					modified = 1;
1139 					goto again;
1140 				}
1141 				if ((*bitmap & bmmask11) == bmmask00) {
1142 					bmap->avail -=
1143 						HAMMER2_FREEMAP_BLOCK_SIZE;
1144 					bgsize += HAMMER2_FREEMAP_BLOCK_SIZE;
1145 				}
1146 				if (bmap->class == 0)
1147 					bmap->class = class;
1148 				*bitmap |= bmmask11;
1149 				if (hammer2_debug & 0x0040) {
1150 					kprintf("hammer2_freemap_recover: "
1151 						"fixup type=%02x "
1152 						"block=%016jx/%zd\n",
1153 						bref->type, data_off, bytes);
1154 				}
1155 			} else {
1156 				/*
1157 				kprintf("hammer2_freemap_recover:  good "
1158 					"type=%02x block=%016jx/%zd\n",
1159 					bref->type, data_off, bytes);
1160 				*/
1161 			}
1162 		}
1163 #if 0
1164 		/*
1165 		 * XXX this stuff doesn't work, avail is miscalculated and
1166 		 * code 10 means something else now.
1167 		 */
1168 		else if ((*bitmap & bmmask11) == bmmask11) {
1169 			/*
1170 			 * Mayfree/Realfree request and bitmap is currently
1171 			 * marked as being fully allocated.
1172 			 */
1173 			if (!modified) {
1174 				hammer2_chain_modify(chain, 0);
1175 				modified = 1;
1176 				goto again;
1177 			}
1178 			if (how == HAMMER2_FREEMAP_DOREALFREE)
1179 				*bitmap &= ~bmmask11;
1180 			else
1181 				*bitmap = (*bitmap & ~bmmask11) | bmmask10;
1182 		} else if ((*bitmap & bmmask11) == bmmask10) {
1183 			/*
1184 			 * Mayfree/Realfree request and bitmap is currently
1185 			 * marked as being possibly freeable.
1186 			 */
1187 			if (how == HAMMER2_FREEMAP_DOREALFREE) {
1188 				if (!modified) {
1189 					hammer2_chain_modify(chain, 0);
1190 					modified = 1;
1191 					goto again;
1192 				}
1193 				*bitmap &= ~bmmask11;
1194 			}
1195 		} else {
1196 			/*
1197 			 * 01 - Not implemented, currently illegal state
1198 			 * 00 - Not allocated at all, illegal free.
1199 			 */
1200 			panic("hammer2_freemap_adjust: "
1201 			      "Illegal state %08x(%08x)",
1202 			      *bitmap, *bitmap & bmmask11);
1203 		}
1204 #endif
1205 		--count;
1206 		bmmask01 <<= 2;
1207 		bmmask10 <<= 2;
1208 		bmmask11 <<= 2;
1209 	}
1210 #if HAMMER2_BMAP_ELEMENTS != 8
1211 #error "hammer2_freemap.c: HAMMER2_BMAP_ELEMENTS expected to be 8"
1212 #endif
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);
1227 			bmap->class = 0;
1228 		}
1229 	}
1230 
1231 	/*
1232 	 * chain->bref.check.freemap.bigmask (XXX)
1233 	 *
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.
1238 	 *
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.
1241 	 */
1242 	if (modified) {
1243 		chain->bref.check.freemap.bigmask = -1;
1244 		hmp->freemap_relaxed = 0;	/* reset heuristic */
1245 	}
1246 
1247 	hammer2_chain_unlock(chain);
1248 	hammer2_chain_drop(chain);
1249 done:
1250 	hammer2_chain_unlock(parent);
1251 	hammer2_chain_drop(parent);
1252 
1253 	if (bgsize) {
1254 		hammer2_voldata_lock(hmp);
1255 		hammer2_voldata_modify(hmp);
1256 		hmp->voldata.allocator_free -= bgsize;
1257 		hammer2_voldata_unlock(hmp);
1258 	}
1259 }
1260 
1261 /*
1262  * Validate the freemap, in three stages.
1263  *
1264  * stage-1	ALLOCATED     -> POSSIBLY FREE
1265  *		POSSIBLY FREE -> POSSIBLY FREE (type corrected)
1266  *
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.
1270  *
1271  *	This is typically done during normal filesystem operations when
1272  *	something is deleted or a block is replaced.
1273  *
1274  *	This is done by bulkfree in-bulk after a memory-bounded meta-data
1275  *	scan to try to determine what might be freeable.
1276  *
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.
1279  *
1280  * stage-2	POSSIBLY FREE -> ALLOCATED	(scan metadata topology)
1281  *
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
1284  *	as such.
1285  *
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
1290  *	      blocks to FREE.
1291  *
1292  * stage-3	POSSIBLY FREE (type 1) -> FREE	(scan freemap)
1293  *
1294  *	This is done by bulkfree to finalize POSSIBLY FREE states.
1295  *
1296  */
1297