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