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