os_linux.cpp revision 6223:09edc8e9fa4d
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#if defined(VM_LITTLE_ENDIAN)
1967    {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2LSB, (char*)"Power PC 64"},
1968#else
1969    {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1970#endif
1971    {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
1972    {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1973    {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1974    {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1975    {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1976    {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1977    {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"}
1978  };
1979
1980  #if  (defined IA32)
1981    static  Elf32_Half running_arch_code=EM_386;
1982  #elif   (defined AMD64)
1983    static  Elf32_Half running_arch_code=EM_X86_64;
1984  #elif  (defined IA64)
1985    static  Elf32_Half running_arch_code=EM_IA_64;
1986  #elif  (defined __sparc) && (defined _LP64)
1987    static  Elf32_Half running_arch_code=EM_SPARCV9;
1988  #elif  (defined __sparc) && (!defined _LP64)
1989    static  Elf32_Half running_arch_code=EM_SPARC;
1990  #elif  (defined __powerpc64__)
1991    static  Elf32_Half running_arch_code=EM_PPC64;
1992  #elif  (defined __powerpc__)
1993    static  Elf32_Half running_arch_code=EM_PPC;
1994  #elif  (defined ARM)
1995    static  Elf32_Half running_arch_code=EM_ARM;
1996  #elif  (defined S390)
1997    static  Elf32_Half running_arch_code=EM_S390;
1998  #elif  (defined ALPHA)
1999    static  Elf32_Half running_arch_code=EM_ALPHA;
2000  #elif  (defined MIPSEL)
2001    static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
2002  #elif  (defined PARISC)
2003    static  Elf32_Half running_arch_code=EM_PARISC;
2004  #elif  (defined MIPS)
2005    static  Elf32_Half running_arch_code=EM_MIPS;
2006  #elif  (defined M68K)
2007    static  Elf32_Half running_arch_code=EM_68K;
2008  #else
2009    #error Method os::dll_load requires that one of following is defined:\
2010         IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K
2011  #endif
2012
2013  // Identify compatability class for VM's architecture and library's architecture
2014  // Obtain string descriptions for architectures
2015
2016  arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
2017  int running_arch_index=-1;
2018
2019  for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {
2020    if (running_arch_code == arch_array[i].code) {
2021      running_arch_index    = i;
2022    }
2023    if (lib_arch.code == arch_array[i].code) {
2024      lib_arch.compat_class = arch_array[i].compat_class;
2025      lib_arch.name         = arch_array[i].name;
2026    }
2027  }
2028
2029  assert(running_arch_index != -1,
2030    "Didn't find running architecture code (running_arch_code) in arch_array");
2031  if (running_arch_index == -1) {
2032    // Even though running architecture detection failed
2033    // we may still continue with reporting dlerror() message
2034    return NULL;
2035  }
2036
2037  if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
2038    ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
2039    return NULL;
2040  }
2041
2042#ifndef S390
2043  if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
2044    ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
2045    return NULL;
2046  }
2047#endif // !S390
2048
2049  if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
2050    if ( lib_arch.name!=NULL ) {
2051      ::snprintf(diag_msg_buf, diag_msg_max_length-1,
2052        " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
2053        lib_arch.name, arch_array[running_arch_index].name);
2054    } else {
2055      ::snprintf(diag_msg_buf, diag_msg_max_length-1,
2056      " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
2057        lib_arch.code,
2058        arch_array[running_arch_index].name);
2059    }
2060  }
2061
2062  return NULL;
2063}
2064
2065void * os::Linux::dlopen_helper(const char *filename, char *ebuf, int ebuflen) {
2066  void * result = ::dlopen(filename, RTLD_LAZY);
2067  if (result == NULL) {
2068    ::strncpy(ebuf, ::dlerror(), ebuflen - 1);
2069    ebuf[ebuflen-1] = '\0';
2070  }
2071  return result;
2072}
2073
2074void * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf, int ebuflen) {
2075  void * result = NULL;
2076  if (LoadExecStackDllInVMThread) {
2077    result = dlopen_helper(filename, ebuf, ebuflen);
2078  }
2079
2080  // Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a
2081  // library that requires an executable stack, or which does not have this
2082  // stack attribute set, dlopen changes the stack attribute to executable. The
2083  // read protection of the guard pages gets lost.
2084  //
2085  // Need to check _stack_is_executable again as multiple VM_LinuxDllLoad
2086  // may have been queued at the same time.
2087
2088  if (!_stack_is_executable) {
2089    JavaThread *jt = Threads::first();
2090
2091    while (jt) {
2092      if (!jt->stack_guard_zone_unused() &&        // Stack not yet fully initialized
2093          jt->stack_yellow_zone_enabled()) {       // No pending stack overflow exceptions
2094        if (!os::guard_memory((char *) jt->stack_red_zone_base() - jt->stack_red_zone_size(),
2095                              jt->stack_yellow_zone_size() + jt->stack_red_zone_size())) {
2096          warning("Attempt to reguard stack yellow zone failed.");
2097        }
2098      }
2099      jt = jt->next();
2100    }
2101  }
2102
2103  return result;
2104}
2105
2106/*
2107 * glibc-2.0 libdl is not MT safe.  If you are building with any glibc,
2108 * chances are you might want to run the generated bits against glibc-2.0
2109 * libdl.so, so always use locking for any version of glibc.
2110 */
2111void* os::dll_lookup(void* handle, const char* name) {
2112  pthread_mutex_lock(&dl_mutex);
2113  void* res = dlsym(handle, name);
2114  pthread_mutex_unlock(&dl_mutex);
2115  return res;
2116}
2117
2118void* os::get_default_process_handle() {
2119  return (void*)::dlopen(NULL, RTLD_LAZY);
2120}
2121
2122static bool _print_ascii_file(const char* filename, outputStream* st) {
2123  int fd = ::open(filename, O_RDONLY);
2124  if (fd == -1) {
2125     return false;
2126  }
2127
2128  char buf[32];
2129  int bytes;
2130  while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
2131    st->print_raw(buf, bytes);
2132  }
2133
2134  ::close(fd);
2135
2136  return true;
2137}
2138
2139void os::print_dll_info(outputStream *st) {
2140   st->print_cr("Dynamic libraries:");
2141
2142   char fname[32];
2143   pid_t pid = os::Linux::gettid();
2144
2145   jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid);
2146
2147   if (!_print_ascii_file(fname, st)) {
2148     st->print("Can not get library information for pid = %d\n", pid);
2149   }
2150}
2151
2152void os::print_os_info_brief(outputStream* st) {
2153  os::Linux::print_distro_info(st);
2154
2155  os::Posix::print_uname_info(st);
2156
2157  os::Linux::print_libversion_info(st);
2158
2159}
2160
2161void os::print_os_info(outputStream* st) {
2162  st->print("OS:");
2163
2164  os::Linux::print_distro_info(st);
2165
2166  os::Posix::print_uname_info(st);
2167
2168  // Print warning if unsafe chroot environment detected
2169  if (unsafe_chroot_detected) {
2170    st->print("WARNING!! ");
2171    st->print_cr(unstable_chroot_error);
2172  }
2173
2174  os::Linux::print_libversion_info(st);
2175
2176  os::Posix::print_rlimit_info(st);
2177
2178  os::Posix::print_load_average(st);
2179
2180  os::Linux::print_full_memory_info(st);
2181}
2182
2183// Try to identify popular distros.
2184// Most Linux distributions have a /etc/XXX-release file, which contains
2185// the OS version string. Newer Linux distributions have a /etc/lsb-release
2186// file that also contains the OS version string. Some have more than one
2187// /etc/XXX-release file (e.g. Mandrake has both /etc/mandrake-release and
2188// /etc/redhat-release.), so the order is important.
2189// Any Linux that is based on Redhat (i.e. Oracle, Mandrake, Sun JDS...) have
2190// their own specific XXX-release file as well as a redhat-release file.
2191// Because of this the XXX-release file needs to be searched for before the
2192// redhat-release file.
2193// Since Red Hat has a lsb-release file that is not very descriptive the
2194// search for redhat-release needs to be before lsb-release.
2195// Since the lsb-release file is the new standard it needs to be searched
2196// before the older style release files.
2197// Searching system-release (Red Hat) and os-release (other Linuxes) are a
2198// next to last resort.  The os-release file is a new standard that contains
2199// distribution information and the system-release file seems to be an old
2200// standard that has been replaced by the lsb-release and os-release files.
2201// Searching for the debian_version file is the last resort.  It contains
2202// an informative string like "6.0.6" or "wheezy/sid". Because of this
2203// "Debian " is printed before the contents of the debian_version file.
2204void os::Linux::print_distro_info(outputStream* st) {
2205   if (!_print_ascii_file("/etc/oracle-release", st) &&
2206       !_print_ascii_file("/etc/mandriva-release", st) &&
2207       !_print_ascii_file("/etc/mandrake-release", st) &&
2208       !_print_ascii_file("/etc/sun-release", st) &&
2209       !_print_ascii_file("/etc/redhat-release", st) &&
2210       !_print_ascii_file("/etc/lsb-release", st) &&
2211       !_print_ascii_file("/etc/SuSE-release", st) &&
2212       !_print_ascii_file("/etc/turbolinux-release", st) &&
2213       !_print_ascii_file("/etc/gentoo-release", st) &&
2214       !_print_ascii_file("/etc/ltib-release", st) &&
2215       !_print_ascii_file("/etc/angstrom-version", st) &&
2216       !_print_ascii_file("/etc/system-release", st) &&
2217       !_print_ascii_file("/etc/os-release", st)) {
2218
2219       if (file_exists("/etc/debian_version")) {
2220         st->print("Debian ");
2221         _print_ascii_file("/etc/debian_version", st);
2222       } else {
2223         st->print("Linux");
2224       }
2225   }
2226   st->cr();
2227}
2228
2229void os::Linux::print_libversion_info(outputStream* st) {
2230  // libc, pthread
2231  st->print("libc:");
2232  st->print(os::Linux::glibc_version()); st->print(" ");
2233  st->print(os::Linux::libpthread_version()); st->print(" ");
2234  if (os::Linux::is_LinuxThreads()) {
2235     st->print("(%s stack)", os::Linux::is_floating_stack() ? "floating" : "fixed");
2236  }
2237  st->cr();
2238}
2239
2240void os::Linux::print_full_memory_info(outputStream* st) {
2241   st->print("\n/proc/meminfo:\n");
2242   _print_ascii_file("/proc/meminfo", st);
2243   st->cr();
2244}
2245
2246void os::print_memory_info(outputStream* st) {
2247
2248  st->print("Memory:");
2249  st->print(" %dk page", os::vm_page_size()>>10);
2250
2251  // values in struct sysinfo are "unsigned long"
2252  struct sysinfo si;
2253  sysinfo(&si);
2254
2255  st->print(", physical " UINT64_FORMAT "k",
2256            os::physical_memory() >> 10);
2257  st->print("(" UINT64_FORMAT "k free)",
2258            os::available_memory() >> 10);
2259  st->print(", swap " UINT64_FORMAT "k",
2260            ((jlong)si.totalswap * si.mem_unit) >> 10);
2261  st->print("(" UINT64_FORMAT "k free)",
2262            ((jlong)si.freeswap * si.mem_unit) >> 10);
2263  st->cr();
2264}
2265
2266void os::pd_print_cpu_info(outputStream* st) {
2267  st->print("\n/proc/cpuinfo:\n");
2268  if (!_print_ascii_file("/proc/cpuinfo", st)) {
2269    st->print("  <Not Available>");
2270  }
2271  st->cr();
2272}
2273
2274void os::print_siginfo(outputStream* st, void* siginfo) {
2275  const siginfo_t* si = (const siginfo_t*)siginfo;
2276
2277  os::Posix::print_siginfo_brief(st, si);
2278
2279  if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
2280      UseSharedSpaces) {
2281    FileMapInfo* mapinfo = FileMapInfo::current_info();
2282    if (mapinfo->is_in_shared_space(si->si_addr)) {
2283      st->print("\n\nError accessing class data sharing archive."   \
2284                " Mapped file inaccessible during execution, "      \
2285                " possible disk/network problem.");
2286    }
2287  }
2288  st->cr();
2289}
2290
2291
2292static void print_signal_handler(outputStream* st, int sig,
2293                                 char* buf, size_t buflen);
2294
2295void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
2296  st->print_cr("Signal Handlers:");
2297  print_signal_handler(st, SIGSEGV, buf, buflen);
2298  print_signal_handler(st, SIGBUS , buf, buflen);
2299  print_signal_handler(st, SIGFPE , buf, buflen);
2300  print_signal_handler(st, SIGPIPE, buf, buflen);
2301  print_signal_handler(st, SIGXFSZ, buf, buflen);
2302  print_signal_handler(st, SIGILL , buf, buflen);
2303  print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);
2304  print_signal_handler(st, SR_signum, buf, buflen);
2305  print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
2306  print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
2307  print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
2308  print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
2309#if defined(PPC64)
2310  print_signal_handler(st, SIGTRAP, buf, buflen);
2311#endif
2312}
2313
2314static char saved_jvm_path[MAXPATHLEN] = {0};
2315
2316// Find the full path to the current module, libjvm.so
2317void os::jvm_path(char *buf, jint buflen) {
2318  // Error checking.
2319  if (buflen < MAXPATHLEN) {
2320    assert(false, "must use a large-enough buffer");
2321    buf[0] = '\0';
2322    return;
2323  }
2324  // Lazy resolve the path to current module.
2325  if (saved_jvm_path[0] != 0) {
2326    strcpy(buf, saved_jvm_path);
2327    return;
2328  }
2329
2330  char dli_fname[MAXPATHLEN];
2331  bool ret = dll_address_to_library_name(
2332                CAST_FROM_FN_PTR(address, os::jvm_path),
2333                dli_fname, sizeof(dli_fname), NULL);
2334  assert(ret, "cannot locate libjvm");
2335  char *rp = NULL;
2336  if (ret && dli_fname[0] != '\0') {
2337    rp = realpath(dli_fname, buf);
2338  }
2339  if (rp == NULL)
2340    return;
2341
2342  if (Arguments::sun_java_launcher_is_altjvm()) {
2343    // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
2344    // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so".
2345    // If "/jre/lib/" appears at the right place in the string, then
2346    // assume we are installed in a JDK and we're done. Otherwise, check
2347    // for a JAVA_HOME environment variable and fix up the path so it
2348    // looks like libjvm.so is installed there (append a fake suffix
2349    // hotspot/libjvm.so).
2350    const char *p = buf + strlen(buf) - 1;
2351    for (int count = 0; p > buf && count < 5; ++count) {
2352      for (--p; p > buf && *p != '/'; --p)
2353        /* empty */ ;
2354    }
2355
2356    if (strncmp(p, "/jre/lib/", 9) != 0) {
2357      // Look for JAVA_HOME in the environment.
2358      char* java_home_var = ::getenv("JAVA_HOME");
2359      if (java_home_var != NULL && java_home_var[0] != 0) {
2360        char* jrelib_p;
2361        int len;
2362
2363        // Check the current module name "libjvm.so".
2364        p = strrchr(buf, '/');
2365        assert(strstr(p, "/libjvm") == p, "invalid library name");
2366
2367        rp = realpath(java_home_var, buf);
2368        if (rp == NULL)
2369          return;
2370
2371        // determine if this is a legacy image or modules image
2372        // modules image doesn't have "jre" subdirectory
2373        len = strlen(buf);
2374        jrelib_p = buf + len;
2375        snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch);
2376        if (0 != access(buf, F_OK)) {
2377          snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch);
2378        }
2379
2380        if (0 == access(buf, F_OK)) {
2381          // Use current module name "libjvm.so"
2382          len = strlen(buf);
2383          snprintf(buf + len, buflen-len, "/hotspot/libjvm.so");
2384        } else {
2385          // Go back to path of .so
2386          rp = realpath(dli_fname, buf);
2387          if (rp == NULL)
2388            return;
2389        }
2390      }
2391    }
2392  }
2393
2394  strcpy(saved_jvm_path, buf);
2395}
2396
2397void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
2398  // no prefix required, not even "_"
2399}
2400
2401void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
2402  // no suffix required
2403}
2404
2405////////////////////////////////////////////////////////////////////////////////
2406// sun.misc.Signal support
2407
2408static volatile jint sigint_count = 0;
2409
2410static void
2411UserHandler(int sig, void *siginfo, void *context) {
2412  // 4511530 - sem_post is serialized and handled by the manager thread. When
2413  // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
2414  // don't want to flood the manager thread with sem_post requests.
2415  if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1)
2416      return;
2417
2418  // Ctrl-C is pressed during error reporting, likely because the error
2419  // handler fails to abort. Let VM die immediately.
2420  if (sig == SIGINT && is_error_reported()) {
2421     os::die();
2422  }
2423
2424  os::signal_notify(sig);
2425}
2426
2427void* os::user_handler() {
2428  return CAST_FROM_FN_PTR(void*, UserHandler);
2429}
2430
2431class Semaphore : public StackObj {
2432  public:
2433    Semaphore();
2434    ~Semaphore();
2435    void signal();
2436    void wait();
2437    bool trywait();
2438    bool timedwait(unsigned int sec, int nsec);
2439  private:
2440    sem_t _semaphore;
2441};
2442
2443Semaphore::Semaphore() {
2444  sem_init(&_semaphore, 0, 0);
2445}
2446
2447Semaphore::~Semaphore() {
2448  sem_destroy(&_semaphore);
2449}
2450
2451void Semaphore::signal() {
2452  sem_post(&_semaphore);
2453}
2454
2455void Semaphore::wait() {
2456  sem_wait(&_semaphore);
2457}
2458
2459bool Semaphore::trywait() {
2460  return sem_trywait(&_semaphore) == 0;
2461}
2462
2463bool Semaphore::timedwait(unsigned int sec, int nsec) {
2464
2465  struct timespec ts;
2466  // Semaphore's are always associated with CLOCK_REALTIME
2467  os::Linux::clock_gettime(CLOCK_REALTIME, &ts);
2468  // see unpackTime for discussion on overflow checking
2469  if (sec >= MAX_SECS) {
2470    ts.tv_sec += MAX_SECS;
2471    ts.tv_nsec = 0;
2472  } else {
2473    ts.tv_sec += sec;
2474    ts.tv_nsec += nsec;
2475    if (ts.tv_nsec >= NANOSECS_PER_SEC) {
2476      ts.tv_nsec -= NANOSECS_PER_SEC;
2477      ++ts.tv_sec; // note: this must be <= max_secs
2478    }
2479  }
2480
2481  while (1) {
2482    int result = sem_timedwait(&_semaphore, &ts);
2483    if (result == 0) {
2484      return true;
2485    } else if (errno == EINTR) {
2486      continue;
2487    } else if (errno == ETIMEDOUT) {
2488      return false;
2489    } else {
2490      return false;
2491    }
2492  }
2493}
2494
2495extern "C" {
2496  typedef void (*sa_handler_t)(int);
2497  typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
2498}
2499
2500void* os::signal(int signal_number, void* handler) {
2501  struct sigaction sigAct, oldSigAct;
2502
2503  sigfillset(&(sigAct.sa_mask));
2504  sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
2505  sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
2506
2507  if (sigaction(signal_number, &sigAct, &oldSigAct)) {
2508    // -1 means registration failed
2509    return (void *)-1;
2510  }
2511
2512  return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
2513}
2514
2515void os::signal_raise(int signal_number) {
2516  ::raise(signal_number);
2517}
2518
2519/*
2520 * The following code is moved from os.cpp for making this
2521 * code platform specific, which it is by its very nature.
2522 */
2523
2524// Will be modified when max signal is changed to be dynamic
2525int os::sigexitnum_pd() {
2526  return NSIG;
2527}
2528
2529// a counter for each possible signal value
2530static volatile jint pending_signals[NSIG+1] = { 0 };
2531
2532// Linux(POSIX) specific hand shaking semaphore.
2533static sem_t sig_sem;
2534static Semaphore sr_semaphore;
2535
2536void os::signal_init_pd() {
2537  // Initialize signal structures
2538  ::memset((void*)pending_signals, 0, sizeof(pending_signals));
2539
2540  // Initialize signal semaphore
2541  ::sem_init(&sig_sem, 0, 0);
2542}
2543
2544void os::signal_notify(int sig) {
2545  Atomic::inc(&pending_signals[sig]);
2546  ::sem_post(&sig_sem);
2547}
2548
2549static int check_pending_signals(bool wait) {
2550  Atomic::store(0, &sigint_count);
2551  for (;;) {
2552    for (int i = 0; i < NSIG + 1; i++) {
2553      jint n = pending_signals[i];
2554      if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
2555        return i;
2556      }
2557    }
2558    if (!wait) {
2559      return -1;
2560    }
2561    JavaThread *thread = JavaThread::current();
2562    ThreadBlockInVM tbivm(thread);
2563
2564    bool threadIsSuspended;
2565    do {
2566      thread->set_suspend_equivalent();
2567      // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
2568      ::sem_wait(&sig_sem);
2569
2570      // were we externally suspended while we were waiting?
2571      threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2572      if (threadIsSuspended) {
2573        //
2574        // The semaphore has been incremented, but while we were waiting
2575        // another thread suspended us. We don't want to continue running
2576        // while suspended because that would surprise the thread that
2577        // suspended us.
2578        //
2579        ::sem_post(&sig_sem);
2580
2581        thread->java_suspend_self();
2582      }
2583    } while (threadIsSuspended);
2584  }
2585}
2586
2587int os::signal_lookup() {
2588  return check_pending_signals(false);
2589}
2590
2591int os::signal_wait() {
2592  return check_pending_signals(true);
2593}
2594
2595////////////////////////////////////////////////////////////////////////////////
2596// Virtual Memory
2597
2598int os::vm_page_size() {
2599  // Seems redundant as all get out
2600  assert(os::Linux::page_size() != -1, "must call os::init");
2601  return os::Linux::page_size();
2602}
2603
2604// Solaris allocates memory by pages.
2605int os::vm_allocation_granularity() {
2606  assert(os::Linux::page_size() != -1, "must call os::init");
2607  return os::Linux::page_size();
2608}
2609
2610// Rationale behind this function:
2611//  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
2612//  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
2613//  samples for JITted code. Here we create private executable mapping over the code cache
2614//  and then we can use standard (well, almost, as mapping can change) way to provide
2615//  info for the reporting script by storing timestamp and location of symbol
2616void linux_wrap_code(char* base, size_t size) {
2617  static volatile jint cnt = 0;
2618
2619  if (!UseOprofile) {
2620    return;
2621  }
2622
2623  char buf[PATH_MAX+1];
2624  int num = Atomic::add(1, &cnt);
2625
2626  snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d",
2627           os::get_temp_directory(), os::current_process_id(), num);
2628  unlink(buf);
2629
2630  int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
2631
2632  if (fd != -1) {
2633    off_t rv = ::lseek(fd, size-2, SEEK_SET);
2634    if (rv != (off_t)-1) {
2635      if (::write(fd, "", 1) == 1) {
2636        mmap(base, size,
2637             PROT_READ|PROT_WRITE|PROT_EXEC,
2638             MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
2639      }
2640    }
2641    ::close(fd);
2642    unlink(buf);
2643  }
2644}
2645
2646static bool recoverable_mmap_error(int err) {
2647  // See if the error is one we can let the caller handle. This
2648  // list of errno values comes from JBS-6843484. I can't find a
2649  // Linux man page that documents this specific set of errno
2650  // values so while this list currently matches Solaris, it may
2651  // change as we gain experience with this failure mode.
2652  switch (err) {
2653  case EBADF:
2654  case EINVAL:
2655  case ENOTSUP:
2656    // let the caller deal with these errors
2657    return true;
2658
2659  default:
2660    // Any remaining errors on this OS can cause our reserved mapping
2661    // to be lost. That can cause confusion where different data
2662    // structures think they have the same memory mapped. The worst
2663    // scenario is if both the VM and a library think they have the
2664    // same memory mapped.
2665    return false;
2666  }
2667}
2668
2669static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
2670                                    int err) {
2671  warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2672          ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
2673          strerror(err), err);
2674}
2675
2676static void warn_fail_commit_memory(char* addr, size_t size,
2677                                    size_t alignment_hint, bool exec,
2678                                    int err) {
2679  warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2680          ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, size,
2681          alignment_hint, exec, strerror(err), err);
2682}
2683
2684// NOTE: Linux kernel does not really reserve the pages for us.
2685//       All it does is to check if there are enough free pages
2686//       left at the time of mmap(). This could be a potential
2687//       problem.
2688int os::Linux::commit_memory_impl(char* addr, size_t size, bool exec) {
2689  int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2690  uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2691                                   MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2692  if (res != (uintptr_t) MAP_FAILED) {
2693    if (UseNUMAInterleaving) {
2694      numa_make_global(addr, size);
2695    }
2696    return 0;
2697  }
2698
2699  int err = errno;  // save errno from mmap() call above
2700
2701  if (!recoverable_mmap_error(err)) {
2702    warn_fail_commit_memory(addr, size, exec, err);
2703    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "committing reserved memory.");
2704  }
2705
2706  return err;
2707}
2708
2709bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2710  return os::Linux::commit_memory_impl(addr, size, exec) == 0;
2711}
2712
2713void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
2714                                  const char* mesg) {
2715  assert(mesg != NULL, "mesg must be specified");
2716  int err = os::Linux::commit_memory_impl(addr, size, exec);
2717  if (err != 0) {
2718    // the caller wants all commit errors to exit with the specified mesg:
2719    warn_fail_commit_memory(addr, size, exec, err);
2720    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
2721  }
2722}
2723
2724// Define MAP_HUGETLB here so we can build HotSpot on old systems.
2725#ifndef MAP_HUGETLB
2726#define MAP_HUGETLB 0x40000
2727#endif
2728
2729// Define MADV_HUGEPAGE here so we can build HotSpot on old systems.
2730#ifndef MADV_HUGEPAGE
2731#define MADV_HUGEPAGE 14
2732#endif
2733
2734int os::Linux::commit_memory_impl(char* addr, size_t size,
2735                                  size_t alignment_hint, bool exec) {
2736  int err = os::Linux::commit_memory_impl(addr, size, exec);
2737  if (err == 0) {
2738    realign_memory(addr, size, alignment_hint);
2739  }
2740  return err;
2741}
2742
2743bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2744                          bool exec) {
2745  return os::Linux::commit_memory_impl(addr, size, alignment_hint, exec) == 0;
2746}
2747
2748void os::pd_commit_memory_or_exit(char* addr, size_t size,
2749                                  size_t alignment_hint, bool exec,
2750                                  const char* mesg) {
2751  assert(mesg != NULL, "mesg must be specified");
2752  int err = os::Linux::commit_memory_impl(addr, size, alignment_hint, exec);
2753  if (err != 0) {
2754    // the caller wants all commit errors to exit with the specified mesg:
2755    warn_fail_commit_memory(addr, size, alignment_hint, exec, err);
2756    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
2757  }
2758}
2759
2760void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2761  if (UseTransparentHugePages && alignment_hint > (size_t)vm_page_size()) {
2762    // We don't check the return value: madvise(MADV_HUGEPAGE) may not
2763    // be supported or the memory may already be backed by huge pages.
2764    ::madvise(addr, bytes, MADV_HUGEPAGE);
2765  }
2766}
2767
2768void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2769  // This method works by doing an mmap over an existing mmaping and effectively discarding
2770  // the existing pages. However it won't work for SHM-based large pages that cannot be
2771  // uncommitted at all. We don't do anything in this case to avoid creating a segment with
2772  // small pages on top of the SHM segment. This method always works for small pages, so we
2773  // allow that in any case.
2774  if (alignment_hint <= (size_t)os::vm_page_size() || can_commit_large_page_memory()) {
2775    commit_memory(addr, bytes, alignment_hint, !ExecMem);
2776  }
2777}
2778
2779void os::numa_make_global(char *addr, size_t bytes) {
2780  Linux::numa_interleave_memory(addr, bytes);
2781}
2782
2783// Define for numa_set_bind_policy(int). Setting the argument to 0 will set the
2784// bind policy to MPOL_PREFERRED for the current thread.
2785#define USE_MPOL_PREFERRED 0
2786
2787void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2788  // To make NUMA and large pages more robust when both enabled, we need to ease
2789  // the requirements on where the memory should be allocated. MPOL_BIND is the
2790  // default policy and it will force memory to be allocated on the specified
2791  // node. Changing this to MPOL_PREFERRED will prefer to allocate the memory on
2792  // the specified node, but will not force it. Using this policy will prevent
2793  // getting SIGBUS when trying to allocate large pages on NUMA nodes with no
2794  // free large pages.
2795  Linux::numa_set_bind_policy(USE_MPOL_PREFERRED);
2796  Linux::numa_tonode_memory(addr, bytes, lgrp_hint);
2797}
2798
2799bool os::numa_topology_changed()   { return false; }
2800
2801size_t os::numa_get_groups_num() {
2802  int max_node = Linux::numa_max_node();
2803  return max_node > 0 ? max_node + 1 : 1;
2804}
2805
2806int os::numa_get_group_id() {
2807  int cpu_id = Linux::sched_getcpu();
2808  if (cpu_id != -1) {
2809    int lgrp_id = Linux::get_node_by_cpu(cpu_id);
2810    if (lgrp_id != -1) {
2811      return lgrp_id;
2812    }
2813  }
2814  return 0;
2815}
2816
2817size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2818  for (size_t i = 0; i < size; i++) {
2819    ids[i] = i;
2820  }
2821  return size;
2822}
2823
2824bool os::get_page_info(char *start, page_info* info) {
2825  return false;
2826}
2827
2828char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {
2829  return end;
2830}
2831
2832
2833int os::Linux::sched_getcpu_syscall(void) {
2834  unsigned int cpu;
2835  int retval = -1;
2836
2837#if defined(IA32)
2838# ifndef SYS_getcpu
2839# define SYS_getcpu 318
2840# endif
2841  retval = syscall(SYS_getcpu, &cpu, NULL, NULL);
2842#elif defined(AMD64)
2843// Unfortunately we have to bring all these macros here from vsyscall.h
2844// to be able to compile on old linuxes.
2845# define __NR_vgetcpu 2
2846# define VSYSCALL_START (-10UL << 20)
2847# define VSYSCALL_SIZE 1024
2848# define VSYSCALL_ADDR(vsyscall_nr) (VSYSCALL_START+VSYSCALL_SIZE*(vsyscall_nr))
2849  typedef long (*vgetcpu_t)(unsigned int *cpu, unsigned int *node, unsigned long *tcache);
2850  vgetcpu_t vgetcpu = (vgetcpu_t)VSYSCALL_ADDR(__NR_vgetcpu);
2851  retval = vgetcpu(&cpu, NULL, NULL);
2852#endif
2853
2854  return (retval == -1) ? retval : cpu;
2855}
2856
2857// Something to do with the numa-aware allocator needs these symbols
2858extern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { }
2859extern "C" JNIEXPORT void numa_error(char *where) { }
2860extern "C" JNIEXPORT int fork1() { return fork(); }
2861
2862
2863// If we are running with libnuma version > 2, then we should
2864// be trying to use symbols with versions 1.1
2865// If we are running with earlier version, which did not have symbol versions,
2866// we should use the base version.
2867void* os::Linux::libnuma_dlsym(void* handle, const char *name) {
2868  void *f = dlvsym(handle, name, "libnuma_1.1");
2869  if (f == NULL) {
2870    f = dlsym(handle, name);
2871  }
2872  return f;
2873}
2874
2875bool os::Linux::libnuma_init() {
2876  // sched_getcpu() should be in libc.
2877  set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,
2878                                  dlsym(RTLD_DEFAULT, "sched_getcpu")));
2879
2880  // If it's not, try a direct syscall.
2881  if (sched_getcpu() == -1)
2882    set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, (void*)&sched_getcpu_syscall));
2883
2884  if (sched_getcpu() != -1) { // Does it work?
2885    void *handle = dlopen("libnuma.so.1", RTLD_LAZY);
2886    if (handle != NULL) {
2887      set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t,
2888                                           libnuma_dlsym(handle, "numa_node_to_cpus")));
2889      set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t,
2890                                       libnuma_dlsym(handle, "numa_max_node")));
2891      set_numa_available(CAST_TO_FN_PTR(numa_available_func_t,
2892                                        libnuma_dlsym(handle, "numa_available")));
2893      set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t,
2894                                            libnuma_dlsym(handle, "numa_tonode_memory")));
2895      set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t,
2896                                            libnuma_dlsym(handle, "numa_interleave_memory")));
2897      set_numa_set_bind_policy(CAST_TO_FN_PTR(numa_set_bind_policy_func_t,
2898                                            libnuma_dlsym(handle, "numa_set_bind_policy")));
2899
2900
2901      if (numa_available() != -1) {
2902        set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes"));
2903        // Create a cpu -> node mapping
2904        _cpu_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, true);
2905        rebuild_cpu_to_node_map();
2906        return true;
2907      }
2908    }
2909  }
2910  return false;
2911}
2912
2913// rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id.
2914// The table is later used in get_node_by_cpu().
2915void os::Linux::rebuild_cpu_to_node_map() {
2916  const size_t NCPUS = 32768; // Since the buffer size computation is very obscure
2917                              // in libnuma (possible values are starting from 16,
2918                              // and continuing up with every other power of 2, but less
2919                              // than the maximum number of CPUs supported by kernel), and
2920                              // is a subject to change (in libnuma version 2 the requirements
2921                              // are more reasonable) we'll just hardcode the number they use
2922                              // in the library.
2923  const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;
2924
2925  size_t cpu_num = os::active_processor_count();
2926  size_t cpu_map_size = NCPUS / BitsPerCLong;
2927  size_t cpu_map_valid_size =
2928    MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);
2929
2930  cpu_to_node()->clear();
2931  cpu_to_node()->at_grow(cpu_num - 1);
2932  size_t node_num = numa_get_groups_num();
2933
2934  unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal);
2935  for (size_t i = 0; i < node_num; i++) {
2936    if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) {
2937      for (size_t j = 0; j < cpu_map_valid_size; j++) {
2938        if (cpu_map[j] != 0) {
2939          for (size_t k = 0; k < BitsPerCLong; k++) {
2940            if (cpu_map[j] & (1UL << k)) {
2941              cpu_to_node()->at_put(j * BitsPerCLong + k, i);
2942            }
2943          }
2944        }
2945      }
2946    }
2947  }
2948  FREE_C_HEAP_ARRAY(unsigned long, cpu_map, mtInternal);
2949}
2950
2951int os::Linux::get_node_by_cpu(int cpu_id) {
2952  if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) {
2953    return cpu_to_node()->at(cpu_id);
2954  }
2955  return -1;
2956}
2957
2958GrowableArray<int>* os::Linux::_cpu_to_node;
2959os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu;
2960os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus;
2961os::Linux::numa_max_node_func_t os::Linux::_numa_max_node;
2962os::Linux::numa_available_func_t os::Linux::_numa_available;
2963os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory;
2964os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory;
2965os::Linux::numa_set_bind_policy_func_t os::Linux::_numa_set_bind_policy;
2966unsigned long* os::Linux::_numa_all_nodes;
2967
2968bool os::pd_uncommit_memory(char* addr, size_t size) {
2969  uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
2970                MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
2971  return res  != (uintptr_t) MAP_FAILED;
2972}
2973
2974static
2975address get_stack_commited_bottom(address bottom, size_t size) {
2976  address nbot = bottom;
2977  address ntop = bottom + size;
2978
2979  size_t page_sz = os::vm_page_size();
2980  unsigned pages = size / page_sz;
2981
2982  unsigned char vec[1];
2983  unsigned imin = 1, imax = pages + 1, imid;
2984  int mincore_return_value = 0;
2985
2986  assert(imin <= imax, "Unexpected page size");
2987
2988  while (imin < imax) {
2989    imid = (imax + imin) / 2;
2990    nbot = ntop - (imid * page_sz);
2991
2992    // Use a trick with mincore to check whether the page is mapped or not.
2993    // mincore sets vec to 1 if page resides in memory and to 0 if page
2994    // is swapped output but if page we are asking for is unmapped
2995    // it returns -1,ENOMEM
2996    mincore_return_value = mincore(nbot, page_sz, vec);
2997
2998    if (mincore_return_value == -1) {
2999      // Page is not mapped go up
3000      // to find first mapped page
3001      if (errno != EAGAIN) {
3002        assert(errno == ENOMEM, "Unexpected mincore errno");
3003        imax = imid;
3004      }
3005    } else {
3006      // Page is mapped go down
3007      // to find first not mapped page
3008      imin = imid + 1;
3009    }
3010  }
3011
3012  nbot = nbot + page_sz;
3013
3014  // Adjust stack bottom one page up if last checked page is not mapped
3015  if (mincore_return_value == -1) {
3016    nbot = nbot + page_sz;
3017  }
3018
3019  return nbot;
3020}
3021
3022
3023// Linux uses a growable mapping for the stack, and if the mapping for
3024// the stack guard pages is not removed when we detach a thread the
3025// stack cannot grow beyond the pages where the stack guard was
3026// mapped.  If at some point later in the process the stack expands to
3027// that point, the Linux kernel cannot expand the stack any further
3028// because the guard pages are in the way, and a segfault occurs.
3029//
3030// However, it's essential not to split the stack region by unmapping
3031// a region (leaving a hole) that's already part of the stack mapping,
3032// so if the stack mapping has already grown beyond the guard pages at
3033// the time we create them, we have to truncate the stack mapping.
3034// So, we need to know the extent of the stack mapping when
3035// create_stack_guard_pages() is called.
3036
3037// We only need this for stacks that are growable: at the time of
3038// writing thread stacks don't use growable mappings (i.e. those
3039// creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this
3040// only applies to the main thread.
3041
3042// If the (growable) stack mapping already extends beyond the point
3043// where we're going to put our guard pages, truncate the mapping at
3044// that point by munmap()ping it.  This ensures that when we later
3045// munmap() the guard pages we don't leave a hole in the stack
3046// mapping. This only affects the main/initial thread
3047
3048bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
3049
3050  if (os::Linux::is_initial_thread()) {
3051    // As we manually grow stack up to bottom inside create_attached_thread(),
3052    // it's likely that os::Linux::initial_thread_stack_bottom is mapped and
3053    // we don't need to do anything special.
3054    // Check it first, before calling heavy function.
3055    uintptr_t stack_extent = (uintptr_t) os::Linux::initial_thread_stack_bottom();
3056    unsigned char vec[1];
3057
3058    if (mincore((address)stack_extent, os::vm_page_size(), vec) == -1) {
3059      // Fallback to slow path on all errors, including EAGAIN
3060      stack_extent = (uintptr_t) get_stack_commited_bottom(
3061                                    os::Linux::initial_thread_stack_bottom(),
3062                                    (size_t)addr - stack_extent);
3063    }
3064
3065    if (stack_extent < (uintptr_t)addr) {
3066      ::munmap((void*)stack_extent, (uintptr_t)(addr - stack_extent));
3067    }
3068  }
3069
3070  return os::commit_memory(addr, size, !ExecMem);
3071}
3072
3073// If this is a growable mapping, remove the guard pages entirely by
3074// munmap()ping them.  If not, just call uncommit_memory(). This only
3075// affects the main/initial thread, but guard against future OS changes
3076// It's safe to always unmap guard pages for initial thread because we
3077// always place it right after end of the mapped region
3078
3079bool os::remove_stack_guard_pages(char* addr, size_t size) {
3080  uintptr_t stack_extent, stack_base;
3081
3082  if (os::Linux::is_initial_thread()) {
3083    return ::munmap(addr, size) == 0;
3084  }
3085
3086  return os::uncommit_memory(addr, size);
3087}
3088
3089static address _highest_vm_reserved_address = NULL;
3090
3091// If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
3092// at 'requested_addr'. If there are existing memory mappings at the same
3093// location, however, they will be overwritten. If 'fixed' is false,
3094// 'requested_addr' is only treated as a hint, the return value may or
3095// may not start from the requested address. Unlike Linux mmap(), this
3096// function returns NULL to indicate failure.
3097static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
3098  char * addr;
3099  int flags;
3100
3101  flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
3102  if (fixed) {
3103    assert((uintptr_t)requested_addr % os::Linux::page_size() == 0, "unaligned address");
3104    flags |= MAP_FIXED;
3105  }
3106
3107  // Map reserved/uncommitted pages PROT_NONE so we fail early if we
3108  // touch an uncommitted page. Otherwise, the read/write might
3109  // succeed if we have enough swap space to back the physical page.
3110  addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
3111                       flags, -1, 0);
3112
3113  if (addr != MAP_FAILED) {
3114    // anon_mmap() should only get called during VM initialization,
3115    // don't need lock (actually we can skip locking even it can be called
3116    // from multiple threads, because _highest_vm_reserved_address is just a
3117    // hint about the upper limit of non-stack memory regions.)
3118    if ((address)addr + bytes > _highest_vm_reserved_address) {
3119      _highest_vm_reserved_address = (address)addr + bytes;
3120    }
3121  }
3122
3123  return addr == MAP_FAILED ? NULL : addr;
3124}
3125
3126// Don't update _highest_vm_reserved_address, because there might be memory
3127// regions above addr + size. If so, releasing a memory region only creates
3128// a hole in the address space, it doesn't help prevent heap-stack collision.
3129//
3130static int anon_munmap(char * addr, size_t size) {
3131  return ::munmap(addr, size) == 0;
3132}
3133
3134char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
3135                         size_t alignment_hint) {
3136  return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
3137}
3138
3139bool os::pd_release_memory(char* addr, size_t size) {
3140  return anon_munmap(addr, size);
3141}
3142
3143static address highest_vm_reserved_address() {
3144  return _highest_vm_reserved_address;
3145}
3146
3147static bool linux_mprotect(char* addr, size_t size, int prot) {
3148  // Linux wants the mprotect address argument to be page aligned.
3149  char* bottom = (char*)align_size_down((intptr_t)addr, os::Linux::page_size());
3150
3151  // According to SUSv3, mprotect() should only be used with mappings
3152  // established by mmap(), and mmap() always maps whole pages. Unaligned
3153  // 'addr' likely indicates problem in the VM (e.g. trying to change
3154  // protection of malloc'ed or statically allocated memory). Check the
3155  // caller if you hit this assert.
3156  assert(addr == bottom, "sanity check");
3157
3158  size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size());
3159  return ::mprotect(bottom, size, prot) == 0;
3160}
3161
3162// Set protections specified
3163bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
3164                        bool is_committed) {
3165  unsigned int p = 0;
3166  switch (prot) {
3167  case MEM_PROT_NONE: p = PROT_NONE; break;
3168  case MEM_PROT_READ: p = PROT_READ; break;
3169  case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
3170  case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
3171  default:
3172    ShouldNotReachHere();
3173  }
3174  // is_committed is unused.
3175  return linux_mprotect(addr, bytes, p);
3176}
3177
3178bool os::guard_memory(char* addr, size_t size) {
3179  return linux_mprotect(addr, size, PROT_NONE);
3180}
3181
3182bool os::unguard_memory(char* addr, size_t size) {
3183  return linux_mprotect(addr, size, PROT_READ|PROT_WRITE);
3184}
3185
3186bool os::Linux::transparent_huge_pages_sanity_check(bool warn, size_t page_size) {
3187  bool result = false;
3188  void *p = mmap(NULL, page_size * 2, PROT_READ|PROT_WRITE,
3189                 MAP_ANONYMOUS|MAP_PRIVATE,
3190                 -1, 0);
3191  if (p != MAP_FAILED) {
3192    void *aligned_p = align_ptr_up(p, page_size);
3193
3194    result = madvise(aligned_p, page_size, MADV_HUGEPAGE) == 0;
3195
3196    munmap(p, page_size * 2);
3197  }
3198
3199  if (warn && !result) {
3200    warning("TransparentHugePages is not supported by the operating system.");
3201  }
3202
3203  return result;
3204}
3205
3206bool os::Linux::hugetlbfs_sanity_check(bool warn, size_t page_size) {
3207  bool result = false;
3208  void *p = mmap(NULL, page_size, PROT_READ|PROT_WRITE,
3209                 MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB,
3210                 -1, 0);
3211
3212  if (p != MAP_FAILED) {
3213    // We don't know if this really is a huge page or not.
3214    FILE *fp = fopen("/proc/self/maps", "r");
3215    if (fp) {
3216      while (!feof(fp)) {
3217        char chars[257];
3218        long x = 0;
3219        if (fgets(chars, sizeof(chars), fp)) {
3220          if (sscanf(chars, "%lx-%*x", &x) == 1
3221              && x == (long)p) {
3222            if (strstr (chars, "hugepage")) {
3223              result = true;
3224              break;
3225            }
3226          }
3227        }
3228      }
3229      fclose(fp);
3230    }
3231    munmap(p, page_size);
3232  }
3233
3234  if (warn && !result) {
3235    warning("HugeTLBFS is not supported by the operating system.");
3236  }
3237
3238  return result;
3239}
3240
3241/*
3242* Set the coredump_filter bits to include largepages in core dump (bit 6)
3243*
3244* From the coredump_filter documentation:
3245*
3246* - (bit 0) anonymous private memory
3247* - (bit 1) anonymous shared memory
3248* - (bit 2) file-backed private memory
3249* - (bit 3) file-backed shared memory
3250* - (bit 4) ELF header pages in file-backed private memory areas (it is
3251*           effective only if the bit 2 is cleared)
3252* - (bit 5) hugetlb private memory
3253* - (bit 6) hugetlb shared memory
3254*/
3255static void set_coredump_filter(void) {
3256  FILE *f;
3257  long cdm;
3258
3259  if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) {
3260    return;
3261  }
3262
3263  if (fscanf(f, "%lx", &cdm) != 1) {
3264    fclose(f);
3265    return;
3266  }
3267
3268  rewind(f);
3269
3270  if ((cdm & LARGEPAGES_BIT) == 0) {
3271    cdm |= LARGEPAGES_BIT;
3272    fprintf(f, "%#lx", cdm);
3273  }
3274
3275  fclose(f);
3276}
3277
3278// Large page support
3279
3280static size_t _large_page_size = 0;
3281
3282size_t os::Linux::find_large_page_size() {
3283  size_t large_page_size = 0;
3284
3285  // large_page_size on Linux is used to round up heap size. x86 uses either
3286  // 2M or 4M page, depending on whether PAE (Physical Address Extensions)
3287  // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use
3288  // page as large as 256M.
3289  //
3290  // Here we try to figure out page size by parsing /proc/meminfo and looking
3291  // for a line with the following format:
3292  //    Hugepagesize:     2048 kB
3293  //
3294  // If we can't determine the value (e.g. /proc is not mounted, or the text
3295  // format has been changed), we'll use the largest page size supported by
3296  // the processor.
3297
3298#ifndef ZERO
3299  large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M)
3300                     ARM_ONLY(2 * M) PPC_ONLY(4 * M);
3301#endif // ZERO
3302
3303  FILE *fp = fopen("/proc/meminfo", "r");
3304  if (fp) {
3305    while (!feof(fp)) {
3306      int x = 0;
3307      char buf[16];
3308      if (fscanf(fp, "Hugepagesize: %d", &x) == 1) {
3309        if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) {
3310          large_page_size = x * K;
3311          break;
3312        }
3313      } else {
3314        // skip to next line
3315        for (;;) {
3316          int ch = fgetc(fp);
3317          if (ch == EOF || ch == (int)'\n') break;
3318        }
3319      }
3320    }
3321    fclose(fp);
3322  }
3323
3324  if (!FLAG_IS_DEFAULT(LargePageSizeInBytes) && LargePageSizeInBytes != large_page_size) {
3325    warning("Setting LargePageSizeInBytes has no effect on this OS. Large page size is "
3326        SIZE_FORMAT "%s.", byte_size_in_proper_unit(large_page_size),
3327        proper_unit_for_byte_size(large_page_size));
3328  }
3329
3330  return large_page_size;
3331}
3332
3333size_t os::Linux::setup_large_page_size() {
3334  _large_page_size = Linux::find_large_page_size();
3335  const size_t default_page_size = (size_t)Linux::page_size();
3336  if (_large_page_size > default_page_size) {
3337    _page_sizes[0] = _large_page_size;
3338    _page_sizes[1] = default_page_size;
3339    _page_sizes[2] = 0;
3340  }
3341
3342  return _large_page_size;
3343}
3344
3345bool os::Linux::setup_large_page_type(size_t page_size) {
3346  if (FLAG_IS_DEFAULT(UseHugeTLBFS) &&
3347      FLAG_IS_DEFAULT(UseSHM) &&
3348      FLAG_IS_DEFAULT(UseTransparentHugePages)) {
3349
3350    // The type of large pages has not been specified by the user.
3351
3352    // Try UseHugeTLBFS and then UseSHM.
3353    UseHugeTLBFS = UseSHM = true;
3354
3355    // Don't try UseTransparentHugePages since there are known
3356    // performance issues with it turned on. This might change in the future.
3357    UseTransparentHugePages = false;
3358  }
3359
3360  if (UseTransparentHugePages) {
3361    bool warn_on_failure = !FLAG_IS_DEFAULT(UseTransparentHugePages);
3362    if (transparent_huge_pages_sanity_check(warn_on_failure, page_size)) {
3363      UseHugeTLBFS = false;
3364      UseSHM = false;
3365      return true;
3366    }
3367    UseTransparentHugePages = false;
3368  }
3369
3370  if (UseHugeTLBFS) {
3371    bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS);
3372    if (hugetlbfs_sanity_check(warn_on_failure, page_size)) {
3373      UseSHM = false;
3374      return true;
3375    }
3376    UseHugeTLBFS = false;
3377  }
3378
3379  return UseSHM;
3380}
3381
3382void os::large_page_init() {
3383  if (!UseLargePages &&
3384      !UseTransparentHugePages &&
3385      !UseHugeTLBFS &&
3386      !UseSHM) {
3387    // Not using large pages.
3388    return;
3389  }
3390
3391  if (!FLAG_IS_DEFAULT(UseLargePages) && !UseLargePages) {
3392    // The user explicitly turned off large pages.
3393    // Ignore the rest of the large pages flags.
3394    UseTransparentHugePages = false;
3395    UseHugeTLBFS = false;
3396    UseSHM = false;
3397    return;
3398  }
3399
3400  size_t large_page_size = Linux::setup_large_page_size();
3401  UseLargePages          = Linux::setup_large_page_type(large_page_size);
3402
3403  set_coredump_filter();
3404}
3405
3406#ifndef SHM_HUGETLB
3407#define SHM_HUGETLB 04000
3408#endif
3409
3410char* os::Linux::reserve_memory_special_shm(size_t bytes, size_t alignment, char* req_addr, bool exec) {
3411  // "exec" is passed in but not used.  Creating the shared image for
3412  // the code cache doesn't have an SHM_X executable permission to check.
3413  assert(UseLargePages && UseSHM, "only for SHM large pages");
3414  assert(is_ptr_aligned(req_addr, os::large_page_size()), "Unaligned address");
3415
3416  if (!is_size_aligned(bytes, os::large_page_size()) || alignment > os::large_page_size()) {
3417    return NULL; // Fallback to small pages.
3418  }
3419
3420  key_t key = IPC_PRIVATE;
3421  char *addr;
3422
3423  bool warn_on_failure = UseLargePages &&
3424                        (!FLAG_IS_DEFAULT(UseLargePages) ||
3425                         !FLAG_IS_DEFAULT(UseSHM) ||
3426                         !FLAG_IS_DEFAULT(LargePageSizeInBytes)
3427                        );
3428  char msg[128];
3429
3430  // Create a large shared memory region to attach to based on size.
3431  // Currently, size is the total size of the heap
3432  int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
3433  if (shmid == -1) {
3434     // Possible reasons for shmget failure:
3435     // 1. shmmax is too small for Java heap.
3436     //    > check shmmax value: cat /proc/sys/kernel/shmmax
3437     //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
3438     // 2. not enough large page memory.
3439     //    > check available large pages: cat /proc/meminfo
3440     //    > increase amount of large pages:
3441     //          echo new_value > /proc/sys/vm/nr_hugepages
3442     //      Note 1: different Linux may use different name for this property,
3443     //            e.g. on Redhat AS-3 it is "hugetlb_pool".
3444     //      Note 2: it's possible there's enough physical memory available but
3445     //            they are so fragmented after a long run that they can't
3446     //            coalesce into large pages. Try to reserve large pages when
3447     //            the system is still "fresh".
3448     if (warn_on_failure) {
3449       jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
3450       warning(msg);
3451     }
3452     return NULL;
3453  }
3454
3455  // attach to the region
3456  addr = (char*)shmat(shmid, req_addr, 0);
3457  int err = errno;
3458
3459  // Remove shmid. If shmat() is successful, the actual shared memory segment
3460  // will be deleted when it's detached by shmdt() or when the process
3461  // terminates. If shmat() is not successful this will remove the shared
3462  // segment immediately.
3463  shmctl(shmid, IPC_RMID, NULL);
3464
3465  if ((intptr_t)addr == -1) {
3466     if (warn_on_failure) {
3467       jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
3468       warning(msg);
3469     }
3470     return NULL;
3471  }
3472
3473  return addr;
3474}
3475
3476static void warn_on_large_pages_failure(char* req_addr, size_t bytes, int error) {
3477  assert(error == ENOMEM, "Only expect to fail if no memory is available");
3478
3479  bool warn_on_failure = UseLargePages &&
3480      (!FLAG_IS_DEFAULT(UseLargePages) ||
3481       !FLAG_IS_DEFAULT(UseHugeTLBFS) ||
3482       !FLAG_IS_DEFAULT(LargePageSizeInBytes));
3483
3484  if (warn_on_failure) {
3485    char msg[128];
3486    jio_snprintf(msg, sizeof(msg), "Failed to reserve large pages memory req_addr: "
3487        PTR_FORMAT " bytes: " SIZE_FORMAT " (errno = %d).", req_addr, bytes, error);
3488    warning(msg);
3489  }
3490}
3491
3492char* os::Linux::reserve_memory_special_huge_tlbfs_only(size_t bytes, char* req_addr, bool exec) {
3493  assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages");
3494  assert(is_size_aligned(bytes, os::large_page_size()), "Unaligned size");
3495  assert(is_ptr_aligned(req_addr, os::large_page_size()), "Unaligned address");
3496
3497  int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
3498  char* addr = (char*)::mmap(req_addr, bytes, prot,
3499                             MAP_PRIVATE|MAP_ANONYMOUS|MAP_HUGETLB,
3500                             -1, 0);
3501
3502  if (addr == MAP_FAILED) {
3503    warn_on_large_pages_failure(req_addr, bytes, errno);
3504    return NULL;
3505  }
3506
3507  assert(is_ptr_aligned(addr, os::large_page_size()), "Must be");
3508
3509  return addr;
3510}
3511
3512char* os::Linux::reserve_memory_special_huge_tlbfs_mixed(size_t bytes, size_t alignment, char* req_addr, bool exec) {
3513  size_t large_page_size = os::large_page_size();
3514
3515  assert(bytes >= large_page_size, "Shouldn't allocate large pages for small sizes");
3516
3517  // Allocate small pages.
3518
3519  char* start;
3520  if (req_addr != NULL) {
3521    assert(is_ptr_aligned(req_addr, alignment), "Must be");
3522    assert(is_size_aligned(bytes, alignment), "Must be");
3523    start = os::reserve_memory(bytes, req_addr);
3524    assert(start == NULL || start == req_addr, "Must be");
3525  } else {
3526    start = os::reserve_memory_aligned(bytes, alignment);
3527  }
3528
3529  if (start == NULL) {
3530    return NULL;
3531  }
3532
3533  assert(is_ptr_aligned(start, alignment), "Must be");
3534
3535  // os::reserve_memory_special will record this memory area.
3536  // Need to release it here to prevent overlapping reservations.
3537  MemTracker::record_virtual_memory_release((address)start, bytes);
3538
3539  char* end = start + bytes;
3540
3541  // Find the regions of the allocated chunk that can be promoted to large pages.
3542  char* lp_start = (char*)align_ptr_up(start, large_page_size);
3543  char* lp_end   = (char*)align_ptr_down(end, large_page_size);
3544
3545  size_t lp_bytes = lp_end - lp_start;
3546
3547  assert(is_size_aligned(lp_bytes, large_page_size), "Must be");
3548
3549  if (lp_bytes == 0) {
3550    // The mapped region doesn't even span the start and the end of a large page.
3551    // Fall back to allocate a non-special area.
3552    ::munmap(start, end - start);
3553    return NULL;
3554  }
3555
3556  int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
3557
3558
3559  void* result;
3560
3561  if (start != lp_start) {
3562    result = ::mmap(start, lp_start - start, prot,
3563                    MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED,
3564                    -1, 0);
3565    if (result == MAP_FAILED) {
3566      ::munmap(lp_start, end - lp_start);
3567      return NULL;
3568    }
3569  }
3570
3571  result = ::mmap(lp_start, lp_bytes, prot,
3572                  MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED|MAP_HUGETLB,
3573                  -1, 0);
3574  if (result == MAP_FAILED) {
3575    warn_on_large_pages_failure(req_addr, bytes, errno);
3576    // If the mmap above fails, the large pages region will be unmapped and we
3577    // have regions before and after with small pages. Release these regions.
3578    //
3579    // |  mapped  |  unmapped  |  mapped  |
3580    // ^          ^            ^          ^
3581    // start      lp_start     lp_end     end
3582    //
3583    ::munmap(start, lp_start - start);
3584    ::munmap(lp_end, end - lp_end);
3585    return NULL;
3586  }
3587
3588  if (lp_end != end) {
3589      result = ::mmap(lp_end, end - lp_end, prot,
3590                      MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED,
3591                      -1, 0);
3592    if (result == MAP_FAILED) {
3593      ::munmap(start, lp_end - start);
3594      return NULL;
3595    }
3596  }
3597
3598  return start;
3599}
3600
3601char* os::Linux::reserve_memory_special_huge_tlbfs(size_t bytes, size_t alignment, char* req_addr, bool exec) {
3602  assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages");
3603  assert(is_ptr_aligned(req_addr, alignment), "Must be");
3604  assert(is_power_of_2(alignment), "Must be");
3605  assert(is_power_of_2(os::large_page_size()), "Must be");
3606  assert(bytes >= os::large_page_size(), "Shouldn't allocate large pages for small sizes");
3607
3608  if (is_size_aligned(bytes, os::large_page_size()) && alignment <= os::large_page_size()) {
3609    return reserve_memory_special_huge_tlbfs_only(bytes, req_addr, exec);
3610  } else {
3611    return reserve_memory_special_huge_tlbfs_mixed(bytes, alignment, req_addr, exec);
3612  }
3613}
3614
3615char* os::reserve_memory_special(size_t bytes, size_t alignment, char* req_addr, bool exec) {
3616  assert(UseLargePages, "only for large pages");
3617
3618  char* addr;
3619  if (UseSHM) {
3620    addr = os::Linux::reserve_memory_special_shm(bytes, alignment, req_addr, exec);
3621  } else {
3622    assert(UseHugeTLBFS, "must be");
3623    addr = os::Linux::reserve_memory_special_huge_tlbfs(bytes, alignment, req_addr, exec);
3624  }
3625
3626  if (addr != NULL) {
3627    if (UseNUMAInterleaving) {
3628      numa_make_global(addr, bytes);
3629    }
3630
3631    // The memory is committed
3632    MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, mtNone, CALLER_PC);
3633  }
3634
3635  return addr;
3636}
3637
3638bool os::Linux::release_memory_special_shm(char* base, size_t bytes) {
3639  // detaching the SHM segment will also delete it, see reserve_memory_special_shm()
3640  return shmdt(base) == 0;
3641}
3642
3643bool os::Linux::release_memory_special_huge_tlbfs(char* base, size_t bytes) {
3644  return pd_release_memory(base, bytes);
3645}
3646
3647bool os::release_memory_special(char* base, size_t bytes) {
3648  assert(UseLargePages, "only for large pages");
3649
3650  MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
3651
3652  bool res;
3653  if (UseSHM) {
3654    res = os::Linux::release_memory_special_shm(base, bytes);
3655  } else {
3656    assert(UseHugeTLBFS, "must be");
3657    res = os::Linux::release_memory_special_huge_tlbfs(base, bytes);
3658  }
3659
3660  if (res) {
3661    tkr.record((address)base, bytes);
3662  } else {
3663    tkr.discard();
3664  }
3665
3666  return res;
3667}
3668
3669size_t os::large_page_size() {
3670  return _large_page_size;
3671}
3672
3673// With SysV SHM the entire memory region must be allocated as shared
3674// memory.
3675// HugeTLBFS allows application to commit large page memory on demand.
3676// However, when committing memory with HugeTLBFS fails, the region
3677// that was supposed to be committed will lose the old reservation
3678// and allow other threads to steal that memory region. Because of this
3679// behavior we can't commit HugeTLBFS memory.
3680bool os::can_commit_large_page_memory() {
3681  return UseTransparentHugePages;
3682}
3683
3684bool os::can_execute_large_page_memory() {
3685  return UseTransparentHugePages || UseHugeTLBFS;
3686}
3687
3688// Reserve memory at an arbitrary address, only if that area is
3689// available (and not reserved for something else).
3690
3691char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
3692  const int max_tries = 10;
3693  char* base[max_tries];
3694  size_t size[max_tries];
3695  const size_t gap = 0x000000;
3696
3697  // Assert only that the size is a multiple of the page size, since
3698  // that's all that mmap requires, and since that's all we really know
3699  // about at this low abstraction level.  If we need higher alignment,
3700  // we can either pass an alignment to this method or verify alignment
3701  // in one of the methods further up the call chain.  See bug 5044738.
3702  assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
3703
3704  // Repeatedly allocate blocks until the block is allocated at the
3705  // right spot. Give up after max_tries. Note that reserve_memory() will
3706  // automatically update _highest_vm_reserved_address if the call is
3707  // successful. The variable tracks the highest memory address every reserved
3708  // by JVM. It is used to detect heap-stack collision if running with
3709  // fixed-stack LinuxThreads. Because here we may attempt to reserve more
3710  // space than needed, it could confuse the collision detecting code. To
3711  // solve the problem, save current _highest_vm_reserved_address and
3712  // calculate the correct value before return.
3713  address old_highest = _highest_vm_reserved_address;
3714
3715  // Linux mmap allows caller to pass an address as hint; give it a try first,
3716  // if kernel honors the hint then we can return immediately.
3717  char * addr = anon_mmap(requested_addr, bytes, false);
3718  if (addr == requested_addr) {
3719     return requested_addr;
3720  }
3721
3722  if (addr != NULL) {
3723     // mmap() is successful but it fails to reserve at the requested address
3724     anon_munmap(addr, bytes);
3725  }
3726
3727  int i;
3728  for (i = 0; i < max_tries; ++i) {
3729    base[i] = reserve_memory(bytes);
3730
3731    if (base[i] != NULL) {
3732      // Is this the block we wanted?
3733      if (base[i] == requested_addr) {
3734        size[i] = bytes;
3735        break;
3736      }
3737
3738      // Does this overlap the block we wanted? Give back the overlapped
3739      // parts and try again.
3740
3741      size_t top_overlap = requested_addr + (bytes + gap) - base[i];
3742      if (top_overlap >= 0 && top_overlap < bytes) {
3743        unmap_memory(base[i], top_overlap);
3744        base[i] += top_overlap;
3745        size[i] = bytes - top_overlap;
3746      } else {
3747        size_t bottom_overlap = base[i] + bytes - requested_addr;
3748        if (bottom_overlap >= 0 && bottom_overlap < bytes) {
3749          unmap_memory(requested_addr, bottom_overlap);
3750          size[i] = bytes - bottom_overlap;
3751        } else {
3752          size[i] = bytes;
3753        }
3754      }
3755    }
3756  }
3757
3758  // Give back the unused reserved pieces.
3759
3760  for (int j = 0; j < i; ++j) {
3761    if (base[j] != NULL) {
3762      unmap_memory(base[j], size[j]);
3763    }
3764  }
3765
3766  if (i < max_tries) {
3767    _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes);
3768    return requested_addr;
3769  } else {
3770    _highest_vm_reserved_address = old_highest;
3771    return NULL;
3772  }
3773}
3774
3775size_t os::read(int fd, void *buf, unsigned int nBytes) {
3776  return ::read(fd, buf, nBytes);
3777}
3778
3779//
3780// Short sleep, direct OS call.
3781//
3782// Note: certain versions of Linux CFS scheduler (since 2.6.23) do not guarantee
3783// sched_yield(2) will actually give up the CPU:
3784//
3785//   * Alone on this pariticular CPU, keeps running.
3786//   * Before the introduction of "skip_buddy" with "compat_yield" disabled
3787//     (pre 2.6.39).
3788//
3789// So calling this with 0 is an alternative.
3790//
3791void os::naked_short_sleep(jlong ms) {
3792  struct timespec req;
3793
3794  assert(ms < 1000, "Un-interruptable sleep, short time use only");
3795  req.tv_sec = 0;
3796  if (ms > 0) {
3797    req.tv_nsec = (ms % 1000) * 1000000;
3798  }
3799  else {
3800    req.tv_nsec = 1;
3801  }
3802
3803  nanosleep(&req, NULL);
3804
3805  return;
3806}
3807
3808// Sleep forever; naked call to OS-specific sleep; use with CAUTION
3809void os::infinite_sleep() {
3810  while (true) {    // sleep forever ...
3811    ::sleep(100);   // ... 100 seconds at a time
3812  }
3813}
3814
3815// Used to convert frequent JVM_Yield() to nops
3816bool os::dont_yield() {
3817  return DontYieldALot;
3818}
3819
3820void os::yield() {
3821  sched_yield();
3822}
3823
3824os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;}
3825
3826void os::yield_all(int attempts) {
3827  // Yields to all threads, including threads with lower priorities
3828  // Threads on Linux are all with same priority. The Solaris style
3829  // os::yield_all() with nanosleep(1ms) is not necessary.
3830  sched_yield();
3831}
3832
3833// Called from the tight loops to possibly influence time-sharing heuristics
3834void os::loop_breaker(int attempts) {
3835  os::yield_all(attempts);
3836}
3837
3838////////////////////////////////////////////////////////////////////////////////
3839// thread priority support
3840
3841// Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER
3842// only supports dynamic priority, static priority must be zero. For real-time
3843// applications, Linux supports SCHED_RR which allows static priority (1-99).
3844// However, for large multi-threaded applications, SCHED_RR is not only slower
3845// than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
3846// of 5 runs - Sep 2005).
3847//
3848// The following code actually changes the niceness of kernel-thread/LWP. It
3849// has an assumption that setpriority() only modifies one kernel-thread/LWP,
3850// not the entire user process, and user level threads are 1:1 mapped to kernel
3851// threads. It has always been the case, but could change in the future. For
3852// this reason, the code should not be used as default (ThreadPriorityPolicy=0).
3853// It is only used when ThreadPriorityPolicy=1 and requires root privilege.
3854
3855int os::java_to_os_priority[CriticalPriority + 1] = {
3856  19,              // 0 Entry should never be used
3857
3858   4,              // 1 MinPriority
3859   3,              // 2
3860   2,              // 3
3861
3862   1,              // 4
3863   0,              // 5 NormPriority
3864  -1,              // 6
3865
3866  -2,              // 7
3867  -3,              // 8
3868  -4,              // 9 NearMaxPriority
3869
3870  -5,              // 10 MaxPriority
3871
3872  -5               // 11 CriticalPriority
3873};
3874
3875static int prio_init() {
3876  if (ThreadPriorityPolicy == 1) {
3877    // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
3878    // if effective uid is not root. Perhaps, a more elegant way of doing
3879    // this is to test CAP_SYS_NICE capability, but that will require libcap.so
3880    if (geteuid() != 0) {
3881      if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
3882        warning("-XX:ThreadPriorityPolicy requires root privilege on Linux");
3883      }
3884      ThreadPriorityPolicy = 0;
3885    }
3886  }
3887  if (UseCriticalJavaThreadPriority) {
3888    os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
3889  }
3890  return 0;
3891}
3892
3893OSReturn os::set_native_priority(Thread* thread, int newpri) {
3894  if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
3895
3896  int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
3897  return (ret == 0) ? OS_OK : OS_ERR;
3898}
3899
3900OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
3901  if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) {
3902    *priority_ptr = java_to_os_priority[NormPriority];
3903    return OS_OK;
3904  }
3905
3906  errno = 0;
3907  *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
3908  return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
3909}
3910
3911// Hint to the underlying OS that a task switch would not be good.
3912// Void return because it's a hint and can fail.
3913void os::hint_no_preempt() {}
3914
3915////////////////////////////////////////////////////////////////////////////////
3916// suspend/resume support
3917
3918//  the low-level signal-based suspend/resume support is a remnant from the
3919//  old VM-suspension that used to be for java-suspension, safepoints etc,
3920//  within hotspot. Now there is a single use-case for this:
3921//    - calling get_thread_pc() on the VMThread by the flat-profiler task
3922//      that runs in the watcher thread.
3923//  The remaining code is greatly simplified from the more general suspension
3924//  code that used to be used.
3925//
3926//  The protocol is quite simple:
3927//  - suspend:
3928//      - sends a signal to the target thread
3929//      - polls the suspend state of the osthread using a yield loop
3930//      - target thread signal handler (SR_handler) sets suspend state
3931//        and blocks in sigsuspend until continued
3932//  - resume:
3933//      - sets target osthread state to continue
3934//      - sends signal to end the sigsuspend loop in the SR_handler
3935//
3936//  Note that the SR_lock plays no role in this suspend/resume protocol.
3937//
3938
3939static void resume_clear_context(OSThread *osthread) {
3940  osthread->set_ucontext(NULL);
3941  osthread->set_siginfo(NULL);
3942}
3943
3944static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) {
3945  osthread->set_ucontext(context);
3946  osthread->set_siginfo(siginfo);
3947}
3948
3949//
3950// Handler function invoked when a thread's execution is suspended or
3951// resumed. We have to be careful that only async-safe functions are
3952// called here (Note: most pthread functions are not async safe and
3953// should be avoided.)
3954//
3955// Note: sigwait() is a more natural fit than sigsuspend() from an
3956// interface point of view, but sigwait() prevents the signal hander
3957// from being run. libpthread would get very confused by not having
3958// its signal handlers run and prevents sigwait()'s use with the
3959// mutex granting granting signal.
3960//
3961// Currently only ever called on the VMThread and JavaThreads (PC sampling)
3962//
3963static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
3964  // Save and restore errno to avoid confusing native code with EINTR
3965  // after sigsuspend.
3966  int old_errno = errno;
3967
3968  Thread* thread = Thread::current();
3969  OSThread* osthread = thread->osthread();
3970  assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
3971
3972  os::SuspendResume::State current = osthread->sr.state();
3973  if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
3974    suspend_save_context(osthread, siginfo, context);
3975
3976    // attempt to switch the state, we assume we had a SUSPEND_REQUEST
3977    os::SuspendResume::State state = osthread->sr.suspended();
3978    if (state == os::SuspendResume::SR_SUSPENDED) {
3979      sigset_t suspend_set;  // signals for sigsuspend()
3980
3981      // get current set of blocked signals and unblock resume signal
3982      pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
3983      sigdelset(&suspend_set, SR_signum);
3984
3985      sr_semaphore.signal();
3986      // wait here until we are resumed
3987      while (1) {
3988        sigsuspend(&suspend_set);
3989
3990        os::SuspendResume::State result = osthread->sr.running();
3991        if (result == os::SuspendResume::SR_RUNNING) {
3992          sr_semaphore.signal();
3993          break;
3994        }
3995      }
3996
3997    } else if (state == os::SuspendResume::SR_RUNNING) {
3998      // request was cancelled, continue
3999    } else {
4000      ShouldNotReachHere();
4001    }
4002
4003    resume_clear_context(osthread);
4004  } else if (current == os::SuspendResume::SR_RUNNING) {
4005    // request was cancelled, continue
4006  } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
4007    // ignore
4008  } else {
4009    // ignore
4010  }
4011
4012  errno = old_errno;
4013}
4014
4015
4016static int SR_initialize() {
4017  struct sigaction act;
4018  char *s;
4019  /* Get signal number to use for suspend/resume */
4020  if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
4021    int sig = ::strtol(s, 0, 10);
4022    if (sig > 0 || sig < _NSIG) {
4023        SR_signum = sig;
4024    }
4025  }
4026
4027  assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
4028        "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
4029
4030  sigemptyset(&SR_sigset);
4031  sigaddset(&SR_sigset, SR_signum);
4032
4033  /* Set up signal handler for suspend/resume */
4034  act.sa_flags = SA_RESTART|SA_SIGINFO;
4035  act.sa_handler = (void (*)(int)) SR_handler;
4036
4037  // SR_signum is blocked by default.
4038  // 4528190 - We also need to block pthread restart signal (32 on all
4039  // supported Linux platforms). Note that LinuxThreads need to block
4040  // this signal for all threads to work properly. So we don't have
4041  // to use hard-coded signal number when setting up the mask.
4042  pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
4043
4044  if (sigaction(SR_signum, &act, 0) == -1) {
4045    return -1;
4046  }
4047
4048  // Save signal flag
4049  os::Linux::set_our_sigflags(SR_signum, act.sa_flags);
4050  return 0;
4051}
4052
4053static int sr_notify(OSThread* osthread) {
4054  int status = pthread_kill(osthread->pthread_id(), SR_signum);
4055  assert_status(status == 0, status, "pthread_kill");
4056  return status;
4057}
4058
4059// "Randomly" selected value for how long we want to spin
4060// before bailing out on suspending a thread, also how often
4061// we send a signal to a thread we want to resume
4062static const int RANDOMLY_LARGE_INTEGER = 1000000;
4063static const int RANDOMLY_LARGE_INTEGER2 = 100;
4064
4065// returns true on success and false on error - really an error is fatal
4066// but this seems the normal response to library errors
4067static bool do_suspend(OSThread* osthread) {
4068  assert(osthread->sr.is_running(), "thread should be running");
4069  assert(!sr_semaphore.trywait(), "semaphore has invalid state");
4070
4071  // mark as suspended and send signal
4072  if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
4073    // failed to switch, state wasn't running?
4074    ShouldNotReachHere();
4075    return false;
4076  }
4077
4078  if (sr_notify(osthread) != 0) {
4079    ShouldNotReachHere();
4080  }
4081
4082  // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
4083  while (true) {
4084    if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
4085      break;
4086    } else {
4087      // timeout
4088      os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
4089      if (cancelled == os::SuspendResume::SR_RUNNING) {
4090        return false;
4091      } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
4092        // make sure that we consume the signal on the semaphore as well
4093        sr_semaphore.wait();
4094        break;
4095      } else {
4096        ShouldNotReachHere();
4097        return false;
4098      }
4099    }
4100  }
4101
4102  guarantee(osthread->sr.is_suspended(), "Must be suspended");
4103  return true;
4104}
4105
4106static void do_resume(OSThread* osthread) {
4107  assert(osthread->sr.is_suspended(), "thread should be suspended");
4108  assert(!sr_semaphore.trywait(), "invalid semaphore state");
4109
4110  if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
4111    // failed to switch to WAKEUP_REQUEST
4112    ShouldNotReachHere();
4113    return;
4114  }
4115
4116  while (true) {
4117    if (sr_notify(osthread) == 0) {
4118      if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
4119        if (osthread->sr.is_running()) {
4120          return;
4121        }
4122      }
4123    } else {
4124      ShouldNotReachHere();
4125    }
4126  }
4127
4128  guarantee(osthread->sr.is_running(), "Must be running!");
4129}
4130
4131///////////////////////////////////////////////////////////////////////////////////
4132// signal handling (except suspend/resume)
4133
4134// This routine may be used by user applications as a "hook" to catch signals.
4135// The user-defined signal handler must pass unrecognized signals to this
4136// routine, and if it returns true (non-zero), then the signal handler must
4137// return immediately.  If the flag "abort_if_unrecognized" is true, then this
4138// routine will never retun false (zero), but instead will execute a VM panic
4139// routine kill the process.
4140//
4141// If this routine returns false, it is OK to call it again.  This allows
4142// the user-defined signal handler to perform checks either before or after
4143// the VM performs its own checks.  Naturally, the user code would be making
4144// a serious error if it tried to handle an exception (such as a null check
4145// or breakpoint) that the VM was generating for its own correct operation.
4146//
4147// This routine may recognize any of the following kinds of signals:
4148//    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
4149// It should be consulted by handlers for any of those signals.
4150//
4151// The caller of this routine must pass in the three arguments supplied
4152// to the function referred to in the "sa_sigaction" (not the "sa_handler")
4153// field of the structure passed to sigaction().  This routine assumes that
4154// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
4155//
4156// Note that the VM will print warnings if it detects conflicting signal
4157// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
4158//
4159extern "C" JNIEXPORT int
4160JVM_handle_linux_signal(int signo, siginfo_t* siginfo,
4161                        void* ucontext, int abort_if_unrecognized);
4162
4163void signalHandler(int sig, siginfo_t* info, void* uc) {
4164  assert(info != NULL && uc != NULL, "it must be old kernel");
4165  int orig_errno = errno;  // Preserve errno value over signal handler.
4166  JVM_handle_linux_signal(sig, info, uc, true);
4167  errno = orig_errno;
4168}
4169
4170
4171// This boolean allows users to forward their own non-matching signals
4172// to JVM_handle_linux_signal, harmlessly.
4173bool os::Linux::signal_handlers_are_installed = false;
4174
4175// For signal-chaining
4176struct sigaction os::Linux::sigact[MAXSIGNUM];
4177unsigned int os::Linux::sigs = 0;
4178bool os::Linux::libjsig_is_loaded = false;
4179typedef struct sigaction *(*get_signal_t)(int);
4180get_signal_t os::Linux::get_signal_action = NULL;
4181
4182struct sigaction* os::Linux::get_chained_signal_action(int sig) {
4183  struct sigaction *actp = NULL;
4184
4185  if (libjsig_is_loaded) {
4186    // Retrieve the old signal handler from libjsig
4187    actp = (*get_signal_action)(sig);
4188  }
4189  if (actp == NULL) {
4190    // Retrieve the preinstalled signal handler from jvm
4191    actp = get_preinstalled_handler(sig);
4192  }
4193
4194  return actp;
4195}
4196
4197static bool call_chained_handler(struct sigaction *actp, int sig,
4198                                 siginfo_t *siginfo, void *context) {
4199  // Call the old signal handler
4200  if (actp->sa_handler == SIG_DFL) {
4201    // It's more reasonable to let jvm treat it as an unexpected exception
4202    // instead of taking the default action.
4203    return false;
4204  } else if (actp->sa_handler != SIG_IGN) {
4205    if ((actp->sa_flags & SA_NODEFER) == 0) {
4206      // automaticlly block the signal
4207      sigaddset(&(actp->sa_mask), sig);
4208    }
4209
4210    sa_handler_t hand;
4211    sa_sigaction_t sa;
4212    bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
4213    // retrieve the chained handler
4214    if (siginfo_flag_set) {
4215      sa = actp->sa_sigaction;
4216    } else {
4217      hand = actp->sa_handler;
4218    }
4219
4220    if ((actp->sa_flags & SA_RESETHAND) != 0) {
4221      actp->sa_handler = SIG_DFL;
4222    }
4223
4224    // try to honor the signal mask
4225    sigset_t oset;
4226    pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
4227
4228    // call into the chained handler
4229    if (siginfo_flag_set) {
4230      (*sa)(sig, siginfo, context);
4231    } else {
4232      (*hand)(sig);
4233    }
4234
4235    // restore the signal mask
4236    pthread_sigmask(SIG_SETMASK, &oset, 0);
4237  }
4238  // Tell jvm's signal handler the signal is taken care of.
4239  return true;
4240}
4241
4242bool os::Linux::chained_handler(int sig, siginfo_t* siginfo, void* context) {
4243  bool chained = false;
4244  // signal-chaining
4245  if (UseSignalChaining) {
4246    struct sigaction *actp = get_chained_signal_action(sig);
4247    if (actp != NULL) {
4248      chained = call_chained_handler(actp, sig, siginfo, context);
4249    }
4250  }
4251  return chained;
4252}
4253
4254struct sigaction* os::Linux::get_preinstalled_handler(int sig) {
4255  if ((( (unsigned int)1 << sig ) & sigs) != 0) {
4256    return &sigact[sig];
4257  }
4258  return NULL;
4259}
4260
4261void os::Linux::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
4262  assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4263  sigact[sig] = oldAct;
4264  sigs |= (unsigned int)1 << sig;
4265}
4266
4267// for diagnostic
4268int os::Linux::sigflags[MAXSIGNUM];
4269
4270int os::Linux::get_our_sigflags(int sig) {
4271  assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4272  return sigflags[sig];
4273}
4274
4275void os::Linux::set_our_sigflags(int sig, int flags) {
4276  assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4277  sigflags[sig] = flags;
4278}
4279
4280void os::Linux::set_signal_handler(int sig, bool set_installed) {
4281  // Check for overwrite.
4282  struct sigaction oldAct;
4283  sigaction(sig, (struct sigaction*)NULL, &oldAct);
4284
4285  void* oldhand = oldAct.sa_sigaction
4286                ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
4287                : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
4288  if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
4289      oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
4290      oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
4291    if (AllowUserSignalHandlers || !set_installed) {
4292      // Do not overwrite; user takes responsibility to forward to us.
4293      return;
4294    } else if (UseSignalChaining) {
4295      // save the old handler in jvm
4296      save_preinstalled_handler(sig, oldAct);
4297      // libjsig also interposes the sigaction() call below and saves the
4298      // old sigaction on it own.
4299    } else {
4300      fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
4301                    "%#lx for signal %d.", (long)oldhand, sig));
4302    }
4303  }
4304
4305  struct sigaction sigAct;
4306  sigfillset(&(sigAct.sa_mask));
4307  sigAct.sa_handler = SIG_DFL;
4308  if (!set_installed) {
4309    sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
4310  } else {
4311    sigAct.sa_sigaction = signalHandler;
4312    sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
4313  }
4314  // Save flags, which are set by ours
4315  assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range");
4316  sigflags[sig] = sigAct.sa_flags;
4317
4318  int ret = sigaction(sig, &sigAct, &oldAct);
4319  assert(ret == 0, "check");
4320
4321  void* oldhand2  = oldAct.sa_sigaction
4322                  ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
4323                  : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
4324  assert(oldhand2 == oldhand, "no concurrent signal handler installation");
4325}
4326
4327// install signal handlers for signals that HotSpot needs to
4328// handle in order to support Java-level exception handling.
4329
4330void os::Linux::install_signal_handlers() {
4331  if (!signal_handlers_are_installed) {
4332    signal_handlers_are_installed = true;
4333
4334    // signal-chaining
4335    typedef void (*signal_setting_t)();
4336    signal_setting_t begin_signal_setting = NULL;
4337    signal_setting_t end_signal_setting = NULL;
4338    begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4339                             dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
4340    if (begin_signal_setting != NULL) {
4341      end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4342                             dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
4343      get_signal_action = CAST_TO_FN_PTR(get_signal_t,
4344                            dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
4345      libjsig_is_loaded = true;
4346      assert(UseSignalChaining, "should enable signal-chaining");
4347    }
4348    if (libjsig_is_loaded) {
4349      // Tell libjsig jvm is setting signal handlers
4350      (*begin_signal_setting)();
4351    }
4352
4353    set_signal_handler(SIGSEGV, true);
4354    set_signal_handler(SIGPIPE, true);
4355    set_signal_handler(SIGBUS, true);
4356    set_signal_handler(SIGILL, true);
4357    set_signal_handler(SIGFPE, true);
4358#if defined(PPC64)
4359    set_signal_handler(SIGTRAP, true);
4360#endif
4361    set_signal_handler(SIGXFSZ, true);
4362
4363    if (libjsig_is_loaded) {
4364      // Tell libjsig jvm finishes setting signal handlers
4365      (*end_signal_setting)();
4366    }
4367
4368    // We don't activate signal checker if libjsig is in place, we trust ourselves
4369    // and if UserSignalHandler is installed all bets are off.
4370    // Log that signal checking is off only if -verbose:jni is specified.
4371    if (CheckJNICalls) {
4372      if (libjsig_is_loaded) {
4373        if (PrintJNIResolving) {
4374          tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
4375        }
4376        check_signals = false;
4377      }
4378      if (AllowUserSignalHandlers) {
4379        if (PrintJNIResolving) {
4380          tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
4381        }
4382        check_signals = false;
4383      }
4384    }
4385  }
4386}
4387
4388// This is the fastest way to get thread cpu time on Linux.
4389// Returns cpu time (user+sys) for any thread, not only for current.
4390// POSIX compliant clocks are implemented in the kernels 2.6.16+.
4391// It might work on 2.6.10+ with a special kernel/glibc patch.
4392// For reference, please, see IEEE Std 1003.1-2004:
4393//   http://www.unix.org/single_unix_specification
4394
4395jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) {
4396  struct timespec tp;
4397  int rc = os::Linux::clock_gettime(clockid, &tp);
4398  assert(rc == 0, "clock_gettime is expected to return 0 code");
4399
4400  return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec;
4401}
4402
4403/////
4404// glibc on Linux platform uses non-documented flag
4405// to indicate, that some special sort of signal
4406// trampoline is used.
4407// We will never set this flag, and we should
4408// ignore this flag in our diagnostic
4409#ifdef SIGNIFICANT_SIGNAL_MASK
4410#undef SIGNIFICANT_SIGNAL_MASK
4411#endif
4412#define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
4413
4414static const char* get_signal_handler_name(address handler,
4415                                           char* buf, int buflen) {
4416  int offset;
4417  bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
4418  if (found) {
4419    // skip directory names
4420    const char *p1, *p2;
4421    p1 = buf;
4422    size_t len = strlen(os::file_separator());
4423    while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
4424    jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
4425  } else {
4426    jio_snprintf(buf, buflen, PTR_FORMAT, handler);
4427  }
4428  return buf;
4429}
4430
4431static void print_signal_handler(outputStream* st, int sig,
4432                                 char* buf, size_t buflen) {
4433  struct sigaction sa;
4434
4435  sigaction(sig, NULL, &sa);
4436
4437  // See comment for SIGNIFICANT_SIGNAL_MASK define
4438  sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
4439
4440  st->print("%s: ", os::exception_name(sig, buf, buflen));
4441
4442  address handler = (sa.sa_flags & SA_SIGINFO)
4443    ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
4444    : CAST_FROM_FN_PTR(address, sa.sa_handler);
4445
4446  if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
4447    st->print("SIG_DFL");
4448  } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
4449    st->print("SIG_IGN");
4450  } else {
4451    st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
4452  }
4453
4454  st->print(", sa_mask[0]=");
4455  os::Posix::print_signal_set_short(st, &sa.sa_mask);
4456
4457  address rh = VMError::get_resetted_sighandler(sig);
4458  // May be, handler was resetted by VMError?
4459  if(rh != NULL) {
4460    handler = rh;
4461    sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
4462  }
4463
4464  st->print(", sa_flags=");
4465  os::Posix::print_sa_flags(st, sa.sa_flags);
4466
4467  // Check: is it our handler?
4468  if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
4469     handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
4470    // It is our signal handler
4471    // check for flags, reset system-used one!
4472    if((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) {
4473      st->print(
4474                ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
4475                os::Linux::get_our_sigflags(sig));
4476    }
4477  }
4478  st->cr();
4479}
4480
4481
4482#define DO_SIGNAL_CHECK(sig) \
4483  if (!sigismember(&check_signal_done, sig)) \
4484    os::Linux::check_signal_handler(sig)
4485
4486// This method is a periodic task to check for misbehaving JNI applications
4487// under CheckJNI, we can add any periodic checks here
4488
4489void os::run_periodic_checks() {
4490
4491  if (check_signals == false) return;
4492
4493  // SEGV and BUS if overridden could potentially prevent
4494  // generation of hs*.log in the event of a crash, debugging
4495  // such a case can be very challenging, so we absolutely
4496  // check the following for a good measure:
4497  DO_SIGNAL_CHECK(SIGSEGV);
4498  DO_SIGNAL_CHECK(SIGILL);
4499  DO_SIGNAL_CHECK(SIGFPE);
4500  DO_SIGNAL_CHECK(SIGBUS);
4501  DO_SIGNAL_CHECK(SIGPIPE);
4502  DO_SIGNAL_CHECK(SIGXFSZ);
4503#if defined(PPC64)
4504  DO_SIGNAL_CHECK(SIGTRAP);
4505#endif
4506
4507  // ReduceSignalUsage allows the user to override these handlers
4508  // see comments at the very top and jvm_solaris.h
4509  if (!ReduceSignalUsage) {
4510    DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
4511    DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
4512    DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
4513    DO_SIGNAL_CHECK(BREAK_SIGNAL);
4514  }
4515
4516  DO_SIGNAL_CHECK(SR_signum);
4517  DO_SIGNAL_CHECK(INTERRUPT_SIGNAL);
4518}
4519
4520typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
4521
4522static os_sigaction_t os_sigaction = NULL;
4523
4524void os::Linux::check_signal_handler(int sig) {
4525  char buf[O_BUFLEN];
4526  address jvmHandler = NULL;
4527
4528
4529  struct sigaction act;
4530  if (os_sigaction == NULL) {
4531    // only trust the default sigaction, in case it has been interposed
4532    os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
4533    if (os_sigaction == NULL) return;
4534  }
4535
4536  os_sigaction(sig, (struct sigaction*)NULL, &act);
4537
4538
4539  act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
4540
4541  address thisHandler = (act.sa_flags & SA_SIGINFO)
4542    ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
4543    : CAST_FROM_FN_PTR(address, act.sa_handler) ;
4544
4545
4546  switch(sig) {
4547  case SIGSEGV:
4548  case SIGBUS:
4549  case SIGFPE:
4550  case SIGPIPE:
4551  case SIGILL:
4552  case SIGXFSZ:
4553    jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
4554    break;
4555
4556  case SHUTDOWN1_SIGNAL:
4557  case SHUTDOWN2_SIGNAL:
4558  case SHUTDOWN3_SIGNAL:
4559  case BREAK_SIGNAL:
4560    jvmHandler = (address)user_handler();
4561    break;
4562
4563  case INTERRUPT_SIGNAL:
4564    jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL);
4565    break;
4566
4567  default:
4568    if (sig == SR_signum) {
4569      jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
4570    } else {
4571      return;
4572    }
4573    break;
4574  }
4575
4576  if (thisHandler != jvmHandler) {
4577    tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
4578    tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
4579    tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
4580    // No need to check this sig any longer
4581    sigaddset(&check_signal_done, sig);
4582    // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
4583    if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
4584      tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",
4585                    exception_name(sig, buf, O_BUFLEN));
4586    }
4587  } else if(os::Linux::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Linux::get_our_sigflags(sig)) {
4588    tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
4589    tty->print("expected:" PTR32_FORMAT, os::Linux::get_our_sigflags(sig));
4590    tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
4591    // No need to check this sig any longer
4592    sigaddset(&check_signal_done, sig);
4593  }
4594
4595  // Dump all the signal
4596  if (sigismember(&check_signal_done, sig)) {
4597    print_signal_handlers(tty, buf, O_BUFLEN);
4598  }
4599}
4600
4601extern void report_error(char* file_name, int line_no, char* title, char* format, ...);
4602
4603extern bool signal_name(int signo, char* buf, size_t len);
4604
4605const char* os::exception_name(int exception_code, char* buf, size_t size) {
4606  if (0 < exception_code && exception_code <= SIGRTMAX) {
4607    // signal
4608    if (!signal_name(exception_code, buf, size)) {
4609      jio_snprintf(buf, size, "SIG%d", exception_code);
4610    }
4611    return buf;
4612  } else {
4613    return NULL;
4614  }
4615}
4616
4617// this is called _before_ the most of global arguments have been parsed
4618void os::init(void) {
4619  char dummy;   /* used to get a guess on initial stack address */
4620//  first_hrtime = gethrtime();
4621
4622  // With LinuxThreads the JavaMain thread pid (primordial thread)
4623  // is different than the pid of the java launcher thread.
4624  // So, on Linux, the launcher thread pid is passed to the VM
4625  // via the sun.java.launcher.pid property.
4626  // Use this property instead of getpid() if it was correctly passed.
4627  // See bug 6351349.
4628  pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid();
4629
4630  _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
4631
4632  clock_tics_per_sec = sysconf(_SC_CLK_TCK);
4633
4634  init_random(1234567);
4635
4636  ThreadCritical::initialize();
4637
4638  Linux::set_page_size(sysconf(_SC_PAGESIZE));
4639  if (Linux::page_size() == -1) {
4640    fatal(err_msg("os_linux.cpp: os::init: sysconf failed (%s)",
4641                  strerror(errno)));
4642  }
4643  init_page_sizes((size_t) Linux::page_size());
4644
4645  Linux::initialize_system_info();
4646
4647  // main_thread points to the aboriginal thread
4648  Linux::_main_thread = pthread_self();
4649
4650  Linux::clock_init();
4651  initial_time_count = javaTimeNanos();
4652
4653  // pthread_condattr initialization for monotonic clock
4654  int status;
4655  pthread_condattr_t* _condattr = os::Linux::condAttr();
4656  if ((status = pthread_condattr_init(_condattr)) != 0) {
4657    fatal(err_msg("pthread_condattr_init: %s", strerror(status)));
4658  }
4659  // Only set the clock if CLOCK_MONOTONIC is available
4660  if (os::supports_monotonic_clock()) {
4661    if ((status = pthread_condattr_setclock(_condattr, CLOCK_MONOTONIC)) != 0) {
4662      if (status == EINVAL) {
4663        warning("Unable to use monotonic clock with relative timed-waits" \
4664                " - changes to the time-of-day clock may have adverse affects");
4665      } else {
4666        fatal(err_msg("pthread_condattr_setclock: %s", strerror(status)));
4667      }
4668    }
4669  }
4670  // else it defaults to CLOCK_REALTIME
4671
4672  pthread_mutex_init(&dl_mutex, NULL);
4673
4674  // If the pagesize of the VM is greater than 8K determine the appropriate
4675  // number of initial guard pages.  The user can change this with the
4676  // command line arguments, if needed.
4677  if (vm_page_size() > (int)Linux::vm_default_page_size()) {
4678    StackYellowPages = 1;
4679    StackRedPages = 1;
4680    StackShadowPages = round_to((StackShadowPages*Linux::vm_default_page_size()), vm_page_size()) / vm_page_size();
4681  }
4682}
4683
4684// To install functions for atexit system call
4685extern "C" {
4686  static void perfMemory_exit_helper() {
4687    perfMemory_exit();
4688  }
4689}
4690
4691// this is called _after_ the global arguments have been parsed
4692jint os::init_2(void)
4693{
4694  Linux::fast_thread_clock_init();
4695
4696  // Allocate a single page and mark it as readable for safepoint polling
4697  address polling_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
4698  guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" );
4699
4700  os::set_polling_page( polling_page );
4701
4702#ifndef PRODUCT
4703  if(Verbose && PrintMiscellaneous)
4704    tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
4705#endif
4706
4707  if (!UseMembar) {
4708    address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
4709    guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
4710    os::set_memory_serialize_page( mem_serialize_page );
4711
4712#ifndef PRODUCT
4713    if(Verbose && PrintMiscellaneous)
4714      tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
4715#endif
4716  }
4717
4718  // initialize suspend/resume support - must do this before signal_sets_init()
4719  if (SR_initialize() != 0) {
4720    perror("SR_initialize failed");
4721    return JNI_ERR;
4722  }
4723
4724  Linux::signal_sets_init();
4725  Linux::install_signal_handlers();
4726
4727  // Check minimum allowable stack size for thread creation and to initialize
4728  // the java system classes, including StackOverflowError - depends on page
4729  // size.  Add a page for compiler2 recursion in main thread.
4730  // Add in 2*BytesPerWord times page size to account for VM stack during
4731  // class initialization depending on 32 or 64 bit VM.
4732  os::Linux::min_stack_allowed = MAX2(os::Linux::min_stack_allowed,
4733            (size_t)(StackYellowPages+StackRedPages+StackShadowPages) * Linux::page_size() +
4734                    (2*BytesPerWord COMPILER2_PRESENT(+1)) * Linux::vm_default_page_size());
4735
4736  size_t threadStackSizeInBytes = ThreadStackSize * K;
4737  if (threadStackSizeInBytes != 0 &&
4738      threadStackSizeInBytes < os::Linux::min_stack_allowed) {
4739        tty->print_cr("\nThe stack size specified is too small, "
4740                      "Specify at least %dk",
4741                      os::Linux::min_stack_allowed/ K);
4742        return JNI_ERR;
4743  }
4744
4745  // Make the stack size a multiple of the page size so that
4746  // the yellow/red zones can be guarded.
4747  JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
4748        vm_page_size()));
4749
4750  Linux::capture_initial_stack(JavaThread::stack_size_at_create());
4751
4752#if defined(IA32)
4753  workaround_expand_exec_shield_cs_limit();
4754#endif
4755
4756  Linux::libpthread_init();
4757  if (PrintMiscellaneous && (Verbose || WizardMode)) {
4758     tty->print_cr("[HotSpot is running with %s, %s(%s)]\n",
4759          Linux::glibc_version(), Linux::libpthread_version(),
4760          Linux::is_floating_stack() ? "floating stack" : "fixed stack");
4761  }
4762
4763  if (UseNUMA) {
4764    if (!Linux::libnuma_init()) {
4765      UseNUMA = false;
4766    } else {
4767      if ((Linux::numa_max_node() < 1)) {
4768        // There's only one node(they start from 0), disable NUMA.
4769        UseNUMA = false;
4770      }
4771    }
4772    // With SHM and HugeTLBFS large pages we cannot uncommit a page, so there's no way
4773    // we can make the adaptive lgrp chunk resizing work. If the user specified
4774    // both UseNUMA and UseLargePages (or UseSHM/UseHugeTLBFS) on the command line - warn and
4775    // disable adaptive resizing.
4776    if (UseNUMA && UseLargePages && !can_commit_large_page_memory()) {
4777      if (FLAG_IS_DEFAULT(UseNUMA)) {
4778        UseNUMA = false;
4779      } else {
4780        if (FLAG_IS_DEFAULT(UseLargePages) &&
4781            FLAG_IS_DEFAULT(UseSHM) &&
4782            FLAG_IS_DEFAULT(UseHugeTLBFS)) {
4783          UseLargePages = false;
4784        } else {
4785          warning("UseNUMA is not fully compatible with SHM/HugeTLBFS large pages, disabling adaptive resizing");
4786          UseAdaptiveSizePolicy = false;
4787          UseAdaptiveNUMAChunkSizing = false;
4788        }
4789      }
4790    }
4791    if (!UseNUMA && ForceNUMA) {
4792      UseNUMA = true;
4793    }
4794  }
4795
4796  if (MaxFDLimit) {
4797    // set the number of file descriptors to max. print out error
4798    // if getrlimit/setrlimit fails but continue regardless.
4799    struct rlimit nbr_files;
4800    int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
4801    if (status != 0) {
4802      if (PrintMiscellaneous && (Verbose || WizardMode))
4803        perror("os::init_2 getrlimit failed");
4804    } else {
4805      nbr_files.rlim_cur = nbr_files.rlim_max;
4806      status = setrlimit(RLIMIT_NOFILE, &nbr_files);
4807      if (status != 0) {
4808        if (PrintMiscellaneous && (Verbose || WizardMode))
4809          perror("os::init_2 setrlimit failed");
4810      }
4811    }
4812  }
4813
4814  // Initialize lock used to serialize thread creation (see os::create_thread)
4815  Linux::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false));
4816
4817  // at-exit methods are called in the reverse order of their registration.
4818  // atexit functions are called on return from main or as a result of a
4819  // call to exit(3C). There can be only 32 of these functions registered
4820  // and atexit() does not set errno.
4821
4822  if (PerfAllowAtExitRegistration) {
4823    // only register atexit functions if PerfAllowAtExitRegistration is set.
4824    // atexit functions can be delayed until process exit time, which
4825    // can be problematic for embedded VM situations. Embedded VMs should
4826    // call DestroyJavaVM() to assure that VM resources are released.
4827
4828    // note: perfMemory_exit_helper atexit function may be removed in
4829    // the future if the appropriate cleanup code can be added to the
4830    // VM_Exit VMOperation's doit method.
4831    if (atexit(perfMemory_exit_helper) != 0) {
4832      warning("os::init_2 atexit(perfMemory_exit_helper) failed");
4833    }
4834  }
4835
4836  // initialize thread priority policy
4837  prio_init();
4838
4839  return JNI_OK;
4840}
4841
4842// this is called at the end of vm_initialization
4843void os::init_3(void) {
4844#ifdef JAVASE_EMBEDDED
4845  // Start the MemNotifyThread
4846  if (LowMemoryProtection) {
4847    MemNotifyThread::start();
4848  }
4849  return;
4850#endif
4851}
4852
4853// Mark the polling page as unreadable
4854void os::make_polling_page_unreadable(void) {
4855  if( !guard_memory((char*)_polling_page, Linux::page_size()) )
4856    fatal("Could not disable polling page");
4857};
4858
4859// Mark the polling page as readable
4860void os::make_polling_page_readable(void) {
4861  if( !linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) {
4862    fatal("Could not enable polling page");
4863  }
4864};
4865
4866int os::active_processor_count() {
4867  // Linux doesn't yet have a (official) notion of processor sets,
4868  // so just return the number of online processors.
4869  int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
4870  assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check");
4871  return online_cpus;
4872}
4873
4874void os::set_native_thread_name(const char *name) {
4875  // Not yet implemented.
4876  return;
4877}
4878
4879bool os::distribute_processes(uint length, uint* distribution) {
4880  // Not yet implemented.
4881  return false;
4882}
4883
4884bool os::bind_to_processor(uint processor_id) {
4885  // Not yet implemented.
4886  return false;
4887}
4888
4889///
4890
4891void os::SuspendedThreadTask::internal_do_task() {
4892  if (do_suspend(_thread->osthread())) {
4893    SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
4894    do_task(context);
4895    do_resume(_thread->osthread());
4896  }
4897}
4898
4899class PcFetcher : public os::SuspendedThreadTask {
4900public:
4901  PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
4902  ExtendedPC result();
4903protected:
4904  void do_task(const os::SuspendedThreadTaskContext& context);
4905private:
4906  ExtendedPC _epc;
4907};
4908
4909ExtendedPC PcFetcher::result() {
4910  guarantee(is_done(), "task is not done yet.");
4911  return _epc;
4912}
4913
4914void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
4915  Thread* thread = context.thread();
4916  OSThread* osthread = thread->osthread();
4917  if (osthread->ucontext() != NULL) {
4918    _epc = os::Linux::ucontext_get_pc((ucontext_t *) context.ucontext());
4919  } else {
4920    // NULL context is unexpected, double-check this is the VMThread
4921    guarantee(thread->is_VM_thread(), "can only be called for VMThread");
4922  }
4923}
4924
4925// Suspends the target using the signal mechanism and then grabs the PC before
4926// resuming the target. Used by the flat-profiler only
4927ExtendedPC os::get_thread_pc(Thread* thread) {
4928  // Make sure that it is called by the watcher for the VMThread
4929  assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
4930  assert(thread->is_VM_thread(), "Can only be called for VMThread");
4931
4932  PcFetcher fetcher(thread);
4933  fetcher.run();
4934  return fetcher.result();
4935}
4936
4937int os::Linux::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
4938{
4939   if (is_NPTL()) {
4940      return pthread_cond_timedwait(_cond, _mutex, _abstime);
4941   } else {
4942      // 6292965: LinuxThreads pthread_cond_timedwait() resets FPU control
4943      // word back to default 64bit precision if condvar is signaled. Java
4944      // wants 53bit precision.  Save and restore current value.
4945      int fpu = get_fpu_control_word();
4946      int status = pthread_cond_timedwait(_cond, _mutex, _abstime);
4947      set_fpu_control_word(fpu);
4948      return status;
4949   }
4950}
4951
4952////////////////////////////////////////////////////////////////////////////////
4953// debug support
4954
4955bool os::find(address addr, outputStream* st) {
4956  Dl_info dlinfo;
4957  memset(&dlinfo, 0, sizeof(dlinfo));
4958  if (dladdr(addr, &dlinfo) != 0) {
4959    st->print(PTR_FORMAT ": ", addr);
4960    if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
4961      st->print("%s+%#x", dlinfo.dli_sname,
4962                 addr - (intptr_t)dlinfo.dli_saddr);
4963    } else if (dlinfo.dli_fbase != NULL) {
4964      st->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase);
4965    } else {
4966      st->print("<absolute address>");
4967    }
4968    if (dlinfo.dli_fname != NULL) {
4969      st->print(" in %s", dlinfo.dli_fname);
4970    }
4971    if (dlinfo.dli_fbase != NULL) {
4972      st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
4973    }
4974    st->cr();
4975
4976    if (Verbose) {
4977      // decode some bytes around the PC
4978      address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
4979      address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
4980      address       lowest = (address) dlinfo.dli_sname;
4981      if (!lowest)  lowest = (address) dlinfo.dli_fbase;
4982      if (begin < lowest)  begin = lowest;
4983      Dl_info dlinfo2;
4984      if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
4985          && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
4986        end = (address) dlinfo2.dli_saddr;
4987      Disassembler::decode(begin, end, st);
4988    }
4989    return true;
4990  }
4991  return false;
4992}
4993
4994////////////////////////////////////////////////////////////////////////////////
4995// misc
4996
4997// This does not do anything on Linux. This is basically a hook for being
4998// able to use structured exception handling (thread-local exception filters)
4999// on, e.g., Win32.
5000void
5001os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method,
5002                         JavaCallArguments* args, Thread* thread) {
5003  f(value, method, args, thread);
5004}
5005
5006void os::print_statistics() {
5007}
5008
5009int os::message_box(const char* title, const char* message) {
5010  int i;
5011  fdStream err(defaultStream::error_fd());
5012  for (i = 0; i < 78; i++) err.print_raw("=");
5013  err.cr();
5014  err.print_raw_cr(title);
5015  for (i = 0; i < 78; i++) err.print_raw("-");
5016  err.cr();
5017  err.print_raw_cr(message);
5018  for (i = 0; i < 78; i++) err.print_raw("=");
5019  err.cr();
5020
5021  char buf[16];
5022  // Prevent process from exiting upon "read error" without consuming all CPU
5023  while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
5024
5025  return buf[0] == 'y' || buf[0] == 'Y';
5026}
5027
5028int os::stat(const char *path, struct stat *sbuf) {
5029  char pathbuf[MAX_PATH];
5030  if (strlen(path) > MAX_PATH - 1) {
5031    errno = ENAMETOOLONG;
5032    return -1;
5033  }
5034  os::native_path(strcpy(pathbuf, path));
5035  return ::stat(pathbuf, sbuf);
5036}
5037
5038bool os::check_heap(bool force) {
5039  return true;
5040}
5041
5042int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) {
5043  return ::vsnprintf(buf, count, format, args);
5044}
5045
5046// Is a (classpath) directory empty?
5047bool os::dir_is_empty(const char* path) {
5048  DIR *dir = NULL;
5049  struct dirent *ptr;
5050
5051  dir = opendir(path);
5052  if (dir == NULL) return true;
5053
5054  /* Scan the directory */
5055  bool result = true;
5056  char buf[sizeof(struct dirent) + MAX_PATH];
5057  while (result && (ptr = ::readdir(dir)) != NULL) {
5058    if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
5059      result = false;
5060    }
5061  }
5062  closedir(dir);
5063  return result;
5064}
5065
5066// This code originates from JDK's sysOpen and open64_w
5067// from src/solaris/hpi/src/system_md.c
5068
5069#ifndef O_DELETE
5070#define O_DELETE 0x10000
5071#endif
5072
5073// Open a file. Unlink the file immediately after open returns
5074// if the specified oflag has the O_DELETE flag set.
5075// O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
5076
5077int os::open(const char *path, int oflag, int mode) {
5078
5079  if (strlen(path) > MAX_PATH - 1) {
5080    errno = ENAMETOOLONG;
5081    return -1;
5082  }
5083  int fd;
5084  int o_delete = (oflag & O_DELETE);
5085  oflag = oflag & ~O_DELETE;
5086
5087  fd = ::open64(path, oflag, mode);
5088  if (fd == -1) return -1;
5089
5090  //If the open succeeded, the file might still be a directory
5091  {
5092    struct stat64 buf64;
5093    int ret = ::fstat64(fd, &buf64);
5094    int st_mode = buf64.st_mode;
5095
5096    if (ret != -1) {
5097      if ((st_mode & S_IFMT) == S_IFDIR) {
5098        errno = EISDIR;
5099        ::close(fd);
5100        return -1;
5101      }
5102    } else {
5103      ::close(fd);
5104      return -1;
5105    }
5106  }
5107
5108    /*
5109     * All file descriptors that are opened in the JVM and not
5110     * specifically destined for a subprocess should have the
5111     * close-on-exec flag set.  If we don't set it, then careless 3rd
5112     * party native code might fork and exec without closing all
5113     * appropriate file descriptors (e.g. as we do in closeDescriptors in
5114     * UNIXProcess.c), and this in turn might:
5115     *
5116     * - cause end-of-file to fail to be detected on some file
5117     *   descriptors, resulting in mysterious hangs, or
5118     *
5119     * - might cause an fopen in the subprocess to fail on a system
5120     *   suffering from bug 1085341.
5121     *
5122     * (Yes, the default setting of the close-on-exec flag is a Unix
5123     * design flaw)
5124     *
5125     * See:
5126     * 1085341: 32-bit stdio routines should support file descriptors >255
5127     * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
5128     * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
5129     */
5130#ifdef FD_CLOEXEC
5131    {
5132        int flags = ::fcntl(fd, F_GETFD);
5133        if (flags != -1)
5134            ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
5135    }
5136#endif
5137
5138  if (o_delete != 0) {
5139    ::unlink(path);
5140  }
5141  return fd;
5142}
5143
5144
5145// create binary file, rewriting existing file if required
5146int os::create_binary_file(const char* path, bool rewrite_existing) {
5147  int oflags = O_WRONLY | O_CREAT;
5148  if (!rewrite_existing) {
5149    oflags |= O_EXCL;
5150  }
5151  return ::open64(path, oflags, S_IREAD | S_IWRITE);
5152}
5153
5154// return current position of file pointer
5155jlong os::current_file_offset(int fd) {
5156  return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
5157}
5158
5159// move file pointer to the specified offset
5160jlong os::seek_to_file_offset(int fd, jlong offset) {
5161  return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
5162}
5163
5164// This code originates from JDK's sysAvailable
5165// from src/solaris/hpi/src/native_threads/src/sys_api_td.c
5166
5167int os::available(int fd, jlong *bytes) {
5168  jlong cur, end;
5169  int mode;
5170  struct stat64 buf64;
5171
5172  if (::fstat64(fd, &buf64) >= 0) {
5173    mode = buf64.st_mode;
5174    if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
5175      /*
5176      * XXX: is the following call interruptible? If so, this might
5177      * need to go through the INTERRUPT_IO() wrapper as for other
5178      * blocking, interruptible calls in this file.
5179      */
5180      int n;
5181      if (::ioctl(fd, FIONREAD, &n) >= 0) {
5182        *bytes = n;
5183        return 1;
5184      }
5185    }
5186  }
5187  if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
5188    return 0;
5189  } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
5190    return 0;
5191  } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
5192    return 0;
5193  }
5194  *bytes = end - cur;
5195  return 1;
5196}
5197
5198int os::socket_available(int fd, jint *pbytes) {
5199  // Linux doc says EINTR not returned, unlike Solaris
5200  int ret = ::ioctl(fd, FIONREAD, pbytes);
5201
5202  //%% note ioctl can return 0 when successful, JVM_SocketAvailable
5203  // is expected to return 0 on failure and 1 on success to the jdk.
5204  return (ret < 0) ? 0 : 1;
5205}
5206
5207// Map a block of memory.
5208char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
5209                     char *addr, size_t bytes, bool read_only,
5210                     bool allow_exec) {
5211  int prot;
5212  int flags = MAP_PRIVATE;
5213
5214  if (read_only) {
5215    prot = PROT_READ;
5216  } else {
5217    prot = PROT_READ | PROT_WRITE;
5218  }
5219
5220  if (allow_exec) {
5221    prot |= PROT_EXEC;
5222  }
5223
5224  if (addr != NULL) {
5225    flags |= MAP_FIXED;
5226  }
5227
5228  char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
5229                                     fd, file_offset);
5230  if (mapped_address == MAP_FAILED) {
5231    return NULL;
5232  }
5233  return mapped_address;
5234}
5235
5236
5237// Remap a block of memory.
5238char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
5239                       char *addr, size_t bytes, bool read_only,
5240                       bool allow_exec) {
5241  // same as map_memory() on this OS
5242  return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
5243                        allow_exec);
5244}
5245
5246
5247// Unmap a block of memory.
5248bool os::pd_unmap_memory(char* addr, size_t bytes) {
5249  return munmap(addr, bytes) == 0;
5250}
5251
5252static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time);
5253
5254static clockid_t thread_cpu_clockid(Thread* thread) {
5255  pthread_t tid = thread->osthread()->pthread_id();
5256  clockid_t clockid;
5257
5258  // Get thread clockid
5259  int rc = os::Linux::pthread_getcpuclockid(tid, &clockid);
5260  assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code");
5261  return clockid;
5262}
5263
5264// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
5265// are used by JVM M&M and JVMTI to get user+sys or user CPU time
5266// of a thread.
5267//
5268// current_thread_cpu_time() and thread_cpu_time(Thread*) returns
5269// the fast estimate available on the platform.
5270
5271jlong os::current_thread_cpu_time() {
5272  if (os::Linux::supports_fast_thread_cpu_time()) {
5273    return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5274  } else {
5275    // return user + sys since the cost is the same
5276    return slow_thread_cpu_time(Thread::current(), true /* user + sys */);
5277  }
5278}
5279
5280jlong os::thread_cpu_time(Thread* thread) {
5281  // consistent with what current_thread_cpu_time() returns
5282  if (os::Linux::supports_fast_thread_cpu_time()) {
5283    return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
5284  } else {
5285    return slow_thread_cpu_time(thread, true /* user + sys */);
5286  }
5287}
5288
5289jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
5290  if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5291    return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5292  } else {
5293    return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time);
5294  }
5295}
5296
5297jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5298  if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5299    return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
5300  } else {
5301    return slow_thread_cpu_time(thread, user_sys_cpu_time);
5302  }
5303}
5304
5305//
5306//  -1 on error.
5307//
5308
5309static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5310  static bool proc_task_unchecked = true;
5311  pid_t  tid = thread->osthread()->thread_id();
5312  char *s;
5313  char stat[2048];
5314  int statlen;
5315  char proc_name[64];
5316  int count;
5317  long sys_time, user_time;
5318  char cdummy;
5319  int idummy;
5320  long ldummy;
5321  FILE *fp;
5322
5323  snprintf(proc_name, 64, "/proc/%d/stat", tid);
5324
5325  // The /proc/<tid>/stat aggregates per-process usage on
5326  // new Linux kernels 2.6+ where NPTL is supported.
5327  // The /proc/self/task/<tid>/stat still has the per-thread usage.
5328  // See bug 6328462.
5329  // There possibly can be cases where there is no directory
5330  // /proc/self/task, so we check its availability.
5331  if (proc_task_unchecked && os::Linux::is_NPTL()) {
5332    // This is executed only once
5333    proc_task_unchecked = false;
5334    fp = fopen("/proc/self/task", "r");
5335    if (fp != NULL) {
5336      snprintf(proc_name, 64, "/proc/self/task/%d/stat", tid);
5337      fclose(fp);
5338    }
5339  }
5340
5341  fp = fopen(proc_name, "r");
5342  if ( fp == NULL ) return -1;
5343  statlen = fread(stat, 1, 2047, fp);
5344  stat[statlen] = '\0';
5345  fclose(fp);
5346
5347  // Skip pid and the command string. Note that we could be dealing with
5348  // weird command names, e.g. user could decide to rename java launcher
5349  // to "java 1.4.2 :)", then the stat file would look like
5350  //                1234 (java 1.4.2 :)) R ... ...
5351  // We don't really need to know the command string, just find the last
5352  // occurrence of ")" and then start parsing from there. See bug 4726580.
5353  s = strrchr(stat, ')');
5354  if (s == NULL ) return -1;
5355
5356  // Skip blank chars
5357  do s++; while (isspace(*s));
5358
5359  count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu",
5360                 &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy,
5361                 &ldummy, &ldummy, &ldummy, &ldummy, &ldummy,
5362                 &user_time, &sys_time);
5363  if ( count != 13 ) return -1;
5364  if (user_sys_cpu_time) {
5365    return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
5366  } else {
5367    return (jlong)user_time * (1000000000 / clock_tics_per_sec);
5368  }
5369}
5370
5371void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5372  info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5373  info_ptr->may_skip_backward = false;     // elapsed time not wall time
5374  info_ptr->may_skip_forward = false;      // elapsed time not wall time
5375  info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5376}
5377
5378void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5379  info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5380  info_ptr->may_skip_backward = false;     // elapsed time not wall time
5381  info_ptr->may_skip_forward = false;      // elapsed time not wall time
5382  info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5383}
5384
5385bool os::is_thread_cpu_time_supported() {
5386  return true;
5387}
5388
5389// System loadavg support.  Returns -1 if load average cannot be obtained.
5390// Linux doesn't yet have a (official) notion of processor sets,
5391// so just return the system wide load average.
5392int os::loadavg(double loadavg[], int nelem) {
5393  return ::getloadavg(loadavg, nelem);
5394}
5395
5396void os::pause() {
5397  char filename[MAX_PATH];
5398  if (PauseAtStartupFile && PauseAtStartupFile[0]) {
5399    jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
5400  } else {
5401    jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
5402  }
5403
5404  int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
5405  if (fd != -1) {
5406    struct stat buf;
5407    ::close(fd);
5408    while (::stat(filename, &buf) == 0) {
5409      (void)::poll(NULL, 0, 100);
5410    }
5411  } else {
5412    jio_fprintf(stderr,
5413      "Could not open pause file '%s', continuing immediately.\n", filename);
5414  }
5415}
5416
5417
5418// Refer to the comments in os_solaris.cpp park-unpark.
5419//
5420// Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
5421// hang indefinitely.  For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
5422// For specifics regarding the bug see GLIBC BUGID 261237 :
5423//    http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
5424// Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
5425// will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
5426// is used.  (The simple C test-case provided in the GLIBC bug report manifests the
5427// hang).  The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
5428// and monitorenter when we're using 1-0 locking.  All those operations may result in
5429// calls to pthread_cond_timedwait().  Using LD_ASSUME_KERNEL to use an older version
5430// of libpthread avoids the problem, but isn't practical.
5431//
5432// Possible remedies:
5433//
5434// 1.   Establish a minimum relative wait time.  50 to 100 msecs seems to work.
5435//      This is palliative and probabilistic, however.  If the thread is preempted
5436//      between the call to compute_abstime() and pthread_cond_timedwait(), more
5437//      than the minimum period may have passed, and the abstime may be stale (in the
5438//      past) resultin in a hang.   Using this technique reduces the odds of a hang
5439//      but the JVM is still vulnerable, particularly on heavily loaded systems.
5440//
5441// 2.   Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
5442//      of the usual flag-condvar-mutex idiom.  The write side of the pipe is set
5443//      NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
5444//      reduces to poll()+read().  This works well, but consumes 2 FDs per extant
5445//      thread.
5446//
5447// 3.   Embargo pthread_cond_timedwait() and implement a native "chron" thread
5448//      that manages timeouts.  We'd emulate pthread_cond_timedwait() by enqueuing
5449//      a timeout request to the chron thread and then blocking via pthread_cond_wait().
5450//      This also works well.  In fact it avoids kernel-level scalability impediments
5451//      on certain platforms that don't handle lots of active pthread_cond_timedwait()
5452//      timers in a graceful fashion.
5453//
5454// 4.   When the abstime value is in the past it appears that control returns
5455//      correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
5456//      Subsequent timedwait/wait calls may hang indefinitely.  Given that, we
5457//      can avoid the problem by reinitializing the condvar -- by cond_destroy()
5458//      followed by cond_init() -- after all calls to pthread_cond_timedwait().
5459//      It may be possible to avoid reinitialization by checking the return
5460//      value from pthread_cond_timedwait().  In addition to reinitializing the
5461//      condvar we must establish the invariant that cond_signal() is only called
5462//      within critical sections protected by the adjunct mutex.  This prevents
5463//      cond_signal() from "seeing" a condvar that's in the midst of being
5464//      reinitialized or that is corrupt.  Sadly, this invariant obviates the
5465//      desirable signal-after-unlock optimization that avoids futile context switching.
5466//
5467//      I'm also concerned that some versions of NTPL might allocate an auxilliary
5468//      structure when a condvar is used or initialized.  cond_destroy()  would
5469//      release the helper structure.  Our reinitialize-after-timedwait fix
5470//      put excessive stress on malloc/free and locks protecting the c-heap.
5471//
5472// We currently use (4).  See the WorkAroundNTPLTimedWaitHang flag.
5473// It may be possible to refine (4) by checking the kernel and NTPL verisons
5474// and only enabling the work-around for vulnerable environments.
5475
5476// utility to compute the abstime argument to timedwait:
5477// millis is the relative timeout time
5478// abstime will be the absolute timeout time
5479// TODO: replace compute_abstime() with unpackTime()
5480
5481static struct timespec* compute_abstime(timespec* abstime, jlong millis) {
5482  if (millis < 0)  millis = 0;
5483
5484  jlong seconds = millis / 1000;
5485  millis %= 1000;
5486  if (seconds > 50000000) { // see man cond_timedwait(3T)
5487    seconds = 50000000;
5488  }
5489
5490  if (os::supports_monotonic_clock()) {
5491    struct timespec now;
5492    int status = os::Linux::clock_gettime(CLOCK_MONOTONIC, &now);
5493    assert_status(status == 0, status, "clock_gettime");
5494    abstime->tv_sec = now.tv_sec  + seconds;
5495    long nanos = now.tv_nsec + millis * NANOSECS_PER_MILLISEC;
5496    if (nanos >= NANOSECS_PER_SEC) {
5497      abstime->tv_sec += 1;
5498      nanos -= NANOSECS_PER_SEC;
5499    }
5500    abstime->tv_nsec = nanos;
5501  } else {
5502    struct timeval now;
5503    int status = gettimeofday(&now, NULL);
5504    assert(status == 0, "gettimeofday");
5505    abstime->tv_sec = now.tv_sec  + seconds;
5506    long usec = now.tv_usec + millis * 1000;
5507    if (usec >= 1000000) {
5508      abstime->tv_sec += 1;
5509      usec -= 1000000;
5510    }
5511    abstime->tv_nsec = usec * 1000;
5512  }
5513  return abstime;
5514}
5515
5516
5517// Test-and-clear _Event, always leaves _Event set to 0, returns immediately.
5518// Conceptually TryPark() should be equivalent to park(0).
5519
5520int os::PlatformEvent::TryPark() {
5521  for (;;) {
5522    const int v = _Event ;
5523    guarantee ((v == 0) || (v == 1), "invariant") ;
5524    if (Atomic::cmpxchg (0, &_Event, v) == v) return v  ;
5525  }
5526}
5527
5528void os::PlatformEvent::park() {       // AKA "down()"
5529  // Invariant: Only the thread associated with the Event/PlatformEvent
5530  // may call park().
5531  // TODO: assert that _Assoc != NULL or _Assoc == Self
5532  int v ;
5533  for (;;) {
5534      v = _Event ;
5535      if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
5536  }
5537  guarantee (v >= 0, "invariant") ;
5538  if (v == 0) {
5539     // Do this the hard way by blocking ...
5540     int status = pthread_mutex_lock(_mutex);
5541     assert_status(status == 0, status, "mutex_lock");
5542     guarantee (_nParked == 0, "invariant") ;
5543     ++ _nParked ;
5544     while (_Event < 0) {
5545        status = pthread_cond_wait(_cond, _mutex);
5546        // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
5547        // Treat this the same as if the wait was interrupted
5548        if (status == ETIME) { status = EINTR; }
5549        assert_status(status == 0 || status == EINTR, status, "cond_wait");
5550     }
5551     -- _nParked ;
5552
5553    _Event = 0 ;
5554     status = pthread_mutex_unlock(_mutex);
5555     assert_status(status == 0, status, "mutex_unlock");
5556    // Paranoia to ensure our locked and lock-free paths interact
5557    // correctly with each other.
5558    OrderAccess::fence();
5559  }
5560  guarantee (_Event >= 0, "invariant") ;
5561}
5562
5563int os::PlatformEvent::park(jlong millis) {
5564  guarantee (_nParked == 0, "invariant") ;
5565
5566  int v ;
5567  for (;;) {
5568      v = _Event ;
5569      if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;
5570  }
5571  guarantee (v >= 0, "invariant") ;
5572  if (v != 0) return OS_OK ;
5573
5574  // We do this the hard way, by blocking the thread.
5575  // Consider enforcing a minimum timeout value.
5576  struct timespec abst;
5577  compute_abstime(&abst, millis);
5578
5579  int ret = OS_TIMEOUT;
5580  int status = pthread_mutex_lock(_mutex);
5581  assert_status(status == 0, status, "mutex_lock");
5582  guarantee (_nParked == 0, "invariant") ;
5583  ++_nParked ;
5584
5585  // Object.wait(timo) will return because of
5586  // (a) notification
5587  // (b) timeout
5588  // (c) thread.interrupt
5589  //
5590  // Thread.interrupt and object.notify{All} both call Event::set.
5591  // That is, we treat thread.interrupt as a special case of notification.
5592  // The underlying Solaris implementation, cond_timedwait, admits
5593  // spurious/premature wakeups, but the JLS/JVM spec prevents the
5594  // JVM from making those visible to Java code.  As such, we must
5595  // filter out spurious wakeups.  We assume all ETIME returns are valid.
5596  //
5597  // TODO: properly differentiate simultaneous notify+interrupt.
5598  // In that case, we should propagate the notify to another waiter.
5599
5600  while (_Event < 0) {
5601    status = os::Linux::safe_cond_timedwait(_cond, _mutex, &abst);
5602    if (status != 0 && WorkAroundNPTLTimedWaitHang) {
5603      pthread_cond_destroy (_cond);
5604      pthread_cond_init (_cond, os::Linux::condAttr()) ;
5605    }
5606    assert_status(status == 0 || status == EINTR ||
5607                  status == ETIME || status == ETIMEDOUT,
5608                  status, "cond_timedwait");
5609    if (!FilterSpuriousWakeups) break ;                 // previous semantics
5610    if (status == ETIME || status == ETIMEDOUT) break ;
5611    // We consume and ignore EINTR and spurious wakeups.
5612  }
5613  --_nParked ;
5614  if (_Event >= 0) {
5615     ret = OS_OK;
5616  }
5617  _Event = 0 ;
5618  status = pthread_mutex_unlock(_mutex);
5619  assert_status(status == 0, status, "mutex_unlock");
5620  assert (_nParked == 0, "invariant") ;
5621  // Paranoia to ensure our locked and lock-free paths interact
5622  // correctly with each other.
5623  OrderAccess::fence();
5624  return ret;
5625}
5626
5627void os::PlatformEvent::unpark() {
5628  // Transitions for _Event:
5629  //    0 :=> 1
5630  //    1 :=> 1
5631  //   -1 :=> either 0 or 1; must signal target thread
5632  //          That is, we can safely transition _Event from -1 to either
5633  //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
5634  //          unpark() calls.
5635  // See also: "Semaphores in Plan 9" by Mullender & Cox
5636  //
5637  // Note: Forcing a transition from "-1" to "1" on an unpark() means
5638  // that it will take two back-to-back park() calls for the owning
5639  // thread to block. This has the benefit of forcing a spurious return
5640  // from the first park() call after an unpark() call which will help
5641  // shake out uses of park() and unpark() without condition variables.
5642
5643  if (Atomic::xchg(1, &_Event) >= 0) return;
5644
5645  // Wait for the thread associated with the event to vacate
5646  int status = pthread_mutex_lock(_mutex);
5647  assert_status(status == 0, status, "mutex_lock");
5648  int AnyWaiters = _nParked;
5649  assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
5650  if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
5651    AnyWaiters = 0;
5652    pthread_cond_signal(_cond);
5653  }
5654  status = pthread_mutex_unlock(_mutex);
5655  assert_status(status == 0, status, "mutex_unlock");
5656  if (AnyWaiters != 0) {
5657    status = pthread_cond_signal(_cond);
5658    assert_status(status == 0, status, "cond_signal");
5659  }
5660
5661  // Note that we signal() _after dropping the lock for "immortal" Events.
5662  // This is safe and avoids a common class of  futile wakeups.  In rare
5663  // circumstances this can cause a thread to return prematurely from
5664  // cond_{timed}wait() but the spurious wakeup is benign and the victim will
5665  // simply re-test the condition and re-park itself.
5666}
5667
5668
5669// JSR166
5670// -------------------------------------------------------
5671
5672/*
5673 * The solaris and linux implementations of park/unpark are fairly
5674 * conservative for now, but can be improved. They currently use a
5675 * mutex/condvar pair, plus a a count.
5676 * Park decrements count if > 0, else does a condvar wait.  Unpark
5677 * sets count to 1 and signals condvar.  Only one thread ever waits
5678 * on the condvar. Contention seen when trying to park implies that someone
5679 * is unparking you, so don't wait. And spurious returns are fine, so there
5680 * is no need to track notifications.
5681 */
5682
5683/*
5684 * This code is common to linux and solaris and will be moved to a
5685 * common place in dolphin.
5686 *
5687 * The passed in time value is either a relative time in nanoseconds
5688 * or an absolute time in milliseconds. Either way it has to be unpacked
5689 * into suitable seconds and nanoseconds components and stored in the
5690 * given timespec structure.
5691 * Given time is a 64-bit value and the time_t used in the timespec is only
5692 * a signed-32-bit value (except on 64-bit Linux) we have to watch for
5693 * overflow if times way in the future are given. Further on Solaris versions
5694 * prior to 10 there is a restriction (see cond_timedwait) that the specified
5695 * number of seconds, in abstime, is less than current_time  + 100,000,000.
5696 * As it will be 28 years before "now + 100000000" will overflow we can
5697 * ignore overflow and just impose a hard-limit on seconds using the value
5698 * of "now + 100,000,000". This places a limit on the timeout of about 3.17
5699 * years from "now".
5700 */
5701
5702static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
5703  assert (time > 0, "convertTime");
5704  time_t max_secs = 0;
5705
5706  if (!os::supports_monotonic_clock() || isAbsolute) {
5707    struct timeval now;
5708    int status = gettimeofday(&now, NULL);
5709    assert(status == 0, "gettimeofday");
5710
5711    max_secs = now.tv_sec + MAX_SECS;
5712
5713    if (isAbsolute) {
5714      jlong secs = time / 1000;
5715      if (secs > max_secs) {
5716        absTime->tv_sec = max_secs;
5717      } else {
5718        absTime->tv_sec = secs;
5719      }
5720      absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
5721    } else {
5722      jlong secs = time / NANOSECS_PER_SEC;
5723      if (secs >= MAX_SECS) {
5724        absTime->tv_sec = max_secs;
5725        absTime->tv_nsec = 0;
5726      } else {
5727        absTime->tv_sec = now.tv_sec + secs;
5728        absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
5729        if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
5730          absTime->tv_nsec -= NANOSECS_PER_SEC;
5731          ++absTime->tv_sec; // note: this must be <= max_secs
5732        }
5733      }
5734    }
5735  } else {
5736    // must be relative using monotonic clock
5737    struct timespec now;
5738    int status = os::Linux::clock_gettime(CLOCK_MONOTONIC, &now);
5739    assert_status(status == 0, status, "clock_gettime");
5740    max_secs = now.tv_sec + MAX_SECS;
5741    jlong secs = time / NANOSECS_PER_SEC;
5742    if (secs >= MAX_SECS) {
5743      absTime->tv_sec = max_secs;
5744      absTime->tv_nsec = 0;
5745    } else {
5746      absTime->tv_sec = now.tv_sec + secs;
5747      absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_nsec;
5748      if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
5749        absTime->tv_nsec -= NANOSECS_PER_SEC;
5750        ++absTime->tv_sec; // note: this must be <= max_secs
5751      }
5752    }
5753  }
5754  assert(absTime->tv_sec >= 0, "tv_sec < 0");
5755  assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
5756  assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
5757  assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
5758}
5759
5760void Parker::park(bool isAbsolute, jlong time) {
5761  // Ideally we'd do something useful while spinning, such
5762  // as calling unpackTime().
5763
5764  // Optional fast-path check:
5765  // Return immediately if a permit is available.
5766  // We depend on Atomic::xchg() having full barrier semantics
5767  // since we are doing a lock-free update to _counter.
5768  if (Atomic::xchg(0, &_counter) > 0) return;
5769
5770  Thread* thread = Thread::current();
5771  assert(thread->is_Java_thread(), "Must be JavaThread");
5772  JavaThread *jt = (JavaThread *)thread;
5773
5774  // Optional optimization -- avoid state transitions if there's an interrupt pending.
5775  // Check interrupt before trying to wait
5776  if (Thread::is_interrupted(thread, false)) {
5777    return;
5778  }
5779
5780  // Next, demultiplex/decode time arguments
5781  timespec absTime;
5782  if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
5783    return;
5784  }
5785  if (time > 0) {
5786    unpackTime(&absTime, isAbsolute, time);
5787  }
5788
5789
5790  // Enter safepoint region
5791  // Beware of deadlocks such as 6317397.
5792  // The per-thread Parker:: mutex is a classic leaf-lock.
5793  // In particular a thread must never block on the Threads_lock while
5794  // holding the Parker:: mutex.  If safepoints are pending both the
5795  // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
5796  ThreadBlockInVM tbivm(jt);
5797
5798  // Don't wait if cannot get lock since interference arises from
5799  // unblocking.  Also. check interrupt before trying wait
5800  if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
5801    return;
5802  }
5803
5804  int status ;
5805  if (_counter > 0)  { // no wait needed
5806    _counter = 0;
5807    status = pthread_mutex_unlock(_mutex);
5808    assert (status == 0, "invariant") ;
5809    // Paranoia to ensure our locked and lock-free paths interact
5810    // correctly with each other and Java-level accesses.
5811    OrderAccess::fence();
5812    return;
5813  }
5814
5815#ifdef ASSERT
5816  // Don't catch signals while blocked; let the running threads have the signals.
5817  // (This allows a debugger to break into the running thread.)
5818  sigset_t oldsigs;
5819  sigset_t* allowdebug_blocked = os::Linux::allowdebug_blocked_signals();
5820  pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
5821#endif
5822
5823  OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
5824  jt->set_suspend_equivalent();
5825  // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
5826
5827  assert(_cur_index == -1, "invariant");
5828  if (time == 0) {
5829    _cur_index = REL_INDEX; // arbitrary choice when not timed
5830    status = pthread_cond_wait (&_cond[_cur_index], _mutex) ;
5831  } else {
5832    _cur_index = isAbsolute ? ABS_INDEX : REL_INDEX;
5833    status = os::Linux::safe_cond_timedwait (&_cond[_cur_index], _mutex, &absTime) ;
5834    if (status != 0 && WorkAroundNPTLTimedWaitHang) {
5835      pthread_cond_destroy (&_cond[_cur_index]) ;
5836      pthread_cond_init    (&_cond[_cur_index], isAbsolute ? NULL : os::Linux::condAttr());
5837    }
5838  }
5839  _cur_index = -1;
5840  assert_status(status == 0 || status == EINTR ||
5841                status == ETIME || status == ETIMEDOUT,
5842                status, "cond_timedwait");
5843
5844#ifdef ASSERT
5845  pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
5846#endif
5847
5848  _counter = 0 ;
5849  status = pthread_mutex_unlock(_mutex) ;
5850  assert_status(status == 0, status, "invariant") ;
5851  // Paranoia to ensure our locked and lock-free paths interact
5852  // correctly with each other and Java-level accesses.
5853  OrderAccess::fence();
5854
5855  // If externally suspended while waiting, re-suspend
5856  if (jt->handle_special_suspend_equivalent_condition()) {
5857    jt->java_suspend_self();
5858  }
5859}
5860
5861void Parker::unpark() {
5862  int s, status ;
5863  status = pthread_mutex_lock(_mutex);
5864  assert (status == 0, "invariant") ;
5865  s = _counter;
5866  _counter = 1;
5867  if (s < 1) {
5868    // thread might be parked
5869    if (_cur_index != -1) {
5870      // thread is definitely parked
5871      if (WorkAroundNPTLTimedWaitHang) {
5872        status = pthread_cond_signal (&_cond[_cur_index]);
5873        assert (status == 0, "invariant");
5874        status = pthread_mutex_unlock(_mutex);
5875        assert (status == 0, "invariant");
5876      } else {
5877        status = pthread_mutex_unlock(_mutex);
5878        assert (status == 0, "invariant");
5879        status = pthread_cond_signal (&_cond[_cur_index]);
5880        assert (status == 0, "invariant");
5881      }
5882    } else {
5883      pthread_mutex_unlock(_mutex);
5884      assert (status == 0, "invariant") ;
5885    }
5886  } else {
5887    pthread_mutex_unlock(_mutex);
5888    assert (status == 0, "invariant") ;
5889  }
5890}
5891
5892
5893extern char** environ;
5894
5895#ifndef __NR_fork
5896#define __NR_fork IA32_ONLY(2) IA64_ONLY(not defined) AMD64_ONLY(57)
5897#endif
5898
5899#ifndef __NR_execve
5900#define __NR_execve IA32_ONLY(11) IA64_ONLY(1033) AMD64_ONLY(59)
5901#endif
5902
5903// Run the specified command in a separate process. Return its exit value,
5904// or -1 on failure (e.g. can't fork a new process).
5905// Unlike system(), this function can be called from signal handler. It
5906// doesn't block SIGINT et al.
5907int os::fork_and_exec(char* cmd) {
5908  const char * argv[4] = {"sh", "-c", cmd, NULL};
5909
5910  // fork() in LinuxThreads/NPTL is not async-safe. It needs to run
5911  // pthread_atfork handlers and reset pthread library. All we need is a
5912  // separate process to execve. Make a direct syscall to fork process.
5913  // On IA64 there's no fork syscall, we have to use fork() and hope for
5914  // the best...
5915  pid_t pid = NOT_IA64(syscall(__NR_fork);)
5916              IA64_ONLY(fork();)
5917
5918  if (pid < 0) {
5919    // fork failed
5920    return -1;
5921
5922  } else if (pid == 0) {
5923    // child process
5924
5925    // execve() in LinuxThreads will call pthread_kill_other_threads_np()
5926    // first to kill every thread on the thread list. Because this list is
5927    // not reset by fork() (see notes above), execve() will instead kill
5928    // every thread in the parent process. We know this is the only thread
5929    // in the new process, so make a system call directly.
5930    // IA64 should use normal execve() from glibc to match the glibc fork()
5931    // above.
5932    NOT_IA64(syscall(__NR_execve, "/bin/sh", argv, environ);)
5933    IA64_ONLY(execve("/bin/sh", (char* const*)argv, environ);)
5934
5935    // execve failed
5936    _exit(-1);
5937
5938  } else  {
5939    // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
5940    // care about the actual exit code, for now.
5941
5942    int status;
5943
5944    // Wait for the child process to exit.  This returns immediately if
5945    // the child has already exited. */
5946    while (waitpid(pid, &status, 0) < 0) {
5947        switch (errno) {
5948        case ECHILD: return 0;
5949        case EINTR: break;
5950        default: return -1;
5951        }
5952    }
5953
5954    if (WIFEXITED(status)) {
5955       // The child exited normally; get its exit code.
5956       return WEXITSTATUS(status);
5957    } else if (WIFSIGNALED(status)) {
5958       // The child exited because of a signal
5959       // The best value to return is 0x80 + signal number,
5960       // because that is what all Unix shells do, and because
5961       // it allows callers to distinguish between process exit and
5962       // process death by signal.
5963       return 0x80 + WTERMSIG(status);
5964    } else {
5965       // Unknown exit code; pass it through
5966       return status;
5967    }
5968  }
5969}
5970
5971// is_headless_jre()
5972//
5973// Test for the existence of xawt/libmawt.so or libawt_xawt.so
5974// in order to report if we are running in a headless jre
5975//
5976// Since JDK8 xawt/libmawt.so was moved into the same directory
5977// as libawt.so, and renamed libawt_xawt.so
5978//
5979bool os::is_headless_jre() {
5980    struct stat statbuf;
5981    char buf[MAXPATHLEN];
5982    char libmawtpath[MAXPATHLEN];
5983    const char *xawtstr  = "/xawt/libmawt.so";
5984    const char *new_xawtstr = "/libawt_xawt.so";
5985    char *p;
5986
5987    // Get path to libjvm.so
5988    os::jvm_path(buf, sizeof(buf));
5989
5990    // Get rid of libjvm.so
5991    p = strrchr(buf, '/');
5992    if (p == NULL) return false;
5993    else *p = '\0';
5994
5995    // Get rid of client or server
5996    p = strrchr(buf, '/');
5997    if (p == NULL) return false;
5998    else *p = '\0';
5999
6000    // check xawt/libmawt.so
6001    strcpy(libmawtpath, buf);
6002    strcat(libmawtpath, xawtstr);
6003    if (::stat(libmawtpath, &statbuf) == 0) return false;
6004
6005    // check libawt_xawt.so
6006    strcpy(libmawtpath, buf);
6007    strcat(libmawtpath, new_xawtstr);
6008    if (::stat(libmawtpath, &statbuf) == 0) return false;
6009
6010    return true;
6011}
6012
6013// Get the default path to the core file
6014// Returns the length of the string
6015int os::get_core_path(char* buffer, size_t bufferSize) {
6016  const char* p = get_current_directory(buffer, bufferSize);
6017
6018  if (p == NULL) {
6019    assert(p != NULL, "failed to get current directory");
6020    return 0;
6021  }
6022
6023  return strlen(buffer);
6024}
6025
6026#ifdef JAVASE_EMBEDDED
6027//
6028// A thread to watch the '/dev/mem_notify' device, which will tell us when the OS is running low on memory.
6029//
6030MemNotifyThread* MemNotifyThread::_memnotify_thread = NULL;
6031
6032// ctor
6033//
6034MemNotifyThread::MemNotifyThread(int fd): Thread() {
6035  assert(memnotify_thread() == NULL, "we can only allocate one MemNotifyThread");
6036  _fd = fd;
6037
6038  if (os::create_thread(this, os::os_thread)) {
6039    _memnotify_thread = this;
6040    os::set_priority(this, NearMaxPriority);
6041    os::start_thread(this);
6042  }
6043}
6044
6045// Where all the work gets done
6046//
6047void MemNotifyThread::run() {
6048  assert(this == memnotify_thread(), "expected the singleton MemNotifyThread");
6049
6050  // Set up the select arguments
6051  fd_set rfds;
6052  if (_fd != -1) {
6053    FD_ZERO(&rfds);
6054    FD_SET(_fd, &rfds);
6055  }
6056
6057  // Now wait for the mem_notify device to wake up
6058  while (1) {
6059    // Wait for the mem_notify device to signal us..
6060    int rc = select(_fd+1, _fd != -1 ? &rfds : NULL, NULL, NULL, NULL);
6061    if (rc == -1) {
6062      perror("select!\n");
6063      break;
6064    } else if (rc) {
6065      //ssize_t free_before = os::available_memory();
6066      //tty->print ("Notified: Free: %dK \n",os::available_memory()/1024);
6067
6068      // The kernel is telling us there is not much memory left...
6069      // try to do something about that
6070
6071      // If we are not already in a GC, try one.
6072      if (!Universe::heap()->is_gc_active()) {
6073        Universe::heap()->collect(GCCause::_allocation_failure);
6074
6075        //ssize_t free_after = os::available_memory();
6076        //tty->print ("Post-Notify: Free: %dK\n",free_after/1024);
6077        //tty->print ("GC freed: %dK\n", (free_after - free_before)/1024);
6078      }
6079      // We might want to do something like the following if we find the GC's are not helping...
6080      // Universe::heap()->size_policy()->set_gc_time_limit_exceeded(true);
6081    }
6082  }
6083}
6084
6085//
6086// See if the /dev/mem_notify device exists, and if so, start a thread to monitor it.
6087//
6088void MemNotifyThread::start() {
6089  int    fd;
6090  fd = open ("/dev/mem_notify", O_RDONLY, 0);
6091  if (fd < 0) {
6092      return;
6093  }
6094
6095  if (memnotify_thread() == NULL) {
6096    new MemNotifyThread(fd);
6097  }
6098}
6099
6100#endif // JAVASE_EMBEDDED
6101
6102
6103/////////////// Unit tests ///////////////
6104
6105#ifndef PRODUCT
6106
6107#define test_log(...) \
6108  do {\
6109    if (VerboseInternalVMTests) { \
6110      tty->print_cr(__VA_ARGS__); \
6111      tty->flush(); \
6112    }\
6113  } while (false)
6114
6115class TestReserveMemorySpecial : AllStatic {
6116 public:
6117  static void small_page_write(void* addr, size_t size) {
6118    size_t page_size = os::vm_page_size();
6119
6120    char* end = (char*)addr + size;
6121    for (char* p = (char*)addr; p < end; p += page_size) {
6122      *p = 1;
6123    }
6124  }
6125
6126  static void test_reserve_memory_special_huge_tlbfs_only(size_t size) {
6127    if (!UseHugeTLBFS) {
6128      return;
6129    }
6130
6131    test_log("test_reserve_memory_special_huge_tlbfs_only(" SIZE_FORMAT ")", size);
6132
6133    char* addr = os::Linux::reserve_memory_special_huge_tlbfs_only(size, NULL, false);
6134
6135    if (addr != NULL) {
6136      small_page_write(addr, size);
6137
6138      os::Linux::release_memory_special_huge_tlbfs(addr, size);
6139    }
6140  }
6141
6142  static void test_reserve_memory_special_huge_tlbfs_only() {
6143    if (!UseHugeTLBFS) {
6144      return;
6145    }
6146
6147    size_t lp = os::large_page_size();
6148
6149    for (size_t size = lp; size <= lp * 10; size += lp) {
6150      test_reserve_memory_special_huge_tlbfs_only(size);
6151    }
6152  }
6153
6154  static void test_reserve_memory_special_huge_tlbfs_mixed(size_t size, size_t alignment) {
6155    if (!UseHugeTLBFS) {
6156        return;
6157    }
6158
6159    test_log("test_reserve_memory_special_huge_tlbfs_mixed(" SIZE_FORMAT ", " SIZE_FORMAT ")",
6160        size, alignment);
6161
6162    assert(size >= os::large_page_size(), "Incorrect input to test");
6163
6164    char* addr = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, NULL, false);
6165
6166    if (addr != NULL) {
6167      small_page_write(addr, size);
6168
6169      os::Linux::release_memory_special_huge_tlbfs(addr, size);
6170    }
6171  }
6172
6173  static void test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(size_t size) {
6174    size_t lp = os::large_page_size();
6175    size_t ag = os::vm_allocation_granularity();
6176
6177    for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
6178      test_reserve_memory_special_huge_tlbfs_mixed(size, alignment);
6179    }
6180  }
6181
6182  static void test_reserve_memory_special_huge_tlbfs_mixed() {
6183    size_t lp = os::large_page_size();
6184    size_t ag = os::vm_allocation_granularity();
6185
6186    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp);
6187    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp + ag);
6188    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp + lp / 2);
6189    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2);
6190    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2 + ag);
6191    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2 - ag);
6192    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2 + lp / 2);
6193    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 10);
6194    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 10 + lp / 2);
6195  }
6196
6197  static void test_reserve_memory_special_huge_tlbfs() {
6198    if (!UseHugeTLBFS) {
6199      return;
6200    }
6201
6202    test_reserve_memory_special_huge_tlbfs_only();
6203    test_reserve_memory_special_huge_tlbfs_mixed();
6204  }
6205
6206  static void test_reserve_memory_special_shm(size_t size, size_t alignment) {
6207    if (!UseSHM) {
6208      return;
6209    }
6210
6211    test_log("test_reserve_memory_special_shm(" SIZE_FORMAT ", " SIZE_FORMAT ")", size, alignment);
6212
6213    char* addr = os::Linux::reserve_memory_special_shm(size, alignment, NULL, false);
6214
6215    if (addr != NULL) {
6216      assert(is_ptr_aligned(addr, alignment), "Check");
6217      assert(is_ptr_aligned(addr, os::large_page_size()), "Check");
6218
6219      small_page_write(addr, size);
6220
6221      os::Linux::release_memory_special_shm(addr, size);
6222    }
6223  }
6224
6225  static void test_reserve_memory_special_shm() {
6226    size_t lp = os::large_page_size();
6227    size_t ag = os::vm_allocation_granularity();
6228
6229    for (size_t size = ag; size < lp * 3; size += ag) {
6230      for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
6231        test_reserve_memory_special_shm(size, alignment);
6232      }
6233    }
6234  }
6235
6236  static void test() {
6237    test_reserve_memory_special_huge_tlbfs();
6238    test_reserve_memory_special_shm();
6239  }
6240};
6241
6242void TestReserveMemorySpecial_test() {
6243  TestReserveMemorySpecial::test();
6244}
6245
6246#endif
6247