1.0.4.16: some GC and interrupt refactoring
[sbcl.git] / src / runtime / bsd-os.c
1 /*
2  * OS-dependent routines for BSD-ish systems
3  *
4  * This file (along with os.h) exports an OS-independent interface to
5  * the operating system VM facilities. This interface looks a lot like
6  * the Mach interface (but simpler in some places). For some operating
7  * systems, a subset of these functions will have to be emulated.
8  */
9
10 /*
11  * This software is part of the SBCL system. See the README file for
12  * more information.
13  *
14  * This software is derived from the CMU CL system, which was
15  * written at Carnegie Mellon University and released into the
16  * public domain. The software is in the public domain and is
17  * provided with absolutely no warranty. See the COPYING and CREDITS
18  * files for more information.
19  */
20
21 #include <stdio.h>
22 #include <sys/param.h>
23 #include <sys/file.h>
24 #include <unistd.h>
25 #include <assert.h>
26 #include <errno.h>
27 #include "sbcl.h"
28 #include "./signal.h"
29 #include "os.h"
30 #include "arch.h"
31 #include "globals.h"
32 #include "interrupt.h"
33 #include "interr.h"
34 #include "lispregs.h"
35 #include "thread.h"
36 #include "runtime.h"
37 #include "genesis/static-symbols.h"
38 #include "genesis/fdefn.h"
39
40 #include <sys/types.h>
41 #include <signal.h>
42 /* #include <sys/sysinfo.h> */
43 #include "validate.h"
44 #if defined LISP_FEATURE_GENCGC
45 #include "gencgc-internal.h"
46 #endif
47 \f
48 os_vm_size_t os_vm_page_size;
49
50 #ifdef __NetBSD__
51 #include <sys/resource.h>
52 #include <sys/sysctl.h>
53 #include <string.h>
54 #include <sys/stat.h> /* For the stat-family wrappers. */
55 #include <dirent.h>   /* For the opendir()/readdir() wrappers */
56 #include <sys/socket.h> /* For the socket() wrapper */
57 static void netbsd_init();
58 #endif /* __NetBSD__ */
59
60 #ifdef __FreeBSD__
61 #include <sys/sysctl.h>
62
63 static void freebsd_init();
64 #endif /* __FreeBSD__ */
65
66 void
67 os_init(char *argv[], char *envp[])
68 {
69     os_vm_page_size = getpagesize();
70
71 #ifdef __NetBSD__
72     netbsd_init();
73 #elif defined(__FreeBSD__)
74     freebsd_init();
75 #endif
76 }
77
78 sigset_t *
79 os_context_sigmask_addr(os_context_t *context)
80 {
81     /* (Unlike most of the other context fields that we access, the
82      * signal mask field is a field of the basic, outermost context
83      * struct itself both in FreeBSD 4.0 and in OpenBSD 2.6.) */
84 #if defined(__FreeBSD__)  || defined(__NetBSD__) || defined(LISP_FEATURE_DARWIN)
85     return &context->uc_sigmask;
86 #elif defined (__OpenBSD__)
87     return &context->sc_mask;
88 #else
89 #error unsupported BSD variant
90 #endif
91 }
92
93 os_vm_address_t
94 os_validate(os_vm_address_t addr, os_vm_size_t len)
95 {
96     int flags = MAP_PRIVATE | MAP_ANON;
97
98     if (addr)
99         flags |= MAP_FIXED;
100
101     addr = mmap(addr, len, OS_VM_PROT_ALL, flags, -1, 0);
102
103     if (addr == MAP_FAILED) {
104         perror("mmap");
105         return NULL;
106     }
107
108     return addr;
109 }
110
111 void
112 os_invalidate(os_vm_address_t addr, os_vm_size_t len)
113 {
114     if (munmap(addr, len) == -1)
115         perror("munmap");
116 }
117
118 os_vm_address_t
119 os_map(int fd, int offset, os_vm_address_t addr, os_vm_size_t len)
120 {
121     addr = mmap(addr, len,
122                 OS_VM_PROT_ALL,
123                 MAP_PRIVATE | MAP_FILE | MAP_FIXED,
124                 fd, (off_t) offset);
125
126     if (addr == MAP_FAILED) {
127         perror("mmap");
128         lose("unexpected mmap(..) failure\n");
129     }
130
131     return addr;
132 }
133
134 void
135 os_protect(os_vm_address_t address, os_vm_size_t length, os_vm_prot_t prot)
136 {
137     if (mprotect(address, length, prot) == -1) {
138         perror("mprotect");
139     }
140 }
141 \f
142 static boolean
143 in_range_p(os_vm_address_t a, lispobj sbeg, size_t slen)
144 {
145     char* beg = (char*) sbeg;
146     char* end = (char*) sbeg + slen;
147     char* adr = (char*) a;
148     return (adr >= beg && adr < end);
149 }
150
151 boolean
152 is_valid_lisp_addr(os_vm_address_t addr)
153 {
154     struct thread *th;
155     if(in_range_p(addr, READ_ONLY_SPACE_START, READ_ONLY_SPACE_SIZE) ||
156        in_range_p(addr, STATIC_SPACE_START   , STATIC_SPACE_SIZE) ||
157        in_range_p(addr, DYNAMIC_SPACE_START  , dynamic_space_size))
158         return 1;
159     for_each_thread(th) {
160         if(((os_vm_address_t)th->control_stack_start <= addr) &&
161            (addr < (os_vm_address_t)th->control_stack_end))
162             return 1;
163         if(in_range_p(addr, (lispobj)th->binding_stack_start,
164                       BINDING_STACK_SIZE))
165             return 1;
166     }
167     return 0;
168 }
169 \f
170 /*
171  * any OS-dependent special low-level handling for signals
172  */
173
174 #if defined LISP_FEATURE_GENCGC
175
176 /*
177  * The GENCGC needs to be hooked into whatever signal is raised for
178  * page fault on this OS.
179  */
180
181 void
182 memory_fault_handler(int signal, siginfo_t *siginfo, void *void_context
183 #if defined(LISP_FEATURE_FREEBSD) && defined(LISP_FEATURE_X86_64)
184 /* FreeBSD/amd64 stores fault address only in undocumented 4th arg. */
185                      ,void *fault_addr
186 #endif
187     )
188 {
189     os_context_t *context = arch_os_get_context(&void_context);
190 #if defined(LISP_FEATURE_FREEBSD) && defined(LISP_FEATURE_X86_64)
191     /* KLUDGE: Store fault address into si_addr for compatibilities. */
192     siginfo->si_addr = fault_addr;
193 #else
194     void *fault_addr = arch_get_bad_addr(signal, siginfo, context);
195 #endif
196
197 #if defined(LISP_FEATURE_RESTORE_TLS_SEGMENT_REGISTER_FROM_CONTEXT)
198     FSHOW_SIGNAL((stderr, "/ TLS: restoring fs: %p in memory_fault_handler\n",
199                   *CONTEXT_ADDR_FROM_STEM(fs)));
200     os_restore_tls_segment_register(context);
201 #endif
202
203     FSHOW((stderr, "Memory fault at: %p, PC: %p\n", fault_addr, *os_context_pc_addr(context)));
204
205     if (!gencgc_handle_wp_violation(fault_addr))
206         if(!handle_guard_page_triggered(context,fault_addr)) {
207 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
208             lisp_memory_fault_error(context, fault_addr);
209 #else
210             if (!maybe_gc(context)) {
211                 interrupt_handle_now(signal, siginfo, context);
212             }
213 #if defined(LISP_FEATURE_DARWIN)
214             /* Work around G5 bug; fix courtesy gbyers */
215             DARWIN_FIX_CONTEXT(context);
216 #endif
217 #endif
218         }
219 }
220
221 #if defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
222 void
223 mach_error_memory_fault_handler(int signal, siginfo_t *siginfo, void *void_context) {
224     lose("Unhandled memory fault. Exiting.");
225 }
226 #endif
227
228 void
229 os_install_interrupt_handlers(void)
230 {
231     SHOW("os_install_interrupt_handlers()/bsd-os/defined(GENCGC)");
232 #if defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
233     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
234                                                  mach_error_memory_fault_handler);
235 #else
236     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
237 #ifdef LISP_FEATURE_FREEBSD
238                                                  (__siginfohandler_t *)
239 #endif
240                                                  memory_fault_handler);
241 #ifdef SIG_MEMORY_FAULT2
242     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT2,
243 #ifdef LISP_FEATURE_FREEBSD
244                                                  (__siginfohandler_t *)
245 #endif
246                                                  memory_fault_handler);
247 #endif
248 #endif
249
250 #ifdef LISP_FEATURE_SB_THREAD
251     undoably_install_low_level_interrupt_handler(SIG_INTERRUPT_THREAD,
252                                                  interrupt_thread_handler);
253     undoably_install_low_level_interrupt_handler(SIG_STOP_FOR_GC,
254                                                  sig_stop_for_gc_handler);
255 #ifdef SIG_RESUME_FROM_GC
256     undoably_install_low_level_interrupt_handler(SIG_RESUME_FROM_GC,
257                                                  sig_stop_for_gc_handler);
258 #endif
259 #endif
260     SHOW("leaving os_install_interrupt_handlers()");
261 }
262
263 #else /* Currently PPC/Darwin/Cheney only */
264
265 static void
266 sigsegv_handler(int signal, siginfo_t *info, void* void_context)
267 {
268     os_context_t *context = arch_os_get_context(&void_context);
269     unsigned int pc =  (unsigned int *)(*os_context_pc_addr(context));
270     os_vm_address_t addr;
271
272     addr = arch_get_bad_addr(signal, info, context);
273     if (!cheneygc_handle_wp_violation(context, addr))
274         if (!handle_guard_page_triggered(context, addr))
275             interrupt_handle_now(signal, info, context);
276     /* Work around G5 bug; fix courtesy gbyers */
277     DARWIN_FIX_CONTEXT(context);
278 }
279
280 void
281 os_install_interrupt_handlers(void)
282 {
283     SHOW("os_install_interrupt_handlers()/bsd-os/!defined(GENCGC)");
284     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
285                                                  sigsegv_handler);
286 #ifdef SIG_MEMORY_FAULT2
287     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT2,
288                                                  sigsegv_handler);
289 #endif
290 }
291
292 #endif /* defined GENCGC */
293
294 #ifdef __NetBSD__
295 static void netbsd_init()
296 {
297     struct rlimit rl;
298     int mib[2], osrev;
299     size_t len;
300
301     /* Are we running on a sufficiently functional kernel? */
302     mib[0] = CTL_KERN;
303     mib[1] = KERN_OSREV;
304
305     len = sizeof(osrev);
306     sysctl(mib, 2, &osrev, &len, NULL, 0);
307
308     /* If we're older than 2.0... */
309     if (osrev < 200000000) {
310         fprintf(stderr, "osrev = %d (needed at least 200000000).\n", osrev);
311         lose("NetBSD kernel too old to run sbcl.\n");
312     }
313
314     /* NetBSD counts mmap()ed space against the process's data size limit,
315      * so yank it up. This might be a nasty thing to do? */
316     getrlimit (RLIMIT_DATA, &rl);
317     /* Amazingly for such a new port, the provenance and meaning of
318        this number are unknown.  It might just mean REALLY_BIG_LIMIT,
319        or possibly it should be calculated from dynamic space size.
320        -- CSR, 2004-04-08 */
321     rl.rlim_cur = 1073741824;
322     if (setrlimit (RLIMIT_DATA, &rl) < 0) {
323         fprintf (stderr,
324                  "RUNTIME WARNING: unable to raise process data size limit:\n\
325   %s.\n\
326 The system may fail to start.\n",
327                  strerror(errno));
328     }
329 }
330
331 /* Various routines in NetBSD's C library are compatibility wrappers
332    for old versions. Programs must be processed by the C toolchain in
333    order to get up-to-date definitions of such routines. */
334 /* The stat-family, opendir, and readdir are used only in sb-posix, as
335    of 2007-01-16. -- RMK */
336 int
337 _stat(const char *path, struct stat *sb)
338 {
339     return stat(path, sb);
340 }
341 int
342 _lstat(const char *path, struct stat *sb)
343 {
344     return lstat(path, sb);
345 }
346 int
347 _fstat(int fd, struct stat *sb)
348 {
349     return fstat(fd, sb);
350 }
351
352 DIR *
353 _opendir(const char *filename)
354 {
355     return opendir(filename);
356 }
357 struct dirent *
358 _readdir(DIR *dirp)
359 {
360     return readdir(dirp);
361 }
362
363 /* Used in sb-bsd-sockets. */
364 int
365 _socket(int domain, int type, int protocol)
366 {
367     return socket(domain, type, protocol);
368 }
369 #endif /* __NetBSD__ */
370
371 #ifdef __FreeBSD__
372 static void freebsd_init()
373 {
374     /* Quote from sbcl-devel (NIIMI Satoshi): "Some OSes, like FreeBSD
375      * 4.x with GENERIC kernel, does not enable SSE support even on
376      * SSE capable CPUs". Detect this situation and skip the
377      * fast_bzero sse/base selection logic that's normally done in
378      * x86-assem.S.
379      */
380 #ifdef LISP_FEATURE_X86
381     size_t len;
382     int instruction_sse;
383
384     len = sizeof(instruction_sse);
385     if (sysctlbyname("hw.instruction_sse", &instruction_sse, &len, NULL, 0) == 0
386         && instruction_sse != 0) {
387         /* Use the SSE detector */
388         fast_bzero_pointer = fast_bzero_detect;
389     }
390 #endif /* LISP_FEATURE_X86 */
391 }
392 #endif /* __FreeBSD__ */
393
394 #ifdef LISP_FEATURE_DARWIN
395 /* defined in ppc-darwin-os.c instead */
396 #elif defined(LISP_FEATURE_FREEBSD)
397 #ifndef KERN_PROC_PATHNAME
398 #define KERN_PROC_PATHNAME 12
399 #endif
400
401 extern int getosreldate(void);
402
403 char *
404 os_get_runtime_executable_path()
405 {
406     char path[PATH_MAX + 1];
407
408     if (getosreldate() >= 600024) {
409         /* KERN_PROC_PATHNAME is available */
410         size_t len = PATH_MAX + 1;
411         int mib[4];
412
413         mib[0] = CTL_KERN;
414         mib[1] = KERN_PROC;
415         mib[2] = KERN_PROC_PATHNAME;
416         mib[3] = -1;
417         if (sysctl(mib, 4, &path, &len, NULL, 0) != 0)
418             return NULL;
419     } else {
420         int size;
421         size = readlink("/proc/curproc/file", path, sizeof(path) - 1);
422         if (size < 0)
423             return NULL;
424         path[size] = '\0';
425     }
426     if (strcmp(path, "unknown") == 0)
427         return NULL;
428     return copied_string(path);
429 }
430 #elif defined(LISP_FEATURE_NETBSD)
431 char *
432 os_get_runtime_executable_path()
433 {
434     struct stat sb;
435     char *path = strdup("/proc/curproc/file");
436     if (path && ((stat(path, &sb)) == 0))
437         return path;
438     else {
439         fprintf(stderr, "Couldn't stat /proc/curproc/file; is /proc mounted?\n");
440         return NULL;
441     }
442 }
443 #else /* Not DARWIN or FREEBSD or NETBSD */
444 char *
445 os_get_runtime_executable_path()
446 {
447     return NULL;
448 }
449 #endif