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