xref: /dragonfly/sys/vfs/hammer2/hammer2_freemap.c (revision 8e34d37e)
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 2GB zone
71  *
72  * Rotate between four possibilities.  Theoretically this means we have three
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 thart 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).
498 		 */
499 		if (error == HAMMER2_ERROR_ENOSPC && start == 0) {
500 			chain->bref.check.freemap.bigmask &=
501 				(uint32_t)~((size_t)1 << radix);
502 		}
503 		/* XXX also scan down from original count */
504 	}
505 
506 	if (error == 0) {
507 		/*
508 		 * Assert validity.  Must be beyond the static allocator used
509 		 * by newfs_hammer2 (and thus also beyond the aux area),
510 		 * not go past the volume size, and must not be in the
511 		 * reserved segment area for a zone.
512 		 */
513 		KKASSERT(key >= hmp->voldata.allocator_beg &&
514 			 key + bytes <= hmp->total_size);
515 		KKASSERT((key & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
516 		bref->data_off = key | radix;
517 
518 		/*
519 		 * Record dedupability.  The dedup bits are cleared
520 		 * when bulkfree transitions the freemap from 11->10,
521 		 * and asserted to be clear on the 10->00 transition.
522 		 *
523 		 * We must record the bitmask with the chain locked
524 		 * at the time we set the allocation bits to avoid
525 		 * racing a bulkfree.
526 		 */
527 		if (bref->type == HAMMER2_BREF_TYPE_DATA)
528 			hammer2_io_dedup_set(hmp, bref);
529 #if 0
530 		kprintf("alloc cp=%p %016jx %016jx using %016jx\n",
531 			chain,
532 			bref->key, bref->data_off, chain->bref.data_off);
533 #endif
534 	} else if (error == HAMMER2_ERROR_ENOSPC) {
535 		/*
536 		 * Return EAGAIN with next iteration in iter->bnext, or
537 		 * return ENOSPC if the allocation map has been exhausted.
538 		 */
539 		error = hammer2_freemap_iterate(parentp, &chain, iter);
540 	}
541 
542 	/*
543 	 * Cleanup
544 	 */
545 	if (chain) {
546 		hammer2_chain_unlock(chain);
547 		hammer2_chain_drop(chain);
548 	}
549 	return (error);
550 }
551 
552 /*
553  * Allocate (1<<radix) bytes from the bmap whos base data offset is (*basep).
554  *
555  * If the linear iterator is mid-block we use it directly (the bitmap should
556  * already be marked allocated), otherwise we search for a block in the
557  * bitmap that fits the allocation request.
558  *
559  * A partial bitmap allocation sets the minimum bitmap granularity (16KB)
560  * to fully allocated and adjusts the linear allocator to allow the
561  * remaining space to be allocated.
562  *
563  * sub_key is the lower 32 bits of the chain->bref.key for the chain whos
564  * bref is being allocated.  If the radix represents an allocation >= 16KB
565  * (aka HAMMER2_FREEMAP_BLOCK_RADIX) we try to use this key to select the
566  * blocks directly out of the bmap.
567  */
568 static
569 int
570 hammer2_bmap_alloc(hammer2_dev_t *hmp, hammer2_bmap_data_t *bmap,
571 		   uint16_t class, int n, int sub_key,
572 		   int radix, hammer2_key_t *basep)
573 {
574 	size_t size;
575 	size_t bgsize;
576 	int bmradix;
577 	hammer2_bitmap_t bmmask;
578 	int offset;
579 	int i;
580 	int j;
581 
582 	/*
583 	 * Take into account 2-bits per block when calculating bmradix.
584 	 */
585 	size = (size_t)1 << radix;
586 
587 	if (radix <= HAMMER2_FREEMAP_BLOCK_RADIX) {
588 		bmradix = 2;
589 		/* (16K) 2 bits per allocation block */
590 	} else {
591 		bmradix = (hammer2_bitmap_t)2 <<
592 			  (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
593 		/* (32K-256K) 4, 8, 16, 32 bits per allocation block */
594 	}
595 
596 	/*
597 	 * Use the linear iterator to pack small allocations, otherwise
598 	 * fall-back to finding a free 16KB chunk.  The linear iterator
599 	 * is only valid when *NOT* on a freemap chunking boundary (16KB).
600 	 * If it is the bitmap must be scanned.  It can become invalid
601 	 * once we pack to the boundary.  We adjust it after a bitmap
602 	 * allocation only for sub-16KB allocations (so the perfectly good
603 	 * previous value can still be used for fragments when 16KB+
604 	 * allocations are made inbetween fragmentary allocations).
605 	 *
606 	 * Beware of hardware artifacts when bmradix == 64 (intermediate
607 	 * result can wind up being '1' instead of '0' if hardware masks
608 	 * bit-count & 63).
609 	 *
610 	 * NOTE: j needs to be even in the j= calculation.  As an artifact
611 	 *	 of the /2 division, our bitmask has to clear bit 0.
612 	 *
613 	 * NOTE: TODO this can leave little unallocatable fragments lying
614 	 *	 around.
615 	 */
616 	if (((uint32_t)bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) + size <=
617 	    HAMMER2_FREEMAP_BLOCK_SIZE &&
618 	    (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) &&
619 	    bmap->linear < HAMMER2_SEGSIZE) {
620 		/*
621 		 * Use linear iterator if it is not block-aligned to avoid
622 		 * wasting space.
623 		 *
624 		 * Calculate the bitmapq[] index (i) and calculate the
625 		 * shift count within the 64-bit bitmapq[] entry.
626 		 *
627 		 * The freemap block size is 16KB, but each bitmap
628 		 * entry is two bits so use a little trick to get
629 		 * a (j) shift of 0, 2, 4, ... 62 in 16KB chunks.
630 		 */
631 		KKASSERT(bmap->linear >= 0 &&
632 			 bmap->linear + size <= HAMMER2_SEGSIZE &&
633 			 (bmap->linear & (HAMMER2_ALLOC_MIN - 1)) == 0);
634 		offset = bmap->linear;
635 		i = offset / (HAMMER2_SEGSIZE / HAMMER2_BMAP_ELEMENTS);
636 		j = (offset / (HAMMER2_FREEMAP_BLOCK_SIZE / 2)) & 62;
637 		bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
638 			 HAMMER2_BMAP_ALLONES :
639 			 ((hammer2_bitmap_t)1 << bmradix) - 1;
640 		bmmask <<= j;
641 		bmap->linear = offset + size;
642 	} else {
643 		/*
644 		 * Try to index a starting point based on sub_key.  This
645 		 * attempts to restore sequential block ordering on-disk
646 		 * whenever possible, even if data is committed out of
647 		 * order.
648 		 *
649 		 * i - Index bitmapq[], full data range represented is
650 		 *     HAMMER2_BMAP_SIZE.
651 		 *
652 		 * j - Index within bitmapq[i], full data range represented is
653 		 *     HAMMER2_BMAP_INDEX_SIZE.
654 		 *
655 		 * WARNING!
656 		 */
657 		i = -1;
658 		j = -1;
659 
660 		switch(class >> 8) {
661 		case HAMMER2_BREF_TYPE_DATA:
662 			if (radix >= HAMMER2_FREEMAP_BLOCK_RADIX) {
663 				i = (sub_key & HAMMER2_BMAP_MASK) /
664 				    (HAMMER2_BMAP_SIZE / HAMMER2_BMAP_ELEMENTS);
665 				j = (sub_key & HAMMER2_BMAP_INDEX_MASK) /
666 				    (HAMMER2_BMAP_INDEX_SIZE /
667 				     HAMMER2_BMAP_BLOCKS_PER_ELEMENT);
668 				j = j * 2;
669 			}
670 			break;
671 		case HAMMER2_BREF_TYPE_INODE:
672 			break;
673 		default:
674 			break;
675 		}
676 		if (i >= 0) {
677 			KKASSERT(i < HAMMER2_BMAP_ELEMENTS &&
678 				 j < 2 * HAMMER2_BMAP_BLOCKS_PER_ELEMENT);
679 			KKASSERT(j + bmradix <= HAMMER2_BMAP_BITS_PER_ELEMENT);
680 			bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
681 				 HAMMER2_BMAP_ALLONES :
682 				 ((hammer2_bitmap_t)1 << bmradix) - 1;
683 			bmmask <<= j;
684 
685 			if ((bmap->bitmapq[i] & bmmask) == 0)
686 				goto success;
687 		}
688 
689 		/*
690 		 * General element scan.
691 		 *
692 		 * WARNING: (j) is iterating a bit index (by 2's)
693 		 */
694 		for (i = 0; i < HAMMER2_BMAP_ELEMENTS; ++i) {
695 			bmmask = (bmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
696 				 HAMMER2_BMAP_ALLONES :
697 				 ((hammer2_bitmap_t)1 << bmradix) - 1;
698 			for (j = 0;
699 			     j < HAMMER2_BMAP_BITS_PER_ELEMENT;
700 			     j += bmradix) {
701 				if ((bmap->bitmapq[i] & bmmask) == 0)
702 					goto success;
703 				bmmask <<= bmradix;
704 			}
705 		}
706 		/*fragments might remain*/
707 		/*KKASSERT(bmap->avail == 0);*/
708 		return (HAMMER2_ERROR_ENOSPC);
709 success:
710 		offset = i * (HAMMER2_SEGSIZE / HAMMER2_BMAP_ELEMENTS) +
711 			 (j * (HAMMER2_FREEMAP_BLOCK_SIZE / 2));
712 		if (size & HAMMER2_FREEMAP_BLOCK_MASK)
713 			bmap->linear = offset + size;
714 	}
715 
716 	/* 8 x (64/2) -> 256 x 16K -> 4MB */
717 	KKASSERT(i >= 0 && i < HAMMER2_BMAP_ELEMENTS);
718 
719 	/*
720 	 * Optimize the buffer cache to avoid unnecessary read-before-write
721 	 * operations.
722 	 *
723 	 * The device block size could be larger than the allocation size
724 	 * so the actual bitmap test is somewhat more involved.  We have
725 	 * to use a compatible buffer size for this operation.
726 	 */
727 	if ((bmap->bitmapq[i] & bmmask) == 0 &&
728 	    HAMMER2_PBUFSIZE != size) {
729 		size_t psize = HAMMER2_PBUFSIZE;
730 		hammer2_off_t pmask = (hammer2_off_t)psize - 1;
731 		int pbmradix = (hammer2_bitmap_t)2 <<
732 					(HAMMER2_PBUFRADIX -
733 			       HAMMER2_FREEMAP_BLOCK_RADIX);
734 		hammer2_bitmap_t pbmmask;
735 		int pradix = hammer2_getradix(psize);
736 
737 		pbmmask = (pbmradix == HAMMER2_BMAP_BITS_PER_ELEMENT) ?
738 			HAMMER2_BMAP_ALLONES :
739 			((hammer2_bitmap_t)1 << pbmradix) - 1;
740 		while ((pbmmask & bmmask) == 0)
741 			pbmmask <<= pbmradix;
742 
743 #if 0
744 		kprintf("%016jx mask %016jx %016jx %016jx (%zd/%zd)\n",
745 			*basep + offset, bmap->bitmapq[i],
746 			pbmmask, bmmask, size, psize);
747 #endif
748 
749 		if ((bmap->bitmapq[i] & pbmmask) == 0) {
750 			hammer2_io_t *dio;
751 
752 			hammer2_io_newnz(hmp, class >> 8,
753 					(*basep + (offset & ~pmask)) |
754 					pradix, psize, &dio);
755 			hammer2_io_putblk(&dio);
756 		}
757 	}
758 
759 #if 0
760 	/*
761 	 * When initializing a new inode segment also attempt to initialize
762 	 * an adjacent segment.  Be careful not to index beyond the array
763 	 * bounds.
764 	 *
765 	 * We do this to try to localize inode accesses to improve
766 	 * directory scan rates.  XXX doesn't improve scan rates.
767 	 */
768 	if (size == HAMMER2_INODE_BYTES) {
769 		if (n & 1) {
770 			if (bmap[-1].radix == 0 && bmap[-1].avail)
771 				bmap[-1].radix = radix;
772 		} else {
773 			if (bmap[1].radix == 0 && bmap[1].avail)
774 				bmap[1].radix = radix;
775 		}
776 	}
777 #endif
778 	/*
779 	 * Calculate the bitmap-granular change in bgsize for the volume
780 	 * header.  We cannot use the fine-grained change here because
781 	 * the bulkfree code can't undo it.  If the bitmap element is already
782 	 * marked allocated it has already been accounted for.
783 	 */
784 	if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
785 		if (bmap->bitmapq[i] & bmmask)
786 			bgsize = 0;
787 		else
788 			bgsize = HAMMER2_FREEMAP_BLOCK_SIZE;
789 	} else {
790 		bgsize = size;
791 	}
792 
793 	/*
794 	 * Adjust the bitmap, set the class (it might have been 0),
795 	 * and available bytes, update the allocation offset (*basep)
796 	 * from the L0 base to the actual offset.
797 	 *
798 	 * Do not override the class if doing a relaxed class allocation.
799 	 *
800 	 * avail must reflect the bitmap-granular availability.  The allocator
801 	 * tests will also check the linear iterator.
802 	 */
803 	bmap->bitmapq[i] |= bmmask;
804 	if (bmap->class == 0)
805 		bmap->class = class;
806 	bmap->avail -= bgsize;
807 	*basep += offset;
808 
809 	/*
810 	 * Adjust the volume header's allocator_free parameter.  This
811 	 * parameter has to be fixed up by bulkfree which has no way to
812 	 * figure out sub-16K chunking, so it must be adjusted by the
813 	 * bitmap-granular size.
814 	 */
815 	if (bgsize) {
816 		hammer2_voldata_lock(hmp);
817 		hammer2_voldata_modify(hmp);
818 		hmp->voldata.allocator_free -= bgsize;
819 		hammer2_voldata_unlock(hmp);
820 	}
821 
822 	return(0);
823 }
824 
825 /*
826  * Initialize a freemap for the storage area (in bytes) that begins at (key).
827  */
828 static
829 void
830 hammer2_freemap_init(hammer2_dev_t *hmp, hammer2_key_t key,
831 		     hammer2_chain_t *chain)
832 {
833 	hammer2_off_t l1size;
834 	hammer2_off_t lokey;
835 	hammer2_off_t hikey;
836 	hammer2_bmap_data_t *bmap;
837 	int count;
838 
839 	/*
840 	 * LEVEL1 is 1GB, there are two level1 1GB freemaps per 2GB zone.
841 	 */
842 	l1size = HAMMER2_FREEMAP_LEVEL1_SIZE;
843 
844 	/*
845 	 * Calculate the portion of the 1GB map that should be initialized
846 	 * as free.  Portions below or after will be initialized as allocated.
847 	 * SEGMASK-align the areas so we don't have to worry about sub-scans
848 	 * or endianess when using memset.
849 	 *
850 	 * WARNING! It is possible for lokey to be larger than hikey if the
851 	 *	    entire 2GB segment is within the static allocation.
852 	 */
853 	/*
854 	 * (1) Ensure that all statically allocated space from newfs_hammer2
855 	 *     is marked allocated, and take it up to the level1 base for
856 	 *     this key.
857 	 */
858 	lokey = (hmp->voldata.allocator_beg + HAMMER2_SEGMASK64) &
859 		~HAMMER2_SEGMASK64;
860 	if (lokey < H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX))
861 		lokey = H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX);
862 
863 	/*
864 	 * (2) Ensure that the reserved area is marked allocated (typically
865 	 *     the first 4MB of each 2GB area being represented).  Since
866 	 *     each LEAF represents 1GB of storage and the zone is 2GB, we
867 	 *     have to adjust lowkey upward every other LEAF sequentially.
868 	 */
869 	if (lokey < H2FMZONEBASE(key) + HAMMER2_ZONE_SEG64)
870 		lokey = H2FMZONEBASE(key) + HAMMER2_ZONE_SEG64;
871 
872 	/*
873 	 * (3) Ensure that any trailing space at the end-of-volume is marked
874 	 *     allocated.
875 	 */
876 	hikey = key + HAMMER2_FREEMAP_LEVEL1_SIZE;
877 	if (hikey > hmp->total_size) {
878 		hikey = hmp->total_size & ~HAMMER2_SEGMASK64;
879 	}
880 
881 	/*
882 	 * Heuristic highest possible value
883 	 */
884 	chain->bref.check.freemap.avail = HAMMER2_FREEMAP_LEVEL1_SIZE;
885 	bmap = &chain->data->bmdata[0];
886 
887 	/*
888 	 * Initialize bitmap (bzero'd by caller)
889 	 */
890 	for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
891 		if (key < lokey || key >= hikey) {
892 			memset(bmap->bitmapq, -1,
893 			       sizeof(bmap->bitmapq));
894 			bmap->avail = 0;
895 			bmap->linear = HAMMER2_SEGSIZE;
896 			chain->bref.check.freemap.avail -=
897 				HAMMER2_FREEMAP_LEVEL0_SIZE;
898 		} else {
899 			bmap->avail = HAMMER2_FREEMAP_LEVEL0_SIZE;
900 		}
901 		key += HAMMER2_FREEMAP_LEVEL0_SIZE;
902 		++bmap;
903 	}
904 }
905 
906 /*
907  * The current Level 1 freemap has been exhausted, iterate to the next
908  * one, return ENOSPC if no freemaps remain.
909  *
910  * At least two loops are required.  If we are not in relaxed mode and
911  * we run out of storage we enter relaxed mode and do a third loop.
912  * The relaxed mode is recorded back in the hmp so once we enter the mode
913  * we remain relaxed until stuff begins to get freed and only do 2 loops.
914  *
915  * XXX this should rotate back to the beginning to handle freed-up space
916  * XXX or use intermediate entries to locate free space. TODO
917  */
918 static int
919 hammer2_freemap_iterate(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
920 			hammer2_fiterate_t *iter)
921 {
922 	hammer2_dev_t *hmp = (*parentp)->hmp;
923 
924 	iter->bnext &= ~HAMMER2_FREEMAP_LEVEL1_MASK;
925 	iter->bnext += HAMMER2_FREEMAP_LEVEL1_SIZE;
926 	if (iter->bnext >= hmp->total_size) {
927 		iter->bnext = 0;
928 		if (++iter->loops >= 2) {
929 			if (iter->relaxed == 0)
930 				iter->relaxed = 1;
931 			else
932 				return (HAMMER2_ERROR_ENOSPC);
933 		}
934 	}
935 	return(HAMMER2_ERROR_EAGAIN);
936 }
937 
938 /*
939  * Adjust the bit-pattern for data in the freemap bitmap according to
940  * (how).  This code is called from on-mount recovery to fixup (mark
941  * as allocated) blocks whos freemap upates might not have been committed
942  * in the last crash and is used by the bulk freemap scan to stage frees.
943  *
944  * WARNING! Cannot be called with a empty-data bref (radix == 0).
945  *
946  * XXX currently disabled when how == 0 (the normal real-time case).  At
947  * the moment we depend on the bulk freescan to actually free blocks.  It
948  * will still call this routine with a non-zero how to stage possible frees
949  * and to do the actual free.
950  */
951 void
952 hammer2_freemap_adjust(hammer2_dev_t *hmp, hammer2_blockref_t *bref,
953 		       int how)
954 {
955 	hammer2_off_t data_off = bref->data_off;
956 	hammer2_chain_t *chain;
957 	hammer2_chain_t *parent;
958 	hammer2_bmap_data_t *bmap;
959 	hammer2_key_t key;
960 	hammer2_key_t key_dummy;
961 	hammer2_off_t l0size;
962 	hammer2_off_t l1size;
963 	hammer2_off_t l1mask;
964 	hammer2_tid_t mtid;
965 	hammer2_bitmap_t *bitmap;
966 	const hammer2_bitmap_t bmmask00 = 0;
967 	hammer2_bitmap_t bmmask01;
968 	hammer2_bitmap_t bmmask10;
969 	hammer2_bitmap_t bmmask11;
970 	size_t bytes;
971 	uint16_t class;
972 	int radix;
973 	int start;
974 	int count;
975 	int modified = 0;
976 	int error;
977 	size_t bgsize = 0;
978 
979 	KKASSERT(how == HAMMER2_FREEMAP_DORECOVER);
980 
981 	KKASSERT(hmp->spmp);
982 	mtid = hammer2_trans_sub(hmp->spmp);
983 
984 	radix = (int)data_off & HAMMER2_OFF_MASK_RADIX;
985 	KKASSERT(radix != 0);
986 	data_off &= ~HAMMER2_OFF_MASK_RADIX;
987 	KKASSERT(radix <= HAMMER2_RADIX_MAX);
988 
989 	if (radix)
990 		bytes = (size_t)1 << radix;
991 	else
992 		bytes = 0;
993 	class = (bref->type << 8) | HAMMER2_PBUFRADIX;
994 
995 	/*
996 	 * We can't adjust the freemap for data allocations made by
997 	 * newfs_hammer2.
998 	 */
999 	if (data_off < hmp->voldata.allocator_beg)
1000 		return;
1001 
1002 	KKASSERT((data_off & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
1003 
1004 	/*
1005 	 * Lookup the level1 freemap chain.  The chain must exist.
1006 	 */
1007 	key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL1_RADIX);
1008 	l0size = HAMMER2_FREEMAP_LEVEL0_SIZE;
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 (how == HAMMER2_FREEMAP_DOREALFREE)
1093 			how = HAMMER2_FREEMAP_DOMAYFREE;
1094 	} else {
1095 		count = 1 << (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
1096 	}
1097 
1098 	/*
1099 	 * [re]load the bmap and bitmap pointers.  Each bmap entry covers
1100 	 * a 4MB swath.  The bmap itself (LEVEL1) covers 2GB.
1101 	 *
1102 	 * Be sure to reset the linear iterator to ensure that the adjustment
1103 	 * is not ignored.
1104 	 */
1105 again:
1106 	bmap = &chain->data->bmdata[(int)(data_off >> HAMMER2_SEGRADIX) &
1107 				    (HAMMER2_FREEMAP_COUNT - 1)];
1108 	bitmap = &bmap->bitmapq[(int)(data_off >> (HAMMER2_SEGRADIX - 3)) & 7];
1109 
1110 	if (modified)
1111 		bmap->linear = 0;
1112 
1113 	while (count) {
1114 		KKASSERT(bmmask11);
1115 		if (how == HAMMER2_FREEMAP_DORECOVER) {
1116 			/*
1117 			 * Recovery request, mark as allocated.
1118 			 */
1119 			if ((*bitmap & bmmask11) != bmmask11) {
1120 				if (modified == 0) {
1121 					hammer2_chain_modify(chain, mtid, 0, 0);
1122 					modified = 1;
1123 					goto again;
1124 				}
1125 				if ((*bitmap & bmmask11) == bmmask00) {
1126 					bmap->avail -=
1127 						HAMMER2_FREEMAP_BLOCK_SIZE;
1128 					bgsize += HAMMER2_FREEMAP_BLOCK_SIZE;
1129 				}
1130 				if (bmap->class == 0)
1131 					bmap->class = class;
1132 				*bitmap |= bmmask11;
1133 				if (hammer2_debug & 0x0040) {
1134 					kprintf("hammer2_freemap_adjust: "
1135 						"fixup type=%02x "
1136 						"block=%016jx/%zd\n",
1137 						bref->type, data_off, bytes);
1138 				}
1139 			} else {
1140 				/*
1141 				kprintf("hammer2_freemap_adjust:  good "
1142 					"type=%02x block=%016jx/%zd\n",
1143 					bref->type, data_off, bytes);
1144 				*/
1145 			}
1146 		}
1147 #if 0
1148 		/*
1149 		 * XXX this stuff doesn't work, avail is miscalculated and
1150 		 * code 10 means something else now.
1151 		 */
1152 		else if ((*bitmap & bmmask11) == bmmask11) {
1153 			/*
1154 			 * Mayfree/Realfree request and bitmap is currently
1155 			 * marked as being fully allocated.
1156 			 */
1157 			if (!modified) {
1158 				hammer2_chain_modify(chain, 0);
1159 				modified = 1;
1160 				goto again;
1161 			}
1162 			if (how == HAMMER2_FREEMAP_DOREALFREE)
1163 				*bitmap &= ~bmmask11;
1164 			else
1165 				*bitmap = (*bitmap & ~bmmask11) | bmmask10;
1166 		} else if ((*bitmap & bmmask11) == bmmask10) {
1167 			/*
1168 			 * Mayfree/Realfree request and bitmap is currently
1169 			 * marked as being possibly freeable.
1170 			 */
1171 			if (how == HAMMER2_FREEMAP_DOREALFREE) {
1172 				if (!modified) {
1173 					hammer2_chain_modify(chain, 0);
1174 					modified = 1;
1175 					goto again;
1176 				}
1177 				*bitmap &= ~bmmask11;
1178 			}
1179 		} else {
1180 			/*
1181 			 * 01 - Not implemented, currently illegal state
1182 			 * 00 - Not allocated at all, illegal free.
1183 			 */
1184 			panic("hammer2_freemap_adjust: "
1185 			      "Illegal state %08x(%08x)",
1186 			      *bitmap, *bitmap & bmmask11);
1187 		}
1188 #endif
1189 		--count;
1190 		bmmask01 <<= 2;
1191 		bmmask10 <<= 2;
1192 		bmmask11 <<= 2;
1193 	}
1194 #if HAMMER2_BMAP_ELEMENTS != 8
1195 #error "hammer2_freemap.c: HAMMER2_BMAP_ELEMENTS expected to be 8"
1196 #endif
1197 	if (how == HAMMER2_FREEMAP_DOREALFREE && modified) {
1198 		bmap->avail += 1 << radix;
1199 		KKASSERT(bmap->avail <= HAMMER2_SEGSIZE);
1200 		if (bmap->avail == HAMMER2_SEGSIZE &&
1201 		    bmap->bitmapq[0] == 0 &&
1202 		    bmap->bitmapq[1] == 0 &&
1203 		    bmap->bitmapq[2] == 0 &&
1204 		    bmap->bitmapq[3] == 0 &&
1205 		    bmap->bitmapq[4] == 0 &&
1206 		    bmap->bitmapq[5] == 0 &&
1207 		    bmap->bitmapq[6] == 0 &&
1208 		    bmap->bitmapq[7] == 0) {
1209 			key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL0_RADIX);
1210 			kprintf("Freeseg %016jx\n", (intmax_t)key);
1211 			bmap->class = 0;
1212 		}
1213 	}
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 	 * radii 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