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