]> mj.ucw.cz Git - libucw.git/blob - lib/bigalloc.c
fixed support for 64bit big allocations
[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  *      (c) 2007 Pavel Charvat <char@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include "lib/lib.h"
12
13 #include <sys/mman.h>
14 #include <string.h>
15 #include <limits.h>
16
17 void *
18 page_alloc(u64 len)
19 {
20   if (len > SIZE_MAX)
21     die("page_alloc: Size %llu is too large for the current architecture", (long long) len);
22   ASSERT(!(len & (CPU_PAGE_SIZE-1)));
23   byte *p = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
24   if (p == (byte*) MAP_FAILED)
25     die("Cannot mmap %llu bytes of memory: %m", (long long)len);
26   return p;
27 }
28
29 void
30 page_free(void *start, u64 len)
31 {
32   ASSERT(!(len & (CPU_PAGE_SIZE-1)));
33   ASSERT(!((uintptr_t) start & (CPU_PAGE_SIZE-1)));
34   munmap(start, len);
35 }
36
37 void *
38 page_realloc(void *start, u64 old_len, u64 new_len)
39 {
40   void *p = page_alloc(new_len);
41   memcpy(p, start, MIN(old_len, new_len));
42   page_free(start, old_len);
43   return p;
44 }
45
46 static u64
47 big_round(u64 len)
48 {
49   return ALIGN_TO(len, (u64)CPU_PAGE_SIZE);
50 }
51
52 void *
53 big_alloc(u64 len)
54 {
55   len = big_round(len);
56   if (len > SIZE_MAX - 2*CPU_PAGE_SIZE)
57     die("big_alloc: Size %llu is too large for the current architecture", (long long) len);
58 #ifdef CONFIG_DEBUG
59   len += 2*CPU_PAGE_SIZE;
60 #endif
61   byte *p = page_alloc(len);
62 #ifdef CONFIG_DEBUG
63   mprotect(p, CPU_PAGE_SIZE, PROT_NONE);
64   mprotect(p+len-CPU_PAGE_SIZE, CPU_PAGE_SIZE, PROT_NONE);
65   p += CPU_PAGE_SIZE;
66 #endif
67   return p;
68 }
69
70 void
71 big_free(void *start, u64 len)
72 {
73   byte *p = start;
74   len = big_round(len);
75 #ifdef CONFIG_DEBUG
76   p -= CPU_PAGE_SIZE;
77   len += 2*CPU_PAGE_SIZE;
78 #endif
79   page_free(p, len);
80 }
81
82 #ifdef TEST
83
84 int main(void)
85 {
86   byte *p = big_alloc(123456);
87   // p[-1] = 1;
88   big_free(p, 123456);
89   return 0;
90 }
91
92 #endif