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