os_linux.cpp revision 9639:f0dcbc6e99b1
1275970Scy/*
2275970Scy * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
3275970Scy * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4275970Scy *
5275970Scy * This code is free software; you can redistribute it and/or modify it
6275970Scy * under the terms of the GNU General Public License version 2 only, as
7275970Scy * published by the Free Software Foundation.
8275970Scy *
9275970Scy * This code is distributed in the hope that it will be useful, but WITHOUT
10275970Scy * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11275970Scy * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12275970Scy * version 2 for more details (a copy is included in the LICENSE file that
13310419Sdelphij * accompanied this code).
14275970Scy *
15310419Sdelphij * You should have received a copy of the GNU General Public License version
16275970Scy * 2 along with this work; if not, write to the Free Software Foundation,
17310419Sdelphij * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18275970Scy *
19275970Scy * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20275970Scy * or visit www.oracle.com if you need additional information or have any
21275970Scy * questions.
22275970Scy *
23275970Scy */
24275970Scy
25275970Scy// no precompiled headers
26275970Scy#include "classfile/classLoader.hpp"
27275970Scy#include "classfile/systemDictionary.hpp"
28275970Scy#include "classfile/vmSymbols.hpp"
29275970Scy#include "code/icBuffer.hpp"
30275970Scy#include "code/vtableStubs.hpp"
31275970Scy#include "compiler/compileBroker.hpp"
32275970Scy#include "compiler/disassembler.hpp"
33275970Scy#include "interpreter/interpreter.hpp"
34275970Scy#include "jvm_linux.h"
35275970Scy#include "memory/allocation.inline.hpp"
36275970Scy#include "memory/filemap.hpp"
37275970Scy#include "mutex_linux.inline.hpp"
38290000Sglebius#include "oops/oop.inline.hpp"
39275970Scy#include "os_linux.inline.hpp"
40275970Scy#include "os_share_linux.hpp"
41275970Scy#include "prims/jniFastGetField.hpp"
42275970Scy#include "prims/jvm.h"
43275970Scy#include "prims/jvm_misc.hpp"
44275970Scy#include "runtime/arguments.hpp"
45275970Scy#include "runtime/atomic.inline.hpp"
46275970Scy#include "runtime/extendedPC.hpp"
47275970Scy#include "runtime/globals.hpp"
48275970Scy#include "runtime/interfaceSupport.hpp"
49275970Scy#include "runtime/init.hpp"
50275970Scy#include "runtime/java.hpp"
51275970Scy#include "runtime/javaCalls.hpp"
52275970Scy#include "runtime/mutexLocker.hpp"
53275970Scy#include "runtime/objectMonitor.hpp"
54275970Scy#include "runtime/orderAccess.inline.hpp"
55275970Scy#include "runtime/osThread.hpp"
56275970Scy#include "runtime/perfMemory.hpp"
57275970Scy#include "runtime/sharedRuntime.hpp"
58275970Scy#include "runtime/statSampler.hpp"
59275970Scy#include "runtime/stubRoutines.hpp"
60275970Scy#include "runtime/thread.inline.hpp"
61275970Scy#include "runtime/threadCritical.hpp"
62275970Scy#include "runtime/timer.hpp"
63275970Scy#include "semaphore_posix.hpp"
64275970Scy#include "services/attachListener.hpp"
65275970Scy#include "services/memTracker.hpp"
66275970Scy#include "services/runtimeService.hpp"
67275970Scy#include "utilities/decoder.hpp"
68275970Scy#include "utilities/defaultStream.hpp"
69275970Scy#include "utilities/events.hpp"
70275970Scy#include "utilities/elfFile.hpp"
71275970Scy#include "utilities/growableArray.hpp"
72275970Scy#include "utilities/macros.hpp"
73275970Scy#include "utilities/vmError.hpp"
74275970Scy
75275970Scy// put OS-includes here
76275970Scy# include <sys/types.h>
77275970Scy# include <sys/mman.h>
78275970Scy# include <sys/stat.h>
79275970Scy# include <sys/select.h>
80275970Scy# include <pthread.h>
81275970Scy# include <signal.h>
82275970Scy# include <errno.h>
83275970Scy# include <dlfcn.h>
84275970Scy# include <stdio.h>
85275970Scy# include <unistd.h>
86275970Scy# include <sys/resource.h>
87275970Scy# include <pthread.h>
88275970Scy# include <sys/stat.h>
89275970Scy# include <sys/time.h>
90275970Scy# include <sys/times.h>
91275970Scy# include <sys/utsname.h>
92275970Scy# include <sys/socket.h>
93275970Scy# include <sys/wait.h>
94275970Scy# include <pwd.h>
95275970Scy# include <poll.h>
96275970Scy# include <semaphore.h>
97275970Scy# include <fcntl.h>
98275970Scy# include <string.h>
99275970Scy# include <syscall.h>
100275970Scy# include <sys/sysinfo.h>
101275970Scy# include <gnu/libc-version.h>
102275970Scy# include <sys/ipc.h>
103275970Scy# include <sys/shm.h>
104275970Scy# include <link.h>
105275970Scy# include <stdint.h>
106275970Scy# include <inttypes.h>
107275970Scy# include <sys/ioctl.h>
108275970Scy
109275970Scy// if RUSAGE_THREAD for getrusage() has not been defined, do it here. The code calling
110275970Scy// getrusage() is prepared to handle the associated failure.
111275970Scy#ifndef RUSAGE_THREAD
112275970Scy  #define RUSAGE_THREAD   (1)               /* only the calling thread */
113275970Scy#endif
114275970Scy
115275970Scy#define MAX_PATH    (2 * K)
116275970Scy
117275970Scy#define MAX_SECS 100000000
118275970Scy
119275970Scy// for timer info max values which include all bits
120275970Scy#define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
121275970Scy
122275970Scy#define LARGEPAGES_BIT (1 << 6)
123275970Scy////////////////////////////////////////////////////////////////////////////////
124275970Scy// global variables
125275970Scyjulong os::Linux::_physical_memory = 0;
126275970Scy
127275970Scyaddress   os::Linux::_initial_thread_stack_bottom = NULL;
128275970Scyuintptr_t os::Linux::_initial_thread_stack_size   = 0;
129275970Scy
130275970Scyint (*os::Linux::_clock_gettime)(clockid_t, struct timespec *) = NULL;
131275970Scyint (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL;
132275970Scyint (*os::Linux::_pthread_setname_np)(pthread_t, const char*) = NULL;
133275970ScyMutex* os::Linux::_createThread_lock = NULL;
134275970Scypthread_t os::Linux::_main_thread;
135275970Scyint os::Linux::_page_size = -1;
136298770Sdelphijconst int os::Linux::_vm_default_page_size = (8 * K);
137298770Sdelphijbool os::Linux::_supports_fast_thread_cpu_time = false;
138298770Sdelphijconst char * os::Linux::_glibc_version = NULL;
139298770Sdelphijconst char * os::Linux::_libpthread_version = NULL;
140298770Sdelphijpthread_condattr_t os::Linux::_condattr[1];
141298770Sdelphij
142298770Sdelphijstatic jlong initial_time_count=0;
143298770Sdelphij
144275970Scystatic int clock_tics_per_sec = 100;
145275970Scy
146275970Scy// For diagnostics to print a message once. see run_periodic_checks
147275970Scystatic sigset_t check_signal_done;
148275970Scystatic bool check_signals = true;
149275970Scy
150275970Scy// Signal number used to suspend/resume a thread
151275970Scy
152275970Scy// do not use any signal number less than SIGSEGV, see 4355769
153275970Scystatic int SR_signum = SIGUSR2;
154275970Scysigset_t SR_sigset;
155275970Scy
156275970Scy// Declarations
157275970Scystatic void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
158275970Scy
159275970Scy// utility functions
160275970Scy
161275970Scystatic int SR_initialize();
162275970Scy
163275970Scyjulong os::available_memory() {
164275970Scy  return Linux::available_memory();
165275970Scy}
166298770Sdelphij
167275970Scyjulong os::Linux::available_memory() {
168298770Sdelphij  // values in struct sysinfo are "unsigned long"
169275970Scy  struct sysinfo si;
170298770Sdelphij  sysinfo(&si);
171275970Scy
172275970Scy  return (julong)si.freeram * si.mem_unit;
173275970Scy}
174275970Scy
175275970Scyjulong os::physical_memory() {
176275970Scy  return Linux::physical_memory();
177275970Scy}
178275970Scy
179275970Scy// Return true if user is running as root.
180275970Scy
181275970Scybool os::have_special_privileges() {
182275970Scy  static bool init = false;
183275970Scy  static bool privileges = false;
184275970Scy  if (!init) {
185275970Scy    privileges = (getuid() != geteuid()) || (getgid() != getegid());
186275970Scy    init = true;
187275970Scy  }
188275970Scy  return privileges;
189275970Scy}
190275970Scy
191275970Scy
192275970Scy#ifndef SYS_gettid
193275970Scy// i386: 224, ia64: 1105, amd64: 186, sparc 143
194275970Scy  #ifdef __ia64__
195275970Scy    #define SYS_gettid 1105
196275970Scy  #else
197275970Scy    #ifdef __i386__
198275970Scy      #define SYS_gettid 224
199275970Scy    #else
200275970Scy      #ifdef __amd64__
201275970Scy        #define SYS_gettid 186
202275970Scy      #else
203275970Scy        #ifdef __sparc__
204275970Scy          #define SYS_gettid 143
205275970Scy        #else
206275970Scy          #error define gettid for the arch
207275970Scy        #endif
208275970Scy      #endif
209275970Scy    #endif
210275970Scy  #endif
211275970Scy#endif
212275970Scy
213275970Scy// Cpu architecture string
214275970Scystatic char cpu_arch[] = HOTSPOT_LIB_ARCH;
215275970Scy
216275970Scy
217275970Scy// pid_t gettid()
218275970Scy//
219275970Scy// Returns the kernel thread id of the currently running thread. Kernel
220275970Scy// thread id is used to access /proc.
221275970Scypid_t os::Linux::gettid() {
222275970Scy  int rslt = syscall(SYS_gettid);
223275970Scy  assert(rslt != -1, "must be."); // old linuxthreads implementation?
224275970Scy  return (pid_t)rslt;
225275970Scy}
226275970Scy
227275970Scy// Most versions of linux have a bug where the number of processors are
228275970Scy// determined by looking at the /proc file system.  In a chroot environment,
229275970Scy// the system call returns 1.  This causes the VM to act as if it is
230275970Scy// a single processor and elide locking (see is_MP() call).
231275970Scystatic bool unsafe_chroot_detected = false;
232275970Scystatic const char *unstable_chroot_error = "/proc file system not found.\n"
233275970Scy                     "Java may be unstable running multithreaded in a chroot "
234275970Scy                     "environment on Linux when /proc filesystem is not mounted.";
235275970Scy
236275970Scyvoid os::Linux::initialize_system_info() {
237275970Scy  set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
238275970Scy  if (processor_count() == 1) {
239275970Scy    pid_t pid = os::Linux::gettid();
240275970Scy    char fname[32];
241275970Scy    jio_snprintf(fname, sizeof(fname), "/proc/%d", pid);
242275970Scy    FILE *fp = fopen(fname, "r");
243275970Scy    if (fp == NULL) {
244275970Scy      unsafe_chroot_detected = true;
245275970Scy    } else {
246275970Scy      fclose(fp);
247275970Scy    }
248275970Scy  }
249275970Scy  _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE);
250275970Scy  assert(processor_count() > 0, "linux error");
251275970Scy}
252275970Scy
253275970Scyvoid os::init_system_properties_values() {
254275970Scy  // The next steps are taken in the product version:
255275970Scy  //
256275970Scy  // Obtain the JAVA_HOME value from the location of libjvm.so.
257275970Scy  // This library should be located at:
258275970Scy  // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
259275970Scy  //
260275970Scy  // If "/jre/lib/" appears at the right place in the path, then we
261275970Scy  // assume libjvm.so is installed in a JDK and we use this path.
262275970Scy  //
263275970Scy  // Otherwise exit with message: "Could not create the Java virtual machine."
264275970Scy  //
265275970Scy  // The following extra steps are taken in the debugging version:
266275970Scy  //
267275970Scy  // If "/jre/lib/" does NOT appear at the right place in the path
268275970Scy  // instead of exit check for $JAVA_HOME environment variable.
269275970Scy  //
270275970Scy  // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
271275970Scy  // then we append a fake suffix "hotspot/libjvm.so" to this path so
272275970Scy  // it looks like libjvm.so is installed there
273275970Scy  // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
274275970Scy  //
275275970Scy  // Otherwise exit.
276275970Scy  //
277275970Scy  // Important note: if the location of libjvm.so changes this
278275970Scy  // code needs to be changed accordingly.
279275970Scy
280275970Scy  // See ld(1):
281275970Scy  //      The linker uses the following search paths to locate required
282275970Scy  //      shared libraries:
283275970Scy  //        1: ...
284275970Scy  //        ...
285275970Scy  //        7: The default directories, normally /lib and /usr/lib.
286275970Scy#if defined(AMD64) || defined(_LP64) && (defined(SPARC) || defined(PPC) || defined(S390))
287275970Scy  #define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib"
288275970Scy#else
289275970Scy  #define DEFAULT_LIBPATH "/lib:/usr/lib"
290275970Scy#endif
291275970Scy
292275970Scy// Base path of extensions installed on the system.
293275970Scy#define SYS_EXT_DIR     "/usr/java/packages"
294275970Scy#define EXTENSIONS_DIR  "/lib/ext"
295275970Scy
296275970Scy  // Buffer that fits several sprintfs.
297275970Scy  // Note that the space for the colon and the trailing null are provided
298298770Sdelphij  // by the nulls included by the sizeof operator.
299298770Sdelphij  const size_t bufsize =
300298770Sdelphij    MAX2((size_t)MAXPATHLEN,  // For dll_dir & friends.
301275970Scy         (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir
302275970Scy  char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
303275970Scy
304275970Scy  // sysclasspath, java_home, dll_dir
305275970Scy  {
306275970Scy    char *pslash;
307275970Scy    os::jvm_path(buf, bufsize);
308275970Scy
309275970Scy    // Found the full path to libjvm.so.
310275970Scy    // Now cut the path to <java_home>/jre if we can.
311275970Scy    pslash = strrchr(buf, '/');
312298770Sdelphij    if (pslash != NULL) {
313298770Sdelphij      *pslash = '\0';            // Get rid of /libjvm.so.
314298770Sdelphij    }
315275970Scy    pslash = strrchr(buf, '/');
316275970Scy    if (pslash != NULL) {
317275970Scy      *pslash = '\0';            // Get rid of /{client|server|hotspot}.
318275970Scy    }
319275970Scy    Arguments::set_dll_dir(buf);
320290000Sglebius
321275970Scy    if (pslash != NULL) {
322275970Scy      pslash = strrchr(buf, '/');
323275970Scy      if (pslash != NULL) {
324275970Scy        *pslash = '\0';          // Get rid of /<arch>.
325275970Scy        pslash = strrchr(buf, '/');
326275970Scy        if (pslash != NULL) {
327275970Scy          *pslash = '\0';        // Get rid of /lib.
328275970Scy        }
329275970Scy      }
330275970Scy    }
331275970Scy    Arguments::set_java_home(buf);
332275970Scy    set_boot_path('/', ':');
333275970Scy  }
334275970Scy
335275970Scy  // Where to look for native libraries.
336275970Scy  //
337275970Scy  // Note: Due to a legacy implementation, most of the library path
338275970Scy  // is set in the launcher. This was to accomodate linking restrictions
339275970Scy  // on legacy Linux implementations (which are no longer supported).
340275970Scy  // Eventually, all the library path setting will be done here.
341275970Scy  //
342275970Scy  // However, to prevent the proliferation of improperly built native
343275970Scy  // libraries, the new path component /usr/java/packages is added here.
344275970Scy  // Eventually, all the library path setting will be done here.
345275970Scy  {
346275970Scy    // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
347275970Scy    // should always exist (until the legacy problem cited above is
348275970Scy    // addressed).
349275970Scy    const char *v = ::getenv("LD_LIBRARY_PATH");
350275970Scy    const char *v_colon = ":";
351275970Scy    if (v == NULL) { v = ""; v_colon = ""; }
352298770Sdelphij    // That's +1 for the colon and +1 for the trailing '\0'.
353298770Sdelphij    char *ld_library_path = (char *)NEW_C_HEAP_ARRAY(char,
354298770Sdelphij                                                     strlen(v) + 1 +
355298770Sdelphij                                                     sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH) + 1,
356298770Sdelphij                                                     mtInternal);
357298770Sdelphij    sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib/%s:" DEFAULT_LIBPATH, v, v_colon, cpu_arch);
358298770Sdelphij    Arguments::set_library_path(ld_library_path);
359275970Scy    FREE_C_HEAP_ARRAY(char, ld_library_path);
360275970Scy  }
361275970Scy
362275970Scy  // Extensions directories.
363275970Scy  sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
364275970Scy  Arguments::set_ext_dirs(buf);
365275970Scy
366275970Scy  FREE_C_HEAP_ARRAY(char, buf);
367275970Scy
368275970Scy#undef DEFAULT_LIBPATH
369275970Scy#undef SYS_EXT_DIR
370275970Scy#undef EXTENSIONS_DIR
371275970Scy}
372298770Sdelphij
373298770Sdelphij////////////////////////////////////////////////////////////////////////////////
374298770Sdelphij// breakpoint support
375298770Sdelphij
376298770Sdelphijvoid os::breakpoint() {
377298770Sdelphij  BREAKPOINT;
378275970Scy}
379275970Scy
380275970Scyextern "C" void breakpoint() {
381275970Scy  // use debugger to set breakpoint here
382275970Scy}
383275970Scy
384275970Scy////////////////////////////////////////////////////////////////////////////////
385275970Scy// signal support
386275970Scy
387275970Scydebug_only(static bool signal_sets_initialized = false);
388275970Scystatic sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;
389275970Scy
390275970Scybool os::Linux::is_sig_ignored(int sig) {
391275970Scy  struct sigaction oact;
392275970Scy  sigaction(sig, (struct sigaction*)NULL, &oact);
393275970Scy  void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oact.sa_sigaction)
394275970Scy                                 : CAST_FROM_FN_PTR(void*,  oact.sa_handler);
395275970Scy  if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) {
396275970Scy    return true;
397298770Sdelphij  } else {
398298770Sdelphij    return false;
399298770Sdelphij  }
400298770Sdelphij}
401298770Sdelphij
402298770Sdelphijvoid os::Linux::signal_sets_init() {
403298770Sdelphij  // Should also have an assertion stating we are still single-threaded.
404275970Scy  assert(!signal_sets_initialized, "Already initialized");
405275970Scy  // Fill in signals that are necessarily unblocked for all threads in
406275970Scy  // the VM. Currently, we unblock the following signals:
407275970Scy  // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
408275970Scy  //                         by -Xrs (=ReduceSignalUsage));
409275970Scy  // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
410275970Scy  // other threads. The "ReduceSignalUsage" boolean tells us not to alter
411275970Scy  // the dispositions or masks wrt these signals.
412275970Scy  // Programs embedding the VM that want to use the above signals for their
413275970Scy  // own purposes must, at this time, use the "-Xrs" option to prevent
414275970Scy  // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
415275970Scy  // (See bug 4345157, and other related bugs).
416275970Scy  // In reality, though, unblocking these signals is really a nop, since
417275970Scy  // these signals are not blocked by default.
418275970Scy  sigemptyset(&unblocked_sigs);
419275970Scy  sigemptyset(&allowdebug_blocked_sigs);
420275970Scy  sigaddset(&unblocked_sigs, SIGILL);
421275970Scy  sigaddset(&unblocked_sigs, SIGSEGV);
422275970Scy  sigaddset(&unblocked_sigs, SIGBUS);
423275970Scy  sigaddset(&unblocked_sigs, SIGFPE);
424275970Scy#if defined(PPC64)
425275970Scy  sigaddset(&unblocked_sigs, SIGTRAP);
426275970Scy#endif
427275970Scy  sigaddset(&unblocked_sigs, SR_signum);
428275970Scy
429275970Scy  if (!ReduceSignalUsage) {
430275970Scy    if (!os::Linux::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
431275970Scy      sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
432275970Scy      sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);
433275970Scy    }
434275970Scy    if (!os::Linux::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
435275970Scy      sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
436275970Scy      sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);
437275970Scy    }
438275970Scy    if (!os::Linux::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
439275970Scy      sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
440275970Scy      sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);
441275970Scy    }
442275970Scy  }
443275970Scy  // Fill in signals that are blocked by all but the VM thread.
444275970Scy  sigemptyset(&vm_sigs);
445275970Scy  if (!ReduceSignalUsage) {
446275970Scy    sigaddset(&vm_sigs, BREAK_SIGNAL);
447275970Scy  }
448280849Scy  debug_only(signal_sets_initialized = true);
449280849Scy
450280849Scy}
451280849Scy
452280849Scy// These are signals that are unblocked while a thread is running Java.
453280849Scy// (For some reason, they get blocked by default.)
454280849Scysigset_t* os::Linux::unblocked_signals() {
455280849Scy  assert(signal_sets_initialized, "Not initialized");
456280849Scy  return &unblocked_sigs;
457280849Scy}
458280849Scy
459280849Scy// These are the signals that are blocked while a (non-VM) thread is
460280849Scy// running Java. Only the VM thread handles these signals.
461280849Scysigset_t* os::Linux::vm_signals() {
462280849Scy  assert(signal_sets_initialized, "Not initialized");
463275970Scy  return &vm_sigs;
464275970Scy}
465275970Scy
466275970Scy// These are signals that are blocked during cond_wait to allow debugger in
467275970Scysigset_t* os::Linux::allowdebug_blocked_signals() {
468275970Scy  assert(signal_sets_initialized, "Not initialized");
469275970Scy  return &allowdebug_blocked_sigs;
470275970Scy}
471275970Scy
472275970Scyvoid os::Linux::hotspot_sigmask(Thread* thread) {
473275970Scy
474275970Scy  //Save caller's signal mask before setting VM signal mask
475275970Scy  sigset_t caller_sigmask;
476275970Scy  pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask);
477275970Scy
478275970Scy  OSThread* osthread = thread->osthread();
479275970Scy  osthread->set_caller_sigmask(caller_sigmask);
480275970Scy
481275970Scy  pthread_sigmask(SIG_UNBLOCK, os::Linux::unblocked_signals(), NULL);
482275970Scy
483275970Scy  if (!ReduceSignalUsage) {
484275970Scy    if (thread->is_VM_thread()) {
485275970Scy      // Only the VM thread handles BREAK_SIGNAL ...
486275970Scy      pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
487275970Scy    } else {
488275970Scy      // ... all other threads block BREAK_SIGNAL
489275970Scy      pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
490275970Scy    }
491275970Scy  }
492275970Scy}
493275970Scy
494275970Scy//////////////////////////////////////////////////////////////////////////////
495275970Scy// detecting pthread library
496275970Scy
497275970Scyvoid os::Linux::libpthread_init() {
498275970Scy  // Save glibc and pthread version strings.
499275970Scy#if !defined(_CS_GNU_LIBC_VERSION) || \
500275970Scy    !defined(_CS_GNU_LIBPTHREAD_VERSION)
501275970Scy  #error "glibc too old (< 2.3.2)"
502275970Scy#endif
503275970Scy
504275970Scy  size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0);
505275970Scy  assert(n > 0, "cannot retrieve glibc version");
506275970Scy  char *str = (char *)malloc(n, mtInternal);
507275970Scy  confstr(_CS_GNU_LIBC_VERSION, str, n);
508275970Scy  os::Linux::set_glibc_version(str);
509275970Scy
510275970Scy  n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0);
511275970Scy  assert(n > 0, "cannot retrieve pthread version");
512275970Scy  str = (char *)malloc(n, mtInternal);
513275970Scy  confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n);
514275970Scy  os::Linux::set_libpthread_version(str);
515275970Scy}
516275970Scy
517275970Scy/////////////////////////////////////////////////////////////////////////////
518275970Scy// thread stack expansion
519275970Scy
520275970Scy// os::Linux::manually_expand_stack() takes care of expanding the thread
521275970Scy// stack. Note that this is normally not needed: pthread stacks allocate
522275970Scy// thread stack using mmap() without MAP_NORESERVE, so the stack is already
523275970Scy// committed. Therefore it is not necessary to expand the stack manually.
524275970Scy//
525275970Scy// Manually expanding the stack was historically needed on LinuxThreads
526275970Scy// thread stacks, which were allocated with mmap(MAP_GROWSDOWN). Nowadays
527275970Scy// it is kept to deal with very rare corner cases:
528275970Scy//
529275970Scy// For one, user may run the VM on an own implementation of threads
530275970Scy// whose stacks are - like the old LinuxThreads - implemented using
531275970Scy// mmap(MAP_GROWSDOWN).
532275970Scy//
533275970Scy// Also, this coding may be needed if the VM is running on the primordial
534275970Scy// thread. Normally we avoid running on the primordial thread; however,
535275970Scy// user may still invoke the VM on the primordial thread.
536275970Scy//
537275970Scy// The following historical comment describes the details about running
538275970Scy// on a thread stack allocated with mmap(MAP_GROWSDOWN):
539275970Scy
540275970Scy
541275970Scy// Force Linux kernel to expand current thread stack. If "bottom" is close
542275970Scy// to the stack guard, caller should block all signals.
543275970Scy//
544275970Scy// MAP_GROWSDOWN:
545275970Scy//   A special mmap() flag that is used to implement thread stacks. It tells
546275970Scy//   kernel that the memory region should extend downwards when needed. This
547275970Scy//   allows early versions of LinuxThreads to only mmap the first few pages
548275970Scy//   when creating a new thread. Linux kernel will automatically expand thread
549275970Scy//   stack as needed (on page faults).
550275970Scy//
551275970Scy//   However, because the memory region of a MAP_GROWSDOWN stack can grow on
552275970Scy//   demand, if a page fault happens outside an already mapped MAP_GROWSDOWN
553275970Scy//   region, it's hard to tell if the fault is due to a legitimate stack
554275970Scy//   access or because of reading/writing non-exist memory (e.g. buffer
555275970Scy//   overrun). As a rule, if the fault happens below current stack pointer,
556275970Scy//   Linux kernel does not expand stack, instead a SIGSEGV is sent to the
557275970Scy//   application (see Linux kernel fault.c).
558275970Scy//
559275970Scy//   This Linux feature can cause SIGSEGV when VM bangs thread stack for
560275970Scy//   stack overflow detection.
561290000Sglebius//
562298770Sdelphij//   Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do
563275970Scy//   not use MAP_GROWSDOWN.
564275970Scy//
565275970Scy// To get around the problem and allow stack banging on Linux, we need to
566275970Scy// manually expand thread stack after receiving the SIGSEGV.
567275970Scy//
568275970Scy// There are two ways to expand thread stack to address "bottom", we used
569275970Scy// both of them in JVM before 1.5:
570275970Scy//   1. adjust stack pointer first so that it is below "bottom", and then
571275970Scy//      touch "bottom"
572275970Scy//   2. mmap() the page in question
573275970Scy//
574275970Scy// Now alternate signal stack is gone, it's harder to use 2. For instance,
575275970Scy// if current sp is already near the lower end of page 101, and we need to
576275970Scy// call mmap() to map page 100, it is possible that part of the mmap() frame
577275970Scy// will be placed in page 100. When page 100 is mapped, it is zero-filled.
578275970Scy// That will destroy the mmap() frame and cause VM to crash.
579275970Scy//
580275970Scy// The following code works by adjusting sp first, then accessing the "bottom"
581275970Scy// page to force a page fault. Linux kernel will then automatically expand the
582275970Scy// stack mapping.
583275970Scy//
584275970Scy// _expand_stack_to() assumes its frame size is less than page size, which
585275970Scy// should always be true if the function is not inlined.
586275970Scy
587275970Scy#if __GNUC__ < 3    // gcc 2.x does not support noinline attribute
588275970Scy  #define NOINLINE
589275970Scy#else
590275970Scy  #define NOINLINE __attribute__ ((noinline))
591275970Scy#endif
592275970Scy
593275970Scystatic void _expand_stack_to(address bottom) NOINLINE;
594275970Scy
595275970Scystatic void _expand_stack_to(address bottom) {
596275970Scy  address sp;
597275970Scy  size_t size;
598275970Scy  volatile char *p;
599275970Scy
600275970Scy  // Adjust bottom to point to the largest address within the same page, it
601275970Scy  // gives us a one-page buffer if alloca() allocates slightly more memory.
602275970Scy  bottom = (address)align_size_down((uintptr_t)bottom, os::Linux::page_size());
603275970Scy  bottom += os::Linux::page_size() - 1;
604275970Scy
605275970Scy  // sp might be slightly above current stack pointer; if that's the case, we
606275970Scy  // will alloca() a little more space than necessary, which is OK. Don't use
607275970Scy  // os::current_stack_pointer(), as its result can be slightly below current
608275970Scy  // stack pointer, causing us to not alloca enough to reach "bottom".
609275970Scy  sp = (address)&sp;
610275970Scy
611275970Scy  if (sp > bottom) {
612275970Scy    size = sp - bottom;
613275970Scy    p = (volatile char *)alloca(size);
614275970Scy    assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?");
615275970Scy    p[0] = '\0';
616275970Scy  }
617275970Scy}
618275970Scy
619275970Scybool os::Linux::manually_expand_stack(JavaThread * t, address addr) {
620275970Scy  assert(t!=NULL, "just checking");
621275970Scy  assert(t->osthread()->expanding_stack(), "expand should be set");
622275970Scy  assert(t->stack_base() != NULL, "stack_base was not initialized");
623275970Scy
624275970Scy  if (addr <  t->stack_base() && addr >= t->stack_yellow_zone_base()) {
625275970Scy    sigset_t mask_all, old_sigset;
626275970Scy    sigfillset(&mask_all);
627275970Scy    pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset);
628290000Sglebius    _expand_stack_to(addr);
629275970Scy    pthread_sigmask(SIG_SETMASK, &old_sigset, NULL);
630290000Sglebius    return true;
631275970Scy  }
632275970Scy  return false;
633275970Scy}
634275970Scy
635275970Scy//////////////////////////////////////////////////////////////////////////////
636290000Sglebius// create new thread
637275970Scy
638275970Scy// Thread start routine for all newly created threads
639275970Scystatic void *java_start(Thread *thread) {
640275970Scy  // Try to randomize the cache line index of hot stack frames.
641275970Scy  // This helps when threads of the same stack traces evict each other's
642275970Scy  // cache lines. The threads can be either from the same JVM instance, or
643275970Scy  // from different JVM instances. The benefit is especially true for
644275970Scy  // processors with hyperthreading technology.
645275970Scy  static int counter = 0;
646275970Scy  int pid = os::current_process_id();
647275970Scy  alloca(((pid ^ counter++) & 7) * 128);
648275970Scy
649275970Scy  ThreadLocalStorage::set_thread(thread);
650290000Sglebius
651275970Scy  OSThread* osthread = thread->osthread();
652275970Scy  Monitor* sync = osthread->startThread_lock();
653275970Scy
654275970Scy  osthread->set_thread_id(os::current_thread_id());
655275970Scy
656290000Sglebius  if (UseNUMA) {
657275970Scy    int lgrp_id = os::numa_get_group_id();
658275970Scy    if (lgrp_id != -1) {
659275970Scy      thread->set_lgrp_id(lgrp_id);
660290000Sglebius    }
661275970Scy  }
662275970Scy  // initialize signal mask for this thread
663275970Scy  os::Linux::hotspot_sigmask(thread);
664275970Scy
665275970Scy  // initialize floating point control register
666275970Scy  os::Linux::init_thread_fpu_state();
667275970Scy
668275970Scy  // handshaking with parent thread
669275970Scy  {
670275970Scy    MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag);
671275970Scy
672275970Scy    // notify parent thread
673275970Scy    osthread->set_state(INITIALIZED);
674275970Scy    sync->notify_all();
675275970Scy
676275970Scy    // wait until os::start_thread()
677275970Scy    while (osthread->get_state() == INITIALIZED) {
678275970Scy      sync->wait(Mutex::_no_safepoint_check_flag);
679275970Scy    }
680275970Scy  }
681275970Scy
682275970Scy  // call one more level start routine
683275970Scy  thread->run();
684275970Scy
685275970Scy  return 0;
686275970Scy}
687275970Scy
688275970Scybool os::create_thread(Thread* thread, ThreadType thr_type,
689275970Scy                       size_t stack_size) {
690275970Scy  assert(thread->osthread() == NULL, "caller responsible");
691275970Scy
692275970Scy  // Allocate the OSThread object
693275970Scy  OSThread* osthread = new OSThread(NULL, NULL);
694275970Scy  if (osthread == NULL) {
695275970Scy    return false;
696275970Scy  }
697275970Scy
698275970Scy  // set the correct thread state
699275970Scy  osthread->set_thread_type(thr_type);
700275970Scy
701275970Scy  // Initial state is ALLOCATED but not INITIALIZED
702275970Scy  osthread->set_state(ALLOCATED);
703275970Scy
704275970Scy  thread->set_osthread(osthread);
705275970Scy
706275970Scy  // init thread attributes
707290000Sglebius  pthread_attr_t attr;
708275970Scy  pthread_attr_init(&attr);
709275970Scy  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
710275970Scy
711275970Scy  // stack size
712275970Scy  // calculate stack size if it's not specified by caller
713275970Scy  if (stack_size == 0) {
714275970Scy    stack_size = os::Linux::default_stack_size(thr_type);
715275970Scy
716275970Scy    switch (thr_type) {
717275970Scy    case os::java_thread:
718275970Scy      // Java threads use ThreadStackSize which default value can be
719275970Scy      // changed with the flag -Xss
720275970Scy      assert(JavaThread::stack_size_at_create() > 0, "this should be set");
721275970Scy      stack_size = JavaThread::stack_size_at_create();
722275970Scy      break;
723275970Scy    case os::compiler_thread:
724275970Scy      if (CompilerThreadStackSize > 0) {
725275970Scy        stack_size = (size_t)(CompilerThreadStackSize * K);
726275970Scy        break;
727275970Scy      } // else fall through:
728275970Scy        // use VMThreadStackSize if CompilerThreadStackSize is not defined
729275970Scy    case os::vm_thread:
730275970Scy    case os::pgc_thread:
731275970Scy    case os::cgc_thread:
732275970Scy    case os::watcher_thread:
733275970Scy      if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);
734275970Scy      break;
735275970Scy    }
736275970Scy  }
737275970Scy
738275970Scy  stack_size = MAX2(stack_size, os::Linux::min_stack_allowed);
739275970Scy  pthread_attr_setstacksize(&attr, stack_size);
740275970Scy
741275970Scy  // glibc guard page
742275970Scy  pthread_attr_setguardsize(&attr, os::Linux::default_guard_size(thr_type));
743275970Scy
744275970Scy  ThreadState state;
745275970Scy
746275970Scy  {
747275970Scy    pthread_t tid;
748275970Scy    int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
749275970Scy
750275970Scy    pthread_attr_destroy(&attr);
751275970Scy
752275970Scy    if (ret != 0) {
753275970Scy      if (PrintMiscellaneous && (Verbose || WizardMode)) {
754290000Sglebius        perror("pthread_create()");
755275970Scy      }
756275970Scy      // Need to clean up stuff we've allocated so far
757275970Scy      thread->set_osthread(NULL);
758275970Scy      delete osthread;
759275970Scy      return false;
760275970Scy    }
761275970Scy
762275970Scy    // Store pthread info into the OSThread
763275970Scy    osthread->set_pthread_id(tid);
764275970Scy
765275970Scy    // Wait until child thread is either initialized or aborted
766275970Scy    {
767275970Scy      Monitor* sync_with_child = osthread->startThread_lock();
768298770Sdelphij      MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
769275970Scy      while ((state = osthread->get_state()) == ALLOCATED) {
770275970Scy        sync_with_child->wait(Mutex::_no_safepoint_check_flag);
771275970Scy      }
772275970Scy    }
773275970Scy  }
774275970Scy
775275970Scy  // Aborted due to thread limit being reached
776275970Scy  if (state == ZOMBIE) {
777275970Scy    thread->set_osthread(NULL);
778275970Scy    delete osthread;
779275970Scy    return false;
780275970Scy  }
781275970Scy
782275970Scy  // The thread is returned suspended (in state INITIALIZED),
783275970Scy  // and is started higher up in the call chain
784275970Scy  assert(state == INITIALIZED, "race condition");
785275970Scy  return true;
786275970Scy}
787275970Scy
788275970Scy/////////////////////////////////////////////////////////////////////////////
789275970Scy// attach existing thread
790275970Scy
791275970Scy// bootstrap the main thread
792275970Scybool os::create_main_thread(JavaThread* thread) {
793275970Scy  assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread");
794275970Scy  return create_attached_thread(thread);
795275970Scy}
796275970Scy
797275970Scybool os::create_attached_thread(JavaThread* thread) {
798275970Scy#ifdef ASSERT
799275970Scy  thread->verify_not_published();
800275970Scy#endif
801275970Scy
802275970Scy  // Allocate the OSThread object
803275970Scy  OSThread* osthread = new OSThread(NULL, NULL);
804275970Scy
805275970Scy  if (osthread == NULL) {
806275970Scy    return false;
807275970Scy  }
808275970Scy
809275970Scy  // Store pthread info into the OSThread
810275970Scy  osthread->set_thread_id(os::Linux::gettid());
811275970Scy  osthread->set_pthread_id(::pthread_self());
812275970Scy
813275970Scy  // initialize floating point control register
814275970Scy  os::Linux::init_thread_fpu_state();
815275970Scy
816275970Scy  // Initial thread state is RUNNABLE
817275970Scy  osthread->set_state(RUNNABLE);
818275970Scy
819275970Scy  thread->set_osthread(osthread);
820275970Scy
821275970Scy  if (UseNUMA) {
822275970Scy    int lgrp_id = os::numa_get_group_id();
823275970Scy    if (lgrp_id != -1) {
824275970Scy      thread->set_lgrp_id(lgrp_id);
825275970Scy    }
826275970Scy  }
827275970Scy
828275970Scy  if (os::Linux::is_initial_thread()) {
829275970Scy    // If current thread is initial thread, its stack is mapped on demand,
830275970Scy    // see notes about MAP_GROWSDOWN. Here we try to force kernel to map
831275970Scy    // the entire stack region to avoid SEGV in stack banging.
832275970Scy    // It is also useful to get around the heap-stack-gap problem on SuSE
833275970Scy    // kernel (see 4821821 for details). We first expand stack to the top
834275970Scy    // of yellow zone, then enable stack yellow zone (order is significant,
835275970Scy    // enabling yellow zone first will crash JVM on SuSE Linux), so there
836275970Scy    // is no gap between the last two virtual memory regions.
837275970Scy
838275970Scy    JavaThread *jt = (JavaThread *)thread;
839275970Scy    address addr = jt->stack_yellow_zone_base();
840275970Scy    assert(addr != NULL, "initialization problem?");
841275970Scy    assert(jt->stack_available(addr) > 0, "stack guard should not be enabled");
842275970Scy
843275970Scy    osthread->set_expanding_stack();
844275970Scy    os::Linux::manually_expand_stack(jt, addr);
845275970Scy    osthread->clear_expanding_stack();
846275970Scy  }
847275970Scy
848275970Scy  // initialize signal mask for this thread
849275970Scy  // and save the caller's signal mask
850275970Scy  os::Linux::hotspot_sigmask(thread);
851275970Scy
852275970Scy  return true;
853275970Scy}
854290000Sglebius
855275970Scyvoid os::pd_start_thread(Thread* thread) {
856275970Scy  OSThread * osthread = thread->osthread();
857275970Scy  assert(osthread->get_state() != INITIALIZED, "just checking");
858275970Scy  Monitor* sync_with_child = osthread->startThread_lock();
859275970Scy  MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag);
860275970Scy  sync_with_child->notify();
861275970Scy}
862275970Scy
863275970Scy// Free Linux resources related to the OSThread
864275970Scyvoid os::free_thread(OSThread* osthread) {
865275970Scy  assert(osthread != NULL, "osthread not set");
866275970Scy
867275970Scy  if (Thread::current()->osthread() == osthread) {
868275970Scy    // Restore caller's signal mask
869275970Scy    sigset_t sigmask = osthread->caller_sigmask();
870275970Scy    pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
871275970Scy  }
872275970Scy
873275970Scy  delete osthread;
874275970Scy}
875275970Scy
876275970Scy//////////////////////////////////////////////////////////////////////////////
877275970Scy// thread local storage
878275970Scy
879290000Sglebius// Restore the thread pointer if the destructor is called. This is in case
880275970Scy// someone from JNI code sets up a destructor with pthread_key_create to run
881275970Scy// detachCurrentThread on thread death. Unless we restore the thread pointer we
882275970Scy// will hang or crash. When detachCurrentThread is called the key will be set
883275970Scy// to null and we will not be called again. If detachCurrentThread is never
884275970Scy// called we could loop forever depending on the pthread implementation.
885275970Scystatic void restore_thread_pointer(void* p) {
886275970Scy  Thread* thread = (Thread*) p;
887275970Scy  os::thread_local_storage_at_put(ThreadLocalStorage::thread_index(), thread);
888290000Sglebius}
889275970Scy
890290000Sglebiusint os::allocate_thread_local_storage() {
891275970Scy  pthread_key_t key;
892275970Scy  int rslt = pthread_key_create(&key, restore_thread_pointer);
893275970Scy  assert(rslt == 0, "cannot allocate thread local storage");
894275970Scy  return (int)key;
895275970Scy}
896275970Scy
897275970Scy// Note: This is currently not used by VM, as we don't destroy TLS key
898275970Scy// on VM exit.
899275970Scyvoid os::free_thread_local_storage(int index) {
900275970Scy  int rslt = pthread_key_delete((pthread_key_t)index);
901275970Scy  assert(rslt == 0, "invalid index");
902275970Scy}
903275970Scy
904275970Scyvoid os::thread_local_storage_at_put(int index, void* value) {
905275970Scy  int rslt = pthread_setspecific((pthread_key_t)index, value);
906275970Scy  assert(rslt == 0, "pthread_setspecific failed");
907275970Scy}
908275970Scy
909275970Scyextern "C" Thread* get_thread() {
910275970Scy  return ThreadLocalStorage::thread();
911275970Scy}
912275970Scy
913275970Scy//////////////////////////////////////////////////////////////////////////////
914275970Scy// initial thread
915275970Scy
916275970Scy// Check if current thread is the initial thread, similar to Solaris thr_main.
917275970Scybool os::Linux::is_initial_thread(void) {
918275970Scy  char dummy;
919275970Scy  // If called before init complete, thread stack bottom will be null.
920275970Scy  // Can be called if fatal error occurs before initialization.
921275970Scy  if (initial_thread_stack_bottom() == NULL) return false;
922275970Scy  assert(initial_thread_stack_bottom() != NULL &&
923275970Scy         initial_thread_stack_size()   != 0,
924275970Scy         "os::init did not locate initial thread's stack region");
925275970Scy  if ((address)&dummy >= initial_thread_stack_bottom() &&
926275970Scy      (address)&dummy < initial_thread_stack_bottom() + initial_thread_stack_size()) {
927275970Scy    return true;
928290000Sglebius  } else {
929275970Scy    return false;
930275970Scy  }
931275970Scy}
932275970Scy
933275970Scy// Find the virtual memory area that contains addr
934275970Scystatic bool find_vma(address addr, address* vma_low, address* vma_high) {
935275970Scy  FILE *fp = fopen("/proc/self/maps", "r");
936275970Scy  if (fp) {
937275970Scy    address low, high;
938275970Scy    while (!feof(fp)) {
939275970Scy      if (fscanf(fp, "%p-%p", &low, &high) == 2) {
940275970Scy        if (low <= addr && addr < high) {
941275970Scy          if (vma_low)  *vma_low  = low;
942275970Scy          if (vma_high) *vma_high = high;
943275970Scy          fclose(fp);
944275970Scy          return true;
945275970Scy        }
946275970Scy      }
947275970Scy      for (;;) {
948275970Scy        int ch = fgetc(fp);
949275970Scy        if (ch == EOF || ch == (int)'\n') break;
950275970Scy      }
951275970Scy    }
952275970Scy    fclose(fp);
953275970Scy  }
954275970Scy  return false;
955275970Scy}
956275970Scy
957275970Scy// Locate initial thread stack. This special handling of initial thread stack
958275970Scy// is needed because pthread_getattr_np() on most (all?) Linux distros returns
959275970Scy// bogus value for initial thread.
960275970Scyvoid os::Linux::capture_initial_stack(size_t max_size) {
961275970Scy  // stack size is the easy part, get it from RLIMIT_STACK
962275970Scy  size_t stack_size;
963275970Scy  struct rlimit rlim;
964275970Scy  getrlimit(RLIMIT_STACK, &rlim);
965275970Scy  stack_size = rlim.rlim_cur;
966275970Scy
967275970Scy  // 6308388: a bug in ld.so will relocate its own .data section to the
968275970Scy  //   lower end of primordial stack; reduce ulimit -s value a little bit
969275970Scy  //   so we won't install guard page on ld.so's data section.
970275970Scy  stack_size -= 2 * page_size();
971275970Scy
972275970Scy  // 4441425: avoid crash with "unlimited" stack size on SuSE 7.1 or Redhat
973275970Scy  //   7.1, in both cases we will get 2G in return value.
974275970Scy  // 4466587: glibc 2.2.x compiled w/o "--enable-kernel=2.4.0" (RH 7.0,
975298770Sdelphij  //   SuSE 7.2, Debian) can not handle alternate signal stack correctly
976298770Sdelphij  //   for initial thread if its stack size exceeds 6M. Cap it at 2M,
977275970Scy  //   in case other parts in glibc still assumes 2M max stack size.
978275970Scy  // FIXME: alt signal stack is gone, maybe we can relax this constraint?
979275970Scy  // Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small
980275970Scy  if (stack_size > 2 * K * K IA64_ONLY(*2)) {
981275970Scy    stack_size = 2 * K * K IA64_ONLY(*2);
982275970Scy  }
983275970Scy  // Try to figure out where the stack base (top) is. This is harder.
984275970Scy  //
985275970Scy  // When an application is started, glibc saves the initial stack pointer in
986275970Scy  // a global variable "__libc_stack_end", which is then used by system
987275970Scy  // libraries. __libc_stack_end should be pretty close to stack top. The
988298770Sdelphij  // variable is available since the very early days. However, because it is
989275970Scy  // a private interface, it could disappear in the future.
990275970Scy  //
991275970Scy  // Linux kernel saves start_stack information in /proc/<pid>/stat. Similar
992275970Scy  // to __libc_stack_end, it is very close to stack top, but isn't the real
993275970Scy  // stack top. Note that /proc may not exist if VM is running as a chroot
994275970Scy  // program, so reading /proc/<pid>/stat could fail. Also the contents of
995275970Scy  // /proc/<pid>/stat could change in the future (though unlikely).
996275970Scy  //
997275970Scy  // We try __libc_stack_end first. If that doesn't work, look for
998275970Scy  // /proc/<pid>/stat. If neither of them works, we use current stack pointer
999275970Scy  // as a hint, which should work well in most cases.
1000275970Scy
1001275970Scy  uintptr_t stack_start;
1002275970Scy
1003275970Scy  // try __libc_stack_end first
1004275970Scy  uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end");
1005275970Scy  if (p && *p) {
1006275970Scy    stack_start = *p;
1007275970Scy  } else {
1008275970Scy    // see if we can get the start_stack field from /proc/self/stat
1009275970Scy    FILE *fp;
1010275970Scy    int pid;
1011275970Scy    char state;
1012275970Scy    int ppid;
1013275970Scy    int pgrp;
1014275970Scy    int session;
1015275970Scy    int nr;
1016290000Sglebius    int tpgrp;
1017290000Sglebius    unsigned long flags;
1018275970Scy    unsigned long minflt;
1019290000Sglebius    unsigned long cminflt;
1020275970Scy    unsigned long majflt;
1021275970Scy    unsigned long cmajflt;
1022275970Scy    unsigned long utime;
1023275970Scy    unsigned long stime;
1024275970Scy    long cutime;
1025275970Scy    long cstime;
1026275970Scy    long prio;
1027275970Scy    long nice;
1028275970Scy    long junk;
1029275970Scy    long it_real;
1030275970Scy    uintptr_t start;
1031275970Scy    uintptr_t vsize;
1032275970Scy    intptr_t rss;
1033290000Sglebius    uintptr_t rsslim;
1034275970Scy    uintptr_t scodes;
1035275970Scy    uintptr_t ecode;
1036290000Sglebius    int i;
1037275970Scy
1038275970Scy    // Figure what the primordial thread stack base is. Code is inspired
1039275970Scy    // by email from Hans Boehm. /proc/self/stat begins with current pid,
1040275970Scy    // followed by command name surrounded by parentheses, state, etc.
1041275970Scy    char stat[2048];
1042275970Scy    int statlen;
1043275970Scy
1044275970Scy    fp = fopen("/proc/self/stat", "r");
1045275970Scy    if (fp) {
1046275970Scy      statlen = fread(stat, 1, 2047, fp);
1047275970Scy      stat[statlen] = '\0';
1048275970Scy      fclose(fp);
1049275970Scy
1050275970Scy      // Skip pid and the command string. Note that we could be dealing with
1051275970Scy      // weird command names, e.g. user could decide to rename java launcher
1052275970Scy      // to "java 1.4.2 :)", then the stat file would look like
1053275970Scy      //                1234 (java 1.4.2 :)) R ... ...
1054275970Scy      // We don't really need to know the command string, just find the last
1055275970Scy      // occurrence of ")" and then start parsing from there. See bug 4726580.
1056275970Scy      char * s = strrchr(stat, ')');
1057275970Scy
1058275970Scy      i = 0;
1059290000Sglebius      if (s) {
1060275970Scy        // Skip blank chars
1061290000Sglebius        do { s++; } while (s && isspace(*s));
1062275970Scy
1063275970Scy#define _UFM UINTX_FORMAT
1064275970Scy#define _DFM INTX_FORMAT
1065275970Scy
1066275970Scy        //                                     1   1   1   1   1   1   1   1   1   1   2   2    2    2    2    2    2    2    2
1067275970Scy        //              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
1068275970Scy        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,
1069275970Scy                   &state,          // 3  %c
1070275970Scy                   &ppid,           // 4  %d
1071275970Scy                   &pgrp,           // 5  %d
1072275970Scy                   &session,        // 6  %d
1073275970Scy                   &nr,             // 7  %d
1074275970Scy                   &tpgrp,          // 8  %d
1075275970Scy                   &flags,          // 9  %lu
1076275970Scy                   &minflt,         // 10 %lu
1077275970Scy                   &cminflt,        // 11 %lu
1078275970Scy                   &majflt,         // 12 %lu
1079275970Scy                   &cmajflt,        // 13 %lu
1080275970Scy                   &utime,          // 14 %lu
1081275970Scy                   &stime,          // 15 %lu
1082275970Scy                   &cutime,         // 16 %ld
1083275970Scy                   &cstime,         // 17 %ld
1084275970Scy                   &prio,           // 18 %ld
1085275970Scy                   &nice,           // 19 %ld
1086275970Scy                   &junk,           // 20 %ld
1087275970Scy                   &it_real,        // 21 %ld
1088275970Scy                   &start,          // 22 UINTX_FORMAT
1089275970Scy                   &vsize,          // 23 UINTX_FORMAT
1090275970Scy                   &rss,            // 24 INTX_FORMAT
1091275970Scy                   &rsslim,         // 25 UINTX_FORMAT
1092275970Scy                   &scodes,         // 26 UINTX_FORMAT
1093275970Scy                   &ecode,          // 27 UINTX_FORMAT
1094275970Scy                   &stack_start);   // 28 UINTX_FORMAT
1095275970Scy      }
1096275970Scy
1097275970Scy#undef _UFM
1098275970Scy#undef _DFM
1099275970Scy
1100275970Scy      if (i != 28 - 2) {
1101275970Scy        assert(false, "Bad conversion from /proc/self/stat");
1102275970Scy        // product mode - assume we are the initial thread, good luck in the
1103275970Scy        // embedded case.
1104275970Scy        warning("Can't detect initial thread stack location - bad conversion");
1105275970Scy        stack_start = (uintptr_t) &rlim;
1106275970Scy      }
1107275970Scy    } else {
1108275970Scy      // For some reason we can't open /proc/self/stat (for example, running on
1109275970Scy      // FreeBSD with a Linux emulator, or inside chroot), this should work for
1110275970Scy      // most cases, so don't abort:
1111275970Scy      warning("Can't detect initial thread stack location - no /proc/self/stat");
1112275970Scy      stack_start = (uintptr_t) &rlim;
1113275970Scy    }
1114275970Scy  }
1115275970Scy
1116275970Scy  // Now we have a pointer (stack_start) very close to the stack top, the
1117275970Scy  // next thing to do is to figure out the exact location of stack top. We
1118275970Scy  // can find out the virtual memory area that contains stack_start by
1119275970Scy  // reading /proc/self/maps, it should be the last vma in /proc/self/maps,
1120275970Scy  // and its upper limit is the real stack top. (again, this would fail if
1121275970Scy  // running inside chroot, because /proc may not exist.)
1122275970Scy
1123275970Scy  uintptr_t stack_top;
1124275970Scy  address low, high;
1125275970Scy  if (find_vma((address)stack_start, &low, &high)) {
1126275970Scy    // success, "high" is the true stack top. (ignore "low", because initial
1127275970Scy    // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.)
1128275970Scy    stack_top = (uintptr_t)high;
1129275970Scy  } else {
1130275970Scy    // failed, likely because /proc/self/maps does not exist
1131275970Scy    warning("Can't detect initial thread stack location - find_vma failed");
1132275970Scy    // best effort: stack_start is normally within a few pages below the real
1133275970Scy    // stack top, use it as stack top, and reduce stack size so we won't put
1134275970Scy    // guard page outside stack.
1135275970Scy    stack_top = stack_start;
1136275970Scy    stack_size -= 16 * page_size();
1137275970Scy  }
1138290000Sglebius
1139275970Scy  // stack_top could be partially down the page so align it
1140275970Scy  stack_top = align_size_up(stack_top, page_size());
1141275970Scy
1142275970Scy  if (max_size && stack_size > max_size) {
1143275970Scy    _initial_thread_stack_size = max_size;
1144275970Scy  } else {
1145275970Scy    _initial_thread_stack_size = stack_size;
1146275970Scy  }
1147275970Scy
1148275970Scy  _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size());
1149275970Scy  _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size;
1150298770Sdelphij}
1151275970Scy
1152275970Scy////////////////////////////////////////////////////////////////////////////////
1153275970Scy// time support
1154290000Sglebius
1155275970Scy// Time since start-up in seconds to a fine granularity.
1156275970Scy// Used by VMSelfDestructTimer and the MemProfiler.
1157275970Scydouble os::elapsedTime() {
1158275970Scy
1159275970Scy  return ((double)os::elapsed_counter()) / os::elapsed_frequency(); // nanosecond resolution
1160275970Scy}
1161275970Scy
1162275970Scyjlong os::elapsed_counter() {
1163275970Scy  return javaTimeNanos() - initial_time_count;
1164275970Scy}
1165275970Scy
1166275970Scyjlong os::elapsed_frequency() {
1167275970Scy  return NANOSECS_PER_SEC; // nanosecond resolution
1168275970Scy}
1169275970Scy
1170275970Scybool os::supports_vtime() { return true; }
1171275970Scybool os::enable_vtime()   { return false; }
1172275970Scybool os::vtime_enabled()  { return false; }
1173275970Scy
1174275970Scydouble os::elapsedVTime() {
1175275970Scy  struct rusage usage;
1176275970Scy  int retval = getrusage(RUSAGE_THREAD, &usage);
1177275970Scy  if (retval == 0) {
1178275970Scy    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);
1179275970Scy  } else {
1180275970Scy    // better than nothing, but not much
1181275970Scy    return elapsedTime();
1182275970Scy  }
1183275970Scy}
1184275970Scy
1185275970Scyjlong os::javaTimeMillis() {
1186275970Scy  timeval time;
1187275970Scy  int status = gettimeofday(&time, NULL);
1188275970Scy  assert(status != -1, "linux error");
1189275970Scy  return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
1190275970Scy}
1191275970Scy
1192275970Scyvoid os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) {
1193275970Scy  timeval time;
1194275970Scy  int status = gettimeofday(&time, NULL);
1195275970Scy  assert(status != -1, "linux error");
1196275970Scy  seconds = jlong(time.tv_sec);
1197275970Scy  nanos = jlong(time.tv_usec) * 1000;
1198275970Scy}
1199275970Scy
1200275970Scy
1201275970Scy#ifndef CLOCK_MONOTONIC
1202275970Scy  #define CLOCK_MONOTONIC (1)
1203275970Scy#endif
1204275970Scy
1205275970Scyvoid os::Linux::clock_init() {
1206275970Scy  // we do dlopen's in this particular order due to bug in linux
1207275970Scy  // dynamical loader (see 6348968) leading to crash on exit
1208275970Scy  void* handle = dlopen("librt.so.1", RTLD_LAZY);
1209275970Scy  if (handle == NULL) {
1210275970Scy    handle = dlopen("librt.so", RTLD_LAZY);
1211275970Scy  }
1212275970Scy
1213275970Scy  if (handle) {
1214275970Scy    int (*clock_getres_func)(clockid_t, struct timespec*) =
1215275970Scy           (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres");
1216275970Scy    int (*clock_gettime_func)(clockid_t, struct timespec*) =
1217275970Scy           (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime");
1218275970Scy    if (clock_getres_func && clock_gettime_func) {
1219275970Scy      // See if monotonic clock is supported by the kernel. Note that some
1220275970Scy      // early implementations simply return kernel jiffies (updated every
1221275970Scy      // 1/100 or 1/1000 second). It would be bad to use such a low res clock
1222275970Scy      // for nano time (though the monotonic property is still nice to have).
1223275970Scy      // It's fixed in newer kernels, however clock_getres() still returns
1224275970Scy      // 1/HZ. We check if clock_getres() works, but will ignore its reported
1225275970Scy      // resolution for now. Hopefully as people move to new kernels, this
1226275970Scy      // won't be a problem.
1227275970Scy      struct timespec res;
1228275970Scy      struct timespec tp;
1229275970Scy      if (clock_getres_func (CLOCK_MONOTONIC, &res) == 0 &&
1230275970Scy          clock_gettime_func(CLOCK_MONOTONIC, &tp)  == 0) {
1231275970Scy        // yes, monotonic clock is supported
1232275970Scy        _clock_gettime = clock_gettime_func;
1233275970Scy        return;
1234275970Scy      } else {
1235275970Scy        // close librt if there is no monotonic clock
1236275970Scy        dlclose(handle);
1237275970Scy      }
1238275970Scy    }
1239275970Scy  }
1240275970Scy  warning("No monotonic clock was available - timed services may " \
1241275970Scy          "be adversely affected if the time-of-day clock changes");
1242275970Scy}
1243275970Scy
1244275970Scy#ifndef SYS_clock_getres
1245275970Scy  #if defined(IA32) || defined(AMD64)
1246275970Scy    #define SYS_clock_getres IA32_ONLY(266)  AMD64_ONLY(229)
1247275970Scy    #define sys_clock_getres(x,y)  ::syscall(SYS_clock_getres, x, y)
1248275970Scy  #else
1249275970Scy    #warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time"
1250275970Scy    #define sys_clock_getres(x,y)  -1
1251275970Scy  #endif
1252275970Scy#else
1253275970Scy  #define sys_clock_getres(x,y)  ::syscall(SYS_clock_getres, x, y)
1254275970Scy#endif
1255275970Scy
1256275970Scyvoid os::Linux::fast_thread_clock_init() {
1257275970Scy  if (!UseLinuxPosixThreadCPUClocks) {
1258275970Scy    return;
1259275970Scy  }
1260275970Scy  clockid_t clockid;
1261275970Scy  struct timespec tp;
1262275970Scy  int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) =
1263275970Scy      (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid");
1264275970Scy
1265275970Scy  // Switch to using fast clocks for thread cpu time if
1266275970Scy  // the sys_clock_getres() returns 0 error code.
1267275970Scy  // Note, that some kernels may support the current thread
1268275970Scy  // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks
1269275970Scy  // returned by the pthread_getcpuclockid().
1270275970Scy  // If the fast Posix clocks are supported then the sys_clock_getres()
1271275970Scy  // must return at least tp.tv_sec == 0 which means a resolution
1272275970Scy  // better than 1 sec. This is extra check for reliability.
1273275970Scy
1274275970Scy  if (pthread_getcpuclockid_func &&
1275275970Scy      pthread_getcpuclockid_func(_main_thread, &clockid) == 0 &&
1276275970Scy      sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) {
1277275970Scy    _supports_fast_thread_cpu_time = true;
1278275970Scy    _pthread_getcpuclockid = pthread_getcpuclockid_func;
1279275970Scy  }
1280275970Scy}
1281275970Scy
1282275970Scyjlong os::javaTimeNanos() {
1283275970Scy  if (os::supports_monotonic_clock()) {
1284275970Scy    struct timespec tp;
1285275970Scy    int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp);
1286275970Scy    assert(status == 0, "gettime error");
1287275970Scy    jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
1288275970Scy    return result;
1289275970Scy  } else {
1290275970Scy    timeval time;
1291275970Scy    int status = gettimeofday(&time, NULL);
1292275970Scy    assert(status != -1, "linux error");
1293275970Scy    jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
1294275970Scy    return 1000 * usecs;
1295275970Scy  }
1296275970Scy}
1297275970Scy
1298275970Scyvoid os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1299275970Scy  if (os::supports_monotonic_clock()) {
1300275970Scy    info_ptr->max_value = ALL_64_BITS;
1301275970Scy
1302275970Scy    // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past
1303275970Scy    info_ptr->may_skip_backward = false;      // not subject to resetting or drifting
1304275970Scy    info_ptr->may_skip_forward = false;       // not subject to resetting or drifting
1305275970Scy  } else {
1306275970Scy    // gettimeofday - based on time in seconds since the Epoch thus does not wrap
1307275970Scy    info_ptr->max_value = ALL_64_BITS;
1308275970Scy
1309275970Scy    // gettimeofday is a real time clock so it skips
1310275970Scy    info_ptr->may_skip_backward = true;
1311275970Scy    info_ptr->may_skip_forward = true;
1312275970Scy  }
1313275970Scy
1314275970Scy  info_ptr->kind = JVMTI_TIMER_ELAPSED;                // elapsed not CPU time
1315275970Scy}
1316275970Scy
1317275970Scy// Return the real, user, and system times in seconds from an
1318275970Scy// arbitrary fixed point in the past.
1319275970Scybool os::getTimesSecs(double* process_real_time,
1320275970Scy                      double* process_user_time,
1321275970Scy                      double* process_system_time) {
1322275970Scy  struct tms ticks;
1323275970Scy  clock_t real_ticks = times(&ticks);
1324275970Scy
1325275970Scy  if (real_ticks == (clock_t) (-1)) {
1326275970Scy    return false;
1327275970Scy  } else {
1328275970Scy    double ticks_per_second = (double) clock_tics_per_sec;
1329275970Scy    *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1330275970Scy    *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1331275970Scy    *process_real_time = ((double) real_ticks) / ticks_per_second;
1332275970Scy
1333275970Scy    return true;
1334275970Scy  }
1335275970Scy}
1336275970Scy
1337275970Scy
1338275970Scychar * os::local_time_string(char *buf, size_t buflen) {
1339275970Scy  struct tm t;
1340275970Scy  time_t long_time;
1341275970Scy  time(&long_time);
1342275970Scy  localtime_r(&long_time, &t);
1343275970Scy  jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1344275970Scy               t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1345275970Scy               t.tm_hour, t.tm_min, t.tm_sec);
1346275970Scy  return buf;
1347275970Scy}
1348275970Scy
1349275970Scystruct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
1350275970Scy  return localtime_r(clock, res);
1351275970Scy}
1352275970Scy
1353275970Scy////////////////////////////////////////////////////////////////////////////////
1354275970Scy// runtime exit support
1355275970Scy
1356275970Scy// Note: os::shutdown() might be called very early during initialization, or
1357275970Scy// called from signal handler. Before adding something to os::shutdown(), make
1358275970Scy// sure it is async-safe and can handle partially initialized VM.
1359275970Scyvoid os::shutdown() {
1360275970Scy
1361275970Scy  // allow PerfMemory to attempt cleanup of any persistent resources
1362275970Scy  perfMemory_exit();
1363275970Scy
1364275970Scy  // needs to remove object in file system
1365275970Scy  AttachListener::abort();
1366275970Scy
1367275970Scy  // flush buffered output, finish log files
1368275970Scy  ostream_abort();
1369275970Scy
1370275970Scy  // Check for abort hook
1371275970Scy  abort_hook_t abort_hook = Arguments::abort_hook();
1372275970Scy  if (abort_hook != NULL) {
1373275970Scy    abort_hook();
1374275970Scy  }
1375275970Scy
1376275970Scy}
1377275970Scy
1378275970Scy// Note: os::abort() might be called very early during initialization, or
1379275970Scy// called from signal handler. Before adding something to os::abort(), make
1380290000Sglebius// sure it is async-safe and can handle partially initialized VM.
1381275970Scyvoid os::abort(bool dump_core, void* siginfo, void* context) {
1382275970Scy  os::shutdown();
1383275970Scy  if (dump_core) {
1384275970Scy#ifndef PRODUCT
1385275970Scy    fdStream out(defaultStream::output_fd());
1386275970Scy    out.print_raw("Current thread is ");
1387275970Scy    char buf[16];
1388275970Scy    jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1389275970Scy    out.print_raw_cr(buf);
1390275970Scy    out.print_raw_cr("Dumping core ...");
1391275970Scy#endif
1392275970Scy    ::abort(); // dump core
1393275970Scy  }
1394275970Scy
1395275970Scy  ::exit(1);
1396275970Scy}
1397275970Scy
1398275970Scy// Die immediately, no exit hook, no abort hook, no cleanup.
1399275970Scyvoid os::die() {
1400275970Scy  ::abort();
1401275970Scy}
1402275970Scy
1403275970Scy
1404275970Scy// This method is a copy of JDK's sysGetLastErrorString
1405275970Scy// from src/solaris/hpi/src/system_md.c
1406275970Scy
1407275970Scysize_t os::lasterror(char *buf, size_t len) {
1408275970Scy  if (errno == 0)  return 0;
1409275970Scy
1410275970Scy  const char *s = ::strerror(errno);
1411275970Scy  size_t n = ::strlen(s);
1412275970Scy  if (n >= len) {
1413275970Scy    n = len - 1;
1414275970Scy  }
1415275970Scy  ::strncpy(buf, s, n);
1416275970Scy  buf[n] = '\0';
1417275970Scy  return n;
1418275970Scy}
1419275970Scy
1420275970Scy// thread_id is kernel thread id (similar to Solaris LWP id)
1421275970Scyintx os::current_thread_id() { return os::Linux::gettid(); }
1422275970Scyint os::current_process_id() {
1423275970Scy  return ::getpid();
1424275970Scy}
1425275970Scy
1426275970Scy// DLL functions
1427275970Scy
1428275970Scyconst char* os::dll_file_extension() { return ".so"; }
1429275970Scy
1430275970Scy// This must be hard coded because it's the system's temporary
1431275970Scy// directory not the java application's temp directory, ala java.io.tmpdir.
1432275970Scyconst char* os::get_temp_directory() { return "/tmp"; }
1433275970Scy
1434275970Scystatic bool file_exists(const char* filename) {
1435275970Scy  struct stat statbuf;
1436275970Scy  if (filename == NULL || strlen(filename) == 0) {
1437275970Scy    return false;
1438275970Scy  }
1439275970Scy  return os::stat(filename, &statbuf) == 0;
1440275970Scy}
1441275970Scy
1442275970Scybool os::dll_build_name(char* buffer, size_t buflen,
1443275970Scy                        const char* pname, const char* fname) {
1444275970Scy  bool retval = false;
1445275970Scy  // Copied from libhpi
1446275970Scy  const size_t pnamelen = pname ? strlen(pname) : 0;
1447275970Scy
1448275970Scy  // Return error on buffer overflow.
1449275970Scy  if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {
1450275970Scy    return retval;
1451275970Scy  }
1452275970Scy
1453275970Scy  if (pnamelen == 0) {
1454290000Sglebius    snprintf(buffer, buflen, "lib%s.so", fname);
1455275970Scy    retval = true;
1456275970Scy  } else if (strchr(pname, *os::path_separator()) != NULL) {
1457275970Scy    int n;
1458275970Scy    char** pelements = split_path(pname, &n);
1459275970Scy    if (pelements == NULL) {
1460275970Scy      return false;
1461275970Scy    }
1462275970Scy    for (int i = 0; i < n; i++) {
1463275970Scy      // Really shouldn't be NULL, but check can't hurt
1464290000Sglebius      if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
1465275970Scy        continue; // skip the empty path values
1466275970Scy      }
1467275970Scy      snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);
1468275970Scy      if (file_exists(buffer)) {
1469275970Scy        retval = true;
1470275970Scy        break;
1471275970Scy      }
1472275970Scy    }
1473275970Scy    // release the storage
1474275970Scy    for (int i = 0; i < n; i++) {
1475275970Scy      if (pelements[i] != NULL) {
1476275970Scy        FREE_C_HEAP_ARRAY(char, pelements[i]);
1477275970Scy      }
1478275970Scy    }
1479275970Scy    if (pelements != NULL) {
1480275970Scy      FREE_C_HEAP_ARRAY(char*, pelements);
1481275970Scy    }
1482275970Scy  } else {
1483275970Scy    snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);
1484275970Scy    retval = true;
1485275970Scy  }
1486275970Scy  return retval;
1487275970Scy}
1488275970Scy
1489275970Scy// check if addr is inside libjvm.so
1490275970Scybool os::address_is_in_vm(address addr) {
1491275970Scy  static address libjvm_base_addr;
1492275970Scy  Dl_info dlinfo;
1493275970Scy
1494275970Scy  if (libjvm_base_addr == NULL) {
1495275970Scy    if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1496275970Scy      libjvm_base_addr = (address)dlinfo.dli_fbase;
1497275970Scy    }
1498275970Scy    assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1499275970Scy  }
1500275970Scy
1501275970Scy  if (dladdr((void *)addr, &dlinfo) != 0) {
1502275970Scy    if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1503275970Scy  }
1504275970Scy
1505275970Scy  return false;
1506275970Scy}
1507275970Scy
1508275970Scybool os::dll_address_to_function_name(address addr, char *buf,
1509275970Scy                                      int buflen, int *offset,
1510275970Scy                                      bool demangle) {
1511275970Scy  // buf is not optional, but offset is optional
1512275970Scy  assert(buf != NULL, "sanity check");
1513275970Scy
1514275970Scy  Dl_info dlinfo;
1515275970Scy
1516275970Scy  if (dladdr((void*)addr, &dlinfo) != 0) {
1517275970Scy    // see if we have a matching symbol
1518275970Scy    if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1519275970Scy      if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1520275970Scy        jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1521275970Scy      }
1522275970Scy      if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1523275970Scy      return true;
1524275970Scy    }
1525275970Scy    // no matching symbol so try for just file info
1526275970Scy    if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1527275970Scy      if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1528275970Scy                          buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1529275970Scy        return true;
1530275970Scy      }
1531275970Scy    }
1532275970Scy  }
1533275970Scy
1534275970Scy  buf[0] = '\0';
1535275970Scy  if (offset != NULL) *offset = -1;
1536275970Scy  return false;
1537275970Scy}
1538275970Scy
1539275970Scystruct _address_to_library_name {
1540275970Scy  address addr;          // input : memory address
1541275970Scy  size_t  buflen;        //         size of fname
1542275970Scy  char*   fname;         // output: library name
1543298770Sdelphij  address base;          //         library base addr
1544298770Sdelphij};
1545298770Sdelphij
1546275970Scystatic int address_to_library_name_callback(struct dl_phdr_info *info,
1547275970Scy                                            size_t size, void *data) {
1548275970Scy  int i;
1549275970Scy  bool found = false;
1550275970Scy  address libbase = NULL;
1551275970Scy  struct _address_to_library_name * d = (struct _address_to_library_name *)data;
1552275970Scy
1553275970Scy  // iterate through all loadable segments
1554275970Scy  for (i = 0; i < info->dlpi_phnum; i++) {
1555275970Scy    address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1556275970Scy    if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1557275970Scy      // base address of a library is the lowest address of its loaded
1558290000Sglebius      // segments.
1559275970Scy      if (libbase == NULL || libbase > segbase) {
1560275970Scy        libbase = segbase;
1561275970Scy      }
1562275970Scy      // see if 'addr' is within current segment
1563275970Scy      if (segbase <= d->addr &&
1564275970Scy          d->addr < segbase + info->dlpi_phdr[i].p_memsz) {
1565275970Scy        found = true;
1566275970Scy      }
1567275970Scy    }
1568275970Scy  }
1569275970Scy
1570275970Scy  // dlpi_name is NULL or empty if the ELF file is executable, return 0
1571275970Scy  // so dll_address_to_library_name() can fall through to use dladdr() which
1572275970Scy  // can figure out executable name from argv[0].
1573275970Scy  if (found && info->dlpi_name && info->dlpi_name[0]) {
1574275970Scy    d->base = libbase;
1575275970Scy    if (d->fname) {
1576275970Scy      jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name);
1577275970Scy    }
1578275970Scy    return 1;
1579275970Scy  }
1580275970Scy  return 0;
1581275970Scy}
1582275970Scy
1583275970Scybool os::dll_address_to_library_name(address addr, char* buf,
1584275970Scy                                     int buflen, int* offset) {
1585275970Scy  // buf is not optional, but offset is optional
1586275970Scy  assert(buf != NULL, "sanity check");
1587275970Scy
1588275970Scy  Dl_info dlinfo;
1589275970Scy  struct _address_to_library_name data;
1590275970Scy
1591275970Scy  // There is a bug in old glibc dladdr() implementation that it could resolve
1592275970Scy  // to wrong library name if the .so file has a base address != NULL. Here
1593298770Sdelphij  // we iterate through the program headers of all loaded libraries to find
1594298770Sdelphij  // out which library 'addr' really belongs to. This workaround can be
1595298770Sdelphij  // removed once the minimum requirement for glibc is moved to 2.3.x.
1596275970Scy  data.addr = addr;
1597275970Scy  data.fname = buf;
1598275970Scy  data.buflen = buflen;
1599275970Scy  data.base = NULL;
1600275970Scy  int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data);
1601275970Scy
1602275970Scy  if (rslt) {
1603275970Scy    // buf already contains library name
1604275970Scy    if (offset) *offset = addr - data.base;
1605298770Sdelphij    return true;
1606275970Scy  }
1607298770Sdelphij  if (dladdr((void*)addr, &dlinfo) != 0) {
1608275970Scy    if (dlinfo.dli_fname != NULL) {
1609275970Scy      jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1610275970Scy    }
1611275970Scy    if (dlinfo.dli_fbase != NULL && offset != NULL) {
1612275970Scy      *offset = addr - (address)dlinfo.dli_fbase;
1613275970Scy    }
1614275970Scy    return true;
1615275970Scy  }
1616275970Scy
1617275970Scy  buf[0] = '\0';
1618275970Scy  if (offset) *offset = -1;
1619275970Scy  return false;
1620275970Scy}
1621275970Scy
1622275970Scy// Loads .dll/.so and
1623275970Scy// in case of error it checks if .dll/.so was built for the
1624275970Scy// same architecture as Hotspot is running on
1625275970Scy
1626275970Scy
1627275970Scy// Remember the stack's state. The Linux dynamic linker will change
1628275970Scy// the stack to 'executable' at most once, so we must safepoint only once.
1629275970Scybool os::Linux::_stack_is_executable = false;
1630275970Scy
1631275970Scy// VM operation that loads a library.  This is necessary if stack protection
1632275970Scy// of the Java stacks can be lost during loading the library.  If we
1633275970Scy// do not stop the Java threads, they can stack overflow before the stacks
1634275970Scy// are protected again.
1635275970Scyclass VM_LinuxDllLoad: public VM_Operation {
1636275970Scy private:
1637275970Scy  const char *_filename;
1638275970Scy  char *_ebuf;
1639275970Scy  int _ebuflen;
1640275970Scy  void *_lib;
1641275970Scy public:
1642275970Scy  VM_LinuxDllLoad(const char *fn, char *ebuf, int ebuflen) :
1643275970Scy    _filename(fn), _ebuf(ebuf), _ebuflen(ebuflen), _lib(NULL) {}
1644275970Scy  VMOp_Type type() const { return VMOp_LinuxDllLoad; }
1645275970Scy  void doit() {
1646275970Scy    _lib = os::Linux::dll_load_in_vmthread(_filename, _ebuf, _ebuflen);
1647275970Scy    os::Linux::_stack_is_executable = true;
1648275970Scy  }
1649275970Scy  void* loaded_library() { return _lib; }
1650275970Scy};
1651275970Scy
1652275970Scyvoid * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1653275970Scy  void * result = NULL;
1654275970Scy  bool load_attempted = false;
1655275970Scy
1656275970Scy  // Check whether the library to load might change execution rights
1657275970Scy  // of the stack. If they are changed, the protection of the stack
1658275970Scy  // guard pages will be lost. We need a safepoint to fix this.
1659275970Scy  //
1660275970Scy  // See Linux man page execstack(8) for more info.
1661275970Scy  if (os::uses_stack_guard_pages() && !os::Linux::_stack_is_executable) {
1662275970Scy    ElfFile ef(filename);
1663298770Sdelphij    if (!ef.specifies_noexecstack()) {
1664298770Sdelphij      if (!is_init_completed()) {
1665298770Sdelphij        os::Linux::_stack_is_executable = true;
1666275970Scy        // This is OK - No Java threads have been created yet, and hence no
1667275970Scy        // stack guard pages to fix.
1668275970Scy        //
1669275970Scy        // This should happen only when you are building JDK7 using a very
1670275970Scy        // old version of JDK6 (e.g., with JPRT) and running test_gamma.
1671275970Scy        //
1672275970Scy        // Dynamic loader will make all stacks executable after
1673275970Scy        // this function returns, and will not do that again.
1674275970Scy        assert(Threads::first() == NULL, "no Java threads should exist yet.");
1675275970Scy      } else {
1676275970Scy        warning("You have loaded library %s which might have disabled stack guard. "
1677275970Scy                "The VM will try to fix the stack guard now.\n"
1678275970Scy                "It's highly recommended that you fix the library with "
1679275970Scy                "'execstack -c <libfile>', or link it with '-z noexecstack'.",
1680275970Scy                filename);
1681275970Scy
1682275970Scy        assert(Thread::current()->is_Java_thread(), "must be Java thread");
1683275970Scy        JavaThread *jt = JavaThread::current();
1684275970Scy        if (jt->thread_state() != _thread_in_native) {
1685275970Scy          // This happens when a compiler thread tries to load a hsdis-<arch>.so file
1686275970Scy          // that requires ExecStack. Cannot enter safe point. Let's give up.
1687275970Scy          warning("Unable to fix stack guard. Giving up.");
1688275970Scy        } else {
1689275970Scy          if (!LoadExecStackDllInVMThread) {
1690275970Scy            // This is for the case where the DLL has an static
1691275970Scy            // constructor function that executes JNI code. We cannot
1692275970Scy            // load such DLLs in the VMThread.
1693275970Scy            result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1694275970Scy          }
1695275970Scy
1696275970Scy          ThreadInVMfromNative tiv(jt);
1697275970Scy          debug_only(VMNativeEntryWrapper vew;)
1698275970Scy
1699275970Scy          VM_LinuxDllLoad op(filename, ebuf, ebuflen);
1700275970Scy          VMThread::execute(&op);
1701275970Scy          if (LoadExecStackDllInVMThread) {
1702275970Scy            result = op.loaded_library();
1703275970Scy          }
1704275970Scy          load_attempted = true;
1705275970Scy        }
1706275970Scy      }
1707275970Scy    }
1708275970Scy  }
1709275970Scy
1710290000Sglebius  if (!load_attempted) {
1711275970Scy    result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1712290000Sglebius  }
1713275970Scy
1714275970Scy  if (result != NULL) {
1715275970Scy    // Successful loading
1716275970Scy    return result;
1717275970Scy  }
1718275970Scy
1719275970Scy  Elf32_Ehdr elf_head;
1720275970Scy  int diag_msg_max_length=ebuflen-strlen(ebuf);
1721275970Scy  char* diag_msg_buf=ebuf+strlen(ebuf);
1722275970Scy
1723275970Scy  if (diag_msg_max_length==0) {
1724275970Scy    // No more space in ebuf for additional diagnostics message
1725298770Sdelphij    return NULL;
1726298770Sdelphij  }
1727298770Sdelphij
1728275970Scy
1729275970Scy  int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1730290000Sglebius
1731275970Scy  if (file_descriptor < 0) {
1732275970Scy    // Can't open library, report dlerror() message
1733275970Scy    return NULL;
1734275970Scy  }
1735275970Scy
1736275970Scy  bool failed_to_read_elf_head=
1737275970Scy    (sizeof(elf_head)!=
1738275970Scy     (::read(file_descriptor, &elf_head,sizeof(elf_head))));
1739275970Scy
1740275970Scy  ::close(file_descriptor);
1741275970Scy  if (failed_to_read_elf_head) {
1742275970Scy    // file i/o error - report dlerror() msg
1743275970Scy    return NULL;
1744275970Scy  }
1745275970Scy
1746275970Scy  typedef struct {
1747275970Scy    Elf32_Half  code;         // Actual value as defined in elf.h
1748275970Scy    Elf32_Half  compat_class; // Compatibility of archs at VM's sense
1749290000Sglebius    char        elf_class;    // 32 or 64 bit
1750275970Scy    char        endianess;    // MSB or LSB
1751290000Sglebius    char*       name;         // String representation
1752275970Scy  } arch_t;
1753275970Scy
1754275970Scy#ifndef EM_486
1755275970Scy  #define EM_486          6               /* Intel 80486 */
1756275970Scy#endif
1757275970Scy#ifndef EM_AARCH64
1758275970Scy  #define EM_AARCH64    183               /* ARM AARCH64 */
1759290000Sglebius#endif
1760275970Scy
1761290000Sglebius  static const arch_t arch_array[]={
1762275970Scy    {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1763275970Scy    {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1764275970Scy    {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1765275970Scy    {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1766275970Scy    {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1767275970Scy    {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1768275970Scy    {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1769275970Scy    {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1770275970Scy#if defined(VM_LITTLE_ENDIAN)
1771275970Scy    {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2LSB, (char*)"Power PC 64"},
1772275970Scy#else
1773275970Scy    {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1774275970Scy#endif
1775275970Scy    {EM_ARM,         EM_ARM,     ELFCLASS32,   ELFDATA2LSB, (char*)"ARM"},
1776275970Scy    {EM_S390,        EM_S390,    ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"},
1777275970Scy    {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1778275970Scy    {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1779275970Scy    {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1780275970Scy    {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1781275970Scy    {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"},
1782275970Scy    {EM_AARCH64,     EM_AARCH64, ELFCLASS64, ELFDATA2LSB, (char*)"AARCH64"},
1783275970Scy  };
1784275970Scy
1785275970Scy#if  (defined IA32)
1786290000Sglebius  static  Elf32_Half running_arch_code=EM_386;
1787275970Scy#elif   (defined AMD64)
1788290000Sglebius  static  Elf32_Half running_arch_code=EM_X86_64;
1789275970Scy#elif  (defined IA64)
1790275970Scy  static  Elf32_Half running_arch_code=EM_IA_64;
1791275970Scy#elif  (defined __sparc) && (defined _LP64)
1792275970Scy  static  Elf32_Half running_arch_code=EM_SPARCV9;
1793275970Scy#elif  (defined __sparc) && (!defined _LP64)
1794298770Sdelphij  static  Elf32_Half running_arch_code=EM_SPARC;
1795298770Sdelphij#elif  (defined __powerpc64__)
1796298770Sdelphij  static  Elf32_Half running_arch_code=EM_PPC64;
1797275970Scy#elif  (defined __powerpc__)
1798275970Scy  static  Elf32_Half running_arch_code=EM_PPC;
1799275970Scy#elif  (defined ARM)
1800275970Scy  static  Elf32_Half running_arch_code=EM_ARM;
1801275970Scy#elif  (defined S390)
1802275970Scy  static  Elf32_Half running_arch_code=EM_S390;
1803275970Scy#elif  (defined ALPHA)
1804275970Scy  static  Elf32_Half running_arch_code=EM_ALPHA;
1805275970Scy#elif  (defined MIPSEL)
1806275970Scy  static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1807275970Scy#elif  (defined PARISC)
1808275970Scy  static  Elf32_Half running_arch_code=EM_PARISC;
1809275970Scy#elif  (defined MIPS)
1810275970Scy  static  Elf32_Half running_arch_code=EM_MIPS;
1811275970Scy#elif  (defined M68K)
1812275970Scy  static  Elf32_Half running_arch_code=EM_68K;
1813275970Scy#elif  (defined AARCH64)
1814275970Scy  static  Elf32_Half running_arch_code=EM_AARCH64;
1815275970Scy#else
1816275970Scy    #error Method os::dll_load requires that one of following is defined:\
1817275970Scy         IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K, AARCH64
1818275970Scy#endif
1819275970Scy
1820275970Scy  // Identify compatability class for VM's architecture and library's architecture
1821275970Scy  // Obtain string descriptions for architectures
1822275970Scy
1823275970Scy  arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1824275970Scy  int running_arch_index=-1;
1825275970Scy
1826275970Scy  for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) {
1827275970Scy    if (running_arch_code == arch_array[i].code) {
1828275970Scy      running_arch_index    = i;
1829275970Scy    }
1830275970Scy    if (lib_arch.code == arch_array[i].code) {
1831275970Scy      lib_arch.compat_class = arch_array[i].compat_class;
1832275970Scy      lib_arch.name         = arch_array[i].name;
1833275970Scy    }
1834275970Scy  }
1835275970Scy
1836275970Scy  assert(running_arch_index != -1,
1837275970Scy         "Didn't find running architecture code (running_arch_code) in arch_array");
1838275970Scy  if (running_arch_index == -1) {
1839275970Scy    // Even though running architecture detection failed
1840275970Scy    // we may still continue with reporting dlerror() message
1841275970Scy    return NULL;
1842275970Scy  }
1843275970Scy
1844275970Scy  if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1845275970Scy    ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1846275970Scy    return NULL;
1847275970Scy  }
1848275970Scy
1849275970Scy#ifndef S390
1850275970Scy  if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1851275970Scy    ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1852275970Scy    return NULL;
1853275970Scy  }
1854275970Scy#endif // !S390
1855275970Scy
1856275970Scy  if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1857275970Scy    if (lib_arch.name!=NULL) {
1858275970Scy      ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1859275970Scy                 " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1860275970Scy                 lib_arch.name, arch_array[running_arch_index].name);
1861275970Scy    } else {
1862275970Scy      ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1863275970Scy                 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1864275970Scy                 lib_arch.code,
1865275970Scy                 arch_array[running_arch_index].name);
1866275970Scy    }
1867275970Scy  }
1868275970Scy
1869275970Scy  return NULL;
1870275970Scy}
1871275970Scy
1872275970Scyvoid * os::Linux::dlopen_helper(const char *filename, char *ebuf,
1873275970Scy                                int ebuflen) {
1874298770Sdelphij  void * result = ::dlopen(filename, RTLD_LAZY);
1875298770Sdelphij  if (result == NULL) {
1876298770Sdelphij    ::strncpy(ebuf, ::dlerror(), ebuflen - 1);
1877298770Sdelphij    ebuf[ebuflen-1] = '\0';
1878298770Sdelphij  }
1879275970Scy  return result;
1880275970Scy}
1881275970Scy
1882275970Scyvoid * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf,
1883275970Scy                                       int ebuflen) {
1884275970Scy  void * result = NULL;
1885275970Scy  if (LoadExecStackDllInVMThread) {
1886275970Scy    result = dlopen_helper(filename, ebuf, ebuflen);
1887275970Scy  }
1888275970Scy
1889275970Scy  // Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a
1890275970Scy  // library that requires an executable stack, or which does not have this
1891275970Scy  // stack attribute set, dlopen changes the stack attribute to executable. The
1892275970Scy  // read protection of the guard pages gets lost.
1893275970Scy  //
1894275970Scy  // Need to check _stack_is_executable again as multiple VM_LinuxDllLoad
1895275970Scy  // may have been queued at the same time.
1896275970Scy
1897275970Scy  if (!_stack_is_executable) {
1898275970Scy    JavaThread *jt = Threads::first();
1899275970Scy
1900275970Scy    while (jt) {
1901275970Scy      if (!jt->stack_guard_zone_unused() &&        // Stack not yet fully initialized
1902275970Scy          jt->stack_yellow_zone_enabled()) {       // No pending stack overflow exceptions
1903275970Scy        if (!os::guard_memory((char *) jt->stack_red_zone_base() - jt->stack_red_zone_size(),
1904275970Scy                              jt->stack_yellow_zone_size() + jt->stack_red_zone_size())) {
1905275970Scy          warning("Attempt to reguard stack yellow zone failed.");
1906275970Scy        }
1907275970Scy      }
1908275970Scy      jt = jt->next();
1909275970Scy    }
1910275970Scy  }
1911275970Scy
1912275970Scy  return result;
1913275970Scy}
1914275970Scy
1915275970Scyvoid* os::dll_lookup(void* handle, const char* name) {
1916275970Scy  void* res = dlsym(handle, name);
1917275970Scy  return res;
1918275970Scy}
1919275970Scy
1920275970Scyvoid* os::get_default_process_handle() {
1921275970Scy  return (void*)::dlopen(NULL, RTLD_LAZY);
1922275970Scy}
1923275970Scy
1924275970Scystatic bool _print_ascii_file(const char* filename, outputStream* st) {
1925275970Scy  int fd = ::open(filename, O_RDONLY);
1926275970Scy  if (fd == -1) {
1927275970Scy    return false;
1928275970Scy  }
1929275970Scy
1930275970Scy  char buf[32];
1931275970Scy  int bytes;
1932275970Scy  while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
1933275970Scy    st->print_raw(buf, bytes);
1934275970Scy  }
1935275970Scy
1936275970Scy  ::close(fd);
1937275970Scy
1938275970Scy  return true;
1939275970Scy}
1940275970Scy
1941275970Scyvoid os::print_dll_info(outputStream *st) {
1942275970Scy  st->print_cr("Dynamic libraries:");
1943275970Scy
1944275970Scy  char fname[32];
1945275970Scy  pid_t pid = os::Linux::gettid();
1946275970Scy
1947275970Scy  jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid);
1948275970Scy
1949275970Scy  if (!_print_ascii_file(fname, st)) {
1950275970Scy    st->print("Can not get library information for pid = %d\n", pid);
1951275970Scy  }
1952275970Scy}
1953275970Scy
1954298770Sdelphijint os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {
1955298770Sdelphij  FILE *procmapsFile = NULL;
1956298770Sdelphij
1957275970Scy  // Open the procfs maps file for the current process
1958275970Scy  if ((procmapsFile = fopen("/proc/self/maps", "r")) != NULL) {
1959275970Scy    // Allocate PATH_MAX for file name plus a reasonable size for other fields.
1960275970Scy    char line[PATH_MAX + 100];
1961275970Scy
1962275970Scy    // Read line by line from 'file'
1963275970Scy    while (fgets(line, sizeof(line), procmapsFile) != NULL) {
1964275970Scy      u8 base, top, offset, inode;
1965275970Scy      char permissions[5];
1966275970Scy      char device[6];
1967275970Scy      char name[PATH_MAX + 1];
1968275970Scy
1969275970Scy      // Parse fields from line
1970275970Scy      sscanf(line, UINT64_FORMAT_X "-" UINT64_FORMAT_X " %4s " UINT64_FORMAT_X " %5s " INT64_FORMAT " %s",
1971275970Scy             &base, &top, permissions, &offset, device, &inode, name);
1972275970Scy
1973275970Scy      // Filter by device id '00:00' so that we only get file system mapped files.
1974275970Scy      if (strcmp(device, "00:00") != 0) {
1975275970Scy
1976275970Scy        // Call callback with the fields of interest
1977275970Scy        if(callback(name, (address)base, (address)top, param)) {
1978275970Scy          // Oops abort, callback aborted
1979275970Scy          fclose(procmapsFile);
1980275970Scy          return 1;
1981275970Scy        }
1982275970Scy      }
1983275970Scy    }
1984275970Scy    fclose(procmapsFile);
1985275970Scy  }
1986275970Scy  return 0;
1987275970Scy}
1988275970Scy
1989275970Scyvoid os::print_os_info_brief(outputStream* st) {
1990275970Scy  os::Linux::print_distro_info(st);
1991275970Scy
1992275970Scy  os::Posix::print_uname_info(st);
1993275970Scy
1994275970Scy  os::Linux::print_libversion_info(st);
1995275970Scy
1996275970Scy}
1997275970Scy
1998275970Scyvoid os::print_os_info(outputStream* st) {
1999275970Scy  st->print("OS:");
2000275970Scy
2001275970Scy  os::Linux::print_distro_info(st);
2002275970Scy
2003275970Scy  os::Posix::print_uname_info(st);
2004275970Scy
2005275970Scy  // Print warning if unsafe chroot environment detected
2006275970Scy  if (unsafe_chroot_detected) {
2007275970Scy    st->print("WARNING!! ");
2008275970Scy    st->print_cr("%s", unstable_chroot_error);
2009275970Scy  }
2010275970Scy
2011275970Scy  os::Linux::print_libversion_info(st);
2012275970Scy
2013275970Scy  os::Posix::print_rlimit_info(st);
2014275970Scy
2015275970Scy  os::Posix::print_load_average(st);
2016275970Scy
2017275970Scy  os::Linux::print_full_memory_info(st);
2018275970Scy}
2019275970Scy
2020275970Scy// Try to identify popular distros.
2021275970Scy// Most Linux distributions have a /etc/XXX-release file, which contains
2022275970Scy// the OS version string. Newer Linux distributions have a /etc/lsb-release
2023275970Scy// file that also contains the OS version string. Some have more than one
2024275970Scy// /etc/XXX-release file (e.g. Mandrake has both /etc/mandrake-release and
2025275970Scy// /etc/redhat-release.), so the order is important.
2026275970Scy// Any Linux that is based on Redhat (i.e. Oracle, Mandrake, Sun JDS...) have
2027275970Scy// their own specific XXX-release file as well as a redhat-release file.
2028275970Scy// Because of this the XXX-release file needs to be searched for before the
2029275970Scy// redhat-release file.
2030275970Scy// Since Red Hat has a lsb-release file that is not very descriptive the
2031275970Scy// search for redhat-release needs to be before lsb-release.
2032275970Scy// Since the lsb-release file is the new standard it needs to be searched
2033275970Scy// before the older style release files.
2034275970Scy// Searching system-release (Red Hat) and os-release (other Linuxes) are a
2035275970Scy// next to last resort.  The os-release file is a new standard that contains
2036275970Scy// distribution information and the system-release file seems to be an old
2037275970Scy// standard that has been replaced by the lsb-release and os-release files.
2038275970Scy// Searching for the debian_version file is the last resort.  It contains
2039275970Scy// an informative string like "6.0.6" or "wheezy/sid". Because of this
2040275970Scy// "Debian " is printed before the contents of the debian_version file.
2041275970Scy
2042275970Scyconst char* distro_files[] = {
2043275970Scy  "/etc/oracle-release",
2044275970Scy  "/etc/mandriva-release",
2045275970Scy  "/etc/mandrake-release",
2046275970Scy  "/etc/sun-release",
2047275970Scy  "/etc/redhat-release",
2048275970Scy  "/etc/lsb-release",
2049275970Scy  "/etc/SuSE-release",
2050275970Scy  "/etc/turbolinux-release",
2051275970Scy  "/etc/gentoo-release",
2052275970Scy  "/etc/ltib-release",
2053275970Scy  "/etc/angstrom-version",
2054275970Scy  "/etc/system-release",
2055275970Scy  "/etc/os-release",
2056275970Scy  NULL };
2057275970Scy
2058275970Scyvoid os::Linux::print_distro_info(outputStream* st) {
2059275970Scy  for (int i = 0;; i++) {
2060275970Scy    const char* file = distro_files[i];
2061275970Scy    if (file == NULL) {
2062275970Scy      break;  // done
2063275970Scy    }
2064275970Scy    // If file prints, we found it.
2065275970Scy    if (_print_ascii_file(file, st)) {
2066275970Scy      return;
2067275970Scy    }
2068275970Scy  }
2069275970Scy
2070275970Scy  if (file_exists("/etc/debian_version")) {
2071275970Scy    st->print("Debian ");
2072275970Scy    _print_ascii_file("/etc/debian_version", st);
2073275970Scy  } else {
2074275970Scy    st->print("Linux");
2075275970Scy  }
2076275970Scy  st->cr();
2077275970Scy}
2078275970Scy
2079275970Scystatic void parse_os_info(char* distro, size_t length, const char* file) {
2080275970Scy  FILE* fp = fopen(file, "r");
2081275970Scy  if (fp != NULL) {
2082275970Scy    char buf[256];
2083275970Scy    // get last line of the file.
2084275970Scy    while (fgets(buf, sizeof(buf), fp)) { }
2085275970Scy    // Edit out extra stuff in expected ubuntu format
2086275970Scy    if (strstr(buf, "DISTRIB_DESCRIPTION=") != NULL) {
2087275970Scy      char* ptr = strstr(buf, "\"");  // the name is in quotes
2088275970Scy      if (ptr != NULL) {
2089275970Scy        ptr++; // go beyond first quote
2090275970Scy        char* nl = strchr(ptr, '\"');
2091275970Scy        if (nl != NULL) *nl = '\0';
2092275970Scy        strncpy(distro, ptr, length);
2093275970Scy      } else {
2094275970Scy        ptr = strstr(buf, "=");
2095275970Scy        ptr++; // go beyond equals then
2096275970Scy        char* nl = strchr(ptr, '\n');
2097275970Scy        if (nl != NULL) *nl = '\0';
2098275970Scy        strncpy(distro, ptr, length);
2099275970Scy      }
2100275970Scy    } else {
2101275970Scy      // if not in expected Ubuntu format, print out whole line minus \n
2102275970Scy      char* nl = strchr(buf, '\n');
2103275970Scy      if (nl != NULL) *nl = '\0';
2104275970Scy      strncpy(distro, buf, length);
2105275970Scy    }
2106275970Scy    // close distro file
2107275970Scy    fclose(fp);
2108275970Scy  }
2109275970Scy}
2110275970Scy
2111275970Scyvoid os::get_summary_os_info(char* buf, size_t buflen) {
2112275970Scy  for (int i = 0;; i++) {
2113275970Scy    const char* file = distro_files[i];
2114275970Scy    if (file == NULL) {
2115275970Scy      break; // ran out of distro_files
2116275970Scy    }
2117275970Scy    if (file_exists(file)) {
2118275970Scy      parse_os_info(buf, buflen, file);
2119275970Scy      return;
2120275970Scy    }
2121275970Scy  }
2122275970Scy  // special case for debian
2123275970Scy  if (file_exists("/etc/debian_version")) {
2124275970Scy    strncpy(buf, "Debian ", buflen);
2125290000Sglebius    parse_os_info(&buf[7], buflen-7, "/etc/debian_version");
2126275970Scy  } else {
2127290000Sglebius    strncpy(buf, "Linux", buflen);
2128275970Scy  }
2129290000Sglebius}
2130275970Scy
2131275970Scyvoid os::Linux::print_libversion_info(outputStream* st) {
2132275970Scy  // libc, pthread
2133275970Scy  st->print("libc:");
2134275970Scy  st->print("%s ", os::Linux::glibc_version());
2135275970Scy  st->print("%s ", os::Linux::libpthread_version());
2136275970Scy  st->cr();
2137290000Sglebius}
2138275970Scy
2139275970Scyvoid os::Linux::print_full_memory_info(outputStream* st) {
2140275970Scy  st->print("\n/proc/meminfo:\n");
2141275970Scy  _print_ascii_file("/proc/meminfo", st);
2142275970Scy  st->cr();
2143275970Scy}
2144275970Scy
2145275970Scyvoid os::print_memory_info(outputStream* st) {
2146275970Scy
2147275970Scy  st->print("Memory:");
2148275970Scy  st->print(" %dk page", os::vm_page_size()>>10);
2149275970Scy
2150275970Scy  // values in struct sysinfo are "unsigned long"
2151275970Scy  struct sysinfo si;
2152275970Scy  sysinfo(&si);
2153275970Scy
2154275970Scy  st->print(", physical " UINT64_FORMAT "k",
2155275970Scy            os::physical_memory() >> 10);
2156275970Scy  st->print("(" UINT64_FORMAT "k free)",
2157275970Scy            os::available_memory() >> 10);
2158275970Scy  st->print(", swap " UINT64_FORMAT "k",
2159275970Scy            ((jlong)si.totalswap * si.mem_unit) >> 10);
2160275970Scy  st->print("(" UINT64_FORMAT "k free)",
2161275970Scy            ((jlong)si.freeswap * si.mem_unit) >> 10);
2162275970Scy  st->cr();
2163275970Scy}
2164275970Scy
2165275970Scy// Print the first "model name" line and the first "flags" line
2166275970Scy// that we find and nothing more. We assume "model name" comes
2167275970Scy// before "flags" so if we find a second "model name", then the
2168275970Scy// "flags" field is considered missing.
2169275970Scystatic bool print_model_name_and_flags(outputStream* st, char* buf, size_t buflen) {
2170275970Scy#if defined(IA32) || defined(AMD64)
2171275970Scy  // Other platforms have less repetitive cpuinfo files
2172275970Scy  FILE *fp = fopen("/proc/cpuinfo", "r");
2173275970Scy  if (fp) {
2174275970Scy    while (!feof(fp)) {
2175275970Scy      if (fgets(buf, buflen, fp)) {
2176275970Scy        // Assume model name comes before flags
2177310419Sdelphij        bool model_name_printed = false;
2178310419Sdelphij        if (strstr(buf, "model name") != NULL) {
2179310419Sdelphij          if (!model_name_printed) {
2180310419Sdelphij            st->print_raw("\nCPU Model and flags from /proc/cpuinfo:\n");
2181310419Sdelphij            st->print_raw(buf);
2182310419Sdelphij            model_name_printed = true;
2183310419Sdelphij          } else {
2184310419Sdelphij            // model name printed but not flags?  Odd, just return
2185310419Sdelphij            fclose(fp);
2186310419Sdelphij            return true;
2187310419Sdelphij          }
2188310419Sdelphij        }
2189310419Sdelphij        // print the flags line too
2190310419Sdelphij        if (strstr(buf, "flags") != NULL) {
2191310419Sdelphij          st->print_raw(buf);
2192275970Scy          fclose(fp);
2193310419Sdelphij          return true;
2194275970Scy        }
2195275970Scy      }
2196275970Scy    }
2197275970Scy    fclose(fp);
2198275970Scy  }
2199275970Scy#endif // x86 platforms
2200275970Scy  return false;
2201275970Scy}
2202275970Scy
2203275970Scyvoid os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
2204275970Scy  // Only print the model name if the platform provides this as a summary
2205275970Scy  if (!print_model_name_and_flags(st, buf, buflen)) {
2206275970Scy    st->print("\n/proc/cpuinfo:\n");
2207275970Scy    if (!_print_ascii_file("/proc/cpuinfo", st)) {
2208275970Scy      st->print_cr("  <Not Available>");
2209275970Scy    }
2210275970Scy  }
2211275970Scy}
2212275970Scy
2213275970Scy#if defined(AMD64) || defined(IA32) || defined(X32)
2214275970Scyconst char* search_string = "model name";
2215275970Scy#elif defined(SPARC)
2216275970Scyconst char* search_string = "cpu";
2217275970Scy#else
2218275970Scyconst char* search_string = "Processor";
2219275970Scy#endif
2220275970Scy
2221275970Scy// Parses the cpuinfo file for string representing the model name.
2222275970Scyvoid os::get_summary_cpu_info(char* cpuinfo, size_t length) {
2223275970Scy  FILE* fp = fopen("/proc/cpuinfo", "r");
2224275970Scy  if (fp != NULL) {
2225275970Scy    while (!feof(fp)) {
2226275970Scy      char buf[256];
2227275970Scy      if (fgets(buf, sizeof(buf), fp)) {
2228275970Scy        char* start = strstr(buf, search_string);
2229275970Scy        if (start != NULL) {
2230275970Scy          char *ptr = start + strlen(search_string);
2231275970Scy          char *end = buf + strlen(buf);
2232275970Scy          while (ptr != end) {
2233290000Sglebius             // skip whitespace and colon for the rest of the name.
2234275970Scy             if (*ptr != ' ' && *ptr != '\t' && *ptr != ':') {
2235275970Scy               break;
2236275970Scy             }
2237275970Scy             ptr++;
2238275970Scy          }
2239275970Scy          if (ptr != end) {
2240275970Scy            // reasonable string, get rid of newline and keep the rest
2241275970Scy            char* nl = strchr(buf, '\n');
2242275970Scy            if (nl != NULL) *nl = '\0';
2243275970Scy            strncpy(cpuinfo, ptr, length);
2244275970Scy            fclose(fp);
2245275970Scy            return;
2246275970Scy          }
2247275970Scy        }
2248275970Scy      }
2249275970Scy    }
2250275970Scy    fclose(fp);
2251275970Scy  }
2252275970Scy  // cpuinfo not found or parsing failed, just print generic string.  The entire
2253275970Scy  // /proc/cpuinfo file will be printed later in the file (or enough of it for x86)
2254275970Scy#if defined(AMD64)
2255275970Scy  strncpy(cpuinfo, "x86_64", length);
2256275970Scy#elif defined(IA32)
2257275970Scy  strncpy(cpuinfo, "x86_32", length);
2258275970Scy#elif defined(IA64)
2259275970Scy  strncpy(cpuinfo, "IA64", length);
2260275970Scy#elif defined(SPARC)
2261275970Scy  strncpy(cpuinfo, "sparcv9", length);
2262275970Scy#elif defined(AARCH64)
2263310419Sdelphij  strncpy(cpuinfo, "AArch64", length);
2264275970Scy#elif defined(ARM)
2265275970Scy  strncpy(cpuinfo, "ARM", length);
2266275970Scy#elif defined(PPC)
2267275970Scy  strncpy(cpuinfo, "PPC64", length);
2268275970Scy#elif defined(ZERO_LIBARCH)
2269275970Scy  strncpy(cpuinfo, ZERO_LIBARCH, length);
2270275970Scy#else
2271275970Scy  strncpy(cpuinfo, "unknown", length);
2272275970Scy#endif
2273275970Scy}
2274275970Scy
2275275970Scyvoid os::print_siginfo(outputStream* st, void* siginfo) {
2276275970Scy  const siginfo_t* si = (const siginfo_t*)siginfo;
2277275970Scy
2278275970Scy  os::Posix::print_siginfo_brief(st, si);
2279275970Scy#if INCLUDE_CDS
2280275970Scy  if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&
2281275970Scy      UseSharedSpaces) {
2282275970Scy    FileMapInfo* mapinfo = FileMapInfo::current_info();
2283275970Scy    if (mapinfo->is_in_shared_space(si->si_addr)) {
2284275970Scy      st->print("\n\nError accessing class data sharing archive."   \
2285275970Scy                " Mapped file inaccessible during execution, "      \
2286275970Scy                " possible disk/network problem.");
2287275970Scy    }
2288275970Scy  }
2289275970Scy#endif
2290275970Scy  st->cr();
2291275970Scy}
2292275970Scy
2293275970Scy
2294275970Scystatic void print_signal_handler(outputStream* st, int sig,
2295275970Scy                                 char* buf, size_t buflen);
2296275970Scy
2297275970Scyvoid os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
2298275970Scy  st->print_cr("Signal Handlers:");
2299275970Scy  print_signal_handler(st, SIGSEGV, buf, buflen);
2300275970Scy  print_signal_handler(st, SIGBUS , buf, buflen);
2301275970Scy  print_signal_handler(st, SIGFPE , buf, buflen);
2302275970Scy  print_signal_handler(st, SIGPIPE, buf, buflen);
2303275970Scy  print_signal_handler(st, SIGXFSZ, buf, buflen);
2304275970Scy  print_signal_handler(st, SIGILL , buf, buflen);
2305275970Scy  print_signal_handler(st, SR_signum, buf, buflen);
2306275970Scy  print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen);
2307275970Scy  print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
2308275970Scy  print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen);
2309275970Scy  print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
2310275970Scy#if defined(PPC64)
2311275970Scy  print_signal_handler(st, SIGTRAP, buf, buflen);
2312275970Scy#endif
2313275970Scy}
2314275970Scy
2315275970Scystatic char saved_jvm_path[MAXPATHLEN] = {0};
2316275970Scy
2317275970Scy// Find the full path to the current module, libjvm.so
2318275970Scyvoid os::jvm_path(char *buf, jint buflen) {
2319275970Scy  // Error checking.
2320275970Scy  if (buflen < MAXPATHLEN) {
2321275970Scy    assert(false, "must use a large-enough buffer");
2322275970Scy    buf[0] = '\0';
2323290000Sglebius    return;
2324275970Scy  }
2325275970Scy  // Lazy resolve the path to current module.
2326275970Scy  if (saved_jvm_path[0] != 0) {
2327275970Scy    strcpy(buf, saved_jvm_path);
2328275970Scy    return;
2329275970Scy  }
2330275970Scy
2331275970Scy  char dli_fname[MAXPATHLEN];
2332275970Scy  bool ret = dll_address_to_library_name(
2333275970Scy                                         CAST_FROM_FN_PTR(address, os::jvm_path),
2334275970Scy                                         dli_fname, sizeof(dli_fname), NULL);
2335275970Scy  assert(ret, "cannot locate libjvm");
2336275970Scy  char *rp = NULL;
2337275970Scy  if (ret && dli_fname[0] != '\0') {
2338275970Scy    rp = realpath(dli_fname, buf);
2339275970Scy  }
2340275970Scy  if (rp == NULL) {
2341275970Scy    return;
2342275970Scy  }
2343275970Scy
2344275970Scy  if (Arguments::sun_java_launcher_is_altjvm()) {
2345275970Scy    // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
2346275970Scy    // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so".
2347275970Scy    // If "/jre/lib/" appears at the right place in the string, then
2348275970Scy    // assume we are installed in a JDK and we're done. Otherwise, check
2349275970Scy    // for a JAVA_HOME environment variable and fix up the path so it
2350275970Scy    // looks like libjvm.so is installed there (append a fake suffix
2351275970Scy    // hotspot/libjvm.so).
2352275970Scy    const char *p = buf + strlen(buf) - 1;
2353275970Scy    for (int count = 0; p > buf && count < 5; ++count) {
2354275970Scy      for (--p; p > buf && *p != '/'; --p)
2355275970Scy        /* empty */ ;
2356275970Scy    }
2357275970Scy
2358275970Scy    if (strncmp(p, "/jre/lib/", 9) != 0) {
2359275970Scy      // Look for JAVA_HOME in the environment.
2360275970Scy      char* java_home_var = ::getenv("JAVA_HOME");
2361275970Scy      if (java_home_var != NULL && java_home_var[0] != 0) {
2362275970Scy        char* jrelib_p;
2363275970Scy        int len;
2364275970Scy
2365275970Scy        // Check the current module name "libjvm.so".
2366275970Scy        p = strrchr(buf, '/');
2367275970Scy        if (p == NULL) {
2368275970Scy          return;
2369275970Scy        }
2370275970Scy        assert(strstr(p, "/libjvm") == p, "invalid library name");
2371275970Scy
2372275970Scy        rp = realpath(java_home_var, buf);
2373275970Scy        if (rp == NULL) {
2374275970Scy          return;
2375275970Scy        }
2376275970Scy
2377275970Scy        // determine if this is a legacy image or modules image
2378275970Scy        // modules image doesn't have "jre" subdirectory
2379275970Scy        len = strlen(buf);
2380275970Scy        assert(len < buflen, "Ran out of buffer room");
2381275970Scy        jrelib_p = buf + len;
2382275970Scy        snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch);
2383275970Scy        if (0 != access(buf, F_OK)) {
2384275970Scy          snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch);
2385275970Scy        }
2386275970Scy
2387275970Scy        if (0 == access(buf, F_OK)) {
2388275970Scy          // Use current module name "libjvm.so"
2389275970Scy          len = strlen(buf);
2390275970Scy          snprintf(buf + len, buflen-len, "/hotspot/libjvm.so");
2391275970Scy        } else {
2392275970Scy          // Go back to path of .so
2393275970Scy          rp = realpath(dli_fname, buf);
2394275970Scy          if (rp == NULL) {
2395275970Scy            return;
2396275970Scy          }
2397275970Scy        }
2398275970Scy      }
2399275970Scy    }
2400275970Scy  }
2401275970Scy
2402275970Scy  strncpy(saved_jvm_path, buf, MAXPATHLEN);
2403275970Scy  saved_jvm_path[MAXPATHLEN - 1] = '\0';
2404275970Scy}
2405275970Scy
2406275970Scyvoid os::print_jni_name_prefix_on(outputStream* st, int args_size) {
2407275970Scy  // no prefix required, not even "_"
2408275970Scy}
2409275970Scy
2410275970Scyvoid os::print_jni_name_suffix_on(outputStream* st, int args_size) {
2411290000Sglebius  // no suffix required
2412275970Scy}
2413275970Scy
2414275970Scy////////////////////////////////////////////////////////////////////////////////
2415275970Scy// sun.misc.Signal support
2416275970Scy
2417275970Scystatic volatile jint sigint_count = 0;
2418275970Scy
2419275970Scystatic void UserHandler(int sig, void *siginfo, void *context) {
2420275970Scy  // 4511530 - sem_post is serialized and handled by the manager thread. When
2421275970Scy  // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We
2422275970Scy  // don't want to flood the manager thread with sem_post requests.
2423275970Scy  if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) {
2424275970Scy    return;
2425275970Scy  }
2426275970Scy
2427275970Scy  // Ctrl-C is pressed during error reporting, likely because the error
2428275970Scy  // handler fails to abort. Let VM die immediately.
2429275970Scy  if (sig == SIGINT && is_error_reported()) {
2430310419Sdelphij    os::die();
2431275970Scy  }
2432275970Scy
2433275970Scy  os::signal_notify(sig);
2434275970Scy}
2435275970Scy
2436275970Scyvoid* os::user_handler() {
2437275970Scy  return CAST_FROM_FN_PTR(void*, UserHandler);
2438275970Scy}
2439275970Scy
2440275970Scystruct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) {
2441275970Scy  struct timespec ts;
2442275970Scy  // Semaphore's are always associated with CLOCK_REALTIME
2443275970Scy  os::Linux::clock_gettime(CLOCK_REALTIME, &ts);
2444275970Scy  // see unpackTime for discussion on overflow checking
2445275970Scy  if (sec >= MAX_SECS) {
2446275970Scy    ts.tv_sec += MAX_SECS;
2447275970Scy    ts.tv_nsec = 0;
2448275970Scy  } else {
2449275970Scy    ts.tv_sec += sec;
2450275970Scy    ts.tv_nsec += nsec;
2451275970Scy    if (ts.tv_nsec >= NANOSECS_PER_SEC) {
2452275970Scy      ts.tv_nsec -= NANOSECS_PER_SEC;
2453275970Scy      ++ts.tv_sec; // note: this must be <= max_secs
2454275970Scy    }
2455275970Scy  }
2456275970Scy
2457275970Scy  return ts;
2458275970Scy}
2459275970Scy
2460275970Scyextern "C" {
2461275970Scy  typedef void (*sa_handler_t)(int);
2462275970Scy  typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
2463275970Scy}
2464275970Scy
2465275970Scyvoid* os::signal(int signal_number, void* handler) {
2466275970Scy  struct sigaction sigAct, oldSigAct;
2467275970Scy
2468275970Scy  sigfillset(&(sigAct.sa_mask));
2469275970Scy  sigAct.sa_flags   = SA_RESTART|SA_SIGINFO;
2470275970Scy  sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
2471275970Scy
2472275970Scy  if (sigaction(signal_number, &sigAct, &oldSigAct)) {
2473275970Scy    // -1 means registration failed
2474275970Scy    return (void *)-1;
2475275970Scy  }
2476275970Scy
2477275970Scy  return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
2478275970Scy}
2479275970Scy
2480275970Scyvoid os::signal_raise(int signal_number) {
2481275970Scy  ::raise(signal_number);
2482275970Scy}
2483275970Scy
2484275970Scy// The following code is moved from os.cpp for making this
2485275970Scy// code platform specific, which it is by its very nature.
2486290000Sglebius
2487275970Scy// Will be modified when max signal is changed to be dynamic
2488275970Scyint os::sigexitnum_pd() {
2489275970Scy  return NSIG;
2490275970Scy}
2491275970Scy
2492275970Scy// a counter for each possible signal value
2493275970Scystatic volatile jint pending_signals[NSIG+1] = { 0 };
2494275970Scy
2495275970Scy// Linux(POSIX) specific hand shaking semaphore.
2496275970Scystatic sem_t sig_sem;
2497275970Scystatic PosixSemaphore sr_semaphore;
2498275970Scy
2499275970Scyvoid os::signal_init_pd() {
2500275970Scy  // Initialize signal structures
2501275970Scy  ::memset((void*)pending_signals, 0, sizeof(pending_signals));
2502275970Scy
2503275970Scy  // Initialize signal semaphore
2504275970Scy  ::sem_init(&sig_sem, 0, 0);
2505275970Scy}
2506275970Scy
2507275970Scyvoid os::signal_notify(int sig) {
2508275970Scy  Atomic::inc(&pending_signals[sig]);
2509275970Scy  ::sem_post(&sig_sem);
2510275970Scy}
2511275970Scy
2512275970Scystatic int check_pending_signals(bool wait) {
2513275970Scy  Atomic::store(0, &sigint_count);
2514275970Scy  for (;;) {
2515275970Scy    for (int i = 0; i < NSIG + 1; i++) {
2516275970Scy      jint n = pending_signals[i];
2517275970Scy      if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
2518275970Scy        return i;
2519275970Scy      }
2520275970Scy    }
2521275970Scy    if (!wait) {
2522275970Scy      return -1;
2523275970Scy    }
2524275970Scy    JavaThread *thread = JavaThread::current();
2525275970Scy    ThreadBlockInVM tbivm(thread);
2526275970Scy
2527275970Scy    bool threadIsSuspended;
2528275970Scy    do {
2529275970Scy      thread->set_suspend_equivalent();
2530275970Scy      // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
2531275970Scy      ::sem_wait(&sig_sem);
2532275970Scy
2533275970Scy      // were we externally suspended while we were waiting?
2534275970Scy      threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2535275970Scy      if (threadIsSuspended) {
2536275970Scy        // The semaphore has been incremented, but while we were waiting
2537275970Scy        // another thread suspended us. We don't want to continue running
2538275970Scy        // while suspended because that would surprise the thread that
2539275970Scy        // suspended us.
2540275970Scy        ::sem_post(&sig_sem);
2541275970Scy
2542275970Scy        thread->java_suspend_self();
2543275970Scy      }
2544275970Scy    } while (threadIsSuspended);
2545275970Scy  }
2546275970Scy}
2547275970Scy
2548275970Scyint os::signal_lookup() {
2549275970Scy  return check_pending_signals(false);
2550275970Scy}
2551275970Scy
2552275970Scyint os::signal_wait() {
2553275970Scy  return check_pending_signals(true);
2554275970Scy}
2555275970Scy
2556275970Scy////////////////////////////////////////////////////////////////////////////////
2557275970Scy// Virtual Memory
2558275970Scy
2559275970Scyint os::vm_page_size() {
2560275970Scy  // Seems redundant as all get out
2561275970Scy  assert(os::Linux::page_size() != -1, "must call os::init");
2562275970Scy  return os::Linux::page_size();
2563275970Scy}
2564275970Scy
2565275970Scy// Solaris allocates memory by pages.
2566275970Scyint os::vm_allocation_granularity() {
2567275970Scy  assert(os::Linux::page_size() != -1, "must call os::init");
2568275970Scy  return os::Linux::page_size();
2569275970Scy}
2570275970Scy
2571275970Scy// Rationale behind this function:
2572275970Scy//  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
2573275970Scy//  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
2574275970Scy//  samples for JITted code. Here we create private executable mapping over the code cache
2575275970Scy//  and then we can use standard (well, almost, as mapping can change) way to provide
2576275970Scy//  info for the reporting script by storing timestamp and location of symbol
2577275970Scyvoid linux_wrap_code(char* base, size_t size) {
2578275970Scy  static volatile jint cnt = 0;
2579310419Sdelphij
2580275970Scy  if (!UseOprofile) {
2581310419Sdelphij    return;
2582275970Scy  }
2583275970Scy
2584275970Scy  char buf[PATH_MAX+1];
2585275970Scy  int num = Atomic::add(1, &cnt);
2586275970Scy
2587275970Scy  snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d",
2588275970Scy           os::get_temp_directory(), os::current_process_id(), num);
2589275970Scy  unlink(buf);
2590275970Scy
2591275970Scy  int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
2592275970Scy
2593275970Scy  if (fd != -1) {
2594275970Scy    off_t rv = ::lseek(fd, size-2, SEEK_SET);
2595275970Scy    if (rv != (off_t)-1) {
2596275970Scy      if (::write(fd, "", 1) == 1) {
2597275970Scy        mmap(base, size,
2598275970Scy             PROT_READ|PROT_WRITE|PROT_EXEC,
2599275970Scy             MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
2600275970Scy      }
2601275970Scy    }
2602275970Scy    ::close(fd);
2603275970Scy    unlink(buf);
2604275970Scy  }
2605275970Scy}
2606275970Scy
2607275970Scystatic bool recoverable_mmap_error(int err) {
2608275970Scy  // See if the error is one we can let the caller handle. This
2609275970Scy  // list of errno values comes from JBS-6843484. I can't find a
2610275970Scy  // Linux man page that documents this specific set of errno
2611275970Scy  // values so while this list currently matches Solaris, it may
2612275970Scy  // change as we gain experience with this failure mode.
2613275970Scy  switch (err) {
2614275970Scy  case EBADF:
2615275970Scy  case EINVAL:
2616275970Scy  case ENOTSUP:
2617275970Scy    // let the caller deal with these errors
2618275970Scy    return true;
2619275970Scy
2620275970Scy  default:
2621275970Scy    // Any remaining errors on this OS can cause our reserved mapping
2622275970Scy    // to be lost. That can cause confusion where different data
2623275970Scy    // structures think they have the same memory mapped. The worst
2624275970Scy    // scenario is if both the VM and a library think they have the
2625275970Scy    // same memory mapped.
2626275970Scy    return false;
2627275970Scy  }
2628275970Scy}
2629290000Sglebius
2630275970Scystatic void warn_fail_commit_memory(char* addr, size_t size, bool exec,
2631275970Scy                                    int err) {
2632275970Scy  warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2633275970Scy          ", %d) failed; error='%s' (errno=%d)", p2i(addr), size, exec,
2634290000Sglebius          strerror(err), err);
2635290000Sglebius}
2636298770Sdelphij
2637298770Sdelphijstatic void warn_fail_commit_memory(char* addr, size_t size,
2638290000Sglebius                                    size_t alignment_hint, bool exec,
2639301301Sdelphij                                    int err) {
2640275970Scy  warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2641301301Sdelphij          ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", p2i(addr), size,
2642275970Scy          alignment_hint, exec, strerror(err), err);
2643275970Scy}
2644275970Scy
2645275970Scy// NOTE: Linux kernel does not really reserve the pages for us.
2646290000Sglebius//       All it does is to check if there are enough free pages
2647275970Scy//       left at the time of mmap(). This could be a potential
2648275970Scy//       problem.
2649275970Scyint os::Linux::commit_memory_impl(char* addr, size_t size, bool exec) {
2650275970Scy  int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2651275970Scy  uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2652275970Scy                                     MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2653275970Scy  if (res != (uintptr_t) MAP_FAILED) {
2654275970Scy    if (UseNUMAInterleaving) {
2655275970Scy      numa_make_global(addr, size);
2656275970Scy    }
2657275970Scy    return 0;
2658275970Scy  }
2659275970Scy
2660275970Scy  int err = errno;  // save errno from mmap() call above
2661275970Scy
2662275970Scy  if (!recoverable_mmap_error(err)) {
2663275970Scy    warn_fail_commit_memory(addr, size, exec, err);
2664275970Scy    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "committing reserved memory.");
2665275970Scy  }
2666275970Scy
2667275970Scy  return err;
2668275970Scy}
2669275970Scy
2670275970Scybool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2671275970Scy  return os::Linux::commit_memory_impl(addr, size, exec) == 0;
2672275970Scy}
2673275970Scy
2674275970Scyvoid os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
2675275970Scy                                  const char* mesg) {
2676275970Scy  assert(mesg != NULL, "mesg must be specified");
2677275970Scy  int err = os::Linux::commit_memory_impl(addr, size, exec);
2678275970Scy  if (err != 0) {
2679275970Scy    // the caller wants all commit errors to exit with the specified mesg:
2680275970Scy    warn_fail_commit_memory(addr, size, exec, err);
2681275970Scy    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);
2682275970Scy  }
2683290000Sglebius}
2684275970Scy
2685275970Scy// Define MAP_HUGETLB here so we can build HotSpot on old systems.
2686275970Scy#ifndef MAP_HUGETLB
2687290000Sglebius  #define MAP_HUGETLB 0x40000
2688275970Scy#endif
2689290000Sglebius
2690275970Scy// Define MADV_HUGEPAGE here so we can build HotSpot on old systems.
2691290000Sglebius#ifndef MADV_HUGEPAGE
2692275970Scy  #define MADV_HUGEPAGE 14
2693275970Scy#endif
2694275970Scy
2695275970Scyint os::Linux::commit_memory_impl(char* addr, size_t size,
2696275970Scy                                  size_t alignment_hint, bool exec) {
2697290000Sglebius  int err = os::Linux::commit_memory_impl(addr, size, exec);
2698275970Scy  if (err == 0) {
2699275970Scy    realign_memory(addr, size, alignment_hint);
2700275970Scy  }
2701275970Scy  return err;
2702275970Scy}
2703275970Scy
2704275970Scybool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2705275970Scy                          bool exec) {
2706275970Scy  return os::Linux::commit_memory_impl(addr, size, alignment_hint, exec) == 0;
2707275970Scy}
2708275970Scy
2709275970Scyvoid os::pd_commit_memory_or_exit(char* addr, size_t size,
2710275970Scy                                  size_t alignment_hint, bool exec,
2711275970Scy                                  const char* mesg) {
2712275970Scy  assert(mesg != NULL, "mesg must be specified");
2713275970Scy  int err = os::Linux::commit_memory_impl(addr, size, alignment_hint, exec);
2714301301Sdelphij  if (err != 0) {
2715301301Sdelphij    // the caller wants all commit errors to exit with the specified mesg:
2716301301Sdelphij    warn_fail_commit_memory(addr, size, alignment_hint, exec, err);
2717301301Sdelphij    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);
2718301301Sdelphij  }
2719301301Sdelphij}
2720301301Sdelphij
2721301301Sdelphijvoid os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2722301301Sdelphij  if (UseTransparentHugePages && alignment_hint > (size_t)vm_page_size()) {
2723301301Sdelphij    // We don't check the return value: madvise(MADV_HUGEPAGE) may not
2724301301Sdelphij    // be supported or the memory may already be backed by huge pages.
2725301301Sdelphij    ::madvise(addr, bytes, MADV_HUGEPAGE);
2726301301Sdelphij  }
2727301301Sdelphij}
2728301301Sdelphij
2729301301Sdelphijvoid os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2730301301Sdelphij  // This method works by doing an mmap over an existing mmaping and effectively discarding
2731301301Sdelphij  // the existing pages. However it won't work for SHM-based large pages that cannot be
2732301301Sdelphij  // uncommitted at all. We don't do anything in this case to avoid creating a segment with
2733301301Sdelphij  // small pages on top of the SHM segment. This method always works for small pages, so we
2734301301Sdelphij  // allow that in any case.
2735275970Scy  if (alignment_hint <= (size_t)os::vm_page_size() || can_commit_large_page_memory()) {
2736275970Scy    commit_memory(addr, bytes, alignment_hint, !ExecMem);
2737275970Scy  }
2738275970Scy}
2739275970Scy
2740275970Scyvoid os::numa_make_global(char *addr, size_t bytes) {
2741275970Scy  Linux::numa_interleave_memory(addr, bytes);
2742294904Sdelphij}
2743294904Sdelphij
2744294904Sdelphij// Define for numa_set_bind_policy(int). Setting the argument to 0 will set the
2745294904Sdelphij// bind policy to MPOL_PREFERRED for the current thread.
2746294904Sdelphij#define USE_MPOL_PREFERRED 0
2747294904Sdelphij
2748294904Sdelphijvoid os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2749294904Sdelphij  // To make NUMA and large pages more robust when both enabled, we need to ease
2750294904Sdelphij  // the requirements on where the memory should be allocated. MPOL_BIND is the
2751294904Sdelphij  // default policy and it will force memory to be allocated on the specified
2752294904Sdelphij  // node. Changing this to MPOL_PREFERRED will prefer to allocate the memory on
2753294904Sdelphij  // the specified node, but will not force it. Using this policy will prevent
2754294904Sdelphij  // getting SIGBUS when trying to allocate large pages on NUMA nodes with no
2755294904Sdelphij  // free large pages.
2756294904Sdelphij  Linux::numa_set_bind_policy(USE_MPOL_PREFERRED);
2757294904Sdelphij  Linux::numa_tonode_memory(addr, bytes, lgrp_hint);
2758294904Sdelphij}
2759294904Sdelphij
2760294904Sdelphijbool os::numa_topology_changed() { return false; }
2761294904Sdelphij
2762294904Sdelphijsize_t os::numa_get_groups_num() {
2763294904Sdelphij  int max_node = Linux::numa_max_node();
2764294904Sdelphij  return max_node > 0 ? max_node + 1 : 1;
2765294904Sdelphij}
2766294904Sdelphij
2767294904Sdelphijint os::numa_get_group_id() {
2768294904Sdelphij  int cpu_id = Linux::sched_getcpu();
2769294904Sdelphij  if (cpu_id != -1) {
2770294904Sdelphij    int lgrp_id = Linux::get_node_by_cpu(cpu_id);
2771294904Sdelphij    if (lgrp_id != -1) {
2772294904Sdelphij      return lgrp_id;
2773294904Sdelphij    }
2774294904Sdelphij  }
2775294904Sdelphij  return 0;
2776294904Sdelphij}
2777294904Sdelphij
2778294904Sdelphijsize_t os::numa_get_leaf_groups(int *ids, size_t size) {
2779294904Sdelphij  for (size_t i = 0; i < size; i++) {
2780294904Sdelphij    ids[i] = i;
2781294904Sdelphij  }
2782294904Sdelphij  return size;
2783294904Sdelphij}
2784294904Sdelphij
2785294904Sdelphijbool os::get_page_info(char *start, page_info* info) {
2786294904Sdelphij  return false;
2787294904Sdelphij}
2788294904Sdelphij
2789294904Sdelphijchar *os::scan_pages(char *start, char* end, page_info* page_expected,
2790294904Sdelphij                     page_info* page_found) {
2791294904Sdelphij  return end;
2792294904Sdelphij}
2793294904Sdelphij
2794294904Sdelphij
2795294904Sdelphijint os::Linux::sched_getcpu_syscall(void) {
2796294904Sdelphij  unsigned int cpu = 0;
2797294904Sdelphij  int retval = -1;
2798294904Sdelphij
2799294904Sdelphij#if defined(IA32)
2800294904Sdelphij  #ifndef SYS_getcpu
2801294904Sdelphij    #define SYS_getcpu 318
2802294904Sdelphij  #endif
2803294904Sdelphij  retval = syscall(SYS_getcpu, &cpu, NULL, NULL);
2804294904Sdelphij#elif defined(AMD64)
2805294904Sdelphij// Unfortunately we have to bring all these macros here from vsyscall.h
2806275970Scy// to be able to compile on old linuxes.
2807275970Scy  #define __NR_vgetcpu 2
2808275970Scy  #define VSYSCALL_START (-10UL << 20)
2809275970Scy  #define VSYSCALL_SIZE 1024
2810275970Scy  #define VSYSCALL_ADDR(vsyscall_nr) (VSYSCALL_START+VSYSCALL_SIZE*(vsyscall_nr))
2811275970Scy  typedef long (*vgetcpu_t)(unsigned int *cpu, unsigned int *node, unsigned long *tcache);
2812275970Scy  vgetcpu_t vgetcpu = (vgetcpu_t)VSYSCALL_ADDR(__NR_vgetcpu);
2813275970Scy  retval = vgetcpu(&cpu, NULL, NULL);
2814275970Scy#endif
2815275970Scy
2816290000Sglebius  return (retval == -1) ? retval : cpu;
2817275970Scy}
2818275970Scy
2819275970Scy// Something to do with the numa-aware allocator needs these symbols
2820290000Sglebiusextern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { }
2821290000Sglebiusextern "C" JNIEXPORT void numa_error(char *where) { }
2822290000Sglebius
2823290000Sglebius
2824290000Sglebius// If we are running with libnuma version > 2, then we should
2825290000Sglebius// be trying to use symbols with versions 1.1
2826290000Sglebius// If we are running with earlier version, which did not have symbol versions,
2827290000Sglebius// we should use the base version.
2828290000Sglebiusvoid* os::Linux::libnuma_dlsym(void* handle, const char *name) {
2829290000Sglebius  void *f = dlvsym(handle, name, "libnuma_1.1");
2830290000Sglebius  if (f == NULL) {
2831290000Sglebius    f = dlsym(handle, name);
2832290000Sglebius  }
2833290000Sglebius  return f;
2834275970Scy}
2835275970Scy
2836275970Scybool os::Linux::libnuma_init() {
2837290000Sglebius  // sched_getcpu() should be in libc.
2838275970Scy  set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,
2839275970Scy                                  dlsym(RTLD_DEFAULT, "sched_getcpu")));
2840275970Scy
2841275970Scy  // If it's not, try a direct syscall.
2842275970Scy  if (sched_getcpu() == -1) {
2843275970Scy    set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,
2844275970Scy                                    (void*)&sched_getcpu_syscall));
2845275970Scy  }
2846275970Scy
2847275970Scy  if (sched_getcpu() != -1) { // Does it work?
2848275970Scy    void *handle = dlopen("libnuma.so.1", RTLD_LAZY);
2849275970Scy    if (handle != NULL) {
2850275970Scy      set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t,
2851275970Scy                                           libnuma_dlsym(handle, "numa_node_to_cpus")));
2852290000Sglebius      set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t,
2853275970Scy                                       libnuma_dlsym(handle, "numa_max_node")));
2854275970Scy      set_numa_available(CAST_TO_FN_PTR(numa_available_func_t,
2855275970Scy                                        libnuma_dlsym(handle, "numa_available")));
2856275970Scy      set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t,
2857275970Scy                                            libnuma_dlsym(handle, "numa_tonode_memory")));
2858275970Scy      set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t,
2859290000Sglebius                                                libnuma_dlsym(handle, "numa_interleave_memory")));
2860275970Scy      set_numa_set_bind_policy(CAST_TO_FN_PTR(numa_set_bind_policy_func_t,
2861275970Scy                                              libnuma_dlsym(handle, "numa_set_bind_policy")));
2862275970Scy
2863275970Scy
2864275970Scy      if (numa_available() != -1) {
2865275970Scy        set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes"));
2866275970Scy        // Create a cpu -> node mapping
2867275970Scy        _cpu_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, true);
2868275970Scy        rebuild_cpu_to_node_map();
2869275970Scy        return true;
2870275970Scy      }
2871275970Scy    }
2872275970Scy  }
2873275970Scy  return false;
2874275970Scy}
2875275970Scy
2876275970Scy// rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id.
2877275970Scy// The table is later used in get_node_by_cpu().
2878275970Scyvoid os::Linux::rebuild_cpu_to_node_map() {
2879275970Scy  const size_t NCPUS = 32768; // Since the buffer size computation is very obscure
2880275970Scy                              // in libnuma (possible values are starting from 16,
2881275970Scy                              // and continuing up with every other power of 2, but less
2882275970Scy                              // than the maximum number of CPUs supported by kernel), and
2883275970Scy                              // is a subject to change (in libnuma version 2 the requirements
2884275970Scy                              // are more reasonable) we'll just hardcode the number they use
2885298770Sdelphij                              // in the library.
2886298770Sdelphij  const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;
2887275970Scy
2888275970Scy  size_t cpu_num = os::active_processor_count();
2889275970Scy  size_t cpu_map_size = NCPUS / BitsPerCLong;
2890275970Scy  size_t cpu_map_valid_size =
2891275970Scy    MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);
2892275970Scy
2893275970Scy  cpu_to_node()->clear();
2894275970Scy  cpu_to_node()->at_grow(cpu_num - 1);
2895275970Scy  size_t node_num = numa_get_groups_num();
2896275970Scy
2897275970Scy  unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal);
2898290000Sglebius  for (size_t i = 0; i < node_num; i++) {
2899275970Scy    if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) {
2900275970Scy      for (size_t j = 0; j < cpu_map_valid_size; j++) {
2901275970Scy        if (cpu_map[j] != 0) {
2902275970Scy          for (size_t k = 0; k < BitsPerCLong; k++) {
2903275970Scy            if (cpu_map[j] & (1UL << k)) {
2904275970Scy              cpu_to_node()->at_put(j * BitsPerCLong + k, i);
2905275970Scy            }
2906275970Scy          }
2907275970Scy        }
2908275970Scy      }
2909275970Scy    }
2910275970Scy  }
2911275970Scy  FREE_C_HEAP_ARRAY(unsigned long, cpu_map);
2912275970Scy}
2913275970Scy
2914275970Scyint os::Linux::get_node_by_cpu(int cpu_id) {
2915275970Scy  if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) {
2916275970Scy    return cpu_to_node()->at(cpu_id);
2917275970Scy  }
2918275970Scy  return -1;
2919290000Sglebius}
2920275970Scy
2921298770SdelphijGrowableArray<int>* os::Linux::_cpu_to_node;
2922298770Sdelphijos::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu;
2923298770Sdelphijos::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus;
2924275970Scyos::Linux::numa_max_node_func_t os::Linux::_numa_max_node;
2925275970Scyos::Linux::numa_available_func_t os::Linux::_numa_available;
2926275970Scyos::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory;
2927275970Scyos::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory;
2928275970Scyos::Linux::numa_set_bind_policy_func_t os::Linux::_numa_set_bind_policy;
2929275970Scyunsigned long* os::Linux::_numa_all_nodes;
2930275970Scy
2931275970Scybool os::pd_uncommit_memory(char* addr, size_t size) {
2932275970Scy  uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
2933275970Scy                                     MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
2934275970Scy  return res  != (uintptr_t) MAP_FAILED;
2935275970Scy}
2936290000Sglebius
2937275970Scystatic address get_stack_commited_bottom(address bottom, size_t size) {
2938275970Scy  address nbot = bottom;
2939275970Scy  address ntop = bottom + size;
2940275970Scy
2941275970Scy  size_t page_sz = os::vm_page_size();
2942275970Scy  unsigned pages = size / page_sz;
2943275970Scy
2944275970Scy  unsigned char vec[1];
2945275970Scy  unsigned imin = 1, imax = pages + 1, imid;
2946275970Scy  int mincore_return_value = 0;
2947275970Scy
2948275970Scy  assert(imin <= imax, "Unexpected page size");
2949275970Scy
2950275970Scy  while (imin < imax) {
2951275970Scy    imid = (imax + imin) / 2;
2952275970Scy    nbot = ntop - (imid * page_sz);
2953275970Scy
2954275970Scy    // Use a trick with mincore to check whether the page is mapped or not.
2955275970Scy    // mincore sets vec to 1 if page resides in memory and to 0 if page
2956275970Scy    // is swapped output but if page we are asking for is unmapped
2957275970Scy    // it returns -1,ENOMEM
2958290000Sglebius    mincore_return_value = mincore(nbot, page_sz, vec);
2959275970Scy
2960275970Scy    if (mincore_return_value == -1) {
2961275970Scy      // Page is not mapped go up
2962275970Scy      // to find first mapped page
2963275970Scy      if (errno != EAGAIN) {
2964275970Scy        assert(errno == ENOMEM, "Unexpected mincore errno");
2965275970Scy        imax = imid;
2966275970Scy      }
2967275970Scy    } else {
2968275970Scy      // Page is mapped go down
2969275970Scy      // to find first not mapped page
2970275970Scy      imin = imid + 1;
2971275970Scy    }
2972275970Scy  }
2973275970Scy
2974275970Scy  nbot = nbot + page_sz;
2975275970Scy
2976275970Scy  // Adjust stack bottom one page up if last checked page is not mapped
2977275970Scy  if (mincore_return_value == -1) {
2978275970Scy    nbot = nbot + page_sz;
2979275970Scy  }
2980275970Scy
2981275970Scy  return nbot;
2982275970Scy}
2983275970Scy
2984275970Scy
2985275970Scy// Linux uses a growable mapping for the stack, and if the mapping for
2986275970Scy// the stack guard pages is not removed when we detach a thread the
2987275970Scy// stack cannot grow beyond the pages where the stack guard was
2988275970Scy// mapped.  If at some point later in the process the stack expands to
2989275970Scy// that point, the Linux kernel cannot expand the stack any further
2990275970Scy// because the guard pages are in the way, and a segfault occurs.
2991275970Scy//
2992275970Scy// However, it's essential not to split the stack region by unmapping
2993275970Scy// a region (leaving a hole) that's already part of the stack mapping,
2994275970Scy// so if the stack mapping has already grown beyond the guard pages at
2995275970Scy// the time we create them, we have to truncate the stack mapping.
2996275970Scy// So, we need to know the extent of the stack mapping when
2997275970Scy// create_stack_guard_pages() is called.
2998275970Scy
2999275970Scy// We only need this for stacks that are growable: at the time of
3000275970Scy// writing thread stacks don't use growable mappings (i.e. those
3001275970Scy// creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this
3002275970Scy// only applies to the main thread.
3003275970Scy
3004275970Scy// If the (growable) stack mapping already extends beyond the point
3005275970Scy// where we're going to put our guard pages, truncate the mapping at
3006275970Scy// that point by munmap()ping it.  This ensures that when we later
3007275970Scy// munmap() the guard pages we don't leave a hole in the stack
3008275970Scy// mapping. This only affects the main/initial thread
3009275970Scy
3010275970Scybool os::pd_create_stack_guard_pages(char* addr, size_t size) {
3011275970Scy  if (os::Linux::is_initial_thread()) {
3012275970Scy    // As we manually grow stack up to bottom inside create_attached_thread(),
3013275970Scy    // it's likely that os::Linux::initial_thread_stack_bottom is mapped and
3014275970Scy    // we don't need to do anything special.
3015275970Scy    // Check it first, before calling heavy function.
3016275970Scy    uintptr_t stack_extent = (uintptr_t) os::Linux::initial_thread_stack_bottom();
3017275970Scy    unsigned char vec[1];
3018275970Scy
3019275970Scy    if (mincore((address)stack_extent, os::vm_page_size(), vec) == -1) {
3020275970Scy      // Fallback to slow path on all errors, including EAGAIN
3021275970Scy      stack_extent = (uintptr_t) get_stack_commited_bottom(
3022275970Scy                                                           os::Linux::initial_thread_stack_bottom(),
3023275970Scy                                                           (size_t)addr - stack_extent);
3024290000Sglebius    }
3025290000Sglebius
3026290000Sglebius    if (stack_extent < (uintptr_t)addr) {
3027290000Sglebius      ::munmap((void*)stack_extent, (uintptr_t)(addr - stack_extent));
3028290000Sglebius    }
3029290000Sglebius  }
3030290000Sglebius
3031290000Sglebius  return os::commit_memory(addr, size, !ExecMem);
3032290000Sglebius}
3033290000Sglebius
3034290000Sglebius// If this is a growable mapping, remove the guard pages entirely by
3035290000Sglebius// munmap()ping them.  If not, just call uncommit_memory(). This only
3036290000Sglebius// affects the main/initial thread, but guard against future OS changes
3037290000Sglebius// It's safe to always unmap guard pages for initial thread because we
3038290000Sglebius// always place it right after end of the mapped region
3039275970Scy
3040275970Scybool os::remove_stack_guard_pages(char* addr, size_t size) {
3041275970Scy  uintptr_t stack_extent, stack_base;
3042275970Scy
3043275970Scy  if (os::Linux::is_initial_thread()) {
3044275970Scy    return ::munmap(addr, size) == 0;
3045275970Scy  }
3046275970Scy
3047275970Scy  return os::uncommit_memory(addr, size);
3048275970Scy}
3049275970Scy
3050275970Scy// If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory
3051290000Sglebius// at 'requested_addr'. If there are existing memory mappings at the same
3052290000Sglebius// location, however, they will be overwritten. If 'fixed' is false,
3053290000Sglebius// 'requested_addr' is only treated as a hint, the return value may or
3054275970Scy// may not start from the requested address. Unlike Linux mmap(), this
3055275970Scy// function returns NULL to indicate failure.
3056275970Scystatic char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) {
3057290000Sglebius  char * addr;
3058290000Sglebius  int flags;
3059290000Sglebius
3060275970Scy  flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
3061275970Scy  if (fixed) {
3062275970Scy    assert((uintptr_t)requested_addr % os::Linux::page_size() == 0, "unaligned address");
3063290000Sglebius    flags |= MAP_FIXED;
3064290000Sglebius  }
3065290000Sglebius
3066275970Scy  // Map reserved/uncommitted pages PROT_NONE so we fail early if we
3067275970Scy  // touch an uncommitted page. Otherwise, the read/write might
3068298770Sdelphij  // succeed if we have enough swap space to back the physical page.
3069298770Sdelphij  addr = (char*)::mmap(requested_addr, bytes, PROT_NONE,
3070275970Scy                       flags, -1, 0);
3071275970Scy
3072275970Scy  return addr == MAP_FAILED ? NULL : addr;
3073275970Scy}
3074275970Scy
3075275970Scystatic int anon_munmap(char * addr, size_t size) {
3076275970Scy  return ::munmap(addr, size) == 0;
3077275970Scy}
3078275970Scy
3079275970Scychar* os::pd_reserve_memory(size_t bytes, char* requested_addr,
3080275970Scy                            size_t alignment_hint) {
3081275970Scy  return anon_mmap(requested_addr, bytes, (requested_addr != NULL));
3082275970Scy}
3083275970Scy
3084275970Scybool os::pd_release_memory(char* addr, size_t size) {
3085275970Scy  return anon_munmap(addr, size);
3086275970Scy}
3087275970Scy
3088275970Scystatic bool linux_mprotect(char* addr, size_t size, int prot) {
3089275970Scy  // Linux wants the mprotect address argument to be page aligned.
3090275970Scy  char* bottom = (char*)align_size_down((intptr_t)addr, os::Linux::page_size());
3091275970Scy
3092275970Scy  // According to SUSv3, mprotect() should only be used with mappings
3093275970Scy  // established by mmap(), and mmap() always maps whole pages. Unaligned
3094275970Scy  // 'addr' likely indicates problem in the VM (e.g. trying to change
3095275970Scy  // protection of malloc'ed or statically allocated memory). Check the
3096275970Scy  // caller if you hit this assert.
3097275970Scy  assert(addr == bottom, "sanity check");
3098275970Scy
3099275970Scy  size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size());
3100310419Sdelphij  return ::mprotect(bottom, size, prot) == 0;
3101275970Scy}
3102310419Sdelphij
3103275970Scy// Set protections specified
3104275970Scybool os::protect_memory(char* addr, size_t bytes, ProtType prot,
3105275970Scy                        bool is_committed) {
3106275970Scy  unsigned int p = 0;
3107275970Scy  switch (prot) {
3108275970Scy  case MEM_PROT_NONE: p = PROT_NONE; break;
3109275970Scy  case MEM_PROT_READ: p = PROT_READ; break;
3110275970Scy  case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
3111275970Scy  case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
3112275970Scy  default:
3113275970Scy    ShouldNotReachHere();
3114310419Sdelphij  }
3115275970Scy  // is_committed is unused.
3116275970Scy  return linux_mprotect(addr, bytes, p);
3117275970Scy}
3118275970Scy
3119275970Scybool os::guard_memory(char* addr, size_t size) {
3120275970Scy  return linux_mprotect(addr, size, PROT_NONE);
3121275970Scy}
3122275970Scy
3123275970Scybool os::unguard_memory(char* addr, size_t size) {
3124275970Scy  return linux_mprotect(addr, size, PROT_READ|PROT_WRITE);
3125310419Sdelphij}
3126275970Scy
3127275970Scybool os::Linux::transparent_huge_pages_sanity_check(bool warn,
3128275970Scy                                                    size_t page_size) {
3129275970Scy  bool result = false;
3130275970Scy  void *p = mmap(NULL, page_size * 2, PROT_READ|PROT_WRITE,
3131275970Scy                 MAP_ANONYMOUS|MAP_PRIVATE,
3132275970Scy                 -1, 0);
3133275970Scy  if (p != MAP_FAILED) {
3134275970Scy    void *aligned_p = align_ptr_up(p, page_size);
3135275970Scy
3136275970Scy    result = madvise(aligned_p, page_size, MADV_HUGEPAGE) == 0;
3137275970Scy
3138275970Scy    munmap(p, page_size * 2);
3139275970Scy  }
3140275970Scy
3141275970Scy  if (warn && !result) {
3142275970Scy    warning("TransparentHugePages is not supported by the operating system.");
3143275970Scy  }
3144275970Scy
3145275970Scy  return result;
3146275970Scy}
3147275970Scy
3148275970Scybool os::Linux::hugetlbfs_sanity_check(bool warn, size_t page_size) {
3149310419Sdelphij  bool result = false;
3150275970Scy  void *p = mmap(NULL, page_size, PROT_READ|PROT_WRITE,
3151275970Scy                 MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB,
3152310419Sdelphij                 -1, 0);
3153275970Scy
3154275970Scy  if (p != MAP_FAILED) {
3155275970Scy    // We don't know if this really is a huge page or not.
3156275970Scy    FILE *fp = fopen("/proc/self/maps", "r");
3157275970Scy    if (fp) {
3158275970Scy      while (!feof(fp)) {
3159275970Scy        char chars[257];
3160275970Scy        long x = 0;
3161275970Scy        if (fgets(chars, sizeof(chars), fp)) {
3162275970Scy          if (sscanf(chars, "%lx-%*x", &x) == 1
3163310419Sdelphij              && x == (long)p) {
3164275970Scy            if (strstr (chars, "hugepage")) {
3165290000Sglebius              result = true;
3166290000Sglebius              break;
3167290000Sglebius            }
3168275970Scy          }
3169275970Scy        }
3170275970Scy      }
3171275970Scy      fclose(fp);
3172275970Scy    }
3173275970Scy    munmap(p, page_size);
3174275970Scy  }
3175275970Scy
3176275970Scy  if (warn && !result) {
3177275970Scy    warning("HugeTLBFS is not supported by the operating system.");
3178275970Scy  }
3179275970Scy
3180275970Scy  return result;
3181275970Scy}
3182275970Scy
3183280849Scy// Set the coredump_filter bits to include largepages in core dump (bit 6)
3184275970Scy//
3185294904Sdelphij// From the coredump_filter documentation:
3186275970Scy//
3187275970Scy// - (bit 0) anonymous private memory
3188275970Scy// - (bit 1) anonymous shared memory
3189275970Scy// - (bit 2) file-backed private memory
3190275970Scy// - (bit 3) file-backed shared memory
3191275970Scy// - (bit 4) ELF header pages in file-backed private memory areas (it is
3192275970Scy//           effective only if the bit 2 is cleared)
3193275970Scy// - (bit 5) hugetlb private memory
3194275970Scy// - (bit 6) hugetlb shared memory
3195275970Scy//
3196275970Scystatic void set_coredump_filter(void) {
3197275970Scy  FILE *f;
3198275970Scy  long cdm;
3199275970Scy
3200275970Scy  if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) {
3201275970Scy    return;
3202275970Scy  }
3203275970Scy
3204275970Scy  if (fscanf(f, "%lx", &cdm) != 1) {
3205275970Scy    fclose(f);
3206275970Scy    return;
3207275970Scy  }
3208275970Scy
3209275970Scy  rewind(f);
3210275970Scy
3211  if ((cdm & LARGEPAGES_BIT) == 0) {
3212    cdm |= LARGEPAGES_BIT;
3213    fprintf(f, "%#lx", cdm);
3214  }
3215
3216  fclose(f);
3217}
3218
3219// Large page support
3220
3221static size_t _large_page_size = 0;
3222
3223size_t os::Linux::find_large_page_size() {
3224  size_t large_page_size = 0;
3225
3226  // large_page_size on Linux is used to round up heap size. x86 uses either
3227  // 2M or 4M page, depending on whether PAE (Physical Address Extensions)
3228  // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use
3229  // page as large as 256M.
3230  //
3231  // Here we try to figure out page size by parsing /proc/meminfo and looking
3232  // for a line with the following format:
3233  //    Hugepagesize:     2048 kB
3234  //
3235  // If we can't determine the value (e.g. /proc is not mounted, or the text
3236  // format has been changed), we'll use the largest page size supported by
3237  // the processor.
3238
3239#ifndef ZERO
3240  large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M)
3241                     ARM32_ONLY(2 * M) PPC_ONLY(4 * M) AARCH64_ONLY(2 * M);
3242#endif // ZERO
3243
3244  FILE *fp = fopen("/proc/meminfo", "r");
3245  if (fp) {
3246    while (!feof(fp)) {
3247      int x = 0;
3248      char buf[16];
3249      if (fscanf(fp, "Hugepagesize: %d", &x) == 1) {
3250        if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) {
3251          large_page_size = x * K;
3252          break;
3253        }
3254      } else {
3255        // skip to next line
3256        for (;;) {
3257          int ch = fgetc(fp);
3258          if (ch == EOF || ch == (int)'\n') break;
3259        }
3260      }
3261    }
3262    fclose(fp);
3263  }
3264
3265  if (!FLAG_IS_DEFAULT(LargePageSizeInBytes) && LargePageSizeInBytes != large_page_size) {
3266    warning("Setting LargePageSizeInBytes has no effect on this OS. Large page size is "
3267            SIZE_FORMAT "%s.", byte_size_in_proper_unit(large_page_size),
3268            proper_unit_for_byte_size(large_page_size));
3269  }
3270
3271  return large_page_size;
3272}
3273
3274size_t os::Linux::setup_large_page_size() {
3275  _large_page_size = Linux::find_large_page_size();
3276  const size_t default_page_size = (size_t)Linux::page_size();
3277  if (_large_page_size > default_page_size) {
3278    _page_sizes[0] = _large_page_size;
3279    _page_sizes[1] = default_page_size;
3280    _page_sizes[2] = 0;
3281  }
3282
3283  return _large_page_size;
3284}
3285
3286bool os::Linux::setup_large_page_type(size_t page_size) {
3287  if (FLAG_IS_DEFAULT(UseHugeTLBFS) &&
3288      FLAG_IS_DEFAULT(UseSHM) &&
3289      FLAG_IS_DEFAULT(UseTransparentHugePages)) {
3290
3291    // The type of large pages has not been specified by the user.
3292
3293    // Try UseHugeTLBFS and then UseSHM.
3294    UseHugeTLBFS = UseSHM = true;
3295
3296    // Don't try UseTransparentHugePages since there are known
3297    // performance issues with it turned on. This might change in the future.
3298    UseTransparentHugePages = false;
3299  }
3300
3301  if (UseTransparentHugePages) {
3302    bool warn_on_failure = !FLAG_IS_DEFAULT(UseTransparentHugePages);
3303    if (transparent_huge_pages_sanity_check(warn_on_failure, page_size)) {
3304      UseHugeTLBFS = false;
3305      UseSHM = false;
3306      return true;
3307    }
3308    UseTransparentHugePages = false;
3309  }
3310
3311  if (UseHugeTLBFS) {
3312    bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS);
3313    if (hugetlbfs_sanity_check(warn_on_failure, page_size)) {
3314      UseSHM = false;
3315      return true;
3316    }
3317    UseHugeTLBFS = false;
3318  }
3319
3320  return UseSHM;
3321}
3322
3323void os::large_page_init() {
3324  if (!UseLargePages &&
3325      !UseTransparentHugePages &&
3326      !UseHugeTLBFS &&
3327      !UseSHM) {
3328    // Not using large pages.
3329    return;
3330  }
3331
3332  if (!FLAG_IS_DEFAULT(UseLargePages) && !UseLargePages) {
3333    // The user explicitly turned off large pages.
3334    // Ignore the rest of the large pages flags.
3335    UseTransparentHugePages = false;
3336    UseHugeTLBFS = false;
3337    UseSHM = false;
3338    return;
3339  }
3340
3341  size_t large_page_size = Linux::setup_large_page_size();
3342  UseLargePages          = Linux::setup_large_page_type(large_page_size);
3343
3344  set_coredump_filter();
3345}
3346
3347#ifndef SHM_HUGETLB
3348  #define SHM_HUGETLB 04000
3349#endif
3350
3351char* os::Linux::reserve_memory_special_shm(size_t bytes, size_t alignment,
3352                                            char* req_addr, bool exec) {
3353  // "exec" is passed in but not used.  Creating the shared image for
3354  // the code cache doesn't have an SHM_X executable permission to check.
3355  assert(UseLargePages && UseSHM, "only for SHM large pages");
3356  assert(is_ptr_aligned(req_addr, os::large_page_size()), "Unaligned address");
3357
3358  if (!is_size_aligned(bytes, os::large_page_size()) || alignment > os::large_page_size()) {
3359    return NULL; // Fallback to small pages.
3360  }
3361
3362  key_t key = IPC_PRIVATE;
3363  char *addr;
3364
3365  bool warn_on_failure = UseLargePages &&
3366                        (!FLAG_IS_DEFAULT(UseLargePages) ||
3367                         !FLAG_IS_DEFAULT(UseSHM) ||
3368                         !FLAG_IS_DEFAULT(LargePageSizeInBytes));
3369  char msg[128];
3370
3371  // Create a large shared memory region to attach to based on size.
3372  // Currently, size is the total size of the heap
3373  int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
3374  if (shmid == -1) {
3375    // Possible reasons for shmget failure:
3376    // 1. shmmax is too small for Java heap.
3377    //    > check shmmax value: cat /proc/sys/kernel/shmmax
3378    //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
3379    // 2. not enough large page memory.
3380    //    > check available large pages: cat /proc/meminfo
3381    //    > increase amount of large pages:
3382    //          echo new_value > /proc/sys/vm/nr_hugepages
3383    //      Note 1: different Linux may use different name for this property,
3384    //            e.g. on Redhat AS-3 it is "hugetlb_pool".
3385    //      Note 2: it's possible there's enough physical memory available but
3386    //            they are so fragmented after a long run that they can't
3387    //            coalesce into large pages. Try to reserve large pages when
3388    //            the system is still "fresh".
3389    if (warn_on_failure) {
3390      jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
3391      warning("%s", msg);
3392    }
3393    return NULL;
3394  }
3395
3396  // attach to the region
3397  addr = (char*)shmat(shmid, req_addr, 0);
3398  int err = errno;
3399
3400  // Remove shmid. If shmat() is successful, the actual shared memory segment
3401  // will be deleted when it's detached by shmdt() or when the process
3402  // terminates. If shmat() is not successful this will remove the shared
3403  // segment immediately.
3404  shmctl(shmid, IPC_RMID, NULL);
3405
3406  if ((intptr_t)addr == -1) {
3407    if (warn_on_failure) {
3408      jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
3409      warning("%s", msg);
3410    }
3411    return NULL;
3412  }
3413
3414  return addr;
3415}
3416
3417static void warn_on_large_pages_failure(char* req_addr, size_t bytes,
3418                                        int error) {
3419  assert(error == ENOMEM, "Only expect to fail if no memory is available");
3420
3421  bool warn_on_failure = UseLargePages &&
3422      (!FLAG_IS_DEFAULT(UseLargePages) ||
3423       !FLAG_IS_DEFAULT(UseHugeTLBFS) ||
3424       !FLAG_IS_DEFAULT(LargePageSizeInBytes));
3425
3426  if (warn_on_failure) {
3427    char msg[128];
3428    jio_snprintf(msg, sizeof(msg), "Failed to reserve large pages memory req_addr: "
3429                 PTR_FORMAT " bytes: " SIZE_FORMAT " (errno = %d).", req_addr, bytes, error);
3430    warning("%s", msg);
3431  }
3432}
3433
3434char* os::Linux::reserve_memory_special_huge_tlbfs_only(size_t bytes,
3435                                                        char* req_addr,
3436                                                        bool exec) {
3437  assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages");
3438  assert(is_size_aligned(bytes, os::large_page_size()), "Unaligned size");
3439  assert(is_ptr_aligned(req_addr, os::large_page_size()), "Unaligned address");
3440
3441  int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
3442  char* addr = (char*)::mmap(req_addr, bytes, prot,
3443                             MAP_PRIVATE|MAP_ANONYMOUS|MAP_HUGETLB,
3444                             -1, 0);
3445
3446  if (addr == MAP_FAILED) {
3447    warn_on_large_pages_failure(req_addr, bytes, errno);
3448    return NULL;
3449  }
3450
3451  assert(is_ptr_aligned(addr, os::large_page_size()), "Must be");
3452
3453  return addr;
3454}
3455
3456// Helper for os::Linux::reserve_memory_special_huge_tlbfs_mixed().
3457// Allocate (using mmap, NO_RESERVE, with small pages) at either a given request address
3458//   (req_addr != NULL) or with a given alignment.
3459//  - bytes shall be a multiple of alignment.
3460//  - req_addr can be NULL. If not NULL, it must be a multiple of alignment.
3461//  - alignment sets the alignment at which memory shall be allocated.
3462//     It must be a multiple of allocation granularity.
3463// Returns address of memory or NULL. If req_addr was not NULL, will only return
3464//  req_addr or NULL.
3465static char* anon_mmap_aligned(size_t bytes, size_t alignment, char* req_addr) {
3466
3467  size_t extra_size = bytes;
3468  if (req_addr == NULL && alignment > 0) {
3469    extra_size += alignment;
3470  }
3471
3472  char* start = (char*) ::mmap(req_addr, extra_size, PROT_NONE,
3473    MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
3474    -1, 0);
3475  if (start == MAP_FAILED) {
3476    start = NULL;
3477  } else {
3478    if (req_addr != NULL) {
3479      if (start != req_addr) {
3480        ::munmap(start, extra_size);
3481        start = NULL;
3482      }
3483    } else {
3484      char* const start_aligned = (char*) align_ptr_up(start, alignment);
3485      char* const end_aligned = start_aligned + bytes;
3486      char* const end = start + extra_size;
3487      if (start_aligned > start) {
3488        ::munmap(start, start_aligned - start);
3489      }
3490      if (end_aligned < end) {
3491        ::munmap(end_aligned, end - end_aligned);
3492      }
3493      start = start_aligned;
3494    }
3495  }
3496  return start;
3497
3498}
3499
3500// Reserve memory using mmap(MAP_HUGETLB).
3501//  - bytes shall be a multiple of alignment.
3502//  - req_addr can be NULL. If not NULL, it must be a multiple of alignment.
3503//  - alignment sets the alignment at which memory shall be allocated.
3504//     It must be a multiple of allocation granularity.
3505// Returns address of memory or NULL. If req_addr was not NULL, will only return
3506//  req_addr or NULL.
3507char* os::Linux::reserve_memory_special_huge_tlbfs_mixed(size_t bytes,
3508                                                         size_t alignment,
3509                                                         char* req_addr,
3510                                                         bool exec) {
3511  size_t large_page_size = os::large_page_size();
3512  assert(bytes >= large_page_size, "Shouldn't allocate large pages for small sizes");
3513
3514  assert(is_ptr_aligned(req_addr, alignment), "Must be");
3515  assert(is_size_aligned(bytes, alignment), "Must be");
3516
3517  // First reserve - but not commit - the address range in small pages.
3518  char* const start = anon_mmap_aligned(bytes, alignment, req_addr);
3519
3520  if (start == NULL) {
3521    return NULL;
3522  }
3523
3524  assert(is_ptr_aligned(start, alignment), "Must be");
3525
3526  char* end = start + bytes;
3527
3528  // Find the regions of the allocated chunk that can be promoted to large pages.
3529  char* lp_start = (char*)align_ptr_up(start, large_page_size);
3530  char* lp_end   = (char*)align_ptr_down(end, large_page_size);
3531
3532  size_t lp_bytes = lp_end - lp_start;
3533
3534  assert(is_size_aligned(lp_bytes, large_page_size), "Must be");
3535
3536  if (lp_bytes == 0) {
3537    // The mapped region doesn't even span the start and the end of a large page.
3538    // Fall back to allocate a non-special area.
3539    ::munmap(start, end - start);
3540    return NULL;
3541  }
3542
3543  int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
3544
3545  void* result;
3546
3547  // Commit small-paged leading area.
3548  if (start != lp_start) {
3549    result = ::mmap(start, lp_start - start, prot,
3550                    MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED,
3551                    -1, 0);
3552    if (result == MAP_FAILED) {
3553      ::munmap(lp_start, end - lp_start);
3554      return NULL;
3555    }
3556  }
3557
3558  // Commit large-paged area.
3559  result = ::mmap(lp_start, lp_bytes, prot,
3560                  MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED|MAP_HUGETLB,
3561                  -1, 0);
3562  if (result == MAP_FAILED) {
3563    warn_on_large_pages_failure(lp_start, lp_bytes, errno);
3564    // If the mmap above fails, the large pages region will be unmapped and we
3565    // have regions before and after with small pages. Release these regions.
3566    //
3567    // |  mapped  |  unmapped  |  mapped  |
3568    // ^          ^            ^          ^
3569    // start      lp_start     lp_end     end
3570    //
3571    ::munmap(start, lp_start - start);
3572    ::munmap(lp_end, end - lp_end);
3573    return NULL;
3574  }
3575
3576  // Commit small-paged trailing area.
3577  if (lp_end != end) {
3578    result = ::mmap(lp_end, end - lp_end, prot,
3579                    MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED,
3580                    -1, 0);
3581    if (result == MAP_FAILED) {
3582      ::munmap(start, lp_end - start);
3583      return NULL;
3584    }
3585  }
3586
3587  return start;
3588}
3589
3590char* os::Linux::reserve_memory_special_huge_tlbfs(size_t bytes,
3591                                                   size_t alignment,
3592                                                   char* req_addr,
3593                                                   bool exec) {
3594  assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages");
3595  assert(is_ptr_aligned(req_addr, alignment), "Must be");
3596  assert(is_size_aligned(alignment, os::vm_allocation_granularity()), "Must be");
3597  assert(is_power_of_2(os::large_page_size()), "Must be");
3598  assert(bytes >= os::large_page_size(), "Shouldn't allocate large pages for small sizes");
3599
3600  if (is_size_aligned(bytes, os::large_page_size()) && alignment <= os::large_page_size()) {
3601    return reserve_memory_special_huge_tlbfs_only(bytes, req_addr, exec);
3602  } else {
3603    return reserve_memory_special_huge_tlbfs_mixed(bytes, alignment, req_addr, exec);
3604  }
3605}
3606
3607char* os::reserve_memory_special(size_t bytes, size_t alignment,
3608                                 char* req_addr, bool exec) {
3609  assert(UseLargePages, "only for large pages");
3610
3611  char* addr;
3612  if (UseSHM) {
3613    addr = os::Linux::reserve_memory_special_shm(bytes, alignment, req_addr, exec);
3614  } else {
3615    assert(UseHugeTLBFS, "must be");
3616    addr = os::Linux::reserve_memory_special_huge_tlbfs(bytes, alignment, req_addr, exec);
3617  }
3618
3619  if (addr != NULL) {
3620    if (UseNUMAInterleaving) {
3621      numa_make_global(addr, bytes);
3622    }
3623
3624    // The memory is committed
3625    MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, CALLER_PC);
3626  }
3627
3628  return addr;
3629}
3630
3631bool os::Linux::release_memory_special_shm(char* base, size_t bytes) {
3632  // detaching the SHM segment will also delete it, see reserve_memory_special_shm()
3633  return shmdt(base) == 0;
3634}
3635
3636bool os::Linux::release_memory_special_huge_tlbfs(char* base, size_t bytes) {
3637  return pd_release_memory(base, bytes);
3638}
3639
3640bool os::release_memory_special(char* base, size_t bytes) {
3641  bool res;
3642  if (MemTracker::tracking_level() > NMT_minimal) {
3643    Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
3644    res = os::Linux::release_memory_special_impl(base, bytes);
3645    if (res) {
3646      tkr.record((address)base, bytes);
3647    }
3648
3649  } else {
3650    res = os::Linux::release_memory_special_impl(base, bytes);
3651  }
3652  return res;
3653}
3654
3655bool os::Linux::release_memory_special_impl(char* base, size_t bytes) {
3656  assert(UseLargePages, "only for large pages");
3657  bool res;
3658
3659  if (UseSHM) {
3660    res = os::Linux::release_memory_special_shm(base, bytes);
3661  } else {
3662    assert(UseHugeTLBFS, "must be");
3663    res = os::Linux::release_memory_special_huge_tlbfs(base, bytes);
3664  }
3665  return res;
3666}
3667
3668size_t os::large_page_size() {
3669  return _large_page_size;
3670}
3671
3672// With SysV SHM the entire memory region must be allocated as shared
3673// memory.
3674// HugeTLBFS allows application to commit large page memory on demand.
3675// However, when committing memory with HugeTLBFS fails, the region
3676// that was supposed to be committed will lose the old reservation
3677// and allow other threads to steal that memory region. Because of this
3678// behavior we can't commit HugeTLBFS memory.
3679bool os::can_commit_large_page_memory() {
3680  return UseTransparentHugePages;
3681}
3682
3683bool os::can_execute_large_page_memory() {
3684  return UseTransparentHugePages || UseHugeTLBFS;
3685}
3686
3687// Reserve memory at an arbitrary address, only if that area is
3688// available (and not reserved for something else).
3689
3690char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
3691  const int max_tries = 10;
3692  char* base[max_tries];
3693  size_t size[max_tries];
3694  const size_t gap = 0x000000;
3695
3696  // Assert only that the size is a multiple of the page size, since
3697  // that's all that mmap requires, and since that's all we really know
3698  // about at this low abstraction level.  If we need higher alignment,
3699  // we can either pass an alignment to this method or verify alignment
3700  // in one of the methods further up the call chain.  See bug 5044738.
3701  assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
3702
3703  // Repeatedly allocate blocks until the block is allocated at the
3704  // right spot.
3705
3706  // Linux mmap allows caller to pass an address as hint; give it a try first,
3707  // if kernel honors the hint then we can return immediately.
3708  char * addr = anon_mmap(requested_addr, bytes, false);
3709  if (addr == requested_addr) {
3710    return requested_addr;
3711  }
3712
3713  if (addr != NULL) {
3714    // mmap() is successful but it fails to reserve at the requested address
3715    anon_munmap(addr, bytes);
3716  }
3717
3718  int i;
3719  for (i = 0; i < max_tries; ++i) {
3720    base[i] = reserve_memory(bytes);
3721
3722    if (base[i] != NULL) {
3723      // Is this the block we wanted?
3724      if (base[i] == requested_addr) {
3725        size[i] = bytes;
3726        break;
3727      }
3728
3729      // Does this overlap the block we wanted? Give back the overlapped
3730      // parts and try again.
3731
3732      ptrdiff_t top_overlap = requested_addr + (bytes + gap) - base[i];
3733      if (top_overlap >= 0 && (size_t)top_overlap < bytes) {
3734        unmap_memory(base[i], top_overlap);
3735        base[i] += top_overlap;
3736        size[i] = bytes - top_overlap;
3737      } else {
3738        ptrdiff_t bottom_overlap = base[i] + bytes - requested_addr;
3739        if (bottom_overlap >= 0 && (size_t)bottom_overlap < bytes) {
3740          unmap_memory(requested_addr, bottom_overlap);
3741          size[i] = bytes - bottom_overlap;
3742        } else {
3743          size[i] = bytes;
3744        }
3745      }
3746    }
3747  }
3748
3749  // Give back the unused reserved pieces.
3750
3751  for (int j = 0; j < i; ++j) {
3752    if (base[j] != NULL) {
3753      unmap_memory(base[j], size[j]);
3754    }
3755  }
3756
3757  if (i < max_tries) {
3758    return requested_addr;
3759  } else {
3760    return NULL;
3761  }
3762}
3763
3764size_t os::read(int fd, void *buf, unsigned int nBytes) {
3765  return ::read(fd, buf, nBytes);
3766}
3767
3768size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) {
3769  return ::pread(fd, buf, nBytes, offset);
3770}
3771
3772// Short sleep, direct OS call.
3773//
3774// Note: certain versions of Linux CFS scheduler (since 2.6.23) do not guarantee
3775// sched_yield(2) will actually give up the CPU:
3776//
3777//   * Alone on this pariticular CPU, keeps running.
3778//   * Before the introduction of "skip_buddy" with "compat_yield" disabled
3779//     (pre 2.6.39).
3780//
3781// So calling this with 0 is an alternative.
3782//
3783void os::naked_short_sleep(jlong ms) {
3784  struct timespec req;
3785
3786  assert(ms < 1000, "Un-interruptable sleep, short time use only");
3787  req.tv_sec = 0;
3788  if (ms > 0) {
3789    req.tv_nsec = (ms % 1000) * 1000000;
3790  } else {
3791    req.tv_nsec = 1;
3792  }
3793
3794  nanosleep(&req, NULL);
3795
3796  return;
3797}
3798
3799// Sleep forever; naked call to OS-specific sleep; use with CAUTION
3800void os::infinite_sleep() {
3801  while (true) {    // sleep forever ...
3802    ::sleep(100);   // ... 100 seconds at a time
3803  }
3804}
3805
3806// Used to convert frequent JVM_Yield() to nops
3807bool os::dont_yield() {
3808  return DontYieldALot;
3809}
3810
3811void os::naked_yield() {
3812  sched_yield();
3813}
3814
3815////////////////////////////////////////////////////////////////////////////////
3816// thread priority support
3817
3818// Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER
3819// only supports dynamic priority, static priority must be zero. For real-time
3820// applications, Linux supports SCHED_RR which allows static priority (1-99).
3821// However, for large multi-threaded applications, SCHED_RR is not only slower
3822// than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
3823// of 5 runs - Sep 2005).
3824//
3825// The following code actually changes the niceness of kernel-thread/LWP. It
3826// has an assumption that setpriority() only modifies one kernel-thread/LWP,
3827// not the entire user process, and user level threads are 1:1 mapped to kernel
3828// threads. It has always been the case, but could change in the future. For
3829// this reason, the code should not be used as default (ThreadPriorityPolicy=0).
3830// It is only used when ThreadPriorityPolicy=1 and requires root privilege.
3831
3832int os::java_to_os_priority[CriticalPriority + 1] = {
3833  19,              // 0 Entry should never be used
3834
3835   4,              // 1 MinPriority
3836   3,              // 2
3837   2,              // 3
3838
3839   1,              // 4
3840   0,              // 5 NormPriority
3841  -1,              // 6
3842
3843  -2,              // 7
3844  -3,              // 8
3845  -4,              // 9 NearMaxPriority
3846
3847  -5,              // 10 MaxPriority
3848
3849  -5               // 11 CriticalPriority
3850};
3851
3852static int prio_init() {
3853  if (ThreadPriorityPolicy == 1) {
3854    // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1
3855    // if effective uid is not root. Perhaps, a more elegant way of doing
3856    // this is to test CAP_SYS_NICE capability, but that will require libcap.so
3857    if (geteuid() != 0) {
3858      if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) {
3859        warning("-XX:ThreadPriorityPolicy requires root privilege on Linux");
3860      }
3861      ThreadPriorityPolicy = 0;
3862    }
3863  }
3864  if (UseCriticalJavaThreadPriority) {
3865    os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
3866  }
3867  return 0;
3868}
3869
3870OSReturn os::set_native_priority(Thread* thread, int newpri) {
3871  if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK;
3872
3873  int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
3874  return (ret == 0) ? OS_OK : OS_ERR;
3875}
3876
3877OSReturn os::get_native_priority(const Thread* const thread,
3878                                 int *priority_ptr) {
3879  if (!UseThreadPriorities || ThreadPriorityPolicy == 0) {
3880    *priority_ptr = java_to_os_priority[NormPriority];
3881    return OS_OK;
3882  }
3883
3884  errno = 0;
3885  *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
3886  return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
3887}
3888
3889// Hint to the underlying OS that a task switch would not be good.
3890// Void return because it's a hint and can fail.
3891void os::hint_no_preempt() {}
3892
3893////////////////////////////////////////////////////////////////////////////////
3894// suspend/resume support
3895
3896//  the low-level signal-based suspend/resume support is a remnant from the
3897//  old VM-suspension that used to be for java-suspension, safepoints etc,
3898//  within hotspot. Now there is a single use-case for this:
3899//    - calling get_thread_pc() on the VMThread by the flat-profiler task
3900//      that runs in the watcher thread.
3901//  The remaining code is greatly simplified from the more general suspension
3902//  code that used to be used.
3903//
3904//  The protocol is quite simple:
3905//  - suspend:
3906//      - sends a signal to the target thread
3907//      - polls the suspend state of the osthread using a yield loop
3908//      - target thread signal handler (SR_handler) sets suspend state
3909//        and blocks in sigsuspend until continued
3910//  - resume:
3911//      - sets target osthread state to continue
3912//      - sends signal to end the sigsuspend loop in the SR_handler
3913//
3914//  Note that the SR_lock plays no role in this suspend/resume protocol.
3915
3916static void resume_clear_context(OSThread *osthread) {
3917  osthread->set_ucontext(NULL);
3918  osthread->set_siginfo(NULL);
3919}
3920
3921static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo,
3922                                 ucontext_t* context) {
3923  osthread->set_ucontext(context);
3924  osthread->set_siginfo(siginfo);
3925}
3926
3927// Handler function invoked when a thread's execution is suspended or
3928// resumed. We have to be careful that only async-safe functions are
3929// called here (Note: most pthread functions are not async safe and
3930// should be avoided.)
3931//
3932// Note: sigwait() is a more natural fit than sigsuspend() from an
3933// interface point of view, but sigwait() prevents the signal hander
3934// from being run. libpthread would get very confused by not having
3935// its signal handlers run and prevents sigwait()'s use with the
3936// mutex granting granting signal.
3937//
3938// Currently only ever called on the VMThread and JavaThreads (PC sampling)
3939//
3940static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) {
3941  // Save and restore errno to avoid confusing native code with EINTR
3942  // after sigsuspend.
3943  int old_errno = errno;
3944
3945  Thread* thread = Thread::current();
3946  OSThread* osthread = thread->osthread();
3947  assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
3948
3949  os::SuspendResume::State current = osthread->sr.state();
3950  if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
3951    suspend_save_context(osthread, siginfo, context);
3952
3953    // attempt to switch the state, we assume we had a SUSPEND_REQUEST
3954    os::SuspendResume::State state = osthread->sr.suspended();
3955    if (state == os::SuspendResume::SR_SUSPENDED) {
3956      sigset_t suspend_set;  // signals for sigsuspend()
3957
3958      // get current set of blocked signals and unblock resume signal
3959      pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
3960      sigdelset(&suspend_set, SR_signum);
3961
3962      sr_semaphore.signal();
3963      // wait here until we are resumed
3964      while (1) {
3965        sigsuspend(&suspend_set);
3966
3967        os::SuspendResume::State result = osthread->sr.running();
3968        if (result == os::SuspendResume::SR_RUNNING) {
3969          sr_semaphore.signal();
3970          break;
3971        }
3972      }
3973
3974    } else if (state == os::SuspendResume::SR_RUNNING) {
3975      // request was cancelled, continue
3976    } else {
3977      ShouldNotReachHere();
3978    }
3979
3980    resume_clear_context(osthread);
3981  } else if (current == os::SuspendResume::SR_RUNNING) {
3982    // request was cancelled, continue
3983  } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
3984    // ignore
3985  } else {
3986    // ignore
3987  }
3988
3989  errno = old_errno;
3990}
3991
3992static int SR_initialize() {
3993  struct sigaction act;
3994  char *s;
3995
3996  // Get signal number to use for suspend/resume
3997  if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
3998    int sig = ::strtol(s, 0, 10);
3999    if (sig > MAX2(SIGSEGV, SIGBUS) &&  // See 4355769.
4000        sig < NSIG) {                   // Must be legal signal and fit into sigflags[].
4001      SR_signum = sig;
4002    } else {
4003      warning("You set _JAVA_SR_SIGNUM=%d. It must be in range [%d, %d]. Using %d instead.",
4004              sig, MAX2(SIGSEGV, SIGBUS)+1, NSIG-1, SR_signum);
4005    }
4006  }
4007
4008  assert(SR_signum > SIGSEGV && SR_signum > SIGBUS,
4009         "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769");
4010
4011  sigemptyset(&SR_sigset);
4012  sigaddset(&SR_sigset, SR_signum);
4013
4014  // Set up signal handler for suspend/resume
4015  act.sa_flags = SA_RESTART|SA_SIGINFO;
4016  act.sa_handler = (void (*)(int)) SR_handler;
4017
4018  // SR_signum is blocked by default.
4019  // 4528190 - We also need to block pthread restart signal (32 on all
4020  // supported Linux platforms). Note that LinuxThreads need to block
4021  // this signal for all threads to work properly. So we don't have
4022  // to use hard-coded signal number when setting up the mask.
4023  pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask);
4024
4025  if (sigaction(SR_signum, &act, 0) == -1) {
4026    return -1;
4027  }
4028
4029  // Save signal flag
4030  os::Linux::set_our_sigflags(SR_signum, act.sa_flags);
4031  return 0;
4032}
4033
4034static int sr_notify(OSThread* osthread) {
4035  int status = pthread_kill(osthread->pthread_id(), SR_signum);
4036  assert_status(status == 0, status, "pthread_kill");
4037  return status;
4038}
4039
4040// "Randomly" selected value for how long we want to spin
4041// before bailing out on suspending a thread, also how often
4042// we send a signal to a thread we want to resume
4043static const int RANDOMLY_LARGE_INTEGER = 1000000;
4044static const int RANDOMLY_LARGE_INTEGER2 = 100;
4045
4046// returns true on success and false on error - really an error is fatal
4047// but this seems the normal response to library errors
4048static bool do_suspend(OSThread* osthread) {
4049  assert(osthread->sr.is_running(), "thread should be running");
4050  assert(!sr_semaphore.trywait(), "semaphore has invalid state");
4051
4052  // mark as suspended and send signal
4053  if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
4054    // failed to switch, state wasn't running?
4055    ShouldNotReachHere();
4056    return false;
4057  }
4058
4059  if (sr_notify(osthread) != 0) {
4060    ShouldNotReachHere();
4061  }
4062
4063  // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
4064  while (true) {
4065    if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
4066      break;
4067    } else {
4068      // timeout
4069      os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
4070      if (cancelled == os::SuspendResume::SR_RUNNING) {
4071        return false;
4072      } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
4073        // make sure that we consume the signal on the semaphore as well
4074        sr_semaphore.wait();
4075        break;
4076      } else {
4077        ShouldNotReachHere();
4078        return false;
4079      }
4080    }
4081  }
4082
4083  guarantee(osthread->sr.is_suspended(), "Must be suspended");
4084  return true;
4085}
4086
4087static void do_resume(OSThread* osthread) {
4088  assert(osthread->sr.is_suspended(), "thread should be suspended");
4089  assert(!sr_semaphore.trywait(), "invalid semaphore state");
4090
4091  if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
4092    // failed to switch to WAKEUP_REQUEST
4093    ShouldNotReachHere();
4094    return;
4095  }
4096
4097  while (true) {
4098    if (sr_notify(osthread) == 0) {
4099      if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
4100        if (osthread->sr.is_running()) {
4101          return;
4102        }
4103      }
4104    } else {
4105      ShouldNotReachHere();
4106    }
4107  }
4108
4109  guarantee(osthread->sr.is_running(), "Must be running!");
4110}
4111
4112///////////////////////////////////////////////////////////////////////////////////
4113// signal handling (except suspend/resume)
4114
4115// This routine may be used by user applications as a "hook" to catch signals.
4116// The user-defined signal handler must pass unrecognized signals to this
4117// routine, and if it returns true (non-zero), then the signal handler must
4118// return immediately.  If the flag "abort_if_unrecognized" is true, then this
4119// routine will never retun false (zero), but instead will execute a VM panic
4120// routine kill the process.
4121//
4122// If this routine returns false, it is OK to call it again.  This allows
4123// the user-defined signal handler to perform checks either before or after
4124// the VM performs its own checks.  Naturally, the user code would be making
4125// a serious error if it tried to handle an exception (such as a null check
4126// or breakpoint) that the VM was generating for its own correct operation.
4127//
4128// This routine may recognize any of the following kinds of signals:
4129//    SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1.
4130// It should be consulted by handlers for any of those signals.
4131//
4132// The caller of this routine must pass in the three arguments supplied
4133// to the function referred to in the "sa_sigaction" (not the "sa_handler")
4134// field of the structure passed to sigaction().  This routine assumes that
4135// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
4136//
4137// Note that the VM will print warnings if it detects conflicting signal
4138// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
4139//
4140extern "C" JNIEXPORT int JVM_handle_linux_signal(int signo,
4141                                                 siginfo_t* siginfo,
4142                                                 void* ucontext,
4143                                                 int abort_if_unrecognized);
4144
4145void signalHandler(int sig, siginfo_t* info, void* uc) {
4146  assert(info != NULL && uc != NULL, "it must be old kernel");
4147  int orig_errno = errno;  // Preserve errno value over signal handler.
4148  JVM_handle_linux_signal(sig, info, uc, true);
4149  errno = orig_errno;
4150}
4151
4152
4153// This boolean allows users to forward their own non-matching signals
4154// to JVM_handle_linux_signal, harmlessly.
4155bool os::Linux::signal_handlers_are_installed = false;
4156
4157// For signal-chaining
4158struct sigaction sigact[NSIG];
4159uint64_t sigs = 0;
4160#if (64 < NSIG-1)
4161#error "Not all signals can be encoded in sigs. Adapt its type!"
4162#endif
4163bool os::Linux::libjsig_is_loaded = false;
4164typedef struct sigaction *(*get_signal_t)(int);
4165get_signal_t os::Linux::get_signal_action = NULL;
4166
4167struct sigaction* os::Linux::get_chained_signal_action(int sig) {
4168  struct sigaction *actp = NULL;
4169
4170  if (libjsig_is_loaded) {
4171    // Retrieve the old signal handler from libjsig
4172    actp = (*get_signal_action)(sig);
4173  }
4174  if (actp == NULL) {
4175    // Retrieve the preinstalled signal handler from jvm
4176    actp = get_preinstalled_handler(sig);
4177  }
4178
4179  return actp;
4180}
4181
4182static bool call_chained_handler(struct sigaction *actp, int sig,
4183                                 siginfo_t *siginfo, void *context) {
4184  // Call the old signal handler
4185  if (actp->sa_handler == SIG_DFL) {
4186    // It's more reasonable to let jvm treat it as an unexpected exception
4187    // instead of taking the default action.
4188    return false;
4189  } else if (actp->sa_handler != SIG_IGN) {
4190    if ((actp->sa_flags & SA_NODEFER) == 0) {
4191      // automaticlly block the signal
4192      sigaddset(&(actp->sa_mask), sig);
4193    }
4194
4195    sa_handler_t hand = NULL;
4196    sa_sigaction_t sa = NULL;
4197    bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
4198    // retrieve the chained handler
4199    if (siginfo_flag_set) {
4200      sa = actp->sa_sigaction;
4201    } else {
4202      hand = actp->sa_handler;
4203    }
4204
4205    if ((actp->sa_flags & SA_RESETHAND) != 0) {
4206      actp->sa_handler = SIG_DFL;
4207    }
4208
4209    // try to honor the signal mask
4210    sigset_t oset;
4211    pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
4212
4213    // call into the chained handler
4214    if (siginfo_flag_set) {
4215      (*sa)(sig, siginfo, context);
4216    } else {
4217      (*hand)(sig);
4218    }
4219
4220    // restore the signal mask
4221    pthread_sigmask(SIG_SETMASK, &oset, 0);
4222  }
4223  // Tell jvm's signal handler the signal is taken care of.
4224  return true;
4225}
4226
4227bool os::Linux::chained_handler(int sig, siginfo_t* siginfo, void* context) {
4228  bool chained = false;
4229  // signal-chaining
4230  if (UseSignalChaining) {
4231    struct sigaction *actp = get_chained_signal_action(sig);
4232    if (actp != NULL) {
4233      chained = call_chained_handler(actp, sig, siginfo, context);
4234    }
4235  }
4236  return chained;
4237}
4238
4239struct sigaction* os::Linux::get_preinstalled_handler(int sig) {
4240  if ((((uint64_t)1 << (sig-1)) & sigs) != 0) {
4241    return &sigact[sig];
4242  }
4243  return NULL;
4244}
4245
4246void os::Linux::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
4247  assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
4248  sigact[sig] = oldAct;
4249  sigs |= (uint64_t)1 << (sig-1);
4250}
4251
4252// for diagnostic
4253int sigflags[NSIG];
4254
4255int os::Linux::get_our_sigflags(int sig) {
4256  assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
4257  return sigflags[sig];
4258}
4259
4260void os::Linux::set_our_sigflags(int sig, int flags) {
4261  assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
4262  if (sig > 0 && sig < NSIG) {
4263    sigflags[sig] = flags;
4264  }
4265}
4266
4267void os::Linux::set_signal_handler(int sig, bool set_installed) {
4268  // Check for overwrite.
4269  struct sigaction oldAct;
4270  sigaction(sig, (struct sigaction*)NULL, &oldAct);
4271
4272  void* oldhand = oldAct.sa_sigaction
4273                ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
4274                : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
4275  if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
4276      oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
4277      oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) {
4278    if (AllowUserSignalHandlers || !set_installed) {
4279      // Do not overwrite; user takes responsibility to forward to us.
4280      return;
4281    } else if (UseSignalChaining) {
4282      // save the old handler in jvm
4283      save_preinstalled_handler(sig, oldAct);
4284      // libjsig also interposes the sigaction() call below and saves the
4285      // old sigaction on it own.
4286    } else {
4287      fatal("Encountered unexpected pre-existing sigaction handler "
4288            "%#lx for signal %d.", (long)oldhand, sig);
4289    }
4290  }
4291
4292  struct sigaction sigAct;
4293  sigfillset(&(sigAct.sa_mask));
4294  sigAct.sa_handler = SIG_DFL;
4295  if (!set_installed) {
4296    sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
4297  } else {
4298    sigAct.sa_sigaction = signalHandler;
4299    sigAct.sa_flags = SA_SIGINFO|SA_RESTART;
4300  }
4301  // Save flags, which are set by ours
4302  assert(sig > 0 && sig < NSIG, "vm signal out of expected range");
4303  sigflags[sig] = sigAct.sa_flags;
4304
4305  int ret = sigaction(sig, &sigAct, &oldAct);
4306  assert(ret == 0, "check");
4307
4308  void* oldhand2  = oldAct.sa_sigaction
4309                  ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
4310                  : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
4311  assert(oldhand2 == oldhand, "no concurrent signal handler installation");
4312}
4313
4314// install signal handlers for signals that HotSpot needs to
4315// handle in order to support Java-level exception handling.
4316
4317void os::Linux::install_signal_handlers() {
4318  if (!signal_handlers_are_installed) {
4319    signal_handlers_are_installed = true;
4320
4321    // signal-chaining
4322    typedef void (*signal_setting_t)();
4323    signal_setting_t begin_signal_setting = NULL;
4324    signal_setting_t end_signal_setting = NULL;
4325    begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4326                                          dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
4327    if (begin_signal_setting != NULL) {
4328      end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4329                                          dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
4330      get_signal_action = CAST_TO_FN_PTR(get_signal_t,
4331                                         dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
4332      libjsig_is_loaded = true;
4333      assert(UseSignalChaining, "should enable signal-chaining");
4334    }
4335    if (libjsig_is_loaded) {
4336      // Tell libjsig jvm is setting signal handlers
4337      (*begin_signal_setting)();
4338    }
4339
4340    set_signal_handler(SIGSEGV, true);
4341    set_signal_handler(SIGPIPE, true);
4342    set_signal_handler(SIGBUS, true);
4343    set_signal_handler(SIGILL, true);
4344    set_signal_handler(SIGFPE, true);
4345#if defined(PPC64)
4346    set_signal_handler(SIGTRAP, true);
4347#endif
4348    set_signal_handler(SIGXFSZ, true);
4349
4350    if (libjsig_is_loaded) {
4351      // Tell libjsig jvm finishes setting signal handlers
4352      (*end_signal_setting)();
4353    }
4354
4355    // We don't activate signal checker if libjsig is in place, we trust ourselves
4356    // and if UserSignalHandler is installed all bets are off.
4357    // Log that signal checking is off only if -verbose:jni is specified.
4358    if (CheckJNICalls) {
4359      if (libjsig_is_loaded) {
4360        if (PrintJNIResolving) {
4361          tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
4362        }
4363        check_signals = false;
4364      }
4365      if (AllowUserSignalHandlers) {
4366        if (PrintJNIResolving) {
4367          tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
4368        }
4369        check_signals = false;
4370      }
4371    }
4372  }
4373}
4374
4375// This is the fastest way to get thread cpu time on Linux.
4376// Returns cpu time (user+sys) for any thread, not only for current.
4377// POSIX compliant clocks are implemented in the kernels 2.6.16+.
4378// It might work on 2.6.10+ with a special kernel/glibc patch.
4379// For reference, please, see IEEE Std 1003.1-2004:
4380//   http://www.unix.org/single_unix_specification
4381
4382jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) {
4383  struct timespec tp;
4384  int rc = os::Linux::clock_gettime(clockid, &tp);
4385  assert(rc == 0, "clock_gettime is expected to return 0 code");
4386
4387  return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec;
4388}
4389
4390/////
4391// glibc on Linux platform uses non-documented flag
4392// to indicate, that some special sort of signal
4393// trampoline is used.
4394// We will never set this flag, and we should
4395// ignore this flag in our diagnostic
4396#ifdef SIGNIFICANT_SIGNAL_MASK
4397  #undef SIGNIFICANT_SIGNAL_MASK
4398#endif
4399#define SIGNIFICANT_SIGNAL_MASK (~0x04000000)
4400
4401static const char* get_signal_handler_name(address handler,
4402                                           char* buf, int buflen) {
4403  int offset = 0;
4404  bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
4405  if (found) {
4406    // skip directory names
4407    const char *p1, *p2;
4408    p1 = buf;
4409    size_t len = strlen(os::file_separator());
4410    while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
4411    jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
4412  } else {
4413    jio_snprintf(buf, buflen, PTR_FORMAT, handler);
4414  }
4415  return buf;
4416}
4417
4418static void print_signal_handler(outputStream* st, int sig,
4419                                 char* buf, size_t buflen) {
4420  struct sigaction sa;
4421
4422  sigaction(sig, NULL, &sa);
4423
4424  // See comment for SIGNIFICANT_SIGNAL_MASK define
4425  sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
4426
4427  st->print("%s: ", os::exception_name(sig, buf, buflen));
4428
4429  address handler = (sa.sa_flags & SA_SIGINFO)
4430    ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
4431    : CAST_FROM_FN_PTR(address, sa.sa_handler);
4432
4433  if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
4434    st->print("SIG_DFL");
4435  } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
4436    st->print("SIG_IGN");
4437  } else {
4438    st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
4439  }
4440
4441  st->print(", sa_mask[0]=");
4442  os::Posix::print_signal_set_short(st, &sa.sa_mask);
4443
4444  address rh = VMError::get_resetted_sighandler(sig);
4445  // May be, handler was resetted by VMError?
4446  if (rh != NULL) {
4447    handler = rh;
4448    sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK;
4449  }
4450
4451  st->print(", sa_flags=");
4452  os::Posix::print_sa_flags(st, sa.sa_flags);
4453
4454  // Check: is it our handler?
4455  if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) ||
4456      handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) {
4457    // It is our signal handler
4458    // check for flags, reset system-used one!
4459    if ((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) {
4460      st->print(
4461                ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
4462                os::Linux::get_our_sigflags(sig));
4463    }
4464  }
4465  st->cr();
4466}
4467
4468
4469#define DO_SIGNAL_CHECK(sig)                      \
4470  do {                                            \
4471    if (!sigismember(&check_signal_done, sig)) {  \
4472      os::Linux::check_signal_handler(sig);       \
4473    }                                             \
4474  } while (0)
4475
4476// This method is a periodic task to check for misbehaving JNI applications
4477// under CheckJNI, we can add any periodic checks here
4478
4479void os::run_periodic_checks() {
4480  if (check_signals == false) return;
4481
4482  // SEGV and BUS if overridden could potentially prevent
4483  // generation of hs*.log in the event of a crash, debugging
4484  // such a case can be very challenging, so we absolutely
4485  // check the following for a good measure:
4486  DO_SIGNAL_CHECK(SIGSEGV);
4487  DO_SIGNAL_CHECK(SIGILL);
4488  DO_SIGNAL_CHECK(SIGFPE);
4489  DO_SIGNAL_CHECK(SIGBUS);
4490  DO_SIGNAL_CHECK(SIGPIPE);
4491  DO_SIGNAL_CHECK(SIGXFSZ);
4492#if defined(PPC64)
4493  DO_SIGNAL_CHECK(SIGTRAP);
4494#endif
4495
4496  // ReduceSignalUsage allows the user to override these handlers
4497  // see comments at the very top and jvm_solaris.h
4498  if (!ReduceSignalUsage) {
4499    DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
4500    DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
4501    DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
4502    DO_SIGNAL_CHECK(BREAK_SIGNAL);
4503  }
4504
4505  DO_SIGNAL_CHECK(SR_signum);
4506}
4507
4508typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
4509
4510static os_sigaction_t os_sigaction = NULL;
4511
4512void os::Linux::check_signal_handler(int sig) {
4513  char buf[O_BUFLEN];
4514  address jvmHandler = NULL;
4515
4516
4517  struct sigaction act;
4518  if (os_sigaction == NULL) {
4519    // only trust the default sigaction, in case it has been interposed
4520    os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
4521    if (os_sigaction == NULL) return;
4522  }
4523
4524  os_sigaction(sig, (struct sigaction*)NULL, &act);
4525
4526
4527  act.sa_flags &= SIGNIFICANT_SIGNAL_MASK;
4528
4529  address thisHandler = (act.sa_flags & SA_SIGINFO)
4530    ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
4531    : CAST_FROM_FN_PTR(address, act.sa_handler);
4532
4533
4534  switch (sig) {
4535  case SIGSEGV:
4536  case SIGBUS:
4537  case SIGFPE:
4538  case SIGPIPE:
4539  case SIGILL:
4540  case SIGXFSZ:
4541    jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler);
4542    break;
4543
4544  case SHUTDOWN1_SIGNAL:
4545  case SHUTDOWN2_SIGNAL:
4546  case SHUTDOWN3_SIGNAL:
4547  case BREAK_SIGNAL:
4548    jvmHandler = (address)user_handler();
4549    break;
4550
4551  default:
4552    if (sig == SR_signum) {
4553      jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler);
4554    } else {
4555      return;
4556    }
4557    break;
4558  }
4559
4560  if (thisHandler != jvmHandler) {
4561    tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
4562    tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
4563    tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
4564    // No need to check this sig any longer
4565    sigaddset(&check_signal_done, sig);
4566    // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
4567    if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
4568      tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",
4569                    exception_name(sig, buf, O_BUFLEN));
4570    }
4571  } else if(os::Linux::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Linux::get_our_sigflags(sig)) {
4572    tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
4573    tty->print("expected:" PTR32_FORMAT, os::Linux::get_our_sigflags(sig));
4574    tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
4575    // No need to check this sig any longer
4576    sigaddset(&check_signal_done, sig);
4577  }
4578
4579  // Dump all the signal
4580  if (sigismember(&check_signal_done, sig)) {
4581    print_signal_handlers(tty, buf, O_BUFLEN);
4582  }
4583}
4584
4585extern void report_error(char* file_name, int line_no, char* title,
4586                         char* format, ...);
4587
4588// this is called _before_ the most of global arguments have been parsed
4589void os::init(void) {
4590  char dummy;   // used to get a guess on initial stack address
4591//  first_hrtime = gethrtime();
4592
4593  clock_tics_per_sec = sysconf(_SC_CLK_TCK);
4594
4595  init_random(1234567);
4596
4597  ThreadCritical::initialize();
4598
4599  Linux::set_page_size(sysconf(_SC_PAGESIZE));
4600  if (Linux::page_size() == -1) {
4601    fatal("os_linux.cpp: os::init: sysconf failed (%s)",
4602          strerror(errno));
4603  }
4604  init_page_sizes((size_t) Linux::page_size());
4605
4606  Linux::initialize_system_info();
4607
4608  // main_thread points to the aboriginal thread
4609  Linux::_main_thread = pthread_self();
4610
4611  Linux::clock_init();
4612  initial_time_count = javaTimeNanos();
4613
4614  // pthread_condattr initialization for monotonic clock
4615  int status;
4616  pthread_condattr_t* _condattr = os::Linux::condAttr();
4617  if ((status = pthread_condattr_init(_condattr)) != 0) {
4618    fatal("pthread_condattr_init: %s", strerror(status));
4619  }
4620  // Only set the clock if CLOCK_MONOTONIC is available
4621  if (os::supports_monotonic_clock()) {
4622    if ((status = pthread_condattr_setclock(_condattr, CLOCK_MONOTONIC)) != 0) {
4623      if (status == EINVAL) {
4624        warning("Unable to use monotonic clock with relative timed-waits" \
4625                " - changes to the time-of-day clock may have adverse affects");
4626      } else {
4627        fatal("pthread_condattr_setclock: %s", strerror(status));
4628      }
4629    }
4630  }
4631  // else it defaults to CLOCK_REALTIME
4632
4633  // If the pagesize of the VM is greater than 8K determine the appropriate
4634  // number of initial guard pages.  The user can change this with the
4635  // command line arguments, if needed.
4636  if (vm_page_size() > (int)Linux::vm_default_page_size()) {
4637    StackYellowPages = 1;
4638    StackRedPages = 1;
4639    StackShadowPages = round_to((StackShadowPages*Linux::vm_default_page_size()), vm_page_size()) / vm_page_size();
4640  }
4641
4642  // retrieve entry point for pthread_setname_np
4643  Linux::_pthread_setname_np =
4644    (int(*)(pthread_t, const char*))dlsym(RTLD_DEFAULT, "pthread_setname_np");
4645
4646}
4647
4648// To install functions for atexit system call
4649extern "C" {
4650  static void perfMemory_exit_helper() {
4651    perfMemory_exit();
4652  }
4653}
4654
4655// this is called _after_ the global arguments have been parsed
4656jint os::init_2(void) {
4657  Linux::fast_thread_clock_init();
4658
4659  // Allocate a single page and mark it as readable for safepoint polling
4660  address polling_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
4661  guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page");
4662
4663  os::set_polling_page(polling_page);
4664
4665#ifndef PRODUCT
4666  if (Verbose && PrintMiscellaneous) {
4667    tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n",
4668               (intptr_t)polling_page);
4669  }
4670#endif
4671
4672  if (!UseMembar) {
4673    address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
4674    guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
4675    os::set_memory_serialize_page(mem_serialize_page);
4676
4677#ifndef PRODUCT
4678    if (Verbose && PrintMiscellaneous) {
4679      tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n",
4680                 (intptr_t)mem_serialize_page);
4681    }
4682#endif
4683  }
4684
4685  // initialize suspend/resume support - must do this before signal_sets_init()
4686  if (SR_initialize() != 0) {
4687    perror("SR_initialize failed");
4688    return JNI_ERR;
4689  }
4690
4691  Linux::signal_sets_init();
4692  Linux::install_signal_handlers();
4693
4694  // Check minimum allowable stack size for thread creation and to initialize
4695  // the java system classes, including StackOverflowError - depends on page
4696  // size.  Add a page for compiler2 recursion in main thread.
4697  // Add in 2*BytesPerWord times page size to account for VM stack during
4698  // class initialization depending on 32 or 64 bit VM.
4699  os::Linux::min_stack_allowed = MAX2(os::Linux::min_stack_allowed,
4700                                      (size_t)(StackYellowPages+StackRedPages+StackShadowPages) * Linux::page_size() +
4701                                      (2*BytesPerWord COMPILER2_PRESENT(+1)) * Linux::vm_default_page_size());
4702
4703  size_t threadStackSizeInBytes = ThreadStackSize * K;
4704  if (threadStackSizeInBytes != 0 &&
4705      threadStackSizeInBytes < os::Linux::min_stack_allowed) {
4706    tty->print_cr("\nThe stack size specified is too small, "
4707                  "Specify at least " SIZE_FORMAT "k",
4708                  os::Linux::min_stack_allowed/ K);
4709    return JNI_ERR;
4710  }
4711
4712  // Make the stack size a multiple of the page size so that
4713  // the yellow/red zones can be guarded.
4714  JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
4715                                                vm_page_size()));
4716
4717  Linux::capture_initial_stack(JavaThread::stack_size_at_create());
4718
4719#if defined(IA32)
4720  workaround_expand_exec_shield_cs_limit();
4721#endif
4722
4723  Linux::libpthread_init();
4724  if (PrintMiscellaneous && (Verbose || WizardMode)) {
4725    tty->print_cr("[HotSpot is running with %s, %s]\n",
4726                  Linux::glibc_version(), Linux::libpthread_version());
4727  }
4728
4729  if (UseNUMA) {
4730    if (!Linux::libnuma_init()) {
4731      UseNUMA = false;
4732    } else {
4733      if ((Linux::numa_max_node() < 1)) {
4734        // There's only one node(they start from 0), disable NUMA.
4735        UseNUMA = false;
4736      }
4737    }
4738    // With SHM and HugeTLBFS large pages we cannot uncommit a page, so there's no way
4739    // we can make the adaptive lgrp chunk resizing work. If the user specified
4740    // both UseNUMA and UseLargePages (or UseSHM/UseHugeTLBFS) on the command line - warn and
4741    // disable adaptive resizing.
4742    if (UseNUMA && UseLargePages && !can_commit_large_page_memory()) {
4743      if (FLAG_IS_DEFAULT(UseNUMA)) {
4744        UseNUMA = false;
4745      } else {
4746        if (FLAG_IS_DEFAULT(UseLargePages) &&
4747            FLAG_IS_DEFAULT(UseSHM) &&
4748            FLAG_IS_DEFAULT(UseHugeTLBFS)) {
4749          UseLargePages = false;
4750        } else if (UseAdaptiveSizePolicy || UseAdaptiveNUMAChunkSizing) {
4751          warning("UseNUMA is not fully compatible with SHM/HugeTLBFS large pages, disabling adaptive resizing (-XX:-UseAdaptiveSizePolicy -XX:-UseAdaptiveNUMAChunkSizing)");
4752          UseAdaptiveSizePolicy = false;
4753          UseAdaptiveNUMAChunkSizing = false;
4754        }
4755      }
4756    }
4757    if (!UseNUMA && ForceNUMA) {
4758      UseNUMA = true;
4759    }
4760  }
4761
4762  if (MaxFDLimit) {
4763    // set the number of file descriptors to max. print out error
4764    // if getrlimit/setrlimit fails but continue regardless.
4765    struct rlimit nbr_files;
4766    int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
4767    if (status != 0) {
4768      if (PrintMiscellaneous && (Verbose || WizardMode)) {
4769        perror("os::init_2 getrlimit failed");
4770      }
4771    } else {
4772      nbr_files.rlim_cur = nbr_files.rlim_max;
4773      status = setrlimit(RLIMIT_NOFILE, &nbr_files);
4774      if (status != 0) {
4775        if (PrintMiscellaneous && (Verbose || WizardMode)) {
4776          perror("os::init_2 setrlimit failed");
4777        }
4778      }
4779    }
4780  }
4781
4782  // Initialize lock used to serialize thread creation (see os::create_thread)
4783  Linux::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false));
4784
4785  // at-exit methods are called in the reverse order of their registration.
4786  // atexit functions are called on return from main or as a result of a
4787  // call to exit(3C). There can be only 32 of these functions registered
4788  // and atexit() does not set errno.
4789
4790  if (PerfAllowAtExitRegistration) {
4791    // only register atexit functions if PerfAllowAtExitRegistration is set.
4792    // atexit functions can be delayed until process exit time, which
4793    // can be problematic for embedded VM situations. Embedded VMs should
4794    // call DestroyJavaVM() to assure that VM resources are released.
4795
4796    // note: perfMemory_exit_helper atexit function may be removed in
4797    // the future if the appropriate cleanup code can be added to the
4798    // VM_Exit VMOperation's doit method.
4799    if (atexit(perfMemory_exit_helper) != 0) {
4800      warning("os::init_2 atexit(perfMemory_exit_helper) failed");
4801    }
4802  }
4803
4804  // initialize thread priority policy
4805  prio_init();
4806
4807  return JNI_OK;
4808}
4809
4810// Mark the polling page as unreadable
4811void os::make_polling_page_unreadable(void) {
4812  if (!guard_memory((char*)_polling_page, Linux::page_size())) {
4813    fatal("Could not disable polling page");
4814  }
4815}
4816
4817// Mark the polling page as readable
4818void os::make_polling_page_readable(void) {
4819  if (!linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) {
4820    fatal("Could not enable polling page");
4821  }
4822}
4823
4824int os::active_processor_count() {
4825  // Linux doesn't yet have a (official) notion of processor sets,
4826  // so just return the number of online processors.
4827  int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
4828  assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check");
4829  return online_cpus;
4830}
4831
4832void os::set_native_thread_name(const char *name) {
4833  if (Linux::_pthread_setname_np) {
4834    char buf [16]; // according to glibc manpage, 16 chars incl. '/0'
4835    snprintf(buf, sizeof(buf), "%s", name);
4836    buf[sizeof(buf) - 1] = '\0';
4837    const int rc = Linux::_pthread_setname_np(pthread_self(), buf);
4838    // ERANGE should not happen; all other errors should just be ignored.
4839    assert(rc != ERANGE, "pthread_setname_np failed");
4840  }
4841}
4842
4843bool os::distribute_processes(uint length, uint* distribution) {
4844  // Not yet implemented.
4845  return false;
4846}
4847
4848bool os::bind_to_processor(uint processor_id) {
4849  // Not yet implemented.
4850  return false;
4851}
4852
4853///
4854
4855void os::SuspendedThreadTask::internal_do_task() {
4856  if (do_suspend(_thread->osthread())) {
4857    SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
4858    do_task(context);
4859    do_resume(_thread->osthread());
4860  }
4861}
4862
4863class PcFetcher : public os::SuspendedThreadTask {
4864 public:
4865  PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
4866  ExtendedPC result();
4867 protected:
4868  void do_task(const os::SuspendedThreadTaskContext& context);
4869 private:
4870  ExtendedPC _epc;
4871};
4872
4873ExtendedPC PcFetcher::result() {
4874  guarantee(is_done(), "task is not done yet.");
4875  return _epc;
4876}
4877
4878void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
4879  Thread* thread = context.thread();
4880  OSThread* osthread = thread->osthread();
4881  if (osthread->ucontext() != NULL) {
4882    _epc = os::Linux::ucontext_get_pc((ucontext_t *) context.ucontext());
4883  } else {
4884    // NULL context is unexpected, double-check this is the VMThread
4885    guarantee(thread->is_VM_thread(), "can only be called for VMThread");
4886  }
4887}
4888
4889// Suspends the target using the signal mechanism and then grabs the PC before
4890// resuming the target. Used by the flat-profiler only
4891ExtendedPC os::get_thread_pc(Thread* thread) {
4892  // Make sure that it is called by the watcher for the VMThread
4893  assert(Thread::current()->is_Watcher_thread(), "Must be watcher");
4894  assert(thread->is_VM_thread(), "Can only be called for VMThread");
4895
4896  PcFetcher fetcher(thread);
4897  fetcher.run();
4898  return fetcher.result();
4899}
4900
4901////////////////////////////////////////////////////////////////////////////////
4902// debug support
4903
4904bool os::find(address addr, outputStream* st) {
4905  Dl_info dlinfo;
4906  memset(&dlinfo, 0, sizeof(dlinfo));
4907  if (dladdr(addr, &dlinfo) != 0) {
4908    st->print(PTR_FORMAT ": ", p2i(addr));
4909    if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
4910      st->print("%s+" PTR_FORMAT, dlinfo.dli_sname,
4911                p2i(addr) - p2i(dlinfo.dli_saddr));
4912    } else if (dlinfo.dli_fbase != NULL) {
4913      st->print("<offset " PTR_FORMAT ">", p2i(addr) - p2i(dlinfo.dli_fbase));
4914    } else {
4915      st->print("<absolute address>");
4916    }
4917    if (dlinfo.dli_fname != NULL) {
4918      st->print(" in %s", dlinfo.dli_fname);
4919    }
4920    if (dlinfo.dli_fbase != NULL) {
4921      st->print(" at " PTR_FORMAT, p2i(dlinfo.dli_fbase));
4922    }
4923    st->cr();
4924
4925    if (Verbose) {
4926      // decode some bytes around the PC
4927      address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
4928      address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
4929      address       lowest = (address) dlinfo.dli_sname;
4930      if (!lowest)  lowest = (address) dlinfo.dli_fbase;
4931      if (begin < lowest)  begin = lowest;
4932      Dl_info dlinfo2;
4933      if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
4934          && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
4935        end = (address) dlinfo2.dli_saddr;
4936      }
4937      Disassembler::decode(begin, end, st);
4938    }
4939    return true;
4940  }
4941  return false;
4942}
4943
4944////////////////////////////////////////////////////////////////////////////////
4945// misc
4946
4947// This does not do anything on Linux. This is basically a hook for being
4948// able to use structured exception handling (thread-local exception filters)
4949// on, e.g., Win32.
4950void
4951os::os_exception_wrapper(java_call_t f, JavaValue* value, const methodHandle& method,
4952                         JavaCallArguments* args, Thread* thread) {
4953  f(value, method, args, thread);
4954}
4955
4956void os::print_statistics() {
4957}
4958
4959bool os::message_box(const char* title, const char* message) {
4960  int i;
4961  fdStream err(defaultStream::error_fd());
4962  for (i = 0; i < 78; i++) err.print_raw("=");
4963  err.cr();
4964  err.print_raw_cr(title);
4965  for (i = 0; i < 78; i++) err.print_raw("-");
4966  err.cr();
4967  err.print_raw_cr(message);
4968  for (i = 0; i < 78; i++) err.print_raw("=");
4969  err.cr();
4970
4971  char buf[16];
4972  // Prevent process from exiting upon "read error" without consuming all CPU
4973  while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
4974
4975  return buf[0] == 'y' || buf[0] == 'Y';
4976}
4977
4978int os::stat(const char *path, struct stat *sbuf) {
4979  char pathbuf[MAX_PATH];
4980  if (strlen(path) > MAX_PATH - 1) {
4981    errno = ENAMETOOLONG;
4982    return -1;
4983  }
4984  os::native_path(strcpy(pathbuf, path));
4985  return ::stat(pathbuf, sbuf);
4986}
4987
4988bool os::check_heap(bool force) {
4989  return true;
4990}
4991
4992// Is a (classpath) directory empty?
4993bool os::dir_is_empty(const char* path) {
4994  DIR *dir = NULL;
4995  struct dirent *ptr;
4996
4997  dir = opendir(path);
4998  if (dir == NULL) return true;
4999
5000  // Scan the directory
5001  bool result = true;
5002  char buf[sizeof(struct dirent) + MAX_PATH];
5003  while (result && (ptr = ::readdir(dir)) != NULL) {
5004    if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
5005      result = false;
5006    }
5007  }
5008  closedir(dir);
5009  return result;
5010}
5011
5012// This code originates from JDK's sysOpen and open64_w
5013// from src/solaris/hpi/src/system_md.c
5014
5015int os::open(const char *path, int oflag, int mode) {
5016  if (strlen(path) > MAX_PATH - 1) {
5017    errno = ENAMETOOLONG;
5018    return -1;
5019  }
5020
5021  // All file descriptors that are opened in the Java process and not
5022  // specifically destined for a subprocess should have the close-on-exec
5023  // flag set.  If we don't set it, then careless 3rd party native code
5024  // might fork and exec without closing all appropriate file descriptors
5025  // (e.g. as we do in closeDescriptors in UNIXProcess.c), and this in
5026  // turn might:
5027  //
5028  // - cause end-of-file to fail to be detected on some file
5029  //   descriptors, resulting in mysterious hangs, or
5030  //
5031  // - might cause an fopen in the subprocess to fail on a system
5032  //   suffering from bug 1085341.
5033  //
5034  // (Yes, the default setting of the close-on-exec flag is a Unix
5035  // design flaw)
5036  //
5037  // See:
5038  // 1085341: 32-bit stdio routines should support file descriptors >255
5039  // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
5040  // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
5041  //
5042  // Modern Linux kernels (after 2.6.23 2007) support O_CLOEXEC with open().
5043  // O_CLOEXEC is preferable to using FD_CLOEXEC on an open file descriptor
5044  // because it saves a system call and removes a small window where the flag
5045  // is unset.  On ancient Linux kernels the O_CLOEXEC flag will be ignored
5046  // and we fall back to using FD_CLOEXEC (see below).
5047#ifdef O_CLOEXEC
5048  oflag |= O_CLOEXEC;
5049#endif
5050
5051  int fd = ::open64(path, oflag, mode);
5052  if (fd == -1) return -1;
5053
5054  //If the open succeeded, the file might still be a directory
5055  {
5056    struct stat64 buf64;
5057    int ret = ::fstat64(fd, &buf64);
5058    int st_mode = buf64.st_mode;
5059
5060    if (ret != -1) {
5061      if ((st_mode & S_IFMT) == S_IFDIR) {
5062        errno = EISDIR;
5063        ::close(fd);
5064        return -1;
5065      }
5066    } else {
5067      ::close(fd);
5068      return -1;
5069    }
5070  }
5071
5072#ifdef FD_CLOEXEC
5073  // Validate that the use of the O_CLOEXEC flag on open above worked.
5074  // With recent kernels, we will perform this check exactly once.
5075  static sig_atomic_t O_CLOEXEC_is_known_to_work = 0;
5076  if (!O_CLOEXEC_is_known_to_work) {
5077    int flags = ::fcntl(fd, F_GETFD);
5078    if (flags != -1) {
5079      if ((flags & FD_CLOEXEC) != 0)
5080        O_CLOEXEC_is_known_to_work = 1;
5081      else
5082        ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
5083    }
5084  }
5085#endif
5086
5087  return fd;
5088}
5089
5090
5091// create binary file, rewriting existing file if required
5092int os::create_binary_file(const char* path, bool rewrite_existing) {
5093  int oflags = O_WRONLY | O_CREAT;
5094  if (!rewrite_existing) {
5095    oflags |= O_EXCL;
5096  }
5097  return ::open64(path, oflags, S_IREAD | S_IWRITE);
5098}
5099
5100// return current position of file pointer
5101jlong os::current_file_offset(int fd) {
5102  return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
5103}
5104
5105// move file pointer to the specified offset
5106jlong os::seek_to_file_offset(int fd, jlong offset) {
5107  return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
5108}
5109
5110// This code originates from JDK's sysAvailable
5111// from src/solaris/hpi/src/native_threads/src/sys_api_td.c
5112
5113int os::available(int fd, jlong *bytes) {
5114  jlong cur, end;
5115  int mode;
5116  struct stat64 buf64;
5117
5118  if (::fstat64(fd, &buf64) >= 0) {
5119    mode = buf64.st_mode;
5120    if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
5121      int n;
5122      if (::ioctl(fd, FIONREAD, &n) >= 0) {
5123        *bytes = n;
5124        return 1;
5125      }
5126    }
5127  }
5128  if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
5129    return 0;
5130  } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
5131    return 0;
5132  } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
5133    return 0;
5134  }
5135  *bytes = end - cur;
5136  return 1;
5137}
5138
5139// Map a block of memory.
5140char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
5141                        char *addr, size_t bytes, bool read_only,
5142                        bool allow_exec) {
5143  int prot;
5144  int flags = MAP_PRIVATE;
5145
5146  if (read_only) {
5147    prot = PROT_READ;
5148  } else {
5149    prot = PROT_READ | PROT_WRITE;
5150  }
5151
5152  if (allow_exec) {
5153    prot |= PROT_EXEC;
5154  }
5155
5156  if (addr != NULL) {
5157    flags |= MAP_FIXED;
5158  }
5159
5160  char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
5161                                     fd, file_offset);
5162  if (mapped_address == MAP_FAILED) {
5163    return NULL;
5164  }
5165  return mapped_address;
5166}
5167
5168
5169// Remap a block of memory.
5170char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
5171                          char *addr, size_t bytes, bool read_only,
5172                          bool allow_exec) {
5173  // same as map_memory() on this OS
5174  return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
5175                        allow_exec);
5176}
5177
5178
5179// Unmap a block of memory.
5180bool os::pd_unmap_memory(char* addr, size_t bytes) {
5181  return munmap(addr, bytes) == 0;
5182}
5183
5184static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time);
5185
5186static clockid_t thread_cpu_clockid(Thread* thread) {
5187  pthread_t tid = thread->osthread()->pthread_id();
5188  clockid_t clockid;
5189
5190  // Get thread clockid
5191  int rc = os::Linux::pthread_getcpuclockid(tid, &clockid);
5192  assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code");
5193  return clockid;
5194}
5195
5196// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
5197// are used by JVM M&M and JVMTI to get user+sys or user CPU time
5198// of a thread.
5199//
5200// current_thread_cpu_time() and thread_cpu_time(Thread*) returns
5201// the fast estimate available on the platform.
5202
5203jlong os::current_thread_cpu_time() {
5204  if (os::Linux::supports_fast_thread_cpu_time()) {
5205    return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5206  } else {
5207    // return user + sys since the cost is the same
5208    return slow_thread_cpu_time(Thread::current(), true /* user + sys */);
5209  }
5210}
5211
5212jlong os::thread_cpu_time(Thread* thread) {
5213  // consistent with what current_thread_cpu_time() returns
5214  if (os::Linux::supports_fast_thread_cpu_time()) {
5215    return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
5216  } else {
5217    return slow_thread_cpu_time(thread, true /* user + sys */);
5218  }
5219}
5220
5221jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
5222  if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5223    return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5224  } else {
5225    return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time);
5226  }
5227}
5228
5229jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5230  if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5231    return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread));
5232  } else {
5233    return slow_thread_cpu_time(thread, user_sys_cpu_time);
5234  }
5235}
5236
5237//  -1 on error.
5238static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5239  pid_t  tid = thread->osthread()->thread_id();
5240  char *s;
5241  char stat[2048];
5242  int statlen;
5243  char proc_name[64];
5244  int count;
5245  long sys_time, user_time;
5246  char cdummy;
5247  int idummy;
5248  long ldummy;
5249  FILE *fp;
5250
5251  snprintf(proc_name, 64, "/proc/self/task/%d/stat", tid);
5252  fp = fopen(proc_name, "r");
5253  if (fp == NULL) return -1;
5254  statlen = fread(stat, 1, 2047, fp);
5255  stat[statlen] = '\0';
5256  fclose(fp);
5257
5258  // Skip pid and the command string. Note that we could be dealing with
5259  // weird command names, e.g. user could decide to rename java launcher
5260  // to "java 1.4.2 :)", then the stat file would look like
5261  //                1234 (java 1.4.2 :)) R ... ...
5262  // We don't really need to know the command string, just find the last
5263  // occurrence of ")" and then start parsing from there. See bug 4726580.
5264  s = strrchr(stat, ')');
5265  if (s == NULL) return -1;
5266
5267  // Skip blank chars
5268  do { s++; } while (s && isspace(*s));
5269
5270  count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu",
5271                 &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy,
5272                 &ldummy, &ldummy, &ldummy, &ldummy, &ldummy,
5273                 &user_time, &sys_time);
5274  if (count != 13) return -1;
5275  if (user_sys_cpu_time) {
5276    return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
5277  } else {
5278    return (jlong)user_time * (1000000000 / clock_tics_per_sec);
5279  }
5280}
5281
5282void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5283  info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5284  info_ptr->may_skip_backward = false;     // elapsed time not wall time
5285  info_ptr->may_skip_forward = false;      // elapsed time not wall time
5286  info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5287}
5288
5289void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5290  info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5291  info_ptr->may_skip_backward = false;     // elapsed time not wall time
5292  info_ptr->may_skip_forward = false;      // elapsed time not wall time
5293  info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5294}
5295
5296bool os::is_thread_cpu_time_supported() {
5297  return true;
5298}
5299
5300// System loadavg support.  Returns -1 if load average cannot be obtained.
5301// Linux doesn't yet have a (official) notion of processor sets,
5302// so just return the system wide load average.
5303int os::loadavg(double loadavg[], int nelem) {
5304  return ::getloadavg(loadavg, nelem);
5305}
5306
5307void os::pause() {
5308  char filename[MAX_PATH];
5309  if (PauseAtStartupFile && PauseAtStartupFile[0]) {
5310    jio_snprintf(filename, MAX_PATH, "%s", PauseAtStartupFile);
5311  } else {
5312    jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
5313  }
5314
5315  int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
5316  if (fd != -1) {
5317    struct stat buf;
5318    ::close(fd);
5319    while (::stat(filename, &buf) == 0) {
5320      (void)::poll(NULL, 0, 100);
5321    }
5322  } else {
5323    jio_fprintf(stderr,
5324                "Could not open pause file '%s', continuing immediately.\n", filename);
5325  }
5326}
5327
5328
5329// Refer to the comments in os_solaris.cpp park-unpark. The next two
5330// comment paragraphs are worth repeating here:
5331//
5332// Assumption:
5333//    Only one parker can exist on an event, which is why we allocate
5334//    them per-thread. Multiple unparkers can coexist.
5335//
5336// _Event serves as a restricted-range semaphore.
5337//   -1 : thread is blocked, i.e. there is a waiter
5338//    0 : neutral: thread is running or ready,
5339//        could have been signaled after a wait started
5340//    1 : signaled - thread is running or ready
5341//
5342// Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can
5343// hang indefinitely.  For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable.
5344// For specifics regarding the bug see GLIBC BUGID 261237 :
5345//    http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html.
5346// Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future
5347// will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar
5348// is used.  (The simple C test-case provided in the GLIBC bug report manifests the
5349// hang).  The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos()
5350// and monitorenter when we're using 1-0 locking.  All those operations may result in
5351// calls to pthread_cond_timedwait().  Using LD_ASSUME_KERNEL to use an older version
5352// of libpthread avoids the problem, but isn't practical.
5353//
5354// Possible remedies:
5355//
5356// 1.   Establish a minimum relative wait time.  50 to 100 msecs seems to work.
5357//      This is palliative and probabilistic, however.  If the thread is preempted
5358//      between the call to compute_abstime() and pthread_cond_timedwait(), more
5359//      than the minimum period may have passed, and the abstime may be stale (in the
5360//      past) resultin in a hang.   Using this technique reduces the odds of a hang
5361//      but the JVM is still vulnerable, particularly on heavily loaded systems.
5362//
5363// 2.   Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead
5364//      of the usual flag-condvar-mutex idiom.  The write side of the pipe is set
5365//      NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo)
5366//      reduces to poll()+read().  This works well, but consumes 2 FDs per extant
5367//      thread.
5368//
5369// 3.   Embargo pthread_cond_timedwait() and implement a native "chron" thread
5370//      that manages timeouts.  We'd emulate pthread_cond_timedwait() by enqueuing
5371//      a timeout request to the chron thread and then blocking via pthread_cond_wait().
5372//      This also works well.  In fact it avoids kernel-level scalability impediments
5373//      on certain platforms that don't handle lots of active pthread_cond_timedwait()
5374//      timers in a graceful fashion.
5375//
5376// 4.   When the abstime value is in the past it appears that control returns
5377//      correctly from pthread_cond_timedwait(), but the condvar is left corrupt.
5378//      Subsequent timedwait/wait calls may hang indefinitely.  Given that, we
5379//      can avoid the problem by reinitializing the condvar -- by cond_destroy()
5380//      followed by cond_init() -- after all calls to pthread_cond_timedwait().
5381//      It may be possible to avoid reinitialization by checking the return
5382//      value from pthread_cond_timedwait().  In addition to reinitializing the
5383//      condvar we must establish the invariant that cond_signal() is only called
5384//      within critical sections protected by the adjunct mutex.  This prevents
5385//      cond_signal() from "seeing" a condvar that's in the midst of being
5386//      reinitialized or that is corrupt.  Sadly, this invariant obviates the
5387//      desirable signal-after-unlock optimization that avoids futile context switching.
5388//
5389//      I'm also concerned that some versions of NTPL might allocate an auxilliary
5390//      structure when a condvar is used or initialized.  cond_destroy()  would
5391//      release the helper structure.  Our reinitialize-after-timedwait fix
5392//      put excessive stress on malloc/free and locks protecting the c-heap.
5393//
5394// We currently use (4).  See the WorkAroundNTPLTimedWaitHang flag.
5395// It may be possible to refine (4) by checking the kernel and NTPL verisons
5396// and only enabling the work-around for vulnerable environments.
5397
5398// utility to compute the abstime argument to timedwait:
5399// millis is the relative timeout time
5400// abstime will be the absolute timeout time
5401// TODO: replace compute_abstime() with unpackTime()
5402
5403static struct timespec* compute_abstime(timespec* abstime, jlong millis) {
5404  if (millis < 0)  millis = 0;
5405
5406  jlong seconds = millis / 1000;
5407  millis %= 1000;
5408  if (seconds > 50000000) { // see man cond_timedwait(3T)
5409    seconds = 50000000;
5410  }
5411
5412  if (os::supports_monotonic_clock()) {
5413    struct timespec now;
5414    int status = os::Linux::clock_gettime(CLOCK_MONOTONIC, &now);
5415    assert_status(status == 0, status, "clock_gettime");
5416    abstime->tv_sec = now.tv_sec  + seconds;
5417    long nanos = now.tv_nsec + millis * NANOSECS_PER_MILLISEC;
5418    if (nanos >= NANOSECS_PER_SEC) {
5419      abstime->tv_sec += 1;
5420      nanos -= NANOSECS_PER_SEC;
5421    }
5422    abstime->tv_nsec = nanos;
5423  } else {
5424    struct timeval now;
5425    int status = gettimeofday(&now, NULL);
5426    assert(status == 0, "gettimeofday");
5427    abstime->tv_sec = now.tv_sec  + seconds;
5428    long usec = now.tv_usec + millis * 1000;
5429    if (usec >= 1000000) {
5430      abstime->tv_sec += 1;
5431      usec -= 1000000;
5432    }
5433    abstime->tv_nsec = usec * 1000;
5434  }
5435  return abstime;
5436}
5437
5438void os::PlatformEvent::park() {       // AKA "down()"
5439  // Transitions for _Event:
5440  //   -1 => -1 : illegal
5441  //    1 =>  0 : pass - return immediately
5442  //    0 => -1 : block; then set _Event to 0 before returning
5443
5444  // Invariant: Only the thread associated with the Event/PlatformEvent
5445  // may call park().
5446  // TODO: assert that _Assoc != NULL or _Assoc == Self
5447  assert(_nParked == 0, "invariant");
5448
5449  int v;
5450  for (;;) {
5451    v = _Event;
5452    if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
5453  }
5454  guarantee(v >= 0, "invariant");
5455  if (v == 0) {
5456    // Do this the hard way by blocking ...
5457    int status = pthread_mutex_lock(_mutex);
5458    assert_status(status == 0, status, "mutex_lock");
5459    guarantee(_nParked == 0, "invariant");
5460    ++_nParked;
5461    while (_Event < 0) {
5462      status = pthread_cond_wait(_cond, _mutex);
5463      // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
5464      // Treat this the same as if the wait was interrupted
5465      if (status == ETIME) { status = EINTR; }
5466      assert_status(status == 0 || status == EINTR, status, "cond_wait");
5467    }
5468    --_nParked;
5469
5470    _Event = 0;
5471    status = pthread_mutex_unlock(_mutex);
5472    assert_status(status == 0, status, "mutex_unlock");
5473    // Paranoia to ensure our locked and lock-free paths interact
5474    // correctly with each other.
5475    OrderAccess::fence();
5476  }
5477  guarantee(_Event >= 0, "invariant");
5478}
5479
5480int os::PlatformEvent::park(jlong millis) {
5481  // Transitions for _Event:
5482  //   -1 => -1 : illegal
5483  //    1 =>  0 : pass - return immediately
5484  //    0 => -1 : block; then set _Event to 0 before returning
5485
5486  guarantee(_nParked == 0, "invariant");
5487
5488  int v;
5489  for (;;) {
5490    v = _Event;
5491    if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
5492  }
5493  guarantee(v >= 0, "invariant");
5494  if (v != 0) return OS_OK;
5495
5496  // We do this the hard way, by blocking the thread.
5497  // Consider enforcing a minimum timeout value.
5498  struct timespec abst;
5499  compute_abstime(&abst, millis);
5500
5501  int ret = OS_TIMEOUT;
5502  int status = pthread_mutex_lock(_mutex);
5503  assert_status(status == 0, status, "mutex_lock");
5504  guarantee(_nParked == 0, "invariant");
5505  ++_nParked;
5506
5507  // Object.wait(timo) will return because of
5508  // (a) notification
5509  // (b) timeout
5510  // (c) thread.interrupt
5511  //
5512  // Thread.interrupt and object.notify{All} both call Event::set.
5513  // That is, we treat thread.interrupt as a special case of notification.
5514  // We ignore spurious OS wakeups unless FilterSpuriousWakeups is false.
5515  // We assume all ETIME returns are valid.
5516  //
5517  // TODO: properly differentiate simultaneous notify+interrupt.
5518  // In that case, we should propagate the notify to another waiter.
5519
5520  while (_Event < 0) {
5521    status = pthread_cond_timedwait(_cond, _mutex, &abst);
5522    if (status != 0 && WorkAroundNPTLTimedWaitHang) {
5523      pthread_cond_destroy(_cond);
5524      pthread_cond_init(_cond, os::Linux::condAttr());
5525    }
5526    assert_status(status == 0 || status == EINTR ||
5527                  status == ETIME || status == ETIMEDOUT,
5528                  status, "cond_timedwait");
5529    if (!FilterSpuriousWakeups) break;                 // previous semantics
5530    if (status == ETIME || status == ETIMEDOUT) break;
5531    // We consume and ignore EINTR and spurious wakeups.
5532  }
5533  --_nParked;
5534  if (_Event >= 0) {
5535    ret = OS_OK;
5536  }
5537  _Event = 0;
5538  status = pthread_mutex_unlock(_mutex);
5539  assert_status(status == 0, status, "mutex_unlock");
5540  assert(_nParked == 0, "invariant");
5541  // Paranoia to ensure our locked and lock-free paths interact
5542  // correctly with each other.
5543  OrderAccess::fence();
5544  return ret;
5545}
5546
5547void os::PlatformEvent::unpark() {
5548  // Transitions for _Event:
5549  //    0 => 1 : just return
5550  //    1 => 1 : just return
5551  //   -1 => either 0 or 1; must signal target thread
5552  //         That is, we can safely transition _Event from -1 to either
5553  //         0 or 1.
5554  // See also: "Semaphores in Plan 9" by Mullender & Cox
5555  //
5556  // Note: Forcing a transition from "-1" to "1" on an unpark() means
5557  // that it will take two back-to-back park() calls for the owning
5558  // thread to block. This has the benefit of forcing a spurious return
5559  // from the first park() call after an unpark() call which will help
5560  // shake out uses of park() and unpark() without condition variables.
5561
5562  if (Atomic::xchg(1, &_Event) >= 0) return;
5563
5564  // Wait for the thread associated with the event to vacate
5565  int status = pthread_mutex_lock(_mutex);
5566  assert_status(status == 0, status, "mutex_lock");
5567  int AnyWaiters = _nParked;
5568  assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
5569  if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
5570    AnyWaiters = 0;
5571    pthread_cond_signal(_cond);
5572  }
5573  status = pthread_mutex_unlock(_mutex);
5574  assert_status(status == 0, status, "mutex_unlock");
5575  if (AnyWaiters != 0) {
5576    // Note that we signal() *after* dropping the lock for "immortal" Events.
5577    // This is safe and avoids a common class of  futile wakeups.  In rare
5578    // circumstances this can cause a thread to return prematurely from
5579    // cond_{timed}wait() but the spurious wakeup is benign and the victim
5580    // will simply re-test the condition and re-park itself.
5581    // This provides particular benefit if the underlying platform does not
5582    // provide wait morphing.
5583    status = pthread_cond_signal(_cond);
5584    assert_status(status == 0, status, "cond_signal");
5585  }
5586}
5587
5588
5589// JSR166
5590// -------------------------------------------------------
5591
5592// The solaris and linux implementations of park/unpark are fairly
5593// conservative for now, but can be improved. They currently use a
5594// mutex/condvar pair, plus a a count.
5595// Park decrements count if > 0, else does a condvar wait.  Unpark
5596// sets count to 1 and signals condvar.  Only one thread ever waits
5597// on the condvar. Contention seen when trying to park implies that someone
5598// is unparking you, so don't wait. And spurious returns are fine, so there
5599// is no need to track notifications.
5600
5601// This code is common to linux and solaris and will be moved to a
5602// common place in dolphin.
5603//
5604// The passed in time value is either a relative time in nanoseconds
5605// or an absolute time in milliseconds. Either way it has to be unpacked
5606// into suitable seconds and nanoseconds components and stored in the
5607// given timespec structure.
5608// Given time is a 64-bit value and the time_t used in the timespec is only
5609// a signed-32-bit value (except on 64-bit Linux) we have to watch for
5610// overflow if times way in the future are given. Further on Solaris versions
5611// prior to 10 there is a restriction (see cond_timedwait) that the specified
5612// number of seconds, in abstime, is less than current_time  + 100,000,000.
5613// As it will be 28 years before "now + 100000000" will overflow we can
5614// ignore overflow and just impose a hard-limit on seconds using the value
5615// of "now + 100,000,000". This places a limit on the timeout of about 3.17
5616// years from "now".
5617
5618static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
5619  assert(time > 0, "convertTime");
5620  time_t max_secs = 0;
5621
5622  if (!os::supports_monotonic_clock() || isAbsolute) {
5623    struct timeval now;
5624    int status = gettimeofday(&now, NULL);
5625    assert(status == 0, "gettimeofday");
5626
5627    max_secs = now.tv_sec + MAX_SECS;
5628
5629    if (isAbsolute) {
5630      jlong secs = time / 1000;
5631      if (secs > max_secs) {
5632        absTime->tv_sec = max_secs;
5633      } else {
5634        absTime->tv_sec = secs;
5635      }
5636      absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
5637    } else {
5638      jlong secs = time / NANOSECS_PER_SEC;
5639      if (secs >= MAX_SECS) {
5640        absTime->tv_sec = max_secs;
5641        absTime->tv_nsec = 0;
5642      } else {
5643        absTime->tv_sec = now.tv_sec + secs;
5644        absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
5645        if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
5646          absTime->tv_nsec -= NANOSECS_PER_SEC;
5647          ++absTime->tv_sec; // note: this must be <= max_secs
5648        }
5649      }
5650    }
5651  } else {
5652    // must be relative using monotonic clock
5653    struct timespec now;
5654    int status = os::Linux::clock_gettime(CLOCK_MONOTONIC, &now);
5655    assert_status(status == 0, status, "clock_gettime");
5656    max_secs = now.tv_sec + MAX_SECS;
5657    jlong secs = time / NANOSECS_PER_SEC;
5658    if (secs >= MAX_SECS) {
5659      absTime->tv_sec = max_secs;
5660      absTime->tv_nsec = 0;
5661    } else {
5662      absTime->tv_sec = now.tv_sec + secs;
5663      absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_nsec;
5664      if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
5665        absTime->tv_nsec -= NANOSECS_PER_SEC;
5666        ++absTime->tv_sec; // note: this must be <= max_secs
5667      }
5668    }
5669  }
5670  assert(absTime->tv_sec >= 0, "tv_sec < 0");
5671  assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
5672  assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
5673  assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
5674}
5675
5676void Parker::park(bool isAbsolute, jlong time) {
5677  // Ideally we'd do something useful while spinning, such
5678  // as calling unpackTime().
5679
5680  // Optional fast-path check:
5681  // Return immediately if a permit is available.
5682  // We depend on Atomic::xchg() having full barrier semantics
5683  // since we are doing a lock-free update to _counter.
5684  if (Atomic::xchg(0, &_counter) > 0) return;
5685
5686  Thread* thread = Thread::current();
5687  assert(thread->is_Java_thread(), "Must be JavaThread");
5688  JavaThread *jt = (JavaThread *)thread;
5689
5690  // Optional optimization -- avoid state transitions if there's an interrupt pending.
5691  // Check interrupt before trying to wait
5692  if (Thread::is_interrupted(thread, false)) {
5693    return;
5694  }
5695
5696  // Next, demultiplex/decode time arguments
5697  timespec absTime;
5698  if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all
5699    return;
5700  }
5701  if (time > 0) {
5702    unpackTime(&absTime, isAbsolute, time);
5703  }
5704
5705
5706  // Enter safepoint region
5707  // Beware of deadlocks such as 6317397.
5708  // The per-thread Parker:: mutex is a classic leaf-lock.
5709  // In particular a thread must never block on the Threads_lock while
5710  // holding the Parker:: mutex.  If safepoints are pending both the
5711  // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
5712  ThreadBlockInVM tbivm(jt);
5713
5714  // Don't wait if cannot get lock since interference arises from
5715  // unblocking.  Also. check interrupt before trying wait
5716  if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) {
5717    return;
5718  }
5719
5720  int status;
5721  if (_counter > 0)  { // no wait needed
5722    _counter = 0;
5723    status = pthread_mutex_unlock(_mutex);
5724    assert(status == 0, "invariant");
5725    // Paranoia to ensure our locked and lock-free paths interact
5726    // correctly with each other and Java-level accesses.
5727    OrderAccess::fence();
5728    return;
5729  }
5730
5731#ifdef ASSERT
5732  // Don't catch signals while blocked; let the running threads have the signals.
5733  // (This allows a debugger to break into the running thread.)
5734  sigset_t oldsigs;
5735  sigset_t* allowdebug_blocked = os::Linux::allowdebug_blocked_signals();
5736  pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
5737#endif
5738
5739  OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
5740  jt->set_suspend_equivalent();
5741  // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
5742
5743  assert(_cur_index == -1, "invariant");
5744  if (time == 0) {
5745    _cur_index = REL_INDEX; // arbitrary choice when not timed
5746    status = pthread_cond_wait(&_cond[_cur_index], _mutex);
5747  } else {
5748    _cur_index = isAbsolute ? ABS_INDEX : REL_INDEX;
5749    status = pthread_cond_timedwait(&_cond[_cur_index], _mutex, &absTime);
5750    if (status != 0 && WorkAroundNPTLTimedWaitHang) {
5751      pthread_cond_destroy(&_cond[_cur_index]);
5752      pthread_cond_init(&_cond[_cur_index], isAbsolute ? NULL : os::Linux::condAttr());
5753    }
5754  }
5755  _cur_index = -1;
5756  assert_status(status == 0 || status == EINTR ||
5757                status == ETIME || status == ETIMEDOUT,
5758                status, "cond_timedwait");
5759
5760#ifdef ASSERT
5761  pthread_sigmask(SIG_SETMASK, &oldsigs, NULL);
5762#endif
5763
5764  _counter = 0;
5765  status = pthread_mutex_unlock(_mutex);
5766  assert_status(status == 0, status, "invariant");
5767  // Paranoia to ensure our locked and lock-free paths interact
5768  // correctly with each other and Java-level accesses.
5769  OrderAccess::fence();
5770
5771  // If externally suspended while waiting, re-suspend
5772  if (jt->handle_special_suspend_equivalent_condition()) {
5773    jt->java_suspend_self();
5774  }
5775}
5776
5777void Parker::unpark() {
5778  int status = pthread_mutex_lock(_mutex);
5779  assert(status == 0, "invariant");
5780  const int s = _counter;
5781  _counter = 1;
5782  if (s < 1) {
5783    // thread might be parked
5784    if (_cur_index != -1) {
5785      // thread is definitely parked
5786      if (WorkAroundNPTLTimedWaitHang) {
5787        status = pthread_cond_signal(&_cond[_cur_index]);
5788        assert(status == 0, "invariant");
5789        status = pthread_mutex_unlock(_mutex);
5790        assert(status == 0, "invariant");
5791      } else {
5792        // must capture correct index before unlocking
5793        int index = _cur_index;
5794        status = pthread_mutex_unlock(_mutex);
5795        assert(status == 0, "invariant");
5796        status = pthread_cond_signal(&_cond[index]);
5797        assert(status == 0, "invariant");
5798      }
5799    } else {
5800      pthread_mutex_unlock(_mutex);
5801      assert(status == 0, "invariant");
5802    }
5803  } else {
5804    pthread_mutex_unlock(_mutex);
5805    assert(status == 0, "invariant");
5806  }
5807}
5808
5809
5810extern char** environ;
5811
5812// Run the specified command in a separate process. Return its exit value,
5813// or -1 on failure (e.g. can't fork a new process).
5814// Unlike system(), this function can be called from signal handler. It
5815// doesn't block SIGINT et al.
5816int os::fork_and_exec(char* cmd) {
5817  const char * argv[4] = {"sh", "-c", cmd, NULL};
5818
5819  pid_t pid = fork();
5820
5821  if (pid < 0) {
5822    // fork failed
5823    return -1;
5824
5825  } else if (pid == 0) {
5826    // child process
5827
5828    execve("/bin/sh", (char* const*)argv, environ);
5829
5830    // execve failed
5831    _exit(-1);
5832
5833  } else  {
5834    // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
5835    // care about the actual exit code, for now.
5836
5837    int status;
5838
5839    // Wait for the child process to exit.  This returns immediately if
5840    // the child has already exited. */
5841    while (waitpid(pid, &status, 0) < 0) {
5842      switch (errno) {
5843      case ECHILD: return 0;
5844      case EINTR: break;
5845      default: return -1;
5846      }
5847    }
5848
5849    if (WIFEXITED(status)) {
5850      // The child exited normally; get its exit code.
5851      return WEXITSTATUS(status);
5852    } else if (WIFSIGNALED(status)) {
5853      // The child exited because of a signal
5854      // The best value to return is 0x80 + signal number,
5855      // because that is what all Unix shells do, and because
5856      // it allows callers to distinguish between process exit and
5857      // process death by signal.
5858      return 0x80 + WTERMSIG(status);
5859    } else {
5860      // Unknown exit code; pass it through
5861      return status;
5862    }
5863  }
5864}
5865
5866// is_headless_jre()
5867//
5868// Test for the existence of xawt/libmawt.so or libawt_xawt.so
5869// in order to report if we are running in a headless jre
5870//
5871// Since JDK8 xawt/libmawt.so was moved into the same directory
5872// as libawt.so, and renamed libawt_xawt.so
5873//
5874bool os::is_headless_jre() {
5875  struct stat statbuf;
5876  char buf[MAXPATHLEN];
5877  char libmawtpath[MAXPATHLEN];
5878  const char *xawtstr  = "/xawt/libmawt.so";
5879  const char *new_xawtstr = "/libawt_xawt.so";
5880  char *p;
5881
5882  // Get path to libjvm.so
5883  os::jvm_path(buf, sizeof(buf));
5884
5885  // Get rid of libjvm.so
5886  p = strrchr(buf, '/');
5887  if (p == NULL) {
5888    return false;
5889  } else {
5890    *p = '\0';
5891  }
5892
5893  // Get rid of client or server
5894  p = strrchr(buf, '/');
5895  if (p == NULL) {
5896    return false;
5897  } else {
5898    *p = '\0';
5899  }
5900
5901  // check xawt/libmawt.so
5902  strcpy(libmawtpath, buf);
5903  strcat(libmawtpath, xawtstr);
5904  if (::stat(libmawtpath, &statbuf) == 0) return false;
5905
5906  // check libawt_xawt.so
5907  strcpy(libmawtpath, buf);
5908  strcat(libmawtpath, new_xawtstr);
5909  if (::stat(libmawtpath, &statbuf) == 0) return false;
5910
5911  return true;
5912}
5913
5914// Get the default path to the core file
5915// Returns the length of the string
5916int os::get_core_path(char* buffer, size_t bufferSize) {
5917  /*
5918   * Max length of /proc/sys/kernel/core_pattern is 128 characters.
5919   * See https://www.kernel.org/doc/Documentation/sysctl/kernel.txt
5920   */
5921  const int core_pattern_len = 129;
5922  char core_pattern[core_pattern_len] = {0};
5923
5924  int core_pattern_file = ::open("/proc/sys/kernel/core_pattern", O_RDONLY);
5925  if (core_pattern_file == -1) {
5926    return -1;
5927  }
5928
5929  ssize_t ret = ::read(core_pattern_file, core_pattern, core_pattern_len);
5930  ::close(core_pattern_file);
5931  if (ret <= 0 || ret >= core_pattern_len || core_pattern[0] == '\n') {
5932    return -1;
5933  }
5934  if (core_pattern[ret-1] == '\n') {
5935    core_pattern[ret-1] = '\0';
5936  } else {
5937    core_pattern[ret] = '\0';
5938  }
5939
5940  char *pid_pos = strstr(core_pattern, "%p");
5941  int written;
5942
5943  if (core_pattern[0] == '/') {
5944    written = jio_snprintf(buffer, bufferSize, "%s", core_pattern);
5945  } else {
5946    char cwd[PATH_MAX];
5947
5948    const char* p = get_current_directory(cwd, PATH_MAX);
5949    if (p == NULL) {
5950      return -1;
5951    }
5952
5953    if (core_pattern[0] == '|') {
5954      written = jio_snprintf(buffer, bufferSize,
5955                        "\"%s\" (or dumping to %s/core.%d)",
5956                                     &core_pattern[1], p, current_process_id());
5957    } else {
5958      written = jio_snprintf(buffer, bufferSize, "%s/%s", p, core_pattern);
5959    }
5960  }
5961
5962  if (written < 0) {
5963    return -1;
5964  }
5965
5966  if (((size_t)written < bufferSize) && (pid_pos == NULL) && (core_pattern[0] != '|')) {
5967    int core_uses_pid_file = ::open("/proc/sys/kernel/core_uses_pid", O_RDONLY);
5968
5969    if (core_uses_pid_file != -1) {
5970      char core_uses_pid = 0;
5971      ssize_t ret = ::read(core_uses_pid_file, &core_uses_pid, 1);
5972      ::close(core_uses_pid_file);
5973
5974      if (core_uses_pid == '1') {
5975        jio_snprintf(buffer + written, bufferSize - written,
5976                                          ".%d", current_process_id());
5977      }
5978    }
5979  }
5980
5981  return strlen(buffer);
5982}
5983
5984bool os::start_debugging(char *buf, int buflen) {
5985  int len = (int)strlen(buf);
5986  char *p = &buf[len];
5987
5988  jio_snprintf(p, buflen-len,
5989             "\n\n"
5990             "Do you want to debug the problem?\n\n"
5991             "To debug, run 'gdb /proc/%d/exe %d'; then switch to thread " UINTX_FORMAT " (" INTPTR_FORMAT ")\n"
5992             "Enter 'yes' to launch gdb automatically (PATH must include gdb)\n"
5993             "Otherwise, press RETURN to abort...",
5994             os::current_process_id(), os::current_process_id(),
5995             os::current_thread_id(), os::current_thread_id());
5996
5997  bool yes = os::message_box("Unexpected Error", buf);
5998
5999  if (yes) {
6000    // yes, user asked VM to launch debugger
6001    jio_snprintf(buf, sizeof(buf), "gdb /proc/%d/exe %d",
6002                     os::current_process_id(), os::current_process_id());
6003
6004    os::fork_and_exec(buf);
6005    yes = false;
6006  }
6007  return yes;
6008}
6009
6010
6011
6012/////////////// Unit tests ///////////////
6013
6014#ifndef PRODUCT
6015
6016#define test_log(...)              \
6017  do {                             \
6018    if (VerboseInternalVMTests) {  \
6019      tty->print_cr(__VA_ARGS__);  \
6020      tty->flush();                \
6021    }                              \
6022  } while (false)
6023
6024class TestReserveMemorySpecial : AllStatic {
6025 public:
6026  static void small_page_write(void* addr, size_t size) {
6027    size_t page_size = os::vm_page_size();
6028
6029    char* end = (char*)addr + size;
6030    for (char* p = (char*)addr; p < end; p += page_size) {
6031      *p = 1;
6032    }
6033  }
6034
6035  static void test_reserve_memory_special_huge_tlbfs_only(size_t size) {
6036    if (!UseHugeTLBFS) {
6037      return;
6038    }
6039
6040    test_log("test_reserve_memory_special_huge_tlbfs_only(" SIZE_FORMAT ")", size);
6041
6042    char* addr = os::Linux::reserve_memory_special_huge_tlbfs_only(size, NULL, false);
6043
6044    if (addr != NULL) {
6045      small_page_write(addr, size);
6046
6047      os::Linux::release_memory_special_huge_tlbfs(addr, size);
6048    }
6049  }
6050
6051  static void test_reserve_memory_special_huge_tlbfs_only() {
6052    if (!UseHugeTLBFS) {
6053      return;
6054    }
6055
6056    size_t lp = os::large_page_size();
6057
6058    for (size_t size = lp; size <= lp * 10; size += lp) {
6059      test_reserve_memory_special_huge_tlbfs_only(size);
6060    }
6061  }
6062
6063  static void test_reserve_memory_special_huge_tlbfs_mixed() {
6064    size_t lp = os::large_page_size();
6065    size_t ag = os::vm_allocation_granularity();
6066
6067    // sizes to test
6068    const size_t sizes[] = {
6069      lp, lp + ag, lp + lp / 2, lp * 2,
6070      lp * 2 + ag, lp * 2 - ag, lp * 2 + lp / 2,
6071      lp * 10, lp * 10 + lp / 2
6072    };
6073    const int num_sizes = sizeof(sizes) / sizeof(size_t);
6074
6075    // For each size/alignment combination, we test three scenarios:
6076    // 1) with req_addr == NULL
6077    // 2) with a non-null req_addr at which we expect to successfully allocate
6078    // 3) with a non-null req_addr which contains a pre-existing mapping, at which we
6079    //    expect the allocation to either fail or to ignore req_addr
6080
6081    // Pre-allocate two areas; they shall be as large as the largest allocation
6082    //  and aligned to the largest alignment we will be testing.
6083    const size_t mapping_size = sizes[num_sizes - 1] * 2;
6084    char* const mapping1 = (char*) ::mmap(NULL, mapping_size,
6085      PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
6086      -1, 0);
6087    assert(mapping1 != MAP_FAILED, "should work");
6088
6089    char* const mapping2 = (char*) ::mmap(NULL, mapping_size,
6090      PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
6091      -1, 0);
6092    assert(mapping2 != MAP_FAILED, "should work");
6093
6094    // Unmap the first mapping, but leave the second mapping intact: the first
6095    // mapping will serve as a value for a "good" req_addr (case 2). The second
6096    // mapping, still intact, as "bad" req_addr (case 3).
6097    ::munmap(mapping1, mapping_size);
6098
6099    // Case 1
6100    test_log("%s, req_addr NULL:", __FUNCTION__);
6101    test_log("size            align           result");
6102
6103    for (int i = 0; i < num_sizes; i++) {
6104      const size_t size = sizes[i];
6105      for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
6106        char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, NULL, false);
6107        test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " ->  " PTR_FORMAT " %s",
6108                 size, alignment, p2i(p), (p != NULL ? "" : "(failed)"));
6109        if (p != NULL) {
6110          assert(is_ptr_aligned(p, alignment), "must be");
6111          small_page_write(p, size);
6112          os::Linux::release_memory_special_huge_tlbfs(p, size);
6113        }
6114      }
6115    }
6116
6117    // Case 2
6118    test_log("%s, req_addr non-NULL:", __FUNCTION__);
6119    test_log("size            align           req_addr         result");
6120
6121    for (int i = 0; i < num_sizes; i++) {
6122      const size_t size = sizes[i];
6123      for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
6124        char* const req_addr = (char*) align_ptr_up(mapping1, alignment);
6125        char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, req_addr, false);
6126        test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " " PTR_FORMAT " ->  " PTR_FORMAT " %s",
6127                 size, alignment, p2i(req_addr), p2i(p),
6128                 ((p != NULL ? (p == req_addr ? "(exact match)" : "") : "(failed)")));
6129        if (p != NULL) {
6130          assert(p == req_addr, "must be");
6131          small_page_write(p, size);
6132          os::Linux::release_memory_special_huge_tlbfs(p, size);
6133        }
6134      }
6135    }
6136
6137    // Case 3
6138    test_log("%s, req_addr non-NULL with preexisting mapping:", __FUNCTION__);
6139    test_log("size            align           req_addr         result");
6140
6141    for (int i = 0; i < num_sizes; i++) {
6142      const size_t size = sizes[i];
6143      for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
6144        char* const req_addr = (char*) align_ptr_up(mapping2, alignment);
6145        char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, req_addr, false);
6146        test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " " PTR_FORMAT " ->  " PTR_FORMAT " %s",
6147                 size, alignment, p2i(req_addr), p2i(p), ((p != NULL ? "" : "(failed)")));
6148        // as the area around req_addr contains already existing mappings, the API should always
6149        // return NULL (as per contract, it cannot return another address)
6150        assert(p == NULL, "must be");
6151      }
6152    }
6153
6154    ::munmap(mapping2, mapping_size);
6155
6156  }
6157
6158  static void test_reserve_memory_special_huge_tlbfs() {
6159    if (!UseHugeTLBFS) {
6160      return;
6161    }
6162
6163    test_reserve_memory_special_huge_tlbfs_only();
6164    test_reserve_memory_special_huge_tlbfs_mixed();
6165  }
6166
6167  static void test_reserve_memory_special_shm(size_t size, size_t alignment) {
6168    if (!UseSHM) {
6169      return;
6170    }
6171
6172    test_log("test_reserve_memory_special_shm(" SIZE_FORMAT ", " SIZE_FORMAT ")", size, alignment);
6173
6174    char* addr = os::Linux::reserve_memory_special_shm(size, alignment, NULL, false);
6175
6176    if (addr != NULL) {
6177      assert(is_ptr_aligned(addr, alignment), "Check");
6178      assert(is_ptr_aligned(addr, os::large_page_size()), "Check");
6179
6180      small_page_write(addr, size);
6181
6182      os::Linux::release_memory_special_shm(addr, size);
6183    }
6184  }
6185
6186  static void test_reserve_memory_special_shm() {
6187    size_t lp = os::large_page_size();
6188    size_t ag = os::vm_allocation_granularity();
6189
6190    for (size_t size = ag; size < lp * 3; size += ag) {
6191      for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
6192        test_reserve_memory_special_shm(size, alignment);
6193      }
6194    }
6195  }
6196
6197  static void test() {
6198    test_reserve_memory_special_huge_tlbfs();
6199    test_reserve_memory_special_shm();
6200  }
6201};
6202
6203void TestReserveMemorySpecial_test() {
6204  TestReserveMemorySpecial::test();
6205}
6206
6207#endif
6208