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