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