xref: /freebsd/contrib/jemalloc/src/rtree.c (revision e39e854e27f53a784c3982cbeb68f4ad1cfd9162)
1 #define	JEMALLOC_RTREE_C_
2 #include "jemalloc/internal/jemalloc_internal.h"
3 
4 rtree_t *
5 rtree_new(unsigned bits)
6 {
7 	rtree_t *ret;
8 	unsigned bits_per_level, height, i;
9 
10 	bits_per_level = ffs(pow2_ceil((RTREE_NODESIZE / sizeof(void *)))) - 1;
11 	height = bits / bits_per_level;
12 	if (height * bits_per_level != bits)
13 		height++;
14 	assert(height * bits_per_level >= bits);
15 
16 	ret = (rtree_t*)base_alloc(offsetof(rtree_t, level2bits) +
17 	    (sizeof(unsigned) * height));
18 	if (ret == NULL)
19 		return (NULL);
20 	memset(ret, 0, offsetof(rtree_t, level2bits) + (sizeof(unsigned) *
21 	    height));
22 
23 	if (malloc_mutex_init(&ret->mutex)) {
24 		/* Leak the rtree. */
25 		return (NULL);
26 	}
27 	ret->height = height;
28 	if (bits_per_level * height > bits)
29 		ret->level2bits[0] = bits % bits_per_level;
30 	else
31 		ret->level2bits[0] = bits_per_level;
32 	for (i = 1; i < height; i++)
33 		ret->level2bits[i] = bits_per_level;
34 
35 	ret->root = (void**)base_alloc(sizeof(void *) << ret->level2bits[0]);
36 	if (ret->root == NULL) {
37 		/*
38 		 * We leak the rtree here, since there's no generic base
39 		 * deallocation.
40 		 */
41 		return (NULL);
42 	}
43 	memset(ret->root, 0, sizeof(void *) << ret->level2bits[0]);
44 
45 	return (ret);
46 }
47