os-mac.h: implement blockdev_size()
[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;
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         posix_fallocate(fd, 0, alloc_size);
207 #endif
208
209         if (ftruncate(fd, alloc_size) < 0)
210                 goto out_unlink;
211
212         ptr = mmap(NULL, alloc_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
213         if (ptr == MAP_FAILED)
214                 goto out_unlink;
215
216         memset(ptr, 0, alloc_size);
217         pool->map = ptr;
218         pool->bitmap = (void *) ptr + (pool->nr_blocks * SMALLOC_BPL);
219
220         pool->lock = fio_mutex_init(1);
221         if (!pool->lock)
222                 goto out_unlink;
223
224         /*
225          * Unlink pool file now. It wont get deleted until the fd is closed,
226          * which happens both for cleanup or unexpected quit. This way we
227          * don't leave temp files around in case of a crash.
228          */
229         unlink(file);
230         pool->fd = fd;
231
232         nr_pools++;
233         return 0;
234 out_unlink:
235         fprintf(stderr, "smalloc: failed adding pool\n");
236         if (pool->map)
237                 munmap(pool->map, pool->mmap_size);
238         unlink(file);
239 out_close:
240         close(fd);
241         return 1;
242 }
243
244 void sinit(void)
245 {
246         int ret;
247
248         lock = fio_mutex_rw_init();
249         ret = add_pool(&mp[0], INITIAL_SIZE);
250         assert(!ret);
251 }
252
253 static void cleanup_pool(struct pool *pool)
254 {
255         /*
256          * This will also remove the temporary file we used as a backing
257          * store, it was already unlinked
258          */
259         close(pool->fd);
260         munmap(pool->map, pool->mmap_size);
261
262         if (pool->lock)
263                 fio_mutex_remove(pool->lock);
264 }
265
266 void scleanup(void)
267 {
268         unsigned int i;
269
270         for (i = 0; i < nr_pools; i++)
271                 cleanup_pool(&mp[i]);
272
273         if (lock)
274                 fio_mutex_remove(lock);
275 }
276
277 #ifdef SMALLOC_REDZONE
278 static void *postred_ptr(struct block_hdr *hdr)
279 {
280         unsigned long ptr;
281
282         ptr = (unsigned long) hdr + hdr->size - sizeof(unsigned int);
283         ptr = (ptr + int_mask) & ~int_mask;
284
285         return (void *) ptr;
286 }
287
288 static void fill_redzone(struct block_hdr *hdr)
289 {
290         unsigned int *postred = postred_ptr(hdr);
291
292         hdr->prered = SMALLOC_PRE_RED;
293         *postred = SMALLOC_POST_RED;
294 }
295
296 static void sfree_check_redzone(struct block_hdr *hdr)
297 {
298         unsigned int *postred = postred_ptr(hdr);
299
300         if (hdr->prered != SMALLOC_PRE_RED) {
301                 fprintf(stderr, "smalloc pre redzone destroyed!\n");
302                 fprintf(stderr, "  ptr=%p, prered=%x, expected %x\n",
303                                 hdr, hdr->prered, SMALLOC_PRE_RED);
304                 assert(0);
305         }
306         if (*postred != SMALLOC_POST_RED) {
307                 fprintf(stderr, "smalloc post redzone destroyed!\n");
308                 fprintf(stderr, "  ptr=%p, postred=%x, expected %x\n",
309                                 hdr, *postred, SMALLOC_POST_RED);
310                 assert(0);
311         }
312 }
313 #else
314 static void fill_redzone(struct block_hdr *hdr)
315 {
316 }
317
318 static void sfree_check_redzone(struct block_hdr *hdr)
319 {
320 }
321 #endif
322
323 static void sfree_pool(struct pool *pool, void *ptr)
324 {
325         struct block_hdr *hdr;
326         unsigned int i, idx;
327         unsigned long offset;
328
329         if (!ptr)
330                 return;
331
332         ptr -= sizeof(*hdr);
333         hdr = ptr;
334
335         assert(ptr_valid(pool, ptr));
336
337         sfree_check_redzone(hdr);
338
339         offset = ptr - pool->map;
340         i = offset / SMALLOC_BPL;
341         idx = (offset % SMALLOC_BPL) / SMALLOC_BPB;
342
343         pool_lock(pool);
344         clear_blocks(pool, i, idx, size_to_blocks(hdr->size));
345         if (i < pool->next_non_full)
346                 pool->next_non_full = i;
347         pool->free_blocks += size_to_blocks(hdr->size);
348         pool_unlock(pool);
349 }
350
351 void sfree(void *ptr)
352 {
353         struct pool *pool = NULL;
354         unsigned int i;
355
356         if (!ptr)
357                 return;
358
359         global_read_lock();
360
361         for (i = 0; i < nr_pools; i++) {
362                 if (ptr_valid(&mp[i], ptr)) {
363                         pool = &mp[i];
364                         break;
365                 }
366         }
367
368         global_read_unlock();
369
370         assert(pool);
371         sfree_pool(pool, ptr);
372 }
373
374 static void *__smalloc_pool(struct pool *pool, unsigned int size)
375 {
376         unsigned int nr_blocks;
377         unsigned int i;
378         unsigned int offset;
379         unsigned int last_idx;
380         void *ret = NULL;
381
382         pool_lock(pool);
383
384         nr_blocks = size_to_blocks(size);
385         if (nr_blocks > pool->free_blocks)
386                 goto fail;
387
388         i = pool->next_non_full;
389         last_idx = 0;
390         offset = -1U;
391         while (i < pool->nr_blocks) {
392                 unsigned int idx;
393
394                 if (pool->bitmap[i] == -1U) {
395                         i++;
396                         pool->next_non_full = i;
397                         last_idx = 0;
398                         continue;
399                 }
400
401                 idx = find_next_zero(pool->bitmap[i], last_idx);
402                 if (!blocks_free(pool, i, idx, nr_blocks)) {
403                         idx += nr_blocks;
404                         if (idx < SMALLOC_BPI)
405                                 last_idx = idx;
406                         else {
407                                 last_idx = 0;
408                                 while (idx >= SMALLOC_BPI) {
409                                         i++;
410                                         idx -= SMALLOC_BPI;
411                                 }
412                         }
413                         continue;
414                 }
415                 set_blocks(pool, i, idx, nr_blocks);
416                 offset = i * SMALLOC_BPL + idx * SMALLOC_BPB;
417                 break;
418         }
419
420         if (i < pool->nr_blocks) {
421                 pool->free_blocks -= nr_blocks;
422                 ret = pool->map + offset;
423         }
424 fail:
425         pool_unlock(pool);
426         return ret;
427 }
428
429 static void *smalloc_pool(struct pool *pool, unsigned int size)
430 {
431         unsigned int alloc_size = size + sizeof(struct block_hdr);
432         void *ptr;
433
434         /*
435          * Round to int alignment, so that the postred pointer will
436          * be naturally aligned as well.
437          */
438 #ifdef SMALLOC_REDZONE
439         alloc_size += sizeof(unsigned int);
440         alloc_size = (alloc_size + int_mask) & ~int_mask;
441 #endif
442
443         ptr = __smalloc_pool(pool, alloc_size);
444         if (ptr) {
445                 struct block_hdr *hdr = ptr;
446
447                 hdr->size = alloc_size;
448                 fill_redzone(hdr);
449
450                 ptr += sizeof(*hdr);
451                 memset(ptr, 0, size);
452         }
453
454         return ptr;
455 }
456
457 void *smalloc(unsigned int size)
458 {
459         unsigned int i;
460
461         global_write_lock();
462         i = last_pool;
463
464         do {
465                 for (; i < nr_pools; i++) {
466                         void *ptr = smalloc_pool(&mp[i], size);
467
468                         if (ptr) {
469                                 last_pool = i;
470                                 global_write_unlock();
471                                 return ptr;
472                         }
473                 }
474                 if (last_pool) {
475                         last_pool = 0;
476                         continue;
477                 }
478
479                 if (nr_pools + 1 > MAX_POOLS)
480                         break;
481                 else {
482                         i = nr_pools;
483                         if (add_pool(&mp[nr_pools], size))
484                                 goto out;
485                 }
486         } while (1);
487
488 out:
489         global_write_unlock();
490         return NULL;
491 }
492
493 char *smalloc_strdup(const char *str)
494 {
495         char *ptr;
496
497         ptr = smalloc(strlen(str) + 1);
498         strcpy(ptr, str);
499         return ptr;
500 }