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