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