src/os/linux/vm/os_linux.cpp

Wed, 27 Apr 2016 01:25:04 +0800

author
aoqi
date
Wed, 27 Apr 2016 01:25:04 +0800
changeset 0
f90c822e73f8
child 1
2d8a650513c2
permissions
-rw-r--r--

Initial load
http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/
changeset: 6782:28b50d07f6f8
tag: jdk8u25-b17

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

mercurial