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