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