src/os/linux/vm/os_linux.cpp

Fri, 29 Apr 2016 00:06:10 +0800

author
aoqi
date
Fri, 29 Apr 2016 00:06:10 +0800
changeset 1
2d8a650513c2
parent 0
f90c822e73f8
child 25
873fd82b133d
permissions
-rw-r--r--

Added MIPS 64-bit port.

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

mercurial