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