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