Debian Codegraph @

src/ikarus-winmmap.c

raw
1 /*
2 * Ikarus Scheme -- A compiler for R6RS Scheme.
3 * Copyright (C) 2006,2007,2008 Abdulaziz Ghuloum
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18
19 #ifdef __CYGWIN__
20
21
22 #include <sys/mman.h>
23 #include <stdio.h>
24 #include <strings.h>
25 #include <errno.h>
26 #include <assert.h>
27
28 #define pagesize 4096
29 #define pageshift 12
30 #define segment_size (16*pagesize)
31 #define segment_shift (4+pageshift)
32 #include "ikarus-winmmap.h"
33
34 /* vim:syntax=c */
35
36 static unsigned short* table = 0;
37 static char* ap = 0;
38 static size_t as = 0;
39
40 static void*
41 do_mmap(size_t n){
42 void* x = mmap(0, n, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
43 if(x == (void*)-1){
44 fprintf(stderr, "failed to mmap: %s\n", strerror(errno));
45 exit(-1);
46 }
47 assert((((unsigned int)x) & (segment_size-1)) == 0);
48 return x;
49 }
50
51 static void
52 do_munmap(void* addr, size_t size){
53 int err = munmap(addr, size);
54 if(err){
55 fprintf(stderr, "failed to unmap\n");
56 exit(-1);
57 }
58 }
59
60
61 static void
62 init_table(){
63 assert(sizeof(unsigned short) == 2);
64 table = do_mmap(32*pagesize);
65 bzero(table, 32*pagesize);
66 }
67
68 void
69 win_munmap(char* addr, size_t size){
70 while(size){
71 unsigned int page = (((unsigned int) addr) >> pageshift);
72 unsigned int segment_index = page / 16;
73 unsigned int page_index = page & 15;
74 unsigned short alloc_bits = table[segment_index];
75 assert((alloc_bits & (1<<page_index)) == (1<<page_index));
76 unsigned int new_bits = alloc_bits & ~ (1 << page_index);
77 table[segment_index] = new_bits;
78 if(new_bits == 0){
79 do_munmap((void*)(segment_index*segment_size), segment_size);
80 }
81 size -= pagesize;
82 addr += pagesize;
83 }
84 }
85
86
87 char*
88 win_mmap(size_t size){
89 if(size <= as){
90 char* x = ap;
91 ap += size;
92 as -= size;
93 return x;
94 }
95 if(table == 0) init_table();
96 win_munmap(ap, as);
97 size_t segments = ((size+segment_size-1) >> segment_shift);
98 size_t aligned_size = segments << segment_shift;
99 char* addr = do_mmap(aligned_size);
100 unsigned int page = (((unsigned int) addr) >> pageshift);
101 unsigned int segment_index = page / 16;
102 int i;
103 for(i=0; i<segments; i++){
104 table[segment_index+i] = -1;
105 }
106 ap = addr + size;
107 as = aligned_size - size;
108 return addr;
109 }
110
111 #endif