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