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