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