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_share_linux.hpp"
  42 #include "osContainer_linux.hpp"
  43 #include "prims/jniFastGetField.hpp"
  44 #include "prims/jvm_misc.hpp"
  45 #include "runtime/arguments.hpp"
  46 #include "runtime/atomic.hpp"
  47 #include "runtime/extendedPC.hpp"
  48 #include "runtime/globals.hpp"
  49 #include "runtime/interfaceSupport.inline.hpp"
  50 #include "runtime/init.hpp"
  51 #include "runtime/java.hpp"
  52 #include "runtime/javaCalls.hpp"
  53 #include "runtime/mutexLocker.hpp"
  54 #include "runtime/objectMonitor.hpp"
  55 #include "runtime/orderAccess.hpp"
  56 #include "runtime/osThread.hpp"
  57 #include "runtime/perfMemory.hpp"
  58 #include "runtime/sharedRuntime.hpp"
  59 #include "runtime/statSampler.hpp"
  60 #include "runtime/stubRoutines.hpp"
  61 #include "runtime/thread.inline.hpp"
  62 #include "runtime/threadCritical.hpp"
  63 #include "runtime/threadSMR.hpp"
  64 #include "runtime/timer.hpp"
  65 #include "semaphore_posix.hpp"
  66 #include "services/attachListener.hpp"
  67 #include "services/memTracker.hpp"
  68 #include "services/runtimeService.hpp"
  69 #include "utilities/align.hpp"
  70 #include "utilities/decoder.hpp"
  71 #include "utilities/defaultStream.hpp"
  72 #include "utilities/events.hpp"
  73 #include "utilities/elfFile.hpp"
  74 #include "utilities/growableArray.hpp"
  75 #include "utilities/macros.hpp"
  76 #include "utilities/vmError.hpp"
  77 
  78 // put OS-includes here
  79 # include <sys/types.h>
  80 # include <sys/mman.h>
  81 # include <sys/stat.h>
  82 # include <sys/select.h>
  83 # include <pthread.h>
  84 # include <signal.h>
  85 # include <errno.h>
  86 # include <dlfcn.h>
  87 # include <stdio.h>
  88 # include <unistd.h>
  89 # include <sys/resource.h>
  90 # include <pthread.h>
  91 # include <sys/stat.h>
  92 # include <sys/time.h>
  93 # include <sys/times.h>
  94 # include <sys/utsname.h>
  95 # include <sys/socket.h>
  96 # include <sys/wait.h>
  97 # include <pwd.h>
  98 # include <poll.h>
  99 # include <fcntl.h>
 100 # include <string.h>
 101 # include <syscall.h>
 102 # include <sys/sysinfo.h>
 103 # include <gnu/libc-version.h>
 104 # include <sys/ipc.h>
 105 # include <sys/shm.h>
 106 # include <link.h>
 107 # include <stdint.h>
 108 # include <inttypes.h>
 109 # include <sys/ioctl.h>
 110 
 111 #ifndef _GNU_SOURCE
 112   #define _GNU_SOURCE
 113   #include <sched.h>
 114   #undef _GNU_SOURCE
 115 #else
 116   #include <sched.h>
 117 #endif
 118 
 119 // if RUSAGE_THREAD for getrusage() has not been defined, do it here. The code calling
 120 // getrusage() is prepared to handle the associated failure.
 121 #ifndef RUSAGE_THREAD
 122   #define RUSAGE_THREAD   (1)               /* only the calling thread */
 123 #endif
 124 
 125 #define MAX_PATH    (2 * K)
 126 
 127 #define MAX_SECS 100000000
 128 
 129 // for timer info max values which include all bits
 130 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
 131 
 132 enum CoredumpFilterBit {
 133   FILE_BACKED_PVT_BIT = 1 << 2,

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



5139 
5140   return JNI_OK;
5141 }
5142 
5143 // Mark the polling page as unreadable
5144 void os::make_polling_page_unreadable(void) {
5145   if (!guard_memory((char*)_polling_page, Linux::page_size())) {
5146     fatal("Could not disable polling page");
5147   }
5148 }
5149 
5150 // Mark the polling page as readable
5151 void os::make_polling_page_readable(void) {
5152   if (!linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) {
5153     fatal("Could not enable polling page");
5154   }
5155 }
5156 
5157 // older glibc versions don't have this macro (which expands to
5158 // an optimized bit-counting function) so we have to roll our own
5159 #ifndef CPU_COUNT
5160 
5161 static int _cpu_count(const cpu_set_t* cpus) {
5162   int count = 0;
5163   // only look up to the number of configured processors
5164   for (int i = 0; i < os::processor_count(); i++) {
5165     if (CPU_ISSET(i, cpus)) {
5166       count++;
5167     }
5168   }
5169   return count;
5170 }
5171 
5172 #define CPU_COUNT(cpus) _cpu_count(cpus)
5173 
5174 #endif // CPU_COUNT
5175 
5176 // Get the current number of available processors for this process.
5177 // This value can change at any time during a process's lifetime.
5178 // sched_getaffinity gives an accurate answer as it accounts for cpusets.
5179 // If it appears there may be more than 1024 processors then we do a
5180 // dynamic check - see 6515172 for details.
5181 // If anything goes wrong we fallback to returning the number of online
5182 // processors - which can be greater than the number available to the process.
5183 int os::Linux::active_processor_count() {
5184   cpu_set_t cpus;  // can represent at most 1024 (CPU_SETSIZE) processors
5185   cpu_set_t* cpus_p = &cpus;
5186   int cpus_size = sizeof(cpu_set_t);
5187 
5188   int configured_cpus = os::processor_count();  // upper bound on available cpus
5189   int cpu_count = 0;
5190 
5191 // old build platforms may not support dynamic cpu sets
5192 #ifdef CPU_ALLOC
5193 
5194   // To enable easy testing of the dynamic path on different platforms we
5195   // introduce a diagnostic flag: UseCpuAllocPath
5196   if (configured_cpus >= CPU_SETSIZE || UseCpuAllocPath) {
5197     // kernel may use a mask bigger than cpu_set_t
5198     log_trace(os)("active_processor_count: using dynamic path %s"
5199                   "- configured processors: %d",
5200                   UseCpuAllocPath ? "(forced) " : "",
5201                   configured_cpus);
5202     cpus_p = CPU_ALLOC(configured_cpus);
5203     if (cpus_p != NULL) {
5204       cpus_size = CPU_ALLOC_SIZE(configured_cpus);
5205       // zero it just to be safe
5206       CPU_ZERO_S(cpus_size, cpus_p);
5207     }
5208     else {
5209        // failed to allocate so fallback to online cpus
5210        int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
5211        log_trace(os)("active_processor_count: "
5212                      "CPU_ALLOC failed (%s) - using "
5213                      "online processor count: %d",
5214                      os::strerror(errno), online_cpus);
5215        return online_cpus;
5216     }
5217   }
5218   else {
5219     log_trace(os)("active_processor_count: using static path - configured processors: %d",
5220                   configured_cpus);
5221   }
5222 #else // CPU_ALLOC
5223 // these stubs won't be executed
5224 #define CPU_COUNT_S(size, cpus) -1
5225 #define CPU_FREE(cpus)
5226 
5227   log_trace(os)("active_processor_count: only static path available - configured processors: %d",
5228                 configured_cpus);
5229 #endif // CPU_ALLOC
5230 
5231   // pid 0 means the current thread - which we have to assume represents the process
5232   if (sched_getaffinity(0, cpus_size, cpus_p) == 0) {
5233     if (cpus_p != &cpus) { // can only be true when CPU_ALLOC used
5234       cpu_count = CPU_COUNT_S(cpus_size, cpus_p);
5235     }
5236     else {
5237       cpu_count = CPU_COUNT(cpus_p);
5238     }
5239     log_trace(os)("active_processor_count: sched_getaffinity processor count: %d", cpu_count);
5240   }
5241   else {
5242     cpu_count = ::sysconf(_SC_NPROCESSORS_ONLN);
5243     warning("sched_getaffinity failed (%s)- using online processor count (%d) "
5244             "which may exceed available processors", os::strerror(errno), cpu_count);
5245   }
5246 
5247   if (cpus_p != &cpus) { // can only be true when CPU_ALLOC used
5248     CPU_FREE(cpus_p);
5249   }
5250 
5251   assert(cpu_count > 0 && cpu_count <= os::processor_count(), "sanity check");
5252   return cpu_count;
5253 }
5254 
5255 // Determine the active processor count from one of
5256 // three different sources:
5257 //
5258 // 1. User option -XX:ActiveProcessorCount
5259 // 2. kernel os calls (sched_getaffinity or sysconf(_SC_NPROCESSORS_ONLN)
5260 // 3. extracted from cgroup cpu subsystem (shares and quotas)
5261 //
5262 // Option 1, if specified, will always override.
5263 // If the cgroup subsystem is active and configured, we
5264 // will return the min of the cgroup and option 2 results.
5265 // This is required since tools, such as numactl, that
5266 // alter cpu affinity do not update cgroup subsystem
5267 // cpuset configuration files.
5268 int os::active_processor_count() {
5269   // User has overridden the number of active processors
5270   if (ActiveProcessorCount > 0) {
5271     log_trace(os)("active_processor_count: "
5272                   "active processor count set by user : %d",
5273                   ActiveProcessorCount);
5274     return ActiveProcessorCount;
5275   }
5276 
5277   int active_cpus;
5278   if (OSContainer::is_containerized()) {
5279     active_cpus = OSContainer::active_processor_count();
5280     log_trace(os)("active_processor_count: determined by OSContainer: %d",
5281                    active_cpus);
5282   } else {
5283     active_cpus = os::Linux::active_processor_count();
5284   }
5285 
5286   return active_cpus;
5287 }
5288 
5289 uint os::processor_id() {
5290   const int id = Linux::sched_getcpu();
5291   assert(id >= 0 && id < _processor_count, "Invalid processor id");
5292   return (uint)id;
5293 }
5294 
5295 void os::set_native_thread_name(const char *name) {
5296   if (Linux::_pthread_setname_np) {
5297     char buf [16]; // according to glibc manpage, 16 chars incl. '/0'
5298     snprintf(buf, sizeof(buf), "%s", name);
5299     buf[sizeof(buf) - 1] = '\0';
5300     const int rc = Linux::_pthread_setname_np(pthread_self(), buf);
5301     // ERANGE should not happen; all other errors should just be ignored.
5302     assert(rc != ERANGE, "pthread_setname_np failed");
5303   }
5304 }
5305 
5306 bool os::distribute_processes(uint length, uint* distribution) {
5307   // Not yet implemented.
5308   return false;
5309 }
5310 
5311 bool os::bind_to_processor(uint processor_id) {
5312   // Not yet implemented.
5313   return false;
5314 }
5315 
5316 ///
5317 
5318 void os::SuspendedThreadTask::internal_do_task() {
5319   if (do_suspend(_thread->osthread())) {
5320     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
5321     do_task(context);
5322     do_resume(_thread->osthread());
5323   }
5324 }
5325 
5326 ////////////////////////////////////////////////////////////////////////////////
5327 // debug support
5328 
5329 bool os::find(address addr, outputStream* st) {
5330   Dl_info dlinfo;
5331   memset(&dlinfo, 0, sizeof(dlinfo));
5332   if (dladdr(addr, &dlinfo) != 0) {
5333     st->print(PTR_FORMAT ": ", p2i(addr));
5334     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
5335       st->print("%s+" PTR_FORMAT, dlinfo.dli_sname,
5336                 p2i(addr) - p2i(dlinfo.dli_saddr));
5337     } else if (dlinfo.dli_fbase != NULL) {
5338       st->print("<offset " PTR_FORMAT ">", p2i(addr) - p2i(dlinfo.dli_fbase));
5339     } else {
5340       st->print("<absolute address>");
5341     }
5342     if (dlinfo.dli_fname != NULL) {
5343       st->print(" in %s", dlinfo.dli_fname);
5344     }
5345     if (dlinfo.dli_fbase != NULL) {
5346       st->print(" at " PTR_FORMAT, p2i(dlinfo.dli_fbase));
5347     }
5348     st->cr();
5349 
5350     if (Verbose) {
5351       // decode some bytes around the PC
5352       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
5353       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
5354       address       lowest = (address) dlinfo.dli_sname;
5355       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
5356       if (begin < lowest)  begin = lowest;
5357       Dl_info dlinfo2;
5358       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
5359           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
5360         end = (address) dlinfo2.dli_saddr;
5361       }
5362       Disassembler::decode(begin, end, st);
5363     }
5364     return true;
5365   }
5366   return false;
5367 }
5368 
5369 ////////////////////////////////////////////////////////////////////////////////
5370 // misc
5371 
5372 // This does not do anything on Linux. This is basically a hook for being
5373 // able to use structured exception handling (thread-local exception filters)
5374 // on, e.g., Win32.
5375 void
5376 os::os_exception_wrapper(java_call_t f, JavaValue* value, const methodHandle& method,
5377                          JavaCallArguments* args, Thread* thread) {
5378   f(value, method, args, thread);
5379 }
5380 
5381 void os::print_statistics() {
5382 }
5383 
5384 bool os::message_box(const char* title, const char* message) {
5385   int i;
5386   fdStream err(defaultStream::error_fd());
5387   for (i = 0; i < 78; i++) err.print_raw("=");
5388   err.cr();
5389   err.print_raw_cr(title);
5390   for (i = 0; i < 78; i++) err.print_raw("-");
5391   err.cr();
5392   err.print_raw_cr(message);
5393   for (i = 0; i < 78; i++) err.print_raw("=");
5394   err.cr();
5395 
5396   char buf[16];
5397   // Prevent process from exiting upon "read error" without consuming all CPU
5398   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
5399 
5400   return buf[0] == 'y' || buf[0] == 'Y';
5401 }
5402 
5403 // Is a (classpath) directory empty?
5404 bool os::dir_is_empty(const char* path) {
5405   DIR *dir = NULL;
5406   struct dirent *ptr;
5407 
5408   dir = opendir(path);
5409   if (dir == NULL) return true;
5410 
5411   // Scan the directory
5412   bool result = true;
5413   while (result && (ptr = readdir(dir)) != NULL) {
5414     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
5415       result = false;
5416     }
5417   }
5418   closedir(dir);
5419   return result;
5420 }
5421 
5422 // This code originates from JDK's sysOpen and open64_w
5423 // from src/solaris/hpi/src/system_md.c
5424 
5425 int os::open(const char *path, int oflag, int mode) {
5426   if (strlen(path) > MAX_PATH - 1) {
5427     errno = ENAMETOOLONG;
5428     return -1;
5429   }
5430 
5431   // All file descriptors that are opened in the Java process and not
5432   // specifically destined for a subprocess should have the close-on-exec
5433   // flag set.  If we don't set it, then careless 3rd party native code
5434   // might fork and exec without closing all appropriate file descriptors
5435   // (e.g. as we do in closeDescriptors in UNIXProcess.c), and this in
5436   // turn might:
5437   //
5438   // - cause end-of-file to fail to be detected on some file
5439   //   descriptors, resulting in mysterious hangs, or
5440   //
5441   // - might cause an fopen in the subprocess to fail on a system
5442   //   suffering from bug 1085341.
5443   //
5444   // (Yes, the default setting of the close-on-exec flag is a Unix
5445   // design flaw)
5446   //
5447   // See:
5448   // 1085341: 32-bit stdio routines should support file descriptors >255
5449   // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
5450   // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
5451   //
5452   // Modern Linux kernels (after 2.6.23 2007) support O_CLOEXEC with open().
5453   // O_CLOEXEC is preferable to using FD_CLOEXEC on an open file descriptor
5454   // because it saves a system call and removes a small window where the flag
5455   // is unset.  On ancient Linux kernels the O_CLOEXEC flag will be ignored
5456   // and we fall back to using FD_CLOEXEC (see below).
5457 #ifdef O_CLOEXEC
5458   oflag |= O_CLOEXEC;
5459 #endif
5460 
5461   int fd = ::open64(path, oflag, mode);
5462   if (fd == -1) return -1;
5463 
5464   //If the open succeeded, the file might still be a directory
5465   {
5466     struct stat64 buf64;
5467     int ret = ::fstat64(fd, &buf64);
5468     int st_mode = buf64.st_mode;
5469 
5470     if (ret != -1) {
5471       if ((st_mode & S_IFMT) == S_IFDIR) {
5472         errno = EISDIR;
5473         ::close(fd);
5474         return -1;
5475       }
5476     } else {
5477       ::close(fd);
5478       return -1;
5479     }
5480   }
5481 
5482 #ifdef FD_CLOEXEC
5483   // Validate that the use of the O_CLOEXEC flag on open above worked.
5484   // With recent kernels, we will perform this check exactly once.
5485   static sig_atomic_t O_CLOEXEC_is_known_to_work = 0;
5486   if (!O_CLOEXEC_is_known_to_work) {
5487     int flags = ::fcntl(fd, F_GETFD);
5488     if (flags != -1) {
5489       if ((flags & FD_CLOEXEC) != 0)
5490         O_CLOEXEC_is_known_to_work = 1;
5491       else
5492         ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
5493     }
5494   }
5495 #endif
5496 
5497   return fd;
5498 }
5499 
5500 
5501 // create binary file, rewriting existing file if required
5502 int os::create_binary_file(const char* path, bool rewrite_existing) {
5503   int oflags = O_WRONLY | O_CREAT;
5504   if (!rewrite_existing) {
5505     oflags |= O_EXCL;
5506   }
5507   return ::open64(path, oflags, S_IREAD | S_IWRITE);
5508 }
5509 
5510 // return current position of file pointer
5511 jlong os::current_file_offset(int fd) {
5512   return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
5513 }
5514 
5515 // move file pointer to the specified offset
5516 jlong os::seek_to_file_offset(int fd, jlong offset) {
5517   return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
5518 }
5519 
5520 // This code originates from JDK's sysAvailable
5521 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
5522 
5523 int os::available(int fd, jlong *bytes) {
5524   jlong cur, end;
5525   int mode;
5526   struct stat64 buf64;
5527 
5528   if (::fstat64(fd, &buf64) >= 0) {
5529     mode = buf64.st_mode;
5530     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
5531       int n;
5532       if (::ioctl(fd, FIONREAD, &n) >= 0) {
5533         *bytes = n;
5534         return 1;
5535       }
5536     }
5537   }
5538   if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
5539     return 0;
5540   } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
5541     return 0;
5542   } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
5543     return 0;
5544   }
5545   *bytes = end - cur;
5546   return 1;
5547 }
5548 
5549 // Map a block of memory.
5550 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
5551                         char *addr, size_t bytes, bool read_only,
5552                         bool allow_exec) {
5553   int prot;
5554   int flags = MAP_PRIVATE;
5555 
5556   if (read_only) {
5557     prot = PROT_READ;
5558   } else {
5559     prot = PROT_READ | PROT_WRITE;
5560   }
5561 
5562   if (allow_exec) {
5563     prot |= PROT_EXEC;
5564   }
5565 
5566   if (addr != NULL) {
5567     flags |= MAP_FIXED;
5568   }
5569 
5570   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
5571                                      fd, file_offset);
5572   if (mapped_address == MAP_FAILED) {
5573     return NULL;
5574   }
5575   return mapped_address;
5576 }
5577 
5578 
5579 // Remap a block of memory.
5580 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
5581                           char *addr, size_t bytes, bool read_only,
5582                           bool allow_exec) {
5583   // same as map_memory() on this OS
5584   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
5585                         allow_exec);
5586 }
5587 
5588 
5589 // Unmap a block of memory.
5590 bool os::pd_unmap_memory(char* addr, size_t bytes) {
5591   return munmap(addr, bytes) == 0;
5592 }
5593 
5594 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time);
5595 
5596 static jlong fast_cpu_time(Thread *thread) {
5597     clockid_t clockid;
5598     int rc = os::Linux::pthread_getcpuclockid(thread->osthread()->pthread_id(),
5599                                               &clockid);
5600     if (rc == 0) {
5601       return os::Linux::fast_thread_cpu_time(clockid);
5602     } else {
5603       // It's possible to encounter a terminated native thread that failed
5604       // to detach itself from the VM - which should result in ESRCH.
5605       assert_status(rc == ESRCH, rc, "pthread_getcpuclockid failed");
5606       return -1;
5607     }
5608 }
5609 
5610 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
5611 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
5612 // of a thread.
5613 //
5614 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
5615 // the fast estimate available on the platform.
5616 
5617 jlong os::current_thread_cpu_time() {
5618   if (os::Linux::supports_fast_thread_cpu_time()) {
5619     return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5620   } else {
5621     // return user + sys since the cost is the same
5622     return slow_thread_cpu_time(Thread::current(), true /* user + sys */);
5623   }
5624 }
5625 
5626 jlong os::thread_cpu_time(Thread* thread) {
5627   // consistent with what current_thread_cpu_time() returns
5628   if (os::Linux::supports_fast_thread_cpu_time()) {
5629     return fast_cpu_time(thread);
5630   } else {
5631     return slow_thread_cpu_time(thread, true /* user + sys */);
5632   }
5633 }
5634 
5635 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
5636   if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5637     return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5638   } else {
5639     return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time);
5640   }
5641 }
5642 
5643 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5644   if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5645     return fast_cpu_time(thread);
5646   } else {
5647     return slow_thread_cpu_time(thread, user_sys_cpu_time);
5648   }
5649 }
5650 
5651 //  -1 on error.
5652 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5653   pid_t  tid = thread->osthread()->thread_id();
5654   char *s;
5655   char stat[2048];
5656   int statlen;
5657   char proc_name[64];
5658   int count;
5659   long sys_time, user_time;
5660   char cdummy;
5661   int idummy;
5662   long ldummy;
5663   FILE *fp;
5664 
5665   snprintf(proc_name, 64, "/proc/self/task/%d/stat", tid);
5666   fp = fopen(proc_name, "r");
5667   if (fp == NULL) return -1;
5668   statlen = fread(stat, 1, 2047, fp);
5669   stat[statlen] = '\0';
5670   fclose(fp);
5671 
5672   // Skip pid and the command string. Note that we could be dealing with
5673   // weird command names, e.g. user could decide to rename java launcher
5674   // to "java 1.4.2 :)", then the stat file would look like
5675   //                1234 (java 1.4.2 :)) R ... ...
5676   // We don't really need to know the command string, just find the last
5677   // occurrence of ")" and then start parsing from there. See bug 4726580.
5678   s = strrchr(stat, ')');
5679   if (s == NULL) return -1;
5680 
5681   // Skip blank chars
5682   do { s++; } while (s && isspace(*s));
5683 
5684   count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu",
5685                  &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy,
5686                  &ldummy, &ldummy, &ldummy, &ldummy, &ldummy,
5687                  &user_time, &sys_time);
5688   if (count != 13) return -1;
5689   if (user_sys_cpu_time) {
5690     return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
5691   } else {
5692     return (jlong)user_time * (1000000000 / clock_tics_per_sec);
5693   }
5694 }
5695 
5696 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5697   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5698   info_ptr->may_skip_backward = false;     // elapsed time not wall time
5699   info_ptr->may_skip_forward = false;      // elapsed time not wall time
5700   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5701 }
5702 
5703 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5704   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5705   info_ptr->may_skip_backward = false;     // elapsed time not wall time
5706   info_ptr->may_skip_forward = false;      // elapsed time not wall time
5707   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5708 }
5709 
5710 bool os::is_thread_cpu_time_supported() {
5711   return true;
5712 }
5713 
5714 // System loadavg support.  Returns -1 if load average cannot be obtained.
5715 // Linux doesn't yet have a (official) notion of processor sets,
5716 // so just return the system wide load average.
5717 int os::loadavg(double loadavg[], int nelem) {
5718   return ::getloadavg(loadavg, nelem);
5719 }
5720 
5721 void os::pause() {
5722   char filename[MAX_PATH];
5723   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
5724     jio_snprintf(filename, MAX_PATH, "%s", PauseAtStartupFile);
5725   } else {
5726     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
5727   }
5728 
5729   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
5730   if (fd != -1) {
5731     struct stat buf;
5732     ::close(fd);
5733     while (::stat(filename, &buf) == 0) {
5734       (void)::poll(NULL, 0, 100);
5735     }
5736   } else {
5737     jio_fprintf(stderr,
5738                 "Could not open pause file '%s', continuing immediately.\n", filename);
5739   }
5740 }
5741 
5742 extern char** environ;
5743 
5744 // Run the specified command in a separate process. Return its exit value,
5745 // or -1 on failure (e.g. can't fork a new process).
5746 // Unlike system(), this function can be called from signal handler. It
5747 // doesn't block SIGINT et al.
5748 int os::fork_and_exec(char* cmd, bool use_vfork_if_available) {
5749   const char * argv[4] = {"sh", "-c", cmd, NULL};
5750 
5751   pid_t pid ;
5752 
5753   if (use_vfork_if_available) {
5754     pid = vfork();
5755   } else {
5756     pid = fork();
5757   }
5758 
5759   if (pid < 0) {
5760     // fork failed
5761     return -1;
5762 
5763   } else if (pid == 0) {
5764     // child process
5765 
5766     execve("/bin/sh", (char* const*)argv, environ);
5767 
5768     // execve failed
5769     _exit(-1);
5770 
5771   } else  {
5772     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
5773     // care about the actual exit code, for now.
5774 
5775     int status;
5776 
5777     // Wait for the child process to exit.  This returns immediately if
5778     // the child has already exited. */
5779     while (waitpid(pid, &status, 0) < 0) {
5780       switch (errno) {
5781       case ECHILD: return 0;
5782       case EINTR: break;
5783       default: return -1;
5784       }
5785     }
5786 
5787     if (WIFEXITED(status)) {
5788       // The child exited normally; get its exit code.
5789       return WEXITSTATUS(status);
5790     } else if (WIFSIGNALED(status)) {
5791       // The child exited because of a signal
5792       // The best value to return is 0x80 + signal number,
5793       // because that is what all Unix shells do, and because
5794       // it allows callers to distinguish between process exit and
5795       // process death by signal.
5796       return 0x80 + WTERMSIG(status);
5797     } else {
5798       // Unknown exit code; pass it through
5799       return status;
5800     }
5801   }
5802 }
5803 
5804 // Get the default path to the core file
5805 // Returns the length of the string
5806 int os::get_core_path(char* buffer, size_t bufferSize) {
5807   /*
5808    * Max length of /proc/sys/kernel/core_pattern is 128 characters.
5809    * See https://www.kernel.org/doc/Documentation/sysctl/kernel.txt
5810    */
5811   const int core_pattern_len = 129;
5812   char core_pattern[core_pattern_len] = {0};
5813 
5814   int core_pattern_file = ::open("/proc/sys/kernel/core_pattern", O_RDONLY);
5815   if (core_pattern_file == -1) {
5816     return -1;
5817   }
5818 
5819   ssize_t ret = ::read(core_pattern_file, core_pattern, core_pattern_len);
5820   ::close(core_pattern_file);
5821   if (ret <= 0 || ret >= core_pattern_len || core_pattern[0] == '\n') {
5822     return -1;
5823   }
5824   if (core_pattern[ret-1] == '\n') {
5825     core_pattern[ret-1] = '\0';
5826   } else {
5827     core_pattern[ret] = '\0';
5828   }
5829 
5830   // Replace the %p in the core pattern with the process id. NOTE: we do this
5831   // only if the pattern doesn't start with "|", and we support only one %p in
5832   // the pattern.
5833   char *pid_pos = strstr(core_pattern, "%p");
5834   const char* tail = (pid_pos != NULL) ? (pid_pos + 2) : "";  // skip over the "%p"
5835   int written;
5836 
5837   if (core_pattern[0] == '/') {
5838     if (pid_pos != NULL) {
5839       *pid_pos = '\0';
5840       written = jio_snprintf(buffer, bufferSize, "%s%d%s", core_pattern,
5841                              current_process_id(), tail);
5842     } else {
5843       written = jio_snprintf(buffer, bufferSize, "%s", core_pattern);
5844     }
5845   } else {
5846     char cwd[PATH_MAX];
5847 
5848     const char* p = get_current_directory(cwd, PATH_MAX);
5849     if (p == NULL) {
5850       return -1;
5851     }
5852 
5853     if (core_pattern[0] == '|') {
5854       written = jio_snprintf(buffer, bufferSize,
5855                              "\"%s\" (or dumping to %s/core.%d)",
5856                              &core_pattern[1], p, current_process_id());
5857     } else if (pid_pos != NULL) {
5858       *pid_pos = '\0';
5859       written = jio_snprintf(buffer, bufferSize, "%s/%s%d%s", p, core_pattern,
5860                              current_process_id(), tail);
5861     } else {
5862       written = jio_snprintf(buffer, bufferSize, "%s/%s", p, core_pattern);
5863     }
5864   }
5865 
5866   if (written < 0) {
5867     return -1;
5868   }
5869 
5870   if (((size_t)written < bufferSize) && (pid_pos == NULL) && (core_pattern[0] != '|')) {
5871     int core_uses_pid_file = ::open("/proc/sys/kernel/core_uses_pid", O_RDONLY);
5872 
5873     if (core_uses_pid_file != -1) {
5874       char core_uses_pid = 0;
5875       ssize_t ret = ::read(core_uses_pid_file, &core_uses_pid, 1);
5876       ::close(core_uses_pid_file);
5877 
5878       if (core_uses_pid == '1') {
5879         jio_snprintf(buffer + written, bufferSize - written,
5880                                           ".%d", current_process_id());
5881       }
5882     }
5883   }
5884 
5885   return strlen(buffer);
5886 }
5887 
5888 bool os::start_debugging(char *buf, int buflen) {
5889   int len = (int)strlen(buf);
5890   char *p = &buf[len];
5891 
5892   jio_snprintf(p, buflen-len,
5893                "\n\n"
5894                "Do you want to debug the problem?\n\n"
5895                "To debug, run 'gdb /proc/%d/exe %d'; then switch to thread " UINTX_FORMAT " (" INTPTR_FORMAT ")\n"
5896                "Enter 'yes' to launch gdb automatically (PATH must include gdb)\n"
5897                "Otherwise, press RETURN to abort...",
5898                os::current_process_id(), os::current_process_id(),
5899                os::current_thread_id(), os::current_thread_id());
5900 
5901   bool yes = os::message_box("Unexpected Error", buf);
5902 
5903   if (yes) {
5904     // yes, user asked VM to launch debugger
5905     jio_snprintf(buf, sizeof(char)*buflen, "gdb /proc/%d/exe %d",
5906                  os::current_process_id(), os::current_process_id());
5907 
5908     os::fork_and_exec(buf);
5909     yes = false;
5910   }
5911   return yes;
5912 }
5913 
5914 
5915 // Java/Compiler thread:
5916 //
5917 //   Low memory addresses
5918 // P0 +------------------------+
5919 //    |                        |\  Java thread created by VM does not have glibc
5920 //    |    glibc guard page    | - guard page, attached Java thread usually has
5921 //    |                        |/  1 glibc guard page.
5922 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
5923 //    |                        |\
5924 //    |  HotSpot Guard Pages   | - red, yellow and reserved pages
5925 //    |                        |/
5926 //    +------------------------+ JavaThread::stack_reserved_zone_base()
5927 //    |                        |\
5928 //    |      Normal Stack      | -
5929 //    |                        |/
5930 // P2 +------------------------+ Thread::stack_base()
5931 //
5932 // Non-Java thread:
5933 //
5934 //   Low memory addresses
5935 // P0 +------------------------+
5936 //    |                        |\
5937 //    |  glibc guard page      | - usually 1 page
5938 //    |                        |/
5939 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
5940 //    |                        |\
5941 //    |      Normal Stack      | -
5942 //    |                        |/
5943 // P2 +------------------------+ Thread::stack_base()
5944 //
5945 // ** P1 (aka bottom) and size (P2 = P1 - size) are the address and stack size
5946 //    returned from pthread_attr_getstack().
5947 // ** Due to NPTL implementation error, linux takes the glibc guard page out
5948 //    of the stack size given in pthread_attr. We work around this for
5949 //    threads created by the VM. (We adapt bottom to be P1 and size accordingly.)
5950 //
5951 #ifndef ZERO
5952 static void current_stack_region(address * bottom, size_t * size) {
5953   if (os::is_primordial_thread()) {
5954     // primordial thread needs special handling because pthread_getattr_np()
5955     // may return bogus value.
5956     *bottom = os::Linux::initial_thread_stack_bottom();
5957     *size   = os::Linux::initial_thread_stack_size();
5958   } else {
5959     pthread_attr_t attr;
5960 
5961     int rslt = pthread_getattr_np(pthread_self(), &attr);
5962 
5963     // JVM needs to know exact stack location, abort if it fails
5964     if (rslt != 0) {
5965       if (rslt == ENOMEM) {
5966         vm_exit_out_of_memory(0, OOM_MMAP_ERROR, "pthread_getattr_np");
5967       } else {
5968         fatal("pthread_getattr_np failed with error = %d", rslt);
5969       }
5970     }
5971 
5972     if (pthread_attr_getstack(&attr, (void **)bottom, size) != 0) {
5973       fatal("Cannot locate current stack attributes!");
5974     }
5975 
5976     // Work around NPTL stack guard error.
5977     size_t guard_size = 0;
5978     rslt = pthread_attr_getguardsize(&attr, &guard_size);
5979     if (rslt != 0) {
5980       fatal("pthread_attr_getguardsize failed with error = %d", rslt);
5981     }
5982     *bottom += guard_size;
5983     *size   -= guard_size;
5984 
5985     pthread_attr_destroy(&attr);
5986 
5987   }
5988   assert(os::current_stack_pointer() >= *bottom &&
5989          os::current_stack_pointer() < *bottom + *size, "just checking");
5990 }
5991 
5992 address os::current_stack_base() {
5993   address bottom;
5994   size_t size;
5995   current_stack_region(&bottom, &size);
5996   return (bottom + size);
5997 }
5998 
5999 size_t os::current_stack_size() {
6000   // This stack size includes the usable stack and HotSpot guard pages
6001   // (for the threads that have Hotspot guard pages).
6002   address bottom;
6003   size_t size;
6004   current_stack_region(&bottom, &size);
6005   return size;
6006 }
6007 #endif
6008 
6009 static inline struct timespec get_mtime(const char* filename) {
6010   struct stat st;
6011   int ret = os::stat(filename, &st);
6012   assert(ret == 0, "failed to stat() file '%s': %s", filename, os::strerror(errno));
6013   return st.st_mtim;
6014 }
6015 
6016 int os::compare_file_modified_times(const char* file1, const char* file2) {
6017   struct timespec filetime1 = get_mtime(file1);
6018   struct timespec filetime2 = get_mtime(file2);
6019   int diff = filetime1.tv_sec - filetime2.tv_sec;
6020   if (diff == 0) {
6021     return filetime1.tv_nsec - filetime2.tv_nsec;
6022   }
6023   return diff;
6024 }
6025 
6026 /////////////// Unit tests ///////////////
6027 
6028 #ifndef PRODUCT
6029 
6030 class TestReserveMemorySpecial : AllStatic {
6031  public:
6032   static void small_page_write(void* addr, size_t size) {
6033     size_t page_size = os::vm_page_size();
6034 
6035     char* end = (char*)addr + size;
6036     for (char* p = (char*)addr; p < end; p += page_size) {
6037       *p = 1;
6038     }
6039   }
6040 
6041   static void test_reserve_memory_special_huge_tlbfs_only(size_t size) {
6042     if (!UseHugeTLBFS) {
6043       return;
6044     }
6045 
6046     char* addr = os::Linux::reserve_memory_special_huge_tlbfs_only(size, NULL, false);
6047 
6048     if (addr != NULL) {
6049       small_page_write(addr, size);
6050 
6051       os::Linux::release_memory_special_huge_tlbfs(addr, size);
6052     }
6053   }
6054 
6055   static void test_reserve_memory_special_huge_tlbfs_only() {
6056     if (!UseHugeTLBFS) {
6057       return;
6058     }
6059 
6060     size_t lp = os::large_page_size();
6061 
6062     for (size_t size = lp; size <= lp * 10; size += lp) {
6063       test_reserve_memory_special_huge_tlbfs_only(size);
6064     }
6065   }
6066 
6067   static void test_reserve_memory_special_huge_tlbfs_mixed() {
6068     size_t lp = os::large_page_size();
6069     size_t ag = os::vm_allocation_granularity();
6070 
6071     // sizes to test
6072     const size_t sizes[] = {
6073       lp, lp + ag, lp + lp / 2, lp * 2,
6074       lp * 2 + ag, lp * 2 - ag, lp * 2 + lp / 2,
6075       lp * 10, lp * 10 + lp / 2
6076     };
6077     const int num_sizes = sizeof(sizes) / sizeof(size_t);
6078 
6079     // For each size/alignment combination, we test three scenarios:
6080     // 1) with req_addr == NULL
6081     // 2) with a non-null req_addr at which we expect to successfully allocate
6082     // 3) with a non-null req_addr which contains a pre-existing mapping, at which we
6083     //    expect the allocation to either fail or to ignore req_addr
6084 
6085     // Pre-allocate two areas; they shall be as large as the largest allocation
6086     //  and aligned to the largest alignment we will be testing.
6087     const size_t mapping_size = sizes[num_sizes - 1] * 2;
6088     char* const mapping1 = (char*) ::mmap(NULL, mapping_size,
6089       PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
6090       -1, 0);
6091     assert(mapping1 != MAP_FAILED, "should work");
6092 
6093     char* const mapping2 = (char*) ::mmap(NULL, mapping_size,
6094       PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
6095       -1, 0);
6096     assert(mapping2 != MAP_FAILED, "should work");
6097 
6098     // Unmap the first mapping, but leave the second mapping intact: the first
6099     // mapping will serve as a value for a "good" req_addr (case 2). The second
6100     // mapping, still intact, as "bad" req_addr (case 3).
6101     ::munmap(mapping1, mapping_size);
6102 
6103     // Case 1
6104     for (int i = 0; i < num_sizes; i++) {
6105       const size_t size = sizes[i];
6106       for (size_t alignment = ag; is_aligned(size, alignment); alignment *= 2) {
6107         char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, NULL, false);
6108         if (p != NULL) {
6109           assert(is_aligned(p, alignment), "must be");
6110           small_page_write(p, size);
6111           os::Linux::release_memory_special_huge_tlbfs(p, size);
6112         }
6113       }
6114     }
6115 
6116     // Case 2
6117     for (int i = 0; i < num_sizes; i++) {
6118       const size_t size = sizes[i];
6119       for (size_t alignment = ag; is_aligned(size, alignment); alignment *= 2) {
6120         char* const req_addr = align_up(mapping1, alignment);
6121         char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, req_addr, false);
6122         if (p != NULL) {
6123           assert(p == req_addr, "must be");
6124           small_page_write(p, size);
6125           os::Linux::release_memory_special_huge_tlbfs(p, size);
6126         }
6127       }
6128     }
6129 
6130     // Case 3
6131     for (int i = 0; i < num_sizes; i++) {
6132       const size_t size = sizes[i];
6133       for (size_t alignment = ag; is_aligned(size, alignment); alignment *= 2) {
6134         char* const req_addr = align_up(mapping2, alignment);
6135         char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, req_addr, false);
6136         // as the area around req_addr contains already existing mappings, the API should always
6137         // return NULL (as per contract, it cannot return another address)
6138         assert(p == NULL, "must be");
6139       }
6140     }
6141 
6142     ::munmap(mapping2, mapping_size);
6143 
6144   }
6145 
6146   static void test_reserve_memory_special_huge_tlbfs() {
6147     if (!UseHugeTLBFS) {
6148       return;
6149     }
6150 
6151     test_reserve_memory_special_huge_tlbfs_only();
6152     test_reserve_memory_special_huge_tlbfs_mixed();
6153   }
6154 
6155   static void test_reserve_memory_special_shm(size_t size, size_t alignment) {
6156     if (!UseSHM) {
6157       return;
6158     }
6159 
6160     char* addr = os::Linux::reserve_memory_special_shm(size, alignment, NULL, false);
6161 
6162     if (addr != NULL) {
6163       assert(is_aligned(addr, alignment), "Check");
6164       assert(is_aligned(addr, os::large_page_size()), "Check");
6165 
6166       small_page_write(addr, size);
6167 
6168       os::Linux::release_memory_special_shm(addr, size);
6169     }
6170   }
6171 
6172   static void test_reserve_memory_special_shm() {
6173     size_t lp = os::large_page_size();
6174     size_t ag = os::vm_allocation_granularity();
6175 
6176     for (size_t size = ag; size < lp * 3; size += ag) {
6177       for (size_t alignment = ag; is_aligned(size, alignment); alignment *= 2) {
6178         test_reserve_memory_special_shm(size, alignment);
6179       }
6180     }
6181   }
6182 
6183   static void test() {
6184     test_reserve_memory_special_huge_tlbfs();
6185     test_reserve_memory_special_shm();
6186   }
6187 };
6188 
6189 void TestReserveMemorySpecial_test() {
6190   TestReserveMemorySpecial::test();
6191 }
6192 
6193 #endif
--- EOF ---