1.0.26.13: OpenBSD x86-64 support
[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, os_context_t *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 #if defined(LISP_FEATURE_FREEBSD) && defined(LISP_FEATURE_X86_64)
205     /* KLUDGE: Store fault address into si_addr for compatibilities. */
206     siginfo->si_addr = fault_addr;
207 #else
208     void *fault_addr = arch_get_bad_addr(signal, siginfo, context);
209 #endif
210
211 #if defined(LISP_FEATURE_RESTORE_TLS_SEGMENT_REGISTER_FROM_CONTEXT)
212     FSHOW_SIGNAL((stderr, "/ TLS: restoring fs: %p in memory_fault_handler\n",
213                   *CONTEXT_ADDR_FROM_STEM(fs)));
214     os_restore_tls_segment_register(context);
215 #endif
216
217     FSHOW((stderr, "Memory fault at: %p, PC: %p\n", fault_addr, *os_context_pc_addr(context)));
218
219     if (!gencgc_handle_wp_violation(fault_addr))
220         if(!handle_guard_page_triggered(context,fault_addr))
221             lisp_memory_fault_error(context, fault_addr);
222 }
223
224 #if defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
225 void
226 mach_error_memory_fault_handler(int signal, siginfo_t *siginfo,
227                                 os_context_t *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 #endif
246
247 #ifdef LISP_FEATURE_SB_THREAD
248     undoably_install_low_level_interrupt_handler(SIG_STOP_FOR_GC,
249                                                  sig_stop_for_gc_handler);
250 #endif
251     SHOW("leaving os_install_interrupt_handlers()");
252 }
253
254 #else /* Currently PPC/Darwin/Cheney only */
255
256 static void
257 sigsegv_handler(int signal, siginfo_t *info, os_context_t *context)
258 {
259 #if 0
260     unsigned int pc =  (unsigned int *)(*os_context_pc_addr(context));
261 #endif
262     os_vm_address_t addr;
263
264     addr = arch_get_bad_addr(signal, info, context);
265     if (!cheneygc_handle_wp_violation(context, addr))
266         if (!handle_guard_page_triggered(context, addr))
267             interrupt_handle_now(signal, info, context);
268 }
269
270 void
271 os_install_interrupt_handlers(void)
272 {
273     SHOW("os_install_interrupt_handlers()/bsd-os/!defined(GENCGC)");
274     undoably_install_low_level_interrupt_handler(SIG_MEMORY_FAULT,
275                                                  sigsegv_handler);
276 }
277
278 #endif /* defined GENCGC */
279
280 #ifdef __NetBSD__
281 static void netbsd_init()
282 {
283     struct rlimit rl;
284     int mib[2], osrev;
285     size_t len;
286
287     /* Are we running on a sufficiently functional kernel? */
288     mib[0] = CTL_KERN;
289     mib[1] = KERN_OSREV;
290
291     len = sizeof(osrev);
292     sysctl(mib, 2, &osrev, &len, NULL, 0);
293
294     /* If we're older than 2.0... */
295     if (osrev < 200000000) {
296         fprintf(stderr, "osrev = %d (needed at least 200000000).\n", osrev);
297         lose("NetBSD kernel too old to run sbcl.\n");
298     }
299
300     /* NetBSD counts mmap()ed space against the process's data size limit,
301      * so yank it up. This might be a nasty thing to do? */
302     getrlimit (RLIMIT_DATA, &rl);
303     /* Amazingly for such a new port, the provenance and meaning of
304        this number are unknown.  It might just mean REALLY_BIG_LIMIT,
305        or possibly it should be calculated from dynamic space size.
306        -- CSR, 2004-04-08 */
307     rl.rlim_cur = 1073741824;
308     if (setrlimit (RLIMIT_DATA, &rl) < 0) {
309         fprintf (stderr,
310                  "RUNTIME WARNING: unable to raise process data size limit:\n\
311   %s.\n\
312 The system may fail to start.\n",
313                  strerror(errno));
314     }
315 }
316
317 /* Various routines in NetBSD's C library are compatibility wrappers
318    for old versions. Programs must be processed by the C toolchain in
319    order to get up-to-date definitions of such routines. */
320 /* The stat-family, opendir, and readdir are used only in sb-posix, as
321    of 2007-01-16. -- RMK */
322 int
323 _stat(const char *path, struct stat *sb)
324 {
325     return stat(path, sb);
326 }
327 int
328 _lstat(const char *path, struct stat *sb)
329 {
330     return lstat(path, sb);
331 }
332 int
333 _fstat(int fd, struct stat *sb)
334 {
335     return fstat(fd, sb);
336 }
337
338 DIR *
339 _opendir(const char *filename)
340 {
341     return opendir(filename);
342 }
343 struct dirent *
344 _readdir(DIR *dirp)
345 {
346     return readdir(dirp);
347 }
348
349 /* Used in sb-bsd-sockets. */
350 int
351 _socket(int domain, int type, int protocol)
352 {
353     return socket(domain, type, protocol);
354 }
355 #endif /* __NetBSD__ */
356
357 #ifdef __FreeBSD__
358 extern int getosreldate(void);
359
360 int sig_memory_fault;
361
362 static void freebsd_init()
363 {
364     /* Memory fault signal on FreeBSD was changed from SIGBUS to
365      * SIGSEGV. */
366     if (getosreldate() < 700004)
367         sig_memory_fault = SIGBUS;
368     else
369         sig_memory_fault = SIGSEGV;
370
371     /* Quote from sbcl-devel (NIIMI Satoshi): "Some OSes, like FreeBSD
372      * 4.x with GENERIC kernel, does not enable SSE support even on
373      * SSE capable CPUs". Detect this situation and skip the
374      * fast_bzero sse/base selection logic that's normally done in
375      * x86-assem.S.
376      */
377 #ifdef LISP_FEATURE_X86
378     {
379         size_t len;
380         int instruction_sse;
381
382         len = sizeof(instruction_sse);
383         if (sysctlbyname("hw.instruction_sse", &instruction_sse, &len,
384                          NULL, 0) == 0 && instruction_sse != 0) {
385             /* Use the SSE detector */
386             fast_bzero_pointer = fast_bzero_detect;
387         }
388     }
389 #endif /* LISP_FEATURE_X86 */
390 }
391
392 #if defined(LISP_FEATURE_SB_THREAD) && !defined(LISP_FEATURE_SB_PTHREAD_FUTEX)
393 int
394 futex_wait(int *lock_word, long oldval, long sec, unsigned long usec)
395 {
396     struct timespec timeout;
397     int ret;
398
399     if (sec < 0)
400         ret = umtx_wait((void *)lock_word, oldval, NULL);
401     else {
402         timeout.tv_sec = sec;
403         timeout.tv_nsec = usec * 1000;
404         ret = umtx_wait((void *)lock_word, oldval, &timeout);
405     }
406
407     switch (ret) {
408     case 0:
409         return 0;
410     case ETIMEDOUT:
411         return 1;
412     case EINTR:
413         return 2;
414     default:
415         /* EWOULDBLOCK and others, need to check the lock */
416         return -1;
417     }
418 }
419
420 int
421 futex_wake(int *lock_word, int n)
422 {
423     return umtx_wake((void *)lock_word, n);
424 }
425 #endif
426 #endif /* __FreeBSD__ */
427
428 #ifdef LISP_FEATURE_DARWIN
429 /* defined in ppc-darwin-os.c instead */
430 #elif defined(LISP_FEATURE_FREEBSD)
431 #ifndef KERN_PROC_PATHNAME
432 #define KERN_PROC_PATHNAME 12
433 #endif
434
435 char *
436 os_get_runtime_executable_path()
437 {
438     char path[PATH_MAX + 1];
439
440     if (getosreldate() >= 600024) {
441         /* KERN_PROC_PATHNAME is available */
442         size_t len = PATH_MAX + 1;
443         int mib[4];
444
445         mib[0] = CTL_KERN;
446         mib[1] = KERN_PROC;
447         mib[2] = KERN_PROC_PATHNAME;
448         mib[3] = -1;
449         if (sysctl(mib, 4, &path, &len, NULL, 0) != 0)
450             return NULL;
451     } else {
452         int size;
453         size = readlink("/proc/curproc/file", path, sizeof(path) - 1);
454         if (size < 0)
455             return NULL;
456         path[size] = '\0';
457     }
458     if (strcmp(path, "unknown") == 0)
459         return NULL;
460     return copied_string(path);
461 }
462 #elif defined(LISP_FEATURE_NETBSD) || defined(LISP_FEATURE_OPENBSD)
463 char *
464 os_get_runtime_executable_path()
465 {
466     struct stat sb;
467     char *path = strdup("/proc/curproc/file");
468     if (path && ((stat(path, &sb)) == 0))
469         return path;
470     else {
471         fprintf(stderr, "Couldn't stat /proc/curproc/file; is /proc mounted?\n");
472         return NULL;
473     }
474 }
475 #else /* Not DARWIN or FREEBSD or NETBSD or OPENBSD */
476 char *
477 os_get_runtime_executable_path()
478 {
479     return NULL;
480 }
481 #endif
482
483 #ifdef __OpenBSD__
484 void
485 openbsd_init()
486 {
487     /*
488      * Show a warning if it looks like the memory available after
489      * allocating the spaces won't be at least this much.
490      */
491 #ifdef LISP_FEATURE_X86_64
492     const int wantfree = 64 * 1024 * 1024;
493 #else
494     const int wantfree = 32 * 1024 * 1024;
495 #endif
496     struct rlimit rl;
497
498     /* OpenBSD, like NetBSD, counts mmap()ed space against the
499      * process's data size limit. If the soft limit is lower than the
500      * hard limit then try to yank it up, this lets users in the
501      * "staff" or "daemon" login classes run sbcl with larger dynamic
502      * space sizes.
503      */
504     getrlimit (RLIMIT_DATA, &rl);
505     if (rl.rlim_cur < rl.rlim_max) {
506         rl.rlim_cur = rl.rlim_max;
507         if (setrlimit (RLIMIT_DATA, &rl) < 0) {
508             fprintf (stderr,
509                      "RUNTIME WARNING: unable to raise process data size limit:\n\
510   %s.\n\
511 The system may fail to start.\n",
512                      strerror(errno));
513         }
514     }
515
516     /*
517      * Display a (hopefully) helpful warning if it looks like we won't
518      * be able to allocate enough memory.
519      */
520     getrlimit (RLIMIT_DATA, &rl);
521     if (dynamic_space_size + READ_ONLY_SPACE_SIZE + STATIC_SPACE_SIZE +
522         LINKAGE_TABLE_SPACE_SIZE + wantfree > rl.rlim_cur)
523         fprintf (stderr,
524                  "RUNTIME WARNING: data size resource limit may be too low,\n"
525                  "  try decreasing the dynamic space size with --dynamic-space-size\n"
526                  "  or raising the datasize or datasize-max limits in /etc/login.conf\n");
527 }
528
529 /* OpenBSD's dlsym() relies on the gcc bulitin
530  * __builtin_return_address(0) returning an address in the
531  * executable's text segment, but when called from lisp it will return
532  * an address in the dynamic space.  Work around this by calling this
533  * wrapper function instead. Note that tail-call optimization will
534  * defeat this, disable it by saving the dlsym() return value in a
535  * volatile variable.
536 */
537 void *
538 os_dlsym(void *handle, const char *symbol)
539 {
540     void * volatile ret = dlsym(handle, symbol);
541     return ret;
542 }
543
544 #endif