xref: /dragonfly/sys/vfs/hammer2/hammer2_freemap.c (revision 61c0377f)
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.
111 	 */
112 	if ((bref->data_off & ~HAMMER2_OFF_MASK_RADIX) == 0) {
113 		index = 0;
114 	} else {
115 		off = bref->data_off & ~HAMMER2_OFF_MASK_RADIX &
116 		      (((hammer2_off_t)1 << HAMMER2_FREEMAP_LEVEL1_RADIX) - 1);
117 		off = off / HAMMER2_PBUFSIZE;
118 		KKASSERT(off >= HAMMER2_ZONE_FREEMAP_00 &&
119 			 off < HAMMER2_ZONE_FREEMAP_END);
120 		index = (int)(off - HAMMER2_ZONE_FREEMAP_00) / 4;
121 		KKASSERT(index >= 0 && index < HAMMER2_ZONE_FREEMAP_COPIES);
122 	}
123 
124 	/*
125 	 * Calculate new index (our 'allocation').
126 	 */
127 	index = (index + 1) % HAMMER2_ZONE_FREEMAP_COPIES;
128 
129 	/*
130 	 * Calculate the block offset of the reserved block.  This will
131 	 * point into the 4MB reserved area at the base of the appropriate
132 	 * 2GB zone, once added to the FREEMAP_x selection above.
133 	 */
134 	switch(bref->keybits) {
135 	/* case HAMMER2_FREEMAP_LEVEL5_RADIX: not applicable */
136 	case HAMMER2_FREEMAP_LEVEL4_RADIX:	/* 2EB */
137 		KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
138 		KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
139 		off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL4_RADIX) +
140 		      (index * 4 + HAMMER2_ZONE_FREEMAP_00 +
141 		       HAMMER2_ZONEFM_LEVEL4) * HAMMER2_PBUFSIZE;
142 		break;
143 	case HAMMER2_FREEMAP_LEVEL3_RADIX:	/* 2PB */
144 		KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
145 		KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
146 		off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL3_RADIX) +
147 		      (index * 4 + HAMMER2_ZONE_FREEMAP_00 +
148 		       HAMMER2_ZONEFM_LEVEL3) * HAMMER2_PBUFSIZE;
149 		break;
150 	case HAMMER2_FREEMAP_LEVEL2_RADIX:	/* 2TB */
151 		KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE);
152 		KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
153 		off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL2_RADIX) +
154 		      (index * 4 + HAMMER2_ZONE_FREEMAP_00 +
155 		       HAMMER2_ZONEFM_LEVEL2) * HAMMER2_PBUFSIZE;
156 		break;
157 	case HAMMER2_FREEMAP_LEVEL1_RADIX:	/* 2GB */
158 		KKASSERT(bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
159 		KKASSERT(bytes == HAMMER2_FREEMAP_LEVELN_PSIZE);
160 		off = H2FMBASE(bref->key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
161 		      (index * 4 + HAMMER2_ZONE_FREEMAP_00 +
162 		       HAMMER2_ZONEFM_LEVEL1) * HAMMER2_PBUFSIZE;
163 		break;
164 	default:
165 		panic("freemap: bad radix(2) %p %d\n", bref, bref->keybits);
166 		/* NOT REACHED */
167 		off = (hammer2_off_t)-1;
168 		break;
169 	}
170 	bref->data_off = off | radix;
171 #if FREEMAP_DEBUG
172 	kprintf("FREEMAP BLOCK TYPE %d %016jx/%d DATA_OFF=%016jx\n",
173 		bref->type, bref->key, bref->keybits, bref->data_off);
174 #endif
175 	return (0);
176 }
177 
178 /*
179  * Normal freemap allocator
180  *
181  * Use available hints to allocate space using the freemap.  Create missing
182  * freemap infrastructure on-the-fly as needed (including marking initial
183  * allocations using the iterator as allocated, instantiating new 2GB zones,
184  * and dealing with the end-of-media edge case).
185  *
186  * ip and bpref are only used as a heuristic to determine locality of
187  * reference.  bref->key may also be used heuristically.
188  */
189 int
190 hammer2_freemap_alloc(hammer2_trans_t *trans, hammer2_chain_t *chain,
191 		      size_t bytes)
192 {
193 	hammer2_mount_t *hmp = chain->hmp;
194 	hammer2_blockref_t *bref = &chain->bref;
195 	hammer2_chain_t *parent;
196 	int radix;
197 	int error;
198 	unsigned int hindex;
199 	hammer2_fiterate_t iter;
200 
201 	/*
202 	 * Validate the allocation size.  It must be a power of 2.
203 	 *
204 	 * For now require that the caller be aware of the minimum
205 	 * allocation (1K).
206 	 */
207 	radix = hammer2_getradix(bytes);
208 	KKASSERT((size_t)1 << radix == bytes);
209 
210 	if (bref->type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
211 	    bref->type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
212 		/*
213 		 * Freemap blocks themselves are assigned from the reserve
214 		 * area, not allocated from the freemap.
215 		 */
216 		error = hammer2_freemap_reserve(trans, chain, radix);
217 		return error;
218 	}
219 
220 	KKASSERT(bytes >= HAMMER2_ALLOC_MIN && bytes <= HAMMER2_ALLOC_MAX);
221 
222 	if (trans->flags & (HAMMER2_TRANS_ISFLUSH | HAMMER2_TRANS_PREFLUSH))
223 		++trans->sync_xid;
224 
225 	/*
226 	 * Calculate the starting point for our allocation search.
227 	 *
228 	 * Each freemap leaf is dedicated to a specific freemap_radix.
229 	 * The freemap_radix can be more fine-grained than the device buffer
230 	 * radix which results in inodes being grouped together in their
231 	 * own segment, terminal-data (16K or less) and initial indirect
232 	 * block being grouped together, and then full-indirect and full-data
233 	 * blocks (64K) being grouped together.
234 	 *
235 	 * The single most important aspect of this is the inode grouping
236 	 * because that is what allows 'find' and 'ls' and other filesystem
237 	 * topology operations to run fast.
238 	 */
239 #if 0
240 	if (bref->data_off & ~HAMMER2_OFF_MASK_RADIX)
241 		bpref = bref->data_off & ~HAMMER2_OFF_MASK_RADIX;
242 	else if (trans->tmp_bpref)
243 		bpref = trans->tmp_bpref;
244 	else if (trans->tmp_ip)
245 		bpref = trans->tmp_ip->chain->bref.data_off;
246 	else
247 #endif
248 	/*
249 	 * Heuristic tracking index.  We would like one for each distinct
250 	 * bref type if possible.  heur_freemap[] has room for two classes
251 	 * for each type.  At a minimum we have to break-up our heuristic
252 	 * by device block sizes.
253 	 */
254 	hindex = hammer2_devblkradix(radix) - HAMMER2_MINIORADIX;
255 	KKASSERT(hindex < HAMMER2_FREEMAP_HEUR_NRADIX);
256 	hindex += bref->type * HAMMER2_FREEMAP_HEUR_NRADIX;
257 	hindex &= HAMMER2_FREEMAP_HEUR_TYPES * HAMMER2_FREEMAP_HEUR_NRADIX - 1;
258 	KKASSERT(hindex < HAMMER2_FREEMAP_HEUR);
259 
260 	iter.bpref = hmp->heur_freemap[hindex];
261 
262 	/*
263 	 * Make sure bpref is in-bounds.  It's ok if bpref covers a zone's
264 	 * reserved area, the try code will iterate past it.
265 	 */
266 	if (iter.bpref > hmp->voldata.volu_size)
267 		iter.bpref = hmp->voldata.volu_size - 1;
268 
269 	/*
270 	 * Iterate the freemap looking for free space before and after.
271 	 */
272 	parent = &hmp->fchain;
273 	hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
274 	error = EAGAIN;
275 	iter.bnext = iter.bpref;
276 	iter.loops = 0;
277 
278 	while (error == EAGAIN) {
279 		error = hammer2_freemap_try_alloc(trans, &parent, bref,
280 						  radix, &iter);
281 	}
282 	hmp->heur_freemap[hindex] = iter.bnext;
283 	hammer2_chain_unlock(parent);
284 
285 	if (trans->flags & (HAMMER2_TRANS_ISFLUSH | HAMMER2_TRANS_PREFLUSH))
286 		--trans->sync_xid;
287 
288 	return (error);
289 }
290 
291 static int
292 hammer2_freemap_try_alloc(hammer2_trans_t *trans, hammer2_chain_t **parentp,
293 			  hammer2_blockref_t *bref, int radix,
294 			  hammer2_fiterate_t *iter)
295 {
296 	hammer2_mount_t *hmp = (*parentp)->hmp;
297 	hammer2_off_t l0size;
298 	hammer2_off_t l1size;
299 	hammer2_off_t l1mask;
300 	hammer2_key_t key_dummy;
301 	hammer2_chain_t *chain;
302 	hammer2_off_t key;
303 	size_t bytes;
304 	uint16_t class;
305 	int error = 0;
306 	int cache_index = -1;
307 	int ddflag;
308 
309 
310 	/*
311 	 * Calculate the number of bytes being allocated, the number
312 	 * of contiguous bits of bitmap being allocated, and the bitmap
313 	 * mask.
314 	 *
315 	 * WARNING! cpu hardware may mask bits == 64 -> 0 and blow up the
316 	 *	    mask calculation.
317 	 */
318 	bytes = (size_t)1 << radix;
319 	class = (bref->type << 8) | hammer2_devblkradix(radix);
320 
321 	/*
322 	 * Lookup the level1 freemap chain, creating and initializing one
323 	 * if necessary.  Intermediate levels will be created automatically
324 	 * when necessary by hammer2_chain_create().
325 	 */
326 	key = H2FMBASE(iter->bnext, HAMMER2_FREEMAP_LEVEL1_RADIX);
327 	l0size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
328 	l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
329 	l1mask = l1size - 1;
330 
331 	chain = hammer2_chain_lookup(parentp, &key_dummy, key, key + l1mask,
332 				     &cache_index,
333 				     HAMMER2_LOOKUP_ALWAYS |
334 				     HAMMER2_LOOKUP_MATCHIND, &ddflag);
335 
336 	if (chain == NULL) {
337 		/*
338 		 * Create the missing leaf, be sure to initialize
339 		 * the auxillary freemap tracking information in
340 		 * the bref.check.freemap structure.
341 		 */
342 #if 0
343 		kprintf("freemap create L1 @ %016jx bpref %016jx\n",
344 			key, iter->bpref);
345 #endif
346 		error = hammer2_chain_create(trans, parentp, &chain, hmp->spmp,
347 				     key, HAMMER2_FREEMAP_LEVEL1_RADIX,
348 				     HAMMER2_BREF_TYPE_FREEMAP_LEAF,
349 				     HAMMER2_FREEMAP_LEVELN_PSIZE);
350 		KKASSERT(error == 0);
351 		if (error == 0) {
352 			hammer2_chain_modify(trans, &chain, 0);
353 			bzero(&chain->data->bmdata[0],
354 			      HAMMER2_FREEMAP_LEVELN_PSIZE);
355 			chain->bref.check.freemap.bigmask = (uint32_t)-1;
356 			chain->bref.check.freemap.avail = l1size;
357 			/* bref.methods should already be inherited */
358 
359 			hammer2_freemap_init(trans, hmp, key, chain);
360 		}
361 	} else if ((chain->bref.check.freemap.bigmask & (1 << radix)) == 0) {
362 		/*
363 		 * Already flagged as not having enough space
364 		 */
365 		error = ENOSPC;
366 	} else {
367 		/*
368 		 * Modify existing chain to setup for adjustment.
369 		 */
370 		hammer2_chain_modify(trans, &chain, 0);
371 	}
372 
373 	/*
374 	 * Scan 2MB entries.
375 	 */
376 	if (error == 0) {
377 		hammer2_bmap_data_t *bmap;
378 		hammer2_key_t base_key;
379 		int count;
380 		int start;
381 		int n;
382 
383 		KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF);
384 		start = (int)((iter->bnext - key) >>
385 			      HAMMER2_FREEMAP_LEVEL0_RADIX);
386 		KKASSERT(start >= 0 && start < HAMMER2_FREEMAP_COUNT);
387 		hammer2_chain_modify(trans, &chain, 0);
388 
389 		error = ENOSPC;
390 		for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
391 			if (start + count >= HAMMER2_FREEMAP_COUNT &&
392 			    start - count < 0) {
393 				break;
394 			}
395 			n = start + count;
396 			bmap = &chain->data->bmdata[n];
397 			if (n < HAMMER2_FREEMAP_COUNT && bmap->avail &&
398 			    (bmap->class == 0 || bmap->class == class)) {
399 				base_key = key + n * l0size;
400 				error = hammer2_bmap_alloc(trans, hmp, bmap,
401 							   class, n, radix,
402 							   &base_key);
403 				if (error != ENOSPC) {
404 					key = base_key;
405 					break;
406 				}
407 			}
408 			n = start - count;
409 			bmap = &chain->data->bmdata[n];
410 			if (n >= 0 && bmap->avail &&
411 			    (bmap->class == 0 || bmap->class == class)) {
412 				base_key = key + n * l0size;
413 				error = hammer2_bmap_alloc(trans, hmp, bmap,
414 							   class, n, radix,
415 							   &base_key);
416 				if (error != ENOSPC) {
417 					key = base_key;
418 					break;
419 				}
420 			}
421 		}
422 		if (error == ENOSPC)
423 			chain->bref.check.freemap.bigmask &= ~(1 << radix);
424 		/* XXX also scan down from original count */
425 	}
426 
427 	if (error == 0) {
428 		/*
429 		 * Assert validity.  Must be beyond the static allocator used
430 		 * by newfs_hammer2 (and thus also beyond the aux area),
431 		 * not go past the volume size, and must not be in the
432 		 * reserved segment area for a zone.
433 		 */
434 		KKASSERT(key >= hmp->voldata.allocator_beg &&
435 			 key + bytes <= hmp->voldata.volu_size);
436 		KKASSERT((key & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
437 		bref->data_off = key | radix;
438 
439 #if 0
440 		kprintf("alloc cp=%p %016jx %016jx using %016jx\n",
441 			chain,
442 			bref->key, bref->data_off, chain->bref.data_off);
443 #endif
444 	} else if (error == ENOSPC) {
445 		/*
446 		 * Return EAGAIN with next iteration in iter->bnext, or
447 		 * return ENOSPC if the allocation map has been exhausted.
448 		 */
449 		error = hammer2_freemap_iterate(trans, parentp, &chain, iter);
450 	}
451 
452 	/*
453 	 * Cleanup
454 	 */
455 	if (chain)
456 		hammer2_chain_unlock(chain);
457 	return (error);
458 }
459 
460 /*
461  * Allocate (1<<radix) bytes from the bmap whos base data offset is (*basep).
462  *
463  * If the linear iterator is mid-block we use it directly (the bitmap should
464  * already be marked allocated), otherwise we search for a block in the bitmap
465  * that fits the allocation request.
466  *
467  * A partial bitmap allocation sets the minimum bitmap granularity (16KB)
468  * to fully allocated and adjusts the linear allocator to allow the
469  * remaining space to be allocated.
470  */
471 static
472 int
473 hammer2_bmap_alloc(hammer2_trans_t *trans, hammer2_mount_t *hmp,
474 		   hammer2_bmap_data_t *bmap,
475 		   uint16_t class, int n, int radix, hammer2_key_t *basep)
476 {
477 	hammer2_io_t *dio;
478 	size_t size;
479 	size_t bsize;
480 	int bmradix;
481 	uint32_t bmmask;
482 	int offset;
483 	int error;
484 	int i;
485 	int j;
486 
487 	/*
488 	 * Take into account 2-bits per block when calculating bmradix.
489 	 */
490 	size = (size_t)1 << radix;
491 
492 	if (radix <= HAMMER2_FREEMAP_BLOCK_RADIX) {
493 		bmradix = 2;
494 		bsize = HAMMER2_FREEMAP_BLOCK_SIZE;
495 		/* (16K) 2 bits per allocation block */
496 	} else {
497 		bmradix = 2 << (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
498 		bsize = size;
499 		/* (32K-256K) 4, 8, 16, 32 bits per allocation block */
500 	}
501 
502 	/*
503 	 * Use the linear iterator to pack small allocations, otherwise
504 	 * fall-back to finding a free 16KB chunk.  The linear iterator
505 	 * is only valid when *NOT* on a freemap chunking boundary (16KB).
506 	 * If it is the bitmap must be scanned.  It can become invalid
507 	 * once we pack to the boundary.  We adjust it after a bitmap
508 	 * allocation only for sub-16KB allocations (so the perfectly good
509 	 * previous value can still be used for fragments when 16KB+
510 	 * allocations are made).
511 	 *
512 	 * Beware of hardware artifacts when bmradix == 32 (intermediate
513 	 * result can wind up being '1' instead of '0' if hardware masks
514 	 * bit-count & 31).
515 	 *
516 	 * NOTE: j needs to be even in the j= calculation.  As an artifact
517 	 *	 of the /2 division, our bitmask has to clear bit 0.
518 	 *
519 	 * NOTE: TODO this can leave little unallocatable fragments lying
520 	 *	 around.
521 	 */
522 	if (((uint32_t)bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) + size <=
523 	    HAMMER2_FREEMAP_BLOCK_SIZE &&
524 	    (bmap->linear & HAMMER2_FREEMAP_BLOCK_MASK) &&
525 	    bmap->linear < HAMMER2_SEGSIZE) {
526 		KKASSERT(bmap->linear >= 0 &&
527 			 bmap->linear + size <= HAMMER2_SEGSIZE &&
528 			 (bmap->linear & (HAMMER2_ALLOC_MIN - 1)) == 0);
529 		offset = bmap->linear;
530 		i = offset / (HAMMER2_SEGSIZE / 8);
531 		j = (offset / (HAMMER2_FREEMAP_BLOCK_SIZE / 2)) & 30;
532 		bmmask = (bmradix == 32) ?
533 			 0xFFFFFFFFU : (1 << bmradix) - 1;
534 		bmmask <<= j;
535 		bmap->linear = offset + size;
536 	} else {
537 		for (i = 0; i < 8; ++i) {
538 			bmmask = (bmradix == 32) ?
539 				 0xFFFFFFFFU : (1 << bmradix) - 1;
540 			for (j = 0; j < 32; j += bmradix) {
541 				if ((bmap->bitmap[i] & bmmask) == 0)
542 					goto success;
543 				bmmask <<= bmradix;
544 			}
545 		}
546 		/*fragments might remain*/
547 		/*KKASSERT(bmap->avail == 0);*/
548 		return (ENOSPC);
549 success:
550 		offset = i * (HAMMER2_SEGSIZE / 8) +
551 			 (j * (HAMMER2_FREEMAP_BLOCK_SIZE / 2));
552 		if (size & HAMMER2_FREEMAP_BLOCK_MASK)
553 			bmap->linear = offset + size;
554 	}
555 
556 	KKASSERT(i >= 0 && i < 8);	/* 8 x 16 -> 128 x 16K -> 2MB */
557 
558 	/*
559 	 * Optimize the buffer cache to avoid unnecessary read-before-write
560 	 * operations.
561 	 *
562 	 * The device block size could be larger than the allocation size
563 	 * so the actual bitmap test is somewhat more involved.  We have
564 	 * to use a compatible buffer size for this operation.
565 	 */
566 	if ((bmap->bitmap[i] & bmmask) == 0 &&
567 	    hammer2_devblksize(size) != size) {
568 		size_t psize = hammer2_devblksize(size);
569 		hammer2_off_t pmask = (hammer2_off_t)psize - 1;
570 		int pbmradix = 2 << (hammer2_devblkradix(radix) -
571 				     HAMMER2_FREEMAP_BLOCK_RADIX);
572 		uint32_t pbmmask;
573 		int pradix = hammer2_getradix(psize);
574 
575 		pbmmask = (pbmradix == 32) ? 0xFFFFFFFFU : (1 << pbmradix) - 1;
576 		while ((pbmmask & bmmask) == 0)
577 			pbmmask <<= pbmradix;
578 
579 #if 0
580 		kprintf("%016jx mask %08x %08x %08x (%zd/%zd)\n",
581 			*basep + offset, bmap->bitmap[i],
582 			pbmmask, bmmask, size, psize);
583 #endif
584 
585 		if ((bmap->bitmap[i] & pbmmask) == 0) {
586 			error = hammer2_io_newq(hmp,
587 						(*basep + (offset & ~pmask)) |
588 						 pradix,
589 						psize, &dio);
590 			hammer2_io_bqrelse(&dio);
591 		}
592 	}
593 
594 #if 0
595 	/*
596 	 * When initializing a new inode segment also attempt to initialize
597 	 * an adjacent segment.  Be careful not to index beyond the array
598 	 * bounds.
599 	 *
600 	 * We do this to try to localize inode accesses to improve
601 	 * directory scan rates.  XXX doesn't improve scan rates.
602 	 */
603 	if (size == HAMMER2_INODE_BYTES) {
604 		if (n & 1) {
605 			if (bmap[-1].radix == 0 && bmap[-1].avail)
606 				bmap[-1].radix = radix;
607 		} else {
608 			if (bmap[1].radix == 0 && bmap[1].avail)
609 				bmap[1].radix = radix;
610 		}
611 	}
612 #endif
613 
614 	/*
615 	 * Adjust the linear iterator, set the radix if necessary (might as
616 	 * well just set it unconditionally), adjust *basep to return the
617 	 * allocated data offset.
618 	 */
619 	bmap->bitmap[i] |= bmmask;
620 	bmap->class = class;
621 	bmap->avail -= size;
622 	*basep += offset;
623 
624 	hammer2_voldata_lock(hmp);
625 	hammer2_voldata_modify(hmp);
626 	hmp->voldata.allocator_free -= size;  /* XXX */
627 	hammer2_voldata_unlock(hmp);
628 
629 	return(0);
630 }
631 
632 static
633 void
634 hammer2_freemap_init(hammer2_trans_t *trans, hammer2_mount_t *hmp,
635 		     hammer2_key_t key, hammer2_chain_t *chain)
636 {
637 	hammer2_off_t l1size;
638 	hammer2_off_t lokey;
639 	hammer2_off_t hikey;
640 	hammer2_bmap_data_t *bmap;
641 	int count;
642 
643 	l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
644 
645 	/*
646 	 * Calculate the portion of the 2GB map that should be initialized
647 	 * as free.  Portions below or after will be initialized as allocated.
648 	 * SEGMASK-align the areas so we don't have to worry about sub-scans
649 	 * or endianess when using memset.
650 	 *
651 	 * (1) Ensure that all statically allocated space from newfs_hammer2
652 	 *     is marked allocated.
653 	 *
654 	 * (2) Ensure that the reserved area is marked allocated (typically
655 	 *     the first 4MB of the 2GB area being represented).
656 	 *
657 	 * (3) Ensure that any trailing space at the end-of-volume is marked
658 	 *     allocated.
659 	 *
660 	 * WARNING! It is possible for lokey to be larger than hikey if the
661 	 *	    entire 2GB segment is within the static allocation.
662 	 */
663 	lokey = (hmp->voldata.allocator_beg + HAMMER2_SEGMASK64) &
664 		~HAMMER2_SEGMASK64;
665 
666 	if (lokey < H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
667 		  HAMMER2_ZONE_SEG64) {
668 		lokey = H2FMBASE(key, HAMMER2_FREEMAP_LEVEL1_RADIX) +
669 			HAMMER2_ZONE_SEG64;
670 	}
671 
672 	hikey = key + H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
673 	if (hikey > hmp->voldata.volu_size) {
674 		hikey = hmp->voldata.volu_size & ~HAMMER2_SEGMASK64;
675 	}
676 
677 	chain->bref.check.freemap.avail =
678 		H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
679 	bmap = &chain->data->bmdata[0];
680 
681 	for (count = 0; count < HAMMER2_FREEMAP_COUNT; ++count) {
682 		if (key < lokey || key >= hikey) {
683 			memset(bmap->bitmap, -1,
684 			       sizeof(bmap->bitmap));
685 			bmap->avail = 0;
686 			bmap->linear = HAMMER2_SEGSIZE;
687 			chain->bref.check.freemap.avail -=
688 				H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
689 		} else {
690 			bmap->avail = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
691 		}
692 		key += H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
693 		++bmap;
694 	}
695 }
696 
697 /*
698  * The current Level 1 freemap has been exhausted, iterate to the next
699  * one, return ENOSPC if no freemaps remain.
700  *
701  * XXX this should rotate back to the beginning to handle freed-up space
702  * XXX or use intermediate entries to locate free space. TODO
703  */
704 static int
705 hammer2_freemap_iterate(hammer2_trans_t *trans, hammer2_chain_t **parentp,
706 			hammer2_chain_t **chainp, hammer2_fiterate_t *iter)
707 {
708 	hammer2_mount_t *hmp = (*parentp)->hmp;
709 
710 	iter->bnext &= ~(H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX) - 1);
711 	iter->bnext += H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
712 	if (iter->bnext >= hmp->voldata.volu_size) {
713 		iter->bnext = 0;
714 		if (++iter->loops == 2)
715 			return (ENOSPC);
716 	}
717 	return(EAGAIN);
718 }
719 
720 /*
721  * Adjust the bit-pattern for data in the freemap bitmap according to
722  * (how).  This code is called from on-mount recovery to fixup (mark
723  * as allocated) blocks whos freemap upates might not have been committed
724  * in the last crash and is used by the bulk freemap scan to stage frees.
725  *
726  * XXX currently disabled when how == 0 (the normal real-time case).  At
727  * the moment we depend on the bulk freescan to actually free blocks.  It
728  * will still call this routine with a non-zero how to stage possible frees
729  * and to do the actual free.
730  */
731 void
732 hammer2_freemap_adjust(hammer2_trans_t *trans, hammer2_mount_t *hmp,
733 		       hammer2_blockref_t *bref, int how)
734 {
735 	hammer2_off_t data_off = bref->data_off;
736 	hammer2_chain_t *chain;
737 	hammer2_chain_t *parent;
738 	hammer2_bmap_data_t *bmap;
739 	hammer2_key_t key;
740 	hammer2_key_t key_dummy;
741 	hammer2_off_t l0size;
742 	hammer2_off_t l1size;
743 	hammer2_off_t l1mask;
744 	uint32_t *bitmap;
745 	const uint32_t bmmask00 = 0;
746 	uint32_t bmmask01;
747 	uint32_t bmmask10;
748 	uint32_t bmmask11;
749 	size_t bytes;
750 	uint16_t class;
751 	int radix;
752 	int start;
753 	int count;
754 	int modified = 0;
755 	int cache_index = -1;
756 	int error;
757 	int ddflag;
758 
759 	radix = (int)data_off & HAMMER2_OFF_MASK_RADIX;
760 	data_off &= ~HAMMER2_OFF_MASK_RADIX;
761 	KKASSERT(radix <= HAMMER2_RADIX_MAX);
762 
763 	bytes = (size_t)1 << radix;
764 	class = (bref->type << 8) | hammer2_devblkradix(radix);
765 
766 	/*
767 	 * We can't adjust thre freemap for data allocations made by
768 	 * newfs_hammer2.
769 	 */
770 	if (data_off < hmp->voldata.allocator_beg)
771 		return;
772 
773 	KKASSERT((data_off & HAMMER2_ZONE_MASK64) >= HAMMER2_ZONE_SEG);
774 
775 	/*
776 	 * Lookup the level1 freemap chain.  The chain must exist.
777 	 */
778 	key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL1_RADIX);
779 	l0size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL0_RADIX);
780 	l1size = H2FMSHIFT(HAMMER2_FREEMAP_LEVEL1_RADIX);
781 	l1mask = l1size - 1;
782 
783 	parent = &hmp->fchain;
784 	hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
785 
786 	chain = hammer2_chain_lookup(&parent, &key_dummy, key, key + l1mask,
787 				     &cache_index,
788 				     HAMMER2_LOOKUP_ALWAYS |
789 				     HAMMER2_LOOKUP_MATCHIND, &ddflag);
790 
791 	/*
792 	 * Stop early if we are trying to free something but no leaf exists.
793 	 */
794 	if (chain == NULL && how != HAMMER2_FREEMAP_DORECOVER) {
795 		kprintf("hammer2_freemap_adjust: %016jx: no chain\n",
796 			(intmax_t)bref->data_off);
797 		goto done;
798 	}
799 
800 	/*
801 	 * Create any missing leaf(s) if we are doing a recovery (marking
802 	 * the block(s) as being allocated instead of being freed).  Be sure
803 	 * to initialize the auxillary freemap tracking info in the
804 	 * bref.check.freemap structure.
805 	 */
806 	if (chain == NULL && how == HAMMER2_FREEMAP_DORECOVER) {
807 		error = hammer2_chain_create(trans, &parent, &chain, hmp->spmp,
808 				     key, HAMMER2_FREEMAP_LEVEL1_RADIX,
809 				     HAMMER2_BREF_TYPE_FREEMAP_LEAF,
810 				     HAMMER2_FREEMAP_LEVELN_PSIZE);
811 
812 		if (hammer2_debug & 0x0040) {
813 			kprintf("fixup create chain %p %016jx:%d\n",
814 				chain, chain->bref.key, chain->bref.keybits);
815 		}
816 
817 		if (error == 0) {
818 			hammer2_chain_modify(trans, &chain, 0);
819 			bzero(&chain->data->bmdata[0],
820 			      HAMMER2_FREEMAP_LEVELN_PSIZE);
821 			chain->bref.check.freemap.bigmask = (uint32_t)-1;
822 			chain->bref.check.freemap.avail = l1size;
823 			/* bref.methods should already be inherited */
824 
825 			hammer2_freemap_init(trans, hmp, key, chain);
826 		}
827 		/* XXX handle error */
828 	}
829 
830 #if FREEMAP_DEBUG
831 	kprintf("FREEMAP ADJUST TYPE %d %016jx/%d DATA_OFF=%016jx\n",
832 		chain->bref.type, chain->bref.key,
833 		chain->bref.keybits, chain->bref.data_off);
834 #endif
835 
836 	/*
837 	 * Calculate the bitmask (runs in 2-bit pairs).
838 	 */
839 	start = ((int)(data_off >> HAMMER2_FREEMAP_BLOCK_RADIX) & 15) * 2;
840 	bmmask01 = 1 << start;
841 	bmmask10 = 2 << start;
842 	bmmask11 = 3 << start;
843 
844 	/*
845 	 * Fixup the bitmap.  Partial blocks cannot be fully freed unless
846 	 * a bulk scan is able to roll them up.
847 	 */
848 	if (radix < HAMMER2_FREEMAP_BLOCK_RADIX) {
849 		count = 1;
850 		if (how == HAMMER2_FREEMAP_DOREALFREE)
851 			how = HAMMER2_FREEMAP_DOMAYFREE;
852 	} else {
853 		count = 1 << (radix - HAMMER2_FREEMAP_BLOCK_RADIX);
854 	}
855 
856 	/*
857 	 * [re]load the bmap and bitmap pointers.  Each bmap entry covers
858 	 * a 2MB swath.  The bmap itself (LEVEL1) covers 2GB.
859 	 *
860 	 * Be sure to reset the linear iterator to ensure that the adjustment
861 	 * is not ignored.
862 	 */
863 again:
864 	bmap = &chain->data->bmdata[(int)(data_off >> HAMMER2_SEGRADIX) &
865 				    (HAMMER2_FREEMAP_COUNT - 1)];
866 	bitmap = &bmap->bitmap[(int)(data_off >> (HAMMER2_SEGRADIX - 3)) & 7];
867 	bmap->linear = 0;
868 
869 	while (count) {
870 		KKASSERT(bmmask11);
871 		if (how == HAMMER2_FREEMAP_DORECOVER) {
872 			/*
873 			 * Recovery request, mark as allocated.
874 			 */
875 			if ((*bitmap & bmmask11) != bmmask11) {
876 				if (modified == 0) {
877 					hammer2_chain_modify(trans, &chain, 0);
878 					modified = 1;
879 					goto again;
880 				}
881 				if ((*bitmap & bmmask11) == bmmask00)
882 					bmap->avail -= 1 << radix;
883 				if (bmap->class == 0)
884 					bmap->class = class;
885 				*bitmap |= bmmask11;
886 				if (hammer2_debug & 0x0040) {
887 					kprintf("hammer2_freemap_recover: "
888 						"fixup type=%02x "
889 						"block=%016jx/%zd\n",
890 						bref->type, data_off, bytes);
891 				}
892 			} else {
893 				/*
894 				kprintf("hammer2_freemap_recover:  good "
895 					"type=%02x block=%016jx/%zd\n",
896 					bref->type, data_off, bytes);
897 				*/
898 			}
899 		} else if ((*bitmap & bmmask11) == bmmask11) {
900 			/*
901 			 * Mayfree/Realfree request and bitmap is currently
902 			 * marked as being fully allocated.
903 			 */
904 			if (!modified) {
905 				hammer2_chain_modify(trans, &chain, 0);
906 				modified = 1;
907 				goto again;
908 			}
909 			if (how == HAMMER2_FREEMAP_DOREALFREE)
910 				*bitmap &= ~bmmask11;
911 			else
912 				*bitmap = (*bitmap & ~bmmask11) | bmmask10;
913 		} else if ((*bitmap & bmmask11) == bmmask10) {
914 			/*
915 			 * Mayfree/Realfree request and bitmap is currently
916 			 * marked as being possibly freeable.
917 			 */
918 			if (how == HAMMER2_FREEMAP_DOREALFREE) {
919 				if (!modified) {
920 					hammer2_chain_modify(trans, &chain, 0);
921 					modified = 1;
922 					goto again;
923 				}
924 				*bitmap &= ~bmmask11;
925 			}
926 		} else {
927 			/*
928 			 * 01 - Not implemented, currently illegal state
929 			 * 00 - Not allocated at all, illegal free.
930 			 */
931 			panic("hammer2_freemap_adjust: "
932 			      "Illegal state %08x(%08x)",
933 			      *bitmap, *bitmap & bmmask11);
934 		}
935 		--count;
936 		bmmask01 <<= 2;
937 		bmmask10 <<= 2;
938 		bmmask11 <<= 2;
939 	}
940 	if (how == HAMMER2_FREEMAP_DOREALFREE && modified) {
941 		bmap->avail += 1 << radix;
942 		KKASSERT(bmap->avail <= HAMMER2_SEGSIZE);
943 		if (bmap->avail == HAMMER2_SEGSIZE &&
944 		    bmap->bitmap[0] == 0 &&
945 		    bmap->bitmap[1] == 0 &&
946 		    bmap->bitmap[2] == 0 &&
947 		    bmap->bitmap[3] == 0 &&
948 		    bmap->bitmap[4] == 0 &&
949 		    bmap->bitmap[5] == 0 &&
950 		    bmap->bitmap[6] == 0 &&
951 		    bmap->bitmap[7] == 0) {
952 			key = H2FMBASE(data_off, HAMMER2_FREEMAP_LEVEL0_RADIX);
953 			kprintf("Freeseg %016jx\n", (intmax_t)key);
954 			bmap->class = 0;
955 		}
956 	}
957 
958 	/*
959 	 * chain->bref.check.freemap.bigmask (XXX)
960 	 *
961 	 * Setting bigmask is a hint to the allocation code that there might
962 	 * be something allocatable.  We also set this in recovery... it
963 	 * doesn't hurt and we might want to use the hint for other validation
964 	 * operations later on.
965 	 */
966 	if (modified)
967 		chain->bref.check.freemap.bigmask |= 1 << radix;
968 
969 	hammer2_chain_unlock(chain);
970 done:
971 	hammer2_chain_unlock(parent);
972 }
973