]> mj.ucw.cz Git - libucw.git/blob - lib/bigalloc.c
Format string cleanup.
[libucw.git] / lib / bigalloc.c
1 /*
2  *      UCW Library -- Allocation of Large Aligned Buffers
3  *
4  *      (c) 2006--2007 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "lib/lib.h"
11
12 #include <sys/mman.h>
13
14 static u64
15 big_round(u64 len)
16 {
17   return ALIGN_TO(len, (u64)CPU_PAGE_SIZE);
18 }
19
20 void *
21 big_alloc(u64 len)
22 {
23   len = big_round(len);
24 #ifndef CPU_64BIT_POINTERS
25   if (len > 0xff000000)
26     die("big_alloc: Size %ju is too large for a 32-bit machine", (uintmax_t) len);
27 #endif
28 #ifdef CONFIG_DEBUG
29   len += 2*CPU_PAGE_SIZE;
30 #endif
31   byte *p = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
32   if (p == (byte*) MAP_FAILED)
33     die("Cannot mmap %ju bytes of memory: %m", (uintmax_t) len);
34 #ifdef CONFIG_DEBUG
35   mprotect(p, CPU_PAGE_SIZE, PROT_NONE);
36   mprotect(p+len-CPU_PAGE_SIZE, CPU_PAGE_SIZE, PROT_NONE);
37   p += CPU_PAGE_SIZE;
38 #endif
39   return p;
40 }
41
42 void
43 big_free(void *start, u64 len)
44 {
45   byte *p = start;
46   ASSERT(!((uintptr_t) p & (CPU_PAGE_SIZE-1)));
47   len = big_round(len);
48 #ifdef CONFIG_DEBUG
49   p -= CPU_PAGE_SIZE;
50   len += 2*CPU_PAGE_SIZE;
51 #endif
52   munmap(p, len);
53 }
54
55 #ifdef TEST
56
57 int main(void)
58 {
59   byte *p = big_alloc(123456);
60   // p[-1] = 1;
61   big_free(p, 123456);
62   return 0;
63 }
64
65 #endif