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