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