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