]> git.ipfire.org Git - thirdparty/xfsprogs-dev.git/blob - libxfs/kmem.c
42d813088d6ada92842f5ce0fd3c6a5fb9533cd9
[thirdparty/xfsprogs-dev.git] / libxfs / kmem.c
1 // SPDX-License-Identifier: GPL-2.0
2
3
4 #include "libxfs_priv.h"
5
6 /*
7 * Simple memory interface
8 */
9 struct kmem_cache *
10 kmem_cache_create(const char *name, unsigned int size, unsigned int align,
11 unsigned int slab_flags, void (*ctor)(void *))
12 {
13 struct kmem_cache *ptr = malloc(sizeof(struct kmem_cache));
14
15 if (ptr == NULL) {
16 fprintf(stderr, _("%s: cache init failed (%s, %d bytes): %s\n"),
17 progname, name, (int)sizeof(struct kmem_cache),
18 strerror(errno));
19 exit(1);
20 }
21 ptr->cache_unitsize = size;
22 ptr->cache_name = name;
23 ptr->allocated = 0;
24 ptr->align = align;
25 ptr->ctor = ctor;
26
27 return ptr;
28 }
29
30 int
31 kmem_cache_destroy(struct kmem_cache *cache)
32 {
33 int leaked = 0;
34
35 if (getenv("LIBXFS_LEAK_CHECK") && cache->allocated) {
36 leaked = 1;
37 fprintf(stderr, "cache %s freed with %d items allocated\n",
38 cache->cache_name, cache->allocated);
39 }
40 free(cache);
41 return leaked;
42 }
43
44 void *
45 kmem_cache_alloc(struct kmem_cache *cache, gfp_t flags)
46 {
47 void *ptr = malloc(cache->cache_unitsize);
48
49 if (ptr == NULL) {
50 fprintf(stderr, _("%s: cache alloc failed (%s, %d bytes): %s\n"),
51 progname, cache->cache_name, cache->cache_unitsize,
52 strerror(errno));
53 exit(1);
54 }
55 cache->allocated++;
56 return ptr;
57 }
58
59 void *
60 kmem_cache_zalloc(struct kmem_cache *cache, gfp_t flags)
61 {
62 void *ptr = kmem_cache_alloc(cache, flags);
63
64 memset(ptr, 0, cache->cache_unitsize);
65 return ptr;
66 }
67
68 void *
69 kmem_alloc(size_t size, int flags)
70 {
71 void *ptr = malloc(size);
72
73 if (ptr == NULL) {
74 fprintf(stderr, _("%s: malloc failed (%d bytes): %s\n"),
75 progname, (int)size, strerror(errno));
76 exit(1);
77 }
78 return ptr;
79 }
80
81 void *
82 kvmalloc(size_t size, gfp_t flags)
83 {
84 if (flags & __GFP_ZERO)
85 return kmem_zalloc(size, 0);
86 return kmem_alloc(size, 0);
87 }
88
89 void *
90 kmem_zalloc(size_t size, int flags)
91 {
92 void *ptr = kmem_alloc(size, flags);
93
94 memset(ptr, 0, size);
95 return ptr;
96 }
97
98 void *
99 krealloc(void *ptr, size_t new_size, int flags)
100 {
101 ptr = realloc(ptr, new_size);
102 if (ptr == NULL) {
103 fprintf(stderr, _("%s: realloc failed (%d bytes): %s\n"),
104 progname, (int)new_size, strerror(errno));
105 exit(1);
106 }
107 return ptr;
108 }