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