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