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