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