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