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