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