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>
28 void *kmem_cache_alloc(struct kmem_cache
*cachep
, int flags
)
30 struct radix_tree_node
*node
;
32 if (!(flags
& __GFP_DIRECT_RECLAIM
))
35 pthread_mutex_lock(&cachep
->lock
);
36 if (cachep
->nr_objs
) {
39 cachep
->objs
= node
->parent
;
40 pthread_mutex_unlock(&cachep
->lock
);
43 pthread_mutex_unlock(&cachep
->lock
);
44 node
= malloc(cachep
->size
);
49 uatomic_inc(&nr_allocated
);
51 printf("Allocating %p from slab\n", node
);
55 void kmem_cache_free(struct kmem_cache
*cachep
, void *objp
)
58 uatomic_dec(&nr_allocated
);
60 printf("Freeing %p to slab\n", objp
);
61 pthread_mutex_lock(&cachep
->lock
);
62 if (cachep
->nr_objs
> 10) {
63 memset(objp
, POISON_FREE
, cachep
->size
);
66 struct radix_tree_node
*node
= objp
;
68 node
->parent
= cachep
->objs
;
71 pthread_mutex_unlock(&cachep
->lock
);
74 void *kmalloc(size_t size
, gfp_t gfp
)
78 if (!(gfp
& __GFP_DIRECT_RECLAIM
))
82 uatomic_inc(&nr_allocated
);
84 printf("Allocating %p from malloc\n", ret
);
94 uatomic_dec(&nr_allocated
);
96 printf("Freeing %p to malloc\n", p
);
101 kmem_cache_create(const char *name
, size_t size
, size_t offset
,
102 unsigned long flags
, void (*ctor
)(void *))
104 struct kmem_cache
*ret
= malloc(sizeof(*ret
));
106 pthread_mutex_init(&ret
->lock
, NULL
);