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