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