1.0.25.44: INTERRUPT-THREAD and timer improvements
[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 #if defined(LISP_FEATURE_SB_THREAD) && !defined(LISP_FEATURE_SB_PTHREAD_FUTEX)
63 #include <sys/umtx.h>
64 #endif
65
66 static void freebsd_init();
67 #endif /* __FreeBSD__ */
68
69 #ifdef __OpenBSD__
70 #include <sys/types.h>
71 #include <sys/resource.h>
72 #include <sys/stat.h>
73 #include <dlfcn.h>
74
75 static void openbsd_init();
76 #endif
77
78 void
79 os_init(char *argv[], char *envp[])
80 {
81     os_vm_page_size = getpagesize();
82
83 #ifdef __NetBSD__
84     netbsd_init();
85 #elif defined(__FreeBSD__)
86     freebsd_init();
87 #elif defined(__OpenBSD__)
88     openbsd_init();
89 #endif
90 }
91
92 sigset_t *
93 os_context_sigmask_addr(os_context_t *context)
94 {
95     /* (Unlike most of the other context fields that we access, the
96      * signal mask field is a field of the basic, outermost context
97      * struct itself both in FreeBSD 4.0 and in OpenBSD 2.6.) */
98 #if defined(__FreeBSD__)  || defined(__NetBSD__) || defined(LISP_FEATURE_DARWIN)
99     return &context->uc_sigmask;
100 #elif defined (__OpenBSD__)
101     return &context->sc_mask;
102 #else
103 #error unsupported BSD variant
104 #endif
105 }
106
107 os_vm_address_t
108 os_validate(os_vm_address_t addr, os_vm_size_t len)
109 {
110     int flags = MAP_PRIVATE | MAP_ANON;
111
112     if (addr)
113         flags |= MAP_FIXED;
114
115     addr = mmap(addr, len, OS_VM_PROT_ALL, flags, -1, 0);
116
117     if (addr == MAP_FAILED) {
118         perror("mmap");
119         return NULL;
120     }
121
122     return addr;
123 }
124
125 void
126 os_invalidate(os_vm_address_t addr, os_vm_size_t len)
127 {
128     if (munmap(addr, len) == -1)
129         perror("munmap");
130 }
131
132 os_vm_address_t
133 os_map(int fd, int offset, os_vm_address_t addr, os_vm_size_t len)
134 {
135     addr = mmap(addr, len,
136                 OS_VM_PROT_ALL,
137                 MAP_PRIVATE | MAP_FILE | MAP_FIXED,
138                 fd, (off_t) offset);
139
140     if (addr == MAP_FAILED) {
141         perror("mmap");
142         lose("unexpected mmap(..) failure\n");
143     }
144
145     return addr;
146 }
147
148 void
149 os_protect(os_vm_address_t address, os_vm_size_t length, os_vm_prot_t prot)
150 {
151     if (mprotect(address, length, prot) == -1) {
152         perror("mprotect");
153     }
154 }
155 \f
156 static boolean
157 in_range_p(os_vm_address_t a, lispobj sbeg, size_t slen)
158 {
159     char* beg = (char*) sbeg;
160     char* end = (char*) sbeg + slen;
161     char* adr = (char*) a;
162     return (adr >= beg && adr < end);
163 }
164
165 boolean
166 is_valid_lisp_addr(os_vm_address_t addr)
167 {
168     struct thread *th;
169
170     if (in_range_p(addr, READ_ONLY_SPACE_START, READ_ONLY_SPACE_SIZE) ||
171         in_range_p(addr, STATIC_SPACE_START, STATIC_SPACE_SIZE) ||
172         in_range_p(addr, DYNAMIC_SPACE_START, dynamic_space_size))
173         return 1;
174     for_each_thread(th) {
175         if (((os_vm_address_t)th->control_stack_start <= addr) &&
176             (addr < (os_vm_address_t)th->control_stack_end))
177             return 1;
178         if (in_range_p(addr, (lispobj) th->binding_stack_start,
179                        BINDING_STACK_SIZE))
180             return 1;
181     }
182     return 0;
183 }
184 \f
185 /*
186  * any OS-dependent special low-level handling for signals
187  */
188
189 #if defined LISP_FEATURE_GENCGC
190
191 /*
192  * The GENCGC needs to be hooked into whatever signal is raised for
193  * page fault on this OS.
194  */
195
196 void
197 memory_fault_handler(int signal, siginfo_t *siginfo, void *void_context
198 #if defined(LISP_FEATURE_FREEBSD) && defined(LISP_FEATURE_X86_64)
199 /* FreeBSD/amd64 stores fault address only in undocumented 4th arg. */
200                      ,void *fault_addr
201 #endif
202     )
203 {
204     os_context_t *context = arch_os_get_context(&void_context);
205 #if defined(LISP_FEATURE_FREEBSD) && defined(LISP_FEATURE_X86_64)
206     /* KLUDGE: Store fault address into si_addr for compatibilities. */
207     siginfo->si_addr = fault_addr;
208 #else
209     void *fault_addr = arch_get_bad_addr(signal, siginfo, context);
210 #endif
211
212 #if defined(LISP_FEATURE_RESTORE_TLS_SEGMENT_REGISTER_FROM_CONTEXT)
213     FSHOW_SIGNAL((stderr, "/ TLS: restoring fs: %p in memory_fault_handler\n",
214                   *CONTEXT_ADDR_FROM_STEM(fs)));
215     os_restore_tls_segment_register(context);
216 #endif
217
218     FSHOW((stderr, "Memory fault at: %p, PC: %p\n", fault_addr, *os_context_pc_addr(context)));
219
220     if (!gencgc_handle_wp_violation(fault_addr))
221         if(!handle_guard_page_triggered(context,fault_addr)) {
222 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
223             lisp_memory_fault_error(context, fault_addr);
224 #else
225
226             /* this disabled section is what used to be here: */
227 #if 0
228             /* FIXME: never returns 0 */
229             if (!maybe_gc(context)) {
230                 interrupt_handle_now(signal, siginfo, context);
231             }
232 #endif
233             /* FIXME: Nowadays, maybe_gc does return 1 to indicate
234              * that GC did happen, but I'm keeping the code as it
235              * was. */
236             maybe_gc(context);
237             interrupt_handle_now(signal, siginfo, context);
238 #endif
239         }
240 }
241
242 #if defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
243 void
244 mach_error_memory_fault_handler(int signal, siginfo_t *siginfo, void *void_context) {
245     lose("Unhandled memory fault. Exiting.");
246 }
247 #endif
248
249 void
250 os_install_interrupt_handlers(void)
251 {
252     SHOW("os_install_interrupt_handlers()/bsd-os/defined(GENCGC)");
253 #if defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
254     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
255                                                  mach_error_memory_fault_handler);
256 #else
257     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
258 #ifdef LISP_FEATURE_FREEBSD
259                                                  (__siginfohandler_t *)
260 #endif
261                                                  memory_fault_handler);
262 #endif
263
264 #ifdef LISP_FEATURE_SB_THREAD
265     undoably_install_low_level_interrupt_handler(SIG_STOP_FOR_GC,
266                                                  sig_stop_for_gc_handler);
267 #endif
268     SHOW("leaving os_install_interrupt_handlers()");
269 }
270
271 #else /* Currently PPC/Darwin/Cheney only */
272
273 static void
274 sigsegv_handler(int signal, siginfo_t *info, void* void_context)
275 {
276     os_context_t *context = arch_os_get_context(&void_context);
277 #if 0
278     unsigned int pc =  (unsigned int *)(*os_context_pc_addr(context));
279 #endif
280     os_vm_address_t addr;
281
282     addr = arch_get_bad_addr(signal, info, context);
283     if (!cheneygc_handle_wp_violation(context, addr))
284         if (!handle_guard_page_triggered(context, addr))
285             interrupt_handle_now(signal, info, context);
286 }
287
288 void
289 os_install_interrupt_handlers(void)
290 {
291     SHOW("os_install_interrupt_handlers()/bsd-os/!defined(GENCGC)");
292     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
293                                                  sigsegv_handler);
294 }
295
296 #endif /* defined GENCGC */
297
298 #ifdef __NetBSD__
299 static void netbsd_init()
300 {
301     struct rlimit rl;
302     int mib[2], osrev;
303     size_t len;
304
305     /* Are we running on a sufficiently functional kernel? */
306     mib[0] = CTL_KERN;
307     mib[1] = KERN_OSREV;
308
309     len = sizeof(osrev);
310     sysctl(mib, 2, &osrev, &len, NULL, 0);
311
312     /* If we're older than 2.0... */
313     if (osrev < 200000000) {
314         fprintf(stderr, "osrev = %d (needed at least 200000000).\n", osrev);
315         lose("NetBSD kernel too old to run sbcl.\n");
316     }
317
318     /* NetBSD counts mmap()ed space against the process's data size limit,
319      * so yank it up. This might be a nasty thing to do? */
320     getrlimit (RLIMIT_DATA, &rl);
321     /* Amazingly for such a new port, the provenance and meaning of
322        this number are unknown.  It might just mean REALLY_BIG_LIMIT,
323        or possibly it should be calculated from dynamic space size.
324        -- CSR, 2004-04-08 */
325     rl.rlim_cur = 1073741824;
326     if (setrlimit (RLIMIT_DATA, &rl) < 0) {
327         fprintf (stderr,
328                  "RUNTIME WARNING: unable to raise process data size limit:\n\
329   %s.\n\
330 The system may fail to start.\n",
331                  strerror(errno));
332     }
333 }
334
335 /* Various routines in NetBSD's C library are compatibility wrappers
336    for old versions. Programs must be processed by the C toolchain in
337    order to get up-to-date definitions of such routines. */
338 /* The stat-family, opendir, and readdir are used only in sb-posix, as
339    of 2007-01-16. -- RMK */
340 int
341 _stat(const char *path, struct stat *sb)
342 {
343     return stat(path, sb);
344 }
345 int
346 _lstat(const char *path, struct stat *sb)
347 {
348     return lstat(path, sb);
349 }
350 int
351 _fstat(int fd, struct stat *sb)
352 {
353     return fstat(fd, sb);
354 }
355
356 DIR *
357 _opendir(const char *filename)
358 {
359     return opendir(filename);
360 }
361 struct dirent *
362 _readdir(DIR *dirp)
363 {
364     return readdir(dirp);
365 }
366
367 /* Used in sb-bsd-sockets. */
368 int
369 _socket(int domain, int type, int protocol)
370 {
371     return socket(domain, type, protocol);
372 }
373 #endif /* __NetBSD__ */
374
375 #ifdef __FreeBSD__
376 extern int getosreldate(void);
377
378 int sig_memory_fault;
379
380 static void freebsd_init()
381 {
382     /* Memory fault signal on FreeBSD was changed from SIGBUS to
383      * SIGSEGV. */
384     if (getosreldate() < 700004)
385         sig_memory_fault = SIGBUS;
386     else
387         sig_memory_fault = SIGSEGV;
388
389     /* Quote from sbcl-devel (NIIMI Satoshi): "Some OSes, like FreeBSD
390      * 4.x with GENERIC kernel, does not enable SSE support even on
391      * SSE capable CPUs". Detect this situation and skip the
392      * fast_bzero sse/base selection logic that's normally done in
393      * x86-assem.S.
394      */
395 #ifdef LISP_FEATURE_X86
396     {
397         size_t len;
398         int instruction_sse;
399
400         len = sizeof(instruction_sse);
401         if (sysctlbyname("hw.instruction_sse", &instruction_sse, &len,
402                          NULL, 0) == 0 && instruction_sse != 0) {
403             /* Use the SSE detector */
404             fast_bzero_pointer = fast_bzero_detect;
405         }
406     }
407 #endif /* LISP_FEATURE_X86 */
408 }
409
410 #if defined(LISP_FEATURE_SB_THREAD) && !defined(LISP_FEATURE_SB_PTHREAD_FUTEX)
411 int
412 futex_wait(int *lock_word, long oldval, long sec, unsigned long usec)
413 {
414     struct timespec timeout;
415     int ret;
416
417 again:
418     if (sec < 0)
419         ret = umtx_wait((void *)lock_word, oldval, NULL);
420     else {
421         timeout.tv_sec = sec;
422         timeout.tv_nsec = usec * 1000;
423         ret = umtx_wait((void *)lock_word, oldval, &timeout);
424     }
425
426     switch (ret) {
427     case 0:
428         return 0;
429     case ETIMEDOUT:
430         return 1;
431     case EINTR:
432         /* spurious wakeup from interrupt */
433         goto again;
434     default:
435         /* EWOULDBLOCK and others, need to check the lock */
436         return -1;
437     }
438 }
439
440 int
441 futex_wake(int *lock_word, int n)
442 {
443     return umtx_wake((void *)lock_word, n);
444 }
445 #endif
446 #endif /* __FreeBSD__ */
447
448 #ifdef LISP_FEATURE_DARWIN
449 /* defined in ppc-darwin-os.c instead */
450 #elif defined(LISP_FEATURE_FREEBSD)
451 #ifndef KERN_PROC_PATHNAME
452 #define KERN_PROC_PATHNAME 12
453 #endif
454
455 char *
456 os_get_runtime_executable_path()
457 {
458     char path[PATH_MAX + 1];
459
460     if (getosreldate() >= 600024) {
461         /* KERN_PROC_PATHNAME is available */
462         size_t len = PATH_MAX + 1;
463         int mib[4];
464
465         mib[0] = CTL_KERN;
466         mib[1] = KERN_PROC;
467         mib[2] = KERN_PROC_PATHNAME;
468         mib[3] = -1;
469         if (sysctl(mib, 4, &path, &len, NULL, 0) != 0)
470             return NULL;
471     } else {
472         int size;
473         size = readlink("/proc/curproc/file", path, sizeof(path) - 1);
474         if (size < 0)
475             return NULL;
476         path[size] = '\0';
477     }
478     if (strcmp(path, "unknown") == 0)
479         return NULL;
480     return copied_string(path);
481 }
482 #elif defined(LISP_FEATURE_NETBSD) || defined(LISP_FEATURE_OPENBSD)
483 char *
484 os_get_runtime_executable_path()
485 {
486     struct stat sb;
487     char *path = strdup("/proc/curproc/file");
488     if (path && ((stat(path, &sb)) == 0))
489         return path;
490     else {
491         fprintf(stderr, "Couldn't stat /proc/curproc/file; is /proc mounted?\n");
492         return NULL;
493     }
494 }
495 #else /* Not DARWIN or FREEBSD or NETBSD or OPENBSD */
496 char *
497 os_get_runtime_executable_path()
498 {
499     return NULL;
500 }
501 #endif
502
503 #ifdef __OpenBSD__
504 void
505 openbsd_init()
506 {
507     struct rlimit rl;
508
509     /* OpenBSD, like NetBSD, counts mmap()ed space against the
510      * process's data size limit. If the soft limit is lower than the
511      * hard limit then try to yank it up, this lets users in the
512      * "staff" login class run sbcl with a default /etc/login.conf
513      */
514     getrlimit (RLIMIT_DATA, &rl);
515     if (rl.rlim_cur < rl.rlim_max) {
516         rl.rlim_cur = rl.rlim_max;
517         if (setrlimit (RLIMIT_DATA, &rl) < 0) {
518             fprintf (stderr,
519                      "RUNTIME WARNING: unable to raise process data size limit:\n\
520   %s.\n\
521 The system may fail to start.\n",
522                      strerror(errno));
523         }
524     }
525
526     /* Display a (hopefully) helpful warning if it looks like we won't
527      * be able to allocate enough memory. In testing I found that on
528      * my system at least, a minimum of 25M on top of the three space
529      * sizes was needed to start SBCL. Show a warning below 32M so as
530      * to leave a little breathing room.
531      */
532     getrlimit (RLIMIT_DATA, &rl);
533     if (dynamic_space_size + READ_ONLY_SPACE_SIZE + STATIC_SPACE_SIZE +
534         LINKAGE_TABLE_SPACE_SIZE + (32*1024*1024) > rl.rlim_cur)
535         fprintf (stderr,
536                  "RUNTIME WARNING: data size resource limit may be too low,\n"
537                  "  try decreasing the dynamic space size with --dynamic-space-size\n");
538 }
539
540 /* OpenBSD's dlsym() relies on the gcc bulitin
541  * __builtin_return_address(0) returning an address in the
542  * executable's text segment, but when called from lisp it will return
543  * an address in the dynamic space.  Work around this by calling this
544  * wrapper function instead. Note that tail-call optimization will
545  * defeat this, disable it by saving the dlsym() return value in a
546  * volatile variable.
547 */
548 void *
549 os_dlsym(void *handle, const char *symbol)
550 {
551     void * volatile ret = dlsym(handle, symbol);
552     return ret;
553 }
554
555 #endif