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