]> mj.ucw.cz Git - libucw.git/blob - lib/bigalloc.c
Merge with git+ssh://git.ucw.cz/projects/sherlock/GIT/sherlock.git#v3.10.1
[libucw.git] / lib / bigalloc.c
1 /*
2  *      UCW Library -- Allocation of Large Aligned Buffers
3  *
4  *      (c) 2006 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 unsigned int
15 big_round(unsigned int len)
16 {
17   return ALIGN_TO(len, CPU_PAGE_SIZE);
18 }
19
20 void *
21 big_alloc(unsigned int len)
22 {
23   len = big_round(len);
24 #ifdef CONFIG_DEBUG
25   len += 2*CPU_PAGE_SIZE;
26 #endif
27   byte *p = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
28   if (p == (byte*) MAP_FAILED)
29     die("Cannot mmap %d bytes of memory: %m", len);
30 #ifdef CONFIG_DEBUG
31   mprotect(p, CPU_PAGE_SIZE, PROT_NONE);
32   mprotect(p+len-CPU_PAGE_SIZE, CPU_PAGE_SIZE, PROT_NONE);
33   p += CPU_PAGE_SIZE;
34 #endif
35   return p;
36 }
37
38 void
39 big_free(void *start, unsigned int len)
40 {
41   byte *p = start;
42   ASSERT(!((uintptr_t) p & (CPU_PAGE_SIZE-1)));
43   len = big_round(len);
44 #ifdef CONFIG_DEBUG
45   p -= CPU_PAGE_SIZE;
46   len += 2*CPU_PAGE_SIZE;
47 #endif
48   munmap(p, len);
49 }
50
51 #ifdef TEST
52
53 int main(void)
54 {
55   byte *p = big_alloc(123456);
56   // p[-1] = 1;
57   big_free(p, 123456);
58   return 0;
59 }
60
61 #endif