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