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