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