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