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