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