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