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