Fri, 06 Jul 2018 17:25:06 +0100
8197429: Increased stack guard causes segfaults on x86-32
Reviewed-by: dholmes
1 /*
2 * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
25 // no precompiled headers
26 #include "classfile/classLoader.hpp"
27 #include "classfile/systemDictionary.hpp"
28 #include "classfile/vmSymbols.hpp"
29 #include "code/icBuffer.hpp"
30 #include "code/vtableStubs.hpp"
31 #include "compiler/compileBroker.hpp"
32 #include "compiler/disassembler.hpp"
33 #include "interpreter/interpreter.hpp"
34 #include "jvm_linux.h"
35 #include "memory/allocation.inline.hpp"
36 #include "memory/filemap.hpp"
37 #include "mutex_linux.inline.hpp"
38 #include "oops/oop.inline.hpp"
39 #include "os_share_linux.hpp"
40 #include "osContainer_linux.hpp"
41 #include "prims/jniFastGetField.hpp"
42 #include "prims/jvm.h"
43 #include "prims/jvm_misc.hpp"
44 #include "runtime/arguments.hpp"
45 #include "runtime/extendedPC.hpp"
46 #include "runtime/globals.hpp"
47 #include "runtime/interfaceSupport.hpp"
48 #include "runtime/init.hpp"
49 #include "runtime/java.hpp"
50 #include "runtime/javaCalls.hpp"
51 #include "runtime/mutexLocker.hpp"
52 #include "runtime/objectMonitor.hpp"
53 #include "runtime/orderAccess.inline.hpp"
54 #include "runtime/osThread.hpp"
55 #include "runtime/perfMemory.hpp"
56 #include "runtime/sharedRuntime.hpp"
57 #include "runtime/statSampler.hpp"
58 #include "runtime/stubRoutines.hpp"
59 #include "runtime/thread.inline.hpp"
60 #include "runtime/threadCritical.hpp"
61 #include "runtime/timer.hpp"
62 #include "services/attachListener.hpp"
63 #include "services/memTracker.hpp"
64 #include "services/runtimeService.hpp"
65 #include "utilities/decoder.hpp"
66 #include "utilities/defaultStream.hpp"
67 #include "utilities/events.hpp"
68 #include "utilities/elfFile.hpp"
69 #include "utilities/growableArray.hpp"
70 #include "utilities/vmError.hpp"
72 // put OS-includes here
73 # include <sys/types.h>
74 # include <sys/mman.h>
75 # include <sys/stat.h>
76 # include <sys/select.h>
77 # include <pthread.h>
78 # include <signal.h>
79 # include <errno.h>
80 # include <dlfcn.h>
81 # include <stdio.h>
82 # include <unistd.h>
83 # include <sys/resource.h>
84 # include <pthread.h>
85 # include <sys/stat.h>
86 # include <sys/time.h>
87 # include <sys/times.h>
88 # include <sys/utsname.h>
89 # include <sys/socket.h>
90 # include <sys/wait.h>
91 # include <pwd.h>
92 # include <poll.h>
93 # include <semaphore.h>
94 # include <fcntl.h>
95 # include <string.h>
96 # include <syscall.h>
97 # include <sys/sysinfo.h>
98 # include <gnu/libc-version.h>
99 # include <sys/ipc.h>
100 # include <sys/shm.h>
101 # include <link.h>
102 # include <stdint.h>
103 # include <inttypes.h>
104 # include <sys/ioctl.h>
106 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
108 #ifndef _GNU_SOURCE
109 #define _GNU_SOURCE
110 #include <sched.h>
111 #undef _GNU_SOURCE
112 #else
113 #include <sched.h>
114 #endif
116 // if RUSAGE_THREAD for getrusage() has not been defined, do it here. The code calling
117 // getrusage() is prepared to handle the associated failure.
118 #ifndef RUSAGE_THREAD
119 #define RUSAGE_THREAD (1) /* only the calling thread */
120 #endif
122 #define MAX_PATH (2 * K)
124 #define MAX_SECS 100000000
126 // for timer info max values which include all bits
127 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
129 #define LARGEPAGES_BIT (1 << 6)
130 ////////////////////////////////////////////////////////////////////////////////
131 // global variables
132 julong os::Linux::_physical_memory = 0;
134 address os::Linux::_initial_thread_stack_bottom = NULL;
135 uintptr_t os::Linux::_initial_thread_stack_size = 0;
137 int (*os::Linux::_clock_gettime)(clockid_t, struct timespec *) = NULL;
138 int (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL;
139 Mutex* os::Linux::_createThread_lock = NULL;
140 pthread_t os::Linux::_main_thread;
141 int os::Linux::_page_size = -1;
142 const int os::Linux::_vm_default_page_size = (8 * K);
143 bool os::Linux::_is_floating_stack = false;
144 bool os::Linux::_is_NPTL = false;
145 bool os::Linux::_supports_fast_thread_cpu_time = false;
146 const char * os::Linux::_glibc_version = NULL;
147 const char * os::Linux::_libpthread_version = NULL;
148 pthread_condattr_t os::Linux::_condattr[1];
150 static jlong initial_time_count=0;
152 static int clock_tics_per_sec = 100;
154 // For diagnostics to print a message once. see run_periodic_checks
155 static sigset_t check_signal_done;
156 static bool check_signals = true;
158 static pid_t _initial_pid = 0;
160 /* Signal number used to suspend/resume a thread */
162 /* do not use any signal number less than SIGSEGV, see 4355769 */
163 static int SR_signum = SIGUSR2;
164 sigset_t SR_sigset;
166 /* Used to protect dlsym() calls */
167 static pthread_mutex_t dl_mutex;
169 // Declarations
170 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
172 // utility functions
174 static int SR_initialize();
176 julong os::available_memory() {
177 return Linux::available_memory();
178 }
180 julong os::Linux::available_memory() {
181 // values in struct sysinfo are "unsigned long"
182 struct sysinfo si;
183 julong avail_mem;
185 if (OSContainer::is_containerized()) {
186 jlong mem_limit, mem_usage;
187 if ((mem_limit = OSContainer::memory_limit_in_bytes()) < 1) {
188 if (PrintContainerInfo) {
189 tty->print_cr("container memory limit %s: " JLONG_FORMAT ", using host value",
190 mem_limit == OSCONTAINER_ERROR ? "failed" : "unlimited", mem_limit);
191 }
192 }
194 if (mem_limit > 0 && (mem_usage = OSContainer::memory_usage_in_bytes()) < 1) {
195 if (PrintContainerInfo) {
196 tty->print_cr("container memory usage failed: " JLONG_FORMAT ", using host value", mem_usage);
197 }
198 }
200 if (mem_limit > 0 && mem_usage > 0 ) {
201 avail_mem = mem_limit > mem_usage ? (julong)mem_limit - (julong)mem_usage : 0;
202 if (PrintContainerInfo) {
203 tty->print_cr("available container memory: " JULONG_FORMAT, avail_mem);
204 }
205 return avail_mem;
206 }
207 }
209 sysinfo(&si);
210 avail_mem = (julong)si.freeram * si.mem_unit;
211 if (Verbose) {
212 tty->print_cr("available memory: " JULONG_FORMAT, avail_mem);
213 }
214 return avail_mem;
215 }
217 julong os::physical_memory() {
218 jlong phys_mem = 0;
219 if (OSContainer::is_containerized()) {
220 jlong mem_limit;
221 if ((mem_limit = OSContainer::memory_limit_in_bytes()) > 0) {
222 if (PrintContainerInfo) {
223 tty->print_cr("total container memory: " JLONG_FORMAT, mem_limit);
224 }
225 return mem_limit;
226 }
228 if (PrintContainerInfo) {
229 tty->print_cr("container memory limit %s: " JLONG_FORMAT ", using host value",
230 mem_limit == OSCONTAINER_ERROR ? "failed" : "unlimited", mem_limit);
231 }
232 }
234 phys_mem = Linux::physical_memory();
235 if (Verbose) {
236 tty->print_cr("total system memory: " JLONG_FORMAT, phys_mem);
237 }
238 return phys_mem;
239 }
241 ////////////////////////////////////////////////////////////////////////////////
242 // environment support
244 bool os::getenv(const char* name, char* buf, int len) {
245 const char* val = ::getenv(name);
246 if (val != NULL && strlen(val) < (size_t)len) {
247 strcpy(buf, val);
248 return true;
249 }
250 if (len > 0) buf[0] = 0; // return a null string
251 return false;
252 }
255 // Return true if user is running as root.
257 bool os::have_special_privileges() {
258 static bool init = false;
259 static bool privileges = false;
260 if (!init) {
261 privileges = (getuid() != geteuid()) || (getgid() != getegid());
262 init = true;
263 }
264 return privileges;
265 }
268 #ifndef SYS_gettid
269 // i386: 224, ia64: 1105, amd64: 186, sparc 143
270 #ifdef __ia64__
271 #define SYS_gettid 1105
272 #else
273 #ifdef __i386__
274 #define SYS_gettid 224
275 #else
276 #ifdef __amd64__
277 #define SYS_gettid 186
278 #else
279 #ifdef __sparc__
280 #define SYS_gettid 143
281 #else
282 #error define gettid for the arch
283 #endif
284 #endif
285 #endif
286 #endif
287 #endif
289 // Cpu architecture string
290 static char cpu_arch[] = HOTSPOT_LIB_ARCH;
292 // pid_t gettid()
293 //
294 // Returns the kernel thread id of the currently running thread. Kernel
295 // thread id is used to access /proc.
296 //
297 // (Note that getpid() on LinuxThreads returns kernel thread id too; but
298 // on NPTL, it returns the same pid for all threads, as required by POSIX.)
299 //
300 pid_t os::Linux::gettid() {
301 int rslt = syscall(SYS_gettid);
302 if (rslt == -1) {
303 // old kernel, no NPTL support
304 return getpid();
305 } else {
306 return (pid_t)rslt;
307 }
308 }
310 // Most versions of linux have a bug where the number of processors are
311 // determined by looking at the /proc file system. In a chroot environment,
312 // the system call returns 1. This causes the VM to act as if it is
313 // a single processor and elide locking (see is_MP() call).
314 static bool unsafe_chroot_detected = false;
315 static const char *unstable_chroot_error = "/proc file system not found.\n"
316 "Java may be unstable running multithreaded in a chroot "
317 "environment on Linux when /proc filesystem is not mounted.";
319 void os::Linux::initialize_system_info() {
320 set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
321 if (processor_count() == 1) {
322 pid_t pid = os::Linux::gettid();
323 char fname[32];
324 jio_snprintf(fname, sizeof(fname), "/proc/%d", pid);
325 FILE *fp = fopen(fname, "r");
326 if (fp == NULL) {
327 unsafe_chroot_detected = true;
328 } else {
329 fclose(fp);
330 }
331 }
332 _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE);
333 assert(processor_count() > 0, "linux error");
334 }
336 void os::init_system_properties_values() {
337 // The next steps are taken in the product version:
338 //
339 // Obtain the JAVA_HOME value from the location of libjvm.so.
340 // This library should be located at:
341 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
342 //
343 // If "/jre/lib/" appears at the right place in the path, then we
344 // assume libjvm.so is installed in a JDK and we use this path.
345 //
346 // Otherwise exit with message: "Could not create the Java virtual machine."
347 //
348 // The following extra steps are taken in the debugging version:
349 //
350 // If "/jre/lib/" does NOT appear at the right place in the path
351 // instead of exit check for $JAVA_HOME environment variable.
352 //
353 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
354 // then we append a fake suffix "hotspot/libjvm.so" to this path so
355 // it looks like libjvm.so is installed there
356 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
357 //
358 // Otherwise exit.
359 //
360 // Important note: if the location of libjvm.so changes this
361 // code needs to be changed accordingly.
363 // See ld(1):
364 // The linker uses the following search paths to locate required
365 // shared libraries:
366 // 1: ...
367 // ...
368 // 7: The default directories, normally /lib and /usr/lib.
369 #if defined(AMD64) || defined(_LP64) && (defined(SPARC) || defined(PPC) || defined(S390))
370 #define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib"
371 #else
372 #define DEFAULT_LIBPATH "/lib:/usr/lib"
373 #endif
375 // Base path of extensions installed on the system.
376 #define SYS_EXT_DIR "/usr/java/packages"
377 #define EXTENSIONS_DIR "/lib/ext"
378 #define ENDORSED_DIR "/lib/endorsed"
380 // Buffer that fits several sprintfs.
381 // Note that the space for the colon and the trailing null are provided
382 // by the nulls included by the sizeof operator.
383 const size_t bufsize =
384 MAX3((size_t)MAXPATHLEN, // For dll_dir & friends.
385 (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR), // extensions dir
386 (size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir
387 char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
389 // sysclasspath, java_home, dll_dir
390 {
391 char *pslash;
392 os::jvm_path(buf, bufsize);
394 // Found the full path to libjvm.so.
395 // Now cut the path to <java_home>/jre if we can.
396 *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
397 pslash = strrchr(buf, '/');
398 if (pslash != NULL) {
399 *pslash = '\0'; // Get rid of /{client|server|hotspot}.
400 }
401 Arguments::set_dll_dir(buf);
403 if (pslash != NULL) {
404 pslash = strrchr(buf, '/');
405 if (pslash != NULL) {
406 *pslash = '\0'; // Get rid of /<arch>.
407 pslash = strrchr(buf, '/');
408 if (pslash != NULL) {
409 *pslash = '\0'; // Get rid of /lib.
410 }
411 }
412 }
413 Arguments::set_java_home(buf);
414 set_boot_path('/', ':');
415 }
417 // Where to look for native libraries.
418 //
419 // Note: Due to a legacy implementation, most of the library path
420 // is set in the launcher. This was to accomodate linking restrictions
421 // on legacy Linux implementations (which are no longer supported).
422 // Eventually, all the library path setting will be done here.
423 //
424 // However, to prevent the proliferation of improperly built native
425 // libraries, the new path component /usr/java/packages is added here.
426 // Eventually, all the library path setting will be done here.
427 {
428 // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
429 // should always exist (until the legacy problem cited above is
430 // addressed).
431 const char *v = ::getenv("LD_LIBRARY_PATH");
432 const char *v_colon = ":";
433 if (v == NULL) { v = ""; v_colon = ""; }
434 // That's +1 for the colon and +1 for the trailing '\0'.
435 char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,
436 strlen(v) + 1 +
437 sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1,
438 mtInternal);
439 sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch);
440 Arguments::set_library_path(ld_library_path);
441 FREE_C_HEAP_ARRAY(char, ld_library_path, mtInternal);
442 }
444 // Extensions directories.
445 sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
446 Arguments::set_ext_dirs(buf);
448 // Endorsed standards default directory.
449 sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());
450 Arguments::set_endorsed_dirs(buf);
452 FREE_C_HEAP_ARRAY(char, buf, mtInternal);
454 #undef DEFAULT_LIBPATH
455 #undef SYS_EXT_DIR
456 #undef EXTENSIONS_DIR
457 #undef ENDORSED_DIR
458 }
460 ////////////////////////////////////////////////////////////////////////////////
461 // breakpoint support
463 void os::breakpoint() {
464 BREAKPOINT;
465 }
467 extern "C" void breakpoint() {
468 // use debugger to set breakpoint here
469 }
471 ////////////////////////////////////////////////////////////////////////////////
472 // signal support
474 debug_only(static bool signal_sets_initialized = false);
475 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
477 bool os::Linux::is_sig_ignored(int sig) {
478 struct sigaction oact;
479 sigaction(sig, (struct sigaction*)NULL, &oact);
480 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction)
481 : CAST_FROM_FN_PTR(void*, oact.sa_handler);
482 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))
483 return true;
484 else
485 return false;
486 }
488 void os::Linux::signal_sets_init() {
489 // Should also have an assertion stating we are still single-threaded.
490 assert(!signal_sets_initialized, "Already initialized");
491 // Fill in signals that are necessarily unblocked for all threads in
492 // the VM. Currently, we unblock the following signals:
493 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
494 // by -Xrs (=ReduceSignalUsage));
495 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
496 // other threads. The "ReduceSignalUsage" boolean tells us not to alter
497 // the dispositions or masks wrt these signals.
498 // Programs embedding the VM that want to use the above signals for their
499 // own purposes must, at this time, use the "-Xrs" option to prevent
500 // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
501 // (See bug 4345157, and other related bugs).
502 // In reality, though, unblocking these signals is really a nop, since
503 // these signals are not blocked by default.
504 sigemptyset(&unblocked_sigs);
505 sigemptyset(&allowdebug_blocked_sigs);
506 sigaddset(&unblocked_sigs, SIGILL);
507 sigaddset(&unblocked_sigs, SIGSEGV);
508 sigaddset(&unblocked_sigs, SIGBUS);
509 sigaddset(&unblocked_sigs, SIGFPE);
510 #if defined(PPC64)
511 sigaddset(&unblocked_sigs, SIGTRAP);
512 #endif
513 sigaddset(&unblocked_sigs, SR_signum);
515 if (!ReduceSignalUsage) {
516 if (!os::Linux::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
517 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
518 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
519 }
520 if (!os::Linux::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
521 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
522 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
523 }
524 if (!os::Linux::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
525 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
526 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
527 }
528 }
529 // Fill in signals that are blocked by all but the VM thread.
530 sigemptyset(&vm_sigs);
531 if (!ReduceSignalUsage)
532 sigaddset(&vm_sigs, BREAK_SIGNAL);
533 debug_only(signal_sets_initialized = true);
535 }
537 // These are signals that are unblocked while a thread is running Java.
538 // (For some reason, they get blocked by default.)
539 sigset_t* os::Linux::unblocked_signals() {
540 assert(signal_sets_initialized, "Not initialized");
541 return &unblocked_sigs;
542 }
544 // These are the signals that are blocked while a (non-VM) thread is
545 // running Java. Only the VM thread handles these signals.
546 sigset_t* os::Linux::vm_signals() {
547 assert(signal_sets_initialized, "Not initialized");
548 return &vm_sigs;
549 }
551 // These are signals that are blocked during cond_wait to allow debugger in
552 sigset_t* os::Linux::allowdebug_blocked_signals() {
553 assert(signal_sets_initialized, "Not initialized");
554 return &allowdebug_blocked_sigs;
555 }
557 void os::Linux::hotspot_sigmask(Thread* thread) {
559 //Save caller's signal mask before setting VM signal mask
560 sigset_t caller_sigmask;
561 pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
563 OSThread* osthread = thread->osthread();
564 osthread->set_caller_sigmask(caller_sigmask);
566 pthread_sigmask(SIG_UNBLOCK, os::Linux::unblocked_signals(), NULL);
568 if (!ReduceSignalUsage) {
569 if (thread->is_VM_thread()) {
570 // Only the VM thread handles BREAK_SIGNAL ...
571 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
572 } else {
573 // ... all other threads block BREAK_SIGNAL
574 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
575 }
576 }
577 }
579 //////////////////////////////////////////////////////////////////////////////
580 // detecting pthread library
582 void os::Linux::libpthread_init() {
583 // Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION
584 // and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a
585 // generic name for earlier versions.
586 // Define macros here so we can build HotSpot on old systems.
587 # ifndef _CS_GNU_LIBC_VERSION
588 # define _CS_GNU_LIBC_VERSION 2
589 # endif
590 # ifndef _CS_GNU_LIBPTHREAD_VERSION
591 # define _CS_GNU_LIBPTHREAD_VERSION 3
592 # endif
594 size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0);
595 if (n > 0) {
596 char *str = (char *)malloc(n, mtInternal);
597 confstr(_CS_GNU_LIBC_VERSION, str, n);
598 os::Linux::set_glibc_version(str);
599 } else {
600 // _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version()
601 static char _gnu_libc_version[32];
602 jio_snprintf(_gnu_libc_version, sizeof(_gnu_libc_version),
603 "glibc %s %s", gnu_get_libc_version(), gnu_get_libc_release());
604 os::Linux::set_glibc_version(_gnu_libc_version);
605 }
607 n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0);
608 if (n > 0) {
609 char *str = (char *)malloc(n, mtInternal);
610 confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n);
611 // Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells
612 // us "NPTL-0.29" even we are running with LinuxThreads. Check if this
613 // is the case. LinuxThreads has a hard limit on max number of threads.
614 // So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value.
615 // On the other hand, NPTL does not have such a limit, sysconf()
616 // will return -1 and errno is not changed. Check if it is really NPTL.
617 if (strcmp(os::Linux::glibc_version(), "glibc 2.3.2") == 0 &&
618 strstr(str, "NPTL") &&
619 sysconf(_SC_THREAD_THREADS_MAX) > 0) {
620 free(str);
621 os::Linux::set_libpthread_version("linuxthreads");
622 } else {
623 os::Linux::set_libpthread_version(str);
624 }
625 } else {
626 // glibc before 2.3.2 only has LinuxThreads.
627 os::Linux::set_libpthread_version("linuxthreads");
628 }
630 if (strstr(libpthread_version(), "NPTL")) {
631 os::Linux::set_is_NPTL();
632 } else {
633 os::Linux::set_is_LinuxThreads();
634 }
636 // LinuxThreads have two flavors: floating-stack mode, which allows variable
637 // stack size; and fixed-stack mode. NPTL is always floating-stack.
638 if (os::Linux::is_NPTL() || os::Linux::supports_variable_stack_size()) {
639 os::Linux::set_is_floating_stack();
640 }
641 }
643 /////////////////////////////////////////////////////////////////////////////
644 // thread stack
646 // Force Linux kernel to expand current thread stack. If "bottom" is close
647 // to the stack guard, caller should block all signals.
648 //
649 // MAP_GROWSDOWN:
650 // A special mmap() flag that is used to implement thread stacks. It tells
651 // kernel that the memory region should extend downwards when needed. This
652 // allows early versions of LinuxThreads to only mmap the first few pages
653 // when creating a new thread. Linux kernel will automatically expand thread
654 // stack as needed (on page faults).
655 //
656 // However, because the memory region of a MAP_GROWSDOWN stack can grow on
657 // demand, if a page fault happens outside an already mapped MAP_GROWSDOWN
658 // region, it's hard to tell if the fault is due to a legitimate stack
659 // access or because of reading/writing non-exist memory (e.g. buffer
660 // overrun). As a rule, if the fault happens below current stack pointer,
661 // Linux kernel does not expand stack, instead a SIGSEGV is sent to the
662 // application (see Linux kernel fault.c).
663 //
664 // This Linux feature can cause SIGSEGV when VM bangs thread stack for
665 // stack overflow detection.
666 //
667 // Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do
668 // not use this flag. However, the stack of initial thread is not created
669 // by pthread, it is still MAP_GROWSDOWN. Also it's possible (though
670 // unlikely) that user code can create a thread with MAP_GROWSDOWN stack
671 // and then attach the thread to JVM.
672 //
673 // To get around the problem and allow stack banging on Linux, we need to
674 // manually expand thread stack after receiving the SIGSEGV.
675 //
676 // There are two ways to expand thread stack to address "bottom", we used
677 // both of them in JVM before 1.5:
678 // 1. adjust stack pointer first so that it is below "bottom", and then
679 // touch "bottom"
680 // 2. mmap() the page in question
681 //
682 // Now alternate signal stack is gone, it's harder to use 2. For instance,
683 // if current sp is already near the lower end of page 101, and we need to
684 // call mmap() to map page 100, it is possible that part of the mmap() frame
685 // will be placed in page 100. When page 100 is mapped, it is zero-filled.
686 // That will destroy the mmap() frame and cause VM to crash.
687 //
688 // The following code works by adjusting sp first, then accessing the "bottom"
689 // page to force a page fault. Linux kernel will then automatically expand the
690 // stack mapping.
691 //
692 // _expand_stack_to() assumes its frame size is less than page size, which
693 // should always be true if the function is not inlined.
695 #if __GNUC__ < 3 // gcc 2.x does not support noinline attribute
696 #define NOINLINE
697 #else
698 #define NOINLINE __attribute__ ((noinline))
699 #endif
701 static void _expand_stack_to(address bottom) NOINLINE;
703 static void _expand_stack_to(address bottom) {
704 address sp;
705 size_t size;
706 volatile char *p;
708 // Adjust bottom to point to the largest address within the same page, it
709 // gives us a one-page buffer if alloca() allocates slightly more memory.
710 bottom = (address)align_size_down((uintptr_t)bottom, os::Linux::page_size());
711 bottom += os::Linux::page_size() - 1;
713 // sp might be slightly above current stack pointer; if that's the case, we
714 // will alloca() a little more space than necessary, which is OK. Don't use
715 // os::current_stack_pointer(), as its result can be slightly below current
716 // stack pointer, causing us to not alloca enough to reach "bottom".
717 sp = (address)&sp;
719 if (sp > bottom) {
720 size = sp - bottom;
721 p = (volatile char *)alloca(size);
722 assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?");
723 p[0] = '\0';
724 }
725 }
727 void os::Linux::expand_stack_to(address bottom) {
728 _expand_stack_to(bottom);
729 }
731 bool os::Linux::manually_expand_stack(JavaThread * t, address addr) {
732 assert(t!=NULL, "just checking");
733 assert(t->osthread()->expanding_stack(), "expand should be set");
734 assert(t->stack_base() != NULL, "stack_base was not initialized");
736 if (addr < t->stack_base() && addr >= t->stack_yellow_zone_base()) {
737 sigset_t mask_all, old_sigset;
738 sigfillset(&mask_all);
739 pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset);
740 _expand_stack_to(addr);
741 pthread_sigmask(SIG_SETMASK, &old_sigset, NULL);
742 return true;
743 }
744 return false;
745 }
747 //////////////////////////////////////////////////////////////////////////////
748 // create new thread
750 static address highest_vm_reserved_address();
752 // check if it's safe to start a new thread
753 static bool _thread_safety_check(Thread* thread) {
754 if (os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack()) {
755 // Fixed stack LinuxThreads (SuSE Linux/x86, and some versions of Redhat)
756 // Heap is mmap'ed at lower end of memory space. Thread stacks are
757 // allocated (MAP_FIXED) from high address space. Every thread stack
758 // occupies a fixed size slot (usually 2Mbytes, but user can change
759 // it to other values if they rebuild LinuxThreads).
760 //
761 // Problem with MAP_FIXED is that mmap() can still succeed even part of
762 // the memory region has already been mmap'ed. That means if we have too
763 // many threads and/or very large heap, eventually thread stack will
764 // collide with heap.
765 //
766 // Here we try to prevent heap/stack collision by comparing current
767 // stack bottom with the highest address that has been mmap'ed by JVM
768 // plus a safety margin for memory maps created by native code.
769 //
770 // This feature can be disabled by setting ThreadSafetyMargin to 0
771 //
772 if (ThreadSafetyMargin > 0) {
773 address stack_bottom = os::current_stack_base() - os::current_stack_size();
775 // not safe if our stack extends below the safety margin
776 return stack_bottom - ThreadSafetyMargin >= highest_vm_reserved_address();
777 } else {
778 return true;
779 }
780 } else {
781 // Floating stack LinuxThreads or NPTL:
782 // Unlike fixed stack LinuxThreads, thread stacks are not MAP_FIXED. When
783 // there's not enough space left, pthread_create() will fail. If we come
784 // here, that means enough space has been reserved for stack.
785 return true;
786 }
787 }
789 // Thread start routine for all newly created threads
790 static void *java_start(Thread *thread) {
791 // Try to randomize the cache line index of hot stack frames.
792 // This helps when threads of the same stack traces evict each other's
793 // cache lines. The threads can be either from the same JVM instance, or
794 // from different JVM instances. The benefit is especially true for
795 // processors with hyperthreading technology.
796 static int counter = 0;
797 int pid = os::current_process_id();
798 alloca(((pid ^ counter++) & 7) * 128);
800 ThreadLocalStorage::set_thread(thread);
802 OSThread* osthread = thread->osthread();
803 Monitor* sync = osthread->startThread_lock();
805 // non floating stack LinuxThreads needs extra check, see above
806 if (!_thread_safety_check(thread)) {
807 // notify parent thread
808 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
809 osthread->set_state(ZOMBIE);
810 sync->notify_all();
811 return NULL;
812 }
814 // thread_id is kernel thread id (similar to Solaris LWP id)
815 osthread->set_thread_id(os::Linux::gettid());
817 if (UseNUMA) {
818 int lgrp_id = os::numa_get_group_id();
819 if (lgrp_id != -1) {
820 thread->set_lgrp_id(lgrp_id);
821 }
822 }
823 // initialize signal mask for this thread
824 os::Linux::hotspot_sigmask(thread);
826 // initialize floating point control register
827 os::Linux::init_thread_fpu_state();
829 // handshaking with parent thread
830 {
831 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
833 // notify parent thread
834 osthread->set_state(INITIALIZED);
835 sync->notify_all();
837 // wait until os::start_thread()
838 while (osthread->get_state() == INITIALIZED) {
839 sync->wait(Mutex::_no_safepoint_check_flag);
840 }
841 }
843 // call one more level start routine
844 thread->run();
846 return 0;
847 }
849 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {
850 assert(thread->osthread() == NULL, "caller responsible");
852 // Allocate the OSThread object
853 OSThread* osthread = new OSThread(NULL, NULL);
854 if (osthread == NULL) {
855 return false;
856 }
858 // set the correct thread state
859 osthread->set_thread_type(thr_type);
861 // Initial state is ALLOCATED but not INITIALIZED
862 osthread->set_state(ALLOCATED);
864 thread->set_osthread(osthread);
866 // init thread attributes
867 pthread_attr_t attr;
868 pthread_attr_init(&attr);
869 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
871 // stack size
872 if (os::Linux::supports_variable_stack_size()) {
873 // calculate stack size if it's not specified by caller
874 if (stack_size == 0) {
875 stack_size = os::Linux::default_stack_size(thr_type);
877 switch (thr_type) {
878 case os::java_thread:
879 // Java threads use ThreadStackSize which default value can be
880 // changed with the flag -Xss
881 assert (JavaThread::stack_size_at_create() > 0, "this should be set");
882 stack_size = JavaThread::stack_size_at_create();
883 break;
884 case os::compiler_thread:
885 if (CompilerThreadStackSize > 0) {
886 stack_size = (size_t)(CompilerThreadStackSize * K);
887 break;
888 } // else fall through:
889 // use VMThreadStackSize if CompilerThreadStackSize is not defined
890 case os::vm_thread:
891 case os::pgc_thread:
892 case os::cgc_thread:
893 case os::watcher_thread:
894 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
895 break;
896 }
897 }
899 stack_size = MAX2(stack_size, os::Linux::min_stack_allowed);
900 pthread_attr_setstacksize(&attr, stack_size);
901 } else {
902 // let pthread_create() pick the default value.
903 }
905 // glibc guard page
906 pthread_attr_setguardsize(&attr, os::Linux::default_guard_size(thr_type));
908 ThreadState state;
910 {
911 // Serialize thread creation if we are running with fixed stack LinuxThreads
912 bool lock = os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack();
913 if (lock) {
914 os::Linux::createThread_lock()->lock_without_safepoint_check();
915 }
917 pthread_t tid;
918 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
920 pthread_attr_destroy(&attr);
922 if (ret != 0) {
923 if (PrintMiscellaneous && (Verbose || WizardMode)) {
924 perror("pthread_create()");
925 }
926 // Need to clean up stuff we've allocated so far
927 thread->set_osthread(NULL);
928 delete osthread;
929 if (lock) os::Linux::createThread_lock()->unlock();
930 return false;
931 }
933 // Store pthread info into the OSThread
934 osthread->set_pthread_id(tid);
936 // Wait until child thread is either initialized or aborted
937 {
938 Monitor* sync_with_child = osthread->startThread_lock();
939 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
940 while ((state = osthread->get_state()) == ALLOCATED) {
941 sync_with_child->wait(Mutex::_no_safepoint_check_flag);
942 }
943 }
945 if (lock) {
946 os::Linux::createThread_lock()->unlock();
947 }
948 }
950 // Aborted due to thread limit being reached
951 if (state == ZOMBIE) {
952 thread->set_osthread(NULL);
953 delete osthread;
954 return false;
955 }
957 // The thread is returned suspended (in state INITIALIZED),
958 // and is started higher up in the call chain
959 assert(state == INITIALIZED, "race condition");
960 return true;
961 }
963 /////////////////////////////////////////////////////////////////////////////
964 // attach existing thread
966 // bootstrap the main thread
967 bool os::create_main_thread(JavaThread* thread) {
968 assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread");
969 return create_attached_thread(thread);
970 }
972 bool os::create_attached_thread(JavaThread* thread) {
973 #ifdef ASSERT
974 thread->verify_not_published();
975 #endif
977 // Allocate the OSThread object
978 OSThread* osthread = new OSThread(NULL, NULL);
980 if (osthread == NULL) {
981 return false;
982 }
984 // Store pthread info into the OSThread
985 osthread->set_thread_id(os::Linux::gettid());
986 osthread->set_pthread_id(::pthread_self());
988 // initialize floating point control register
989 os::Linux::init_thread_fpu_state();
991 // Initial thread state is RUNNABLE
992 osthread->set_state(RUNNABLE);
994 thread->set_osthread(osthread);
996 if (UseNUMA) {
997 int lgrp_id = os::numa_get_group_id();
998 if (lgrp_id != -1) {
999 thread->set_lgrp_id(lgrp_id);
1000 }
1001 }
1003 if (os::is_primordial_thread()) {
1004 // If current thread is primordial thread, its stack is mapped on demand,
1005 // see notes about MAP_GROWSDOWN. Here we try to force kernel to map
1006 // the entire stack region to avoid SEGV in stack banging.
1007 // It is also useful to get around the heap-stack-gap problem on SuSE
1008 // kernel (see 4821821 for details). We first expand stack to the top
1009 // of yellow zone, then enable stack yellow zone (order is significant,
1010 // enabling yellow zone first will crash JVM on SuSE Linux), so there
1011 // is no gap between the last two virtual memory regions.
1013 JavaThread *jt = (JavaThread *)thread;
1014 address addr = jt->stack_yellow_zone_base();
1015 assert(addr != NULL, "initialization problem?");
1016 assert(jt->stack_available(addr) > 0, "stack guard should not be enabled");
1018 osthread->set_expanding_stack();
1019 os::Linux::manually_expand_stack(jt, addr);
1020 osthread->clear_expanding_stack();
1021 }
1023 // initialize signal mask for this thread
1024 // and save the caller's signal mask
1025 os::Linux::hotspot_sigmask(thread);
1027 return true;
1028 }
1030 void os::pd_start_thread(Thread* thread) {
1031 OSThread * osthread = thread->osthread();
1032 assert(osthread->get_state() != INITIALIZED, "just checking");
1033 Monitor* sync_with_child = osthread->startThread_lock();
1034 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
1035 sync_with_child->notify();
1036 }
1038 // Free Linux resources related to the OSThread
1039 void os::free_thread(OSThread* osthread) {
1040 assert(osthread != NULL, "osthread not set");
1042 if (Thread::current()->osthread() == osthread) {
1043 // Restore caller's signal mask
1044 sigset_t sigmask = osthread->caller_sigmask();
1045 pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
1046 }
1048 delete osthread;
1049 }
1051 //////////////////////////////////////////////////////////////////////////////
1052 // thread local storage
1054 // Restore the thread pointer if the destructor is called. This is in case
1055 // someone from JNI code sets up a destructor with pthread_key_create to run
1056 // detachCurrentThread on thread death. Unless we restore the thread pointer we
1057 // will hang or crash. When detachCurrentThread is called the key will be set
1058 // to null and we will not be called again. If detachCurrentThread is never
1059 // called we could loop forever depending on the pthread implementation.
1060 static void restore_thread_pointer(void* p) {
1061 Thread* thread = (Thread*) p;
1062 os::thread_local_storage_at_put(ThreadLocalStorage::thread_index(), thread);
1063 }
1065 int os::allocate_thread_local_storage() {
1066 pthread_key_t key;
1067 int rslt = pthread_key_create(&key, restore_thread_pointer);
1068 assert(rslt == 0, "cannot allocate thread local storage");
1069 return (int)key;
1070 }
1072 // Note: This is currently not used by VM, as we don't destroy TLS key
1073 // on VM exit.
1074 void os::free_thread_local_storage(int index) {
1075 int rslt = pthread_key_delete((pthread_key_t)index);
1076 assert(rslt == 0, "invalid index");
1077 }
1079 void os::thread_local_storage_at_put(int index, void* value) {
1080 int rslt = pthread_setspecific((pthread_key_t)index, value);
1081 assert(rslt == 0, "pthread_setspecific failed");
1082 }
1084 extern "C" Thread* get_thread() {
1085 return ThreadLocalStorage::thread();
1086 }
1088 //////////////////////////////////////////////////////////////////////////////
1089 // primordial thread
1091 // Check if current thread is the primordial thread, similar to Solaris thr_main.
1092 bool os::is_primordial_thread(void) {
1093 char dummy;
1094 // If called before init complete, thread stack bottom will be null.
1095 // Can be called if fatal error occurs before initialization.
1096 if (os::Linux::initial_thread_stack_bottom() == NULL) return false;
1097 assert(os::Linux::initial_thread_stack_bottom() != NULL &&
1098 os::Linux::initial_thread_stack_size() != 0,
1099 "os::init did not locate primordial thread's stack region");
1100 if ((address)&dummy >= os::Linux::initial_thread_stack_bottom() &&
1101 (address)&dummy < os::Linux::initial_thread_stack_bottom() +
1102 os::Linux::initial_thread_stack_size()) {
1103 return true;
1104 } else {
1105 return false;
1106 }
1107 }
1109 // Find the virtual memory area that contains addr
1110 static bool find_vma(address addr, address* vma_low, address* vma_high) {
1111 FILE *fp = fopen("/proc/self/maps", "r");
1112 if (fp) {
1113 address low, high;
1114 while (!feof(fp)) {
1115 if (fscanf(fp, "%p-%p", &low, &high) == 2) {
1116 if (low <= addr && addr < high) {
1117 if (vma_low) *vma_low = low;
1118 if (vma_high) *vma_high = high;
1119 fclose (fp);
1120 return true;
1121 }
1122 }
1123 for (;;) {
1124 int ch = fgetc(fp);
1125 if (ch == EOF || ch == (int)'\n') break;
1126 }
1127 }
1128 fclose(fp);
1129 }
1130 return false;
1131 }
1133 // Locate primordial thread stack. This special handling of primordial thread stack
1134 // is needed because pthread_getattr_np() on most (all?) Linux distros returns
1135 // bogus value for the primordial process thread. While the launcher has created
1136 // the VM in a new thread since JDK 6, we still have to allow for the use of the
1137 // JNI invocation API from a primordial thread.
1138 void os::Linux::capture_initial_stack(size_t max_size) {
1140 // max_size is either 0 (which means accept OS default for thread stacks) or
1141 // a user-specified value known to be at least the minimum needed. If we
1142 // are actually on the primordial thread we can make it appear that we have a
1143 // smaller max_size stack by inserting the guard pages at that location. But we
1144 // cannot do anything to emulate a larger stack than what has been provided by
1145 // the OS or threading library. In fact if we try to use a stack greater than
1146 // what is set by rlimit then we will crash the hosting process.
1148 // Maximum stack size is the easy part, get it from RLIMIT_STACK.
1149 // If this is "unlimited" then it will be a huge value.
1150 struct rlimit rlim;
1151 getrlimit(RLIMIT_STACK, &rlim);
1152 size_t stack_size = rlim.rlim_cur;
1154 // 6308388: a bug in ld.so will relocate its own .data section to the
1155 // lower end of primordial stack; reduce ulimit -s value a little bit
1156 // so we won't install guard page on ld.so's data section.
1157 // But ensure we don't underflow the stack size - allow 1 page spare
1158 if (stack_size >= (size_t)(3 * page_size())) {
1159 stack_size -= 2 * page_size();
1160 }
1162 // Try to figure out where the stack base (top) is. This is harder.
1163 //
1164 // When an application is started, glibc saves the initial stack pointer in
1165 // a global variable "__libc_stack_end", which is then used by system
1166 // libraries. __libc_stack_end should be pretty close to stack top. The
1167 // variable is available since the very early days. However, because it is
1168 // a private interface, it could disappear in the future.
1169 //
1170 // Linux kernel saves start_stack information in /proc/<pid>/stat. Similar
1171 // to __libc_stack_end, it is very close to stack top, but isn't the real
1172 // stack top. Note that /proc may not exist if VM is running as a chroot
1173 // program, so reading /proc/<pid>/stat could fail. Also the contents of
1174 // /proc/<pid>/stat could change in the future (though unlikely).
1175 //
1176 // We try __libc_stack_end first. If that doesn't work, look for
1177 // /proc/<pid>/stat. If neither of them works, we use current stack pointer
1178 // as a hint, which should work well in most cases.
1180 uintptr_t stack_start;
1182 // try __libc_stack_end first
1183 uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end");
1184 if (p && *p) {
1185 stack_start = *p;
1186 } else {
1187 // see if we can get the start_stack field from /proc/self/stat
1188 FILE *fp;
1189 int pid;
1190 char state;
1191 int ppid;
1192 int pgrp;
1193 int session;
1194 int nr;
1195 int tpgrp;
1196 unsigned long flags;
1197 unsigned long minflt;
1198 unsigned long cminflt;
1199 unsigned long majflt;
1200 unsigned long cmajflt;
1201 unsigned long utime;
1202 unsigned long stime;
1203 long cutime;
1204 long cstime;
1205 long prio;
1206 long nice;
1207 long junk;
1208 long it_real;
1209 uintptr_t start;
1210 uintptr_t vsize;
1211 intptr_t rss;
1212 uintptr_t rsslim;
1213 uintptr_t scodes;
1214 uintptr_t ecode;
1215 int i;
1217 // Figure what the primordial thread stack base is. Code is inspired
1218 // by email from Hans Boehm. /proc/self/stat begins with current pid,
1219 // followed by command name surrounded by parentheses, state, etc.
1220 char stat[2048];
1221 int statlen;
1223 fp = fopen("/proc/self/stat", "r");
1224 if (fp) {
1225 statlen = fread(stat, 1, 2047, fp);
1226 stat[statlen] = '\0';
1227 fclose(fp);
1229 // Skip pid and the command string. Note that we could be dealing with
1230 // weird command names, e.g. user could decide to rename java launcher
1231 // to "java 1.4.2 :)", then the stat file would look like
1232 // 1234 (java 1.4.2 :)) R ... ...
1233 // We don't really need to know the command string, just find the last
1234 // occurrence of ")" and then start parsing from there. See bug 4726580.
1235 char * s = strrchr(stat, ')');
1237 i = 0;
1238 if (s) {
1239 // Skip blank chars
1240 do s++; while (isspace(*s));
1242 #define _UFM UINTX_FORMAT
1243 #define _DFM INTX_FORMAT
1245 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 */
1246 /* 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 */
1247 i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " _UFM _UFM _DFM _UFM _UFM _UFM _UFM,
1248 &state, /* 3 %c */
1249 &ppid, /* 4 %d */
1250 &pgrp, /* 5 %d */
1251 &session, /* 6 %d */
1252 &nr, /* 7 %d */
1253 &tpgrp, /* 8 %d */
1254 &flags, /* 9 %lu */
1255 &minflt, /* 10 %lu */
1256 &cminflt, /* 11 %lu */
1257 &majflt, /* 12 %lu */
1258 &cmajflt, /* 13 %lu */
1259 &utime, /* 14 %lu */
1260 &stime, /* 15 %lu */
1261 &cutime, /* 16 %ld */
1262 &cstime, /* 17 %ld */
1263 &prio, /* 18 %ld */
1264 &nice, /* 19 %ld */
1265 &junk, /* 20 %ld */
1266 &it_real, /* 21 %ld */
1267 &start, /* 22 UINTX_FORMAT */
1268 &vsize, /* 23 UINTX_FORMAT */
1269 &rss, /* 24 INTX_FORMAT */
1270 &rsslim, /* 25 UINTX_FORMAT */
1271 &scodes, /* 26 UINTX_FORMAT */
1272 &ecode, /* 27 UINTX_FORMAT */
1273 &stack_start); /* 28 UINTX_FORMAT */
1274 }
1276 #undef _UFM
1277 #undef _DFM
1279 if (i != 28 - 2) {
1280 assert(false, "Bad conversion from /proc/self/stat");
1281 // product mode - assume we are the primordial thread, good luck in the
1282 // embedded case.
1283 warning("Can't detect primordial thread stack location - bad conversion");
1284 stack_start = (uintptr_t) &rlim;
1285 }
1286 } else {
1287 // For some reason we can't open /proc/self/stat (for example, running on
1288 // FreeBSD with a Linux emulator, or inside chroot), this should work for
1289 // most cases, so don't abort:
1290 warning("Can't detect primordial thread stack location - no /proc/self/stat");
1291 stack_start = (uintptr_t) &rlim;
1292 }
1293 }
1295 // Now we have a pointer (stack_start) very close to the stack top, the
1296 // next thing to do is to figure out the exact location of stack top. We
1297 // can find out the virtual memory area that contains stack_start by
1298 // reading /proc/self/maps, it should be the last vma in /proc/self/maps,
1299 // and its upper limit is the real stack top. (again, this would fail if
1300 // running inside chroot, because /proc may not exist.)
1302 uintptr_t stack_top;
1303 address low, high;
1304 if (find_vma((address)stack_start, &low, &high)) {
1305 // success, "high" is the true stack top. (ignore "low", because initial
1306 // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.)
1307 stack_top = (uintptr_t)high;
1308 } else {
1309 // failed, likely because /proc/self/maps does not exist
1310 warning("Can't detect primordial thread stack location - find_vma failed");
1311 // best effort: stack_start is normally within a few pages below the real
1312 // stack top, use it as stack top, and reduce stack size so we won't put
1313 // guard page outside stack.
1314 stack_top = stack_start;
1315 stack_size -= 16 * page_size();
1316 }
1318 // stack_top could be partially down the page so align it
1319 stack_top = align_size_up(stack_top, page_size());
1321 // Allowed stack value is minimum of max_size and what we derived from rlimit
1322 if (max_size > 0) {
1323 _initial_thread_stack_size = MIN2(max_size, stack_size);
1324 } else {
1325 // Accept the rlimit max, but if stack is unlimited then it will be huge, so
1326 // clamp it at 8MB as we do on Solaris
1327 _initial_thread_stack_size = MIN2(stack_size, 8*M);
1328 }
1330 _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size());
1331 _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size;
1332 assert(_initial_thread_stack_bottom < (address)stack_top, "overflow!");
1333 }
1335 ////////////////////////////////////////////////////////////////////////////////
1336 // time support
1338 // Time since start-up in seconds to a fine granularity.
1339 // Used by VMSelfDestructTimer and the MemProfiler.
1340 double os::elapsedTime() {
1342 return ((double)os::elapsed_counter()) / os::elapsed_frequency(); // nanosecond resolution
1343 }
1345 jlong os::elapsed_counter() {
1346 return javaTimeNanos() - initial_time_count;
1347 }
1349 jlong os::elapsed_frequency() {
1350 return NANOSECS_PER_SEC; // nanosecond resolution
1351 }
1353 bool os::supports_vtime() { return true; }
1354 bool os::enable_vtime() { return false; }
1355 bool os::vtime_enabled() { return false; }
1357 double os::elapsedVTime() {
1358 struct rusage usage;
1359 int retval = getrusage(RUSAGE_THREAD, &usage);
1360 if (retval == 0) {
1361 return (double) (usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) + (double) (usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / (1000 * 1000);
1362 } else {
1363 // better than nothing, but not much
1364 return elapsedTime();
1365 }
1366 }
1368 jlong os::javaTimeMillis() {
1369 timeval time;
1370 int status = gettimeofday(&time, NULL);
1371 assert(status != -1, "linux error");
1372 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000);
1373 }
1375 #ifndef CLOCK_MONOTONIC
1376 #define CLOCK_MONOTONIC (1)
1377 #endif
1379 void os::Linux::clock_init() {
1380 // we do dlopen's in this particular order due to bug in linux
1381 // dynamical loader (see 6348968) leading to crash on exit
1382 void* handle = dlopen("librt.so.1", RTLD_LAZY);
1383 if (handle == NULL) {
1384 handle = dlopen("librt.so", RTLD_LAZY);
1385 }
1387 if (handle) {
1388 int (*clock_getres_func)(clockid_t, struct timespec*) =
1389 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres");
1390 int (*clock_gettime_func)(clockid_t, struct timespec*) =
1391 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime");
1392 if (clock_getres_func && clock_gettime_func) {
1393 // See if monotonic clock is supported by the kernel. Note that some
1394 // early implementations simply return kernel jiffies (updated every
1395 // 1/100 or 1/1000 second). It would be bad to use such a low res clock
1396 // for nano time (though the monotonic property is still nice to have).
1397 // It's fixed in newer kernels, however clock_getres() still returns
1398 // 1/HZ. We check if clock_getres() works, but will ignore its reported
1399 // resolution for now. Hopefully as people move to new kernels, this
1400 // won't be a problem.
1401 struct timespec res;
1402 struct timespec tp;
1403 if (clock_getres_func (CLOCK_MONOTONIC, &res) == 0 &&
1404 clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) {
1405 // yes, monotonic clock is supported
1406 _clock_gettime = clock_gettime_func;
1407 return;
1408 } else {
1409 // close librt if there is no monotonic clock
1410 dlclose(handle);
1411 }
1412 }
1413 }
1414 warning("No monotonic clock was available - timed services may " \
1415 "be adversely affected if the time-of-day clock changes");
1416 }
1418 #ifndef SYS_clock_getres
1420 #if defined(IA32) || defined(AMD64)
1421 #define SYS_clock_getres IA32_ONLY(266) AMD64_ONLY(229)
1422 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y)
1423 #else
1424 #warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time"
1425 #define sys_clock_getres(x,y) -1
1426 #endif
1428 #else
1429 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y)
1430 #endif
1432 void os::Linux::fast_thread_clock_init() {
1433 if (!UseLinuxPosixThreadCPUClocks) {
1434 return;
1435 }
1436 clockid_t clockid;
1437 struct timespec tp;
1438 int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) =
1439 (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid");
1441 // Switch to using fast clocks for thread cpu time if
1442 // the sys_clock_getres() returns 0 error code.
1443 // Note, that some kernels may support the current thread
1444 // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks
1445 // returned by the pthread_getcpuclockid().
1446 // If the fast Posix clocks are supported then the sys_clock_getres()
1447 // must return at least tp.tv_sec == 0 which means a resolution
1448 // better than 1 sec. This is extra check for reliability.
1450 if(pthread_getcpuclockid_func &&
1451 pthread_getcpuclockid_func(_main_thread, &clockid) == 0 &&
1452 sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) {
1454 _supports_fast_thread_cpu_time = true;
1455 _pthread_getcpuclockid = pthread_getcpuclockid_func;
1456 }
1457 }
1459 jlong os::javaTimeNanos() {
1460 if (Linux::supports_monotonic_clock()) {
1461 struct timespec tp;
1462 int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp);
1463 assert(status == 0, "gettime error");
1464 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
1465 return result;
1466 } else {
1467 timeval time;
1468 int status = gettimeofday(&time, NULL);
1469 assert(status != -1, "linux error");
1470 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
1471 return 1000 * usecs;
1472 }
1473 }
1475 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1476 if (Linux::supports_monotonic_clock()) {
1477 info_ptr->max_value = ALL_64_BITS;
1479 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
1480 info_ptr->may_skip_backward = false; // not subject to resetting or drifting
1481 info_ptr->may_skip_forward = false; // not subject to resetting or drifting
1482 } else {
1483 // gettimeofday - based on time in seconds since the Epoch thus does not wrap
1484 info_ptr->max_value = ALL_64_BITS;
1486 // gettimeofday is a real time clock so it skips
1487 info_ptr->may_skip_backward = true;
1488 info_ptr->may_skip_forward = true;
1489 }
1491 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time
1492 }
1494 // Return the real, user, and system times in seconds from an
1495 // arbitrary fixed point in the past.
1496 bool os::getTimesSecs(double* process_real_time,
1497 double* process_user_time,
1498 double* process_system_time) {
1499 struct tms ticks;
1500 clock_t real_ticks = times(&ticks);
1502 if (real_ticks == (clock_t) (-1)) {
1503 return false;
1504 } else {
1505 double ticks_per_second = (double) clock_tics_per_sec;
1506 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1507 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1508 *process_real_time = ((double) real_ticks) / ticks_per_second;
1510 return true;
1511 }
1512 }
1515 char * os::local_time_string(char *buf, size_t buflen) {
1516 struct tm t;
1517 time_t long_time;
1518 time(&long_time);
1519 localtime_r(&long_time, &t);
1520 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1521 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1522 t.tm_hour, t.tm_min, t.tm_sec);
1523 return buf;
1524 }
1526 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {
1527 return localtime_r(clock, res);
1528 }
1530 ////////////////////////////////////////////////////////////////////////////////
1531 // runtime exit support
1533 // Note: os::shutdown() might be called very early during initialization, or
1534 // called from signal handler. Before adding something to os::shutdown(), make
1535 // sure it is async-safe and can handle partially initialized VM.
1536 void os::shutdown() {
1538 // allow PerfMemory to attempt cleanup of any persistent resources
1539 perfMemory_exit();
1541 // needs to remove object in file system
1542 AttachListener::abort();
1544 // flush buffered output, finish log files
1545 ostream_abort();
1547 // Check for abort hook
1548 abort_hook_t abort_hook = Arguments::abort_hook();
1549 if (abort_hook != NULL) {
1550 abort_hook();
1551 }
1553 }
1555 // Note: os::abort() might be called very early during initialization, or
1556 // called from signal handler. Before adding something to os::abort(), make
1557 // sure it is async-safe and can handle partially initialized VM.
1558 void os::abort(bool dump_core) {
1559 os::shutdown();
1560 if (dump_core) {
1561 #ifndef PRODUCT
1562 fdStream out(defaultStream::output_fd());
1563 out.print_raw("Current thread is ");
1564 char buf[16];
1565 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1566 out.print_raw_cr(buf);
1567 out.print_raw_cr("Dumping core ...");
1568 #endif
1569 ::abort(); // dump core
1570 }
1572 ::exit(1);
1573 }
1575 // Die immediately, no exit hook, no abort hook, no cleanup.
1576 void os::die() {
1577 // _exit() on LinuxThreads only kills current thread
1578 ::abort();
1579 }
1582 // This method is a copy of JDK's sysGetLastErrorString
1583 // from src/solaris/hpi/src/system_md.c
1585 size_t os::lasterror(char *buf, size_t len) {
1587 if (errno == 0) return 0;
1589 const char *s = ::strerror(errno);
1590 size_t n = ::strlen(s);
1591 if (n >= len) {
1592 n = len - 1;
1593 }
1594 ::strncpy(buf, s, n);
1595 buf[n] = '\0';
1596 return n;
1597 }
1599 intx os::current_thread_id() { return (intx)pthread_self(); }
1600 int os::current_process_id() {
1602 // Under the old linux thread library, linux gives each thread
1603 // its own process id. Because of this each thread will return
1604 // a different pid if this method were to return the result
1605 // of getpid(2). Linux provides no api that returns the pid
1606 // of the launcher thread for the vm. This implementation
1607 // returns a unique pid, the pid of the launcher thread
1608 // that starts the vm 'process'.
1610 // Under the NPTL, getpid() returns the same pid as the
1611 // launcher thread rather than a unique pid per thread.
1612 // Use gettid() if you want the old pre NPTL behaviour.
1614 // if you are looking for the result of a call to getpid() that
1615 // returns a unique pid for the calling thread, then look at the
1616 // OSThread::thread_id() method in osThread_linux.hpp file
1618 return (int)(_initial_pid ? _initial_pid : getpid());
1619 }
1621 // DLL functions
1623 const char* os::dll_file_extension() { return ".so"; }
1625 // This must be hard coded because it's the system's temporary
1626 // directory not the java application's temp directory, ala java.io.tmpdir.
1627 const char* os::get_temp_directory() { return "/tmp"; }
1629 static bool file_exists(const char* filename) {
1630 struct stat statbuf;
1631 if (filename == NULL || strlen(filename) == 0) {
1632 return false;
1633 }
1634 return os::stat(filename, &statbuf) == 0;
1635 }
1637 bool os::dll_build_name(char* buffer, size_t buflen,
1638 const char* pname, const char* fname) {
1639 bool retval = false;
1640 // Copied from libhpi
1641 const size_t pnamelen = pname ? strlen(pname) : 0;
1643 // Return error on buffer overflow.
1644 if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {
1645 return retval;
1646 }
1648 if (pnamelen == 0) {
1649 snprintf(buffer, buflen, "lib%s.so", fname);
1650 retval = true;
1651 } else if (strchr(pname, *os::path_separator()) != NULL) {
1652 int n;
1653 char** pelements = split_path(pname, &n);
1654 if (pelements == NULL) {
1655 return false;
1656 }
1657 for (int i = 0 ; i < n ; i++) {
1658 // Really shouldn't be NULL, but check can't hurt
1659 if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
1660 continue; // skip the empty path values
1661 }
1662 snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);
1663 if (file_exists(buffer)) {
1664 retval = true;
1665 break;
1666 }
1667 }
1668 // release the storage
1669 for (int i = 0 ; i < n ; i++) {
1670 if (pelements[i] != NULL) {
1671 FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);
1672 }
1673 }
1674 if (pelements != NULL) {
1675 FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);
1676 }
1677 } else {
1678 snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);
1679 retval = true;
1680 }
1681 return retval;
1682 }
1684 // check if addr is inside libjvm.so
1685 bool os::address_is_in_vm(address addr) {
1686 static address libjvm_base_addr;
1687 Dl_info dlinfo;
1689 if (libjvm_base_addr == NULL) {
1690 if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1691 libjvm_base_addr = (address)dlinfo.dli_fbase;
1692 }
1693 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1694 }
1696 if (dladdr((void *)addr, &dlinfo) != 0) {
1697 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1698 }
1700 return false;
1701 }
1703 bool os::dll_address_to_function_name(address addr, char *buf,
1704 int buflen, int *offset) {
1705 // buf is not optional, but offset is optional
1706 assert(buf != NULL, "sanity check");
1708 Dl_info dlinfo;
1710 if (dladdr((void*)addr, &dlinfo) != 0) {
1711 // see if we have a matching symbol
1712 if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1713 if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {
1714 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1715 }
1716 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1717 return true;
1718 }
1719 // no matching symbol so try for just file info
1720 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1721 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1722 buf, buflen, offset, dlinfo.dli_fname)) {
1723 return true;
1724 }
1725 }
1726 }
1728 buf[0] = '\0';
1729 if (offset != NULL) *offset = -1;
1730 return false;
1731 }
1733 struct _address_to_library_name {
1734 address addr; // input : memory address
1735 size_t buflen; // size of fname
1736 char* fname; // output: library name
1737 address base; // library base addr
1738 };
1740 static int address_to_library_name_callback(struct dl_phdr_info *info,
1741 size_t size, void *data) {
1742 int i;
1743 bool found = false;
1744 address libbase = NULL;
1745 struct _address_to_library_name * d = (struct _address_to_library_name *)data;
1747 // iterate through all loadable segments
1748 for (i = 0; i < info->dlpi_phnum; i++) {
1749 address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1750 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1751 // base address of a library is the lowest address of its loaded
1752 // segments.
1753 if (libbase == NULL || libbase > segbase) {
1754 libbase = segbase;
1755 }
1756 // see if 'addr' is within current segment
1757 if (segbase <= d->addr &&
1758 d->addr < segbase + info->dlpi_phdr[i].p_memsz) {
1759 found = true;
1760 }
1761 }
1762 }
1764 // dlpi_name is NULL or empty if the ELF file is executable, return 0
1765 // so dll_address_to_library_name() can fall through to use dladdr() which
1766 // can figure out executable name from argv[0].
1767 if (found && info->dlpi_name && info->dlpi_name[0]) {
1768 d->base = libbase;
1769 if (d->fname) {
1770 jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name);
1771 }
1772 return 1;
1773 }
1774 return 0;
1775 }
1777 bool os::dll_address_to_library_name(address addr, char* buf,
1778 int buflen, int* offset) {
1779 // buf is not optional, but offset is optional
1780 assert(buf != NULL, "sanity check");
1782 Dl_info dlinfo;
1783 struct _address_to_library_name data;
1785 // There is a bug in old glibc dladdr() implementation that it could resolve
1786 // to wrong library name if the .so file has a base address != NULL. Here
1787 // we iterate through the program headers of all loaded libraries to find
1788 // out which library 'addr' really belongs to. This workaround can be
1789 // removed once the minimum requirement for glibc is moved to 2.3.x.
1790 data.addr = addr;
1791 data.fname = buf;
1792 data.buflen = buflen;
1793 data.base = NULL;
1794 int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data);
1796 if (rslt) {
1797 // buf already contains library name
1798 if (offset) *offset = addr - data.base;
1799 return true;
1800 }
1801 if (dladdr((void*)addr, &dlinfo) != 0) {
1802 if (dlinfo.dli_fname != NULL) {
1803 jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1804 }
1805 if (dlinfo.dli_fbase != NULL && offset != NULL) {
1806 *offset = addr - (address)dlinfo.dli_fbase;
1807 }
1808 return true;
1809 }
1811 buf[0] = '\0';
1812 if (offset) *offset = -1;
1813 return false;
1814 }
1816 // Loads .dll/.so and
1817 // in case of error it checks if .dll/.so was built for the
1818 // same architecture as Hotspot is running on
1821 // Remember the stack's state. The Linux dynamic linker will change
1822 // the stack to 'executable' at most once, so we must safepoint only once.
1823 bool os::Linux::_stack_is_executable = false;
1825 // VM operation that loads a library. This is necessary if stack protection
1826 // of the Java stacks can be lost during loading the library. If we
1827 // do not stop the Java threads, they can stack overflow before the stacks
1828 // are protected again.
1829 class VM_LinuxDllLoad: public VM_Operation {
1830 private:
1831 const char *_filename;
1832 char *_ebuf;
1833 int _ebuflen;
1834 void *_lib;
1835 public:
1836 VM_LinuxDllLoad(const char *fn, char *ebuf, int ebuflen) :
1837 _filename(fn), _ebuf(ebuf), _ebuflen(ebuflen), _lib(NULL) {}
1838 VMOp_Type type() const { return VMOp_LinuxDllLoad; }
1839 void doit() {
1840 _lib = os::Linux::dll_load_in_vmthread(_filename, _ebuf, _ebuflen);
1841 os::Linux::_stack_is_executable = true;
1842 }
1843 void* loaded_library() { return _lib; }
1844 };
1846 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
1847 {
1848 void * result = NULL;
1849 bool load_attempted = false;
1851 // Check whether the library to load might change execution rights
1852 // of the stack. If they are changed, the protection of the stack
1853 // guard pages will be lost. We need a safepoint to fix this.
1854 //
1855 // See Linux man page execstack(8) for more info.
1856 if (os::uses_stack_guard_pages() && !os::Linux::_stack_is_executable) {
1857 ElfFile ef(filename);
1858 if (!ef.specifies_noexecstack()) {
1859 if (!is_init_completed()) {
1860 os::Linux::_stack_is_executable = true;
1861 // This is OK - No Java threads have been created yet, and hence no
1862 // stack guard pages to fix.
1863 //
1864 // This should happen only when you are building JDK7 using a very
1865 // old version of JDK6 (e.g., with JPRT) and running test_gamma.
1866 //
1867 // Dynamic loader will make all stacks executable after
1868 // this function returns, and will not do that again.
1869 assert(Threads::first() == NULL, "no Java threads should exist yet.");
1870 } else {
1871 warning("You have loaded library %s which might have disabled stack guard. "
1872 "The VM will try to fix the stack guard now.\n"
1873 "It's highly recommended that you fix the library with "
1874 "'execstack -c <libfile>', or link it with '-z noexecstack'.",
1875 filename);
1877 assert(Thread::current()->is_Java_thread(), "must be Java thread");
1878 JavaThread *jt = JavaThread::current();
1879 if (jt->thread_state() != _thread_in_native) {
1880 // This happens when a compiler thread tries to load a hsdis-<arch>.so file
1881 // that requires ExecStack. Cannot enter safe point. Let's give up.
1882 warning("Unable to fix stack guard. Giving up.");
1883 } else {
1884 if (!LoadExecStackDllInVMThread) {
1885 // This is for the case where the DLL has an static
1886 // constructor function that executes JNI code. We cannot
1887 // load such DLLs in the VMThread.
1888 result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1889 }
1891 ThreadInVMfromNative tiv(jt);
1892 debug_only(VMNativeEntryWrapper vew;)
1894 VM_LinuxDllLoad op(filename, ebuf, ebuflen);
1895 VMThread::execute(&op);
1896 if (LoadExecStackDllInVMThread) {
1897 result = op.loaded_library();
1898 }
1899 load_attempted = true;
1900 }
1901 }
1902 }
1903 }
1905 if (!load_attempted) {
1906 result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1907 }
1909 if (result != NULL) {
1910 // Successful loading
1911 return result;
1912 }
1914 Elf32_Ehdr elf_head;
1915 int diag_msg_max_length=ebuflen-strlen(ebuf);
1916 char* diag_msg_buf=ebuf+strlen(ebuf);
1918 if (diag_msg_max_length==0) {
1919 // No more space in ebuf for additional diagnostics message
1920 return NULL;
1921 }
1924 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1926 if (file_descriptor < 0) {
1927 // Can't open library, report dlerror() message
1928 return NULL;
1929 }
1931 bool failed_to_read_elf_head=
1932 (sizeof(elf_head)!=
1933 (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;
1935 ::close(file_descriptor);
1936 if (failed_to_read_elf_head) {
1937 // file i/o error - report dlerror() msg
1938 return NULL;
1939 }
1941 typedef struct {
1942 Elf32_Half code; // Actual value as defined in elf.h
1943 Elf32_Half compat_class; // Compatibility of archs at VM's sense
1944 char elf_class; // 32 or 64 bit
1945 char endianess; // MSB or LSB
1946 char* name; // String representation
1947 } arch_t;
1949 #ifndef EM_486
1950 #define EM_486 6 /* Intel 80486 */
1951 #endif
1953 static const arch_t arch_array[]={
1954 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1955 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1956 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1957 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1958 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1959 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1960 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1961 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1962 #if defined(VM_LITTLE_ENDIAN)
1963 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2LSB, (char*)"Power PC 64 LE"},
1964 #else
1965 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1966 #endif
1967 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},
1968 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1969 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1970 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1971 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1972 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1973 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1974 };
1976 #if (defined IA32)
1977 static Elf32_Half running_arch_code=EM_386;
1978 #elif (defined AMD64)
1979 static Elf32_Half running_arch_code=EM_X86_64;
1980 #elif (defined IA64)
1981 static Elf32_Half running_arch_code=EM_IA_64;
1982 #elif (defined __sparc) && (defined _LP64)
1983 static Elf32_Half running_arch_code=EM_SPARCV9;
1984 #elif (defined __sparc) && (!defined _LP64)
1985 static Elf32_Half running_arch_code=EM_SPARC;
1986 #elif (defined __powerpc64__)
1987 static Elf32_Half running_arch_code=EM_PPC64;
1988 #elif (defined __powerpc__)
1989 static Elf32_Half running_arch_code=EM_PPC;
1990 #elif (defined ARM)
1991 static Elf32_Half running_arch_code=EM_ARM;
1992 #elif (defined S390)
1993 static Elf32_Half running_arch_code=EM_S390;
1994 #elif (defined ALPHA)
1995 static Elf32_Half running_arch_code=EM_ALPHA;
1996 #elif (defined MIPSEL)
1997 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1998 #elif (defined PARISC)
1999 static Elf32_Half running_arch_code=EM_PARISC;
2000 #elif (defined MIPS)
2001 static Elf32_Half running_arch_code=EM_MIPS;
2002 #elif (defined M68K)
2003 static Elf32_Half running_arch_code=EM_68K;
2004 #else
2005 #error Method os::dll_load requires that one of following is defined:\
2006 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
2007 #endif
2009 // Identify compatability class for VM's architecture and library's architecture
2010 // Obtain string descriptions for architectures
2012 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
2013 int running_arch_index=-1;
2015 for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
2016 if (running_arch_code == arch_array[i].code) {
2017 running_arch_index = i;
2018 }
2019 if (lib_arch.code == arch_array[i].code) {
2020 lib_arch.compat_class = arch_array[i].compat_class;
2021 lib_arch.name = arch_array[i].name;
2022 }
2023 }
2025 assert(running_arch_index != -1,
2026 "Didn't find running architecture code (running_arch_code) in arch_array");
2027 if (running_arch_index == -1) {
2028 // Even though running architecture detection failed
2029 // we may still continue with reporting dlerror() message
2030 return NULL;
2031 }
2033 if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
2034 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
2035 return NULL;
2036 }
2038 #ifndef S390
2039 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
2040 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
2041 return NULL;
2042 }
2043 #endif // !S390
2045 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
2046 if ( lib_arch.name!=NULL ) {
2047 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
2048 " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
2049 lib_arch.name, arch_array[running_arch_index].name);
2050 } else {
2051 ::snprintf(diag_msg_buf, diag_msg_max_length-1,
2052 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
2053 lib_arch.code,
2054 arch_array[running_arch_index].name);
2055 }
2056 }
2058 return NULL;
2059 }
2061 void * os::Linux::dlopen_helper(const char *filename, char *ebuf, int ebuflen) {
2062 void * result = ::dlopen(filename, RTLD_LAZY);
2063 if (result == NULL) {
2064 ::strncpy(ebuf, ::dlerror(), ebuflen - 1);
2065 ebuf[ebuflen-1] = '\0';
2066 }
2067 return result;
2068 }
2070 void * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf, int ebuflen) {
2071 void * result = NULL;
2072 if (LoadExecStackDllInVMThread) {
2073 result = dlopen_helper(filename, ebuf, ebuflen);
2074 }
2076 // Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a
2077 // library that requires an executable stack, or which does not have this
2078 // stack attribute set, dlopen changes the stack attribute to executable. The
2079 // read protection of the guard pages gets lost.
2080 //
2081 // Need to check _stack_is_executable again as multiple VM_LinuxDllLoad
2082 // may have been queued at the same time.
2084 if (!_stack_is_executable) {
2085 JavaThread *jt = Threads::first();
2087 while (jt) {
2088 if (!jt->stack_guard_zone_unused() && // Stack not yet fully initialized
2089 jt->stack_yellow_zone_enabled()) { // No pending stack overflow exceptions
2090 if (!os::guard_memory((char *) jt->stack_red_zone_base() - jt->stack_red_zone_size(),
2091 jt->stack_yellow_zone_size() + jt->stack_red_zone_size())) {
2092 warning("Attempt to reguard stack yellow zone failed.");
2093 }
2094 }
2095 jt = jt->next();
2096 }
2097 }
2099 return result;
2100 }
2102 /*
2103 * glibc-2.0 libdl is not MT safe. If you are building with any glibc,
2104 * chances are you might want to run the generated bits against glibc-2.0
2105 * libdl.so, so always use locking for any version of glibc.
2106 */
2107 void* os::dll_lookup(void* handle, const char* name) {
2108 pthread_mutex_lock(&dl_mutex);
2109 void* res = dlsym(handle, name);
2110 pthread_mutex_unlock(&dl_mutex);
2111 return res;
2112 }
2114 void* os::get_default_process_handle() {
2115 return (void*)::dlopen(NULL, RTLD_LAZY);
2116 }
2118 static bool _print_ascii_file(const char* filename, outputStream* st) {
2119 int fd = ::open(filename, O_RDONLY);
2120 if (fd == -1) {
2121 return false;
2122 }
2124 char buf[32];
2125 int bytes;
2126 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
2127 st->print_raw(buf, bytes);
2128 }
2130 ::close(fd);
2132 return true;
2133 }
2135 void os::print_dll_info(outputStream *st) {
2136 st->print_cr("Dynamic libraries:");
2138 char fname[32];
2139 pid_t pid = os::Linux::gettid();
2141 jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid);
2143 if (!_print_ascii_file(fname, st)) {
2144 st->print("Can not get library information for pid = %d\n", pid);
2145 }
2146 }
2148 void os::print_os_info_brief(outputStream* st) {
2149 os::Linux::print_distro_info(st);
2151 os::Posix::print_uname_info(st);
2153 os::Linux::print_libversion_info(st);
2155 }
2157 void os::print_os_info(outputStream* st) {
2158 st->print("OS:");
2160 os::Linux::print_distro_info(st);
2162 os::Posix::print_uname_info(st);
2164 // Print warning if unsafe chroot environment detected
2165 if (unsafe_chroot_detected) {
2166 st->print("WARNING!! ");
2167 st->print_cr("%s", unstable_chroot_error);
2168 }
2170 os::Linux::print_libversion_info(st);
2172 os::Posix::print_rlimit_info(st);
2174 os::Posix::print_load_average(st);
2176 os::Linux::print_full_memory_info(st);
2178 os::Linux::print_container_info(st);
2179 }
2181 // Try to identify popular distros.
2182 // Most Linux distributions have a /etc/XXX-release file, which contains
2183 // the OS version string. Newer Linux distributions have a /etc/lsb-release
2184 // file that also contains the OS version string. Some have more than one
2185 // /etc/XXX-release file (e.g. Mandrake has both /etc/mandrake-release and
2186 // /etc/redhat-release.), so the order is important.
2187 // Any Linux that is based on Redhat (i.e. Oracle, Mandrake, Sun JDS...) have
2188 // their own specific XXX-release file as well as a redhat-release file.
2189 // Because of this the XXX-release file needs to be searched for before the
2190 // redhat-release file.
2191 // Since Red Hat has a lsb-release file that is not very descriptive the
2192 // search for redhat-release needs to be before lsb-release.
2193 // Since the lsb-release file is the new standard it needs to be searched
2194 // before the older style release files.
2195 // Searching system-release (Red Hat) and os-release (other Linuxes) are a
2196 // next to last resort. The os-release file is a new standard that contains
2197 // distribution information and the system-release file seems to be an old
2198 // standard that has been replaced by the lsb-release and os-release files.
2199 // Searching for the debian_version file is the last resort. It contains
2200 // an informative string like "6.0.6" or "wheezy/sid". Because of this
2201 // "Debian " is printed before the contents of the debian_version file.
2202 void os::Linux::print_distro_info(outputStream* st) {
2203 if (!_print_ascii_file("/etc/oracle-release", st) &&
2204 !_print_ascii_file("/etc/mandriva-release", st) &&
2205 !_print_ascii_file("/etc/mandrake-release", st) &&
2206 !_print_ascii_file("/etc/sun-release", st) &&
2207 !_print_ascii_file("/etc/redhat-release", st) &&
2208 !_print_ascii_file("/etc/lsb-release", st) &&
2209 !_print_ascii_file("/etc/SuSE-release", st) &&
2210 !_print_ascii_file("/etc/turbolinux-release", st) &&
2211 !_print_ascii_file("/etc/gentoo-release", st) &&
2212 !_print_ascii_file("/etc/ltib-release", st) &&
2213 !_print_ascii_file("/etc/angstrom-version", st) &&
2214 !_print_ascii_file("/etc/system-release", st) &&
2215 !_print_ascii_file("/etc/os-release", st)) {
2217 if (file_exists("/etc/debian_version")) {
2218 st->print("Debian ");
2219 _print_ascii_file("/etc/debian_version", st);
2220 } else {
2221 st->print("Linux");
2222 }
2223 }
2224 st->cr();
2225 }
2227 void os::Linux::print_libversion_info(outputStream* st) {
2228 // libc, pthread
2229 st->print("libc:");
2230 st->print("%s ", os::Linux::glibc_version());
2231 st->print("%s ", os::Linux::libpthread_version());
2232 if (os::Linux::is_LinuxThreads()) {
2233 st->print("(%s stack)", os::Linux::is_floating_stack() ? "floating" : "fixed");
2234 }
2235 st->cr();
2236 }
2238 void os::Linux::print_full_memory_info(outputStream* st) {
2239 st->print("\n/proc/meminfo:\n");
2240 _print_ascii_file("/proc/meminfo", st);
2241 st->cr();
2242 }
2244 void os::Linux::print_container_info(outputStream* st) {
2245 if (!OSContainer::is_containerized()) {
2246 return;
2247 }
2249 st->print("container (cgroup) information:\n");
2251 const char *p_ct = OSContainer::container_type();
2252 st->print("container_type: %s\n", p_ct != NULL ? p_ct : "failed");
2254 char *p = OSContainer::cpu_cpuset_cpus();
2255 st->print("cpu_cpuset_cpus: %s\n", p != NULL ? p : "failed");
2256 free(p);
2258 p = OSContainer::cpu_cpuset_memory_nodes();
2259 st->print("cpu_memory_nodes: %s\n", p != NULL ? p : "failed");
2260 free(p);
2262 int i = OSContainer::active_processor_count();
2263 if (i > 0) {
2264 st->print("active_processor_count: %d\n", i);
2265 } else {
2266 st->print("active_processor_count: failed\n");
2267 }
2269 i = OSContainer::cpu_quota();
2270 st->print("cpu_quota: %d\n", i);
2272 i = OSContainer::cpu_period();
2273 st->print("cpu_period: %d\n", i);
2275 i = OSContainer::cpu_shares();
2276 st->print("cpu_shares: %d\n", i);
2278 jlong j = OSContainer::memory_limit_in_bytes();
2279 st->print("memory_limit_in_bytes: " JLONG_FORMAT "\n", j);
2281 j = OSContainer::memory_and_swap_limit_in_bytes();
2282 st->print("memory_and_swap_limit_in_bytes: " JLONG_FORMAT "\n", j);
2284 j = OSContainer::memory_soft_limit_in_bytes();
2285 st->print("memory_soft_limit_in_bytes: " JLONG_FORMAT "\n", j);
2287 j = OSContainer::OSContainer::memory_usage_in_bytes();
2288 st->print("memory_usage_in_bytes: " JLONG_FORMAT "\n", j);
2290 j = OSContainer::OSContainer::memory_max_usage_in_bytes();
2291 st->print("memory_max_usage_in_bytes: " JLONG_FORMAT "\n", j);
2292 st->cr();
2293 }
2295 void os::print_memory_info(outputStream* st) {
2297 st->print("Memory:");
2298 st->print(" %dk page", os::vm_page_size()>>10);
2300 // values in struct sysinfo are "unsigned long"
2301 struct sysinfo si;
2302 sysinfo(&si);
2304 st->print(", physical " UINT64_FORMAT "k",
2305 os::physical_memory() >> 10);
2306 st->print("(" UINT64_FORMAT "k free)",
2307 os::available_memory() >> 10);
2308 st->print(", swap " UINT64_FORMAT "k",
2309 ((jlong)si.totalswap * si.mem_unit) >> 10);
2310 st->print("(" UINT64_FORMAT "k free)",
2311 ((jlong)si.freeswap * si.mem_unit) >> 10);
2312 st->cr();
2313 }
2315 void os::pd_print_cpu_info(outputStream* st) {
2316 st->print("\n/proc/cpuinfo:\n");
2317 if (!_print_ascii_file("/proc/cpuinfo", st)) {
2318 st->print(" <Not Available>");
2319 }
2320 st->cr();
2321 }
2323 void os::print_siginfo(outputStream* st, void* siginfo) {
2324 const siginfo_t* si = (const siginfo_t*)siginfo;
2326 os::Posix::print_siginfo_brief(st, si);
2327 #if INCLUDE_CDS
2328 if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
2329 UseSharedSpaces) {
2330 FileMapInfo* mapinfo = FileMapInfo::current_info();
2331 if (mapinfo->is_in_shared_space(si->si_addr)) {
2332 st->print("\n\nError accessing class data sharing archive." \
2333 " Mapped file inaccessible during execution, " \
2334 " possible disk/network problem.");
2335 }
2336 }
2337 #endif
2338 st->cr();
2339 }
2342 static void print_signal_handler(outputStream* st, int sig,
2343 char* buf, size_t buflen);
2345 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
2346 st->print_cr("Signal Handlers:");
2347 print_signal_handler(st, SIGSEGV, buf, buflen);
2348 print_signal_handler(st, SIGBUS , buf, buflen);
2349 print_signal_handler(st, SIGFPE , buf, buflen);
2350 print_signal_handler(st, SIGPIPE, buf, buflen);
2351 print_signal_handler(st, SIGXFSZ, buf, buflen);
2352 print_signal_handler(st, SIGILL , buf, buflen);
2353 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
2354 print_signal_handler(st, SR_signum, buf, buflen);
2355 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
2356 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
2357 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
2358 print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
2359 #if defined(PPC64)
2360 print_signal_handler(st, SIGTRAP, buf, buflen);
2361 #endif
2362 }
2364 static char saved_jvm_path[MAXPATHLEN] = {0};
2366 // Find the full path to the current module, libjvm.so
2367 void os::jvm_path(char *buf, jint buflen) {
2368 // Error checking.
2369 if (buflen < MAXPATHLEN) {
2370 assert(false, "must use a large-enough buffer");
2371 buf[0] = '\0';
2372 return;
2373 }
2374 // Lazy resolve the path to current module.
2375 if (saved_jvm_path[0] != 0) {
2376 strcpy(buf, saved_jvm_path);
2377 return;
2378 }
2380 char dli_fname[MAXPATHLEN];
2381 bool ret = dll_address_to_library_name(
2382 CAST_FROM_FN_PTR(address, os::jvm_path),
2383 dli_fname, sizeof(dli_fname), NULL);
2384 assert(ret, "cannot locate libjvm");
2385 char *rp = NULL;
2386 if (ret && dli_fname[0] != '\0') {
2387 rp = realpath(dli_fname, buf);
2388 }
2389 if (rp == NULL)
2390 return;
2392 if (Arguments::created_by_gamma_launcher()) {
2393 // Support for the gamma launcher. Typical value for buf is
2394 // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so". If "/jre/lib/" appears at
2395 // the right place in the string, then assume we are installed in a JDK and
2396 // we're done. Otherwise, check for a JAVA_HOME environment variable and fix
2397 // up the path so it looks like libjvm.so is installed there (append a
2398 // fake suffix hotspot/libjvm.so).
2399 const char *p = buf + strlen(buf) - 1;
2400 for (int count = 0; p > buf && count < 5; ++count) {
2401 for (--p; p > buf && *p != '/'; --p)
2402 /* empty */ ;
2403 }
2405 if (strncmp(p, "/jre/lib/", 9) != 0) {
2406 // Look for JAVA_HOME in the environment.
2407 char* java_home_var = ::getenv("JAVA_HOME");
2408 if (java_home_var != NULL && java_home_var[0] != 0) {
2409 char* jrelib_p;
2410 int len;
2412 // Check the current module name "libjvm.so".
2413 p = strrchr(buf, '/');
2414 assert(strstr(p, "/libjvm") == p, "invalid library name");
2416 rp = realpath(java_home_var, buf);
2417 if (rp == NULL)
2418 return;
2420 // determine if this is a legacy image or modules image
2421 // modules image doesn't have "jre" subdirectory
2422 len = strlen(buf);
2423 assert(len < buflen, "Ran out of buffer room");
2424 jrelib_p = buf + len;
2425 snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch);
2426 if (0 != access(buf, F_OK)) {
2427 snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch);
2428 }
2430 if (0 == access(buf, F_OK)) {
2431 // Use current module name "libjvm.so"
2432 len = strlen(buf);
2433 snprintf(buf + len, buflen-len, "/hotspot/libjvm.so");
2434 } else {
2435 // Go back to path of .so
2436 rp = realpath(dli_fname, buf);
2437 if (rp == NULL)
2438 return;
2439 }
2440 }
2441 }
2442 }
2444 strncpy(saved_jvm_path, buf, MAXPATHLEN);
2445 }
2447 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
2448 // no prefix required, not even "_"
2449 }
2451 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
2452 // no suffix required
2453 }
2455 ////////////////////////////////////////////////////////////////////////////////
2456 // sun.misc.Signal support
2458 static volatile jint sigint_count = 0;
2460 static void
2461 UserHandler(int sig, void *siginfo, void *context) {
2462 // 4511530 - sem_post is serialized and handled by the manager thread. When
2463 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
2464 // don't want to flood the manager thread with sem_post requests.
2465 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
2466 return;
2468 // Ctrl-C is pressed during error reporting, likely because the error
2469 // handler fails to abort. Let VM die immediately.
2470 if (sig == SIGINT && is_error_reported()) {
2471 os::die();
2472 }
2474 os::signal_notify(sig);
2475 }
2477 void* os::user_handler() {
2478 return CAST_FROM_FN_PTR(void*, UserHandler);
2479 }
2481 class Semaphore : public StackObj {
2482 public:
2483 Semaphore();
2484 ~Semaphore();
2485 void signal();
2486 void wait();
2487 bool trywait();
2488 bool timedwait(unsigned int sec, int nsec);
2489 private:
2490 sem_t _semaphore;
2491 };
2493 Semaphore::Semaphore() {
2494 sem_init(&_semaphore, 0, 0);
2495 }
2497 Semaphore::~Semaphore() {
2498 sem_destroy(&_semaphore);
2499 }
2501 void Semaphore::signal() {
2502 sem_post(&_semaphore);
2503 }
2505 void Semaphore::wait() {
2506 sem_wait(&_semaphore);
2507 }
2509 bool Semaphore::trywait() {
2510 return sem_trywait(&_semaphore) == 0;
2511 }
2513 bool Semaphore::timedwait(unsigned int sec, int nsec) {
2515 struct timespec ts;
2516 // Semaphore's are always associated with CLOCK_REALTIME
2517 os::Linux::clock_gettime(CLOCK_REALTIME, &ts);
2518 // see unpackTime for discussion on overflow checking
2519 if (sec >= MAX_SECS) {
2520 ts.tv_sec += MAX_SECS;
2521 ts.tv_nsec = 0;
2522 } else {
2523 ts.tv_sec += sec;
2524 ts.tv_nsec += nsec;
2525 if (ts.tv_nsec >= NANOSECS_PER_SEC) {
2526 ts.tv_nsec -= NANOSECS_PER_SEC;
2527 ++ts.tv_sec; // note: this must be <= max_secs
2528 }
2529 }
2531 while (1) {
2532 int result = sem_timedwait(&_semaphore, &ts);
2533 if (result == 0) {
2534 return true;
2535 } else if (errno == EINTR) {
2536 continue;
2537 } else if (errno == ETIMEDOUT) {
2538 return false;
2539 } else {
2540 return false;
2541 }
2542 }
2543 }
2545 extern "C" {
2546 typedef void (*sa_handler_t)(int);
2547 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
2548 }
2550 void* os::signal(int signal_number, void* handler) {
2551 struct sigaction sigAct, oldSigAct;
2553 sigfillset(&(sigAct.sa_mask));
2554 sigAct.sa_flags = SA_RESTART|SA_SIGINFO;
2555 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
2557 if (sigaction(signal_number, &sigAct, &oldSigAct)) {
2558 // -1 means registration failed
2559 return (void *)-1;
2560 }
2562 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
2563 }
2565 void os::signal_raise(int signal_number) {
2566 ::raise(signal_number);
2567 }
2569 /*
2570 * The following code is moved from os.cpp for making this
2571 * code platform specific, which it is by its very nature.
2572 */
2574 // Will be modified when max signal is changed to be dynamic
2575 int os::sigexitnum_pd() {
2576 return NSIG;
2577 }
2579 // a counter for each possible signal value
2580 static volatile jint pending_signals[NSIG+1] = { 0 };
2582 // Linux(POSIX) specific hand shaking semaphore.
2583 static sem_t sig_sem;
2584 static Semaphore sr_semaphore;
2586 void os::signal_init_pd() {
2587 // Initialize signal structures
2588 ::memset((void*)pending_signals, 0, sizeof(pending_signals));
2590 // Initialize signal semaphore
2591 ::sem_init(&sig_sem, 0, 0);
2592 }
2594 void os::signal_notify(int sig) {
2595 Atomic::inc(&pending_signals[sig]);
2596 ::sem_post(&sig_sem);
2597 }
2599 static int check_pending_signals(bool wait) {
2600 Atomic::store(0, &sigint_count);
2601 for (;;) {
2602 for (int i = 0; i < NSIG + 1; i++) {
2603 jint n = pending_signals[i];
2604 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
2605 return i;
2606 }
2607 }
2608 if (!wait) {
2609 return -1;
2610 }
2611 JavaThread *thread = JavaThread::current();
2612 ThreadBlockInVM tbivm(thread);
2614 bool threadIsSuspended;
2615 do {
2616 thread->set_suspend_equivalent();
2617 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
2618 ::sem_wait(&sig_sem);
2620 // were we externally suspended while we were waiting?
2621 threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2622 if (threadIsSuspended) {
2623 //
2624 // The semaphore has been incremented, but while we were waiting
2625 // another thread suspended us. We don't want to continue running
2626 // while suspended because that would surprise the thread that
2627 // suspended us.
2628 //
2629 ::sem_post(&sig_sem);
2631 thread->java_suspend_self();
2632 }
2633 } while (threadIsSuspended);
2634 }
2635 }
2637 int os::signal_lookup() {
2638 return check_pending_signals(false);
2639 }
2641 int os::signal_wait() {
2642 return check_pending_signals(true);
2643 }
2645 ////////////////////////////////////////////////////////////////////////////////
2646 // Virtual Memory
2648 int os::vm_page_size() {
2649 // Seems redundant as all get out
2650 assert(os::Linux::page_size() != -1, "must call os::init");
2651 return os::Linux::page_size();
2652 }
2654 // Solaris allocates memory by pages.
2655 int os::vm_allocation_granularity() {
2656 assert(os::Linux::page_size() != -1, "must call os::init");
2657 return os::Linux::page_size();
2658 }
2660 // Rationale behind this function:
2661 // current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
2662 // mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
2663 // samples for JITted code. Here we create private executable mapping over the code cache
2664 // and then we can use standard (well, almost, as mapping can change) way to provide
2665 // info for the reporting script by storing timestamp and location of symbol
2666 void linux_wrap_code(char* base, size_t size) {
2667 static volatile jint cnt = 0;
2669 if (!UseOprofile) {
2670 return;
2671 }
2673 char buf[PATH_MAX+1];
2674 int num = Atomic::add(1, &cnt);
2676 snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d",
2677 os::get_temp_directory(), os::current_process_id(), num);
2678 unlink(buf);
2680 int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
2682 if (fd != -1) {
2683 off_t rv = ::lseek(fd, size-2, SEEK_SET);
2684 if (rv != (off_t)-1) {
2685 if (::write(fd, "", 1) == 1) {
2686 mmap(base, size,
2687 PROT_READ|PROT_WRITE|PROT_EXEC,
2688 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
2689 }
2690 }
2691 ::close(fd);
2692 unlink(buf);
2693 }
2694 }
2696 static bool recoverable_mmap_error(int err) {
2697 // See if the error is one we can let the caller handle. This
2698 // list of errno values comes from JBS-6843484. I can't find a
2699 // Linux man page that documents this specific set of errno
2700 // values so while this list currently matches Solaris, it may
2701 // change as we gain experience with this failure mode.
2702 switch (err) {
2703 case EBADF:
2704 case EINVAL:
2705 case ENOTSUP:
2706 // let the caller deal with these errors
2707 return true;
2709 default:
2710 // Any remaining errors on this OS can cause our reserved mapping
2711 // to be lost. That can cause confusion where different data
2712 // structures think they have the same memory mapped. The worst
2713 // scenario is if both the VM and a library think they have the
2714 // same memory mapped.
2715 return false;
2716 }
2717 }
2719 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
2720 int err) {
2721 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2722 ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
2723 strerror(err), err);
2724 }
2726 static void warn_fail_commit_memory(char* addr, size_t size,
2727 size_t alignment_hint, bool exec,
2728 int err) {
2729 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2730 ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, size,
2731 alignment_hint, exec, strerror(err), err);
2732 }
2734 // NOTE: Linux kernel does not really reserve the pages for us.
2735 // All it does is to check if there are enough free pages
2736 // left at the time of mmap(). This could be a potential
2737 // problem.
2738 int os::Linux::commit_memory_impl(char* addr, size_t size, bool exec) {
2739 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2740 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2741 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2742 if (res != (uintptr_t) MAP_FAILED) {
2743 if (UseNUMAInterleaving) {
2744 numa_make_global(addr, size);
2745 }
2746 return 0;
2747 }
2749 int err = errno; // save errno from mmap() call above
2751 if (!recoverable_mmap_error(err)) {
2752 warn_fail_commit_memory(addr, size, exec, err);
2753 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "committing reserved memory.");
2754 }
2756 return err;
2757 }
2759 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2760 return os::Linux::commit_memory_impl(addr, size, exec) == 0;
2761 }
2763 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
2764 const char* mesg) {
2765 assert(mesg != NULL, "mesg must be specified");
2766 int err = os::Linux::commit_memory_impl(addr, size, exec);
2767 if (err != 0) {
2768 // the caller wants all commit errors to exit with the specified mesg:
2769 warn_fail_commit_memory(addr, size, exec, err);
2770 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
2771 }
2772 }
2774 // Define MAP_HUGETLB here so we can build HotSpot on old systems.
2775 #ifndef MAP_HUGETLB
2776 #define MAP_HUGETLB 0x40000
2777 #endif
2779 // Define MADV_HUGEPAGE here so we can build HotSpot on old systems.
2780 #ifndef MADV_HUGEPAGE
2781 #define MADV_HUGEPAGE 14
2782 #endif
2784 int os::Linux::commit_memory_impl(char* addr, size_t size,
2785 size_t alignment_hint, bool exec) {
2786 int err = os::Linux::commit_memory_impl(addr, size, exec);
2787 if (err == 0) {
2788 realign_memory(addr, size, alignment_hint);
2789 }
2790 return err;
2791 }
2793 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2794 bool exec) {
2795 return os::Linux::commit_memory_impl(addr, size, alignment_hint, exec) == 0;
2796 }
2798 void os::pd_commit_memory_or_exit(char* addr, size_t size,
2799 size_t alignment_hint, bool exec,
2800 const char* mesg) {
2801 assert(mesg != NULL, "mesg must be specified");
2802 int err = os::Linux::commit_memory_impl(addr, size, alignment_hint, exec);
2803 if (err != 0) {
2804 // the caller wants all commit errors to exit with the specified mesg:
2805 warn_fail_commit_memory(addr, size, alignment_hint, exec, err);
2806 vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
2807 }
2808 }
2810 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2811 if (UseTransparentHugePages && alignment_hint > (size_t)vm_page_size()) {
2812 // We don't check the return value: madvise(MADV_HUGEPAGE) may not
2813 // be supported or the memory may already be backed by huge pages.
2814 ::madvise(addr, bytes, MADV_HUGEPAGE);
2815 }
2816 }
2818 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2819 // This method works by doing an mmap over an existing mmaping and effectively discarding
2820 // the existing pages. However it won't work for SHM-based large pages that cannot be
2821 // uncommitted at all. We don't do anything in this case to avoid creating a segment with
2822 // small pages on top of the SHM segment. This method always works for small pages, so we
2823 // allow that in any case.
2824 if (alignment_hint <= (size_t)os::vm_page_size() || can_commit_large_page_memory()) {
2825 commit_memory(addr, bytes, alignment_hint, !ExecMem);
2826 }
2827 }
2829 void os::numa_make_global(char *addr, size_t bytes) {
2830 Linux::numa_interleave_memory(addr, bytes);
2831 }
2833 // Define for numa_set_bind_policy(int). Setting the argument to 0 will set the
2834 // bind policy to MPOL_PREFERRED for the current thread.
2835 #define USE_MPOL_PREFERRED 0
2837 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2838 // To make NUMA and large pages more robust when both enabled, we need to ease
2839 // the requirements on where the memory should be allocated. MPOL_BIND is the
2840 // default policy and it will force memory to be allocated on the specified
2841 // node. Changing this to MPOL_PREFERRED will prefer to allocate the memory on
2842 // the specified node, but will not force it. Using this policy will prevent
2843 // getting SIGBUS when trying to allocate large pages on NUMA nodes with no
2844 // free large pages.
2845 Linux::numa_set_bind_policy(USE_MPOL_PREFERRED);
2846 Linux::numa_tonode_memory(addr, bytes, lgrp_hint);
2847 }
2849 bool os::numa_topology_changed() { return false; }
2851 size_t os::numa_get_groups_num() {
2852 // Return just the number of nodes in which it's possible to allocate memory
2853 // (in numa terminology, configured nodes).
2854 return Linux::numa_num_configured_nodes();
2855 }
2857 int os::numa_get_group_id() {
2858 int cpu_id = Linux::sched_getcpu();
2859 if (cpu_id != -1) {
2860 int lgrp_id = Linux::get_node_by_cpu(cpu_id);
2861 if (lgrp_id != -1) {
2862 return lgrp_id;
2863 }
2864 }
2865 return 0;
2866 }
2868 int os::Linux::get_existing_num_nodes() {
2869 size_t node;
2870 size_t highest_node_number = Linux::numa_max_node();
2871 int num_nodes = 0;
2873 // Get the total number of nodes in the system including nodes without memory.
2874 for (node = 0; node <= highest_node_number; node++) {
2875 if (isnode_in_existing_nodes(node)) {
2876 num_nodes++;
2877 }
2878 }
2879 return num_nodes;
2880 }
2882 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2883 size_t highest_node_number = Linux::numa_max_node();
2884 size_t i = 0;
2886 // Map all node ids in which is possible to allocate memory. Also nodes are
2887 // not always consecutively available, i.e. available from 0 to the highest
2888 // node number.
2889 for (size_t node = 0; node <= highest_node_number; node++) {
2890 if (Linux::isnode_in_configured_nodes(node)) {
2891 ids[i++] = node;
2892 }
2893 }
2894 return i;
2895 }
2897 bool os::get_page_info(char *start, page_info* info) {
2898 return false;
2899 }
2901 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
2902 return end;
2903 }
2906 int os::Linux::sched_getcpu_syscall(void) {
2907 unsigned int cpu = 0;
2908 int retval = -1;
2910 #if defined(IA32)
2911 # ifndef SYS_getcpu
2912 # define SYS_getcpu 318
2913 # endif
2914 retval = syscall(SYS_getcpu, &cpu, NULL, NULL);
2915 #elif defined(AMD64)
2916 // Unfortunately we have to bring all these macros here from vsyscall.h
2917 // to be able to compile on old linuxes.
2918 # define __NR_vgetcpu 2
2919 # define VSYSCALL_START (-10UL << 20)
2920 # define VSYSCALL_SIZE 1024
2921 # define VSYSCALL_ADDR(vsyscall_nr) (VSYSCALL_START+VSYSCALL_SIZE*(vsyscall_nr))
2922 typedef long (*vgetcpu_t)(unsigned int *cpu, unsigned int *node, unsigned long *tcache);
2923 vgetcpu_t vgetcpu = (vgetcpu_t)VSYSCALL_ADDR(__NR_vgetcpu);
2924 retval = vgetcpu(&cpu, NULL, NULL);
2925 #endif
2927 return (retval == -1) ? retval : cpu;
2928 }
2930 // Something to do with the numa-aware allocator needs these symbols
2931 extern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { }
2932 extern "C" JNIEXPORT void numa_error(char *where) { }
2933 extern "C" JNIEXPORT int fork1() { return fork(); }
2935 // Handle request to load libnuma symbol version 1.1 (API v1). If it fails
2936 // load symbol from base version instead.
2937 void* os::Linux::libnuma_dlsym(void* handle, const char *name) {
2938 void *f = dlvsym(handle, name, "libnuma_1.1");
2939 if (f == NULL) {
2940 f = dlsym(handle, name);
2941 }
2942 return f;
2943 }
2945 // Handle request to load libnuma symbol version 1.2 (API v2) only.
2946 // Return NULL if the symbol is not defined in this particular version.
2947 void* os::Linux::libnuma_v2_dlsym(void* handle, const char* name) {
2948 return dlvsym(handle, name, "libnuma_1.2");
2949 }
2951 bool os::Linux::libnuma_init() {
2952 // sched_getcpu() should be in libc.
2953 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,
2954 dlsym(RTLD_DEFAULT, "sched_getcpu")));
2956 // If it's not, try a direct syscall.
2957 if (sched_getcpu() == -1)
2958 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, (void*)&sched_getcpu_syscall));
2960 if (sched_getcpu() != -1) { // Does it work?
2961 void *handle = dlopen("libnuma.so.1", RTLD_LAZY);
2962 if (handle != NULL) {
2963 set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t,
2964 libnuma_dlsym(handle, "numa_node_to_cpus")));
2965 set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t,
2966 libnuma_dlsym(handle, "numa_max_node")));
2967 set_numa_num_configured_nodes(CAST_TO_FN_PTR(numa_num_configured_nodes_func_t,
2968 libnuma_dlsym(handle, "numa_num_configured_nodes")));
2969 set_numa_available(CAST_TO_FN_PTR(numa_available_func_t,
2970 libnuma_dlsym(handle, "numa_available")));
2971 set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t,
2972 libnuma_dlsym(handle, "numa_tonode_memory")));
2973 set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t,
2974 libnuma_dlsym(handle, "numa_interleave_memory")));
2975 set_numa_interleave_memory_v2(CAST_TO_FN_PTR(numa_interleave_memory_v2_func_t,
2976 libnuma_v2_dlsym(handle, "numa_interleave_memory")));
2977 set_numa_set_bind_policy(CAST_TO_FN_PTR(numa_set_bind_policy_func_t,
2978 libnuma_dlsym(handle, "numa_set_bind_policy")));
2979 set_numa_bitmask_isbitset(CAST_TO_FN_PTR(numa_bitmask_isbitset_func_t,
2980 libnuma_dlsym(handle, "numa_bitmask_isbitset")));
2981 set_numa_distance(CAST_TO_FN_PTR(numa_distance_func_t,
2982 libnuma_dlsym(handle, "numa_distance")));
2984 if (numa_available() != -1) {
2985 set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes"));
2986 set_numa_all_nodes_ptr((struct bitmask **)libnuma_dlsym(handle, "numa_all_nodes_ptr"));
2987 set_numa_nodes_ptr((struct bitmask **)libnuma_dlsym(handle, "numa_nodes_ptr"));
2988 // Create an index -> node mapping, since nodes are not always consecutive
2989 _nindex_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, true);
2990 rebuild_nindex_to_node_map();
2991 // Create a cpu -> node mapping
2992 _cpu_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, true);
2993 rebuild_cpu_to_node_map();
2994 return true;
2995 }
2996 }
2997 }
2998 return false;
2999 }
3001 void os::Linux::rebuild_nindex_to_node_map() {
3002 int highest_node_number = Linux::numa_max_node();
3004 nindex_to_node()->clear();
3005 for (int node = 0; node <= highest_node_number; node++) {
3006 if (Linux::isnode_in_existing_nodes(node)) {
3007 nindex_to_node()->append(node);
3008 }
3009 }
3010 }
3012 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id.
3013 // The table is later used in get_node_by_cpu().
3014 void os::Linux::rebuild_cpu_to_node_map() {
3015 const size_t NCPUS = 32768; // Since the buffer size computation is very obscure
3016 // in libnuma (possible values are starting from 16,
3017 // and continuing up with every other power of 2, but less
3018 // than the maximum number of CPUs supported by kernel), and
3019 // is a subject to change (in libnuma version 2 the requirements
3020 // are more reasonable) we'll just hardcode the number they use
3021 // in the library.
3022 const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;
3024 size_t cpu_num = processor_count();
3025 size_t cpu_map_size = NCPUS / BitsPerCLong;
3026 size_t cpu_map_valid_size =
3027 MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);
3029 cpu_to_node()->clear();
3030 cpu_to_node()->at_grow(cpu_num - 1);
3032 size_t node_num = get_existing_num_nodes();
3034 int distance = 0;
3035 int closest_distance = INT_MAX;
3036 int closest_node = 0;
3037 unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal);
3038 for (size_t i = 0; i < node_num; i++) {
3039 // Check if node is configured (not a memory-less node). If it is not, find
3040 // the closest configured node.
3041 if (!isnode_in_configured_nodes(nindex_to_node()->at(i))) {
3042 closest_distance = INT_MAX;
3043 // Check distance from all remaining nodes in the system. Ignore distance
3044 // from itself and from another non-configured node.
3045 for (size_t m = 0; m < node_num; m++) {
3046 if (m != i && isnode_in_configured_nodes(nindex_to_node()->at(m))) {
3047 distance = numa_distance(nindex_to_node()->at(i), nindex_to_node()->at(m));
3048 // If a closest node is found, update. There is always at least one
3049 // configured node in the system so there is always at least one node
3050 // close.
3051 if (distance != 0 && distance < closest_distance) {
3052 closest_distance = distance;
3053 closest_node = nindex_to_node()->at(m);
3054 }
3055 }
3056 }
3057 } else {
3058 // Current node is already a configured node.
3059 closest_node = nindex_to_node()->at(i);
3060 }
3062 // Get cpus from the original node and map them to the closest node. If node
3063 // is a configured node (not a memory-less node), then original node and
3064 // closest node are the same.
3065 if (numa_node_to_cpus(nindex_to_node()->at(i), cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) {
3066 for (size_t j = 0; j < cpu_map_valid_size; j++) {
3067 if (cpu_map[j] != 0) {
3068 for (size_t k = 0; k < BitsPerCLong; k++) {
3069 if (cpu_map[j] & (1UL << k)) {
3070 cpu_to_node()->at_put(j * BitsPerCLong + k, closest_node);
3071 }
3072 }
3073 }
3074 }
3075 }
3076 }
3077 FREE_C_HEAP_ARRAY(unsigned long, cpu_map, mtInternal);
3078 }
3080 int os::Linux::get_node_by_cpu(int cpu_id) {
3081 if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) {
3082 return cpu_to_node()->at(cpu_id);
3083 }
3084 return -1;
3085 }
3087 GrowableArray<int>* os::Linux::_cpu_to_node;
3088 GrowableArray<int>* os::Linux::_nindex_to_node;
3089 os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu;
3090 os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus;
3091 os::Linux::numa_max_node_func_t os::Linux::_numa_max_node;
3092 os::Linux::numa_num_configured_nodes_func_t os::Linux::_numa_num_configured_nodes;
3093 os::Linux::numa_available_func_t os::Linux::_numa_available;
3094 os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory;
3095 os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory;
3096 os::Linux::numa_interleave_memory_v2_func_t os::Linux::_numa_interleave_memory_v2;
3097 os::Linux::numa_set_bind_policy_func_t os::Linux::_numa_set_bind_policy;
3098 os::Linux::numa_bitmask_isbitset_func_t os::Linux::_numa_bitmask_isbitset;
3099 os::Linux::numa_distance_func_t os::Linux::_numa_distance;
3100 unsigned long* os::Linux::_numa_all_nodes;
3101 struct bitmask* os::Linux::_numa_all_nodes_ptr;
3102 struct bitmask* os::Linux::_numa_nodes_ptr;
3104 bool os::pd_uncommit_memory(char* addr, size_t size) {
3105 uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
3106 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
3107 return res != (uintptr_t) MAP_FAILED;
3108 }
3110 static
3111 address get_stack_commited_bottom(address bottom, size_t size) {
3112 address nbot = bottom;
3113 address ntop = bottom + size;
3115 size_t page_sz = os::vm_page_size();
3116 unsigned pages = size / page_sz;
3118 unsigned char vec[1];
3119 unsigned imin = 1, imax = pages + 1, imid;
3120 int mincore_return_value = 0;
3122 assert(imin <= imax, "Unexpected page size");
3124 while (imin < imax) {
3125 imid = (imax + imin) / 2;
3126 nbot = ntop - (imid * page_sz);
3128 // Use a trick with mincore to check whether the page is mapped or not.
3129 // mincore sets vec to 1 if page resides in memory and to 0 if page
3130 // is swapped output but if page we are asking for is unmapped
3131 // it returns -1,ENOMEM
3132 mincore_return_value = mincore(nbot, page_sz, vec);
3134 if (mincore_return_value == -1) {
3135 // Page is not mapped go up
3136 // to find first mapped page
3137 if (errno != EAGAIN) {
3138 assert(errno == ENOMEM, "Unexpected mincore errno");
3139 imax = imid;
3140 }
3141 } else {
3142 // Page is mapped go down
3143 // to find first not mapped page
3144 imin = imid + 1;
3145 }
3146 }
3148 nbot = nbot + page_sz;
3150 // Adjust stack bottom one page up if last checked page is not mapped
3151 if (mincore_return_value == -1) {
3152 nbot = nbot + page_sz;
3153 }
3155 return nbot;
3156 }
3159 // Linux uses a growable mapping for the stack, and if the mapping for
3160 // the stack guard pages is not removed when we detach a thread the
3161 // stack cannot grow beyond the pages where the stack guard was
3162 // mapped. If at some point later in the process the stack expands to
3163 // that point, the Linux kernel cannot expand the stack any further
3164 // because the guard pages are in the way, and a segfault occurs.
3165 //
3166 // However, it's essential not to split the stack region by unmapping
3167 // a region (leaving a hole) that's already part of the stack mapping,
3168 // so if the stack mapping has already grown beyond the guard pages at
3169 // the time we create them, we have to truncate the stack mapping.
3170 // So, we need to know the extent of the stack mapping when
3171 // create_stack_guard_pages() is called.
3173 // We only need this for stacks that are growable: at the time of
3174 // writing thread stacks don't use growable mappings (i.e. those
3175 // creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this
3176 // only applies to the main thread.
3178 // If the (growable) stack mapping already extends beyond the point
3179 // where we're going to put our guard pages, truncate the mapping at
3180 // that point by munmap()ping it. This ensures that when we later
3181 // munmap() the guard pages we don't leave a hole in the stack
3182 // mapping. This only affects the main/primordial thread
3184 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
3186 if (os::is_primordial_thread()) {
3187 // As we manually grow stack up to bottom inside create_attached_thread(),
3188 // it's likely that os::Linux::initial_thread_stack_bottom is mapped and
3189 // we don't need to do anything special.
3190 // Check it first, before calling heavy function.
3191 uintptr_t stack_extent = (uintptr_t) os::Linux::initial_thread_stack_bottom();
3192 unsigned char vec[1];
3194 if (mincore((address)stack_extent, os::vm_page_size(), vec) == -1) {
3195 // Fallback to slow path on all errors, including EAGAIN
3196 stack_extent = (uintptr_t) get_stack_commited_bottom(
3197 os::Linux::initial_thread_stack_bottom(),
3198 (size_t)addr - stack_extent);
3199 }
3201 if (stack_extent < (uintptr_t)addr) {
3202 ::munmap((void*)stack_extent, (uintptr_t)(addr - stack_extent));
3203 }
3204 }
3206 return os::commit_memory(addr, size, !ExecMem);
3207 }
3209 // If this is a growable mapping, remove the guard pages entirely by
3210 // munmap()ping them. If not, just call uncommit_memory(). This only
3211 // affects the main/primordial thread, but guard against future OS changes.
3212 // It's safe to always unmap guard pages for primordial thread because we
3213 // always place it right after end of the mapped region.
3215 bool os::remove_stack_guard_pages(char* addr, size_t size) {
3216 uintptr_t stack_extent, stack_base;
3218 if (os::is_primordial_thread()) {
3219 return ::munmap(addr, size) == 0;
3220 }
3222 return os::uncommit_memory(addr, size);
3223 }
3225 static address _highest_vm_reserved_address = NULL;
3227 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
3228 // at 'requested_addr'. If there are existing memory mappings at the same
3229 // location, however, they will be overwritten. If 'fixed' is false,
3230 // 'requested_addr' is only treated as a hint, the return value may or
3231 // may not start from the requested address. Unlike Linux mmap(), this
3232 // function returns NULL to indicate failure.
3233 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
3234 char * addr;
3235 int flags;
3237 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
3238 if (fixed) {
3239 assert((uintptr_t)requested_addr % os::Linux::page_size() == 0, "unaligned address");
3240 flags |= MAP_FIXED;
3241 }
3243 // Map reserved/uncommitted pages PROT_NONE so we fail early if we
3244 // touch an uncommitted page. Otherwise, the read/write might
3245 // succeed if we have enough swap space to back the physical page.
3246 addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
3247 flags, -1, 0);
3249 if (addr != MAP_FAILED) {
3250 // anon_mmap() should only get called during VM initialization,
3251 // don't need lock (actually we can skip locking even it can be called
3252 // from multiple threads, because _highest_vm_reserved_address is just a
3253 // hint about the upper limit of non-stack memory regions.)
3254 if ((address)addr + bytes > _highest_vm_reserved_address) {
3255 _highest_vm_reserved_address = (address)addr + bytes;
3256 }
3257 }
3259 return addr == MAP_FAILED ? NULL : addr;
3260 }
3262 // Allocate (using mmap, NO_RESERVE, with small pages) at either a given request address
3263 // (req_addr != NULL) or with a given alignment.
3264 // - bytes shall be a multiple of alignment.
3265 // - req_addr can be NULL. If not NULL, it must be a multiple of alignment.
3266 // - alignment sets the alignment at which memory shall be allocated.
3267 // It must be a multiple of allocation granularity.
3268 // Returns address of memory or NULL. If req_addr was not NULL, will only return
3269 // req_addr or NULL.
3270 static char* anon_mmap_aligned(size_t bytes, size_t alignment, char* req_addr) {
3272 size_t extra_size = bytes;
3273 if (req_addr == NULL && alignment > 0) {
3274 extra_size += alignment;
3275 }
3277 char* start = (char*) ::mmap(req_addr, extra_size, PROT_NONE,
3278 MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
3279 -1, 0);
3280 if (start == MAP_FAILED) {
3281 start = NULL;
3282 } else {
3283 if (req_addr != NULL) {
3284 if (start != req_addr) {
3285 ::munmap(start, extra_size);
3286 start = NULL;
3287 }
3288 } else {
3289 char* const start_aligned = (char*) align_ptr_up(start, alignment);
3290 char* const end_aligned = start_aligned + bytes;
3291 char* const end = start + extra_size;
3292 if (start_aligned > start) {
3293 ::munmap(start, start_aligned - start);
3294 }
3295 if (end_aligned < end) {
3296 ::munmap(end_aligned, end - end_aligned);
3297 }
3298 start = start_aligned;
3299 }
3300 }
3301 return start;
3302 }
3304 // Don't update _highest_vm_reserved_address, because there might be memory
3305 // regions above addr + size. If so, releasing a memory region only creates
3306 // a hole in the address space, it doesn't help prevent heap-stack collision.
3307 //
3308 static int anon_munmap(char * addr, size_t size) {
3309 return ::munmap(addr, size) == 0;
3310 }
3312 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
3313 size_t alignment_hint) {
3314 return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
3315 }
3317 bool os::pd_release_memory(char* addr, size_t size) {
3318 return anon_munmap(addr, size);
3319 }
3321 static address highest_vm_reserved_address() {
3322 return _highest_vm_reserved_address;
3323 }
3325 static bool linux_mprotect(char* addr, size_t size, int prot) {
3326 // Linux wants the mprotect address argument to be page aligned.
3327 char* bottom = (char*)align_size_down((intptr_t)addr, os::Linux::page_size());
3329 // According to SUSv3, mprotect() should only be used with mappings
3330 // established by mmap(), and mmap() always maps whole pages. Unaligned
3331 // 'addr' likely indicates problem in the VM (e.g. trying to change
3332 // protection of malloc'ed or statically allocated memory). Check the
3333 // caller if you hit this assert.
3334 assert(addr == bottom, "sanity check");
3336 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size());
3337 return ::mprotect(bottom, size, prot) == 0;
3338 }
3340 // Set protections specified
3341 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
3342 bool is_committed) {
3343 unsigned int p = 0;
3344 switch (prot) {
3345 case MEM_PROT_NONE: p = PROT_NONE; break;
3346 case MEM_PROT_READ: p = PROT_READ; break;
3347 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break;
3348 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
3349 default:
3350 ShouldNotReachHere();
3351 }
3352 // is_committed is unused.
3353 return linux_mprotect(addr, bytes, p);
3354 }
3356 bool os::guard_memory(char* addr, size_t size) {
3357 return linux_mprotect(addr, size, PROT_NONE);
3358 }
3360 bool os::unguard_memory(char* addr, size_t size) {
3361 return linux_mprotect(addr, size, PROT_READ|PROT_WRITE);
3362 }
3364 bool os::Linux::transparent_huge_pages_sanity_check(bool warn, size_t page_size) {
3365 bool result = false;
3366 void *p = mmap(NULL, page_size * 2, PROT_READ|PROT_WRITE,
3367 MAP_ANONYMOUS|MAP_PRIVATE,
3368 -1, 0);
3369 if (p != MAP_FAILED) {
3370 void *aligned_p = align_ptr_up(p, page_size);
3372 result = madvise(aligned_p, page_size, MADV_HUGEPAGE) == 0;
3374 munmap(p, page_size * 2);
3375 }
3377 if (warn && !result) {
3378 warning("TransparentHugePages is not supported by the operating system.");
3379 }
3381 return result;
3382 }
3384 bool os::Linux::hugetlbfs_sanity_check(bool warn, size_t page_size) {
3385 bool result = false;
3386 void *p = mmap(NULL, page_size, PROT_READ|PROT_WRITE,
3387 MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB,
3388 -1, 0);
3390 if (p != MAP_FAILED) {
3391 // We don't know if this really is a huge page or not.
3392 FILE *fp = fopen("/proc/self/maps", "r");
3393 if (fp) {
3394 while (!feof(fp)) {
3395 char chars[257];
3396 long x = 0;
3397 if (fgets(chars, sizeof(chars), fp)) {
3398 if (sscanf(chars, "%lx-%*x", &x) == 1
3399 && x == (long)p) {
3400 if (strstr (chars, "hugepage")) {
3401 result = true;
3402 break;
3403 }
3404 }
3405 }
3406 }
3407 fclose(fp);
3408 }
3409 munmap(p, page_size);
3410 }
3412 if (warn && !result) {
3413 warning("HugeTLBFS is not supported by the operating system.");
3414 }
3416 return result;
3417 }
3419 /*
3420 * Set the coredump_filter bits to include largepages in core dump (bit 6)
3421 *
3422 * From the coredump_filter documentation:
3423 *
3424 * - (bit 0) anonymous private memory
3425 * - (bit 1) anonymous shared memory
3426 * - (bit 2) file-backed private memory
3427 * - (bit 3) file-backed shared memory
3428 * - (bit 4) ELF header pages in file-backed private memory areas (it is
3429 * effective only if the bit 2 is cleared)
3430 * - (bit 5) hugetlb private memory
3431 * - (bit 6) hugetlb shared memory
3432 */
3433 static void set_coredump_filter(void) {
3434 FILE *f;
3435 long cdm;
3437 if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) {
3438 return;
3439 }
3441 if (fscanf(f, "%lx", &cdm) != 1) {
3442 fclose(f);
3443 return;
3444 }
3446 rewind(f);
3448 if ((cdm & LARGEPAGES_BIT) == 0) {
3449 cdm |= LARGEPAGES_BIT;
3450 fprintf(f, "%#lx", cdm);
3451 }
3453 fclose(f);
3454 }
3456 // Large page support
3458 static size_t _large_page_size = 0;
3460 size_t os::Linux::find_large_page_size() {
3461 size_t large_page_size = 0;
3463 // large_page_size on Linux is used to round up heap size. x86 uses either
3464 // 2M or 4M page, depending on whether PAE (Physical Address Extensions)
3465 // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use
3466 // page as large as 256M.
3467 //
3468 // Here we try to figure out page size by parsing /proc/meminfo and looking
3469 // for a line with the following format:
3470 // Hugepagesize: 2048 kB
3471 //
3472 // If we can't determine the value (e.g. /proc is not mounted, or the text
3473 // format has been changed), we'll use the largest page size supported by
3474 // the processor.
3476 #ifndef ZERO
3477 large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M)
3478 ARM_ONLY(2 * M) PPC_ONLY(4 * M);
3479 #endif // ZERO
3481 FILE *fp = fopen("/proc/meminfo", "r");
3482 if (fp) {
3483 while (!feof(fp)) {
3484 int x = 0;
3485 char buf[16];
3486 if (fscanf(fp, "Hugepagesize: %d", &x) == 1) {
3487 if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) {
3488 large_page_size = x * K;
3489 break;
3490 }
3491 } else {
3492 // skip to next line
3493 for (;;) {
3494 int ch = fgetc(fp);
3495 if (ch == EOF || ch == (int)'\n') break;
3496 }
3497 }
3498 }
3499 fclose(fp);
3500 }
3502 if (!FLAG_IS_DEFAULT(LargePageSizeInBytes) && LargePageSizeInBytes != large_page_size) {
3503 warning("Setting LargePageSizeInBytes has no effect on this OS. Large page size is "
3504 SIZE_FORMAT "%s.", byte_size_in_proper_unit(large_page_size),
3505 proper_unit_for_byte_size(large_page_size));
3506 }
3508 return large_page_size;
3509 }
3511 size_t os::Linux::setup_large_page_size() {
3512 _large_page_size = Linux::find_large_page_size();
3513 const size_t default_page_size = (size_t)Linux::page_size();
3514 if (_large_page_size > default_page_size) {
3515 _page_sizes[0] = _large_page_size;
3516 _page_sizes[1] = default_page_size;
3517 _page_sizes[2] = 0;
3518 }
3520 return _large_page_size;
3521 }
3523 bool os::Linux::setup_large_page_type(size_t page_size) {
3524 if (FLAG_IS_DEFAULT(UseHugeTLBFS) &&
3525 FLAG_IS_DEFAULT(UseSHM) &&
3526 FLAG_IS_DEFAULT(UseTransparentHugePages)) {
3528 // The type of large pages has not been specified by the user.
3530 // Try UseHugeTLBFS and then UseSHM.
3531 UseHugeTLBFS = UseSHM = true;
3533 // Don't try UseTransparentHugePages since there are known
3534 // performance issues with it turned on. This might change in the future.
3535 UseTransparentHugePages = false;
3536 }
3538 if (UseTransparentHugePages) {
3539 bool warn_on_failure = !FLAG_IS_DEFAULT(UseTransparentHugePages);
3540 if (transparent_huge_pages_sanity_check(warn_on_failure, page_size)) {
3541 UseHugeTLBFS = false;
3542 UseSHM = false;
3543 return true;
3544 }
3545 UseTransparentHugePages = false;
3546 }
3548 if (UseHugeTLBFS) {
3549 bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS);
3550 if (hugetlbfs_sanity_check(warn_on_failure, page_size)) {
3551 UseSHM = false;
3552 return true;
3553 }
3554 UseHugeTLBFS = false;
3555 }
3557 return UseSHM;
3558 }
3560 void os::large_page_init() {
3561 if (!UseLargePages &&
3562 !UseTransparentHugePages &&
3563 !UseHugeTLBFS &&
3564 !UseSHM) {
3565 // Not using large pages.
3566 return;
3567 }
3569 if (!FLAG_IS_DEFAULT(UseLargePages) && !UseLargePages) {
3570 // The user explicitly turned off large pages.
3571 // Ignore the rest of the large pages flags.
3572 UseTransparentHugePages = false;
3573 UseHugeTLBFS = false;
3574 UseSHM = false;
3575 return;
3576 }
3578 size_t large_page_size = Linux::setup_large_page_size();
3579 UseLargePages = Linux::setup_large_page_type(large_page_size);
3581 set_coredump_filter();
3582 }
3584 #ifndef SHM_HUGETLB
3585 #define SHM_HUGETLB 04000
3586 #endif
3588 #define shm_warning_format(format, ...) \
3589 do { \
3590 if (UseLargePages && \
3591 (!FLAG_IS_DEFAULT(UseLargePages) || \
3592 !FLAG_IS_DEFAULT(UseSHM) || \
3593 !FLAG_IS_DEFAULT(LargePageSizeInBytes))) { \
3594 warning(format, __VA_ARGS__); \
3595 } \
3596 } while (0)
3598 #define shm_warning(str) shm_warning_format("%s", str)
3600 #define shm_warning_with_errno(str) \
3601 do { \
3602 int err = errno; \
3603 shm_warning_format(str " (error = %d)", err); \
3604 } while (0)
3606 static char* shmat_with_alignment(int shmid, size_t bytes, size_t alignment) {
3607 assert(is_size_aligned(bytes, alignment), "Must be divisible by the alignment");
3609 if (!is_size_aligned(alignment, SHMLBA)) {
3610 assert(false, "Code below assumes that alignment is at least SHMLBA aligned");
3611 return NULL;
3612 }
3614 // To ensure that we get 'alignment' aligned memory from shmat,
3615 // we pre-reserve aligned virtual memory and then attach to that.
3617 char* pre_reserved_addr = anon_mmap_aligned(bytes, alignment, NULL);
3618 if (pre_reserved_addr == NULL) {
3619 // Couldn't pre-reserve aligned memory.
3620 shm_warning("Failed to pre-reserve aligned memory for shmat.");
3621 return NULL;
3622 }
3624 // SHM_REMAP is needed to allow shmat to map over an existing mapping.
3625 char* addr = (char*)shmat(shmid, pre_reserved_addr, SHM_REMAP);
3627 if ((intptr_t)addr == -1) {
3628 int err = errno;
3629 shm_warning_with_errno("Failed to attach shared memory.");
3631 assert(err != EACCES, "Unexpected error");
3632 assert(err != EIDRM, "Unexpected error");
3633 assert(err != EINVAL, "Unexpected error");
3635 // Since we don't know if the kernel unmapped the pre-reserved memory area
3636 // we can't unmap it, since that would potentially unmap memory that was
3637 // mapped from other threads.
3638 return NULL;
3639 }
3641 return addr;
3642 }
3644 static char* shmat_at_address(int shmid, char* req_addr) {
3645 if (!is_ptr_aligned(req_addr, SHMLBA)) {
3646 assert(false, "Requested address needs to be SHMLBA aligned");
3647 return NULL;
3648 }
3650 char* addr = (char*)shmat(shmid, req_addr, 0);
3652 if ((intptr_t)addr == -1) {
3653 shm_warning_with_errno("Failed to attach shared memory.");
3654 return NULL;
3655 }
3657 return addr;
3658 }
3660 static char* shmat_large_pages(int shmid, size_t bytes, size_t alignment, char* req_addr) {
3661 // If a req_addr has been provided, we assume that the caller has already aligned the address.
3662 if (req_addr != NULL) {
3663 assert(is_ptr_aligned(req_addr, os::large_page_size()), "Must be divisible by the large page size");
3664 assert(is_ptr_aligned(req_addr, alignment), "Must be divisible by given alignment");
3665 return shmat_at_address(shmid, req_addr);
3666 }
3668 // Since shmid has been setup with SHM_HUGETLB, shmat will automatically
3669 // return large page size aligned memory addresses when req_addr == NULL.
3670 // However, if the alignment is larger than the large page size, we have
3671 // to manually ensure that the memory returned is 'alignment' aligned.
3672 if (alignment > os::large_page_size()) {
3673 assert(is_size_aligned(alignment, os::large_page_size()), "Must be divisible by the large page size");
3674 return shmat_with_alignment(shmid, bytes, alignment);
3675 } else {
3676 return shmat_at_address(shmid, NULL);
3677 }
3678 }
3680 char* os::Linux::reserve_memory_special_shm(size_t bytes, size_t alignment, char* req_addr, bool exec) {
3681 // "exec" is passed in but not used. Creating the shared image for
3682 // the code cache doesn't have an SHM_X executable permission to check.
3683 assert(UseLargePages && UseSHM, "only for SHM large pages");
3684 assert(is_ptr_aligned(req_addr, os::large_page_size()), "Unaligned address");
3685 assert(is_ptr_aligned(req_addr, alignment), "Unaligned address");
3687 if (!is_size_aligned(bytes, os::large_page_size())) {
3688 return NULL; // Fallback to small pages.
3689 }
3691 // Create a large shared memory region to attach to based on size.
3692 // Currently, size is the total size of the heap.
3693 int shmid = shmget(IPC_PRIVATE, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
3694 if (shmid == -1) {
3695 // Possible reasons for shmget failure:
3696 // 1. shmmax is too small for Java heap.
3697 // > check shmmax value: cat /proc/sys/kernel/shmmax
3698 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
3699 // 2. not enough large page memory.
3700 // > check available large pages: cat /proc/meminfo
3701 // > increase amount of large pages:
3702 // echo new_value > /proc/sys/vm/nr_hugepages
3703 // Note 1: different Linux may use different name for this property,
3704 // e.g. on Redhat AS-3 it is "hugetlb_pool".
3705 // Note 2: it's possible there's enough physical memory available but
3706 // they are so fragmented after a long run that they can't
3707 // coalesce into large pages. Try to reserve large pages when
3708 // the system is still "fresh".
3709 shm_warning_with_errno("Failed to reserve shared memory.");
3710 return NULL;
3711 }
3713 // Attach to the region.
3714 char* addr = shmat_large_pages(shmid, bytes, alignment, req_addr);
3716 // Remove shmid. If shmat() is successful, the actual shared memory segment
3717 // will be deleted when it's detached by shmdt() or when the process
3718 // terminates. If shmat() is not successful this will remove the shared
3719 // segment immediately.
3720 shmctl(shmid, IPC_RMID, NULL);
3722 return addr;
3723 }
3725 static void warn_on_large_pages_failure(char* req_addr, size_t bytes, int error) {
3726 assert(error == ENOMEM, "Only expect to fail if no memory is available");
3728 bool warn_on_failure = UseLargePages &&
3729 (!FLAG_IS_DEFAULT(UseLargePages) ||
3730 !FLAG_IS_DEFAULT(UseHugeTLBFS) ||
3731 !FLAG_IS_DEFAULT(LargePageSizeInBytes));
3733 if (warn_on_failure) {
3734 char msg[128];
3735 jio_snprintf(msg, sizeof(msg), "Failed to reserve large pages memory req_addr: "
3736 PTR_FORMAT " bytes: " SIZE_FORMAT " (errno = %d).", req_addr, bytes, error);
3737 warning("%s", msg);
3738 }
3739 }
3741 char* os::Linux::reserve_memory_special_huge_tlbfs_only(size_t bytes, char* req_addr, bool exec) {
3742 assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages");
3743 assert(is_size_aligned(bytes, os::large_page_size()), "Unaligned size");
3744 assert(is_ptr_aligned(req_addr, os::large_page_size()), "Unaligned address");
3746 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
3747 char* addr = (char*)::mmap(req_addr, bytes, prot,
3748 MAP_PRIVATE|MAP_ANONYMOUS|MAP_HUGETLB,
3749 -1, 0);
3751 if (addr == MAP_FAILED) {
3752 warn_on_large_pages_failure(req_addr, bytes, errno);
3753 return NULL;
3754 }
3756 assert(is_ptr_aligned(addr, os::large_page_size()), "Must be");
3758 return addr;
3759 }
3761 // Reserve memory using mmap(MAP_HUGETLB).
3762 // - bytes shall be a multiple of alignment.
3763 // - req_addr can be NULL. If not NULL, it must be a multiple of alignment.
3764 // - alignment sets the alignment at which memory shall be allocated.
3765 // It must be a multiple of allocation granularity.
3766 // Returns address of memory or NULL. If req_addr was not NULL, will only return
3767 // req_addr or NULL.
3768 char* os::Linux::reserve_memory_special_huge_tlbfs_mixed(size_t bytes, size_t alignment, char* req_addr, bool exec) {
3769 size_t large_page_size = os::large_page_size();
3770 assert(bytes >= large_page_size, "Shouldn't allocate large pages for small sizes");
3772 assert(is_ptr_aligned(req_addr, alignment), "Must be");
3773 assert(is_size_aligned(bytes, alignment), "Must be");
3775 // First reserve - but not commit - the address range in small pages.
3776 char* const start = anon_mmap_aligned(bytes, alignment, req_addr);
3778 if (start == NULL) {
3779 return NULL;
3780 }
3782 assert(is_ptr_aligned(start, alignment), "Must be");
3784 char* end = start + bytes;
3786 // Find the regions of the allocated chunk that can be promoted to large pages.
3787 char* lp_start = (char*)align_ptr_up(start, large_page_size);
3788 char* lp_end = (char*)align_ptr_down(end, large_page_size);
3790 size_t lp_bytes = lp_end - lp_start;
3792 assert(is_size_aligned(lp_bytes, large_page_size), "Must be");
3794 if (lp_bytes == 0) {
3795 // The mapped region doesn't even span the start and the end of a large page.
3796 // Fall back to allocate a non-special area.
3797 ::munmap(start, end - start);
3798 return NULL;
3799 }
3801 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
3803 void* result;
3805 // Commit small-paged leading area.
3806 if (start != lp_start) {
3807 result = ::mmap(start, lp_start - start, prot,
3808 MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED,
3809 -1, 0);
3810 if (result == MAP_FAILED) {
3811 ::munmap(lp_start, end - lp_start);
3812 return NULL;
3813 }
3814 }
3816 // Commit large-paged area.
3817 result = ::mmap(lp_start, lp_bytes, prot,
3818 MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED|MAP_HUGETLB,
3819 -1, 0);
3820 if (result == MAP_FAILED) {
3821 warn_on_large_pages_failure(lp_start, lp_bytes, errno);
3822 // If the mmap above fails, the large pages region will be unmapped and we
3823 // have regions before and after with small pages. Release these regions.
3824 //
3825 // | mapped | unmapped | mapped |
3826 // ^ ^ ^ ^
3827 // start lp_start lp_end end
3828 //
3829 ::munmap(start, lp_start - start);
3830 ::munmap(lp_end, end - lp_end);
3831 return NULL;
3832 }
3834 // Commit small-paged trailing area.
3835 if (lp_end != end) {
3836 result = ::mmap(lp_end, end - lp_end, prot,
3837 MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED,
3838 -1, 0);
3839 if (result == MAP_FAILED) {
3840 ::munmap(start, lp_end - start);
3841 return NULL;
3842 }
3843 }
3845 return start;
3846 }
3848 char* os::Linux::reserve_memory_special_huge_tlbfs(size_t bytes, size_t alignment, char* req_addr, bool exec) {
3849 assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages");
3850 assert(is_ptr_aligned(req_addr, alignment), "Must be");
3851 assert(is_size_aligned(alignment, os::vm_allocation_granularity()), "Must be");
3852 assert(is_power_of_2(os::large_page_size()), "Must be");
3853 assert(bytes >= os::large_page_size(), "Shouldn't allocate large pages for small sizes");
3855 if (is_size_aligned(bytes, os::large_page_size()) && alignment <= os::large_page_size()) {
3856 return reserve_memory_special_huge_tlbfs_only(bytes, req_addr, exec);
3857 } else {
3858 return reserve_memory_special_huge_tlbfs_mixed(bytes, alignment, req_addr, exec);
3859 }
3860 }
3862 char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {
3863 assert(UseLargePages, "only for large pages");
3865 char* addr;
3866 if (UseSHM) {
3867 addr = os::Linux::reserve_memory_special_shm(bytes, alignment, req_addr, exec);
3868 } else {
3869 assert(UseHugeTLBFS, "must be");
3870 addr = os::Linux::reserve_memory_special_huge_tlbfs(bytes, alignment, req_addr, exec);
3871 }
3873 if (addr != NULL) {
3874 if (UseNUMAInterleaving) {
3875 numa_make_global(addr, bytes);
3876 }
3878 // The memory is committed
3879 MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, CALLER_PC);
3880 }
3882 return addr;
3883 }
3885 bool os::Linux::release_memory_special_shm(char* base, size_t bytes) {
3886 // detaching the SHM segment will also delete it, see reserve_memory_special_shm()
3887 return shmdt(base) == 0;
3888 }
3890 bool os::Linux::release_memory_special_huge_tlbfs(char* base, size_t bytes) {
3891 return pd_release_memory(base, bytes);
3892 }
3894 bool os::release_memory_special(char* base, size_t bytes) {
3895 bool res;
3896 if (MemTracker::tracking_level() > NMT_minimal) {
3897 Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
3898 res = os::Linux::release_memory_special_impl(base, bytes);
3899 if (res) {
3900 tkr.record((address)base, bytes);
3901 }
3903 } else {
3904 res = os::Linux::release_memory_special_impl(base, bytes);
3905 }
3906 return res;
3907 }
3909 bool os::Linux::release_memory_special_impl(char* base, size_t bytes) {
3910 assert(UseLargePages, "only for large pages");
3911 bool res;
3913 if (UseSHM) {
3914 res = os::Linux::release_memory_special_shm(base, bytes);
3915 } else {
3916 assert(UseHugeTLBFS, "must be");
3917 res = os::Linux::release_memory_special_huge_tlbfs(base, bytes);
3918 }
3919 return res;
3920 }
3922 size_t os::large_page_size() {
3923 return _large_page_size;
3924 }
3926 // With SysV SHM the entire memory region must be allocated as shared
3927 // memory.
3928 // HugeTLBFS allows application to commit large page memory on demand.
3929 // However, when committing memory with HugeTLBFS fails, the region
3930 // that was supposed to be committed will lose the old reservation
3931 // and allow other threads to steal that memory region. Because of this
3932 // behavior we can't commit HugeTLBFS memory.
3933 bool os::can_commit_large_page_memory() {
3934 return UseTransparentHugePages;
3935 }
3937 bool os::can_execute_large_page_memory() {
3938 return UseTransparentHugePages || UseHugeTLBFS;
3939 }
3941 // Reserve memory at an arbitrary address, only if that area is
3942 // available (and not reserved for something else).
3944 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
3945 const int max_tries = 10;
3946 char* base[max_tries];
3947 size_t size[max_tries];
3948 const size_t gap = 0x000000;
3950 // Assert only that the size is a multiple of the page size, since
3951 // that's all that mmap requires, and since that's all we really know
3952 // about at this low abstraction level. If we need higher alignment,
3953 // we can either pass an alignment to this method or verify alignment
3954 // in one of the methods further up the call chain. See bug 5044738.
3955 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
3957 // Repeatedly allocate blocks until the block is allocated at the
3958 // right spot. Give up after max_tries. Note that reserve_memory() will
3959 // automatically update _highest_vm_reserved_address if the call is
3960 // successful. The variable tracks the highest memory address every reserved
3961 // by JVM. It is used to detect heap-stack collision if running with
3962 // fixed-stack LinuxThreads. Because here we may attempt to reserve more
3963 // space than needed, it could confuse the collision detecting code. To
3964 // solve the problem, save current _highest_vm_reserved_address and
3965 // calculate the correct value before return.
3966 address old_highest = _highest_vm_reserved_address;
3968 // Linux mmap allows caller to pass an address as hint; give it a try first,
3969 // if kernel honors the hint then we can return immediately.
3970 char * addr = anon_mmap(requested_addr, bytes, false);
3971 if (addr == requested_addr) {
3972 return requested_addr;
3973 }
3975 if (addr != NULL) {
3976 // mmap() is successful but it fails to reserve at the requested address
3977 anon_munmap(addr, bytes);
3978 }
3980 int i;
3981 for (i = 0; i < max_tries; ++i) {
3982 base[i] = reserve_memory(bytes);
3984 if (base[i] != NULL) {
3985 // Is this the block we wanted?
3986 if (base[i] == requested_addr) {
3987 size[i] = bytes;
3988 break;
3989 }
3991 // Does this overlap the block we wanted? Give back the overlapped
3992 // parts and try again.
3994 size_t top_overlap = requested_addr + (bytes + gap) - base[i];
3995 if (top_overlap >= 0 && top_overlap < bytes) {
3996 unmap_memory(base[i], top_overlap);
3997 base[i] += top_overlap;
3998 size[i] = bytes - top_overlap;
3999 } else {
4000 size_t bottom_overlap = base[i] + bytes - requested_addr;
4001 if (bottom_overlap >= 0 && bottom_overlap < bytes) {
4002 unmap_memory(requested_addr, bottom_overlap);
4003 size[i] = bytes - bottom_overlap;
4004 } else {
4005 size[i] = bytes;
4006 }
4007 }
4008 }
4009 }
4011 // Give back the unused reserved pieces.
4013 for (int j = 0; j < i; ++j) {
4014 if (base[j] != NULL) {
4015 unmap_memory(base[j], size[j]);
4016 }
4017 }
4019 if (i < max_tries) {
4020 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
4021 return requested_addr;
4022 } else {
4023 _highest_vm_reserved_address = old_highest;
4024 return NULL;
4025 }
4026 }
4028 size_t os::read(int fd, void *buf, unsigned int nBytes) {
4029 return ::read(fd, buf, nBytes);
4030 }
4032 // TODO-FIXME: reconcile Solaris' os::sleep with the linux variation.
4033 // Solaris uses poll(), linux uses park().
4034 // Poll() is likely a better choice, assuming that Thread.interrupt()
4035 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with
4036 // SIGSEGV, see 4355769.
4038 int os::sleep(Thread* thread, jlong millis, bool interruptible) {
4039 assert(thread == Thread::current(), "thread consistency check");
4041 ParkEvent * const slp = thread->_SleepEvent ;
4042 slp->reset() ;
4043 OrderAccess::fence() ;
4045 if (interruptible) {
4046 jlong prevtime = javaTimeNanos();
4048 for (;;) {
4049 if (os::is_interrupted(thread, true)) {
4050 return OS_INTRPT;
4051 }
4053 jlong newtime = javaTimeNanos();
4055 if (newtime - prevtime < 0) {
4056 // time moving backwards, should only happen if no monotonic clock
4057 // not a guarantee() because JVM should not abort on kernel/glibc bugs
4058 assert(!Linux::supports_monotonic_clock(), "time moving backwards");
4059 } else {
4060 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
4061 }
4063 if(millis <= 0) {
4064 return OS_OK;
4065 }
4067 prevtime = newtime;
4069 {
4070 assert(thread->is_Java_thread(), "sanity check");
4071 JavaThread *jt = (JavaThread *) thread;
4072 ThreadBlockInVM tbivm(jt);
4073 OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
4075 jt->set_suspend_equivalent();
4076 // cleared by handle_special_suspend_equivalent_condition() or
4077 // java_suspend_self() via check_and_wait_while_suspended()
4079 slp->park(millis);
4081 // were we externally suspended while we were waiting?
4082 jt->check_and_wait_while_suspended();
4083 }
4084 }
4085 } else {
4086 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
4087 jlong prevtime = javaTimeNanos();
4089 for (;;) {
4090 // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
4091 // the 1st iteration ...
4092 jlong newtime = javaTimeNanos();
4094 if (newtime - prevtime < 0) {
4095 // time moving backwards, should only happen if no monotonic clock
4096 // not a guarantee() because JVM should not abort on kernel/glibc bugs
4097 assert(!Linux::supports_monotonic_clock(), "time moving backwards");
4098 } else {
4099 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
4100 }
4102 if(millis <= 0) break ;
4104 prevtime = newtime;
4105 slp->park(millis);
4106 }
4107 return OS_OK ;
4108 }
4109 }
4111 //
4112 // Short sleep, direct OS call.
4113 //
4114 // Note: certain versions of Linux CFS scheduler (since 2.6.23) do not guarantee
4115 // sched_yield(2) will actually give up the CPU:
4116 //
4117 // * Alone on this pariticular CPU, keeps running.
4118 // * Before the introduction of "skip_buddy" with "compat_yield" disabled
4119 // (pre 2.6.39).
4120 //
4121 // So calling this with 0 is an alternative.
4122 //
4123 void os::naked_short_sleep(jlong ms) {
4124 struct timespec req;
4126 assert(ms < 1000, "Un-interruptable sleep, short time use only");
4127 req.tv_sec = 0;
4128 if (ms > 0) {
4129 req.tv_nsec = (ms % 1000) * 1000000;
4130 }
4131 else {
4132 req.tv_nsec = 1;
4133 }
4135 nanosleep(&req, NULL);
4137 return;
4138 }
4140 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
4141 void os::infinite_sleep() {
4142 while (true) { // sleep forever ...
4143 ::sleep(100); // ... 100 seconds at a time
4144 }
4145 }
4147 // Used to convert frequent JVM_Yield() to nops
4148 bool os::dont_yield() {
4149 return DontYieldALot;
4150 }
4152 void os::yield() {
4153 sched_yield();
4154 }
4156 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
4158 void os::yield_all(int attempts) {
4159 // Yields to all threads, including threads with lower priorities
4160 // Threads on Linux are all with same priority. The Solaris style
4161 // os::yield_all() with nanosleep(1ms) is not necessary.
4162 sched_yield();
4163 }
4165 // Called from the tight loops to possibly influence time-sharing heuristics
4166 void os::loop_breaker(int attempts) {
4167 os::yield_all(attempts);
4168 }
4170 ////////////////////////////////////////////////////////////////////////////////
4171 // thread priority support
4173 // Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER
4174 // only supports dynamic priority, static priority must be zero. For real-time
4175 // applications, Linux supports SCHED_RR which allows static priority (1-99).
4176 // However, for large multi-threaded applications, SCHED_RR is not only slower
4177 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
4178 // of 5 runs - Sep 2005).
4179 //
4180 // The following code actually changes the niceness of kernel-thread/LWP. It
4181 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
4182 // not the entire user process, and user level threads are 1:1 mapped to kernel
4183 // threads. It has always been the case, but could change in the future. For
4184 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
4185 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
4187 int os::java_to_os_priority[CriticalPriority + 1] = {
4188 19, // 0 Entry should never be used
4190 4, // 1 MinPriority
4191 3, // 2
4192 2, // 3
4194 1, // 4
4195 0, // 5 NormPriority
4196 -1, // 6
4198 -2, // 7
4199 -3, // 8
4200 -4, // 9 NearMaxPriority
4202 -5, // 10 MaxPriority
4204 -5 // 11 CriticalPriority
4205 };
4207 static int prio_init() {
4208 if (ThreadPriorityPolicy == 1) {
4209 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
4210 // if effective uid is not root. Perhaps, a more elegant way of doing
4211 // this is to test CAP_SYS_NICE capability, but that will require libcap.so
4212 if (geteuid() != 0) {
4213 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
4214 warning("-XX:ThreadPriorityPolicy requires root privilege on Linux");
4215 }
4216 ThreadPriorityPolicy = 0;
4217 }
4218 }
4219 if (UseCriticalJavaThreadPriority) {
4220 os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
4221 }
4222 return 0;
4223 }
4225 OSReturn os::set_native_priority(Thread* thread, int newpri) {
4226 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
4228 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
4229 return (ret == 0) ? OS_OK : OS_ERR;
4230 }
4232 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
4233 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
4234 *priority_ptr = java_to_os_priority[NormPriority];
4235 return OS_OK;
4236 }
4238 errno = 0;
4239 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
4240 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
4241 }
4243 // Hint to the underlying OS that a task switch would not be good.
4244 // Void return because it's a hint and can fail.
4245 void os::hint_no_preempt() {}
4247 ////////////////////////////////////////////////////////////////////////////////
4248 // suspend/resume support
4250 // the low-level signal-based suspend/resume support is a remnant from the
4251 // old VM-suspension that used to be for java-suspension, safepoints etc,
4252 // within hotspot. Now there is a single use-case for this:
4253 // - calling get_thread_pc() on the VMThread by the flat-profiler task
4254 // that runs in the watcher thread.
4255 // The remaining code is greatly simplified from the more general suspension
4256 // code that used to be used.
4257 //
4258 // The protocol is quite simple:
4259 // - suspend:
4260 // - sends a signal to the target thread
4261 // - polls the suspend state of the osthread using a yield loop
4262 // - target thread signal handler (SR_handler) sets suspend state
4263 // and blocks in sigsuspend until continued
4264 // - resume:
4265 // - sets target osthread state to continue
4266 // - sends signal to end the sigsuspend loop in the SR_handler
4267 //
4268 // Note that the SR_lock plays no role in this suspend/resume protocol.
4269 //
4271 static void resume_clear_context(OSThread *osthread) {
4272 osthread->set_ucontext(NULL);
4273 osthread->set_siginfo(NULL);
4274 }
4276 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
4277 osthread->set_ucontext(context);
4278 osthread->set_siginfo(siginfo);
4279 }
4281 //
4282 // Handler function invoked when a thread's execution is suspended or
4283 // resumed. We have to be careful that only async-safe functions are
4284 // called here (Note: most pthread functions are not async safe and
4285 // should be avoided.)
4286 //
4287 // Note: sigwait() is a more natural fit than sigsuspend() from an
4288 // interface point of view, but sigwait() prevents the signal hander
4289 // from being run. libpthread would get very confused by not having
4290 // its signal handlers run and prevents sigwait()'s use with the
4291 // mutex granting granting signal.
4292 //
4293 // Currently only ever called on the VMThread and JavaThreads (PC sampling)
4294 //
4295 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
4296 // Save and restore errno to avoid confusing native code with EINTR
4297 // after sigsuspend.
4298 int old_errno = errno;
4300 Thread* thread = Thread::current();
4301 OSThread* osthread = thread->osthread();
4302 assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
4304 os::SuspendResume::State current = osthread->sr.state();
4305 if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
4306 suspend_save_context(osthread, siginfo, context);
4308 // attempt to switch the state, we assume we had a SUSPEND_REQUEST
4309 os::SuspendResume::State state = osthread->sr.suspended();
4310 if (state == os::SuspendResume::SR_SUSPENDED) {
4311 sigset_t suspend_set; // signals for sigsuspend()
4313 // get current set of blocked signals and unblock resume signal
4314 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
4315 sigdelset(&suspend_set, SR_signum);
4317 sr_semaphore.signal();
4318 // wait here until we are resumed
4319 while (1) {
4320 sigsuspend(&suspend_set);
4322 os::SuspendResume::State result = osthread->sr.running();
4323 if (result == os::SuspendResume::SR_RUNNING) {
4324 sr_semaphore.signal();
4325 break;
4326 }
4327 }
4329 } else if (state == os::SuspendResume::SR_RUNNING) {
4330 // request was cancelled, continue
4331 } else {
4332 ShouldNotReachHere();
4333 }
4335 resume_clear_context(osthread);
4336 } else if (current == os::SuspendResume::SR_RUNNING) {
4337 // request was cancelled, continue
4338 } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
4339 // ignore
4340 } else {
4341 // ignore
4342 }
4344 errno = old_errno;
4345 }
4348 static int SR_initialize() {
4349 struct sigaction act;
4350 char *s;
4351 /* Get signal number to use for suspend/resume */
4352 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
4353 int sig = ::strtol(s, 0, 10);
4354 if (sig > 0 || sig < _NSIG) {
4355 SR_signum = sig;
4356 }
4357 }
4359 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
4360 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
4362 sigemptyset(&SR_sigset);
4363 sigaddset(&SR_sigset, SR_signum);
4365 /* Set up signal handler for suspend/resume */
4366 act.sa_flags = SA_RESTART|SA_SIGINFO;
4367 act.sa_handler = (void (*)(int)) SR_handler;
4369 // SR_signum is blocked by default.
4370 // 4528190 - We also need to block pthread restart signal (32 on all
4371 // supported Linux platforms). Note that LinuxThreads need to block
4372 // this signal for all threads to work properly. So we don't have
4373 // to use hard-coded signal number when setting up the mask.
4374 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
4376 if (sigaction(SR_signum, &act, 0) == -1) {
4377 return -1;
4378 }
4380 // Save signal flag
4381 os::Linux::set_our_sigflags(SR_signum, act.sa_flags);
4382 return 0;
4383 }
4385 static int sr_notify(OSThread* osthread) {
4386 int status = pthread_kill(osthread->pthread_id(), SR_signum);
4387 assert_status(status == 0, status, "pthread_kill");
4388 return status;
4389 }
4391 // "Randomly" selected value for how long we want to spin
4392 // before bailing out on suspending a thread, also how often
4393 // we send a signal to a thread we want to resume
4394 static const int RANDOMLY_LARGE_INTEGER = 1000000;
4395 static const int RANDOMLY_LARGE_INTEGER2 = 100;
4397 // returns true on success and false on error - really an error is fatal
4398 // but this seems the normal response to library errors
4399 static bool do_suspend(OSThread* osthread) {
4400 assert(osthread->sr.is_running(), "thread should be running");
4401 assert(!sr_semaphore.trywait(), "semaphore has invalid state");
4403 // mark as suspended and send signal
4404 if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
4405 // failed to switch, state wasn't running?
4406 ShouldNotReachHere();
4407 return false;
4408 }
4410 if (sr_notify(osthread) != 0) {
4411 ShouldNotReachHere();
4412 }
4414 // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
4415 while (true) {
4416 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
4417 break;
4418 } else {
4419 // timeout
4420 os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
4421 if (cancelled == os::SuspendResume::SR_RUNNING) {
4422 return false;
4423 } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
4424 // make sure that we consume the signal on the semaphore as well
4425 sr_semaphore.wait();
4426 break;
4427 } else {
4428 ShouldNotReachHere();
4429 return false;
4430 }
4431 }
4432 }
4434 guarantee(osthread->sr.is_suspended(), "Must be suspended");
4435 return true;
4436 }
4438 static void do_resume(OSThread* osthread) {
4439 assert(osthread->sr.is_suspended(), "thread should be suspended");
4440 assert(!sr_semaphore.trywait(), "invalid semaphore state");
4442 if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
4443 // failed to switch to WAKEUP_REQUEST
4444 ShouldNotReachHere();
4445 return;
4446 }
4448 while (true) {
4449 if (sr_notify(osthread) == 0) {
4450 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
4451 if (osthread->sr.is_running()) {
4452 return;
4453 }
4454 }
4455 } else {
4456 ShouldNotReachHere();
4457 }
4458 }
4460 guarantee(osthread->sr.is_running(), "Must be running!");
4461 }
4463 ////////////////////////////////////////////////////////////////////////////////
4464 // interrupt support
4466 void os::interrupt(Thread* thread) {
4467 assert(Thread::current() == thread || Threads_lock->owned_by_self(),
4468 "possibility of dangling Thread pointer");
4470 OSThread* osthread = thread->osthread();
4472 if (!osthread->interrupted()) {
4473 osthread->set_interrupted(true);
4474 // More than one thread can get here with the same value of osthread,
4475 // resulting in multiple notifications. We do, however, want the store
4476 // to interrupted() to be visible to other threads before we execute unpark().
4477 OrderAccess::fence();
4478 ParkEvent * const slp = thread->_SleepEvent ;
4479 if (slp != NULL) slp->unpark() ;
4480 }
4482 // For JSR166. Unpark even if interrupt status already was set
4483 if (thread->is_Java_thread())
4484 ((JavaThread*)thread)->parker()->unpark();
4486 ParkEvent * ev = thread->_ParkEvent ;
4487 if (ev != NULL) ev->unpark() ;
4489 }
4491 bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
4492 assert(Thread::current() == thread || Threads_lock->owned_by_self(),
4493 "possibility of dangling Thread pointer");
4495 OSThread* osthread = thread->osthread();
4497 bool interrupted = osthread->interrupted();
4499 if (interrupted && clear_interrupted) {
4500 osthread->set_interrupted(false);
4501 // consider thread->_SleepEvent->reset() ... optional optimization
4502 }
4504 return interrupted;
4505 }
4507 ///////////////////////////////////////////////////////////////////////////////////
4508 // signal handling (except suspend/resume)
4510 // This routine may be used by user applications as a "hook" to catch signals.
4511 // The user-defined signal handler must pass unrecognized signals to this
4512 // routine, and if it returns true (non-zero), then the signal handler must
4513 // return immediately. If the flag "abort_if_unrecognized" is true, then this
4514 // routine will never retun false (zero), but instead will execute a VM panic
4515 // routine kill the process.
4516 //
4517 // If this routine returns false, it is OK to call it again. This allows
4518 // the user-defined signal handler to perform checks either before or after
4519 // the VM performs its own checks. Naturally, the user code would be making
4520 // a serious error if it tried to handle an exception (such as a null check
4521 // or breakpoint) that the VM was generating for its own correct operation.
4522 //
4523 // This routine may recognize any of the following kinds of signals:
4524 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
4525 // It should be consulted by handlers for any of those signals.
4526 //
4527 // The caller of this routine must pass in the three arguments supplied
4528 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
4529 // field of the structure passed to sigaction(). This routine assumes that
4530 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
4531 //
4532 // Note that the VM will print warnings if it detects conflicting signal
4533 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
4534 //
4535 extern "C" JNIEXPORT int
4536 JVM_handle_linux_signal(int signo, siginfo_t* siginfo,
4537 void* ucontext, int abort_if_unrecognized);
4539 void signalHandler(int sig, siginfo_t* info, void* uc) {
4540 assert(info != NULL && uc != NULL, "it must be old kernel");
4541 int orig_errno = errno; // Preserve errno value over signal handler.
4542 JVM_handle_linux_signal(sig, info, uc, true);
4543 errno = orig_errno;
4544 }
4547 // This boolean allows users to forward their own non-matching signals
4548 // to JVM_handle_linux_signal, harmlessly.
4549 bool os::Linux::signal_handlers_are_installed = false;
4551 // For signal-chaining
4552 struct sigaction os::Linux::sigact[MAXSIGNUM];
4553 unsigned int os::Linux::sigs = 0;
4554 bool os::Linux::libjsig_is_loaded = false;
4555 typedef struct sigaction *(*get_signal_t)(int);
4556 get_signal_t os::Linux::get_signal_action = NULL;
4558 struct sigaction* os::Linux::get_chained_signal_action(int sig) {
4559 struct sigaction *actp = NULL;
4561 if (libjsig_is_loaded) {
4562 // Retrieve the old signal handler from libjsig
4563 actp = (*get_signal_action)(sig);
4564 }
4565 if (actp == NULL) {
4566 // Retrieve the preinstalled signal handler from jvm
4567 actp = get_preinstalled_handler(sig);
4568 }
4570 return actp;
4571 }
4573 static bool call_chained_handler(struct sigaction *actp, int sig,
4574 siginfo_t *siginfo, void *context) {
4575 // Call the old signal handler
4576 if (actp->sa_handler == SIG_DFL) {
4577 // It's more reasonable to let jvm treat it as an unexpected exception
4578 // instead of taking the default action.
4579 return false;
4580 } else if (actp->sa_handler != SIG_IGN) {
4581 if ((actp->sa_flags & SA_NODEFER) == 0) {
4582 // automaticlly block the signal
4583 sigaddset(&(actp->sa_mask), sig);
4584 }
4586 sa_handler_t hand = NULL;
4587 sa_sigaction_t sa = NULL;
4588 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
4589 // retrieve the chained handler
4590 if (siginfo_flag_set) {
4591 sa = actp->sa_sigaction;
4592 } else {
4593 hand = actp->sa_handler;
4594 }
4596 if ((actp->sa_flags & SA_RESETHAND) != 0) {
4597 actp->sa_handler = SIG_DFL;
4598 }
4600 // try to honor the signal mask
4601 sigset_t oset;
4602 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
4604 // call into the chained handler
4605 if (siginfo_flag_set) {
4606 (*sa)(sig, siginfo, context);
4607 } else {
4608 (*hand)(sig);
4609 }
4611 // restore the signal mask
4612 pthread_sigmask(SIG_SETMASK, &oset, 0);
4613 }
4614 // Tell jvm's signal handler the signal is taken care of.
4615 return true;
4616 }
4618 bool os::Linux::chained_handler(int sig, siginfo_t* siginfo, void* context) {
4619 bool chained = false;
4620 // signal-chaining
4621 if (UseSignalChaining) {
4622 struct sigaction *actp = get_chained_signal_action(sig);
4623 if (actp != NULL) {
4624 chained = call_chained_handler(actp, sig, siginfo, context);
4625 }
4626 }
4627 return chained;
4628 }
4630 struct sigaction* os::Linux::get_preinstalled_handler(int sig) {
4631 if ((( (unsigned int)1 << sig ) & sigs) != 0) {
4632 return &sigact[sig];
4633 }
4634 return NULL;
4635 }
4637 void os::Linux::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
4638 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4639 sigact[sig] = oldAct;
4640 sigs |= (unsigned int)1 << sig;
4641 }
4643 // for diagnostic
4644 int os::Linux::sigflags[MAXSIGNUM];
4646 int os::Linux::get_our_sigflags(int sig) {
4647 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4648 return sigflags[sig];
4649 }
4651 void os::Linux::set_our_sigflags(int sig, int flags) {
4652 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4653 sigflags[sig] = flags;
4654 }
4656 void os::Linux::set_signal_handler(int sig, bool set_installed) {
4657 // Check for overwrite.
4658 struct sigaction oldAct;
4659 sigaction(sig, (struct sigaction*)NULL, &oldAct);
4661 void* oldhand = oldAct.sa_sigaction
4662 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
4663 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
4664 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
4665 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
4666 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
4667 if (AllowUserSignalHandlers || !set_installed) {
4668 // Do not overwrite; user takes responsibility to forward to us.
4669 return;
4670 } else if (UseSignalChaining) {
4671 // save the old handler in jvm
4672 save_preinstalled_handler(sig, oldAct);
4673 // libjsig also interposes the sigaction() call below and saves the
4674 // old sigaction on it own.
4675 } else {
4676 fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
4677 "%#lx for signal %d.", (long)oldhand, sig));
4678 }
4679 }
4681 struct sigaction sigAct;
4682 sigfillset(&(sigAct.sa_mask));
4683 sigAct.sa_handler = SIG_DFL;
4684 if (!set_installed) {
4685 sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
4686 } else {
4687 sigAct.sa_sigaction = signalHandler;
4688 sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
4689 }
4690 // Save flags, which are set by ours
4691 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4692 sigflags[sig] = sigAct.sa_flags;
4694 int ret = sigaction(sig, &sigAct, &oldAct);
4695 assert(ret == 0, "check");
4697 void* oldhand2 = oldAct.sa_sigaction
4698 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
4699 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
4700 assert(oldhand2 == oldhand, "no concurrent signal handler installation");
4701 }
4703 // install signal handlers for signals that HotSpot needs to
4704 // handle in order to support Java-level exception handling.
4706 void os::Linux::install_signal_handlers() {
4707 if (!signal_handlers_are_installed) {
4708 signal_handlers_are_installed = true;
4710 // signal-chaining
4711 typedef void (*signal_setting_t)();
4712 signal_setting_t begin_signal_setting = NULL;
4713 signal_setting_t end_signal_setting = NULL;
4714 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4715 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
4716 if (begin_signal_setting != NULL) {
4717 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4718 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
4719 get_signal_action = CAST_TO_FN_PTR(get_signal_t,
4720 dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
4721 libjsig_is_loaded = true;
4722 assert(UseSignalChaining, "should enable signal-chaining");
4723 }
4724 if (libjsig_is_loaded) {
4725 // Tell libjsig jvm is setting signal handlers
4726 (*begin_signal_setting)();
4727 }
4729 set_signal_handler(SIGSEGV, true);
4730 set_signal_handler(SIGPIPE, true);
4731 set_signal_handler(SIGBUS, true);
4732 set_signal_handler(SIGILL, true);
4733 set_signal_handler(SIGFPE, true);
4734 #if defined(PPC64)
4735 set_signal_handler(SIGTRAP, true);
4736 #endif
4737 set_signal_handler(SIGXFSZ, true);
4739 if (libjsig_is_loaded) {
4740 // Tell libjsig jvm finishes setting signal handlers
4741 (*end_signal_setting)();
4742 }
4744 // We don't activate signal checker if libjsig is in place, we trust ourselves
4745 // and if UserSignalHandler is installed all bets are off.
4746 // Log that signal checking is off only if -verbose:jni is specified.
4747 if (CheckJNICalls) {
4748 if (libjsig_is_loaded) {
4749 if (PrintJNIResolving) {
4750 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
4751 }
4752 check_signals = false;
4753 }
4754 if (AllowUserSignalHandlers) {
4755 if (PrintJNIResolving) {
4756 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
4757 }
4758 check_signals = false;
4759 }
4760 }
4761 }
4762 }
4764 // This is the fastest way to get thread cpu time on Linux.
4765 // Returns cpu time (user+sys) for any thread, not only for current.
4766 // POSIX compliant clocks are implemented in the kernels 2.6.16+.
4767 // It might work on 2.6.10+ with a special kernel/glibc patch.
4768 // For reference, please, see IEEE Std 1003.1-2004:
4769 // http://www.unix.org/single_unix_specification
4771 jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) {
4772 struct timespec tp;
4773 int rc = os::Linux::clock_gettime(clockid, &tp);
4774 assert(rc == 0, "clock_gettime is expected to return 0 code");
4776 return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec;
4777 }
4779 /////
4780 // glibc on Linux platform uses non-documented flag
4781 // to indicate, that some special sort of signal
4782 // trampoline is used.
4783 // We will never set this flag, and we should
4784 // ignore this flag in our diagnostic
4785 #ifdef SIGNIFICANT_SIGNAL_MASK
4786 #undef SIGNIFICANT_SIGNAL_MASK
4787 #endif
4788 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
4790 static const char* get_signal_handler_name(address handler,
4791 char* buf, int buflen) {
4792 int offset = 0;
4793 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
4794 if (found) {
4795 // skip directory names
4796 const char *p1, *p2;
4797 p1 = buf;
4798 size_t len = strlen(os::file_separator());
4799 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
4800 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
4801 } else {
4802 jio_snprintf(buf, buflen, PTR_FORMAT, handler);
4803 }
4804 return buf;
4805 }
4807 static void print_signal_handler(outputStream* st, int sig,
4808 char* buf, size_t buflen) {
4809 struct sigaction sa;
4811 sigaction(sig, NULL, &sa);
4813 // See comment for SIGNIFICANT_SIGNAL_MASK define
4814 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
4816 st->print("%s: ", os::exception_name(sig, buf, buflen));
4818 address handler = (sa.sa_flags & SA_SIGINFO)
4819 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
4820 : CAST_FROM_FN_PTR(address, sa.sa_handler);
4822 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
4823 st->print("SIG_DFL");
4824 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
4825 st->print("SIG_IGN");
4826 } else {
4827 st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
4828 }
4830 st->print(", sa_mask[0]=");
4831 os::Posix::print_signal_set_short(st, &sa.sa_mask);
4833 address rh = VMError::get_resetted_sighandler(sig);
4834 // May be, handler was resetted by VMError?
4835 if(rh != NULL) {
4836 handler = rh;
4837 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
4838 }
4840 st->print(", sa_flags=");
4841 os::Posix::print_sa_flags(st, sa.sa_flags);
4843 // Check: is it our handler?
4844 if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
4845 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
4846 // It is our signal handler
4847 // check for flags, reset system-used one!
4848 if((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) {
4849 st->print(
4850 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
4851 os::Linux::get_our_sigflags(sig));
4852 }
4853 }
4854 st->cr();
4855 }
4858 #define DO_SIGNAL_CHECK(sig) \
4859 if (!sigismember(&check_signal_done, sig)) \
4860 os::Linux::check_signal_handler(sig)
4862 // This method is a periodic task to check for misbehaving JNI applications
4863 // under CheckJNI, we can add any periodic checks here
4865 void os::run_periodic_checks() {
4867 if (check_signals == false) return;
4869 // SEGV and BUS if overridden could potentially prevent
4870 // generation of hs*.log in the event of a crash, debugging
4871 // such a case can be very challenging, so we absolutely
4872 // check the following for a good measure:
4873 DO_SIGNAL_CHECK(SIGSEGV);
4874 DO_SIGNAL_CHECK(SIGILL);
4875 DO_SIGNAL_CHECK(SIGFPE);
4876 DO_SIGNAL_CHECK(SIGBUS);
4877 DO_SIGNAL_CHECK(SIGPIPE);
4878 DO_SIGNAL_CHECK(SIGXFSZ);
4879 #if defined(PPC64)
4880 DO_SIGNAL_CHECK(SIGTRAP);
4881 #endif
4883 // ReduceSignalUsage allows the user to override these handlers
4884 // see comments at the very top and jvm_solaris.h
4885 if (!ReduceSignalUsage) {
4886 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
4887 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
4888 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
4889 DO_SIGNAL_CHECK(BREAK_SIGNAL);
4890 }
4892 DO_SIGNAL_CHECK(SR_signum);
4893 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
4894 }
4896 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
4898 static os_sigaction_t os_sigaction = NULL;
4900 void os::Linux::check_signal_handler(int sig) {
4901 char buf[O_BUFLEN];
4902 address jvmHandler = NULL;
4905 struct sigaction act;
4906 if (os_sigaction == NULL) {
4907 // only trust the default sigaction, in case it has been interposed
4908 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
4909 if (os_sigaction == NULL) return;
4910 }
4912 os_sigaction(sig, (struct sigaction*)NULL, &act);
4915 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
4917 address thisHandler = (act.sa_flags & SA_SIGINFO)
4918 ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
4919 : CAST_FROM_FN_PTR(address, act.sa_handler) ;
4922 switch(sig) {
4923 case SIGSEGV:
4924 case SIGBUS:
4925 case SIGFPE:
4926 case SIGPIPE:
4927 case SIGILL:
4928 case SIGXFSZ:
4929 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
4930 break;
4932 case SHUTDOWN1_SIGNAL:
4933 case SHUTDOWN2_SIGNAL:
4934 case SHUTDOWN3_SIGNAL:
4935 case BREAK_SIGNAL:
4936 jvmHandler = (address)user_handler();
4937 break;
4939 case INTERRUPT_SIGNAL:
4940 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
4941 break;
4943 default:
4944 if (sig == SR_signum) {
4945 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
4946 } else {
4947 return;
4948 }
4949 break;
4950 }
4952 if (thisHandler != jvmHandler) {
4953 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
4954 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
4955 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
4956 // No need to check this sig any longer
4957 sigaddset(&check_signal_done, sig);
4958 // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
4959 if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
4960 tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",
4961 exception_name(sig, buf, O_BUFLEN));
4962 }
4963 } else if(os::Linux::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Linux::get_our_sigflags(sig)) {
4964 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
4965 tty->print("expected:" PTR32_FORMAT, os::Linux::get_our_sigflags(sig));
4966 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags);
4967 // No need to check this sig any longer
4968 sigaddset(&check_signal_done, sig);
4969 }
4971 // Dump all the signal
4972 if (sigismember(&check_signal_done, sig)) {
4973 print_signal_handlers(tty, buf, O_BUFLEN);
4974 }
4975 }
4977 extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
4979 extern bool signal_name(int signo, char* buf, size_t len);
4981 const char* os::exception_name(int exception_code, char* buf, size_t size) {
4982 if (0 < exception_code && exception_code <= SIGRTMAX) {
4983 // signal
4984 if (!signal_name(exception_code, buf, size)) {
4985 jio_snprintf(buf, size, "SIG%d", exception_code);
4986 }
4987 return buf;
4988 } else {
4989 return NULL;
4990 }
4991 }
4993 // this is called _before_ most of the global arguments have been parsed
4994 void os::init(void) {
4995 char dummy; /* used to get a guess on initial stack address */
4997 // With LinuxThreads the JavaMain thread pid (primordial thread)
4998 // is different than the pid of the java launcher thread.
4999 // So, on Linux, the launcher thread pid is passed to the VM
5000 // via the sun.java.launcher.pid property.
5001 // Use this property instead of getpid() if it was correctly passed.
5002 // See bug 6351349.
5003 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
5005 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
5007 clock_tics_per_sec = sysconf(_SC_CLK_TCK);
5009 init_random(1234567);
5011 ThreadCritical::initialize();
5013 Linux::set_page_size(sysconf(_SC_PAGESIZE));
5014 if (Linux::page_size() == -1) {
5015 fatal(err_msg("os_linux.cpp: os::init: sysconf failed (%s)",
5016 strerror(errno)));
5017 }
5018 init_page_sizes((size_t) Linux::page_size());
5020 Linux::initialize_system_info();
5022 // _main_thread points to the thread that created/loaded the JVM.
5023 Linux::_main_thread = pthread_self();
5025 Linux::clock_init();
5026 initial_time_count = javaTimeNanos();
5028 // pthread_condattr initialization for monotonic clock
5029 int status;
5030 pthread_condattr_t* _condattr = os::Linux::condAttr();
5031 if ((status = pthread_condattr_init(_condattr)) != 0) {
5032 fatal(err_msg("pthread_condattr_init: %s", strerror(status)));
5033 }
5034 // Only set the clock if CLOCK_MONOTONIC is available
5035 if (Linux::supports_monotonic_clock()) {
5036 if ((status = pthread_condattr_setclock(_condattr, CLOCK_MONOTONIC)) != 0) {
5037 if (status == EINVAL) {
5038 warning("Unable to use monotonic clock with relative timed-waits" \
5039 " - changes to the time-of-day clock may have adverse affects");
5040 } else {
5041 fatal(err_msg("pthread_condattr_setclock: %s", strerror(status)));
5042 }
5043 }
5044 }
5045 // else it defaults to CLOCK_REALTIME
5047 pthread_mutex_init(&dl_mutex, NULL);
5049 // If the pagesize of the VM is greater than 8K determine the appropriate
5050 // number of initial guard pages. The user can change this with the
5051 // command line arguments, if needed.
5052 if (vm_page_size() > (int)Linux::vm_default_page_size()) {
5053 StackYellowPages = 1;
5054 StackRedPages = 1;
5055 StackShadowPages = round_to((StackShadowPages*Linux::vm_default_page_size()), vm_page_size()) / vm_page_size();
5056 }
5057 }
5059 // To install functions for atexit system call
5060 extern "C" {
5061 static void perfMemory_exit_helper() {
5062 perfMemory_exit();
5063 }
5064 }
5066 void os::pd_init_container_support() {
5067 OSContainer::init();
5068 }
5070 // this is called _after_ the global arguments have been parsed
5071 jint os::init_2(void)
5072 {
5073 Linux::fast_thread_clock_init();
5075 // Allocate a single page and mark it as readable for safepoint polling
5076 address polling_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
5077 guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
5079 os::set_polling_page( polling_page );
5081 #ifndef PRODUCT
5082 if(Verbose && PrintMiscellaneous)
5083 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
5084 #endif
5086 if (!UseMembar) {
5087 address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
5088 guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
5089 os::set_memory_serialize_page( mem_serialize_page );
5091 #ifndef PRODUCT
5092 if(Verbose && PrintMiscellaneous)
5093 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
5094 #endif
5095 }
5097 // initialize suspend/resume support - must do this before signal_sets_init()
5098 if (SR_initialize() != 0) {
5099 perror("SR_initialize failed");
5100 return JNI_ERR;
5101 }
5103 Linux::signal_sets_init();
5104 Linux::install_signal_handlers();
5106 // Check minimum allowable stack size for thread creation and to initialize
5107 // the java system classes, including StackOverflowError - depends on page
5108 // size. Add a page for compiler2 recursion in main thread.
5109 // Add in 2*BytesPerWord times page size to account for VM stack during
5110 // class initialization depending on 32 or 64 bit VM.
5111 os::Linux::min_stack_allowed = MAX2(os::Linux::min_stack_allowed,
5112 (size_t)(StackYellowPages+StackRedPages+StackShadowPages) * Linux::page_size() +
5113 (2*BytesPerWord COMPILER2_PRESENT(+1)) * Linux::vm_default_page_size());
5115 size_t threadStackSizeInBytes = ThreadStackSize * K;
5116 if (threadStackSizeInBytes != 0 &&
5117 threadStackSizeInBytes < os::Linux::min_stack_allowed) {
5118 tty->print_cr("\nThe stack size specified is too small, "
5119 "Specify at least %dk",
5120 os::Linux::min_stack_allowed/ K);
5121 return JNI_ERR;
5122 }
5124 // Make the stack size a multiple of the page size so that
5125 // the yellow/red zones can be guarded.
5126 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
5127 vm_page_size()));
5129 Linux::capture_initial_stack(JavaThread::stack_size_at_create());
5131 #if defined(IA32)
5132 workaround_expand_exec_shield_cs_limit();
5133 #endif
5135 Linux::libpthread_init();
5136 if (PrintMiscellaneous && (Verbose || WizardMode)) {
5137 tty->print_cr("[HotSpot is running with %s, %s(%s)]\n",
5138 Linux::glibc_version(), Linux::libpthread_version(),
5139 Linux::is_floating_stack() ? "floating stack" : "fixed stack");
5140 }
5142 if (UseNUMA) {
5143 if (!Linux::libnuma_init()) {
5144 UseNUMA = false;
5145 } else {
5146 if ((Linux::numa_max_node() < 1)) {
5147 // There's only one node(they start from 0), disable NUMA.
5148 UseNUMA = false;
5149 }
5150 }
5151 // With SHM and HugeTLBFS large pages we cannot uncommit a page, so there's no way
5152 // we can make the adaptive lgrp chunk resizing work. If the user specified
5153 // both UseNUMA and UseLargePages (or UseSHM/UseHugeTLBFS) on the command line - warn and
5154 // disable adaptive resizing.
5155 if (UseNUMA && UseLargePages && !can_commit_large_page_memory()) {
5156 if (FLAG_IS_DEFAULT(UseNUMA)) {
5157 UseNUMA = false;
5158 } else {
5159 if (FLAG_IS_DEFAULT(UseLargePages) &&
5160 FLAG_IS_DEFAULT(UseSHM) &&
5161 FLAG_IS_DEFAULT(UseHugeTLBFS)) {
5162 UseLargePages = false;
5163 } else {
5164 warning("UseNUMA is not fully compatible with SHM/HugeTLBFS large pages, disabling adaptive resizing");
5165 UseAdaptiveSizePolicy = false;
5166 UseAdaptiveNUMAChunkSizing = false;
5167 }
5168 }
5169 }
5170 if (!UseNUMA && ForceNUMA) {
5171 UseNUMA = true;
5172 }
5173 }
5175 if (MaxFDLimit) {
5176 // set the number of file descriptors to max. print out error
5177 // if getrlimit/setrlimit fails but continue regardless.
5178 struct rlimit nbr_files;
5179 int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
5180 if (status != 0) {
5181 if (PrintMiscellaneous && (Verbose || WizardMode))
5182 perror("os::init_2 getrlimit failed");
5183 } else {
5184 nbr_files.rlim_cur = nbr_files.rlim_max;
5185 status = setrlimit(RLIMIT_NOFILE, &nbr_files);
5186 if (status != 0) {
5187 if (PrintMiscellaneous && (Verbose || WizardMode))
5188 perror("os::init_2 setrlimit failed");
5189 }
5190 }
5191 }
5193 // Initialize lock used to serialize thread creation (see os::create_thread)
5194 Linux::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false));
5196 // at-exit methods are called in the reverse order of their registration.
5197 // atexit functions are called on return from main or as a result of a
5198 // call to exit(3C). There can be only 32 of these functions registered
5199 // and atexit() does not set errno.
5201 if (PerfAllowAtExitRegistration) {
5202 // only register atexit functions if PerfAllowAtExitRegistration is set.
5203 // atexit functions can be delayed until process exit time, which
5204 // can be problematic for embedded VM situations. Embedded VMs should
5205 // call DestroyJavaVM() to assure that VM resources are released.
5207 // note: perfMemory_exit_helper atexit function may be removed in
5208 // the future if the appropriate cleanup code can be added to the
5209 // VM_Exit VMOperation's doit method.
5210 if (atexit(perfMemory_exit_helper) != 0) {
5211 warning("os::init_2 atexit(perfMemory_exit_helper) failed");
5212 }
5213 }
5215 // initialize thread priority policy
5216 prio_init();
5218 return JNI_OK;
5219 }
5221 // Mark the polling page as unreadable
5222 void os::make_polling_page_unreadable(void) {
5223 if( !guard_memory((char*)_polling_page, Linux::page_size()) )
5224 fatal("Could not disable polling page");
5225 };
5227 // Mark the polling page as readable
5228 void os::make_polling_page_readable(void) {
5229 if( !linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) {
5230 fatal("Could not enable polling page");
5231 }
5232 };
5234 static int os_cpu_count(const cpu_set_t* cpus) {
5235 int count = 0;
5236 // only look up to the number of configured processors
5237 for (int i = 0; i < os::processor_count(); i++) {
5238 if (CPU_ISSET(i, cpus)) {
5239 count++;
5240 }
5241 }
5242 return count;
5243 }
5245 // Get the current number of available processors for this process.
5246 // This value can change at any time during a process's lifetime.
5247 // sched_getaffinity gives an accurate answer as it accounts for cpusets.
5248 // If anything goes wrong we fallback to returning the number of online
5249 // processors - which can be greater than the number available to the process.
5250 int os::Linux::active_processor_count() {
5251 cpu_set_t cpus; // can represent at most 1024 (CPU_SETSIZE) processors
5252 int cpus_size = sizeof(cpu_set_t);
5253 int cpu_count = 0;
5255 // pid 0 means the current thread - which we have to assume represents the process
5256 if (sched_getaffinity(0, cpus_size, &cpus) == 0) {
5257 cpu_count = os_cpu_count(&cpus);
5258 if (PrintActiveCpus) {
5259 tty->print_cr("active_processor_count: sched_getaffinity processor count: %d", cpu_count);
5260 }
5261 }
5262 else {
5263 cpu_count = ::sysconf(_SC_NPROCESSORS_ONLN);
5264 warning("sched_getaffinity failed (%s)- using online processor count (%d) "
5265 "which may exceed available processors", strerror(errno), cpu_count);
5266 }
5268 assert(cpu_count > 0 && cpu_count <= os::processor_count(), "sanity check");
5269 return cpu_count;
5270 }
5272 // Determine the active processor count from one of
5273 // three different sources:
5274 //
5275 // 1. User option -XX:ActiveProcessorCount
5276 // 2. kernel os calls (sched_getaffinity or sysconf(_SC_NPROCESSORS_ONLN)
5277 // 3. extracted from cgroup cpu subsystem (shares and quotas)
5278 //
5279 // Option 1, if specified, will always override.
5280 // If the cgroup subsystem is active and configured, we
5281 // will return the min of the cgroup and option 2 results.
5282 // This is required since tools, such as numactl, that
5283 // alter cpu affinity do not update cgroup subsystem
5284 // cpuset configuration files.
5285 int os::active_processor_count() {
5286 // User has overridden the number of active processors
5287 if (ActiveProcessorCount > 0) {
5288 if (PrintActiveCpus) {
5289 tty->print_cr("active_processor_count: "
5290 "active processor count set by user : %d",
5291 ActiveProcessorCount);
5292 }
5293 return ActiveProcessorCount;
5294 }
5296 int active_cpus;
5297 if (OSContainer::is_containerized()) {
5298 active_cpus = OSContainer::active_processor_count();
5299 if (PrintActiveCpus) {
5300 tty->print_cr("active_processor_count: determined by OSContainer: %d",
5301 active_cpus);
5302 }
5303 } else {
5304 active_cpus = os::Linux::active_processor_count();
5305 }
5307 return active_cpus;
5308 }
5310 void os::set_native_thread_name(const char *name) {
5311 // Not yet implemented.
5312 return;
5313 }
5315 bool os::distribute_processes(uint length, uint* distribution) {
5316 // Not yet implemented.
5317 return false;
5318 }
5320 bool os::bind_to_processor(uint processor_id) {
5321 // Not yet implemented.
5322 return false;
5323 }
5325 ///
5327 void os::SuspendedThreadTask::internal_do_task() {
5328 if (do_suspend(_thread->osthread())) {
5329 SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
5330 do_task(context);
5331 do_resume(_thread->osthread());
5332 }
5333 }
5335 class PcFetcher : public os::SuspendedThreadTask {
5336 public:
5337 PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
5338 ExtendedPC result();
5339 protected:
5340 void do_task(const os::SuspendedThreadTaskContext& context);
5341 private:
5342 ExtendedPC _epc;
5343 };
5345 ExtendedPC PcFetcher::result() {
5346 guarantee(is_done(), "task is not done yet.");
5347 return _epc;
5348 }
5350 void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
5351 Thread* thread = context.thread();
5352 OSThread* osthread = thread->osthread();
5353 if (osthread->ucontext() != NULL) {
5354 _epc = os::Linux::ucontext_get_pc((ucontext_t *) context.ucontext());
5355 } else {
5356 // NULL context is unexpected, double-check this is the VMThread
5357 guarantee(thread->is_VM_thread(), "can only be called for VMThread");
5358 }
5359 }
5361 // Suspends the target using the signal mechanism and then grabs the PC before
5362 // resuming the target. Used by the flat-profiler only
5363 ExtendedPC os::get_thread_pc(Thread* thread) {
5364 // Make sure that it is called by the watcher for the VMThread
5365 assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
5366 assert(thread->is_VM_thread(), "Can only be called for VMThread");
5368 PcFetcher fetcher(thread);
5369 fetcher.run();
5370 return fetcher.result();
5371 }
5373 int os::Linux::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
5374 {
5375 if (is_NPTL()) {
5376 return pthread_cond_timedwait(_cond, _mutex, _abstime);
5377 } else {
5378 // 6292965: LinuxThreads pthread_cond_timedwait() resets FPU control
5379 // word back to default 64bit precision if condvar is signaled. Java
5380 // wants 53bit precision. Save and restore current value.
5381 int fpu = get_fpu_control_word();
5382 int status = pthread_cond_timedwait(_cond, _mutex, _abstime);
5383 set_fpu_control_word(fpu);
5384 return status;
5385 }
5386 }
5388 ////////////////////////////////////////////////////////////////////////////////
5389 // debug support
5391 bool os::find(address addr, outputStream* st) {
5392 Dl_info dlinfo;
5393 memset(&dlinfo, 0, sizeof(dlinfo));
5394 if (dladdr(addr, &dlinfo) != 0) {
5395 st->print(PTR_FORMAT ": ", addr);
5396 if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
5397 st->print("%s+%#x", dlinfo.dli_sname,
5398 addr - (intptr_t)dlinfo.dli_saddr);
5399 } else if (dlinfo.dli_fbase != NULL) {
5400 st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
5401 } else {
5402 st->print("<absolute address>");
5403 }
5404 if (dlinfo.dli_fname != NULL) {
5405 st->print(" in %s", dlinfo.dli_fname);
5406 }
5407 if (dlinfo.dli_fbase != NULL) {
5408 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
5409 }
5410 st->cr();
5412 if (Verbose) {
5413 // decode some bytes around the PC
5414 address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
5415 address end = clamp_address_in_page(addr+40, addr, os::vm_page_size());
5416 address lowest = (address) dlinfo.dli_sname;
5417 if (!lowest) lowest = (address) dlinfo.dli_fbase;
5418 if (begin < lowest) begin = lowest;
5419 Dl_info dlinfo2;
5420 if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
5421 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
5422 end = (address) dlinfo2.dli_saddr;
5423 Disassembler::decode(begin, end, st);
5424 }
5425 return true;
5426 }
5427 return false;
5428 }
5430 ////////////////////////////////////////////////////////////////////////////////
5431 // misc
5433 // This does not do anything on Linux. This is basically a hook for being
5434 // able to use structured exception handling (thread-local exception filters)
5435 // on, e.g., Win32.
5436 void
5437 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
5438 JavaCallArguments* args, Thread* thread) {
5439 f(value, method, args, thread);
5440 }
5442 void os::print_statistics() {
5443 }
5445 int os::message_box(const char* title, const char* message) {
5446 int i;
5447 fdStream err(defaultStream::error_fd());
5448 for (i = 0; i < 78; i++) err.print_raw("=");
5449 err.cr();
5450 err.print_raw_cr(title);
5451 for (i = 0; i < 78; i++) err.print_raw("-");
5452 err.cr();
5453 err.print_raw_cr(message);
5454 for (i = 0; i < 78; i++) err.print_raw("=");
5455 err.cr();
5457 char buf[16];
5458 // Prevent process from exiting upon "read error" without consuming all CPU
5459 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
5461 return buf[0] == 'y' || buf[0] == 'Y';
5462 }
5464 int os::stat(const char *path, struct stat *sbuf) {
5465 char pathbuf[MAX_PATH];
5466 if (strlen(path) > MAX_PATH - 1) {
5467 errno = ENAMETOOLONG;
5468 return -1;
5469 }
5470 os::native_path(strcpy(pathbuf, path));
5471 return ::stat(pathbuf, sbuf);
5472 }
5474 bool os::check_heap(bool force) {
5475 return true;
5476 }
5478 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
5479 return ::vsnprintf(buf, count, format, args);
5480 }
5482 // Is a (classpath) directory empty?
5483 bool os::dir_is_empty(const char* path) {
5484 DIR *dir = NULL;
5485 struct dirent *ptr;
5487 dir = opendir(path);
5488 if (dir == NULL) return true;
5490 /* Scan the directory */
5491 bool result = true;
5492 char buf[sizeof(struct dirent) + MAX_PATH];
5493 while (result && (ptr = ::readdir(dir)) != NULL) {
5494 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
5495 result = false;
5496 }
5497 }
5498 closedir(dir);
5499 return result;
5500 }
5502 // This code originates from JDK's sysOpen and open64_w
5503 // from src/solaris/hpi/src/system_md.c
5505 #ifndef O_DELETE
5506 #define O_DELETE 0x10000
5507 #endif
5509 // Open a file. Unlink the file immediately after open returns
5510 // if the specified oflag has the O_DELETE flag set.
5511 // O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
5513 int os::open(const char *path, int oflag, int mode) {
5515 if (strlen(path) > MAX_PATH - 1) {
5516 errno = ENAMETOOLONG;
5517 return -1;
5518 }
5519 int fd;
5520 int o_delete = (oflag & O_DELETE);
5521 oflag = oflag & ~O_DELETE;
5523 fd = ::open64(path, oflag, mode);
5524 if (fd == -1) return -1;
5526 //If the open succeeded, the file might still be a directory
5527 {
5528 struct stat64 buf64;
5529 int ret = ::fstat64(fd, &buf64);
5530 int st_mode = buf64.st_mode;
5532 if (ret != -1) {
5533 if ((st_mode & S_IFMT) == S_IFDIR) {
5534 errno = EISDIR;
5535 ::close(fd);
5536 return -1;
5537 }
5538 } else {
5539 ::close(fd);
5540 return -1;
5541 }
5542 }
5544 /*
5545 * All file descriptors that are opened in the JVM and not
5546 * specifically destined for a subprocess should have the
5547 * close-on-exec flag set. If we don't set it, then careless 3rd
5548 * party native code might fork and exec without closing all
5549 * appropriate file descriptors (e.g. as we do in closeDescriptors in
5550 * UNIXProcess.c), and this in turn might:
5551 *
5552 * - cause end-of-file to fail to be detected on some file
5553 * descriptors, resulting in mysterious hangs, or
5554 *
5555 * - might cause an fopen in the subprocess to fail on a system
5556 * suffering from bug 1085341.
5557 *
5558 * (Yes, the default setting of the close-on-exec flag is a Unix
5559 * design flaw)
5560 *
5561 * See:
5562 * 1085341: 32-bit stdio routines should support file descriptors >255
5563 * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
5564 * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
5565 */
5566 #ifdef FD_CLOEXEC
5567 {
5568 int flags = ::fcntl(fd, F_GETFD);
5569 if (flags != -1)
5570 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
5571 }
5572 #endif
5574 if (o_delete != 0) {
5575 ::unlink(path);
5576 }
5577 return fd;
5578 }
5581 // create binary file, rewriting existing file if required
5582 int os::create_binary_file(const char* path, bool rewrite_existing) {
5583 int oflags = O_WRONLY | O_CREAT;
5584 if (!rewrite_existing) {
5585 oflags |= O_EXCL;
5586 }
5587 return ::open64(path, oflags, S_IREAD | S_IWRITE);
5588 }
5590 // return current position of file pointer
5591 jlong os::current_file_offset(int fd) {
5592 return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
5593 }
5595 // move file pointer to the specified offset
5596 jlong os::seek_to_file_offset(int fd, jlong offset) {
5597 return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
5598 }
5600 // This code originates from JDK's sysAvailable
5601 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
5603 int os::available(int fd, jlong *bytes) {
5604 jlong cur, end;
5605 int mode;
5606 struct stat64 buf64;
5608 if (::fstat64(fd, &buf64) >= 0) {
5609 mode = buf64.st_mode;
5610 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
5611 /*
5612 * XXX: is the following call interruptible? If so, this might
5613 * need to go through the INTERRUPT_IO() wrapper as for other
5614 * blocking, interruptible calls in this file.
5615 */
5616 int n;
5617 if (::ioctl(fd, FIONREAD, &n) >= 0) {
5618 *bytes = n;
5619 return 1;
5620 }
5621 }
5622 }
5623 if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
5624 return 0;
5625 } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
5626 return 0;
5627 } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
5628 return 0;
5629 }
5630 *bytes = end - cur;
5631 return 1;
5632 }
5634 int os::socket_available(int fd, jint *pbytes) {
5635 // Linux doc says EINTR not returned, unlike Solaris
5636 int ret = ::ioctl(fd, FIONREAD, pbytes);
5638 //%% note ioctl can return 0 when successful, JVM_SocketAvailable
5639 // is expected to return 0 on failure and 1 on success to the jdk.
5640 return (ret < 0) ? 0 : 1;
5641 }
5643 // Map a block of memory.
5644 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
5645 char *addr, size_t bytes, bool read_only,
5646 bool allow_exec) {
5647 int prot;
5648 int flags = MAP_PRIVATE;
5650 if (read_only) {
5651 prot = PROT_READ;
5652 } else {
5653 prot = PROT_READ | PROT_WRITE;
5654 }
5656 if (allow_exec) {
5657 prot |= PROT_EXEC;
5658 }
5660 if (addr != NULL) {
5661 flags |= MAP_FIXED;
5662 }
5664 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
5665 fd, file_offset);
5666 if (mapped_address == MAP_FAILED) {
5667 return NULL;
5668 }
5669 return mapped_address;
5670 }
5673 // Remap a block of memory.
5674 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
5675 char *addr, size_t bytes, bool read_only,
5676 bool allow_exec) {
5677 // same as map_memory() on this OS
5678 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
5679 allow_exec);
5680 }
5683 // Unmap a block of memory.
5684 bool os::pd_unmap_memory(char* addr, size_t bytes) {
5685 return munmap(addr, bytes) == 0;
5686 }
5688 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time);
5690 static clockid_t thread_cpu_clockid(Thread* thread) {
5691 pthread_t tid = thread->osthread()->pthread_id();
5692 clockid_t clockid;
5694 // Get thread clockid
5695 int rc = os::Linux::pthread_getcpuclockid(tid, &clockid);
5696 assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code");
5697 return clockid;
5698 }
5700 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
5701 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
5702 // of a thread.
5703 //
5704 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
5705 // the fast estimate available on the platform.
5707 jlong os::current_thread_cpu_time() {
5708 if (os::Linux::supports_fast_thread_cpu_time()) {
5709 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5710 } else {
5711 // return user + sys since the cost is the same
5712 return slow_thread_cpu_time(Thread::current(), true /* user + sys */);
5713 }
5714 }
5716 jlong os::thread_cpu_time(Thread* thread) {
5717 // consistent with what current_thread_cpu_time() returns
5718 if (os::Linux::supports_fast_thread_cpu_time()) {
5719 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
5720 } else {
5721 return slow_thread_cpu_time(thread, true /* user + sys */);
5722 }
5723 }
5725 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
5726 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5727 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5728 } else {
5729 return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time);
5730 }
5731 }
5733 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5734 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5735 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
5736 } else {
5737 return slow_thread_cpu_time(thread, user_sys_cpu_time);
5738 }
5739 }
5741 //
5742 // -1 on error.
5743 //
5745 PRAGMA_DIAG_PUSH
5746 PRAGMA_FORMAT_NONLITERAL_IGNORED
5747 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5748 static bool proc_task_unchecked = true;
5749 static const char *proc_stat_path = "/proc/%d/stat";
5750 pid_t tid = thread->osthread()->thread_id();
5751 char *s;
5752 char stat[2048];
5753 int statlen;
5754 char proc_name[64];
5755 int count;
5756 long sys_time, user_time;
5757 char cdummy;
5758 int idummy;
5759 long ldummy;
5760 FILE *fp;
5762 // The /proc/<tid>/stat aggregates per-process usage on
5763 // new Linux kernels 2.6+ where NPTL is supported.
5764 // The /proc/self/task/<tid>/stat still has the per-thread usage.
5765 // See bug 6328462.
5766 // There possibly can be cases where there is no directory
5767 // /proc/self/task, so we check its availability.
5768 if (proc_task_unchecked && os::Linux::is_NPTL()) {
5769 // This is executed only once
5770 proc_task_unchecked = false;
5771 fp = fopen("/proc/self/task", "r");
5772 if (fp != NULL) {
5773 proc_stat_path = "/proc/self/task/%d/stat";
5774 fclose(fp);
5775 }
5776 }
5778 sprintf(proc_name, proc_stat_path, tid);
5779 fp = fopen(proc_name, "r");
5780 if ( fp == NULL ) return -1;
5781 statlen = fread(stat, 1, 2047, fp);
5782 stat[statlen] = '\0';
5783 fclose(fp);
5785 // Skip pid and the command string. Note that we could be dealing with
5786 // weird command names, e.g. user could decide to rename java launcher
5787 // to "java 1.4.2 :)", then the stat file would look like
5788 // 1234 (java 1.4.2 :)) R ... ...
5789 // We don't really need to know the command string, just find the last
5790 // occurrence of ")" and then start parsing from there. See bug 4726580.
5791 s = strrchr(stat, ')');
5792 if (s == NULL ) return -1;
5794 // Skip blank chars
5795 do s++; while (isspace(*s));
5797 count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu",
5798 &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy,
5799 &ldummy, &ldummy, &ldummy, &ldummy, &ldummy,
5800 &user_time, &sys_time);
5801 if ( count != 13 ) return -1;
5802 if (user_sys_cpu_time) {
5803 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
5804 } else {
5805 return (jlong)user_time * (1000000000 / clock_tics_per_sec);
5806 }
5807 }
5808 PRAGMA_DIAG_POP
5810 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5811 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
5812 info_ptr->may_skip_backward = false; // elapsed time not wall time
5813 info_ptr->may_skip_forward = false; // elapsed time not wall time
5814 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
5815 }
5817 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5818 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits
5819 info_ptr->may_skip_backward = false; // elapsed time not wall time
5820 info_ptr->may_skip_forward = false; // elapsed time not wall time
5821 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned
5822 }
5824 bool os::is_thread_cpu_time_supported() {
5825 return true;
5826 }
5828 // System loadavg support. Returns -1 if load average cannot be obtained.
5829 // Linux doesn't yet have a (official) notion of processor sets,
5830 // so just return the system wide load average.
5831 int os::loadavg(double loadavg[], int nelem) {
5832 return ::getloadavg(loadavg, nelem);
5833 }
5835 void os::pause() {
5836 char filename[MAX_PATH];
5837 if (PauseAtStartupFile && PauseAtStartupFile[0]) {
5838 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
5839 } else {
5840 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
5841 }
5843 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
5844 if (fd != -1) {
5845 struct stat buf;
5846 ::close(fd);
5847 while (::stat(filename, &buf) == 0) {
5848 (void)::poll(NULL, 0, 100);
5849 }
5850 } else {
5851 jio_fprintf(stderr,
5852 "Could not open pause file '%s', continuing immediately.\n", filename);
5853 }
5854 }
5857 // Refer to the comments in os_solaris.cpp park-unpark.
5858 //
5859 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
5860 // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
5861 // For specifics regarding the bug see GLIBC BUGID 261237 :
5862 // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
5863 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
5864 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
5865 // is used. (The simple C test-case provided in the GLIBC bug report manifests the
5866 // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
5867 // and monitorenter when we're using 1-0 locking. All those operations may result in
5868 // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version
5869 // of libpthread avoids the problem, but isn't practical.
5870 //
5871 // Possible remedies:
5872 //
5873 // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work.
5874 // This is palliative and probabilistic, however. If the thread is preempted
5875 // between the call to compute_abstime() and pthread_cond_timedwait(), more
5876 // than the minimum period may have passed, and the abstime may be stale (in the
5877 // past) resultin in a hang. Using this technique reduces the odds of a hang
5878 // but the JVM is still vulnerable, particularly on heavily loaded systems.
5879 //
5880 // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
5881 // of the usual flag-condvar-mutex idiom. The write side of the pipe is set
5882 // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
5883 // reduces to poll()+read(). This works well, but consumes 2 FDs per extant
5884 // thread.
5885 //
5886 // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread
5887 // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing
5888 // a timeout request to the chron thread and then blocking via pthread_cond_wait().
5889 // This also works well. In fact it avoids kernel-level scalability impediments
5890 // on certain platforms that don't handle lots of active pthread_cond_timedwait()
5891 // timers in a graceful fashion.
5892 //
5893 // 4. When the abstime value is in the past it appears that control returns
5894 // correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
5895 // Subsequent timedwait/wait calls may hang indefinitely. Given that, we
5896 // can avoid the problem by reinitializing the condvar -- by cond_destroy()
5897 // followed by cond_init() -- after all calls to pthread_cond_timedwait().
5898 // It may be possible to avoid reinitialization by checking the return
5899 // value from pthread_cond_timedwait(). In addition to reinitializing the
5900 // condvar we must establish the invariant that cond_signal() is only called
5901 // within critical sections protected by the adjunct mutex. This prevents
5902 // cond_signal() from "seeing" a condvar that's in the midst of being
5903 // reinitialized or that is corrupt. Sadly, this invariant obviates the
5904 // desirable signal-after-unlock optimization that avoids futile context switching.
5905 //
5906 // I'm also concerned that some versions of NTPL might allocate an auxilliary
5907 // structure when a condvar is used or initialized. cond_destroy() would
5908 // release the helper structure. Our reinitialize-after-timedwait fix
5909 // put excessive stress on malloc/free and locks protecting the c-heap.
5910 //
5911 // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag.
5912 // It may be possible to refine (4) by checking the kernel and NTPL verisons
5913 // and only enabling the work-around for vulnerable environments.
5915 // utility to compute the abstime argument to timedwait:
5916 // millis is the relative timeout time
5917 // abstime will be the absolute timeout time
5918 // TODO: replace compute_abstime() with unpackTime()
5920 static struct timespec* compute_abstime(timespec* abstime, jlong millis) {
5921 if (millis < 0) millis = 0;
5923 jlong seconds = millis / 1000;
5924 millis %= 1000;
5925 if (seconds > 50000000) { // see man cond_timedwait(3T)
5926 seconds = 50000000;
5927 }
5929 if (os::Linux::supports_monotonic_clock()) {
5930 struct timespec now;
5931 int status = os::Linux::clock_gettime(CLOCK_MONOTONIC, &now);
5932 assert_status(status == 0, status, "clock_gettime");
5933 abstime->tv_sec = now.tv_sec + seconds;
5934 long nanos = now.tv_nsec + millis * NANOSECS_PER_MILLISEC;
5935 if (nanos >= NANOSECS_PER_SEC) {
5936 abstime->tv_sec += 1;
5937 nanos -= NANOSECS_PER_SEC;
5938 }
5939 abstime->tv_nsec = nanos;
5940 } else {
5941 struct timeval now;
5942 int status = gettimeofday(&now, NULL);
5943 assert(status == 0, "gettimeofday");
5944 abstime->tv_sec = now.tv_sec + seconds;
5945 long usec = now.tv_usec + millis * 1000;
5946 if (usec >= 1000000) {
5947 abstime->tv_sec += 1;
5948 usec -= 1000000;
5949 }
5950 abstime->tv_nsec = usec * 1000;
5951 }
5952 return abstime;
5953 }
5956 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
5957 // Conceptually TryPark() should be equivalent to park(0).
5959 int os::PlatformEvent::TryPark() {
5960 for (;;) {
5961 const int v = _Event ;
5962 guarantee ((v == 0) || (v == 1), "invariant") ;
5963 if (Atomic::cmpxchg (0, &_Event, v) == v) return v ;
5964 }
5965 }
5967 void os::PlatformEvent::park() { // AKA "down()"
5968 // Invariant: Only the thread associated with the Event/PlatformEvent
5969 // may call park().
5970 // TODO: assert that _Assoc != NULL or _Assoc == Self
5971 int v ;
5972 for (;;) {
5973 v = _Event ;
5974 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
5975 }
5976 guarantee (v >= 0, "invariant") ;
5977 if (v == 0) {
5978 // Do this the hard way by blocking ...
5979 int status = pthread_mutex_lock(_mutex);
5980 assert_status(status == 0, status, "mutex_lock");
5981 guarantee (_nParked == 0, "invariant") ;
5982 ++ _nParked ;
5983 while (_Event < 0) {
5984 status = pthread_cond_wait(_cond, _mutex);
5985 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
5986 // Treat this the same as if the wait was interrupted
5987 if (status == ETIME) { status = EINTR; }
5988 assert_status(status == 0 || status == EINTR, status, "cond_wait");
5989 }
5990 -- _nParked ;
5992 _Event = 0 ;
5993 status = pthread_mutex_unlock(_mutex);
5994 assert_status(status == 0, status, "mutex_unlock");
5995 // Paranoia to ensure our locked and lock-free paths interact
5996 // correctly with each other.
5997 OrderAccess::fence();
5998 }
5999 guarantee (_Event >= 0, "invariant") ;
6000 }
6002 int os::PlatformEvent::park(jlong millis) {
6003 guarantee (_nParked == 0, "invariant") ;
6005 int v ;
6006 for (;;) {
6007 v = _Event ;
6008 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
6009 }
6010 guarantee (v >= 0, "invariant") ;
6011 if (v != 0) return OS_OK ;
6013 // We do this the hard way, by blocking the thread.
6014 // Consider enforcing a minimum timeout value.
6015 struct timespec abst;
6016 compute_abstime(&abst, millis);
6018 int ret = OS_TIMEOUT;
6019 int status = pthread_mutex_lock(_mutex);
6020 assert_status(status == 0, status, "mutex_lock");
6021 guarantee (_nParked == 0, "invariant") ;
6022 ++_nParked ;
6024 // Object.wait(timo) will return because of
6025 // (a) notification
6026 // (b) timeout
6027 // (c) thread.interrupt
6028 //
6029 // Thread.interrupt and object.notify{All} both call Event::set.
6030 // That is, we treat thread.interrupt as a special case of notification.
6031 // The underlying Solaris implementation, cond_timedwait, admits
6032 // spurious/premature wakeups, but the JLS/JVM spec prevents the
6033 // JVM from making those visible to Java code. As such, we must
6034 // filter out spurious wakeups. We assume all ETIME returns are valid.
6035 //
6036 // TODO: properly differentiate simultaneous notify+interrupt.
6037 // In that case, we should propagate the notify to another waiter.
6039 while (_Event < 0) {
6040 status = os::Linux::safe_cond_timedwait(_cond, _mutex, &abst);
6041 if (status != 0 && WorkAroundNPTLTimedWaitHang) {
6042 pthread_cond_destroy (_cond);
6043 pthread_cond_init (_cond, os::Linux::condAttr()) ;
6044 }
6045 assert_status(status == 0 || status == EINTR ||
6046 status == ETIME || status == ETIMEDOUT,
6047 status, "cond_timedwait");
6048 if (!FilterSpuriousWakeups) break ; // previous semantics
6049 if (status == ETIME || status == ETIMEDOUT) break ;
6050 // We consume and ignore EINTR and spurious wakeups.
6051 }
6052 --_nParked ;
6053 if (_Event >= 0) {
6054 ret = OS_OK;
6055 }
6056 _Event = 0 ;
6057 status = pthread_mutex_unlock(_mutex);
6058 assert_status(status == 0, status, "mutex_unlock");
6059 assert (_nParked == 0, "invariant") ;
6060 // Paranoia to ensure our locked and lock-free paths interact
6061 // correctly with each other.
6062 OrderAccess::fence();
6063 return ret;
6064 }
6066 void os::PlatformEvent::unpark() {
6067 // Transitions for _Event:
6068 // 0 :=> 1
6069 // 1 :=> 1
6070 // -1 :=> either 0 or 1; must signal target thread
6071 // That is, we can safely transition _Event from -1 to either
6072 // 0 or 1. Forcing 1 is slightly more efficient for back-to-back
6073 // unpark() calls.
6074 // See also: "Semaphores in Plan 9" by Mullender & Cox
6075 //
6076 // Note: Forcing a transition from "-1" to "1" on an unpark() means
6077 // that it will take two back-to-back park() calls for the owning
6078 // thread to block. This has the benefit of forcing a spurious return
6079 // from the first park() call after an unpark() call which will help
6080 // shake out uses of park() and unpark() without condition variables.
6082 if (Atomic::xchg(1, &_Event) >= 0) return;
6084 // Wait for the thread associated with the event to vacate
6085 int status = pthread_mutex_lock(_mutex);
6086 assert_status(status == 0, status, "mutex_lock");
6087 int AnyWaiters = _nParked;
6088 assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
6089 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
6090 AnyWaiters = 0;
6091 pthread_cond_signal(_cond);
6092 }
6093 status = pthread_mutex_unlock(_mutex);
6094 assert_status(status == 0, status, "mutex_unlock");
6095 if (AnyWaiters != 0) {
6096 status = pthread_cond_signal(_cond);
6097 assert_status(status == 0, status, "cond_signal");
6098 }
6100 // Note that we signal() _after dropping the lock for "immortal" Events.
6101 // This is safe and avoids a common class of futile wakeups. In rare
6102 // circumstances this can cause a thread to return prematurely from
6103 // cond_{timed}wait() but the spurious wakeup is benign and the victim will
6104 // simply re-test the condition and re-park itself.
6105 }
6108 // JSR166
6109 // -------------------------------------------------------
6111 /*
6112 * The solaris and linux implementations of park/unpark are fairly
6113 * conservative for now, but can be improved. They currently use a
6114 * mutex/condvar pair, plus a a count.
6115 * Park decrements count if > 0, else does a condvar wait. Unpark
6116 * sets count to 1 and signals condvar. Only one thread ever waits
6117 * on the condvar. Contention seen when trying to park implies that someone
6118 * is unparking you, so don't wait. And spurious returns are fine, so there
6119 * is no need to track notifications.
6120 */
6122 /*
6123 * This code is common to linux and solaris and will be moved to a
6124 * common place in dolphin.
6125 *
6126 * The passed in time value is either a relative time in nanoseconds
6127 * or an absolute time in milliseconds. Either way it has to be unpacked
6128 * into suitable seconds and nanoseconds components and stored in the
6129 * given timespec structure.
6130 * Given time is a 64-bit value and the time_t used in the timespec is only
6131 * a signed-32-bit value (except on 64-bit Linux) we have to watch for
6132 * overflow if times way in the future are given. Further on Solaris versions
6133 * prior to 10 there is a restriction (see cond_timedwait) that the specified
6134 * number of seconds, in abstime, is less than current_time + 100,000,000.
6135 * As it will be 28 years before "now + 100000000" will overflow we can
6136 * ignore overflow and just impose a hard-limit on seconds using the value
6137 * of "now + 100,000,000". This places a limit on the timeout of about 3.17
6138 * years from "now".
6139 */
6141 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
6142 assert (time > 0, "convertTime");
6143 time_t max_secs = 0;
6145 if (!os::Linux::supports_monotonic_clock() || isAbsolute) {
6146 struct timeval now;
6147 int status = gettimeofday(&now, NULL);
6148 assert(status == 0, "gettimeofday");
6150 max_secs = now.tv_sec + MAX_SECS;
6152 if (isAbsolute) {
6153 jlong secs = time / 1000;
6154 if (secs > max_secs) {
6155 absTime->tv_sec = max_secs;
6156 } else {
6157 absTime->tv_sec = secs;
6158 }
6159 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
6160 } else {
6161 jlong secs = time / NANOSECS_PER_SEC;
6162 if (secs >= MAX_SECS) {
6163 absTime->tv_sec = max_secs;
6164 absTime->tv_nsec = 0;
6165 } else {
6166 absTime->tv_sec = now.tv_sec + secs;
6167 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
6168 if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
6169 absTime->tv_nsec -= NANOSECS_PER_SEC;
6170 ++absTime->tv_sec; // note: this must be <= max_secs
6171 }
6172 }
6173 }
6174 } else {
6175 // must be relative using monotonic clock
6176 struct timespec now;
6177 int status = os::Linux::clock_gettime(CLOCK_MONOTONIC, &now);
6178 assert_status(status == 0, status, "clock_gettime");
6179 max_secs = now.tv_sec + MAX_SECS;
6180 jlong secs = time / NANOSECS_PER_SEC;
6181 if (secs >= MAX_SECS) {
6182 absTime->tv_sec = max_secs;
6183 absTime->tv_nsec = 0;
6184 } else {
6185 absTime->tv_sec = now.tv_sec + secs;
6186 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_nsec;
6187 if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
6188 absTime->tv_nsec -= NANOSECS_PER_SEC;
6189 ++absTime->tv_sec; // note: this must be <= max_secs
6190 }
6191 }
6192 }
6193 assert(absTime->tv_sec >= 0, "tv_sec < 0");
6194 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
6195 assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
6196 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
6197 }
6199 void Parker::park(bool isAbsolute, jlong time) {
6200 // Ideally we'd do something useful while spinning, such
6201 // as calling unpackTime().
6203 // Optional fast-path check:
6204 // Return immediately if a permit is available.
6205 // We depend on Atomic::xchg() having full barrier semantics
6206 // since we are doing a lock-free update to _counter.
6207 if (Atomic::xchg(0, &_counter) > 0) return;
6209 Thread* thread = Thread::current();
6210 assert(thread->is_Java_thread(), "Must be JavaThread");
6211 JavaThread *jt = (JavaThread *)thread;
6213 // Optional optimization -- avoid state transitions if there's an interrupt pending.
6214 // Check interrupt before trying to wait
6215 if (Thread::is_interrupted(thread, false)) {
6216 return;
6217 }
6219 // Next, demultiplex/decode time arguments
6220 timespec absTime;
6221 if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
6222 return;
6223 }
6224 if (time > 0) {
6225 unpackTime(&absTime, isAbsolute, time);
6226 }
6229 // Enter safepoint region
6230 // Beware of deadlocks such as 6317397.
6231 // The per-thread Parker:: mutex is a classic leaf-lock.
6232 // In particular a thread must never block on the Threads_lock while
6233 // holding the Parker:: mutex. If safepoints are pending both the
6234 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
6235 ThreadBlockInVM tbivm(jt);
6237 // Don't wait if cannot get lock since interference arises from
6238 // unblocking. Also. check interrupt before trying wait
6239 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
6240 return;
6241 }
6243 int status ;
6244 if (_counter > 0) { // no wait needed
6245 _counter = 0;
6246 status = pthread_mutex_unlock(_mutex);
6247 assert (status == 0, "invariant") ;
6248 // Paranoia to ensure our locked and lock-free paths interact
6249 // correctly with each other and Java-level accesses.
6250 OrderAccess::fence();
6251 return;
6252 }
6254 #ifdef ASSERT
6255 // Don't catch signals while blocked; let the running threads have the signals.
6256 // (This allows a debugger to break into the running thread.)
6257 sigset_t oldsigs;
6258 sigset_t* allowdebug_blocked = os::Linux::allowdebug_blocked_signals();
6259 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
6260 #endif
6262 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
6263 jt->set_suspend_equivalent();
6264 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
6266 assert(_cur_index == -1, "invariant");
6267 if (time == 0) {
6268 _cur_index = REL_INDEX; // arbitrary choice when not timed
6269 status = pthread_cond_wait (&_cond[_cur_index], _mutex) ;
6270 } else {
6271 _cur_index = isAbsolute ? ABS_INDEX : REL_INDEX;
6272 status = os::Linux::safe_cond_timedwait (&_cond[_cur_index], _mutex, &absTime) ;
6273 if (status != 0 && WorkAroundNPTLTimedWaitHang) {
6274 pthread_cond_destroy (&_cond[_cur_index]) ;
6275 pthread_cond_init (&_cond[_cur_index], isAbsolute ? NULL : os::Linux::condAttr());
6276 }
6277 }
6278 _cur_index = -1;
6279 assert_status(status == 0 || status == EINTR ||
6280 status == ETIME || status == ETIMEDOUT,
6281 status, "cond_timedwait");
6283 #ifdef ASSERT
6284 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
6285 #endif
6287 _counter = 0 ;
6288 status = pthread_mutex_unlock(_mutex) ;
6289 assert_status(status == 0, status, "invariant") ;
6290 // Paranoia to ensure our locked and lock-free paths interact
6291 // correctly with each other and Java-level accesses.
6292 OrderAccess::fence();
6294 // If externally suspended while waiting, re-suspend
6295 if (jt->handle_special_suspend_equivalent_condition()) {
6296 jt->java_suspend_self();
6297 }
6298 }
6300 void Parker::unpark() {
6301 int s, status ;
6302 status = pthread_mutex_lock(_mutex);
6303 assert (status == 0, "invariant") ;
6304 s = _counter;
6305 _counter = 1;
6306 if (s < 1) {
6307 // thread might be parked
6308 if (_cur_index != -1) {
6309 // thread is definitely parked
6310 if (WorkAroundNPTLTimedWaitHang) {
6311 status = pthread_cond_signal (&_cond[_cur_index]);
6312 assert (status == 0, "invariant");
6313 status = pthread_mutex_unlock(_mutex);
6314 assert (status == 0, "invariant");
6315 } else {
6316 // must capture correct index before unlocking
6317 int index = _cur_index;
6318 status = pthread_mutex_unlock(_mutex);
6319 assert (status == 0, "invariant");
6320 status = pthread_cond_signal (&_cond[index]);
6321 assert (status == 0, "invariant");
6322 }
6323 } else {
6324 pthread_mutex_unlock(_mutex);
6325 assert (status == 0, "invariant") ;
6326 }
6327 } else {
6328 pthread_mutex_unlock(_mutex);
6329 assert (status == 0, "invariant") ;
6330 }
6331 }
6334 extern char** environ;
6336 // Run the specified command in a separate process. Return its exit value,
6337 // or -1 on failure (e.g. can't fork a new process).
6338 // Unlike system(), this function can be called from signal handler. It
6339 // doesn't block SIGINT et al.
6340 int os::fork_and_exec(char* cmd) {
6341 const char * argv[4] = {"sh", "-c", cmd, NULL};
6343 pid_t pid = fork();
6345 if (pid < 0) {
6346 // fork failed
6347 return -1;
6349 } else if (pid == 0) {
6350 // child process
6352 execve("/bin/sh", (char* const*)argv, environ);
6354 // execve failed
6355 _exit(-1);
6357 } else {
6358 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
6359 // care about the actual exit code, for now.
6361 int status;
6363 // Wait for the child process to exit. This returns immediately if
6364 // the child has already exited. */
6365 while (waitpid(pid, &status, 0) < 0) {
6366 switch (errno) {
6367 case ECHILD: return 0;
6368 case EINTR: break;
6369 default: return -1;
6370 }
6371 }
6373 if (WIFEXITED(status)) {
6374 // The child exited normally; get its exit code.
6375 return WEXITSTATUS(status);
6376 } else if (WIFSIGNALED(status)) {
6377 // The child exited because of a signal
6378 // The best value to return is 0x80 + signal number,
6379 // because that is what all Unix shells do, and because
6380 // it allows callers to distinguish between process exit and
6381 // process death by signal.
6382 return 0x80 + WTERMSIG(status);
6383 } else {
6384 // Unknown exit code; pass it through
6385 return status;
6386 }
6387 }
6388 }
6390 // is_headless_jre()
6391 //
6392 // Test for the existence of xawt/libmawt.so or libawt_xawt.so
6393 // in order to report if we are running in a headless jre
6394 //
6395 // Since JDK8 xawt/libmawt.so was moved into the same directory
6396 // as libawt.so, and renamed libawt_xawt.so
6397 //
6398 bool os::is_headless_jre() {
6399 struct stat statbuf;
6400 char buf[MAXPATHLEN];
6401 char libmawtpath[MAXPATHLEN];
6402 const char *xawtstr = "/xawt/libmawt.so";
6403 const char *new_xawtstr = "/libawt_xawt.so";
6404 char *p;
6406 // Get path to libjvm.so
6407 os::jvm_path(buf, sizeof(buf));
6409 // Get rid of libjvm.so
6410 p = strrchr(buf, '/');
6411 if (p == NULL) return false;
6412 else *p = '\0';
6414 // Get rid of client or server
6415 p = strrchr(buf, '/');
6416 if (p == NULL) return false;
6417 else *p = '\0';
6419 // check xawt/libmawt.so
6420 strcpy(libmawtpath, buf);
6421 strcat(libmawtpath, xawtstr);
6422 if (::stat(libmawtpath, &statbuf) == 0) return false;
6424 // check libawt_xawt.so
6425 strcpy(libmawtpath, buf);
6426 strcat(libmawtpath, new_xawtstr);
6427 if (::stat(libmawtpath, &statbuf) == 0) return false;
6429 return true;
6430 }
6432 // Get the default path to the core file
6433 // Returns the length of the string
6434 int os::get_core_path(char* buffer, size_t bufferSize) {
6435 const char* p = get_current_directory(buffer, bufferSize);
6437 if (p == NULL) {
6438 assert(p != NULL, "failed to get current directory");
6439 return 0;
6440 }
6442 return strlen(buffer);
6443 }
6445 /////////////// Unit tests ///////////////
6447 #ifndef PRODUCT
6449 #define test_log(...) \
6450 do {\
6451 if (VerboseInternalVMTests) { \
6452 tty->print_cr(__VA_ARGS__); \
6453 tty->flush(); \
6454 }\
6455 } while (false)
6457 class TestReserveMemorySpecial : AllStatic {
6458 public:
6459 static void small_page_write(void* addr, size_t size) {
6460 size_t page_size = os::vm_page_size();
6462 char* end = (char*)addr + size;
6463 for (char* p = (char*)addr; p < end; p += page_size) {
6464 *p = 1;
6465 }
6466 }
6468 static void test_reserve_memory_special_huge_tlbfs_only(size_t size) {
6469 if (!UseHugeTLBFS) {
6470 return;
6471 }
6473 test_log("test_reserve_memory_special_huge_tlbfs_only(" SIZE_FORMAT ")", size);
6475 char* addr = os::Linux::reserve_memory_special_huge_tlbfs_only(size, NULL, false);
6477 if (addr != NULL) {
6478 small_page_write(addr, size);
6480 os::Linux::release_memory_special_huge_tlbfs(addr, size);
6481 }
6482 }
6484 static void test_reserve_memory_special_huge_tlbfs_only() {
6485 if (!UseHugeTLBFS) {
6486 return;
6487 }
6489 size_t lp = os::large_page_size();
6491 for (size_t size = lp; size <= lp * 10; size += lp) {
6492 test_reserve_memory_special_huge_tlbfs_only(size);
6493 }
6494 }
6496 static void test_reserve_memory_special_huge_tlbfs_mixed() {
6497 size_t lp = os::large_page_size();
6498 size_t ag = os::vm_allocation_granularity();
6500 // sizes to test
6501 const size_t sizes[] = {
6502 lp, lp + ag, lp + lp / 2, lp * 2,
6503 lp * 2 + ag, lp * 2 - ag, lp * 2 + lp / 2,
6504 lp * 10, lp * 10 + lp / 2
6505 };
6506 const int num_sizes = sizeof(sizes) / sizeof(size_t);
6508 // For each size/alignment combination, we test three scenarios:
6509 // 1) with req_addr == NULL
6510 // 2) with a non-null req_addr at which we expect to successfully allocate
6511 // 3) with a non-null req_addr which contains a pre-existing mapping, at which we
6512 // expect the allocation to either fail or to ignore req_addr
6514 // Pre-allocate two areas; they shall be as large as the largest allocation
6515 // and aligned to the largest alignment we will be testing.
6516 const size_t mapping_size = sizes[num_sizes - 1] * 2;
6517 char* const mapping1 = (char*) ::mmap(NULL, mapping_size,
6518 PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
6519 -1, 0);
6520 assert(mapping1 != MAP_FAILED, "should work");
6522 char* const mapping2 = (char*) ::mmap(NULL, mapping_size,
6523 PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
6524 -1, 0);
6525 assert(mapping2 != MAP_FAILED, "should work");
6527 // Unmap the first mapping, but leave the second mapping intact: the first
6528 // mapping will serve as a value for a "good" req_addr (case 2). The second
6529 // mapping, still intact, as "bad" req_addr (case 3).
6530 ::munmap(mapping1, mapping_size);
6532 // Case 1
6533 test_log("%s, req_addr NULL:", __FUNCTION__);
6534 test_log("size align result");
6536 for (int i = 0; i < num_sizes; i++) {
6537 const size_t size = sizes[i];
6538 for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
6539 char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, NULL, false);
6540 test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " -> " PTR_FORMAT " %s",
6541 size, alignment, p, (p != NULL ? "" : "(failed)"));
6542 if (p != NULL) {
6543 assert(is_ptr_aligned(p, alignment), "must be");
6544 small_page_write(p, size);
6545 os::Linux::release_memory_special_huge_tlbfs(p, size);
6546 }
6547 }
6548 }
6550 // Case 2
6551 test_log("%s, req_addr non-NULL:", __FUNCTION__);
6552 test_log("size align req_addr result");
6554 for (int i = 0; i < num_sizes; i++) {
6555 const size_t size = sizes[i];
6556 for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
6557 char* const req_addr = (char*) align_ptr_up(mapping1, alignment);
6558 char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, req_addr, false);
6559 test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " " PTR_FORMAT " -> " PTR_FORMAT " %s",
6560 size, alignment, req_addr, p,
6561 ((p != NULL ? (p == req_addr ? "(exact match)" : "") : "(failed)")));
6562 if (p != NULL) {
6563 assert(p == req_addr, "must be");
6564 small_page_write(p, size);
6565 os::Linux::release_memory_special_huge_tlbfs(p, size);
6566 }
6567 }
6568 }
6570 // Case 3
6571 test_log("%s, req_addr non-NULL with preexisting mapping:", __FUNCTION__);
6572 test_log("size align req_addr result");
6574 for (int i = 0; i < num_sizes; i++) {
6575 const size_t size = sizes[i];
6576 for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
6577 char* const req_addr = (char*) align_ptr_up(mapping2, alignment);
6578 char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, req_addr, false);
6579 test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " " PTR_FORMAT " -> " PTR_FORMAT " %s",
6580 size, alignment, req_addr, p,
6581 ((p != NULL ? "" : "(failed)")));
6582 // as the area around req_addr contains already existing mappings, the API should always
6583 // return NULL (as per contract, it cannot return another address)
6584 assert(p == NULL, "must be");
6585 }
6586 }
6588 ::munmap(mapping2, mapping_size);
6590 }
6592 static void test_reserve_memory_special_huge_tlbfs() {
6593 if (!UseHugeTLBFS) {
6594 return;
6595 }
6597 test_reserve_memory_special_huge_tlbfs_only();
6598 test_reserve_memory_special_huge_tlbfs_mixed();
6599 }
6601 static void test_reserve_memory_special_shm(size_t size, size_t alignment) {
6602 if (!UseSHM) {
6603 return;
6604 }
6606 test_log("test_reserve_memory_special_shm(" SIZE_FORMAT ", " SIZE_FORMAT ")", size, alignment);
6608 char* addr = os::Linux::reserve_memory_special_shm(size, alignment, NULL, false);
6610 if (addr != NULL) {
6611 assert(is_ptr_aligned(addr, alignment), "Check");
6612 assert(is_ptr_aligned(addr, os::large_page_size()), "Check");
6614 small_page_write(addr, size);
6616 os::Linux::release_memory_special_shm(addr, size);
6617 }
6618 }
6620 static void test_reserve_memory_special_shm() {
6621 size_t lp = os::large_page_size();
6622 size_t ag = os::vm_allocation_granularity();
6624 for (size_t size = ag; size < lp * 3; size += ag) {
6625 for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
6626 test_reserve_memory_special_shm(size, alignment);
6627 }
6628 }
6629 }
6631 static void test() {
6632 test_reserve_memory_special_huge_tlbfs();
6633 test_reserve_memory_special_shm();
6634 }
6635 };
6637 void TestReserveMemorySpecial_test() {
6638 TestReserveMemorySpecial::test();
6639 }
6641 #endif