1 // SPDX-License-Identifier: GPL-2.0
10 #include <linux/poison.h>
11 #include <linux/slab.h>
12 #include <linux/radix-tree.h>
13 #include <urcu/uatomic.h>
29 void *kmem_cache_alloc(struct kmem_cache
*cachep
, int gfp
)
33 if (!(gfp
& __GFP_DIRECT_RECLAIM
))
36 pthread_mutex_lock(&cachep
->lock
);
37 if (cachep
->nr_objs
) {
38 struct radix_tree_node
*node
= cachep
->objs
;
40 cachep
->objs
= node
->parent
;
41 pthread_mutex_unlock(&cachep
->lock
);
45 pthread_mutex_unlock(&cachep
->lock
);
47 posix_memalign(&p
, cachep
->align
, cachep
->size
);
49 p
= malloc(cachep
->size
);
52 else if (gfp
& __GFP_ZERO
)
53 memset(p
, 0, cachep
->size
);
56 uatomic_inc(&nr_allocated
);
58 printf("Allocating %p from slab\n", p
);
62 void kmem_cache_free(struct kmem_cache
*cachep
, void *objp
)
65 uatomic_dec(&nr_allocated
);
67 printf("Freeing %p to slab\n", objp
);
68 pthread_mutex_lock(&cachep
->lock
);
69 if (cachep
->nr_objs
> 10 || cachep
->align
) {
70 memset(objp
, POISON_FREE
, cachep
->size
);
73 struct radix_tree_node
*node
= objp
;
75 node
->parent
= cachep
->objs
;
78 pthread_mutex_unlock(&cachep
->lock
);
81 void *kmalloc(size_t size
, gfp_t gfp
)
85 if (!(gfp
& __GFP_DIRECT_RECLAIM
))
89 uatomic_inc(&nr_allocated
);
91 printf("Allocating %p from malloc\n", ret
);
101 uatomic_dec(&nr_allocated
);
103 printf("Freeing %p to malloc\n", p
);
108 kmem_cache_create(const char *name
, unsigned int size
, unsigned int align
,
109 unsigned int flags
, void (*ctor
)(void *))
111 struct kmem_cache
*ret
= malloc(sizeof(*ret
));
113 pthread_mutex_init(&ret
->lock
, NULL
);