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