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