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