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