smalloc: unlink pool file in add_pool()
[fio.git] / smalloc.c
1 /*
2  * simple memory allocator, backed by mmap() so that it hands out memory
3  * that can be shared across processes and threads
4  */
5 #include <sys/mman.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <assert.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <sys/types.h>
12 #include <limits.h>
13
14 #include "mutex.h"
15 #include "arch/arch.h"
16
17 #define MP_SAFE                 /* define to make thread safe */
18 #define SMALLOC_REDZONE         /* define to detect memory corruption */
19
20 #define SMALLOC_BPB     32      /* block size, bytes-per-bit in bitmap */
21 #define SMALLOC_BPI     (sizeof(unsigned int) * 8)
22 #define SMALLOC_BPL     (SMALLOC_BPB * SMALLOC_BPI)
23
24 #define INITIAL_SIZE    1024*1024       /* new pool size */
25 #define MAX_POOLS       128             /* maximum number of pools to setup */
26
27 #define SMALLOC_PRE_RED         0xdeadbeefU
28 #define SMALLOC_POST_RED        0x5aa55aa5U
29
30 unsigned int smalloc_pool_size = INITIAL_SIZE;
31
32 struct pool {
33         struct fio_mutex *lock;                 /* protects this pool */
34         void *map;                              /* map of blocks */
35         unsigned int *bitmap;                   /* blocks free/busy map */
36         unsigned int free_blocks;               /* free blocks */
37         unsigned int nr_blocks;                 /* total blocks */
38         unsigned int next_non_full;
39         int fd;                                 /* memory backing fd */
40         char file[PATH_MAX];                    /* filename for fd */
41         unsigned int mmap_size;
42 };
43
44 struct block_hdr {
45         unsigned int size;
46 #ifdef SMALLOC_REDZONE
47         unsigned int prered;
48 #endif
49 };
50
51 static struct pool mp[MAX_POOLS];
52 static unsigned int nr_pools;
53 static unsigned int last_pool;
54 static struct fio_mutex *lock;
55
56 static inline void pool_lock(struct pool *pool)
57 {
58         if (pool->lock)
59                 fio_mutex_down(pool->lock);
60 }
61
62 static inline void pool_unlock(struct pool *pool)
63 {
64         if (pool->lock)
65                 fio_mutex_up(pool->lock);
66 }
67
68 static inline void global_read_lock(void)
69 {
70         if (lock)
71                 fio_mutex_down_read(lock);
72 }
73
74 static inline void global_read_unlock(void)
75 {
76         if (lock)
77                 fio_mutex_up_read(lock);
78 }
79
80 static inline void global_write_lock(void)
81 {
82         if (lock)
83                 fio_mutex_down_write(lock);
84 }
85
86 static inline void global_write_unlock(void)
87 {
88         if (lock)
89                 fio_mutex_up_write(lock);
90 }
91
92 static inline int ptr_valid(struct pool *pool, void *ptr)
93 {
94         unsigned int pool_size = pool->nr_blocks * SMALLOC_BPL;
95
96         return (ptr >= pool->map) && (ptr < pool->map + pool_size);
97 }
98
99 static inline unsigned int size_to_blocks(unsigned int size)
100 {
101         return (size + SMALLOC_BPB - 1) / SMALLOC_BPB;
102 }
103
104 static int blocks_iter(struct pool *pool, unsigned int pool_idx,
105                        unsigned int idx, unsigned int nr_blocks,
106                        int (*func)(unsigned int *map, unsigned int mask))
107 {
108
109         while (nr_blocks) {
110                 unsigned int this_blocks, mask;
111                 unsigned int *map;
112
113                 if (pool_idx >= pool->nr_blocks)
114                         return 0;
115
116                 map = &pool->bitmap[pool_idx];
117
118                 this_blocks = nr_blocks;
119                 if (this_blocks + idx > SMALLOC_BPI) {
120                         this_blocks = SMALLOC_BPI - idx;
121                         idx = SMALLOC_BPI - this_blocks;
122                 }
123
124                 if (this_blocks == SMALLOC_BPI)
125                         mask = -1U;
126                 else
127                         mask = ((1U << this_blocks) - 1) << idx;
128
129                 if (!func(map, mask))
130                         return 0;
131
132                 nr_blocks -= this_blocks;
133                 idx = 0;
134                 pool_idx++;
135         }
136
137         return 1;
138 }
139
140 static int mask_cmp(unsigned int *map, unsigned int mask)
141 {
142         return !(*map & mask);
143 }
144
145 static int mask_clear(unsigned int *map, unsigned int mask)
146 {
147         assert((*map & mask) == mask);
148         *map &= ~mask;
149         return 1;
150 }
151
152 static int mask_set(unsigned int *map, unsigned int mask)
153 {
154         assert(!(*map & mask));
155         *map |= mask;
156         return 1;
157 }
158
159 static int blocks_free(struct pool *pool, unsigned int pool_idx,
160                        unsigned int idx, unsigned int nr_blocks)
161 {
162         return blocks_iter(pool, pool_idx, idx, nr_blocks, mask_cmp);
163 }
164
165 static void set_blocks(struct pool *pool, unsigned int pool_idx,
166                        unsigned int idx, unsigned int nr_blocks)
167 {
168         blocks_iter(pool, pool_idx, idx, nr_blocks, mask_set);
169 }
170
171 static void clear_blocks(struct pool *pool, unsigned int pool_idx,
172                          unsigned int idx, unsigned int nr_blocks)
173 {
174         blocks_iter(pool, pool_idx, idx, nr_blocks, mask_clear);
175 }
176
177 static int find_next_zero(int word, int start)
178 {
179         assert(word != -1U);
180         word >>= (start + 1);
181         return ffz(word) + start + 1;
182 }
183
184 static int add_pool(struct pool *pool, unsigned int alloc_size)
185 {
186         void *ptr;
187         int fd, bitmap_blocks;
188
189         strcpy(pool->file, "/tmp/.fio_smalloc.XXXXXX");
190         fd = mkstemp(pool->file);
191         if (fd < 0)
192                 goto out_close;
193
194 #ifdef SMALLOC_REDZONE
195         alloc_size += sizeof(unsigned int);
196 #endif
197         alloc_size += sizeof(struct block_hdr);
198         if (alloc_size < INITIAL_SIZE)
199                 alloc_size = INITIAL_SIZE;
200
201         /* round up to nearest full number of blocks */
202         alloc_size = (alloc_size + SMALLOC_BPL - 1) & ~(SMALLOC_BPL - 1);
203         bitmap_blocks = alloc_size / SMALLOC_BPL;
204         alloc_size += bitmap_blocks * sizeof(unsigned int);
205         pool->mmap_size = alloc_size;
206         
207         pool->nr_blocks = bitmap_blocks;
208         pool->free_blocks = bitmap_blocks * SMALLOC_BPB;
209
210         if (ftruncate(fd, alloc_size) < 0)
211                 goto out_unlink;
212
213         ptr = mmap(NULL, alloc_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
214         if (ptr == MAP_FAILED)
215                 goto out_unlink;
216
217         memset(ptr, 0, alloc_size);
218         pool->map = ptr;
219         pool->bitmap = (void *) ptr + (pool->nr_blocks * SMALLOC_BPL);
220
221 #ifdef MP_SAFE
222         pool->lock = fio_mutex_init(1);
223         if (!pool->lock)
224                 goto out_unlink;
225 #endif
226
227         /*
228          * Unlink pool file now. It wont get deleted until the fd is closed,
229          * which happens both for cleanup or unexpected quit. This way we
230          * don't leave temp files around in case of a crash.
231          */
232         pool->fd = fd;
233         unlink(pool->file);
234
235         nr_pools++;
236         return 0;
237 out_unlink:
238         fprintf(stderr, "smalloc: failed adding pool\n");
239         if (pool->map)
240                 munmap(pool->map, pool->mmap_size);
241         unlink(pool->file);
242 out_close:
243         if (fd >= 0)
244                 close(fd);
245         return 1;
246 }
247
248 void sinit(void)
249 {
250         int ret;
251
252 #ifdef MP_SAFE
253         lock = fio_mutex_rw_init();
254 #endif
255         ret = add_pool(&mp[0], INITIAL_SIZE);
256         assert(!ret);
257 }
258
259 static void cleanup_pool(struct pool *pool)
260 {
261         /*
262          * This will also remove the temporary file we used as a backing
263          * store, it was already unlinked
264          */
265         close(pool->fd);
266         munmap(pool->map, pool->mmap_size);
267
268         if (pool->lock)
269                 fio_mutex_remove(pool->lock);
270 }
271
272 void scleanup(void)
273 {
274         unsigned int i;
275
276         for (i = 0; i < nr_pools; i++)
277                 cleanup_pool(&mp[i]);
278
279         if (lock)
280                 fio_mutex_remove(lock);
281 }
282
283 #ifdef SMALLOC_REDZONE
284 static void fill_redzone(struct block_hdr *hdr)
285 {
286         unsigned int *postred = (void *) hdr + hdr->size - sizeof(unsigned int);
287
288         hdr->prered = SMALLOC_PRE_RED;
289         *postred = SMALLOC_POST_RED;
290 }
291
292 static void sfree_check_redzone(struct block_hdr *hdr)
293 {
294         unsigned int *postred = (void *) hdr + hdr->size - sizeof(unsigned int);
295
296         if (hdr->prered != SMALLOC_PRE_RED) {
297                 fprintf(stderr, "smalloc pre redzone destroyed!\n");
298                 fprintf(stderr, "  ptr=%p, prered=%x, expected %x\n",
299                                 hdr, hdr->prered, SMALLOC_PRE_RED);
300                 assert(0);
301         }
302         if (*postred != SMALLOC_POST_RED) {
303                 fprintf(stderr, "smalloc post redzone destroyed!\n");
304                 fprintf(stderr, "  ptr=%p, postred=%x, expected %x\n",
305                                 hdr, *postred, SMALLOC_POST_RED);
306                 assert(0);
307         }
308 }
309 #else
310 static void fill_redzone(struct block_hdr *hdr)
311 {
312 }
313
314 static void sfree_check_redzone(struct block_hdr *hdr)
315 {
316 }
317 #endif
318
319 static void sfree_pool(struct pool *pool, void *ptr)
320 {
321         struct block_hdr *hdr;
322         unsigned int i, idx;
323         unsigned long offset;
324
325         if (!ptr)
326                 return;
327
328         ptr -= sizeof(*hdr);
329         hdr = ptr;
330
331         assert(ptr_valid(pool, ptr));
332
333         sfree_check_redzone(hdr);
334
335         offset = ptr - pool->map;
336         i = offset / SMALLOC_BPL;
337         idx = (offset % SMALLOC_BPL) / SMALLOC_BPB;
338
339         pool_lock(pool);
340         clear_blocks(pool, i, idx, size_to_blocks(hdr->size));
341         if (i < pool->next_non_full)
342                 pool->next_non_full = i;
343         pool->free_blocks += size_to_blocks(hdr->size);
344         pool_unlock(pool);
345 }
346
347 void sfree(void *ptr)
348 {
349         struct pool *pool = NULL;
350         unsigned int i;
351
352         if (!ptr)
353                 return;
354
355         global_read_lock();
356
357         for (i = 0; i < nr_pools; i++) {
358                 if (ptr_valid(&mp[i], ptr)) {
359                         pool = &mp[i];
360                         break;
361                 }
362         }
363
364         global_read_unlock();
365
366         assert(pool);
367         sfree_pool(pool, ptr);
368 }
369
370 static void *__smalloc_pool(struct pool *pool, unsigned int size)
371 {
372         unsigned int nr_blocks;
373         unsigned int i;
374         unsigned int offset;
375         unsigned int last_idx;
376         void *ret = NULL;
377
378         pool_lock(pool);
379
380         nr_blocks = size_to_blocks(size);
381         if (nr_blocks > pool->free_blocks)
382                 goto fail;
383
384         i = pool->next_non_full;
385         last_idx = 0;
386         offset = -1U;
387         while (i < pool->nr_blocks) {
388                 unsigned int idx;
389
390                 if (pool->bitmap[i] == -1U) {
391                         i++;
392                         pool->next_non_full = i;
393                         last_idx = 0;
394                         continue;
395                 }
396
397                 idx = find_next_zero(pool->bitmap[i], last_idx);
398                 if (!blocks_free(pool, i, idx, nr_blocks)) {
399                         idx += nr_blocks;
400                         if (idx < SMALLOC_BPI)
401                                 last_idx = idx;
402                         else {
403                                 last_idx = 0;
404                                 while (idx >= SMALLOC_BPI) {
405                                         i++;
406                                         idx -= SMALLOC_BPI;
407                                 }
408                         }
409                         continue;
410                 }
411                 set_blocks(pool, i, idx, nr_blocks);
412                 offset = i * SMALLOC_BPL + idx * SMALLOC_BPB;
413                 break;
414         }
415
416         if (i < pool->nr_blocks) {
417                 pool->free_blocks -= nr_blocks;
418                 ret = pool->map + offset;
419         }
420 fail:
421         pool_unlock(pool);
422         return ret;
423 }
424
425 static void *smalloc_pool(struct pool *pool, unsigned int size)
426 {
427         unsigned int alloc_size = size + sizeof(struct block_hdr);
428         void *ptr;
429
430 #ifdef SMALLOC_REDZONE
431         alloc_size += sizeof(unsigned int);
432 #endif
433
434         ptr = __smalloc_pool(pool, alloc_size);
435         if (ptr) {
436                 struct block_hdr *hdr = ptr;
437
438                 hdr->size = alloc_size;
439                 fill_redzone(hdr);
440
441                 ptr += sizeof(*hdr);
442                 memset(ptr, 0, size);
443         }
444
445         return ptr;
446 }
447
448 void *smalloc(unsigned int size)
449 {
450         unsigned int i;
451
452         global_write_lock();
453         i = last_pool;
454
455         do {
456                 for (; i < nr_pools; i++) {
457                         void *ptr = smalloc_pool(&mp[i], size);
458
459                         if (ptr) {
460                                 last_pool = i;
461                                 global_write_unlock();
462                                 return ptr;
463                         }
464                 }
465                 if (last_pool) {
466                         last_pool = 0;
467                         continue;
468                 }
469
470                 if (nr_pools + 1 > MAX_POOLS)
471                         break;
472                 else {
473                         i = nr_pools;
474                         if (add_pool(&mp[nr_pools], size))
475                                 goto out;
476                 }
477         } while (1);
478
479 out:
480         global_write_unlock();
481         return NULL;
482 }
483
484 char *smalloc_strdup(const char *str)
485 {
486         char *ptr;
487
488         ptr = smalloc(strlen(str) + 1);
489         strcpy(ptr, str);
490         return ptr;
491 }