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