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