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