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