xref: /dragonfly/sys/vfs/hammer2/hammer2_freemap.c (revision 40657594)
1 /*
2  * Copyright (c) 2011-2018 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 /*
72  * Calculate the device offset for the specified FREEMAP_NODE or FREEMAP_LEAF
73  * bref.  Return a combined media offset and physical size radix.  Freemap
74  * chains use fixed storage offsets in the 4MB reserved area at the
75  * beginning of each 2GB zone
76  *
77  * Rotate between four possibilities.  Theoretically this means we have three
78  * good freemaps in case of a crash which we can use as a base for the fixup
79  * scan at mount-time.
80  */
81 static
82 int
83 hammer2_freemap_reserve(hammer2_chain_t *chain, int radix)
84 {
85 	hammer2_blockref_t *bref = &chain->bref;
86 	hammer2_off_t off;
87 	int index;
88 	int index_inc;
89 	size_t bytes;
90 
91 	/*
92 	 * Physical allocation size.
93 	 */
94 	bytes = (size_t)1 << radix;
95 
96 	/*
97 	 * Calculate block selection index 0..7 of current block.  If this
98 	 * is the first allocation of the block (verses a modification of an
99 	 * existing block), we use index 0, otherwise we use the next rotating
100 	 * index.
101 	 */
102 	if ((bref->data_off & ~HAMMER2_OFF_MASK_RADIX) == 0) {
103 		index = 0;
104 	} else {
105 		off = bref->data_off & ~HAMMER2_OFF_MASK_RADIX &
106 		      HAMMER2_SEGMASK;
107 		off = off / HAMMER2_PBUFSIZE;
108 		KKASSERT(off >= HAMMER2_ZONE_FREEMAP_00 &&
109 			 off < HAMMER2_ZONE_FREEMAP_END);
110 		index = (int)(off - HAMMER2_ZONE_FREEMAP_00) /
111 			HAMMER2_ZONE_FREEMAP_INC;
112 		KKASSERT(index >= 0 && index < HAMMER2_NFREEMAPS);
113 		if (++index == HAMMER2_NFREEMAPS)
114 			index = 0;
115 	}
116 
117 	/*
118 	 * Calculate the block offset of the reserved block.  This will
119 	 * point into the 4MB reserved area at the base of the appropriate
120 	 * 2GB zone, once added to the FREEMAP_x selection above.
121 	 */
122 	index_inc = index * HAMMER2_ZONE_FREEMAP_INC;
123 
124 	switch(bref->keybits) {
125 	/* case HAMMER2_FREEMAP_LEVEL6_RADIX: not applicable */
126 	case HAMMER2_FREEMAP_LEVEL5_RADIX:	/* 4EB */
127 		KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
128 		KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
129 		off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL5_RADIX) +
130 		      (index_inc + HAMMER2_ZONE_FREEMAP_00 +
131 		       HAMMER2_ZONEFM_LEVEL5) * HAMMER2_PBUFSIZE;
132 		break;
133 	case HAMMER2_FREEMAP_LEVEL4_RADIX:	/* 16PB */
134 		KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
135 		KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
136 		off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL4_RADIX) +
137 		      (index_inc + HAMMER2_ZONE_FREEMAP_00 +
138 		       HAMMER2_ZONEFM_LEVEL4) * HAMMER2_PBUFSIZE;
139 		break;
140 	case HAMMER2_FREEMAP_LEVEL3_RADIX:	/* 64TB */
141 		KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
142 		KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
143 		off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL3_RADIX) +
144 		      (index_inc + HAMMER2_ZONE_FREEMAP_00 +
145 		       HAMMER2_ZONEFM_LEVEL3) * HAMMER2_PBUFSIZE;
146 		break;
147 	case HAMMER2_FREEMAP_LEVEL2_RADIX:	/* 256GB */
148 		KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
149 		KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
150 		off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL2_RADIX) +
151 		      (index_inc + HAMMER2_ZONE_FREEMAP_00 +
152 		       HAMMER2_ZONEFM_LEVEL2) * HAMMER2_PBUFSIZE;
153 		break;
154 	case HAMMER2_FREEMAP_LEVEL1_RADIX:	/* 1GB */
155 		KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
156 		KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
157 		off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
158 		      (index_inc + HAMMER2_ZONE_FREEMAP_00 +
159 		       HAMMER2_ZONEFM_LEVEL1) * HAMMER2_PBUFSIZE;
160 		break;
161 	default:
162 		panic("freemap: bad radix(2) %p %d\n", bref, bref->keybits);
163 		/* NOT REACHED */
164 		off = (hammer2_off_t)-1;
165 		break;
166 	}
167 	bref->data_off = off | radix;
168 #if FREEMAP_DEBUG
169 	kprintf("FREEMAP BLOCK TYPE %d %016jx/%d DATA_OFF=%016jx\n",
170 		bref->type, bref->key, bref->keybits, bref->data_off);
171 #endif
172 	return (0);
173 }
174 
175 /*
176  * Normal freemap allocator
177  *
178  * Use available hints to allocate space using the freemap.  Create missing
179  * freemap infrastructure on-the-fly as needed (including marking initial
180  * allocations using the iterator as allocated, instantiating new 2GB zones,
181  * and dealing with the end-of-media edge case).
182  *
183  * ip and bpref are only used as a heuristic to determine locality of
184  * reference.  bref->key may also be used heuristically.
185  *
186  * This function is a NOP if bytes is 0.
187  */
188 int
189 hammer2_freemap_alloc(hammer2_chain_t *chain, size_t bytes)
190 {
191 	hammer2_dev_t *hmp = chain->hmp;
192 	hammer2_blockref_t *bref = &chain->bref;
193 	hammer2_chain_t *parent;
194 	hammer2_tid_t mtid;
195 	int radix;
196 	int error;
197 	unsigned int hindex;
198 	hammer2_fiterate_t iter;
199 
200 	/*
201 	 * If allocating or downsizing to zero we just get rid of whatever
202 	 * data_off we had.
203 	 */
204 	if (bytes == 0) {
205 		chain->bref.data_off = 0;
206 		return 0;
207 	}
208 
209 	KKASSERT(hmp->spmp);
210 	mtid = hammer2_trans_sub(hmp->spmp);
211 
212 	/*
213 	 * Validate the allocation size.  It must be a power of 2.
214 	 *
215 	 * For now require that the caller be aware of the minimum
216 	 * allocation (1K).
217 	 */
218 	radix = hammer2_getradix(bytes);
219 	KKASSERT((size_t)1 << radix == bytes);
220 
221 	if (bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
222 	    bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
223 		/*
224 		 * Freemap blocks themselves are assigned from the reserve
225 		 * area, not allocated from the freemap.
226 		 */
227 		error = hammer2_freemap_reserve(chain, radix);
228 
229 		return error;
230 	}
231 
232 	KKASSERT(bytes >= HAMMER2_ALLOC_MIN && bytes <= HAMMER2_ALLOC_MAX);
233 
234 	/*
235 	 * Calculate the starting point for our allocation search.
236 	 *
237 	 * Each freemap leaf is dedicated to a specific freemap_radix.
238 	 * The freemap_radix can be more fine-grained than the device buffer
239 	 * radix which results in inodes being grouped together in their
240 	 * own segment, terminal-data (16K or less) and initial indirect
241 	 * block being grouped together, and then full-indirect and full-data
242 	 * blocks (64K) being grouped together.
243 	 *
244 	 * The single most important aspect of this is the inode grouping
245 	 * because that is what allows 'find' and 'ls' and other filesystem
246 	 * topology operations to run fast.
247 	 */
248 #if 0
249 	if (bref->data_off & ~HAMMER2_OFF_MASK_RADIX)
250 		bpref = bref->data_off & ~HAMMER2_OFF_MASK_RADIX;
251 	else if (trans->tmp_bpref)
252 		bpref = trans->tmp_bpref;
253 	else if (trans->tmp_ip)
254 		bpref = trans->tmp_ip->chain->bref.data_off;
255 	else
256 #endif
257 	/*
258 	 * Heuristic tracking index.  We would like one for each distinct
259 	 * bref type if possible.  heur_freemap[] has room for two classes
260 	 * for each type.  At a minimum we have to break-up our heuristic
261 	 * by device block sizes.
262 	 */
263 	hindex = hammer2_devblkradix(radix) - HAMMER2_MINIORADIX;
264 	KKASSERT(hindex < HAMMER2_FREEMAP_HEUR_NRADIX);
265 	hindex += bref->type * HAMMER2_FREEMAP_HEUR_NRADIX;
266 	hindex &= HAMMER2_FREEMAP_HEUR_TYPES * HAMMER2_FREEMAP_HEUR_NRADIX - 1;
267 	KKASSERT(hindex < HAMMER2_FREEMAP_HEUR_SIZE);
268 
269 	iter.bpref = hmp->heur_freemap[hindex];
270 	iter.relaxed = hmp->freemap_relaxed;
271 
272 	/*
273 	 * Make sure bpref is in-bounds.  It's ok if bpref covers a zone's
274 	 * reserved area, the try code will iterate past it.
275 	 */
276 	if (iter.bpref > hmp->voldata.volu_size)
277 		iter.bpref = hmp->voldata.volu_size - 1;
278 
279 	/*
280 	 * Iterate the freemap looking for free space before and after.
281 	 */
282 	parent = &hmp->fchain;
283 	hammer2_chain_ref(parent);
284 	hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
285 	error = HAMMER2_ERROR_EAGAIN;
286 	iter.bnext = iter.bpref;
287 	iter.loops = 0;
288 
289 	while (error == HAMMER2_ERROR_EAGAIN) {
290 		error = hammer2_freemap_try_alloc(&parent, bref, radix,
291 						  &iter, mtid);
292 	}
293 	hmp->freemap_relaxed |= iter.relaxed;	/* heuristical, SMP race ok */
294 	hmp->heur_freemap[hindex] = iter.bnext;
295 	hammer2_chain_unlock(parent);
296 	hammer2_chain_drop(parent);
297 
298 	return (error);
299 }
300 
301 static int
302 hammer2_freemap_try_alloc(hammer2_chain_t **parentp,
303 			  hammer2_blockref_t *bref, int radix,
304 			  hammer2_fiterate_t *iter, hammer2_tid_t mtid)
305 {
306 	hammer2_dev_t *hmp = (*parentp)->hmp;
307 	hammer2_off_t l0size;
308 	hammer2_off_t l1size;
309 	hammer2_off_t l1mask;
310 	hammer2_key_t key_dummy;
311 	hammer2_chain_t *chain;
312 	hammer2_off_t key;
313 	size_t bytes;
314 	uint16_t class;
315 	int error;
316 
317 	/*
318 	 * Calculate the number of bytes being allocated, the number
319 	 * of contiguous bits of bitmap being allocated, and the bitmap
320 	 * mask.
321 	 *
322 	 * WARNING! cpu hardware may mask bits == 64 -> 0 and blow up the
323 	 *	    mask calculation.
324 	 */
325 	bytes = (size_t)1 << radix;
326 	class = (bref->type << 8) | hammer2_devblkradix(radix);
327 
328 	/*
329 	 * Lookup the level1 freemap chain, creating and initializing one
330 	 * if necessary.  Intermediate levels will be created automatically
331 	 * when necessary by hammer2_chain_create().
332 	 */
333 	key = H2FMBASE(iter->bnext, HAMMER2_FREEMAP_LEVEL1_RADIX);
334 	l0size = HAMMER2_FREEMAP_LEVEL0_SIZE;
335 	l1size = HAMMER2_FREEMAP_LEVEL1_SIZE;
336 	l1mask = l1size - 1;
337 
338 	chain = hammer2_chain_lookup(parentp, &key_dummy, key, key + l1mask,
339 				     &error,
340 				     HAMMER2_LOOKUP_ALWAYS |
341 				     HAMMER2_LOOKUP_MATCHIND);
342 
343 	if (chain == NULL) {
344 		/*
345 		 * Create the missing leaf, be sure to initialize
346 		 * the auxillary freemap tracking information in
347 		 * the bref.check.freemap structure.
348 		 */
349 #if 0
350 		kprintf("freemap create L1 @ %016jx bpref %016jx\n",
351 			key, iter->bpref);
352 #endif
353 		error = hammer2_chain_create(parentp, &chain, NULL, hmp->spmp,
354 				     HAMMER2_METH_DEFAULT,
355 				     key, HAMMER2_FREEMAP_LEVEL1_RADIX,
356 				     HAMMER2_BREF_TYPE_FREEMAP_LEAF,
357 				     HAMMER2_FREEMAP_LEVELN_PSIZE,
358 				     mtid, 0, 0);
359 		KKASSERT(error == 0);
360 		if (error == 0) {
361 			hammer2_chain_modify(chain, mtid, 0, 0);
362 			bzero(&chain->data->bmdata[0],
363 			      HAMMER2_FREEMAP_LEVELN_PSIZE);
364 			chain->bref.check.freemap.bigmask = (uint32_t)-1;
365 			chain->bref.check.freemap.avail = l1size;
366 			/* bref.methods should already be inherited */
367 
368 			hammer2_freemap_init(hmp, key, chain);
369 		}
370 	} else if (chain->error) {
371 		/*
372 		 * Error during lookup.
373 		 */
374 		kprintf("hammer2_freemap_try_alloc: %016jx: error %s\n",
375 			(intmax_t)bref->data_off,
376 			hammer2_error_str(chain->error));
377 		error = HAMMER2_ERROR_EIO;
378 	} else if ((chain->bref.check.freemap.bigmask &
379 		   ((size_t)1 << radix)) == 0) {
380 		/*
381 		 * Already flagged as not having enough space
382 		 */
383 		error = HAMMER2_ERROR_ENOSPC;
384 	} else {
385 		/*
386 		 * Modify existing chain to setup for adjustment.
387 		 */
388 		hammer2_chain_modify(chain, mtid, 0, 0);
389 	}
390 
391 	/*
392 	 * Scan 4MB entries.
393 	 */
394 	if (error == 0) {
395 		hammer2_bmap_data_t *bmap;
396 		hammer2_key_t base_key;
397 		int count;
398 		int start;
399 		int n;
400 
401 		KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
402 		start = (int)((iter->bnext - key) >>
403 			      HAMMER2_FREEMAP_LEVEL0_RADIX);
404 		KKASSERT(start >= 0 && start < HAMMER2_FREEMAP_COUNT);
405 		hammer2_chain_modify(chain, mtid, 0, 0);
406 
407 		error = HAMMER2_ERROR_ENOSPC;
408 		for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
409 			int availchk;
410 
411 			if (start + count >= HAMMER2_FREEMAP_COUNT &&
412 			    start - count < 0) {
413 				break;
414 			}
415 
416 			/*
417 			 * Calculate bmap pointer from thart starting index
418 			 * forwards.
419 			 *
420 			 * NOTE: bmap pointer is invalid if n >= FREEMAP_COUNT.
421 			 */
422 			n = start + count;
423 			bmap = &chain->data->bmdata[n];
424 
425 			if (n >= HAMMER2_FREEMAP_COUNT) {
426 				availchk = 0;
427 			} else if (bmap->avail) {
428 				availchk = 1;
429 			} else if (radix < HAMMER2_FREEMAP_BLOCK_RADIX &&
430 			          (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK)) {
431 				availchk = 1;
432 			} else {
433 				availchk = 0;
434 			}
435 
436 			/*
437 			 * Try to allocate from a matching freemap class
438 			 * superblock.  If we are in relaxed mode we allocate
439 			 * from any freemap class superblock.
440 			 */
441 			if (availchk &&
442 			    (bmap->class == 0 || bmap->class == class ||
443 			     iter->relaxed)) {
444 				base_key = key + n * l0size;
445 				error = hammer2_bmap_alloc(hmp, bmap,
446 							   class, n,
447 							   (int)bref->key,
448 							   radix,
449 							   &base_key);
450 				if (error != HAMMER2_ERROR_ENOSPC) {
451 					key = base_key;
452 					break;
453 				}
454 			}
455 
456 			/*
457 			 * Calculate bmap pointer from thart starting index
458 			 * backwards (locality).
459 			 *
460 			 * Must recalculate after potentially having called
461 			 * hammer2_bmap_alloc() above in case chain was
462 			 * reallocated.
463 			 *
464 			 * NOTE: bmap pointer is invalid if n < 0.
465 			 */
466 			n = start - count;
467 			bmap = &chain->data->bmdata[n];
468 			if (n < 0) {
469 				availchk = 0;
470 			} else if (bmap->avail) {
471 				availchk = 1;
472 			} else if (radix < HAMMER2_FREEMAP_BLOCK_RADIX &&
473 			          (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK)) {
474 				availchk = 1;
475 			} else {
476 				availchk = 0;
477 			}
478 
479 			/*
480 			 * Try to allocate from a matching freemap class
481 			 * superblock.  If we are in relaxed mode we allocate
482 			 * from any freemap class superblock.
483 			 */
484 			if (availchk &&
485 			    (bmap->class == 0 || bmap->class == class ||
486 			    iter->relaxed)) {
487 				base_key = key + n * l0size;
488 				error = hammer2_bmap_alloc(hmp, bmap,
489 							   class, n,
490 							   (int)bref->key,
491 							   radix,
492 							   &base_key);
493 				if (error != HAMMER2_ERROR_ENOSPC) {
494 					key = base_key;
495 					break;
496 				}
497 			}
498 		}
499 
500 		/*
501 		 * We only know for sure that we can clear the bitmap bit
502 		 * if we scanned the entire array (start == 0).
503 		 */
504 		if (error == HAMMER2_ERROR_ENOSPC && start == 0) {
505 			chain->bref.check.freemap.bigmask &=
506 				(uint32_t)~((size_t)1 << radix);
507 		}
508 		/* XXX also scan down from original count */
509 	}
510 
511 	if (error == 0) {
512 		/*
513 		 * Assert validity.  Must be beyond the static allocator used
514 		 * by newfs_hammer2 (and thus also beyond the aux area),
515 		 * not go past the volume size, and must not be in the
516 		 * reserved segment area for a zone.
517 		 */
518 		KKASSERT(key >= hmp->voldata.allocator_beg &&
519 			 key + bytes <= hmp->voldata.volu_size);
520 		KKASSERT((key & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
521 		bref->data_off = key | radix;
522 
523 		/*
524 		 * Record dedupability.  The dedup bits are cleared
525 		 * when bulkfree transitions the freemap from 11->10,
526 		 * and asserted to be clear on the 10->00 transition.
527 		 *
528 		 * We must record the bitmask with the chain locked
529 		 * at the time we set the allocation bits to avoid
530 		 * racing a bulkfree.
531 		 */
532 		if (bref->type == HAMMER2_BREF_TYPE_DATA)
533 			hammer2_io_dedup_set(hmp, bref);
534 #if 0
535 		kprintf("alloc cp=%p %016jx %016jx using %016jx\n",
536 			chain,
537 			bref->key, bref->data_off, chain->bref.data_off);
538 #endif
539 	} else if (error == HAMMER2_ERROR_ENOSPC) {
540 		/*
541 		 * Return EAGAIN with next iteration in iter->bnext, or
542 		 * return ENOSPC if the allocation map has been exhausted.
543 		 */
544 		error = hammer2_freemap_iterate(parentp, &chain, iter);
545 	}
546 
547 	/*
548 	 * Cleanup
549 	 */
550 	if (chain) {
551 		hammer2_chain_unlock(chain);
552 		hammer2_chain_drop(chain);
553 	}
554 	return (error);
555 }
556 
557 /*
558  * Allocate (1<<radix) bytes from the bmap whos base data offset is (*basep).
559  *
560  * If the linear iterator is mid-block we use it directly (the bitmap should
561  * already be marked allocated), otherwise we search for a block in the
562  * bitmap that fits the allocation request.
563  *
564  * A partial bitmap allocation sets the minimum bitmap granularity (16KB)
565  * to fully allocated and adjusts the linear allocator to allow the
566  * remaining space to be allocated.
567  *
568  * sub_key is the lower 32 bits of the chain->bref.key for the chain whos
569  * bref is being allocated.  If the radix represents an allocation >= 16KB
570  * (aka HAMMER2_FREEMAP_BLOCK_RADIX) we try to use this key to select the
571  * blocks directly out of the bmap.
572  */
573 static
574 int
575 hammer2_bmap_alloc(hammer2_dev_t *hmp, hammer2_bmap_data_t *bmap,
576 		   uint16_t class, int n, int sub_key,
577 		   int radix, hammer2_key_t *basep)
578 {
579 	size_t size;
580 	size_t bgsize;
581 	int bmradix;
582 	hammer2_bitmap_t bmmask;
583 	int offset;
584 	int i;
585 	int j;
586 
587 	/*
588 	 * Take into account 2-bits per block when calculating bmradix.
589 	 */
590 	size = (size_t)1 << radix;
591 
592 	if (radix <= HAMMER2_FREEMAP_BLOCK_RADIX) {
593 		bmradix = 2;
594 		/* (16K) 2 bits per allocation block */
595 	} else {
596 		bmradix = (hammer2_bitmap_t)2 <<
597 			  (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
598 		/* (32K-256K) 4, 8, 16, 32 bits per allocation block */
599 	}
600 
601 	/*
602 	 * Use the linear iterator to pack small allocations, otherwise
603 	 * fall-back to finding a free 16KB chunk.  The linear iterator
604 	 * is only valid when *NOT* on a freemap chunking boundary (16KB).
605 	 * If it is the bitmap must be scanned.  It can become invalid
606 	 * once we pack to the boundary.  We adjust it after a bitmap
607 	 * allocation only for sub-16KB allocations (so the perfectly good
608 	 * previous value can still be used for fragments when 16KB+
609 	 * allocations are made inbetween fragmentary allocations).
610 	 *
611 	 * Beware of hardware artifacts when bmradix == 64 (intermediate
612 	 * result can wind up being '1' instead of '0' if hardware masks
613 	 * bit-count & 63).
614 	 *
615 	 * NOTE: j needs to be even in the j= calculation.  As an artifact
616 	 *	 of the /2 division, our bitmask has to clear bit 0.
617 	 *
618 	 * NOTE: TODO this can leave little unallocatable fragments lying
619 	 *	 around.
620 	 */
621 	if (((uint32_t)bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) + size <=
622 	    HAMMER2_FREEMAP_BLOCK_SIZE &&
623 	    (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) &&
624 	    bmap->linear < HAMMER2_SEGSIZE) {
625 		/*
626 		 * Use linear iterator if it is not block-aligned to avoid
627 		 * wasting space.
628 		 *
629 		 * Calculate the bitmapq[] index (i) and calculate the
630 		 * shift count within the 64-bit bitmapq[] entry.
631 		 *
632 		 * The freemap block size is 16KB, but each bitmap
633 		 * entry is two bits so use a little trick to get
634 		 * a (j) shift of 0, 2, 4, ... 62 in 16KB chunks.
635 		 */
636 		KKASSERT(bmap->linear >= 0 &&
637 			 bmap->linear + size <= HAMMER2_SEGSIZE &&
638 			 (bmap->linear & (HAMMER2_ALLOC_MIN - 1)) == 0);
639 		offset = bmap->linear;
640 		i = offset / (HAMMER2_SEGSIZE / HAMMER2_BMAP_ELEMENTS);
641 		j = (offset / (HAMMER2_FREEMAP_BLOCK_SIZE / 2)) & 62;
642 		bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
643 			 HAMMER2_BMAP_ALLONES :
644 			 ((hammer2_bitmap_t)1 << bmradix) - 1;
645 		bmmask <<= j;
646 		bmap->linear = offset + size;
647 	} else {
648 		/*
649 		 * Try to index a starting point based on sub_key.  This
650 		 * attempts to restore sequential block ordering on-disk
651 		 * whenever possible, even if data is committed out of
652 		 * order.
653 		 *
654 		 * i - Index bitmapq[], full data range represented is
655 		 *     HAMMER2_BMAP_SIZE.
656 		 *
657 		 * j - Index within bitmapq[i], full data range represented is
658 		 *     HAMMER2_BMAP_INDEX_SIZE.
659 		 *
660 		 * WARNING!
661 		 */
662 		i = -1;
663 		j = -1;
664 
665 		switch(class >> 8) {
666 		case HAMMER2_BREF_TYPE_DATA:
667 			if (radix >= HAMMER2_FREEMAP_BLOCK_RADIX) {
668 				i = (sub_key & HAMMER2_BMAP_MASK) /
669 				    (HAMMER2_BMAP_SIZE / HAMMER2_BMAP_ELEMENTS);
670 				j = (sub_key & HAMMER2_BMAP_INDEX_MASK) /
671 				    (HAMMER2_BMAP_INDEX_SIZE /
672 				     HAMMER2_BMAP_BLOCKS_PER_ELEMENT);
673 				j = j * 2;
674 			}
675 			break;
676 		case HAMMER2_BREF_TYPE_INODE:
677 			break;
678 		default:
679 			break;
680 		}
681 		if (i >= 0) {
682 			KKASSERT(i < HAMMER2_BMAP_ELEMENTS &&
683 				 j < 2 * HAMMER2_BMAP_BLOCKS_PER_ELEMENT);
684 			KKASSERT(j + bmradix <= HAMMER2_BMAP_BITS_PER_ELEMENT);
685 			bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
686 				 HAMMER2_BMAP_ALLONES :
687 				 ((hammer2_bitmap_t)1 << bmradix) - 1;
688 			bmmask <<= j;
689 
690 			if ((bmap->bitmapq[i] & bmmask) == 0)
691 				goto success;
692 		}
693 
694 		/*
695 		 * General element scan.
696 		 *
697 		 * WARNING: (j) is iterating a bit index (by 2's)
698 		 */
699 		for (i = 0; i < HAMMER2_BMAP_ELEMENTS; ++i) {
700 			bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
701 				 HAMMER2_BMAP_ALLONES :
702 				 ((hammer2_bitmap_t)1 << bmradix) - 1;
703 			for (j = 0;
704 			     j < HAMMER2_BMAP_BITS_PER_ELEMENT;
705 			     j += bmradix) {
706 				if ((bmap->bitmapq[i] & bmmask) == 0)
707 					goto success;
708 				bmmask <<= bmradix;
709 			}
710 		}
711 		/*fragments might remain*/
712 		/*KKASSERT(bmap->avail == 0);*/
713 		return (HAMMER2_ERROR_ENOSPC);
714 success:
715 		offset = i * (HAMMER2_SEGSIZE / HAMMER2_BMAP_ELEMENTS) +
716 			 (j * (HAMMER2_FREEMAP_BLOCK_SIZE / 2));
717 		if (size & HAMMER2_FREEMAP_BLOCK_MASK)
718 			bmap->linear = offset + size;
719 	}
720 
721 	/* 8 x (64/2) -> 256 x 16K -> 4MB */
722 	KKASSERT(i >= 0 && i < HAMMER2_BMAP_ELEMENTS);
723 
724 	/*
725 	 * Optimize the buffer cache to avoid unnecessary read-before-write
726 	 * operations.
727 	 *
728 	 * The device block size could be larger than the allocation size
729 	 * so the actual bitmap test is somewhat more involved.  We have
730 	 * to use a compatible buffer size for this operation.
731 	 */
732 	if ((bmap->bitmapq[i] & bmmask) == 0 &&
733 	    hammer2_devblksize(size) != size) {
734 		size_t psize = hammer2_devblksize(size);
735 		hammer2_off_t pmask = (hammer2_off_t)psize - 1;
736 		int pbmradix = (hammer2_bitmap_t)2 <<
737 					(hammer2_devblkradix(radix) -
738 			       HAMMER2_FREEMAP_BLOCK_RADIX);
739 		hammer2_bitmap_t pbmmask;
740 		int pradix = hammer2_getradix(psize);
741 
742 		pbmmask = (pbmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
743 			HAMMER2_BMAP_ALLONES :
744 			((hammer2_bitmap_t)1 << pbmradix) - 1;
745 		while ((pbmmask & bmmask) == 0)
746 			pbmmask <<= pbmradix;
747 
748 #if 0
749 		kprintf("%016jx mask %016jx %016jx %016jx (%zd/%zd)\n",
750 			*basep + offset, bmap->bitmapq[i],
751 			pbmmask, bmmask, size, psize);
752 #endif
753 
754 		if ((bmap->bitmapq[i] & pbmmask) == 0) {
755 			hammer2_io_t *dio;
756 
757 			hammer2_io_newnz(hmp, class >> 8,
758 					(*basep + (offset & ~pmask)) |
759 					pradix, psize, &dio);
760 			hammer2_io_putblk(&dio);
761 		}
762 	}
763 
764 #if 0
765 	/*
766 	 * When initializing a new inode segment also attempt to initialize
767 	 * an adjacent segment.  Be careful not to index beyond the array
768 	 * bounds.
769 	 *
770 	 * We do this to try to localize inode accesses to improve
771 	 * directory scan rates.  XXX doesn't improve scan rates.
772 	 */
773 	if (size == HAMMER2_INODE_BYTES) {
774 		if (n & 1) {
775 			if (bmap[-1].radix == 0 && bmap[-1].avail)
776 				bmap[-1].radix = radix;
777 		} else {
778 			if (bmap[1].radix == 0 && bmap[1].avail)
779 				bmap[1].radix = radix;
780 		}
781 	}
782 #endif
783 	/*
784 	 * Calculate the bitmap-granular change in bgsize for the volume
785 	 * header.  We cannot use the fine-grained change here because
786 	 * the bulkfree code can't undo it.  If the bitmap element is already
787 	 * marked allocated it has already been accounted for.
788 	 */
789 	if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
790 		if (bmap->bitmapq[i] & bmmask)
791 			bgsize = 0;
792 		else
793 			bgsize = HAMMER2_FREEMAP_BLOCK_SIZE;
794 	} else {
795 		bgsize = size;
796 	}
797 
798 	/*
799 	 * Adjust the bitmap, set the class (it might have been 0),
800 	 * and available bytes, update the allocation offset (*basep)
801 	 * from the L0 base to the actual offset.
802 	 *
803 	 * Do not override the class if doing a relaxed class allocation.
804 	 *
805 	 * avail must reflect the bitmap-granular availability.  The allocator
806 	 * tests will also check the linear iterator.
807 	 */
808 	bmap->bitmapq[i] |= bmmask;
809 	if (bmap->class == 0)
810 		bmap->class = class;
811 	bmap->avail -= bgsize;
812 	*basep += offset;
813 
814 	/*
815 	 * Adjust the volume header's allocator_free parameter.  This
816 	 * parameter has to be fixed up by bulkfree which has no way to
817 	 * figure out sub-16K chunking, so it must be adjusted by the
818 	 * bitmap-granular size.
819 	 */
820 	if (bgsize) {
821 		hammer2_voldata_lock(hmp);
822 		hammer2_voldata_modify(hmp);
823 		hmp->voldata.allocator_free -= bgsize;
824 		hammer2_voldata_unlock(hmp);
825 	}
826 
827 	return(0);
828 }
829 
830 /*
831  * Initialize a freemap for the storage area (in bytes) that begins at (key).
832  */
833 static
834 void
835 hammer2_freemap_init(hammer2_dev_t *hmp, hammer2_key_t key,
836 		     hammer2_chain_t *chain)
837 {
838 	hammer2_off_t l1size;
839 	hammer2_off_t lokey;
840 	hammer2_off_t hikey;
841 	hammer2_bmap_data_t *bmap;
842 	int count;
843 
844 	/*
845 	 * LEVEL1 is 1GB, there are two level1 1GB freemaps per 2GB zone.
846 	 */
847 	l1size = HAMMER2_FREEMAP_LEVEL1_SIZE;
848 
849 	/*
850 	 * Calculate the portion of the 1GB map that should be initialized
851 	 * as free.  Portions below or after will be initialized as allocated.
852 	 * SEGMASK-align the areas so we don't have to worry about sub-scans
853 	 * or endianess when using memset.
854 	 *
855 	 * WARNING! It is possible for lokey to be larger than hikey if the
856 	 *	    entire 2GB segment is within the static allocation.
857 	 */
858 	/*
859 	 * (1) Ensure that all statically allocated space from newfs_hammer2
860 	 *     is marked allocated, and take it up to the level1 base for
861 	 *     this key.
862 	 */
863 	lokey = (hmp->voldata.allocator_beg + HAMMER2_SEGMASK64) &
864 		~HAMMER2_SEGMASK64;
865 	if (lokey < H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX))
866 		lokey = H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX);
867 
868 	/*
869 	 * (2) Ensure that the reserved area is marked allocated (typically
870 	 *     the first 4MB of each 2GB area being represented).  Since
871 	 *     each LEAF represents 1GB of storage and the zone is 2GB, we
872 	 *     have to adjust lowkey upward every other LEAF sequentially.
873 	 */
874 	if (lokey < H2FMZONEBASE(key) + HAMMER2_ZONE_SEG64)
875 		lokey = H2FMZONEBASE(key) + HAMMER2_ZONE_SEG64;
876 
877 	/*
878 	 * (3) Ensure that any trailing space at the end-of-volume is marked
879 	 *     allocated.
880 	 */
881 	hikey = key + HAMMER2_FREEMAP_LEVEL1_SIZE;
882 	if (hikey > hmp->voldata.volu_size) {
883 		hikey = hmp->voldata.volu_size & ~HAMMER2_SEGMASK64;
884 	}
885 
886 	/*
887 	 * Heuristic highest possible value
888 	 */
889 	chain->bref.check.freemap.avail = HAMMER2_FREEMAP_LEVEL1_SIZE;
890 	bmap = &chain->data->bmdata[0];
891 
892 	/*
893 	 * Initialize bitmap (bzero'd by caller)
894 	 */
895 	for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
896 		if (key < lokey || key >= hikey) {
897 			memset(bmap->bitmapq, -1,
898 			       sizeof(bmap->bitmapq));
899 			bmap->avail = 0;
900 			bmap->linear = HAMMER2_SEGSIZE;
901 			chain->bref.check.freemap.avail -=
902 				HAMMER2_FREEMAP_LEVEL0_SIZE;
903 		} else {
904 			bmap->avail = HAMMER2_FREEMAP_LEVEL0_SIZE;
905 		}
906 		key += HAMMER2_FREEMAP_LEVEL0_SIZE;
907 		++bmap;
908 	}
909 }
910 
911 /*
912  * The current Level 1 freemap has been exhausted, iterate to the next
913  * one, return ENOSPC if no freemaps remain.
914  *
915  * At least two loops are required.  If we are not in relaxed mode and
916  * we run out of storage we enter relaxed mode and do a third loop.
917  * The relaxed mode is recorded back in the hmp so once we enter the mode
918  * we remain relaxed until stuff begins to get freed and only do 2 loops.
919  *
920  * XXX this should rotate back to the beginning to handle freed-up space
921  * XXX or use intermediate entries to locate free space. TODO
922  */
923 static int
924 hammer2_freemap_iterate(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
925 			hammer2_fiterate_t *iter)
926 {
927 	hammer2_dev_t *hmp = (*parentp)->hmp;
928 
929 	iter->bnext &= ~HAMMER2_FREEMAP_LEVEL1_MASK;
930 	iter->bnext += HAMMER2_FREEMAP_LEVEL1_SIZE;
931 	if (iter->bnext >= hmp->voldata.volu_size) {
932 		iter->bnext = 0;
933 		if (++iter->loops >= 2) {
934 			if (iter->relaxed == 0)
935 				iter->relaxed = 1;
936 			else
937 				return (HAMMER2_ERROR_ENOSPC);
938 		}
939 	}
940 	return(HAMMER2_ERROR_EAGAIN);
941 }
942 
943 /*
944  * Adjust the bit-pattern for data in the freemap bitmap according to
945  * (how).  This code is called from on-mount recovery to fixup (mark
946  * as allocated) blocks whos freemap upates might not have been committed
947  * in the last crash and is used by the bulk freemap scan to stage frees.
948  *
949  * WARNING! Cannot be called with a empty-data bref (radix == 0).
950  *
951  * XXX currently disabled when how == 0 (the normal real-time case).  At
952  * the moment we depend on the bulk freescan to actually free blocks.  It
953  * will still call this routine with a non-zero how to stage possible frees
954  * and to do the actual free.
955  */
956 void
957 hammer2_freemap_adjust(hammer2_dev_t *hmp, hammer2_blockref_t *bref,
958 		       int how)
959 {
960 	hammer2_off_t data_off = bref->data_off;
961 	hammer2_chain_t *chain;
962 	hammer2_chain_t *parent;
963 	hammer2_bmap_data_t *bmap;
964 	hammer2_key_t key;
965 	hammer2_key_t key_dummy;
966 	hammer2_off_t l0size;
967 	hammer2_off_t l1size;
968 	hammer2_off_t l1mask;
969 	hammer2_tid_t mtid;
970 	hammer2_bitmap_t *bitmap;
971 	const hammer2_bitmap_t bmmask00 = 0;
972 	hammer2_bitmap_t bmmask01;
973 	hammer2_bitmap_t bmmask10;
974 	hammer2_bitmap_t bmmask11;
975 	size_t bytes;
976 	uint16_t class;
977 	int radix;
978 	int start;
979 	int count;
980 	int modified = 0;
981 	int error;
982 	size_t bgsize = 0;
983 
984 	KKASSERT(how == HAMMER2_FREEMAP_DORECOVER);
985 
986 	KKASSERT(hmp->spmp);
987 	mtid = hammer2_trans_sub(hmp->spmp);
988 
989 	radix = (int)data_off & HAMMER2_OFF_MASK_RADIX;
990 	KKASSERT(radix != 0);
991 	data_off &= ~HAMMER2_OFF_MASK_RADIX;
992 	KKASSERT(radix <= HAMMER2_RADIX_MAX);
993 
994 	if (radix)
995 		bytes = (size_t)1 << radix;
996 	else
997 		bytes = 0;
998 	class = (bref->type << 8) | hammer2_devblkradix(radix);
999 
1000 	/*
1001 	 * We can't adjust the freemap for data allocations made by
1002 	 * newfs_hammer2.
1003 	 */
1004 	if (data_off < hmp->voldata.allocator_beg)
1005 		return;
1006 
1007 	KKASSERT((data_off & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
1008 
1009 	/*
1010 	 * Lookup the level1 freemap chain.  The chain must exist.
1011 	 */
1012 	key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL1_RADIX);
1013 	l0size = HAMMER2_FREEMAP_LEVEL0_SIZE;
1014 	l1size = HAMMER2_FREEMAP_LEVEL1_SIZE;
1015 	l1mask = l1size - 1;
1016 
1017 	parent = &hmp->fchain;
1018 	hammer2_chain_ref(parent);
1019 	hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1020 
1021 	chain = hammer2_chain_lookup(&parent, &key_dummy, key, key + l1mask,
1022 				     &error,
1023 				     HAMMER2_LOOKUP_ALWAYS |
1024 				     HAMMER2_LOOKUP_MATCHIND);
1025 
1026 	/*
1027 	 * Stop early if we are trying to free something but no leaf exists.
1028 	 */
1029 	if (chain == NULL && how != HAMMER2_FREEMAP_DORECOVER) {
1030 		kprintf("hammer2_freemap_adjust: %016jx: no chain\n",
1031 			(intmax_t)bref->data_off);
1032 		goto done;
1033 	}
1034 	if (chain->error) {
1035 		kprintf("hammer2_freemap_adjust: %016jx: error %s\n",
1036 			(intmax_t)bref->data_off,
1037 			hammer2_error_str(chain->error));
1038 		hammer2_chain_unlock(chain);
1039 		hammer2_chain_drop(chain);
1040 		chain = NULL;
1041 		goto done;
1042 	}
1043 
1044 	/*
1045 	 * Create any missing leaf(s) if we are doing a recovery (marking
1046 	 * the block(s) as being allocated instead of being freed).  Be sure
1047 	 * to initialize the auxillary freemap tracking info in the
1048 	 * bref.check.freemap structure.
1049 	 */
1050 	if (chain == NULL && how == HAMMER2_FREEMAP_DORECOVER) {
1051 		error = hammer2_chain_create(&parent, &chain, NULL, hmp->spmp,
1052 				     HAMMER2_METH_DEFAULT,
1053 				     key, HAMMER2_FREEMAP_LEVEL1_RADIX,
1054 				     HAMMER2_BREF_TYPE_FREEMAP_LEAF,
1055 				     HAMMER2_FREEMAP_LEVELN_PSIZE,
1056 				     mtid, 0, 0);
1057 
1058 		if (hammer2_debug & 0x0040) {
1059 			kprintf("fixup create chain %p %016jx:%d\n",
1060 				chain, chain->bref.key, chain->bref.keybits);
1061 		}
1062 
1063 		if (error == 0) {
1064 			error = hammer2_chain_modify(chain, mtid, 0, 0);
1065 			KKASSERT(error == 0);
1066 			bzero(&chain->data->bmdata[0],
1067 			      HAMMER2_FREEMAP_LEVELN_PSIZE);
1068 			chain->bref.check.freemap.bigmask = (uint32_t)-1;
1069 			chain->bref.check.freemap.avail = l1size;
1070 			/* bref.methods should already be inherited */
1071 
1072 			hammer2_freemap_init(hmp, key, chain);
1073 		}
1074 		/* XXX handle error */
1075 	}
1076 
1077 #if FREEMAP_DEBUG
1078 	kprintf("FREEMAP ADJUST TYPE %d %016jx/%d DATA_OFF=%016jx\n",
1079 		chain->bref.type, chain->bref.key,
1080 		chain->bref.keybits, chain->bref.data_off);
1081 #endif
1082 
1083 	/*
1084 	 * Calculate the bitmask (runs in 2-bit pairs).
1085 	 */
1086 	start = ((int)(data_off >> HAMMER2_FREEMAP_BLOCK_RADIX) & 15) * 2;
1087 	bmmask01 = (hammer2_bitmap_t)1 << start;
1088 	bmmask10 = (hammer2_bitmap_t)2 << start;
1089 	bmmask11 = (hammer2_bitmap_t)3 << start;
1090 
1091 	/*
1092 	 * Fixup the bitmap.  Partial blocks cannot be fully freed unless
1093 	 * a bulk scan is able to roll them up.
1094 	 */
1095 	if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
1096 		count = 1;
1097 		if (how == HAMMER2_FREEMAP_DOREALFREE)
1098 			how = HAMMER2_FREEMAP_DOMAYFREE;
1099 	} else {
1100 		count = 1 << (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
1101 	}
1102 
1103 	/*
1104 	 * [re]load the bmap and bitmap pointers.  Each bmap entry covers
1105 	 * a 4MB swath.  The bmap itself (LEVEL1) covers 2GB.
1106 	 *
1107 	 * Be sure to reset the linear iterator to ensure that the adjustment
1108 	 * is not ignored.
1109 	 */
1110 again:
1111 	bmap = &chain->data->bmdata[(int)(data_off >> HAMMER2_SEGRADIX) &
1112 				    (HAMMER2_FREEMAP_COUNT - 1)];
1113 	bitmap = &bmap->bitmapq[(int)(data_off >> (HAMMER2_SEGRADIX - 3)) & 7];
1114 
1115 	if (modified)
1116 		bmap->linear = 0;
1117 
1118 	while (count) {
1119 		KKASSERT(bmmask11);
1120 		if (how == HAMMER2_FREEMAP_DORECOVER) {
1121 			/*
1122 			 * Recovery request, mark as allocated.
1123 			 */
1124 			if ((*bitmap & bmmask11) != bmmask11) {
1125 				if (modified == 0) {
1126 					hammer2_chain_modify(chain, mtid, 0, 0);
1127 					modified = 1;
1128 					goto again;
1129 				}
1130 				if ((*bitmap & bmmask11) == bmmask00) {
1131 					bmap->avail -=
1132 						HAMMER2_FREEMAP_BLOCK_SIZE;
1133 					bgsize += HAMMER2_FREEMAP_BLOCK_SIZE;
1134 				}
1135 				if (bmap->class == 0)
1136 					bmap->class = class;
1137 				*bitmap |= bmmask11;
1138 				if (hammer2_debug & 0x0040) {
1139 					kprintf("hammer2_freemap_recover: "
1140 						"fixup type=%02x "
1141 						"block=%016jx/%zd\n",
1142 						bref->type, data_off, bytes);
1143 				}
1144 			} else {
1145 				/*
1146 				kprintf("hammer2_freemap_recover:  good "
1147 					"type=%02x block=%016jx/%zd\n",
1148 					bref->type, data_off, bytes);
1149 				*/
1150 			}
1151 		}
1152 #if 0
1153 		/*
1154 		 * XXX this stuff doesn't work, avail is miscalculated and
1155 		 * code 10 means something else now.
1156 		 */
1157 		else if ((*bitmap & bmmask11) == bmmask11) {
1158 			/*
1159 			 * Mayfree/Realfree request and bitmap is currently
1160 			 * marked as being fully allocated.
1161 			 */
1162 			if (!modified) {
1163 				hammer2_chain_modify(chain, 0);
1164 				modified = 1;
1165 				goto again;
1166 			}
1167 			if (how == HAMMER2_FREEMAP_DOREALFREE)
1168 				*bitmap &= ~bmmask11;
1169 			else
1170 				*bitmap = (*bitmap & ~bmmask11) | bmmask10;
1171 		} else if ((*bitmap & bmmask11) == bmmask10) {
1172 			/*
1173 			 * Mayfree/Realfree request and bitmap is currently
1174 			 * marked as being possibly freeable.
1175 			 */
1176 			if (how == HAMMER2_FREEMAP_DOREALFREE) {
1177 				if (!modified) {
1178 					hammer2_chain_modify(chain, 0);
1179 					modified = 1;
1180 					goto again;
1181 				}
1182 				*bitmap &= ~bmmask11;
1183 			}
1184 		} else {
1185 			/*
1186 			 * 01 - Not implemented, currently illegal state
1187 			 * 00 - Not allocated at all, illegal free.
1188 			 */
1189 			panic("hammer2_freemap_adjust: "
1190 			      "Illegal state %08x(%08x)",
1191 			      *bitmap, *bitmap & bmmask11);
1192 		}
1193 #endif
1194 		--count;
1195 		bmmask01 <<= 2;
1196 		bmmask10 <<= 2;
1197 		bmmask11 <<= 2;
1198 	}
1199 #if HAMMER2_BMAP_ELEMENTS != 8
1200 #error "hammer2_freemap.c: HAMMER2_BMAP_ELEMENTS expected to be 8"
1201 #endif
1202 	if (how == HAMMER2_FREEMAP_DOREALFREE && modified) {
1203 		bmap->avail += 1 << radix;
1204 		KKASSERT(bmap->avail <= HAMMER2_SEGSIZE);
1205 		if (bmap->avail == HAMMER2_SEGSIZE &&
1206 		    bmap->bitmapq[0] == 0 &&
1207 		    bmap->bitmapq[1] == 0 &&
1208 		    bmap->bitmapq[2] == 0 &&
1209 		    bmap->bitmapq[3] == 0 &&
1210 		    bmap->bitmapq[4] == 0 &&
1211 		    bmap->bitmapq[5] == 0 &&
1212 		    bmap->bitmapq[6] == 0 &&
1213 		    bmap->bitmapq[7] == 0) {
1214 			key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL0_RADIX);
1215 			kprintf("Freeseg %016jx\n", (intmax_t)key);
1216 			bmap->class = 0;
1217 		}
1218 	}
1219 
1220 	/*
1221 	 * chain->bref.check.freemap.bigmask (XXX)
1222 	 *
1223 	 * Setting bigmask is a hint to the allocation code that there might
1224 	 * be something allocatable.  We also set this in recovery... it
1225 	 * doesn't hurt and we might want to use the hint for other validation
1226 	 * operations later on.
1227 	 *
1228 	 * We could calculate the largest possible allocation and set the
1229 	 * radii that could fit, but its easier just to set bigmask to -1.
1230 	 */
1231 	if (modified) {
1232 		chain->bref.check.freemap.bigmask = -1;
1233 		hmp->freemap_relaxed = 0;	/* reset heuristic */
1234 	}
1235 
1236 	hammer2_chain_unlock(chain);
1237 	hammer2_chain_drop(chain);
1238 done:
1239 	hammer2_chain_unlock(parent);
1240 	hammer2_chain_drop(parent);
1241 
1242 	if (bgsize) {
1243 		hammer2_voldata_lock(hmp);
1244 		hammer2_voldata_modify(hmp);
1245 		hmp->voldata.allocator_free -= bgsize;
1246 		hammer2_voldata_unlock(hmp);
1247 	}
1248 }
1249 
1250 /*
1251  * Validate the freemap, in three stages.
1252  *
1253  * stage-1	ALLOCATED     -> POSSIBLY FREE
1254  *		POSSIBLY FREE -> POSSIBLY FREE (type corrected)
1255  *
1256  *	This transitions bitmap entries from ALLOCATED to POSSIBLY FREE.
1257  *	The POSSIBLY FREE state does not mean that a block is actually free
1258  *	and may be transitioned back to ALLOCATED in stage-2.
1259  *
1260  *	This is typically done during normal filesystem operations when
1261  *	something is deleted or a block is replaced.
1262  *
1263  *	This is done by bulkfree in-bulk after a memory-bounded meta-data
1264  *	scan to try to determine what might be freeable.
1265  *
1266  *	This can be done unconditionally through a freemap scan when the
1267  *	intention is to brute-force recover the proper state of the freemap.
1268  *
1269  * stage-2	POSSIBLY FREE -> ALLOCATED	(scan metadata topology)
1270  *
1271  *	This is done by bulkfree during a meta-data scan to ensure that
1272  *	all blocks still actually allocated by the filesystem are marked
1273  *	as such.
1274  *
1275  *	NOTE! Live filesystem transitions to POSSIBLY FREE can occur while
1276  *	      the bulkfree stage-2 and stage-3 is running.  The live filesystem
1277  *	      will use the alternative POSSIBLY FREE type (2) to prevent
1278  *	      stage-3 from improperly transitioning unvetted possibly-free
1279  *	      blocks to FREE.
1280  *
1281  * stage-3	POSSIBLY FREE (type 1) -> FREE	(scan freemap)
1282  *
1283  *	This is done by bulkfree to finalize POSSIBLY FREE states.
1284  *
1285  */
1286