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