1 #ifdef USE_PRAGMA_IDENT_SRC 2 #pragma ident "@(#)os_linux.cpp 1.259 08/11/24 12:20:22 JVM" 3 #endif 4 /* 5 * Copyright 1999-2009 Sun Microsystems, Inc. All Rights Reserved. 6 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 7 * 8 * This code is free software; you can redistribute it and/or modify it 9 * under the terms of the GNU General Public License version 2 only, as 10 * published by the Free Software Foundation. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 23 * CA 95054 USA or visit www.sun.com if you need additional information or 24 * have any questions. 25 * 26 */ 27 28 // do not include precompiled header file 29 # include "incls/_os_linux.cpp.incl" 30 31 // put OS-includes here 32 # include <sys/types.h> 33 # include <sys/mman.h> 34 # include <pthread.h> 35 # include <signal.h> 36 # include <errno.h> 37 # include <dlfcn.h> 38 # include <stdio.h> 39 # include <unistd.h> 40 # include <sys/resource.h> 41 # include <pthread.h> 42 # include <sys/stat.h> 43 # include <sys/time.h> 44 # include <sys/times.h> 45 # include <sys/utsname.h> 46 # include <sys/socket.h> 47 # include <sys/wait.h> 48 # include <pwd.h> 49 # include <poll.h> 50 # include <semaphore.h> 51 # include <fcntl.h> 52 # include <string.h> 53 # include <syscall.h> 54 # include <sys/sysinfo.h> 55 # include <gnu/libc-version.h> 56 # include <sys/ipc.h> 57 # include <sys/shm.h> 58 # include <link.h> 59 60 #define MAX_PATH (2 * K) 61 62 // for timer info max values which include all bits 63 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) 64 #define SEC_IN_NANOSECS 1000000000LL 65 66 //////////////////////////////////////////////////////////////////////////////// 67 // global variables 68 julong os::Linux::_physical_memory = 0; 69 70 address os::Linux::_initial_thread_stack_bottom = NULL; 71 uintptr_t os::Linux::_initial_thread_stack_size = 0; 72 73 int (*os::Linux::_clock_gettime)(clockid_t, struct timespec *) = NULL; 74 int (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL; 75 Mutex* os::Linux::_createThread_lock = NULL; 76 pthread_t os::Linux::_main_thread; 77 int os::Linux::_page_size = -1; 78 bool os::Linux::_is_floating_stack = false; 79 bool os::Linux::_is_NPTL = false; 80 bool os::Linux::_supports_fast_thread_cpu_time = false; 81 const char * os::Linux::_glibc_version = NULL; 82 const char * os::Linux::_libpthread_version = NULL; 83 84 static jlong initial_time_count=0; 85 86 static int clock_tics_per_sec = 100; 87 88 // For diagnostics to print a message once. see run_periodic_checks 89 static sigset_t check_signal_done; 90 static bool check_signals = true;; 91 92 static pid_t _initial_pid = 0; 93 94 /* Signal number used to suspend/resume a thread */ 95 96 /* do not use any signal number less than SIGSEGV, see 4355769 */ 97 static int SR_signum = SIGUSR2; 98 sigset_t SR_sigset; 99 100 /* Used to protect dlsym() calls */ 101 static pthread_mutex_t dl_mutex; 102 103 //////////////////////////////////////////////////////////////////////////////// 104 // utility functions 105 106 static int SR_initialize(); 107 static int SR_finalize(); 108 109 julong os::available_memory() { 110 return Linux::available_memory(); 111 } 112 113 julong os::Linux::available_memory() { 114 // values in struct sysinfo are "unsigned long" 115 struct sysinfo si; 116 sysinfo(&si); 117 118 return (julong)si.freeram * si.mem_unit; 119 } 120 121 julong os::physical_memory() { 122 return Linux::physical_memory(); 123 } 124 125 julong os::allocatable_physical_memory(julong size) { 126 #ifdef _LP64 127 return size; 128 #else 129 julong result = MIN2(size, (julong)3800*M); 130 if (!is_allocatable(result)) { 131 // See comments under solaris for alignment considerations 132 julong reasonable_size = (julong)2*G - 2 * os::vm_page_size(); 133 result = MIN2(size, reasonable_size); 134 } 135 return result; 136 #endif // _LP64 137 } 138 139 //////////////////////////////////////////////////////////////////////////////// 140 // environment support 141 142 bool os::getenv(const char* name, char* buf, int len) { 143 const char* val = ::getenv(name); 144 if (val != NULL && strlen(val) < (size_t)len) { 145 strcpy(buf, val); 146 return true; 147 } 148 if (len > 0) buf[0] = 0; // return a null string 149 return false; 150 } 151 152 153 // Return true if user is running as root. 154 155 bool os::have_special_privileges() { 156 static bool init = false; 157 static bool privileges = false; 158 if (!init) { 159 privileges = (getuid() != geteuid()) || (getgid() != getegid()); 160 init = true; 161 } 162 return privileges; 163 } 164 165 166 #ifndef SYS_gettid 167 // i386: 224, ia64: 1105, amd64: 186, sparc 143 168 #ifdef __ia64__ 169 #define SYS_gettid 1105 170 #elif __i386__ 171 #define SYS_gettid 224 172 #elif __amd64__ 173 #define SYS_gettid 186 174 #elif __sparc__ 175 #define SYS_gettid 143 176 #else 177 #error define gettid for the arch 178 #endif 179 #endif 180 181 // Cpu architecture string 182 #if defined(IA64) 183 static char cpu_arch[] = "ia64"; 184 #elif defined(IA32) 185 static char cpu_arch[] = "i386"; 186 #elif defined(AMD64) 187 static char cpu_arch[] = "amd64"; 188 #elif defined(SPARC) 189 # ifdef _LP64 190 static char cpu_arch[] = "sparcv9"; 191 # else 192 static char cpu_arch[] = "sparc"; 193 # endif 194 #else 195 #error Add appropriate cpu_arch setting 196 #endif 197 198 199 // pid_t gettid() 200 // 201 // Returns the kernel thread id of the currently running thread. Kernel 202 // thread id is used to access /proc. 203 // 204 // (Note that getpid() on LinuxThreads returns kernel thread id too; but 205 // on NPTL, it returns the same pid for all threads, as required by POSIX.) 206 // 207 pid_t os::Linux::gettid() { 208 int rslt = syscall(SYS_gettid); 209 if (rslt == -1) { 210 // old kernel, no NPTL support 211 return getpid(); 212 } else { 213 return (pid_t)rslt; 214 } 215 } 216 217 // Most versions of linux have a bug where the number of processors are 218 // determined by looking at the /proc file system. In a chroot environment, 219 // the system call returns 1. This causes the VM to act as if it is 220 // a single processor and elide locking (see is_MP() call). 221 static bool unsafe_chroot_detected = false; 222 static const char *unstable_chroot_error = "/proc file system not found.\n" 223 "Java may be unstable running multithreaded in a chroot " 224 "environment on Linux when /proc filesystem is not mounted."; 225 226 void os::Linux::initialize_system_info() { 227 _processor_count = sysconf(_SC_NPROCESSORS_CONF); 228 if (_processor_count == 1) { 229 pid_t pid = os::Linux::gettid(); 230 char fname[32]; 231 jio_snprintf(fname, sizeof(fname), "/proc/%d", pid); 232 FILE *fp = fopen(fname, "r"); 233 if (fp == NULL) { 234 unsafe_chroot_detected = true; 235 } else { 236 fclose(fp); 237 } 238 } 239 _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE); 240 assert(_processor_count > 0, "linux error"); 241 } 242 243 void os::init_system_properties_values() { 244 // char arch[12]; 245 // sysinfo(SI_ARCHITECTURE, arch, sizeof(arch)); 246 247 // The next steps are taken in the product version: 248 // 249 // Obtain the JAVA_HOME value from the location of libjvm[_g].so. 250 // This library should be located at: 251 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm[_g].so. 252 // 253 // If "/jre/lib/" appears at the right place in the path, then we 254 // assume libjvm[_g].so is installed in a JDK and we use this path. 255 // 256 // Otherwise exit with message: "Could not create the Java virtual machine." 257 // 258 // The following extra steps are taken in the debugging version: 259 // 260 // If "/jre/lib/" does NOT appear at the right place in the path 261 // instead of exit check for $JAVA_HOME environment variable. 262 // 263 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>, 264 // then we append a fake suffix "hotspot/libjvm[_g].so" to this path so 265 // it looks like libjvm[_g].so is installed there 266 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm[_g].so. 267 // 268 // Otherwise exit. 269 // 270 // Important note: if the location of libjvm.so changes this 271 // code needs to be changed accordingly. 272 273 // The next few definitions allow the code to be verbatim: 274 #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n)) 275 #define getenv(n) ::getenv(n) 276 277 /* 278 * See ld(1): 279 * The linker uses the following search paths to locate required 280 * shared libraries: 281 * 1: ... 282 * ... 283 * 7: The default directories, normally /lib and /usr/lib. 284 */ 285 #define DEFAULT_LIBPATH "/lib:/usr/lib" 286 287 #define EXTENSIONS_DIR "/lib/ext" 288 #define ENDORSED_DIR "/lib/endorsed" 289 #define REG_DIR "/usr/java/packages" 290 291 { 292 /* sysclasspath, java_home, dll_dir */ 293 { 294 char *home_path; 295 char *dll_path; 296 char *pslash; 297 char buf[MAXPATHLEN]; 298 os::jvm_path(buf, sizeof(buf)); 299 300 // Found the full path to libjvm.so. 301 // Now cut the path to <java_home>/jre if we can. 302 *(strrchr(buf, '/')) = '\0'; /* get rid of /libjvm.so */ 303 pslash = strrchr(buf, '/'); 304 if (pslash != NULL) 305 *pslash = '\0'; /* get rid of /{client|server|hotspot} */ 306 dll_path = malloc(strlen(buf) + 1); 307 if (dll_path == NULL) 308 return; 309 strcpy(dll_path, buf); 310 Arguments::set_dll_dir(dll_path); 311 312 if (pslash != NULL) { 313 pslash = strrchr(buf, '/'); 314 if (pslash != NULL) { 315 *pslash = '\0'; /* get rid of /<arch> */ 316 pslash = strrchr(buf, '/'); 317 if (pslash != NULL) 318 *pslash = '\0'; /* get rid of /lib */ 319 } 320 } 321 322 home_path = malloc(strlen(buf) + 1); 323 if (home_path == NULL) 324 return; 325 strcpy(home_path, buf); 326 Arguments::set_java_home(home_path); 327 328 if (!set_boot_path('/', ':')) 329 return; 330 } 331 332 /* 333 * Where to look for native libraries 334 * 335 * Note: Due to a legacy implementation, most of the library path 336 * is set in the launcher. This was to accomodate linking restrictions 337 * on legacy Linux implementations (which are no longer supported). 338 * Eventually, all the library path setting will be done here. 339 * 340 * However, to prevent the proliferation of improperly built native 341 * libraries, the new path component /usr/java/packages is added here. 342 * Eventually, all the library path setting will be done here. 343 */ 344 { 345 char *ld_library_path; 346 347 /* 348 * Construct the invariant part of ld_library_path. Note that the 349 * space for the colon and the trailing null are provided by the 350 * nulls included by the sizeof operator (so actually we allocate 351 * a byte more than necessary). 352 */ 353 ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") + 354 strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH)); 355 sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch); 356 357 /* 358 * Get the user setting of LD_LIBRARY_PATH, and prepended it. It 359 * should always exist (until the legacy problem cited above is 360 * addressed). 361 */ 362 char *v = getenv("LD_LIBRARY_PATH"); 363 if (v != NULL) { 364 char *t = ld_library_path; 365 /* That's +1 for the colon and +1 for the trailing '\0' */ 366 ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1); 367 sprintf(ld_library_path, "%s:%s", v, t); 368 } 369 Arguments::set_library_path(ld_library_path); 370 } 371 372 /* 373 * Extensions directories. 374 * 375 * Note that the space for the colon and the trailing null are provided 376 * by the nulls included by the sizeof operator (so actually one byte more 377 * than necessary is allocated). 378 */ 379 { 380 char *buf = malloc(strlen(Arguments::get_java_home()) + 381 sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR)); 382 sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR, 383 Arguments::get_java_home()); 384 Arguments::set_ext_dirs(buf); 385 } 386 387 /* Endorsed standards default directory. */ 388 { 389 char * buf; 390 buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR)); 391 sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home()); 392 Arguments::set_endorsed_dirs(buf); 393 } 394 } 395 396 #undef malloc 397 #undef getenv 398 #undef EXTENSIONS_DIR 399 #undef ENDORSED_DIR 400 401 // Done 402 return; 403 } 404 405 //////////////////////////////////////////////////////////////////////////////// 406 // breakpoint support 407 408 void os::breakpoint() { 409 BREAKPOINT; 410 } 411 412 extern "C" void breakpoint() { 413 // use debugger to set breakpoint here 414 } 415 416 //////////////////////////////////////////////////////////////////////////////// 417 // signal support 418 419 debug_only(static bool signal_sets_initialized = false); 420 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs; 421 422 bool os::Linux::is_sig_ignored(int sig) { 423 struct sigaction oact; 424 sigaction(sig, (struct sigaction*)NULL, &oact); 425 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) 426 : CAST_FROM_FN_PTR(void*, oact.sa_handler); 427 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) 428 return true; 429 else 430 return false; 431 } 432 433 void os::Linux::signal_sets_init() { 434 // Should also have an assertion stating we are still single-threaded. 435 assert(!signal_sets_initialized, "Already initialized"); 436 // Fill in signals that are necessarily unblocked for all threads in 437 // the VM. Currently, we unblock the following signals: 438 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden 439 // by -Xrs (=ReduceSignalUsage)); 440 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all 441 // other threads. The "ReduceSignalUsage" boolean tells us not to alter 442 // the dispositions or masks wrt these signals. 443 // Programs embedding the VM that want to use the above signals for their 444 // own purposes must, at this time, use the "-Xrs" option to prevent 445 // interference with shutdown hooks and BREAK_SIGNAL thread dumping. 446 // (See bug 4345157, and other related bugs). 447 // In reality, though, unblocking these signals is really a nop, since 448 // these signals are not blocked by default. 449 sigemptyset(&unblocked_sigs); 450 sigemptyset(&allowdebug_blocked_sigs); 451 sigaddset(&unblocked_sigs, SIGILL); 452 sigaddset(&unblocked_sigs, SIGSEGV); 453 sigaddset(&unblocked_sigs, SIGBUS); 454 sigaddset(&unblocked_sigs, SIGFPE); 455 sigaddset(&unblocked_sigs, SR_signum); 456 457 if (!ReduceSignalUsage) { 458 if (!os::Linux::is_sig_ignored(SHUTDOWN1_SIGNAL)) { 459 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); 460 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL); 461 } 462 if (!os::Linux::is_sig_ignored(SHUTDOWN2_SIGNAL)) { 463 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); 464 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL); 465 } 466 if (!os::Linux::is_sig_ignored(SHUTDOWN3_SIGNAL)) { 467 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); 468 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL); 469 } 470 } 471 // Fill in signals that are blocked by all but the VM thread. 472 sigemptyset(&vm_sigs); 473 if (!ReduceSignalUsage) 474 sigaddset(&vm_sigs, BREAK_SIGNAL); 475 debug_only(signal_sets_initialized = true); 476 477 } 478 479 // These are signals that are unblocked while a thread is running Java. 480 // (For some reason, they get blocked by default.) 481 sigset_t* os::Linux::unblocked_signals() { 482 assert(signal_sets_initialized, "Not initialized"); 483 return &unblocked_sigs; 484 } 485 486 // These are the signals that are blocked while a (non-VM) thread is 487 // running Java. Only the VM thread handles these signals. 488 sigset_t* os::Linux::vm_signals() { 489 assert(signal_sets_initialized, "Not initialized"); 490 return &vm_sigs; 491 } 492 493 // These are signals that are blocked during cond_wait to allow debugger in 494 sigset_t* os::Linux::allowdebug_blocked_signals() { 495 assert(signal_sets_initialized, "Not initialized"); 496 return &allowdebug_blocked_sigs; 497 } 498 499 void os::Linux::hotspot_sigmask(Thread* thread) { 500 501 //Save caller's signal mask before setting VM signal mask 502 sigset_t caller_sigmask; 503 pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask); 504 505 OSThread* osthread = thread->osthread(); 506 osthread->set_caller_sigmask(caller_sigmask); 507 508 pthread_sigmask(SIG_UNBLOCK, os::Linux::unblocked_signals(), NULL); 509 510 if (!ReduceSignalUsage) { 511 if (thread->is_VM_thread()) { 512 // Only the VM thread handles BREAK_SIGNAL ... 513 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); 514 } else { 515 // ... all other threads block BREAK_SIGNAL 516 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); 517 } 518 } 519 } 520 521 ////////////////////////////////////////////////////////////////////////////// 522 // detecting pthread library 523 524 void os::Linux::libpthread_init() { 525 // Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION 526 // and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a 527 // generic name for earlier versions. 528 // Define macros here so we can build HotSpot on old systems. 529 # ifndef _CS_GNU_LIBC_VERSION 530 # define _CS_GNU_LIBC_VERSION 2 531 # endif 532 # ifndef _CS_GNU_LIBPTHREAD_VERSION 533 # define _CS_GNU_LIBPTHREAD_VERSION 3 534 # endif 535 536 size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0); 537 if (n > 0) { 538 char *str = (char *)malloc(n); 539 confstr(_CS_GNU_LIBC_VERSION, str, n); 540 os::Linux::set_glibc_version(str); 541 } else { 542 // _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version() 543 static char _gnu_libc_version[32]; 544 jio_snprintf(_gnu_libc_version, sizeof(_gnu_libc_version), 545 "glibc %s %s", gnu_get_libc_version(), gnu_get_libc_release()); 546 os::Linux::set_glibc_version(_gnu_libc_version); 547 } 548 549 n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0); 550 if (n > 0) { 551 char *str = (char *)malloc(n); 552 confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n); 553 // Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells 554 // us "NPTL-0.29" even we are running with LinuxThreads. Check if this 555 // is the case. LinuxThreads has a hard limit on max number of threads. 556 // So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value. 557 // On the other hand, NPTL does not have such a limit, sysconf() 558 // will return -1 and errno is not changed. Check if it is really NPTL. 559 if (strcmp(os::Linux::glibc_version(), "glibc 2.3.2") == 0 && 560 strstr(str, "NPTL") && 561 sysconf(_SC_THREAD_THREADS_MAX) > 0) { 562 free(str); 563 os::Linux::set_libpthread_version("linuxthreads"); 564 } else { 565 os::Linux::set_libpthread_version(str); 566 } 567 } else { 568 // glibc before 2.3.2 only has LinuxThreads. 569 os::Linux::set_libpthread_version("linuxthreads"); 570 } 571 572 if (strstr(libpthread_version(), "NPTL")) { 573 os::Linux::set_is_NPTL(); 574 } else { 575 os::Linux::set_is_LinuxThreads(); 576 } 577 578 // LinuxThreads have two flavors: floating-stack mode, which allows variable 579 // stack size; and fixed-stack mode. NPTL is always floating-stack. 580 if (os::Linux::is_NPTL() || os::Linux::supports_variable_stack_size()) { 581 os::Linux::set_is_floating_stack(); 582 } 583 } 584 585 ///////////////////////////////////////////////////////////////////////////// 586 // thread stack 587 588 // Force Linux kernel to expand current thread stack. If "bottom" is close 589 // to the stack guard, caller should block all signals. 590 // 591 // MAP_GROWSDOWN: 592 // A special mmap() flag that is used to implement thread stacks. It tells 593 // kernel that the memory region should extend downwards when needed. This 594 // allows early versions of LinuxThreads to only mmap the first few pages 595 // when creating a new thread. Linux kernel will automatically expand thread 596 // stack as needed (on page faults). 597 // 598 // However, because the memory region of a MAP_GROWSDOWN stack can grow on 599 // demand, if a page fault happens outside an already mapped MAP_GROWSDOWN 600 // region, it's hard to tell if the fault is due to a legitimate stack 601 // access or because of reading/writing non-exist memory (e.g. buffer 602 // overrun). As a rule, if the fault happens below current stack pointer, 603 // Linux kernel does not expand stack, instead a SIGSEGV is sent to the 604 // application (see Linux kernel fault.c). 605 // 606 // This Linux feature can cause SIGSEGV when VM bangs thread stack for 607 // stack overflow detection. 608 // 609 // Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do 610 // not use this flag. However, the stack of initial thread is not created 611 // by pthread, it is still MAP_GROWSDOWN. Also it's possible (though 612 // unlikely) that user code can create a thread with MAP_GROWSDOWN stack 613 // and then attach the thread to JVM. 614 // 615 // To get around the problem and allow stack banging on Linux, we need to 616 // manually expand thread stack after receiving the SIGSEGV. 617 // 618 // There are two ways to expand thread stack to address "bottom", we used 619 // both of them in JVM before 1.5: 620 // 1. adjust stack pointer first so that it is below "bottom", and then 621 // touch "bottom" 622 // 2. mmap() the page in question 623 // 624 // Now alternate signal stack is gone, it's harder to use 2. For instance, 625 // if current sp is already near the lower end of page 101, and we need to 626 // call mmap() to map page 100, it is possible that part of the mmap() frame 627 // will be placed in page 100. When page 100 is mapped, it is zero-filled. 628 // That will destroy the mmap() frame and cause VM to crash. 629 // 630 // The following code works by adjusting sp first, then accessing the "bottom" 631 // page to force a page fault. Linux kernel will then automatically expand the 632 // stack mapping. 633 // 634 // _expand_stack_to() assumes its frame size is less than page size, which 635 // should always be true if the function is not inlined. 636 637 #if __GNUC__ < 3 // gcc 2.x does not support noinline attribute 638 #define NOINLINE 639 #else 640 #define NOINLINE __attribute__ ((noinline)) 641 #endif 642 643 static void _expand_stack_to(address bottom) NOINLINE; 644 645 static void _expand_stack_to(address bottom) { 646 address sp; 647 size_t size; 648 volatile char *p; 649 650 // Adjust bottom to point to the largest address within the same page, it 651 // gives us a one-page buffer if alloca() allocates slightly more memory. 652 bottom = (address)align_size_down((uintptr_t)bottom, os::Linux::page_size()); 653 bottom += os::Linux::page_size() - 1; 654 655 // sp might be slightly above current stack pointer; if that's the case, we 656 // will alloca() a little more space than necessary, which is OK. Don't use 657 // os::current_stack_pointer(), as its result can be slightly below current 658 // stack pointer, causing us to not alloca enough to reach "bottom". 659 sp = (address)&sp; 660 661 if (sp > bottom) { 662 size = sp - bottom; 663 p = (volatile char *)alloca(size); 664 assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?"); 665 p[0] = '\0'; 666 } 667 } 668 669 bool os::Linux::manually_expand_stack(JavaThread * t, address addr) { 670 assert(t!=NULL, "just checking"); 671 assert(t->osthread()->expanding_stack(), "expand should be set"); 672 assert(t->stack_base() != NULL, "stack_base was not initialized"); 673 674 if (addr < t->stack_base() && addr >= t->stack_yellow_zone_base()) { 675 sigset_t mask_all, old_sigset; 676 sigfillset(&mask_all); 677 pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset); 678 _expand_stack_to(addr); 679 pthread_sigmask(SIG_SETMASK, &old_sigset, NULL); 680 return true; 681 } 682 return false; 683 } 684 685 ////////////////////////////////////////////////////////////////////////////// 686 // create new thread 687 688 static address highest_vm_reserved_address(); 689 690 // check if it's safe to start a new thread 691 static bool _thread_safety_check(Thread* thread) { 692 if (os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack()) { 693 // Fixed stack LinuxThreads (SuSE Linux/x86, and some versions of Redhat) 694 // Heap is mmap'ed at lower end of memory space. Thread stacks are 695 // allocated (MAP_FIXED) from high address space. Every thread stack 696 // occupies a fixed size slot (usually 2Mbytes, but user can change 697 // it to other values if they rebuild LinuxThreads). 698 // 699 // Problem with MAP_FIXED is that mmap() can still succeed even part of 700 // the memory region has already been mmap'ed. That means if we have too 701 // many threads and/or very large heap, eventually thread stack will 702 // collide with heap. 703 // 704 // Here we try to prevent heap/stack collision by comparing current 705 // stack bottom with the highest address that has been mmap'ed by JVM 706 // plus a safety margin for memory maps created by native code. 707 // 708 // This feature can be disabled by setting ThreadSafetyMargin to 0 709 // 710 if (ThreadSafetyMargin > 0) { 711 address stack_bottom = os::current_stack_base() - os::current_stack_size(); 712 713 // not safe if our stack extends below the safety margin 714 return stack_bottom - ThreadSafetyMargin >= highest_vm_reserved_address(); 715 } else { 716 return true; 717 } 718 } else { 719 // Floating stack LinuxThreads or NPTL: 720 // Unlike fixed stack LinuxThreads, thread stacks are not MAP_FIXED. When 721 // there's not enough space left, pthread_create() will fail. If we come 722 // here, that means enough space has been reserved for stack. 723 return true; 724 } 725 } 726 727 // Thread start routine for all newly created threads 728 static void *java_start(Thread *thread) { 729 // Try to randomize the cache line index of hot stack frames. 730 // This helps when threads of the same stack traces evict each other's 731 // cache lines. The threads can be either from the same JVM instance, or 732 // from different JVM instances. The benefit is especially true for 733 // processors with hyperthreading technology. 734 static int counter = 0; 735 int pid = os::current_process_id(); 736 alloca(((pid ^ counter++) & 7) * 128); 737 738 ThreadLocalStorage::set_thread(thread); 739 740 OSThread* osthread = thread->osthread(); 741 Monitor* sync = osthread->startThread_lock(); 742 743 // non floating stack LinuxThreads needs extra check, see above 744 if (!_thread_safety_check(thread)) { 745 // notify parent thread 746 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 747 osthread->set_state(ZOMBIE); 748 sync->notify_all(); 749 return NULL; 750 } 751 752 // thread_id is kernel thread id (similar to Solaris LWP id) 753 osthread->set_thread_id(os::Linux::gettid()); 754 755 if (UseNUMA) { 756 int lgrp_id = os::numa_get_group_id(); 757 if (lgrp_id != -1) { 758 thread->set_lgrp_id(lgrp_id); 759 } 760 } 761 // initialize signal mask for this thread 762 os::Linux::hotspot_sigmask(thread); 763 764 // initialize floating point control register 765 os::Linux::init_thread_fpu_state(); 766 767 // handshaking with parent thread 768 { 769 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); 770 771 // notify parent thread 772 osthread->set_state(INITIALIZED); 773 sync->notify_all(); 774 775 // wait until os::start_thread() 776 while (osthread->get_state() == INITIALIZED) { 777 sync->wait(Mutex::_no_safepoint_check_flag); 778 } 779 } 780 781 // call one more level start routine 782 thread->run(); 783 784 return 0; 785 } 786 787 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { 788 assert(thread->osthread() == NULL, "caller responsible"); 789 790 // Allocate the OSThread object 791 OSThread* osthread = new OSThread(NULL, NULL); 792 if (osthread == NULL) { 793 return false; 794 } 795 796 // set the correct thread state 797 osthread->set_thread_type(thr_type); 798 799 // Initial state is ALLOCATED but not INITIALIZED 800 osthread->set_state(ALLOCATED); 801 802 thread->set_osthread(osthread); 803 804 // init thread attributes 805 pthread_attr_t attr; 806 pthread_attr_init(&attr); 807 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 808 809 // stack size 810 if (os::Linux::supports_variable_stack_size()) { 811 // calculate stack size if it's not specified by caller 812 if (stack_size == 0) { 813 stack_size = os::Linux::default_stack_size(thr_type); 814 815 switch (thr_type) { 816 case os::java_thread: 817 // Java threads use ThreadStackSize which default value can be changed with the flag -Xss 818 if (JavaThread::stack_size_at_create() > 0) stack_size = JavaThread::stack_size_at_create(); 819 break; 820 case os::compiler_thread: 821 if (CompilerThreadStackSize > 0) { 822 stack_size = (size_t)(CompilerThreadStackSize * K); 823 break; 824 } // else fall through: 825 // use VMThreadStackSize if CompilerThreadStackSize is not defined 826 case os::vm_thread: 827 case os::pgc_thread: 828 case os::cgc_thread: 829 case os::watcher_thread: 830 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); 831 break; 832 } 833 } 834 835 stack_size = MAX2(stack_size, os::Linux::min_stack_allowed); 836 pthread_attr_setstacksize(&attr, stack_size); 837 } else { 838 // let pthread_create() pick the default value. 839 } 840 841 // glibc guard page 842 pthread_attr_setguardsize(&attr, os::Linux::default_guard_size(thr_type)); 843 844 ThreadState state; 845 846 { 847 // Serialize thread creation if we are running with fixed stack LinuxThreads 848 bool lock = os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack(); 849 if (lock) { 850 os::Linux::createThread_lock()->lock_without_safepoint_check(); 851 } 852 853 pthread_t tid; 854 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); 855 856 pthread_attr_destroy(&attr); 857 858 if (ret != 0) { 859 if (PrintMiscellaneous && (Verbose || WizardMode)) { 860 perror("pthread_create()"); 861 } 862 // Need to clean up stuff we've allocated so far 863 thread->set_osthread(NULL); 864 delete osthread; 865 if (lock) os::Linux::createThread_lock()->unlock(); 866 return false; 867 } 868 869 // Store pthread info into the OSThread 870 osthread->set_pthread_id(tid); 871 872 // Wait until child thread is either initialized or aborted 873 { 874 Monitor* sync_with_child = osthread->startThread_lock(); 875 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 876 while ((state = osthread->get_state()) == ALLOCATED) { 877 sync_with_child->wait(Mutex::_no_safepoint_check_flag); 878 } 879 } 880 881 if (lock) { 882 os::Linux::createThread_lock()->unlock(); 883 } 884 } 885 886 // Aborted due to thread limit being reached 887 if (state == ZOMBIE) { 888 thread->set_osthread(NULL); 889 delete osthread; 890 return false; 891 } 892 893 // The thread is returned suspended (in state INITIALIZED), 894 // and is started higher up in the call chain 895 assert(state == INITIALIZED, "race condition"); 896 return true; 897 } 898 899 ///////////////////////////////////////////////////////////////////////////// 900 // attach existing thread 901 902 // bootstrap the main thread 903 bool os::create_main_thread(JavaThread* thread) { 904 assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread"); 905 return create_attached_thread(thread); 906 } 907 908 bool os::create_attached_thread(JavaThread* thread) { 909 #ifdef ASSERT 910 thread->verify_not_published(); 911 #endif 912 913 // Allocate the OSThread object 914 OSThread* osthread = new OSThread(NULL, NULL); 915 916 if (osthread == NULL) { 917 return false; 918 } 919 920 // Store pthread info into the OSThread 921 osthread->set_thread_id(os::Linux::gettid()); 922 osthread->set_pthread_id(::pthread_self()); 923 924 // initialize floating point control register 925 os::Linux::init_thread_fpu_state(); 926 927 // Initial thread state is RUNNABLE 928 osthread->set_state(RUNNABLE); 929 930 thread->set_osthread(osthread); 931 932 if (UseNUMA) { 933 int lgrp_id = os::numa_get_group_id(); 934 if (lgrp_id != -1) { 935 thread->set_lgrp_id(lgrp_id); 936 } 937 } 938 939 if (os::Linux::is_initial_thread()) { 940 // If current thread is initial thread, its stack is mapped on demand, 941 // see notes about MAP_GROWSDOWN. Here we try to force kernel to map 942 // the entire stack region to avoid SEGV in stack banging. 943 // It is also useful to get around the heap-stack-gap problem on SuSE 944 // kernel (see 4821821 for details). We first expand stack to the top 945 // of yellow zone, then enable stack yellow zone (order is significant, 946 // enabling yellow zone first will crash JVM on SuSE Linux), so there 947 // is no gap between the last two virtual memory regions. 948 949 JavaThread *jt = (JavaThread *)thread; 950 address addr = jt->stack_yellow_zone_base(); 951 assert(addr != NULL, "initialization problem?"); 952 assert(jt->stack_available(addr) > 0, "stack guard should not be enabled"); 953 954 osthread->set_expanding_stack(); 955 os::Linux::manually_expand_stack(jt, addr); 956 osthread->clear_expanding_stack(); 957 } 958 959 // initialize signal mask for this thread 960 // and save the caller's signal mask 961 os::Linux::hotspot_sigmask(thread); 962 963 return true; 964 } 965 966 void os::pd_start_thread(Thread* thread) { 967 OSThread * osthread = thread->osthread(); 968 assert(osthread->get_state() != INITIALIZED, "just checking"); 969 Monitor* sync_with_child = osthread->startThread_lock(); 970 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); 971 sync_with_child->notify(); 972 } 973 974 // Free Linux resources related to the OSThread 975 void os::free_thread(OSThread* osthread) { 976 assert(osthread != NULL, "osthread not set"); 977 978 if (Thread::current()->osthread() == osthread) { 979 // Restore caller's signal mask 980 sigset_t sigmask = osthread->caller_sigmask(); 981 pthread_sigmask(SIG_SETMASK, &sigmask, NULL); 982 } 983 984 delete osthread; 985 } 986 987 ////////////////////////////////////////////////////////////////////////////// 988 // thread local storage 989 990 int os::allocate_thread_local_storage() { 991 pthread_key_t key; 992 int rslt = pthread_key_create(&key, NULL); 993 assert(rslt == 0, "cannot allocate thread local storage"); 994 return (int)key; 995 } 996 997 // Note: This is currently not used by VM, as we don't destroy TLS key 998 // on VM exit. 999 void os::free_thread_local_storage(int index) { 1000 int rslt = pthread_key_delete((pthread_key_t)index); 1001 assert(rslt == 0, "invalid index"); 1002 } 1003 1004 void os::thread_local_storage_at_put(int index, void* value) { 1005 int rslt = pthread_setspecific((pthread_key_t)index, value); 1006 assert(rslt == 0, "pthread_setspecific failed"); 1007 } 1008 1009 extern "C" Thread* get_thread() { 1010 return ThreadLocalStorage::thread(); 1011 } 1012 1013 ////////////////////////////////////////////////////////////////////////////// 1014 // initial thread 1015 1016 // Check if current thread is the initial thread, similar to Solaris thr_main. 1017 bool os::Linux::is_initial_thread(void) { 1018 char dummy; 1019 // If called before init complete, thread stack bottom will be null. 1020 // Can be called if fatal error occurs before initialization. 1021 if (initial_thread_stack_bottom() == NULL) return false; 1022 assert(initial_thread_stack_bottom() != NULL && 1023 initial_thread_stack_size() != 0, 1024 "os::init did not locate initial thread's stack region"); 1025 if ((address)&dummy >= initial_thread_stack_bottom() && 1026 (address)&dummy < initial_thread_stack_bottom() + initial_thread_stack_size()) 1027 return true; 1028 else return false; 1029 } 1030 1031 // Find the virtual memory area that contains addr 1032 static bool find_vma(address addr, address* vma_low, address* vma_high) { 1033 FILE *fp = fopen("/proc/self/maps", "r"); 1034 if (fp) { 1035 address low, high; 1036 while (!feof(fp)) { 1037 if (fscanf(fp, "%p-%p", &low, &high) == 2) { 1038 if (low <= addr && addr < high) { 1039 if (vma_low) *vma_low = low; 1040 if (vma_high) *vma_high = high; 1041 fclose (fp); 1042 return true; 1043 } 1044 } 1045 for (;;) { 1046 int ch = fgetc(fp); 1047 if (ch == EOF || ch == (int)'\n') break; 1048 } 1049 } 1050 fclose(fp); 1051 } 1052 return false; 1053 } 1054 1055 // Locate initial thread stack. This special handling of initial thread stack 1056 // is needed because pthread_getattr_np() on most (all?) Linux distros returns 1057 // bogus value for initial thread. 1058 void os::Linux::capture_initial_stack(size_t max_size) { 1059 // stack size is the easy part, get it from RLIMIT_STACK 1060 size_t stack_size; 1061 struct rlimit rlim; 1062 getrlimit(RLIMIT_STACK, &rlim); 1063 stack_size = rlim.rlim_cur; 1064 1065 // 6308388: a bug in ld.so will relocate its own .data section to the 1066 // lower end of primordial stack; reduce ulimit -s value a little bit 1067 // so we won't install guard page on ld.so's data section. 1068 stack_size -= 2 * page_size(); 1069 1070 // 4441425: avoid crash with "unlimited" stack size on SuSE 7.1 or Redhat 1071 // 7.1, in both cases we will get 2G in return value. 1072 // 4466587: glibc 2.2.x compiled w/o "--enable-kernel=2.4.0" (RH 7.0, 1073 // SuSE 7.2, Debian) can not handle alternate signal stack correctly 1074 // for initial thread if its stack size exceeds 6M. Cap it at 2M, 1075 // in case other parts in glibc still assumes 2M max stack size. 1076 // FIXME: alt signal stack is gone, maybe we can relax this constraint? 1077 #ifndef IA64 1078 if (stack_size > 2 * K * K) stack_size = 2 * K * K; 1079 #else 1080 // Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small 1081 if (stack_size > 4 * K * K) stack_size = 4 * K * K; 1082 #endif 1083 1084 // Try to figure out where the stack base (top) is. This is harder. 1085 // 1086 // When an application is started, glibc saves the initial stack pointer in 1087 // a global variable "__libc_stack_end", which is then used by system 1088 // libraries. __libc_stack_end should be pretty close to stack top. The 1089 // variable is available since the very early days. However, because it is 1090 // a private interface, it could disappear in the future. 1091 // 1092 // Linux kernel saves start_stack information in /proc/<pid>/stat. Similar 1093 // to __libc_stack_end, it is very close to stack top, but isn't the real 1094 // stack top. Note that /proc may not exist if VM is running as a chroot 1095 // program, so reading /proc/<pid>/stat could fail. Also the contents of 1096 // /proc/<pid>/stat could change in the future (though unlikely). 1097 // 1098 // We try __libc_stack_end first. If that doesn't work, look for 1099 // /proc/<pid>/stat. If neither of them works, we use current stack pointer 1100 // as a hint, which should work well in most cases. 1101 1102 uintptr_t stack_start; 1103 1104 // try __libc_stack_end first 1105 uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end"); 1106 if (p && *p) { 1107 stack_start = *p; 1108 } else { 1109 // see if we can get the start_stack field from /proc/self/stat 1110 FILE *fp; 1111 int pid; 1112 char state; 1113 int ppid; 1114 int pgrp; 1115 int session; 1116 int nr; 1117 int tpgrp; 1118 unsigned long flags; 1119 unsigned long minflt; 1120 unsigned long cminflt; 1121 unsigned long majflt; 1122 unsigned long cmajflt; 1123 unsigned long utime; 1124 unsigned long stime; 1125 long cutime; 1126 long cstime; 1127 long prio; 1128 long nice; 1129 long junk; 1130 long it_real; 1131 uintptr_t start; 1132 uintptr_t vsize; 1133 uintptr_t rss; 1134 unsigned long rsslim; 1135 uintptr_t scodes; 1136 uintptr_t ecode; 1137 int i; 1138 1139 // Figure what the primordial thread stack base is. Code is inspired 1140 // by email from Hans Boehm. /proc/self/stat begins with current pid, 1141 // followed by command name surrounded by parentheses, state, etc. 1142 char stat[2048]; 1143 int statlen; 1144 1145 fp = fopen("/proc/self/stat", "r"); 1146 if (fp) { 1147 statlen = fread(stat, 1, 2047, fp); 1148 stat[statlen] = '\0'; 1149 fclose(fp); 1150 1151 // Skip pid and the command string. Note that we could be dealing with 1152 // weird command names, e.g. user could decide to rename java launcher 1153 // to "java 1.4.2 :)", then the stat file would look like 1154 // 1234 (java 1.4.2 :)) R ... ... 1155 // We don't really need to know the command string, just find the last 1156 // occurrence of ")" and then start parsing from there. See bug 4726580. 1157 char * s = strrchr(stat, ')'); 1158 1159 i = 0; 1160 if (s) { 1161 // Skip blank chars 1162 do s++; while (isspace(*s)); 1163 1164 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 */ 1165 /* 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 */ 1166 i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld %lu %lu %ld %lu %lu %lu %lu", 1167 &state, /* 3 %c */ 1168 &ppid, /* 4 %d */ 1169 &pgrp, /* 5 %d */ 1170 &session, /* 6 %d */ 1171 &nr, /* 7 %d */ 1172 &tpgrp, /* 8 %d */ 1173 &flags, /* 9 %lu */ 1174 &minflt, /* 10 %lu */ 1175 &cminflt, /* 11 %lu */ 1176 &majflt, /* 12 %lu */ 1177 &cmajflt, /* 13 %lu */ 1178 &utime, /* 14 %lu */ 1179 &stime, /* 15 %lu */ 1180 &cutime, /* 16 %ld */ 1181 &cstime, /* 17 %ld */ 1182 &prio, /* 18 %ld */ 1183 &nice, /* 19 %ld */ 1184 &junk, /* 20 %ld */ 1185 &it_real, /* 21 %ld */ 1186 &start, /* 22 %lu */ 1187 &vsize, /* 23 %lu */ 1188 &rss, /* 24 %ld */ 1189 &rsslim, /* 25 %lu */ 1190 &scodes, /* 26 %lu */ 1191 &ecode, /* 27 %lu */ 1192 &stack_start); /* 28 %lu */ 1193 } 1194 1195 if (i != 28 - 2) { 1196 assert(false, "Bad conversion from /proc/self/stat"); 1197 // product mode - assume we are the initial thread, good luck in the 1198 // embedded case. 1199 warning("Can't detect initial thread stack location - bad conversion"); 1200 stack_start = (uintptr_t) &rlim; 1201 } 1202 } else { 1203 // For some reason we can't open /proc/self/stat (for example, running on 1204 // FreeBSD with a Linux emulator, or inside chroot), this should work for 1205 // most cases, so don't abort: 1206 warning("Can't detect initial thread stack location - no /proc/self/stat"); 1207 stack_start = (uintptr_t) &rlim; 1208 } 1209 } 1210 1211 // Now we have a pointer (stack_start) very close to the stack top, the 1212 // next thing to do is to figure out the exact location of stack top. We 1213 // can find out the virtual memory area that contains stack_start by 1214 // reading /proc/self/maps, it should be the last vma in /proc/self/maps, 1215 // and its upper limit is the real stack top. (again, this would fail if 1216 // running inside chroot, because /proc may not exist.) 1217 1218 uintptr_t stack_top; 1219 address low, high; 1220 if (find_vma((address)stack_start, &low, &high)) { 1221 // success, "high" is the true stack top. (ignore "low", because initial 1222 // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.) 1223 stack_top = (uintptr_t)high; 1224 } else { 1225 // failed, likely because /proc/self/maps does not exist 1226 warning("Can't detect initial thread stack location - find_vma failed"); 1227 // best effort: stack_start is normally within a few pages below the real 1228 // stack top, use it as stack top, and reduce stack size so we won't put 1229 // guard page outside stack. 1230 stack_top = stack_start; 1231 stack_size -= 16 * page_size(); 1232 } 1233 1234 // stack_top could be partially down the page so align it 1235 stack_top = align_size_up(stack_top, page_size()); 1236 1237 if (max_size && stack_size > max_size) { 1238 _initial_thread_stack_size = max_size; 1239 } else { 1240 _initial_thread_stack_size = stack_size; 1241 } 1242 1243 _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size()); 1244 _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size; 1245 } 1246 1247 //////////////////////////////////////////////////////////////////////////////// 1248 // time support 1249 1250 // Time since start-up in seconds to a fine granularity. 1251 // Used by VMSelfDestructTimer and the MemProfiler. 1252 double os::elapsedTime() { 1253 1254 return (double)(os::elapsed_counter()) * 0.000001; 1255 } 1256 1257 jlong os::elapsed_counter() { 1258 timeval time; 1259 int status = gettimeofday(&time, NULL); 1260 return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count; 1261 } 1262 1263 jlong os::elapsed_frequency() { 1264 return (1000 * 1000); 1265 } 1266 1267 // For now, we say that linux does not support vtime. I have no idea 1268 // whether it can actually be made to (DLD, 9/13/05). 1269 1270 bool os::supports_vtime() { return false; } 1271 bool os::enable_vtime() { return false; } 1272 bool os::vtime_enabled() { return false; } 1273 double os::elapsedVTime() { 1274 // better than nothing, but not much 1275 return elapsedTime(); 1276 } 1277 1278 jlong os::javaTimeMillis() { 1279 timeval time; 1280 int status = gettimeofday(&time, NULL); 1281 assert(status != -1, "linux error"); 1282 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); 1283 } 1284 1285 #ifndef CLOCK_MONOTONIC 1286 #define CLOCK_MONOTONIC (1) 1287 #endif 1288 1289 void os::Linux::clock_init() { 1290 // we do dlopen's in this particular order due to bug in linux 1291 // dynamical loader (see 6348968) leading to crash on exit 1292 void* handle = dlopen("librt.so.1", RTLD_LAZY); 1293 if (handle == NULL) { 1294 handle = dlopen("librt.so", RTLD_LAZY); 1295 } 1296 1297 if (handle) { 1298 int (*clock_getres_func)(clockid_t, struct timespec*) = 1299 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres"); 1300 int (*clock_gettime_func)(clockid_t, struct timespec*) = 1301 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime"); 1302 if (clock_getres_func && clock_gettime_func) { 1303 // See if monotonic clock is supported by the kernel. Note that some 1304 // early implementations simply return kernel jiffies (updated every 1305 // 1/100 or 1/1000 second). It would be bad to use such a low res clock 1306 // for nano time (though the monotonic property is still nice to have). 1307 // It's fixed in newer kernels, however clock_getres() still returns 1308 // 1/HZ. We check if clock_getres() works, but will ignore its reported 1309 // resolution for now. Hopefully as people move to new kernels, this 1310 // won't be a problem. 1311 struct timespec res; 1312 struct timespec tp; 1313 if (clock_getres_func (CLOCK_MONOTONIC, &res) == 0 && 1314 clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) { 1315 // yes, monotonic clock is supported 1316 _clock_gettime = clock_gettime_func; 1317 } else { 1318 // close librt if there is no monotonic clock 1319 dlclose(handle); 1320 } 1321 } 1322 } 1323 } 1324 1325 #ifndef SYS_clock_getres 1326 1327 #if defined(IA32) || defined(AMD64) 1328 #define SYS_clock_getres IA32_ONLY(266) AMD64_ONLY(229) 1329 #else 1330 #error Value of SYS_clock_getres not known on this platform 1331 #endif 1332 1333 #endif 1334 1335 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) 1336 1337 void os::Linux::fast_thread_clock_init() { 1338 if (!UseLinuxPosixThreadCPUClocks) { 1339 return; 1340 } 1341 clockid_t clockid; 1342 struct timespec tp; 1343 int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) = 1344 (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid"); 1345 1346 // Switch to using fast clocks for thread cpu time if 1347 // the sys_clock_getres() returns 0 error code. 1348 // Note, that some kernels may support the current thread 1349 // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks 1350 // returned by the pthread_getcpuclockid(). 1351 // If the fast Posix clocks are supported then the sys_clock_getres() 1352 // must return at least tp.tv_sec == 0 which means a resolution 1353 // better than 1 sec. This is extra check for reliability. 1354 1355 if(pthread_getcpuclockid_func && 1356 pthread_getcpuclockid_func(_main_thread, &clockid) == 0 && 1357 sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) { 1358 1359 _supports_fast_thread_cpu_time = true; 1360 _pthread_getcpuclockid = pthread_getcpuclockid_func; 1361 } 1362 } 1363 1364 jlong os::javaTimeNanos() { 1365 if (Linux::supports_monotonic_clock()) { 1366 struct timespec tp; 1367 int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp); 1368 assert(status == 0, "gettime error"); 1369 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec); 1370 return result; 1371 } else { 1372 timeval time; 1373 int status = gettimeofday(&time, NULL); 1374 assert(status != -1, "linux error"); 1375 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec); 1376 return 1000 * usecs; 1377 } 1378 } 1379 1380 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { 1381 if (Linux::supports_monotonic_clock()) { 1382 info_ptr->max_value = ALL_64_BITS; 1383 1384 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past 1385 info_ptr->may_skip_backward = false; // not subject to resetting or drifting 1386 info_ptr->may_skip_forward = false; // not subject to resetting or drifting 1387 } else { 1388 // gettimeofday - based on time in seconds since the Epoch thus does not wrap 1389 info_ptr->max_value = ALL_64_BITS; 1390 1391 // gettimeofday is a real time clock so it skips 1392 info_ptr->may_skip_backward = true; 1393 info_ptr->may_skip_forward = true; 1394 } 1395 1396 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time 1397 } 1398 1399 // Return the real, user, and system times in seconds from an 1400 // arbitrary fixed point in the past. 1401 bool os::getTimesSecs(double* process_real_time, 1402 double* process_user_time, 1403 double* process_system_time) { 1404 struct tms ticks; 1405 clock_t real_ticks = times(&ticks); 1406 1407 if (real_ticks == (clock_t) (-1)) { 1408 return false; 1409 } else { 1410 double ticks_per_second = (double) clock_tics_per_sec; 1411 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second; 1412 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second; 1413 *process_real_time = ((double) real_ticks) / ticks_per_second; 1414 1415 return true; 1416 } 1417 } 1418 1419 1420 char * os::local_time_string(char *buf, size_t buflen) { 1421 struct tm t; 1422 time_t long_time; 1423 time(&long_time); 1424 localtime_r(&long_time, &t); 1425 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", 1426 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, 1427 t.tm_hour, t.tm_min, t.tm_sec); 1428 return buf; 1429 } 1430 1431 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { 1432 return localtime_r(clock, res); 1433 } 1434 1435 //////////////////////////////////////////////////////////////////////////////// 1436 // runtime exit support 1437 1438 // Note: os::shutdown() might be called very early during initialization, or 1439 // called from signal handler. Before adding something to os::shutdown(), make 1440 // sure it is async-safe and can handle partially initialized VM. 1441 void os::shutdown() { 1442 1443 // allow PerfMemory to attempt cleanup of any persistent resources 1444 perfMemory_exit(); 1445 1446 // needs to remove object in file system 1447 AttachListener::abort(); 1448 1449 // flush buffered output, finish log files 1450 ostream_abort(); 1451 1452 // Check for abort hook 1453 abort_hook_t abort_hook = Arguments::abort_hook(); 1454 if (abort_hook != NULL) { 1455 abort_hook(); 1456 } 1457 1458 } 1459 1460 // Note: os::abort() might be called very early during initialization, or 1461 // called from signal handler. Before adding something to os::abort(), make 1462 // sure it is async-safe and can handle partially initialized VM. 1463 void os::abort(bool dump_core) { 1464 os::shutdown(); 1465 if (dump_core) { 1466 #ifndef PRODUCT 1467 fdStream out(defaultStream::output_fd()); 1468 out.print_raw("Current thread is "); 1469 char buf[16]; 1470 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); 1471 out.print_raw_cr(buf); 1472 out.print_raw_cr("Dumping core ..."); 1473 #endif 1474 ::abort(); // dump core 1475 } 1476 1477 ::exit(1); 1478 } 1479 1480 // Die immediately, no exit hook, no abort hook, no cleanup. 1481 void os::die() { 1482 // _exit() on LinuxThreads only kills current thread 1483 ::abort(); 1484 } 1485 1486 // unused on linux for now. 1487 void os::set_error_file(const char *logfile) {} 1488 1489 intx os::current_thread_id() { return (intx)pthread_self(); } 1490 int os::current_process_id() { 1491 1492 // Under the old linux thread library, linux gives each thread 1493 // its own process id. Because of this each thread will return 1494 // a different pid if this method were to return the result 1495 // of getpid(2). Linux provides no api that returns the pid 1496 // of the launcher thread for the vm. This implementation 1497 // returns a unique pid, the pid of the launcher thread 1498 // that starts the vm 'process'. 1499 1500 // Under the NPTL, getpid() returns the same pid as the 1501 // launcher thread rather than a unique pid per thread. 1502 // Use gettid() if you want the old pre NPTL behaviour. 1503 1504 // if you are looking for the result of a call to getpid() that 1505 // returns a unique pid for the calling thread, then look at the 1506 // OSThread::thread_id() method in osThread_linux.hpp file 1507 1508 return (int)(_initial_pid ? _initial_pid : getpid()); 1509 } 1510 1511 // DLL functions 1512 1513 const char* os::dll_file_extension() { return ".so"; } 1514 1515 const char* os::get_temp_directory() { return "/tmp/"; } 1516 1517 static bool file_exists(const char* filename) { 1518 struct stat statbuf; 1519 if (filename == NULL || strlen(filename) == 0) { 1520 return false; 1521 } 1522 return os::stat(filename, &statbuf) == 0; 1523 } 1524 1525 void os::dll_build_name(char* buffer, size_t buflen, 1526 const char* pname, const char* fname) { 1527 // Copied from libhpi 1528 const size_t pnamelen = pname ? strlen(pname) : 0; 1529 1530 // Quietly truncate on buffer overflow. Should be an error. 1531 if (pnamelen + strlen(fname) + 10 > (size_t) buflen) { 1532 *buffer = '\0'; 1533 return; 1534 } 1535 1536 if (pnamelen == 0) { 1537 snprintf(buffer, buflen, "lib%s.so", fname); 1538 } else if (strchr(pname, *os::path_separator()) != NULL) { 1539 int n; 1540 char** pelements = split_path(pname, &n); 1541 for (int i = 0 ; i < n ; i++) { 1542 // Really shouldn't be NULL, but check can't hurt 1543 if (pelements[i] == NULL || strlen(pelements[i]) == 0) { 1544 continue; // skip the empty path values 1545 } 1546 snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname); 1547 if (file_exists(buffer)) { 1548 break; 1549 } 1550 } 1551 // release the storage 1552 for (int i = 0 ; i < n ; i++) { 1553 if (pelements[i] != NULL) { 1554 FREE_C_HEAP_ARRAY(char, pelements[i]); 1555 } 1556 } 1557 if (pelements != NULL) { 1558 FREE_C_HEAP_ARRAY(char*, pelements); 1559 } 1560 } else { 1561 snprintf(buffer, buflen, "%s/lib%s.so", pname, fname); 1562 } 1563 } 1564 1565 const char* os::get_current_directory(char *buf, int buflen) { 1566 return getcwd(buf, buflen); 1567 } 1568 1569 // check if addr is inside libjvm[_g].so 1570 bool os::address_is_in_vm(address addr) { 1571 static address libjvm_base_addr; 1572 Dl_info dlinfo; 1573 1574 if (libjvm_base_addr == NULL) { 1575 dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo); 1576 libjvm_base_addr = (address)dlinfo.dli_fbase; 1577 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); 1578 } 1579 1580 if (dladdr((void *)addr, &dlinfo)) { 1581 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; 1582 } 1583 1584 return false; 1585 } 1586 1587 bool os::dll_address_to_function_name(address addr, char *buf, 1588 int buflen, int *offset) { 1589 Dl_info dlinfo; 1590 1591 if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) { 1592 if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); 1593 if (offset) *offset = addr - (address)dlinfo.dli_saddr; 1594 return true; 1595 } else { 1596 if (buf) buf[0] = '\0'; 1597 if (offset) *offset = -1; 1598 return false; 1599 } 1600 } 1601 1602 struct _address_to_library_name { 1603 address addr; // input : memory address 1604 size_t buflen; // size of fname 1605 char* fname; // output: library name 1606 address base; // library base addr 1607 }; 1608 1609 static int address_to_library_name_callback(struct dl_phdr_info *info, 1610 size_t size, void *data) { 1611 int i; 1612 bool found = false; 1613 address libbase = NULL; 1614 struct _address_to_library_name * d = (struct _address_to_library_name *)data; 1615 1616 // iterate through all loadable segments 1617 for (i = 0; i < info->dlpi_phnum; i++) { 1618 address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr); 1619 if (info->dlpi_phdr[i].p_type == PT_LOAD) { 1620 // base address of a library is the lowest address of its loaded 1621 // segments. 1622 if (libbase == NULL || libbase > segbase) { 1623 libbase = segbase; 1624 } 1625 // see if 'addr' is within current segment 1626 if (segbase <= d->addr && 1627 d->addr < segbase + info->dlpi_phdr[i].p_memsz) { 1628 found = true; 1629 } 1630 } 1631 } 1632 1633 // dlpi_name is NULL or empty if the ELF file is executable, return 0 1634 // so dll_address_to_library_name() can fall through to use dladdr() which 1635 // can figure out executable name from argv[0]. 1636 if (found && info->dlpi_name && info->dlpi_name[0]) { 1637 d->base = libbase; 1638 if (d->fname) { 1639 jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name); 1640 } 1641 return 1; 1642 } 1643 return 0; 1644 } 1645 1646 bool os::dll_address_to_library_name(address addr, char* buf, 1647 int buflen, int* offset) { 1648 Dl_info dlinfo; 1649 struct _address_to_library_name data; 1650 1651 // There is a bug in old glibc dladdr() implementation that it could resolve 1652 // to wrong library name if the .so file has a base address != NULL. Here 1653 // we iterate through the program headers of all loaded libraries to find 1654 // out which library 'addr' really belongs to. This workaround can be 1655 // removed once the minimum requirement for glibc is moved to 2.3.x. 1656 data.addr = addr; 1657 data.fname = buf; 1658 data.buflen = buflen; 1659 data.base = NULL; 1660 int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data); 1661 1662 if (rslt) { 1663 // buf already contains library name 1664 if (offset) *offset = addr - data.base; 1665 return true; 1666 } else if (dladdr((void*)addr, &dlinfo)){ 1667 if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); 1668 if (offset) *offset = addr - (address)dlinfo.dli_fbase; 1669 return true; 1670 } else { 1671 if (buf) buf[0] = '\0'; 1672 if (offset) *offset = -1; 1673 return false; 1674 } 1675 } 1676 1677 // Loads .dll/.so and 1678 // in case of error it checks if .dll/.so was built for the 1679 // same architecture as Hotspot is running on 1680 1681 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) 1682 { 1683 void * result= ::dlopen(filename, RTLD_LAZY); 1684 if (result != NULL) { 1685 // Successful loading 1686 return result; 1687 } 1688 1689 Elf32_Ehdr elf_head; 1690 1691 // Read system error message into ebuf 1692 // It may or may not be overwritten below 1693 ::strncpy(ebuf, ::dlerror(), ebuflen-1); 1694 ebuf[ebuflen-1]='\0'; 1695 int diag_msg_max_length=ebuflen-strlen(ebuf); 1696 char* diag_msg_buf=ebuf+strlen(ebuf); 1697 1698 if (diag_msg_max_length==0) { 1699 // No more space in ebuf for additional diagnostics message 1700 return NULL; 1701 } 1702 1703 1704 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK); 1705 1706 if (file_descriptor < 0) { 1707 // Can't open library, report dlerror() message 1708 return NULL; 1709 } 1710 1711 bool failed_to_read_elf_head= 1712 (sizeof(elf_head)!= 1713 (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ; 1714 1715 ::close(file_descriptor); 1716 if (failed_to_read_elf_head) { 1717 // file i/o error - report dlerror() msg 1718 return NULL; 1719 } 1720 1721 typedef struct { 1722 Elf32_Half code; // Actual value as defined in elf.h 1723 Elf32_Half compat_class; // Compatibility of archs at VM's sense 1724 char elf_class; // 32 or 64 bit 1725 char endianess; // MSB or LSB 1726 char* name; // String representation 1727 } arch_t; 1728 1729 #ifndef EM_486 1730 #define EM_486 6 /* Intel 80486 */ 1731 #endif 1732 1733 static const arch_t arch_array[]={ 1734 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1735 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1736 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"}, 1737 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"}, 1738 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1739 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1740 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"}, 1741 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"}, 1742 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"} 1743 }; 1744 1745 #if (defined IA32) 1746 static Elf32_Half running_arch_code=EM_386; 1747 #elif (defined AMD64) 1748 static Elf32_Half running_arch_code=EM_X86_64; 1749 #elif (defined IA64) 1750 static Elf32_Half running_arch_code=EM_IA_64; 1751 #elif (defined __sparc) && (defined _LP64) 1752 static Elf32_Half running_arch_code=EM_SPARCV9; 1753 #elif (defined __sparc) && (!defined _LP64) 1754 static Elf32_Half running_arch_code=EM_SPARC; 1755 #elif (defined __powerpc64__) 1756 static Elf32_Half running_arch_code=EM_PPC64; 1757 #elif (defined __powerpc__) 1758 static Elf32_Half running_arch_code=EM_PPC; 1759 #else 1760 #error Method os::dll_load requires that one of following is defined:\ 1761 IA32, AMD64, IA64, __sparc, __powerpc__ 1762 #endif 1763 1764 // Identify compatability class for VM's architecture and library's architecture 1765 // Obtain string descriptions for architectures 1766 1767 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; 1768 int running_arch_index=-1; 1769 1770 for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) { 1771 if (running_arch_code == arch_array[i].code) { 1772 running_arch_index = i; 1773 } 1774 if (lib_arch.code == arch_array[i].code) { 1775 lib_arch.compat_class = arch_array[i].compat_class; 1776 lib_arch.name = arch_array[i].name; 1777 } 1778 } 1779 1780 assert(running_arch_index != -1, 1781 "Didn't find running architecture code (running_arch_code) in arch_array"); 1782 if (running_arch_index == -1) { 1783 // Even though running architecture detection failed 1784 // we may still continue with reporting dlerror() message 1785 return NULL; 1786 } 1787 1788 if (lib_arch.endianess != arch_array[running_arch_index].endianess) { 1789 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)"); 1790 return NULL; 1791 } 1792 1793 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) { 1794 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)"); 1795 return NULL; 1796 } 1797 1798 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { 1799 if ( lib_arch.name!=NULL ) { 1800 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1801 " (Possible cause: can't load %s-bit .so on a %s-bit platform)", 1802 lib_arch.name, arch_array[running_arch_index].name); 1803 } else { 1804 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1805 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)", 1806 lib_arch.code, 1807 arch_array[running_arch_index].name); 1808 } 1809 } 1810 1811 return NULL; 1812 } 1813 1814 /* 1815 * glibc-2.0 libdl is not MT safe. If you are building with any glibc, 1816 * chances are you might want to run the generated bits against glibc-2.0 1817 * libdl.so, so always use locking for any version of glibc. 1818 */ 1819 void* os::dll_lookup(void* handle, const char* name) { 1820 pthread_mutex_lock(&dl_mutex); 1821 void* res = dlsym(handle, name); 1822 pthread_mutex_unlock(&dl_mutex); 1823 return res; 1824 } 1825 1826 1827 bool _print_ascii_file(const char* filename, outputStream* st) { 1828 int fd = open(filename, O_RDONLY); 1829 if (fd == -1) { 1830 return false; 1831 } 1832 1833 char buf[32]; 1834 int bytes; 1835 while ((bytes = read(fd, buf, sizeof(buf))) > 0) { 1836 st->print_raw(buf, bytes); 1837 } 1838 1839 close(fd); 1840 1841 return true; 1842 } 1843 1844 void os::print_dll_info(outputStream *st) { 1845 st->print_cr("Dynamic libraries:"); 1846 1847 char fname[32]; 1848 pid_t pid = os::Linux::gettid(); 1849 1850 jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid); 1851 1852 if (!_print_ascii_file(fname, st)) { 1853 st->print("Can not get library information for pid = %d\n", pid); 1854 } 1855 } 1856 1857 1858 void os::print_os_info(outputStream* st) { 1859 st->print("OS:"); 1860 1861 // Try to identify popular distros. 1862 // Most Linux distributions have /etc/XXX-release file, which contains 1863 // the OS version string. Some have more than one /etc/XXX-release file 1864 // (e.g. Mandrake has both /etc/mandrake-release and /etc/redhat-release.), 1865 // so the order is important. 1866 if (!_print_ascii_file("/etc/mandrake-release", st) && 1867 !_print_ascii_file("/etc/sun-release", st) && 1868 !_print_ascii_file("/etc/redhat-release", st) && 1869 !_print_ascii_file("/etc/SuSE-release", st) && 1870 !_print_ascii_file("/etc/turbolinux-release", st) && 1871 !_print_ascii_file("/etc/gentoo-release", st) && 1872 !_print_ascii_file("/etc/debian_version", st)) { 1873 st->print("Linux"); 1874 } 1875 st->cr(); 1876 1877 // kernel 1878 st->print("uname:"); 1879 struct utsname name; 1880 uname(&name); 1881 st->print(name.sysname); st->print(" "); 1882 st->print(name.release); st->print(" "); 1883 st->print(name.version); st->print(" "); 1884 st->print(name.machine); 1885 st->cr(); 1886 1887 // Print warning if unsafe chroot environment detected 1888 if (unsafe_chroot_detected) { 1889 st->print("WARNING!! "); 1890 st->print_cr(unstable_chroot_error); 1891 } 1892 1893 // libc, pthread 1894 st->print("libc:"); 1895 st->print(os::Linux::glibc_version()); st->print(" "); 1896 st->print(os::Linux::libpthread_version()); st->print(" "); 1897 if (os::Linux::is_LinuxThreads()) { 1898 st->print("(%s stack)", os::Linux::is_floating_stack() ? "floating" : "fixed"); 1899 } 1900 st->cr(); 1901 1902 // rlimit 1903 st->print("rlimit:"); 1904 struct rlimit rlim; 1905 1906 st->print(" STACK "); 1907 getrlimit(RLIMIT_STACK, &rlim); 1908 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 1909 else st->print("%uk", rlim.rlim_cur >> 10); 1910 1911 st->print(", CORE "); 1912 getrlimit(RLIMIT_CORE, &rlim); 1913 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 1914 else st->print("%uk", rlim.rlim_cur >> 10); 1915 1916 st->print(", NPROC "); 1917 getrlimit(RLIMIT_NPROC, &rlim); 1918 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 1919 else st->print("%d", rlim.rlim_cur); 1920 1921 st->print(", NOFILE "); 1922 getrlimit(RLIMIT_NOFILE, &rlim); 1923 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 1924 else st->print("%d", rlim.rlim_cur); 1925 1926 st->print(", AS "); 1927 getrlimit(RLIMIT_AS, &rlim); 1928 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 1929 else st->print("%uk", rlim.rlim_cur >> 10); 1930 st->cr(); 1931 1932 // load average 1933 st->print("load average:"); 1934 double loadavg[3]; 1935 os::loadavg(loadavg, 3); 1936 st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]); 1937 st->cr(); 1938 } 1939 1940 void os::print_memory_info(outputStream* st) { 1941 1942 st->print("Memory:"); 1943 st->print(" %dk page", os::vm_page_size()>>10); 1944 1945 // values in struct sysinfo are "unsigned long" 1946 struct sysinfo si; 1947 sysinfo(&si); 1948 1949 st->print(", physical " UINT64_FORMAT "k", 1950 os::physical_memory() >> 10); 1951 st->print("(" UINT64_FORMAT "k free)", 1952 os::available_memory() >> 10); 1953 st->print(", swap " UINT64_FORMAT "k", 1954 ((jlong)si.totalswap * si.mem_unit) >> 10); 1955 st->print("(" UINT64_FORMAT "k free)", 1956 ((jlong)si.freeswap * si.mem_unit) >> 10); 1957 st->cr(); 1958 } 1959 1960 // Taken from /usr/include/bits/siginfo.h Supposed to be architecture specific 1961 // but they're the same for all the linux arch that we support 1962 // and they're the same for solaris but there's no common place to put this. 1963 const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR", 1964 "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG", 1965 "ILL_COPROC", "ILL_BADSTK" }; 1966 1967 const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV", 1968 "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES", 1969 "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" }; 1970 1971 const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" }; 1972 1973 const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" }; 1974 1975 void os::print_siginfo(outputStream* st, void* siginfo) { 1976 st->print("siginfo:"); 1977 1978 const int buflen = 100; 1979 char buf[buflen]; 1980 siginfo_t *si = (siginfo_t*)siginfo; 1981 st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen)); 1982 if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) { 1983 st->print("si_errno=%s", buf); 1984 } else { 1985 st->print("si_errno=%d", si->si_errno); 1986 } 1987 const int c = si->si_code; 1988 assert(c > 0, "unexpected si_code"); 1989 switch (si->si_signo) { 1990 case SIGILL: 1991 st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]); 1992 st->print(", si_addr=" PTR_FORMAT, si->si_addr); 1993 break; 1994 case SIGFPE: 1995 st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]); 1996 st->print(", si_addr=" PTR_FORMAT, si->si_addr); 1997 break; 1998 case SIGSEGV: 1999 st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]); 2000 st->print(", si_addr=" PTR_FORMAT, si->si_addr); 2001 break; 2002 case SIGBUS: 2003 st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]); 2004 st->print(", si_addr=" PTR_FORMAT, si->si_addr); 2005 break; 2006 default: 2007 st->print(", si_code=%d", si->si_code); 2008 // no si_addr 2009 } 2010 2011 if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) && 2012 UseSharedSpaces) { 2013 FileMapInfo* mapinfo = FileMapInfo::current_info(); 2014 if (mapinfo->is_in_shared_space(si->si_addr)) { 2015 st->print("\n\nError accessing class data sharing archive." \ 2016 " Mapped file inaccessible during execution, " \ 2017 " possible disk/network problem."); 2018 } 2019 } 2020 st->cr(); 2021 } 2022 2023 2024 static void print_signal_handler(outputStream* st, int sig, 2025 char* buf, size_t buflen); 2026 2027 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { 2028 st->print_cr("Signal Handlers:"); 2029 print_signal_handler(st, SIGSEGV, buf, buflen); 2030 print_signal_handler(st, SIGBUS , buf, buflen); 2031 print_signal_handler(st, SIGFPE , buf, buflen); 2032 print_signal_handler(st, SIGPIPE, buf, buflen); 2033 print_signal_handler(st, SIGXFSZ, buf, buflen); 2034 print_signal_handler(st, SIGILL , buf, buflen); 2035 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen); 2036 print_signal_handler(st, SR_signum, buf, buflen); 2037 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen); 2038 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); 2039 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen); 2040 print_signal_handler(st, BREAK_SIGNAL, buf, buflen); 2041 } 2042 2043 static char saved_jvm_path[MAXPATHLEN] = {0}; 2044 2045 // Find the full path to the current module, libjvm.so or libjvm_g.so 2046 void os::jvm_path(char *buf, jint len) { 2047 // Error checking. 2048 if (len < MAXPATHLEN) { 2049 assert(false, "must use a large-enough buffer"); 2050 buf[0] = '\0'; 2051 return; 2052 } 2053 // Lazy resolve the path to current module. 2054 if (saved_jvm_path[0] != 0) { 2055 strcpy(buf, saved_jvm_path); 2056 return; 2057 } 2058 2059 char dli_fname[MAXPATHLEN]; 2060 bool ret = dll_address_to_library_name( 2061 CAST_FROM_FN_PTR(address, os::jvm_path), 2062 dli_fname, sizeof(dli_fname), NULL); 2063 assert(ret != 0, "cannot locate libjvm"); 2064 realpath(dli_fname, buf); 2065 2066 if (strcmp(Arguments::sun_java_launcher(), "gamma") == 0) { 2067 // Support for the gamma launcher. Typical value for buf is 2068 // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so". If "/jre/lib/" appears at 2069 // the right place in the string, then assume we are installed in a JDK and 2070 // we're done. Otherwise, check for a JAVA_HOME environment variable and fix 2071 // up the path so it looks like libjvm.so is installed there (append a 2072 // fake suffix hotspot/libjvm.so). 2073 const char *p = buf + strlen(buf) - 1; 2074 for (int count = 0; p > buf && count < 5; ++count) { 2075 for (--p; p > buf && *p != '/'; --p) 2076 /* empty */ ; 2077 } 2078 2079 if (strncmp(p, "/jre/lib/", 9) != 0) { 2080 // Look for JAVA_HOME in the environment. 2081 char* java_home_var = ::getenv("JAVA_HOME"); 2082 if (java_home_var != NULL && java_home_var[0] != 0) { 2083 // Check the current module name "libjvm.so" or "libjvm_g.so". 2084 p = strrchr(buf, '/'); 2085 assert(strstr(p, "/libjvm") == p, "invalid library name"); 2086 p = strstr(p, "_g") ? "_g" : ""; 2087 2088 realpath(java_home_var, buf); 2089 sprintf(buf + strlen(buf), "/jre/lib/%s", cpu_arch); 2090 if (0 == access(buf, F_OK)) { 2091 // Use current module name "libjvm[_g].so" instead of 2092 // "libjvm"debug_only("_g")".so" since for fastdebug version 2093 // we should have "libjvm.so" but debug_only("_g") adds "_g"! 2094 // It is used when we are choosing the HPI library's name 2095 // "libhpi[_g].so" in hpi::initialize_get_interface(). 2096 sprintf(buf + strlen(buf), "/hotspot/libjvm%s.so", p); 2097 } else { 2098 // Go back to path of .so 2099 realpath(dli_fname, buf); 2100 } 2101 } 2102 } 2103 } 2104 2105 strcpy(saved_jvm_path, buf); 2106 } 2107 2108 void os::print_jni_name_prefix_on(outputStream* st, int args_size) { 2109 // no prefix required, not even "_" 2110 } 2111 2112 void os::print_jni_name_suffix_on(outputStream* st, int args_size) { 2113 // no suffix required 2114 } 2115 2116 //////////////////////////////////////////////////////////////////////////////// 2117 // sun.misc.Signal support 2118 2119 static volatile jint sigint_count = 0; 2120 2121 static void 2122 UserHandler(int sig, void *siginfo, void *context) { 2123 // 4511530 - sem_post is serialized and handled by the manager thread. When 2124 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We 2125 // don't want to flood the manager thread with sem_post requests. 2126 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) 2127 return; 2128 2129 // Ctrl-C is pressed during error reporting, likely because the error 2130 // handler fails to abort. Let VM die immediately. 2131 if (sig == SIGINT && is_error_reported()) { 2132 os::die(); 2133 } 2134 2135 os::signal_notify(sig); 2136 } 2137 2138 void* os::user_handler() { 2139 return CAST_FROM_FN_PTR(void*, UserHandler); 2140 } 2141 2142 extern "C" { 2143 typedef void (*sa_handler_t)(int); 2144 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); 2145 } 2146 2147 void* os::signal(int signal_number, void* handler) { 2148 struct sigaction sigAct, oldSigAct; 2149 2150 sigfillset(&(sigAct.sa_mask)); 2151 sigAct.sa_flags = SA_RESTART|SA_SIGINFO; 2152 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); 2153 2154 if (sigaction(signal_number, &sigAct, &oldSigAct)) { 2155 // -1 means registration failed 2156 return (void *)-1; 2157 } 2158 2159 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); 2160 } 2161 2162 void os::signal_raise(int signal_number) { 2163 ::raise(signal_number); 2164 } 2165 2166 /* 2167 * The following code is moved from os.cpp for making this 2168 * code platform specific, which it is by its very nature. 2169 */ 2170 2171 // Will be modified when max signal is changed to be dynamic 2172 int os::sigexitnum_pd() { 2173 return NSIG; 2174 } 2175 2176 // a counter for each possible signal value 2177 static volatile jint pending_signals[NSIG+1] = { 0 }; 2178 2179 // Linux(POSIX) specific hand shaking semaphore. 2180 static sem_t sig_sem; 2181 2182 void os::signal_init_pd() { 2183 // Initialize signal structures 2184 ::memset((void*)pending_signals, 0, sizeof(pending_signals)); 2185 2186 // Initialize signal semaphore 2187 ::sem_init(&sig_sem, 0, 0); 2188 } 2189 2190 void os::signal_notify(int sig) { 2191 Atomic::inc(&pending_signals[sig]); 2192 ::sem_post(&sig_sem); 2193 } 2194 2195 static int check_pending_signals(bool wait) { 2196 Atomic::store(0, &sigint_count); 2197 for (;;) { 2198 for (int i = 0; i < NSIG + 1; i++) { 2199 jint n = pending_signals[i]; 2200 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { 2201 return i; 2202 } 2203 } 2204 if (!wait) { 2205 return -1; 2206 } 2207 JavaThread *thread = JavaThread::current(); 2208 ThreadBlockInVM tbivm(thread); 2209 2210 bool threadIsSuspended; 2211 do { 2212 thread->set_suspend_equivalent(); 2213 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 2214 ::sem_wait(&sig_sem); 2215 2216 // were we externally suspended while we were waiting? 2217 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); 2218 if (threadIsSuspended) { 2219 // 2220 // The semaphore has been incremented, but while we were waiting 2221 // another thread suspended us. We don't want to continue running 2222 // while suspended because that would surprise the thread that 2223 // suspended us. 2224 // 2225 ::sem_post(&sig_sem); 2226 2227 thread->java_suspend_self(); 2228 } 2229 } while (threadIsSuspended); 2230 } 2231 } 2232 2233 int os::signal_lookup() { 2234 return check_pending_signals(false); 2235 } 2236 2237 int os::signal_wait() { 2238 return check_pending_signals(true); 2239 } 2240 2241 //////////////////////////////////////////////////////////////////////////////// 2242 // Virtual Memory 2243 2244 int os::vm_page_size() { 2245 // Seems redundant as all get out 2246 assert(os::Linux::page_size() != -1, "must call os::init"); 2247 return os::Linux::page_size(); 2248 } 2249 2250 // Solaris allocates memory by pages. 2251 int os::vm_allocation_granularity() { 2252 assert(os::Linux::page_size() != -1, "must call os::init"); 2253 return os::Linux::page_size(); 2254 } 2255 2256 // Rationale behind this function: 2257 // current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable 2258 // mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get 2259 // samples for JITted code. Here we create private executable mapping over the code cache 2260 // and then we can use standard (well, almost, as mapping can change) way to provide 2261 // info for the reporting script by storing timestamp and location of symbol 2262 void linux_wrap_code(char* base, size_t size) { 2263 static volatile jint cnt = 0; 2264 2265 if (!UseOprofile) { 2266 return; 2267 } 2268 2269 char buf[40]; 2270 int num = Atomic::add(1, &cnt); 2271 2272 sprintf(buf, "/tmp/hs-vm-%d-%d", os::current_process_id(), num); 2273 unlink(buf); 2274 2275 int fd = open(buf, O_CREAT | O_RDWR, S_IRWXU); 2276 2277 if (fd != -1) { 2278 off_t rv = lseek(fd, size-2, SEEK_SET); 2279 if (rv != (off_t)-1) { 2280 if (write(fd, "", 1) == 1) { 2281 mmap(base, size, 2282 PROT_READ|PROT_WRITE|PROT_EXEC, 2283 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0); 2284 } 2285 } 2286 close(fd); 2287 unlink(buf); 2288 } 2289 } 2290 2291 // NOTE: Linux kernel does not really reserve the pages for us. 2292 // All it does is to check if there are enough free pages 2293 // left at the time of mmap(). This could be a potential 2294 // problem. 2295 bool os::commit_memory(char* addr, size_t size) { 2296 uintptr_t res = (uintptr_t) ::mmap(addr, size, 2297 PROT_READ|PROT_WRITE|PROT_EXEC, 2298 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0); 2299 return res != (uintptr_t) MAP_FAILED; 2300 } 2301 2302 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint) { 2303 return commit_memory(addr, size); 2304 } 2305 2306 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) { } 2307 2308 void os::free_memory(char *addr, size_t bytes) { 2309 uncommit_memory(addr, bytes); 2310 } 2311 2312 void os::numa_make_global(char *addr, size_t bytes) { 2313 Linux::numa_interleave_memory(addr, bytes); 2314 } 2315 2316 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { 2317 Linux::numa_tonode_memory(addr, bytes, lgrp_hint); 2318 } 2319 2320 bool os::numa_topology_changed() { return false; } 2321 2322 size_t os::numa_get_groups_num() { 2323 int max_node = Linux::numa_max_node(); 2324 return max_node > 0 ? max_node + 1 : 1; 2325 } 2326 2327 int os::numa_get_group_id() { 2328 int cpu_id = Linux::sched_getcpu(); 2329 if (cpu_id != -1) { 2330 int lgrp_id = Linux::get_node_by_cpu(cpu_id); 2331 if (lgrp_id != -1) { 2332 return lgrp_id; 2333 } 2334 } 2335 return 0; 2336 } 2337 2338 size_t os::numa_get_leaf_groups(int *ids, size_t size) { 2339 for (size_t i = 0; i < size; i++) { 2340 ids[i] = i; 2341 } 2342 return size; 2343 } 2344 2345 bool os::get_page_info(char *start, page_info* info) { 2346 return false; 2347 } 2348 2349 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) { 2350 return end; 2351 } 2352 2353 extern "C" void numa_warn(int number, char *where, ...) { } 2354 extern "C" void numa_error(char *where) { } 2355 2356 bool os::Linux::libnuma_init() { 2357 // sched_getcpu() should be in libc. 2358 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, 2359 dlsym(RTLD_DEFAULT, "sched_getcpu"))); 2360 2361 if (sched_getcpu() != -1) { // Does it work? 2362 void *handle = dlopen("libnuma.so.1", RTLD_LAZY); 2363 if (handle != NULL) { 2364 set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t, 2365 dlsym(handle, "numa_node_to_cpus"))); 2366 set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t, 2367 dlsym(handle, "numa_max_node"))); 2368 set_numa_available(CAST_TO_FN_PTR(numa_available_func_t, 2369 dlsym(handle, "numa_available"))); 2370 set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t, 2371 dlsym(handle, "numa_tonode_memory"))); 2372 set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t, 2373 dlsym(handle, "numa_interleave_memory"))); 2374 2375 2376 if (numa_available() != -1) { 2377 set_numa_all_nodes((unsigned long*)dlsym(handle, "numa_all_nodes")); 2378 // Create a cpu -> node mapping 2379 _cpu_to_node = new (ResourceObj::C_HEAP) GrowableArray<int>(0, true); 2380 rebuild_cpu_to_node_map(); 2381 return true; 2382 } 2383 } 2384 } 2385 return false; 2386 } 2387 2388 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id. 2389 // The table is later used in get_node_by_cpu(). 2390 void os::Linux::rebuild_cpu_to_node_map() { 2391 const size_t NCPUS = 32768; // Since the buffer size computation is very obscure 2392 // in libnuma (possible values are starting from 16, 2393 // and continuing up with every other power of 2, but less 2394 // than the maximum number of CPUs supported by kernel), and 2395 // is a subject to change (in libnuma version 2 the requirements 2396 // are more reasonable) we'll just hardcode the number they use 2397 // in the library. 2398 const size_t BitsPerCLong = sizeof(long) * CHAR_BIT; 2399 2400 size_t cpu_num = os::active_processor_count(); 2401 size_t cpu_map_size = NCPUS / BitsPerCLong; 2402 size_t cpu_map_valid_size = 2403 MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size); 2404 2405 cpu_to_node()->clear(); 2406 cpu_to_node()->at_grow(cpu_num - 1); 2407 size_t node_num = numa_get_groups_num(); 2408 2409 unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size); 2410 for (size_t i = 0; i < node_num; i++) { 2411 if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) { 2412 for (size_t j = 0; j < cpu_map_valid_size; j++) { 2413 if (cpu_map[j] != 0) { 2414 for (size_t k = 0; k < BitsPerCLong; k++) { 2415 if (cpu_map[j] & (1UL << k)) { 2416 cpu_to_node()->at_put(j * BitsPerCLong + k, i); 2417 } 2418 } 2419 } 2420 } 2421 } 2422 } 2423 FREE_C_HEAP_ARRAY(unsigned long, cpu_map); 2424 } 2425 2426 int os::Linux::get_node_by_cpu(int cpu_id) { 2427 if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) { 2428 return cpu_to_node()->at(cpu_id); 2429 } 2430 return -1; 2431 } 2432 2433 GrowableArray<int>* os::Linux::_cpu_to_node; 2434 os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu; 2435 os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus; 2436 os::Linux::numa_max_node_func_t os::Linux::_numa_max_node; 2437 os::Linux::numa_available_func_t os::Linux::_numa_available; 2438 os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory; 2439 os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory; 2440 unsigned long* os::Linux::_numa_all_nodes; 2441 2442 bool os::uncommit_memory(char* addr, size_t size) { 2443 return ::mmap(addr, size, 2444 PROT_READ|PROT_WRITE|PROT_EXEC, 2445 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0) 2446 != MAP_FAILED; 2447 } 2448 2449 static address _highest_vm_reserved_address = NULL; 2450 2451 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory 2452 // at 'requested_addr'. If there are existing memory mappings at the same 2453 // location, however, they will be overwritten. If 'fixed' is false, 2454 // 'requested_addr' is only treated as a hint, the return value may or 2455 // may not start from the requested address. Unlike Linux mmap(), this 2456 // function returns NULL to indicate failure. 2457 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) { 2458 char * addr; 2459 int flags; 2460 2461 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS; 2462 if (fixed) { 2463 assert((uintptr_t)requested_addr % os::Linux::page_size() == 0, "unaligned address"); 2464 flags |= MAP_FIXED; 2465 } 2466 2467 addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE|PROT_EXEC, 2468 flags, -1, 0); 2469 2470 if (addr != MAP_FAILED) { 2471 // anon_mmap() should only get called during VM initialization, 2472 // don't need lock (actually we can skip locking even it can be called 2473 // from multiple threads, because _highest_vm_reserved_address is just a 2474 // hint about the upper limit of non-stack memory regions.) 2475 if ((address)addr + bytes > _highest_vm_reserved_address) { 2476 _highest_vm_reserved_address = (address)addr + bytes; 2477 } 2478 } 2479 2480 return addr == MAP_FAILED ? NULL : addr; 2481 } 2482 2483 // Don't update _highest_vm_reserved_address, because there might be memory 2484 // regions above addr + size. If so, releasing a memory region only creates 2485 // a hole in the address space, it doesn't help prevent heap-stack collision. 2486 // 2487 static int anon_munmap(char * addr, size_t size) { 2488 return ::munmap(addr, size) == 0; 2489 } 2490 2491 char* os::reserve_memory(size_t bytes, char* requested_addr, 2492 size_t alignment_hint) { 2493 return anon_mmap(requested_addr, bytes, (requested_addr != NULL)); 2494 } 2495 2496 bool os::release_memory(char* addr, size_t size) { 2497 return anon_munmap(addr, size); 2498 } 2499 2500 static address highest_vm_reserved_address() { 2501 return _highest_vm_reserved_address; 2502 } 2503 2504 static bool linux_mprotect(char* addr, size_t size, int prot) { 2505 // Linux wants the mprotect address argument to be page aligned. 2506 char* bottom = (char*)align_size_down((intptr_t)addr, os::Linux::page_size()); 2507 2508 // According to SUSv3, mprotect() should only be used with mappings 2509 // established by mmap(), and mmap() always maps whole pages. Unaligned 2510 // 'addr' likely indicates problem in the VM (e.g. trying to change 2511 // protection of malloc'ed or statically allocated memory). Check the 2512 // caller if you hit this assert. 2513 assert(addr == bottom, "sanity check"); 2514 2515 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size()); 2516 return ::mprotect(bottom, size, prot) == 0; 2517 } 2518 2519 // Set protections specified 2520 bool os::protect_memory(char* addr, size_t bytes, ProtType prot, 2521 bool is_committed) { 2522 unsigned int p = 0; 2523 switch (prot) { 2524 case MEM_PROT_NONE: p = PROT_NONE; break; 2525 case MEM_PROT_READ: p = PROT_READ; break; 2526 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; 2527 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; 2528 default: 2529 ShouldNotReachHere(); 2530 } 2531 // is_committed is unused. 2532 return linux_mprotect(addr, bytes, p); 2533 } 2534 2535 bool os::guard_memory(char* addr, size_t size) { 2536 return linux_mprotect(addr, size, PROT_NONE); 2537 } 2538 2539 bool os::unguard_memory(char* addr, size_t size) { 2540 return linux_mprotect(addr, size, PROT_READ|PROT_WRITE); 2541 } 2542 2543 // Large page support 2544 2545 static size_t _large_page_size = 0; 2546 2547 bool os::large_page_init() { 2548 if (!UseLargePages) return false; 2549 2550 if (LargePageSizeInBytes) { 2551 _large_page_size = LargePageSizeInBytes; 2552 } else { 2553 // large_page_size on Linux is used to round up heap size. x86 uses either 2554 // 2M or 4M page, depending on whether PAE (Physical Address Extensions) 2555 // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use 2556 // page as large as 256M. 2557 // 2558 // Here we try to figure out page size by parsing /proc/meminfo and looking 2559 // for a line with the following format: 2560 // Hugepagesize: 2048 kB 2561 // 2562 // If we can't determine the value (e.g. /proc is not mounted, or the text 2563 // format has been changed), we'll use the largest page size supported by 2564 // the processor. 2565 2566 _large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M); 2567 2568 FILE *fp = fopen("/proc/meminfo", "r"); 2569 if (fp) { 2570 while (!feof(fp)) { 2571 int x = 0; 2572 char buf[16]; 2573 if (fscanf(fp, "Hugepagesize: %d", &x) == 1) { 2574 if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) { 2575 _large_page_size = x * K; 2576 break; 2577 } 2578 } else { 2579 // skip to next line 2580 for (;;) { 2581 int ch = fgetc(fp); 2582 if (ch == EOF || ch == (int)'\n') break; 2583 } 2584 } 2585 } 2586 fclose(fp); 2587 } 2588 } 2589 2590 const size_t default_page_size = (size_t)Linux::page_size(); 2591 if (_large_page_size > default_page_size) { 2592 _page_sizes[0] = _large_page_size; 2593 _page_sizes[1] = default_page_size; 2594 _page_sizes[2] = 0; 2595 } 2596 2597 // Large page support is available on 2.6 or newer kernel, some vendors 2598 // (e.g. Redhat) have backported it to their 2.4 based distributions. 2599 // We optimistically assume the support is available. If later it turns out 2600 // not true, VM will automatically switch to use regular page size. 2601 return true; 2602 } 2603 2604 #ifndef SHM_HUGETLB 2605 #define SHM_HUGETLB 04000 2606 #endif 2607 2608 char* os::reserve_memory_special(size_t bytes) { 2609 assert(UseLargePages, "only for large pages"); 2610 2611 key_t key = IPC_PRIVATE; 2612 char *addr; 2613 2614 bool warn_on_failure = UseLargePages && 2615 (!FLAG_IS_DEFAULT(UseLargePages) || 2616 !FLAG_IS_DEFAULT(LargePageSizeInBytes) 2617 ); 2618 char msg[128]; 2619 2620 // Create a large shared memory region to attach to based on size. 2621 // Currently, size is the total size of the heap 2622 int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W); 2623 if (shmid == -1) { 2624 // Possible reasons for shmget failure: 2625 // 1. shmmax is too small for Java heap. 2626 // > check shmmax value: cat /proc/sys/kernel/shmmax 2627 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax 2628 // 2. not enough large page memory. 2629 // > check available large pages: cat /proc/meminfo 2630 // > increase amount of large pages: 2631 // echo new_value > /proc/sys/vm/nr_hugepages 2632 // Note 1: different Linux may use different name for this property, 2633 // e.g. on Redhat AS-3 it is "hugetlb_pool". 2634 // Note 2: it's possible there's enough physical memory available but 2635 // they are so fragmented after a long run that they can't 2636 // coalesce into large pages. Try to reserve large pages when 2637 // the system is still "fresh". 2638 if (warn_on_failure) { 2639 jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno); 2640 warning(msg); 2641 } 2642 return NULL; 2643 } 2644 2645 // attach to the region 2646 addr = (char*)shmat(shmid, NULL, 0); 2647 int err = errno; 2648 2649 // Remove shmid. If shmat() is successful, the actual shared memory segment 2650 // will be deleted when it's detached by shmdt() or when the process 2651 // terminates. If shmat() is not successful this will remove the shared 2652 // segment immediately. 2653 shmctl(shmid, IPC_RMID, NULL); 2654 2655 if ((intptr_t)addr == -1) { 2656 if (warn_on_failure) { 2657 jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err); 2658 warning(msg); 2659 } 2660 return NULL; 2661 } 2662 2663 return addr; 2664 } 2665 2666 bool os::release_memory_special(char* base, size_t bytes) { 2667 // detaching the SHM segment will also delete it, see reserve_memory_special() 2668 int rslt = shmdt(base); 2669 return rslt == 0; 2670 } 2671 2672 size_t os::large_page_size() { 2673 return _large_page_size; 2674 } 2675 2676 // Linux does not support anonymous mmap with large page memory. The only way 2677 // to reserve large page memory without file backing is through SysV shared 2678 // memory API. The entire memory region is committed and pinned upfront. 2679 // Hopefully this will change in the future... 2680 bool os::can_commit_large_page_memory() { 2681 return false; 2682 } 2683 2684 bool os::can_execute_large_page_memory() { 2685 return false; 2686 } 2687 2688 // Reserve memory at an arbitrary address, only if that area is 2689 // available (and not reserved for something else). 2690 2691 char* os::attempt_reserve_memory_at(size_t bytes, char* requested_addr) { 2692 const int max_tries = 10; 2693 char* base[max_tries]; 2694 size_t size[max_tries]; 2695 const size_t gap = 0x000000; 2696 2697 // Assert only that the size is a multiple of the page size, since 2698 // that's all that mmap requires, and since that's all we really know 2699 // about at this low abstraction level. If we need higher alignment, 2700 // we can either pass an alignment to this method or verify alignment 2701 // in one of the methods further up the call chain. See bug 5044738. 2702 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block"); 2703 2704 // Repeatedly allocate blocks until the block is allocated at the 2705 // right spot. Give up after max_tries. Note that reserve_memory() will 2706 // automatically update _highest_vm_reserved_address if the call is 2707 // successful. The variable tracks the highest memory address every reserved 2708 // by JVM. It is used to detect heap-stack collision if running with 2709 // fixed-stack LinuxThreads. Because here we may attempt to reserve more 2710 // space than needed, it could confuse the collision detecting code. To 2711 // solve the problem, save current _highest_vm_reserved_address and 2712 // calculate the correct value before return. 2713 address old_highest = _highest_vm_reserved_address; 2714 2715 // Linux mmap allows caller to pass an address as hint; give it a try first, 2716 // if kernel honors the hint then we can return immediately. 2717 char * addr = anon_mmap(requested_addr, bytes, false); 2718 if (addr == requested_addr) { 2719 return requested_addr; 2720 } 2721 2722 if (addr != NULL) { 2723 // mmap() is successful but it fails to reserve at the requested address 2724 anon_munmap(addr, bytes); 2725 } 2726 2727 int i; 2728 for (i = 0; i < max_tries; ++i) { 2729 base[i] = reserve_memory(bytes); 2730 2731 if (base[i] != NULL) { 2732 // Is this the block we wanted? 2733 if (base[i] == requested_addr) { 2734 size[i] = bytes; 2735 break; 2736 } 2737 2738 // Does this overlap the block we wanted? Give back the overlapped 2739 // parts and try again. 2740 2741 size_t top_overlap = requested_addr + (bytes + gap) - base[i]; 2742 if (top_overlap >= 0 && top_overlap < bytes) { 2743 unmap_memory(base[i], top_overlap); 2744 base[i] += top_overlap; 2745 size[i] = bytes - top_overlap; 2746 } else { 2747 size_t bottom_overlap = base[i] + bytes - requested_addr; 2748 if (bottom_overlap >= 0 && bottom_overlap < bytes) { 2749 unmap_memory(requested_addr, bottom_overlap); 2750 size[i] = bytes - bottom_overlap; 2751 } else { 2752 size[i] = bytes; 2753 } 2754 } 2755 } 2756 } 2757 2758 // Give back the unused reserved pieces. 2759 2760 for (int j = 0; j < i; ++j) { 2761 if (base[j] != NULL) { 2762 unmap_memory(base[j], size[j]); 2763 } 2764 } 2765 2766 if (i < max_tries) { 2767 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes); 2768 return requested_addr; 2769 } else { 2770 _highest_vm_reserved_address = old_highest; 2771 return NULL; 2772 } 2773 } 2774 2775 size_t os::read(int fd, void *buf, unsigned int nBytes) { 2776 return ::read(fd, buf, nBytes); 2777 } 2778 2779 // TODO-FIXME: reconcile Solaris' os::sleep with the linux variation. 2780 // Solaris uses poll(), linux uses park(). 2781 // Poll() is likely a better choice, assuming that Thread.interrupt() 2782 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with 2783 // SIGSEGV, see 4355769. 2784 2785 const int NANOSECS_PER_MILLISECS = 1000000; 2786 2787 int os::sleep(Thread* thread, jlong millis, bool interruptible) { 2788 assert(thread == Thread::current(), "thread consistency check"); 2789 2790 ParkEvent * const slp = thread->_SleepEvent ; 2791 slp->reset() ; 2792 OrderAccess::fence() ; 2793 2794 if (interruptible) { 2795 jlong prevtime = javaTimeNanos(); 2796 2797 for (;;) { 2798 if (os::is_interrupted(thread, true)) { 2799 return OS_INTRPT; 2800 } 2801 2802 jlong newtime = javaTimeNanos(); 2803 2804 if (newtime - prevtime < 0) { 2805 // time moving backwards, should only happen if no monotonic clock 2806 // not a guarantee() because JVM should not abort on kernel/glibc bugs 2807 assert(!Linux::supports_monotonic_clock(), "time moving backwards"); 2808 } else { 2809 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISECS; 2810 } 2811 2812 if(millis <= 0) { 2813 return OS_OK; 2814 } 2815 2816 prevtime = newtime; 2817 2818 { 2819 assert(thread->is_Java_thread(), "sanity check"); 2820 JavaThread *jt = (JavaThread *) thread; 2821 ThreadBlockInVM tbivm(jt); 2822 OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */); 2823 2824 jt->set_suspend_equivalent(); 2825 // cleared by handle_special_suspend_equivalent_condition() or 2826 // java_suspend_self() via check_and_wait_while_suspended() 2827 2828 slp->park(millis); 2829 2830 // were we externally suspended while we were waiting? 2831 jt->check_and_wait_while_suspended(); 2832 } 2833 } 2834 } else { 2835 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 2836 jlong prevtime = javaTimeNanos(); 2837 2838 for (;;) { 2839 // It'd be nice to avoid the back-to-back javaTimeNanos() calls on 2840 // the 1st iteration ... 2841 jlong newtime = javaTimeNanos(); 2842 2843 if (newtime - prevtime < 0) { 2844 // time moving backwards, should only happen if no monotonic clock 2845 // not a guarantee() because JVM should not abort on kernel/glibc bugs 2846 assert(!Linux::supports_monotonic_clock(), "time moving backwards"); 2847 } else { 2848 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISECS; 2849 } 2850 2851 if(millis <= 0) break ; 2852 2853 prevtime = newtime; 2854 slp->park(millis); 2855 } 2856 return OS_OK ; 2857 } 2858 } 2859 2860 int os::naked_sleep() { 2861 // %% make the sleep time an integer flag. for now use 1 millisec. 2862 return os::sleep(Thread::current(), 1, false); 2863 } 2864 2865 // Sleep forever; naked call to OS-specific sleep; use with CAUTION 2866 void os::infinite_sleep() { 2867 while (true) { // sleep forever ... 2868 ::sleep(100); // ... 100 seconds at a time 2869 } 2870 } 2871 2872 // Used to convert frequent JVM_Yield() to nops 2873 bool os::dont_yield() { 2874 return DontYieldALot; 2875 } 2876 2877 void os::yield() { 2878 sched_yield(); 2879 } 2880 2881 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;} 2882 2883 void os::yield_all(int attempts) { 2884 // Yields to all threads, including threads with lower priorities 2885 // Threads on Linux are all with same priority. The Solaris style 2886 // os::yield_all() with nanosleep(1ms) is not necessary. 2887 sched_yield(); 2888 } 2889 2890 // Called from the tight loops to possibly influence time-sharing heuristics 2891 void os::loop_breaker(int attempts) { 2892 os::yield_all(attempts); 2893 } 2894 2895 //////////////////////////////////////////////////////////////////////////////// 2896 // thread priority support 2897 2898 // Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER 2899 // only supports dynamic priority, static priority must be zero. For real-time 2900 // applications, Linux supports SCHED_RR which allows static priority (1-99). 2901 // However, for large multi-threaded applications, SCHED_RR is not only slower 2902 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out 2903 // of 5 runs - Sep 2005). 2904 // 2905 // The following code actually changes the niceness of kernel-thread/LWP. It 2906 // has an assumption that setpriority() only modifies one kernel-thread/LWP, 2907 // not the entire user process, and user level threads are 1:1 mapped to kernel 2908 // threads. It has always been the case, but could change in the future. For 2909 // this reason, the code should not be used as default (ThreadPriorityPolicy=0). 2910 // It is only used when ThreadPriorityPolicy=1 and requires root privilege. 2911 2912 int os::java_to_os_priority[MaxPriority + 1] = { 2913 19, // 0 Entry should never be used 2914 2915 4, // 1 MinPriority 2916 3, // 2 2917 2, // 3 2918 2919 1, // 4 2920 0, // 5 NormPriority 2921 -1, // 6 2922 2923 -2, // 7 2924 -3, // 8 2925 -4, // 9 NearMaxPriority 2926 2927 -5 // 10 MaxPriority 2928 }; 2929 2930 static int prio_init() { 2931 if (ThreadPriorityPolicy == 1) { 2932 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1 2933 // if effective uid is not root. Perhaps, a more elegant way of doing 2934 // this is to test CAP_SYS_NICE capability, but that will require libcap.so 2935 if (geteuid() != 0) { 2936 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) { 2937 warning("-XX:ThreadPriorityPolicy requires root privilege on Linux"); 2938 } 2939 ThreadPriorityPolicy = 0; 2940 } 2941 } 2942 return 0; 2943 } 2944 2945 OSReturn os::set_native_priority(Thread* thread, int newpri) { 2946 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK; 2947 2948 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri); 2949 return (ret == 0) ? OS_OK : OS_ERR; 2950 } 2951 2952 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) { 2953 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) { 2954 *priority_ptr = java_to_os_priority[NormPriority]; 2955 return OS_OK; 2956 } 2957 2958 errno = 0; 2959 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id()); 2960 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR); 2961 } 2962 2963 // Hint to the underlying OS that a task switch would not be good. 2964 // Void return because it's a hint and can fail. 2965 void os::hint_no_preempt() {} 2966 2967 //////////////////////////////////////////////////////////////////////////////// 2968 // suspend/resume support 2969 2970 // the low-level signal-based suspend/resume support is a remnant from the 2971 // old VM-suspension that used to be for java-suspension, safepoints etc, 2972 // within hotspot. Now there is a single use-case for this: 2973 // - calling get_thread_pc() on the VMThread by the flat-profiler task 2974 // that runs in the watcher thread. 2975 // The remaining code is greatly simplified from the more general suspension 2976 // code that used to be used. 2977 // 2978 // The protocol is quite simple: 2979 // - suspend: 2980 // - sends a signal to the target thread 2981 // - polls the suspend state of the osthread using a yield loop 2982 // - target thread signal handler (SR_handler) sets suspend state 2983 // and blocks in sigsuspend until continued 2984 // - resume: 2985 // - sets target osthread state to continue 2986 // - sends signal to end the sigsuspend loop in the SR_handler 2987 // 2988 // Note that the SR_lock plays no role in this suspend/resume protocol. 2989 // 2990 2991 static void resume_clear_context(OSThread *osthread) { 2992 osthread->set_ucontext(NULL); 2993 osthread->set_siginfo(NULL); 2994 2995 // notify the suspend action is completed, we have now resumed 2996 osthread->sr.clear_suspended(); 2997 } 2998 2999 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) { 3000 osthread->set_ucontext(context); 3001 osthread->set_siginfo(siginfo); 3002 } 3003 3004 // 3005 // Handler function invoked when a thread's execution is suspended or 3006 // resumed. We have to be careful that only async-safe functions are 3007 // called here (Note: most pthread functions are not async safe and 3008 // should be avoided.) 3009 // 3010 // Note: sigwait() is a more natural fit than sigsuspend() from an 3011 // interface point of view, but sigwait() prevents the signal hander 3012 // from being run. libpthread would get very confused by not having 3013 // its signal handlers run and prevents sigwait()'s use with the 3014 // mutex granting granting signal. 3015 // 3016 // Currently only ever called on the VMThread 3017 // 3018 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) { 3019 // Save and restore errno to avoid confusing native code with EINTR 3020 // after sigsuspend. 3021 int old_errno = errno; 3022 3023 Thread* thread = Thread::current(); 3024 OSThread* osthread = thread->osthread(); 3025 assert(thread->is_VM_thread(), "Must be VMThread"); 3026 // read current suspend action 3027 int action = osthread->sr.suspend_action(); 3028 if (action == SR_SUSPEND) { 3029 suspend_save_context(osthread, siginfo, context); 3030 3031 // Notify the suspend action is about to be completed. do_suspend() 3032 // waits until SR_SUSPENDED is set and then returns. We will wait 3033 // here for a resume signal and that completes the suspend-other 3034 // action. do_suspend/do_resume is always called as a pair from 3035 // the same thread - so there are no races 3036 3037 // notify the caller 3038 osthread->sr.set_suspended(); 3039 3040 sigset_t suspend_set; // signals for sigsuspend() 3041 3042 // get current set of blocked signals and unblock resume signal 3043 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); 3044 sigdelset(&suspend_set, SR_signum); 3045 3046 // wait here until we are resumed 3047 do { 3048 sigsuspend(&suspend_set); 3049 // ignore all returns until we get a resume signal 3050 } while (osthread->sr.suspend_action() != SR_CONTINUE); 3051 3052 resume_clear_context(osthread); 3053 3054 } else { 3055 assert(action == SR_CONTINUE, "unexpected sr action"); 3056 // nothing special to do - just leave the handler 3057 } 3058 3059 errno = old_errno; 3060 } 3061 3062 3063 static int SR_initialize() { 3064 struct sigaction act; 3065 char *s; 3066 /* Get signal number to use for suspend/resume */ 3067 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) { 3068 int sig = ::strtol(s, 0, 10); 3069 if (sig > 0 || sig < _NSIG) { 3070 SR_signum = sig; 3071 } 3072 } 3073 3074 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS, 3075 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769"); 3076 3077 sigemptyset(&SR_sigset); 3078 sigaddset(&SR_sigset, SR_signum); 3079 3080 /* Set up signal handler for suspend/resume */ 3081 act.sa_flags = SA_RESTART|SA_SIGINFO; 3082 act.sa_handler = (void (*)(int)) SR_handler; 3083 3084 // SR_signum is blocked by default. 3085 // 4528190 - We also need to block pthread restart signal (32 on all 3086 // supported Linux platforms). Note that LinuxThreads need to block 3087 // this signal for all threads to work properly. So we don't have 3088 // to use hard-coded signal number when setting up the mask. 3089 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask); 3090 3091 if (sigaction(SR_signum, &act, 0) == -1) { 3092 return -1; 3093 } 3094 3095 // Save signal flag 3096 os::Linux::set_our_sigflags(SR_signum, act.sa_flags); 3097 return 0; 3098 } 3099 3100 static int SR_finalize() { 3101 return 0; 3102 } 3103 3104 3105 // returns true on success and false on error - really an error is fatal 3106 // but this seems the normal response to library errors 3107 static bool do_suspend(OSThread* osthread) { 3108 // mark as suspended and send signal 3109 osthread->sr.set_suspend_action(SR_SUSPEND); 3110 int status = pthread_kill(osthread->pthread_id(), SR_signum); 3111 assert_status(status == 0, status, "pthread_kill"); 3112 3113 // check status and wait until notified of suspension 3114 if (status == 0) { 3115 for (int i = 0; !osthread->sr.is_suspended(); i++) { 3116 os::yield_all(i); 3117 } 3118 osthread->sr.set_suspend_action(SR_NONE); 3119 return true; 3120 } 3121 else { 3122 osthread->sr.set_suspend_action(SR_NONE); 3123 return false; 3124 } 3125 } 3126 3127 static void do_resume(OSThread* osthread) { 3128 assert(osthread->sr.is_suspended(), "thread should be suspended"); 3129 osthread->sr.set_suspend_action(SR_CONTINUE); 3130 3131 int status = pthread_kill(osthread->pthread_id(), SR_signum); 3132 assert_status(status == 0, status, "pthread_kill"); 3133 // check status and wait unit notified of resumption 3134 if (status == 0) { 3135 for (int i = 0; osthread->sr.is_suspended(); i++) { 3136 os::yield_all(i); 3137 } 3138 } 3139 osthread->sr.set_suspend_action(SR_NONE); 3140 } 3141 3142 //////////////////////////////////////////////////////////////////////////////// 3143 // interrupt support 3144 3145 void os::interrupt(Thread* thread) { 3146 assert(Thread::current() == thread || Threads_lock->owned_by_self(), 3147 "possibility of dangling Thread pointer"); 3148 3149 OSThread* osthread = thread->osthread(); 3150 3151 if (!osthread->interrupted()) { 3152 osthread->set_interrupted(true); 3153 // More than one thread can get here with the same value of osthread, 3154 // resulting in multiple notifications. We do, however, want the store 3155 // to interrupted() to be visible to other threads before we execute unpark(). 3156 OrderAccess::fence(); 3157 ParkEvent * const slp = thread->_SleepEvent ; 3158 if (slp != NULL) slp->unpark() ; 3159 } 3160 3161 // For JSR166. Unpark even if interrupt status already was set 3162 if (thread->is_Java_thread()) 3163 ((JavaThread*)thread)->parker()->unpark(); 3164 3165 ParkEvent * ev = thread->_ParkEvent ; 3166 if (ev != NULL) ev->unpark() ; 3167 3168 } 3169 3170 bool os::is_interrupted(Thread* thread, bool clear_interrupted) { 3171 assert(Thread::current() == thread || Threads_lock->owned_by_self(), 3172 "possibility of dangling Thread pointer"); 3173 3174 OSThread* osthread = thread->osthread(); 3175 3176 bool interrupted = osthread->interrupted(); 3177 3178 if (interrupted && clear_interrupted) { 3179 osthread->set_interrupted(false); 3180 // consider thread->_SleepEvent->reset() ... optional optimization 3181 } 3182 3183 return interrupted; 3184 } 3185 3186 /////////////////////////////////////////////////////////////////////////////////// 3187 // signal handling (except suspend/resume) 3188 3189 // This routine may be used by user applications as a "hook" to catch signals. 3190 // The user-defined signal handler must pass unrecognized signals to this 3191 // routine, and if it returns true (non-zero), then the signal handler must 3192 // return immediately. If the flag "abort_if_unrecognized" is true, then this 3193 // routine will never retun false (zero), but instead will execute a VM panic 3194 // routine kill the process. 3195 // 3196 // If this routine returns false, it is OK to call it again. This allows 3197 // the user-defined signal handler to perform checks either before or after 3198 // the VM performs its own checks. Naturally, the user code would be making 3199 // a serious error if it tried to handle an exception (such as a null check 3200 // or breakpoint) that the VM was generating for its own correct operation. 3201 // 3202 // This routine may recognize any of the following kinds of signals: 3203 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1. 3204 // It should be consulted by handlers for any of those signals. 3205 // 3206 // The caller of this routine must pass in the three arguments supplied 3207 // to the function referred to in the "sa_sigaction" (not the "sa_handler") 3208 // field of the structure passed to sigaction(). This routine assumes that 3209 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. 3210 // 3211 // Note that the VM will print warnings if it detects conflicting signal 3212 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". 3213 // 3214 extern "C" int 3215 JVM_handle_linux_signal(int signo, siginfo_t* siginfo, 3216 void* ucontext, int abort_if_unrecognized); 3217 3218 void signalHandler(int sig, siginfo_t* info, void* uc) { 3219 assert(info != NULL && uc != NULL, "it must be old kernel"); 3220 JVM_handle_linux_signal(sig, info, uc, true); 3221 } 3222 3223 3224 // This boolean allows users to forward their own non-matching signals 3225 // to JVM_handle_linux_signal, harmlessly. 3226 bool os::Linux::signal_handlers_are_installed = false; 3227 3228 // For signal-chaining 3229 struct sigaction os::Linux::sigact[MAXSIGNUM]; 3230 unsigned int os::Linux::sigs = 0; 3231 bool os::Linux::libjsig_is_loaded = false; 3232 typedef struct sigaction *(*get_signal_t)(int); 3233 get_signal_t os::Linux::get_signal_action = NULL; 3234 3235 struct sigaction* os::Linux::get_chained_signal_action(int sig) { 3236 struct sigaction *actp = NULL; 3237 3238 if (libjsig_is_loaded) { 3239 // Retrieve the old signal handler from libjsig 3240 actp = (*get_signal_action)(sig); 3241 } 3242 if (actp == NULL) { 3243 // Retrieve the preinstalled signal handler from jvm 3244 actp = get_preinstalled_handler(sig); 3245 } 3246 3247 return actp; 3248 } 3249 3250 static bool call_chained_handler(struct sigaction *actp, int sig, 3251 siginfo_t *siginfo, void *context) { 3252 // Call the old signal handler 3253 if (actp->sa_handler == SIG_DFL) { 3254 // It's more reasonable to let jvm treat it as an unexpected exception 3255 // instead of taking the default action. 3256 return false; 3257 } else if (actp->sa_handler != SIG_IGN) { 3258 if ((actp->sa_flags & SA_NODEFER) == 0) { 3259 // automaticlly block the signal 3260 sigaddset(&(actp->sa_mask), sig); 3261 } 3262 3263 sa_handler_t hand; 3264 sa_sigaction_t sa; 3265 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0; 3266 // retrieve the chained handler 3267 if (siginfo_flag_set) { 3268 sa = actp->sa_sigaction; 3269 } else { 3270 hand = actp->sa_handler; 3271 } 3272 3273 if ((actp->sa_flags & SA_RESETHAND) != 0) { 3274 actp->sa_handler = SIG_DFL; 3275 } 3276 3277 // try to honor the signal mask 3278 sigset_t oset; 3279 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset); 3280 3281 // call into the chained handler 3282 if (siginfo_flag_set) { 3283 (*sa)(sig, siginfo, context); 3284 } else { 3285 (*hand)(sig); 3286 } 3287 3288 // restore the signal mask 3289 pthread_sigmask(SIG_SETMASK, &oset, 0); 3290 } 3291 // Tell jvm's signal handler the signal is taken care of. 3292 return true; 3293 } 3294 3295 bool os::Linux::chained_handler(int sig, siginfo_t* siginfo, void* context) { 3296 bool chained = false; 3297 // signal-chaining 3298 if (UseSignalChaining) { 3299 struct sigaction *actp = get_chained_signal_action(sig); 3300 if (actp != NULL) { 3301 chained = call_chained_handler(actp, sig, siginfo, context); 3302 } 3303 } 3304 return chained; 3305 } 3306 3307 struct sigaction* os::Linux::get_preinstalled_handler(int sig) { 3308 if ((( (unsigned int)1 << sig ) & sigs) != 0) { 3309 return &sigact[sig]; 3310 } 3311 return NULL; 3312 } 3313 3314 void os::Linux::save_preinstalled_handler(int sig, struct sigaction& oldAct) { 3315 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3316 sigact[sig] = oldAct; 3317 sigs |= (unsigned int)1 << sig; 3318 } 3319 3320 // for diagnostic 3321 int os::Linux::sigflags[MAXSIGNUM]; 3322 3323 int os::Linux::get_our_sigflags(int sig) { 3324 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3325 return sigflags[sig]; 3326 } 3327 3328 void os::Linux::set_our_sigflags(int sig, int flags) { 3329 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3330 sigflags[sig] = flags; 3331 } 3332 3333 void os::Linux::set_signal_handler(int sig, bool set_installed) { 3334 // Check for overwrite. 3335 struct sigaction oldAct; 3336 sigaction(sig, (struct sigaction*)NULL, &oldAct); 3337 3338 void* oldhand = oldAct.sa_sigaction 3339 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 3340 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 3341 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && 3342 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && 3343 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) { 3344 if (AllowUserSignalHandlers || !set_installed) { 3345 // Do not overwrite; user takes responsibility to forward to us. 3346 return; 3347 } else if (UseSignalChaining) { 3348 // save the old handler in jvm 3349 save_preinstalled_handler(sig, oldAct); 3350 // libjsig also interposes the sigaction() call below and saves the 3351 // old sigaction on it own. 3352 } else { 3353 fatal2("Encountered unexpected pre-existing sigaction handler %#lx for signal %d.", (long)oldhand, sig); 3354 } 3355 } 3356 3357 struct sigaction sigAct; 3358 sigfillset(&(sigAct.sa_mask)); 3359 sigAct.sa_handler = SIG_DFL; 3360 if (!set_installed) { 3361 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 3362 } else { 3363 sigAct.sa_sigaction = signalHandler; 3364 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; 3365 } 3366 // Save flags, which are set by ours 3367 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); 3368 sigflags[sig] = sigAct.sa_flags; 3369 3370 int ret = sigaction(sig, &sigAct, &oldAct); 3371 assert(ret == 0, "check"); 3372 3373 void* oldhand2 = oldAct.sa_sigaction 3374 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 3375 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 3376 assert(oldhand2 == oldhand, "no concurrent signal handler installation"); 3377 } 3378 3379 // install signal handlers for signals that HotSpot needs to 3380 // handle in order to support Java-level exception handling. 3381 3382 void os::Linux::install_signal_handlers() { 3383 if (!signal_handlers_are_installed) { 3384 signal_handlers_are_installed = true; 3385 3386 // signal-chaining 3387 typedef void (*signal_setting_t)(); 3388 signal_setting_t begin_signal_setting = NULL; 3389 signal_setting_t end_signal_setting = NULL; 3390 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 3391 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); 3392 if (begin_signal_setting != NULL) { 3393 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 3394 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); 3395 get_signal_action = CAST_TO_FN_PTR(get_signal_t, 3396 dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); 3397 libjsig_is_loaded = true; 3398 assert(UseSignalChaining, "should enable signal-chaining"); 3399 } 3400 if (libjsig_is_loaded) { 3401 // Tell libjsig jvm is setting signal handlers 3402 (*begin_signal_setting)(); 3403 } 3404 3405 set_signal_handler(SIGSEGV, true); 3406 set_signal_handler(SIGPIPE, true); 3407 set_signal_handler(SIGBUS, true); 3408 set_signal_handler(SIGILL, true); 3409 set_signal_handler(SIGFPE, true); 3410 set_signal_handler(SIGXFSZ, true); 3411 3412 if (libjsig_is_loaded) { 3413 // Tell libjsig jvm finishes setting signal handlers 3414 (*end_signal_setting)(); 3415 } 3416 3417 // We don't activate signal checker if libjsig is in place, we trust ourselves 3418 // and if UserSignalHandler is installed all bets are off 3419 if (CheckJNICalls) { 3420 if (libjsig_is_loaded) { 3421 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); 3422 check_signals = false; 3423 } 3424 if (AllowUserSignalHandlers) { 3425 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); 3426 check_signals = false; 3427 } 3428 } 3429 } 3430 } 3431 3432 // This is the fastest way to get thread cpu time on Linux. 3433 // Returns cpu time (user+sys) for any thread, not only for current. 3434 // POSIX compliant clocks are implemented in the kernels 2.6.16+. 3435 // It might work on 2.6.10+ with a special kernel/glibc patch. 3436 // For reference, please, see IEEE Std 1003.1-2004: 3437 // http://www.unix.org/single_unix_specification 3438 3439 jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) { 3440 struct timespec tp; 3441 int rc = os::Linux::clock_gettime(clockid, &tp); 3442 assert(rc == 0, "clock_gettime is expected to return 0 code"); 3443 3444 return (tp.tv_sec * SEC_IN_NANOSECS) + tp.tv_nsec; 3445 } 3446 3447 ///// 3448 // glibc on Linux platform uses non-documented flag 3449 // to indicate, that some special sort of signal 3450 // trampoline is used. 3451 // We will never set this flag, and we should 3452 // ignore this flag in our diagnostic 3453 #ifdef SIGNIFICANT_SIGNAL_MASK 3454 #undef SIGNIFICANT_SIGNAL_MASK 3455 #endif 3456 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000) 3457 3458 static const char* get_signal_handler_name(address handler, 3459 char* buf, int buflen) { 3460 int offset; 3461 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); 3462 if (found) { 3463 // skip directory names 3464 const char *p1, *p2; 3465 p1 = buf; 3466 size_t len = strlen(os::file_separator()); 3467 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; 3468 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset); 3469 } else { 3470 jio_snprintf(buf, buflen, PTR_FORMAT, handler); 3471 } 3472 return buf; 3473 } 3474 3475 static void print_signal_handler(outputStream* st, int sig, 3476 char* buf, size_t buflen) { 3477 struct sigaction sa; 3478 3479 sigaction(sig, NULL, &sa); 3480 3481 // See comment for SIGNIFICANT_SIGNAL_MASK define 3482 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 3483 3484 st->print("%s: ", os::exception_name(sig, buf, buflen)); 3485 3486 address handler = (sa.sa_flags & SA_SIGINFO) 3487 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) 3488 : CAST_FROM_FN_PTR(address, sa.sa_handler); 3489 3490 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { 3491 st->print("SIG_DFL"); 3492 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { 3493 st->print("SIG_IGN"); 3494 } else { 3495 st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); 3496 } 3497 3498 st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask); 3499 3500 address rh = VMError::get_resetted_sighandler(sig); 3501 // May be, handler was resetted by VMError? 3502 if(rh != NULL) { 3503 handler = rh; 3504 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK; 3505 } 3506 3507 st->print(", sa_flags=" PTR32_FORMAT, sa.sa_flags); 3508 3509 // Check: is it our handler? 3510 if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || 3511 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { 3512 // It is our signal handler 3513 // check for flags, reset system-used one! 3514 if((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) { 3515 st->print( 3516 ", flags was changed from " PTR32_FORMAT ", consider using jsig library", 3517 os::Linux::get_our_sigflags(sig)); 3518 } 3519 } 3520 st->cr(); 3521 } 3522 3523 3524 #define DO_SIGNAL_CHECK(sig) \ 3525 if (!sigismember(&check_signal_done, sig)) \ 3526 os::Linux::check_signal_handler(sig) 3527 3528 // This method is a periodic task to check for misbehaving JNI applications 3529 // under CheckJNI, we can add any periodic checks here 3530 3531 void os::run_periodic_checks() { 3532 3533 if (check_signals == false) return; 3534 3535 // SEGV and BUS if overridden could potentially prevent 3536 // generation of hs*.log in the event of a crash, debugging 3537 // such a case can be very challenging, so we absolutely 3538 // check the following for a good measure: 3539 DO_SIGNAL_CHECK(SIGSEGV); 3540 DO_SIGNAL_CHECK(SIGILL); 3541 DO_SIGNAL_CHECK(SIGFPE); 3542 DO_SIGNAL_CHECK(SIGBUS); 3543 DO_SIGNAL_CHECK(SIGPIPE); 3544 DO_SIGNAL_CHECK(SIGXFSZ); 3545 3546 3547 // ReduceSignalUsage allows the user to override these handlers 3548 // see comments at the very top and jvm_solaris.h 3549 if (!ReduceSignalUsage) { 3550 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); 3551 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); 3552 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); 3553 DO_SIGNAL_CHECK(BREAK_SIGNAL); 3554 } 3555 3556 DO_SIGNAL_CHECK(SR_signum); 3557 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL); 3558 } 3559 3560 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); 3561 3562 static os_sigaction_t os_sigaction = NULL; 3563 3564 void os::Linux::check_signal_handler(int sig) { 3565 char buf[O_BUFLEN]; 3566 address jvmHandler = NULL; 3567 3568 3569 struct sigaction act; 3570 if (os_sigaction == NULL) { 3571 // only trust the default sigaction, in case it has been interposed 3572 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); 3573 if (os_sigaction == NULL) return; 3574 } 3575 3576 os_sigaction(sig, (struct sigaction*)NULL, &act); 3577 3578 3579 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK; 3580 3581 address thisHandler = (act.sa_flags & SA_SIGINFO) 3582 ? CAST_FROM_FN_PTR(address, act.sa_sigaction) 3583 : CAST_FROM_FN_PTR(address, act.sa_handler) ; 3584 3585 3586 switch(sig) { 3587 case SIGSEGV: 3588 case SIGBUS: 3589 case SIGFPE: 3590 case SIGPIPE: 3591 case SIGILL: 3592 case SIGXFSZ: 3593 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler); 3594 break; 3595 3596 case SHUTDOWN1_SIGNAL: 3597 case SHUTDOWN2_SIGNAL: 3598 case SHUTDOWN3_SIGNAL: 3599 case BREAK_SIGNAL: 3600 jvmHandler = (address)user_handler(); 3601 break; 3602 3603 case INTERRUPT_SIGNAL: 3604 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL); 3605 break; 3606 3607 default: 3608 if (sig == SR_signum) { 3609 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler); 3610 } else { 3611 return; 3612 } 3613 break; 3614 } 3615 3616 if (thisHandler != jvmHandler) { 3617 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); 3618 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); 3619 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); 3620 // No need to check this sig any longer 3621 sigaddset(&check_signal_done, sig); 3622 } else if(os::Linux::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Linux::get_our_sigflags(sig)) { 3623 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); 3624 tty->print("expected:" PTR32_FORMAT, os::Linux::get_our_sigflags(sig)); 3625 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags); 3626 // No need to check this sig any longer 3627 sigaddset(&check_signal_done, sig); 3628 } 3629 3630 // Dump all the signal 3631 if (sigismember(&check_signal_done, sig)) { 3632 print_signal_handlers(tty, buf, O_BUFLEN); 3633 } 3634 } 3635 3636 extern void report_error(char* file_name, int line_no, char* title, char* format, ...); 3637 3638 extern bool signal_name(int signo, char* buf, size_t len); 3639 3640 const char* os::exception_name(int exception_code, char* buf, size_t size) { 3641 if (0 < exception_code && exception_code <= SIGRTMAX) { 3642 // signal 3643 if (!signal_name(exception_code, buf, size)) { 3644 jio_snprintf(buf, size, "SIG%d", exception_code); 3645 } 3646 return buf; 3647 } else { 3648 return NULL; 3649 } 3650 } 3651 3652 // this is called _before_ the most of global arguments have been parsed 3653 void os::init(void) { 3654 char dummy; /* used to get a guess on initial stack address */ 3655 // first_hrtime = gethrtime(); 3656 3657 // With LinuxThreads the JavaMain thread pid (primordial thread) 3658 // is different than the pid of the java launcher thread. 3659 // So, on Linux, the launcher thread pid is passed to the VM 3660 // via the sun.java.launcher.pid property. 3661 // Use this property instead of getpid() if it was correctly passed. 3662 // See bug 6351349. 3663 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid(); 3664 3665 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid(); 3666 3667 clock_tics_per_sec = sysconf(_SC_CLK_TCK); 3668 3669 init_random(1234567); 3670 3671 ThreadCritical::initialize(); 3672 3673 Linux::set_page_size(sysconf(_SC_PAGESIZE)); 3674 if (Linux::page_size() == -1) { 3675 fatal1("os_linux.cpp: os::init: sysconf failed (%s)", strerror(errno)); 3676 } 3677 init_page_sizes((size_t) Linux::page_size()); 3678 3679 Linux::initialize_system_info(); 3680 3681 // main_thread points to the aboriginal thread 3682 Linux::_main_thread = pthread_self(); 3683 3684 Linux::clock_init(); 3685 initial_time_count = os::elapsed_counter(); 3686 pthread_mutex_init(&dl_mutex, NULL); 3687 } 3688 3689 // To install functions for atexit system call 3690 extern "C" { 3691 static void perfMemory_exit_helper() { 3692 perfMemory_exit(); 3693 } 3694 } 3695 3696 // this is called _after_ the global arguments have been parsed 3697 jint os::init_2(void) 3698 { 3699 Linux::fast_thread_clock_init(); 3700 3701 // Allocate a single page and mark it as readable for safepoint polling 3702 address polling_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 3703 guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" ); 3704 3705 os::set_polling_page( polling_page ); 3706 3707 #ifndef PRODUCT 3708 if(Verbose && PrintMiscellaneous) 3709 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page); 3710 #endif 3711 3712 if (!UseMembar) { 3713 address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); 3714 guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page"); 3715 os::set_memory_serialize_page( mem_serialize_page ); 3716 3717 #ifndef PRODUCT 3718 if(Verbose && PrintMiscellaneous) 3719 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); 3720 #endif 3721 } 3722 3723 FLAG_SET_DEFAULT(UseLargePages, os::large_page_init()); 3724 3725 // initialize suspend/resume support - must do this before signal_sets_init() 3726 if (SR_initialize() != 0) { 3727 perror("SR_initialize failed"); 3728 return JNI_ERR; 3729 } 3730 3731 Linux::signal_sets_init(); 3732 Linux::install_signal_handlers(); 3733 3734 size_t threadStackSizeInBytes = ThreadStackSize * K; 3735 if (threadStackSizeInBytes != 0 && 3736 threadStackSizeInBytes < Linux::min_stack_allowed) { 3737 tty->print_cr("\nThe stack size specified is too small, " 3738 "Specify at least %dk", 3739 Linux::min_stack_allowed / K); 3740 return JNI_ERR; 3741 } 3742 3743 // Make the stack size a multiple of the page size so that 3744 // the yellow/red zones can be guarded. 3745 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, 3746 vm_page_size())); 3747 3748 Linux::capture_initial_stack(JavaThread::stack_size_at_create()); 3749 3750 Linux::libpthread_init(); 3751 if (PrintMiscellaneous && (Verbose || WizardMode)) { 3752 tty->print_cr("[HotSpot is running with %s, %s(%s)]\n", 3753 Linux::glibc_version(), Linux::libpthread_version(), 3754 Linux::is_floating_stack() ? "floating stack" : "fixed stack"); 3755 } 3756 3757 if (UseNUMA) { 3758 if (!Linux::libnuma_init()) { 3759 UseNUMA = false; 3760 } else { 3761 if ((Linux::numa_max_node() < 1)) { 3762 // There's only one node(they start from 0), disable NUMA. 3763 UseNUMA = false; 3764 } 3765 } 3766 if (!UseNUMA && ForceNUMA) { 3767 UseNUMA = true; 3768 } 3769 } 3770 3771 if (MaxFDLimit) { 3772 // set the number of file descriptors to max. print out error 3773 // if getrlimit/setrlimit fails but continue regardless. 3774 struct rlimit nbr_files; 3775 int status = getrlimit(RLIMIT_NOFILE, &nbr_files); 3776 if (status != 0) { 3777 if (PrintMiscellaneous && (Verbose || WizardMode)) 3778 perror("os::init_2 getrlimit failed"); 3779 } else { 3780 nbr_files.rlim_cur = nbr_files.rlim_max; 3781 status = setrlimit(RLIMIT_NOFILE, &nbr_files); 3782 if (status != 0) { 3783 if (PrintMiscellaneous && (Verbose || WizardMode)) 3784 perror("os::init_2 setrlimit failed"); 3785 } 3786 } 3787 } 3788 3789 // Initialize lock used to serialize thread creation (see os::create_thread) 3790 Linux::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false)); 3791 3792 // Initialize HPI. 3793 jint hpi_result = hpi::initialize(); 3794 if (hpi_result != JNI_OK) { 3795 tty->print_cr("There was an error trying to initialize the HPI library."); 3796 return hpi_result; 3797 } 3798 3799 // at-exit methods are called in the reverse order of their registration. 3800 // atexit functions are called on return from main or as a result of a 3801 // call to exit(3C). There can be only 32 of these functions registered 3802 // and atexit() does not set errno. 3803 3804 if (PerfAllowAtExitRegistration) { 3805 // only register atexit functions if PerfAllowAtExitRegistration is set. 3806 // atexit functions can be delayed until process exit time, which 3807 // can be problematic for embedded VM situations. Embedded VMs should 3808 // call DestroyJavaVM() to assure that VM resources are released. 3809 3810 // note: perfMemory_exit_helper atexit function may be removed in 3811 // the future if the appropriate cleanup code can be added to the 3812 // VM_Exit VMOperation's doit method. 3813 if (atexit(perfMemory_exit_helper) != 0) { 3814 warning("os::init2 atexit(perfMemory_exit_helper) failed"); 3815 } 3816 } 3817 3818 // initialize thread priority policy 3819 prio_init(); 3820 3821 return JNI_OK; 3822 } 3823 3824 // Mark the polling page as unreadable 3825 void os::make_polling_page_unreadable(void) { 3826 if( !guard_memory((char*)_polling_page, Linux::page_size()) ) 3827 fatal("Could not disable polling page"); 3828 }; 3829 3830 // Mark the polling page as readable 3831 void os::make_polling_page_readable(void) { 3832 if( !linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) { 3833 fatal("Could not enable polling page"); 3834 } 3835 }; 3836 3837 int os::active_processor_count() { 3838 // Linux doesn't yet have a (official) notion of processor sets, 3839 // so just return the number of online processors. 3840 int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN); 3841 assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check"); 3842 return online_cpus; 3843 } 3844 3845 bool os::distribute_processes(uint length, uint* distribution) { 3846 // Not yet implemented. 3847 return false; 3848 } 3849 3850 bool os::bind_to_processor(uint processor_id) { 3851 // Not yet implemented. 3852 return false; 3853 } 3854 3855 /// 3856 3857 // Suspends the target using the signal mechanism and then grabs the PC before 3858 // resuming the target. Used by the flat-profiler only 3859 ExtendedPC os::get_thread_pc(Thread* thread) { 3860 // Make sure that it is called by the watcher for the VMThread 3861 assert(Thread::current()->is_Watcher_thread(), "Must be watcher"); 3862 assert(thread->is_VM_thread(), "Can only be called for VMThread"); 3863 3864 ExtendedPC epc; 3865 3866 OSThread* osthread = thread->osthread(); 3867 if (do_suspend(osthread)) { 3868 if (osthread->ucontext() != NULL) { 3869 epc = os::Linux::ucontext_get_pc(osthread->ucontext()); 3870 } else { 3871 // NULL context is unexpected, double-check this is the VMThread 3872 guarantee(thread->is_VM_thread(), "can only be called for VMThread"); 3873 } 3874 do_resume(osthread); 3875 } 3876 // failure means pthread_kill failed for some reason - arguably this is 3877 // a fatal problem, but such problems are ignored elsewhere 3878 3879 return epc; 3880 } 3881 3882 int os::Linux::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime) 3883 { 3884 if (is_NPTL()) { 3885 return pthread_cond_timedwait(_cond, _mutex, _abstime); 3886 } else { 3887 #ifndef IA64 3888 // 6292965: LinuxThreads pthread_cond_timedwait() resets FPU control 3889 // word back to default 64bit precision if condvar is signaled. Java 3890 // wants 53bit precision. Save and restore current value. 3891 int fpu = get_fpu_control_word(); 3892 #endif // IA64 3893 int status = pthread_cond_timedwait(_cond, _mutex, _abstime); 3894 #ifndef IA64 3895 set_fpu_control_word(fpu); 3896 #endif // IA64 3897 return status; 3898 } 3899 } 3900 3901 //////////////////////////////////////////////////////////////////////////////// 3902 // debug support 3903 3904 #ifndef PRODUCT 3905 static address same_page(address x, address y) { 3906 int page_bits = -os::vm_page_size(); 3907 if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits)) 3908 return x; 3909 else if (x > y) 3910 return (address)(intptr_t(y) | ~page_bits) + 1; 3911 else 3912 return (address)(intptr_t(y) & page_bits); 3913 } 3914 3915 bool os::find(address addr) { 3916 Dl_info dlinfo; 3917 memset(&dlinfo, 0, sizeof(dlinfo)); 3918 if (dladdr(addr, &dlinfo)) { 3919 tty->print(PTR_FORMAT ": ", addr); 3920 if (dlinfo.dli_sname != NULL) { 3921 tty->print("%s+%#x", dlinfo.dli_sname, 3922 addr - (intptr_t)dlinfo.dli_saddr); 3923 } else if (dlinfo.dli_fname) { 3924 tty->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase); 3925 } else { 3926 tty->print("<absolute address>"); 3927 } 3928 if (dlinfo.dli_fname) { 3929 tty->print(" in %s", dlinfo.dli_fname); 3930 } 3931 if (dlinfo.dli_fbase) { 3932 tty->print(" at " PTR_FORMAT, dlinfo.dli_fbase); 3933 } 3934 tty->cr(); 3935 3936 if (Verbose) { 3937 // decode some bytes around the PC 3938 address begin = same_page(addr-40, addr); 3939 address end = same_page(addr+40, addr); 3940 address lowest = (address) dlinfo.dli_sname; 3941 if (!lowest) lowest = (address) dlinfo.dli_fbase; 3942 if (begin < lowest) begin = lowest; 3943 Dl_info dlinfo2; 3944 if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr 3945 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) 3946 end = (address) dlinfo2.dli_saddr; 3947 Disassembler::decode(begin, end); 3948 } 3949 return true; 3950 } 3951 return false; 3952 } 3953 3954 #endif 3955 3956 //////////////////////////////////////////////////////////////////////////////// 3957 // misc 3958 3959 // This does not do anything on Linux. This is basically a hook for being 3960 // able to use structured exception handling (thread-local exception filters) 3961 // on, e.g., Win32. 3962 void 3963 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, 3964 JavaCallArguments* args, Thread* thread) { 3965 f(value, method, args, thread); 3966 } 3967 3968 void os::print_statistics() { 3969 } 3970 3971 int os::message_box(const char* title, const char* message) { 3972 int i; 3973 fdStream err(defaultStream::error_fd()); 3974 for (i = 0; i < 78; i++) err.print_raw("="); 3975 err.cr(); 3976 err.print_raw_cr(title); 3977 for (i = 0; i < 78; i++) err.print_raw("-"); 3978 err.cr(); 3979 err.print_raw_cr(message); 3980 for (i = 0; i < 78; i++) err.print_raw("="); 3981 err.cr(); 3982 3983 char buf[16]; 3984 // Prevent process from exiting upon "read error" without consuming all CPU 3985 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } 3986 3987 return buf[0] == 'y' || buf[0] == 'Y'; 3988 } 3989 3990 int os::stat(const char *path, struct stat *sbuf) { 3991 char pathbuf[MAX_PATH]; 3992 if (strlen(path) > MAX_PATH - 1) { 3993 errno = ENAMETOOLONG; 3994 return -1; 3995 } 3996 hpi::native_path(strcpy(pathbuf, path)); 3997 return ::stat(pathbuf, sbuf); 3998 } 3999 4000 bool os::check_heap(bool force) { 4001 return true; 4002 } 4003 4004 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) { 4005 return ::vsnprintf(buf, count, format, args); 4006 } 4007 4008 // Is a (classpath) directory empty? 4009 bool os::dir_is_empty(const char* path) { 4010 DIR *dir = NULL; 4011 struct dirent *ptr; 4012 4013 dir = opendir(path); 4014 if (dir == NULL) return true; 4015 4016 /* Scan the directory */ 4017 bool result = true; 4018 char buf[sizeof(struct dirent) + MAX_PATH]; 4019 while (result && (ptr = ::readdir(dir)) != NULL) { 4020 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { 4021 result = false; 4022 } 4023 } 4024 closedir(dir); 4025 return result; 4026 } 4027 4028 // create binary file, rewriting existing file if required 4029 int os::create_binary_file(const char* path, bool rewrite_existing) { 4030 int oflags = O_WRONLY | O_CREAT; 4031 if (!rewrite_existing) { 4032 oflags |= O_EXCL; 4033 } 4034 return ::open64(path, oflags, S_IREAD | S_IWRITE); 4035 } 4036 4037 // return current position of file pointer 4038 jlong os::current_file_offset(int fd) { 4039 return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR); 4040 } 4041 4042 // move file pointer to the specified offset 4043 jlong os::seek_to_file_offset(int fd, jlong offset) { 4044 return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET); 4045 } 4046 4047 // Map a block of memory. 4048 char* os::map_memory(int fd, const char* file_name, size_t file_offset, 4049 char *addr, size_t bytes, bool read_only, 4050 bool allow_exec) { 4051 int prot; 4052 int flags; 4053 4054 if (read_only) { 4055 prot = PROT_READ; 4056 flags = MAP_SHARED; 4057 } else { 4058 prot = PROT_READ | PROT_WRITE; 4059 flags = MAP_PRIVATE; 4060 } 4061 4062 if (allow_exec) { 4063 prot |= PROT_EXEC; 4064 } 4065 4066 if (addr != NULL) { 4067 flags |= MAP_FIXED; 4068 } 4069 4070 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags, 4071 fd, file_offset); 4072 if (mapped_address == MAP_FAILED) { 4073 return NULL; 4074 } 4075 return mapped_address; 4076 } 4077 4078 4079 // Remap a block of memory. 4080 char* os::remap_memory(int fd, const char* file_name, size_t file_offset, 4081 char *addr, size_t bytes, bool read_only, 4082 bool allow_exec) { 4083 // same as map_memory() on this OS 4084 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, 4085 allow_exec); 4086 } 4087 4088 4089 // Unmap a block of memory. 4090 bool os::unmap_memory(char* addr, size_t bytes) { 4091 return munmap(addr, bytes) == 0; 4092 } 4093 4094 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time); 4095 4096 static clockid_t thread_cpu_clockid(Thread* thread) { 4097 pthread_t tid = thread->osthread()->pthread_id(); 4098 clockid_t clockid; 4099 4100 // Get thread clockid 4101 int rc = os::Linux::pthread_getcpuclockid(tid, &clockid); 4102 assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code"); 4103 return clockid; 4104 } 4105 4106 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) 4107 // are used by JVM M&M and JVMTI to get user+sys or user CPU time 4108 // of a thread. 4109 // 4110 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns 4111 // the fast estimate available on the platform. 4112 4113 jlong os::current_thread_cpu_time() { 4114 if (os::Linux::supports_fast_thread_cpu_time()) { 4115 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); 4116 } else { 4117 // return user + sys since the cost is the same 4118 return slow_thread_cpu_time(Thread::current(), true /* user + sys */); 4119 } 4120 } 4121 4122 jlong os::thread_cpu_time(Thread* thread) { 4123 // consistent with what current_thread_cpu_time() returns 4124 if (os::Linux::supports_fast_thread_cpu_time()) { 4125 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread)); 4126 } else { 4127 return slow_thread_cpu_time(thread, true /* user + sys */); 4128 } 4129 } 4130 4131 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { 4132 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) { 4133 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); 4134 } else { 4135 return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time); 4136 } 4137 } 4138 4139 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 4140 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) { 4141 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread)); 4142 } else { 4143 return slow_thread_cpu_time(thread, user_sys_cpu_time); 4144 } 4145 } 4146 4147 // 4148 // -1 on error. 4149 // 4150 4151 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 4152 static bool proc_pid_cpu_avail = true; 4153 static bool proc_task_unchecked = true; 4154 static const char *proc_stat_path = "/proc/%d/stat"; 4155 pid_t tid = thread->osthread()->thread_id(); 4156 int i; 4157 char *s; 4158 char stat[2048]; 4159 int statlen; 4160 char proc_name[64]; 4161 int count; 4162 long sys_time, user_time; 4163 char string[64]; 4164 int idummy; 4165 long ldummy; 4166 FILE *fp; 4167 4168 // We first try accessing /proc/<pid>/cpu since this is faster to 4169 // process. If this file is not present (linux kernels 2.5 and above) 4170 // then we open /proc/<pid>/stat. 4171 if ( proc_pid_cpu_avail ) { 4172 sprintf(proc_name, "/proc/%d/cpu", tid); 4173 fp = fopen(proc_name, "r"); 4174 if ( fp != NULL ) { 4175 count = fscanf( fp, "%s %lu %lu\n", string, &user_time, &sys_time); 4176 fclose(fp); 4177 if ( count != 3 ) return -1; 4178 4179 if (user_sys_cpu_time) { 4180 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); 4181 } else { 4182 return (jlong)user_time * (1000000000 / clock_tics_per_sec); 4183 } 4184 } 4185 else proc_pid_cpu_avail = false; 4186 } 4187 4188 // The /proc/<tid>/stat aggregates per-process usage on 4189 // new Linux kernels 2.6+ where NPTL is supported. 4190 // The /proc/self/task/<tid>/stat still has the per-thread usage. 4191 // See bug 6328462. 4192 // There can be no directory /proc/self/task on kernels 2.4 with NPTL 4193 // and possibly in some other cases, so we check its availability. 4194 if (proc_task_unchecked && os::Linux::is_NPTL()) { 4195 // This is executed only once 4196 proc_task_unchecked = false; 4197 fp = fopen("/proc/self/task", "r"); 4198 if (fp != NULL) { 4199 proc_stat_path = "/proc/self/task/%d/stat"; 4200 fclose(fp); 4201 } 4202 } 4203 4204 sprintf(proc_name, proc_stat_path, tid); 4205 fp = fopen(proc_name, "r"); 4206 if ( fp == NULL ) return -1; 4207 statlen = fread(stat, 1, 2047, fp); 4208 stat[statlen] = '\0'; 4209 fclose(fp); 4210 4211 // Skip pid and the command string. Note that we could be dealing with 4212 // weird command names, e.g. user could decide to rename java launcher 4213 // to "java 1.4.2 :)", then the stat file would look like 4214 // 1234 (java 1.4.2 :)) R ... ... 4215 // We don't really need to know the command string, just find the last 4216 // occurrence of ")" and then start parsing from there. See bug 4726580. 4217 s = strrchr(stat, ')'); 4218 i = 0; 4219 if (s == NULL ) return -1; 4220 4221 // Skip blank chars 4222 do s++; while (isspace(*s)); 4223 4224 count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu", 4225 &idummy, &idummy, &idummy, &idummy, &idummy, &idummy, 4226 &ldummy, &ldummy, &ldummy, &ldummy, &ldummy, 4227 &user_time, &sys_time); 4228 if ( count != 13 ) return -1; 4229 if (user_sys_cpu_time) { 4230 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); 4231 } else { 4232 return (jlong)user_time * (1000000000 / clock_tics_per_sec); 4233 } 4234 } 4235 4236 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 4237 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 4238 info_ptr->may_skip_backward = false; // elapsed time not wall time 4239 info_ptr->may_skip_forward = false; // elapsed time not wall time 4240 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 4241 } 4242 4243 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 4244 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 4245 info_ptr->may_skip_backward = false; // elapsed time not wall time 4246 info_ptr->may_skip_forward = false; // elapsed time not wall time 4247 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned 4248 } 4249 4250 bool os::is_thread_cpu_time_supported() { 4251 return true; 4252 } 4253 4254 // System loadavg support. Returns -1 if load average cannot be obtained. 4255 // Linux doesn't yet have a (official) notion of processor sets, 4256 // so just return the system wide load average. 4257 int os::loadavg(double loadavg[], int nelem) { 4258 return ::getloadavg(loadavg, nelem); 4259 } 4260 4261 void os::pause() { 4262 char filename[MAX_PATH]; 4263 if (PauseAtStartupFile && PauseAtStartupFile[0]) { 4264 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); 4265 } else { 4266 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); 4267 } 4268 4269 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); 4270 if (fd != -1) { 4271 struct stat buf; 4272 close(fd); 4273 while (::stat(filename, &buf) == 0) { 4274 (void)::poll(NULL, 0, 100); 4275 } 4276 } else { 4277 jio_fprintf(stderr, 4278 "Could not open pause file '%s', continuing immediately.\n", filename); 4279 } 4280 } 4281 4282 extern "C" { 4283 4284 /** 4285 * NOTE: the following code is to keep the green threads code 4286 * in the libjava.so happy. Once the green threads is removed, 4287 * these code will no longer be needed. 4288 */ 4289 int 4290 jdk_waitpid(pid_t pid, int* status, int options) { 4291 return waitpid(pid, status, options); 4292 } 4293 4294 int 4295 fork1() { 4296 return fork(); 4297 } 4298 4299 int 4300 jdk_sem_init(sem_t *sem, int pshared, unsigned int value) { 4301 return sem_init(sem, pshared, value); 4302 } 4303 4304 int 4305 jdk_sem_post(sem_t *sem) { 4306 return sem_post(sem); 4307 } 4308 4309 int 4310 jdk_sem_wait(sem_t *sem) { 4311 return sem_wait(sem); 4312 } 4313 4314 int 4315 jdk_pthread_sigmask(int how , const sigset_t* newmask, sigset_t* oldmask) { 4316 return pthread_sigmask(how , newmask, oldmask); 4317 } 4318 4319 } 4320 4321 // Refer to the comments in os_solaris.cpp park-unpark. 4322 // 4323 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can 4324 // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable. 4325 // For specifics regarding the bug see GLIBC BUGID 261237 : 4326 // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html. 4327 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future 4328 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar 4329 // is used. (The simple C test-case provided in the GLIBC bug report manifests the 4330 // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos() 4331 // and monitorenter when we're using 1-0 locking. All those operations may result in 4332 // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version 4333 // of libpthread avoids the problem, but isn't practical. 4334 // 4335 // Possible remedies: 4336 // 4337 // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work. 4338 // This is palliative and probabilistic, however. If the thread is preempted 4339 // between the call to compute_abstime() and pthread_cond_timedwait(), more 4340 // than the minimum period may have passed, and the abstime may be stale (in the 4341 // past) resultin in a hang. Using this technique reduces the odds of a hang 4342 // but the JVM is still vulnerable, particularly on heavily loaded systems. 4343 // 4344 // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead 4345 // of the usual flag-condvar-mutex idiom. The write side of the pipe is set 4346 // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo) 4347 // reduces to poll()+read(). This works well, but consumes 2 FDs per extant 4348 // thread. 4349 // 4350 // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread 4351 // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing 4352 // a timeout request to the chron thread and then blocking via pthread_cond_wait(). 4353 // This also works well. In fact it avoids kernel-level scalability impediments 4354 // on certain platforms that don't handle lots of active pthread_cond_timedwait() 4355 // timers in a graceful fashion. 4356 // 4357 // 4. When the abstime value is in the past it appears that control returns 4358 // correctly from pthread_cond_timedwait(), but the condvar is left corrupt. 4359 // Subsequent timedwait/wait calls may hang indefinitely. Given that, we 4360 // can avoid the problem by reinitializing the condvar -- by cond_destroy() 4361 // followed by cond_init() -- after all calls to pthread_cond_timedwait(). 4362 // It may be possible to avoid reinitialization by checking the return 4363 // value from pthread_cond_timedwait(). In addition to reinitializing the 4364 // condvar we must establish the invariant that cond_signal() is only called 4365 // within critical sections protected by the adjunct mutex. This prevents 4366 // cond_signal() from "seeing" a condvar that's in the midst of being 4367 // reinitialized or that is corrupt. Sadly, this invariant obviates the 4368 // desirable signal-after-unlock optimization that avoids futile context switching. 4369 // 4370 // I'm also concerned that some versions of NTPL might allocate an auxilliary 4371 // structure when a condvar is used or initialized. cond_destroy() would 4372 // release the helper structure. Our reinitialize-after-timedwait fix 4373 // put excessive stress on malloc/free and locks protecting the c-heap. 4374 // 4375 // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag. 4376 // It may be possible to refine (4) by checking the kernel and NTPL verisons 4377 // and only enabling the work-around for vulnerable environments. 4378 4379 // utility to compute the abstime argument to timedwait: 4380 // millis is the relative timeout time 4381 // abstime will be the absolute timeout time 4382 // TODO: replace compute_abstime() with unpackTime() 4383 4384 static struct timespec* compute_abstime(timespec* abstime, jlong millis) { 4385 if (millis < 0) millis = 0; 4386 struct timeval now; 4387 int status = gettimeofday(&now, NULL); 4388 assert(status == 0, "gettimeofday"); 4389 jlong seconds = millis / 1000; 4390 millis %= 1000; 4391 if (seconds > 50000000) { // see man cond_timedwait(3T) 4392 seconds = 50000000; 4393 } 4394 abstime->tv_sec = now.tv_sec + seconds; 4395 long usec = now.tv_usec + millis * 1000; 4396 if (usec >= 1000000) { 4397 abstime->tv_sec += 1; 4398 usec -= 1000000; 4399 } 4400 abstime->tv_nsec = usec * 1000; 4401 return abstime; 4402 } 4403 4404 4405 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately. 4406 // Conceptually TryPark() should be equivalent to park(0). 4407 4408 int os::PlatformEvent::TryPark() { 4409 for (;;) { 4410 const int v = _Event ; 4411 guarantee ((v == 0) || (v == 1), "invariant") ; 4412 if (Atomic::cmpxchg (0, &_Event, v) == v) return v ; 4413 } 4414 } 4415 4416 void os::PlatformEvent::park() { // AKA "down()" 4417 // Invariant: Only the thread associated with the Event/PlatformEvent 4418 // may call park(). 4419 // TODO: assert that _Assoc != NULL or _Assoc == Self 4420 int v ; 4421 for (;;) { 4422 v = _Event ; 4423 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; 4424 } 4425 guarantee (v >= 0, "invariant") ; 4426 if (v == 0) { 4427 // Do this the hard way by blocking ... 4428 int status = pthread_mutex_lock(_mutex); 4429 assert_status(status == 0, status, "mutex_lock"); 4430 guarantee (_nParked == 0, "invariant") ; 4431 ++ _nParked ; 4432 while (_Event < 0) { 4433 status = pthread_cond_wait(_cond, _mutex); 4434 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... 4435 // Treat this the same as if the wait was interrupted 4436 if (status == ETIME) { status = EINTR; } 4437 assert_status(status == 0 || status == EINTR, status, "cond_wait"); 4438 } 4439 -- _nParked ; 4440 4441 // In theory we could move the ST of 0 into _Event past the unlock(), 4442 // but then we'd need a MEMBAR after the ST. 4443 _Event = 0 ; 4444 status = pthread_mutex_unlock(_mutex); 4445 assert_status(status == 0, status, "mutex_unlock"); 4446 } 4447 guarantee (_Event >= 0, "invariant") ; 4448 } 4449 4450 int os::PlatformEvent::park(jlong millis) { 4451 guarantee (_nParked == 0, "invariant") ; 4452 4453 int v ; 4454 for (;;) { 4455 v = _Event ; 4456 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; 4457 } 4458 guarantee (v >= 0, "invariant") ; 4459 if (v != 0) return OS_OK ; 4460 4461 // We do this the hard way, by blocking the thread. 4462 // Consider enforcing a minimum timeout value. 4463 struct timespec abst; 4464 compute_abstime(&abst, millis); 4465 4466 int ret = OS_TIMEOUT; 4467 int status = pthread_mutex_lock(_mutex); 4468 assert_status(status == 0, status, "mutex_lock"); 4469 guarantee (_nParked == 0, "invariant") ; 4470 ++_nParked ; 4471 4472 // Object.wait(timo) will return because of 4473 // (a) notification 4474 // (b) timeout 4475 // (c) thread.interrupt 4476 // 4477 // Thread.interrupt and object.notify{All} both call Event::set. 4478 // That is, we treat thread.interrupt as a special case of notification. 4479 // The underlying Solaris implementation, cond_timedwait, admits 4480 // spurious/premature wakeups, but the JLS/JVM spec prevents the 4481 // JVM from making those visible to Java code. As such, we must 4482 // filter out spurious wakeups. We assume all ETIME returns are valid. 4483 // 4484 // TODO: properly differentiate simultaneous notify+interrupt. 4485 // In that case, we should propagate the notify to another waiter. 4486 4487 while (_Event < 0) { 4488 status = os::Linux::safe_cond_timedwait(_cond, _mutex, &abst); 4489 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 4490 pthread_cond_destroy (_cond); 4491 pthread_cond_init (_cond, NULL) ; 4492 } 4493 assert_status(status == 0 || status == EINTR || 4494 status == ETIME || status == ETIMEDOUT, 4495 status, "cond_timedwait"); 4496 if (!FilterSpuriousWakeups) break ; // previous semantics 4497 if (status == ETIME || status == ETIMEDOUT) break ; 4498 // We consume and ignore EINTR and spurious wakeups. 4499 } 4500 --_nParked ; 4501 if (_Event >= 0) { 4502 ret = OS_OK; 4503 } 4504 _Event = 0 ; 4505 status = pthread_mutex_unlock(_mutex); 4506 assert_status(status == 0, status, "mutex_unlock"); 4507 assert (_nParked == 0, "invariant") ; 4508 return ret; 4509 } 4510 4511 void os::PlatformEvent::unpark() { 4512 int v, AnyWaiters ; 4513 for (;;) { 4514 v = _Event ; 4515 if (v > 0) { 4516 // The LD of _Event could have reordered or be satisfied 4517 // by a read-aside from this processor's write buffer. 4518 // To avoid problems execute a barrier and then 4519 // ratify the value. 4520 OrderAccess::fence() ; 4521 if (_Event == v) return ; 4522 continue ; 4523 } 4524 if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ; 4525 } 4526 if (v < 0) { 4527 // Wait for the thread associated with the event to vacate 4528 int status = pthread_mutex_lock(_mutex); 4529 assert_status(status == 0, status, "mutex_lock"); 4530 AnyWaiters = _nParked ; 4531 assert (AnyWaiters == 0 || AnyWaiters == 1, "invariant") ; 4532 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) { 4533 AnyWaiters = 0 ; 4534 pthread_cond_signal (_cond); 4535 } 4536 status = pthread_mutex_unlock(_mutex); 4537 assert_status(status == 0, status, "mutex_unlock"); 4538 if (AnyWaiters != 0) { 4539 status = pthread_cond_signal(_cond); 4540 assert_status(status == 0, status, "cond_signal"); 4541 } 4542 } 4543 4544 // Note that we signal() _after dropping the lock for "immortal" Events. 4545 // This is safe and avoids a common class of futile wakeups. In rare 4546 // circumstances this can cause a thread to return prematurely from 4547 // cond_{timed}wait() but the spurious wakeup is benign and the victim will 4548 // simply re-test the condition and re-park itself. 4549 } 4550 4551 4552 // JSR166 4553 // ------------------------------------------------------- 4554 4555 /* 4556 * The solaris and linux implementations of park/unpark are fairly 4557 * conservative for now, but can be improved. They currently use a 4558 * mutex/condvar pair, plus a a count. 4559 * Park decrements count if > 0, else does a condvar wait. Unpark 4560 * sets count to 1 and signals condvar. Only one thread ever waits 4561 * on the condvar. Contention seen when trying to park implies that someone 4562 * is unparking you, so don't wait. And spurious returns are fine, so there 4563 * is no need to track notifications. 4564 */ 4565 4566 4567 #define NANOSECS_PER_SEC 1000000000 4568 #define NANOSECS_PER_MILLISEC 1000000 4569 #define MAX_SECS 100000000 4570 /* 4571 * This code is common to linux and solaris and will be moved to a 4572 * common place in dolphin. 4573 * 4574 * The passed in time value is either a relative time in nanoseconds 4575 * or an absolute time in milliseconds. Either way it has to be unpacked 4576 * into suitable seconds and nanoseconds components and stored in the 4577 * given timespec structure. 4578 * Given time is a 64-bit value and the time_t used in the timespec is only 4579 * a signed-32-bit value (except on 64-bit Linux) we have to watch for 4580 * overflow if times way in the future are given. Further on Solaris versions 4581 * prior to 10 there is a restriction (see cond_timedwait) that the specified 4582 * number of seconds, in abstime, is less than current_time + 100,000,000. 4583 * As it will be 28 years before "now + 100000000" will overflow we can 4584 * ignore overflow and just impose a hard-limit on seconds using the value 4585 * of "now + 100,000,000". This places a limit on the timeout of about 3.17 4586 * years from "now". 4587 */ 4588 4589 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) { 4590 assert (time > 0, "convertTime"); 4591 4592 struct timeval now; 4593 int status = gettimeofday(&now, NULL); 4594 assert(status == 0, "gettimeofday"); 4595 4596 time_t max_secs = now.tv_sec + MAX_SECS; 4597 4598 if (isAbsolute) { 4599 jlong secs = time / 1000; 4600 if (secs > max_secs) { 4601 absTime->tv_sec = max_secs; 4602 } 4603 else { 4604 absTime->tv_sec = secs; 4605 } 4606 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; 4607 } 4608 else { 4609 jlong secs = time / NANOSECS_PER_SEC; 4610 if (secs >= MAX_SECS) { 4611 absTime->tv_sec = max_secs; 4612 absTime->tv_nsec = 0; 4613 } 4614 else { 4615 absTime->tv_sec = now.tv_sec + secs; 4616 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; 4617 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { 4618 absTime->tv_nsec -= NANOSECS_PER_SEC; 4619 ++absTime->tv_sec; // note: this must be <= max_secs 4620 } 4621 } 4622 } 4623 assert(absTime->tv_sec >= 0, "tv_sec < 0"); 4624 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); 4625 assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); 4626 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); 4627 } 4628 4629 void Parker::park(bool isAbsolute, jlong time) { 4630 // Optional fast-path check: 4631 // Return immediately if a permit is available. 4632 if (_counter > 0) { 4633 _counter = 0 ; 4634 return ; 4635 } 4636 4637 Thread* thread = Thread::current(); 4638 assert(thread->is_Java_thread(), "Must be JavaThread"); 4639 JavaThread *jt = (JavaThread *)thread; 4640 4641 // Optional optimization -- avoid state transitions if there's an interrupt pending. 4642 // Check interrupt before trying to wait 4643 if (Thread::is_interrupted(thread, false)) { 4644 return; 4645 } 4646 4647 // Next, demultiplex/decode time arguments 4648 timespec absTime; 4649 if (time < 0) { // don't wait at all 4650 return; 4651 } 4652 if (time > 0) { 4653 unpackTime(&absTime, isAbsolute, time); 4654 } 4655 4656 4657 // Enter safepoint region 4658 // Beware of deadlocks such as 6317397. 4659 // The per-thread Parker:: mutex is a classic leaf-lock. 4660 // In particular a thread must never block on the Threads_lock while 4661 // holding the Parker:: mutex. If safepoints are pending both the 4662 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. 4663 ThreadBlockInVM tbivm(jt); 4664 4665 // Don't wait if cannot get lock since interference arises from 4666 // unblocking. Also. check interrupt before trying wait 4667 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) { 4668 return; 4669 } 4670 4671 int status ; 4672 if (_counter > 0) { // no wait needed 4673 _counter = 0; 4674 status = pthread_mutex_unlock(_mutex); 4675 assert (status == 0, "invariant") ; 4676 return; 4677 } 4678 4679 #ifdef ASSERT 4680 // Don't catch signals while blocked; let the running threads have the signals. 4681 // (This allows a debugger to break into the running thread.) 4682 sigset_t oldsigs; 4683 sigset_t* allowdebug_blocked = os::Linux::allowdebug_blocked_signals(); 4684 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs); 4685 #endif 4686 4687 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 4688 jt->set_suspend_equivalent(); 4689 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 4690 4691 if (time == 0) { 4692 status = pthread_cond_wait (_cond, _mutex) ; 4693 } else { 4694 status = os::Linux::safe_cond_timedwait (_cond, _mutex, &absTime) ; 4695 if (status != 0 && WorkAroundNPTLTimedWaitHang) { 4696 pthread_cond_destroy (_cond) ; 4697 pthread_cond_init (_cond, NULL); 4698 } 4699 } 4700 assert_status(status == 0 || status == EINTR || 4701 status == ETIME || status == ETIMEDOUT, 4702 status, "cond_timedwait"); 4703 4704 #ifdef ASSERT 4705 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); 4706 #endif 4707 4708 _counter = 0 ; 4709 status = pthread_mutex_unlock(_mutex) ; 4710 assert_status(status == 0, status, "invariant") ; 4711 // If externally suspended while waiting, re-suspend 4712 if (jt->handle_special_suspend_equivalent_condition()) { 4713 jt->java_suspend_self(); 4714 } 4715 4716 } 4717 4718 void Parker::unpark() { 4719 int s, status ; 4720 status = pthread_mutex_lock(_mutex); 4721 assert (status == 0, "invariant") ; 4722 s = _counter; 4723 _counter = 1; 4724 if (s < 1) { 4725 if (WorkAroundNPTLTimedWaitHang) { 4726 status = pthread_cond_signal (_cond) ; 4727 assert (status == 0, "invariant") ; 4728 status = pthread_mutex_unlock(_mutex); 4729 assert (status == 0, "invariant") ; 4730 } else { 4731 status = pthread_mutex_unlock(_mutex); 4732 assert (status == 0, "invariant") ; 4733 status = pthread_cond_signal (_cond) ; 4734 assert (status == 0, "invariant") ; 4735 } 4736 } else { 4737 pthread_mutex_unlock(_mutex); 4738 assert (status == 0, "invariant") ; 4739 } 4740 } 4741 4742 4743 extern char** environ; 4744 4745 #ifndef __NR_fork 4746 #define __NR_fork IA32_ONLY(2) IA64_ONLY(not defined) AMD64_ONLY(57) 4747 #endif 4748 4749 #ifndef __NR_execve 4750 #define __NR_execve IA32_ONLY(11) IA64_ONLY(1033) AMD64_ONLY(59) 4751 #endif 4752 4753 // Run the specified command in a separate process. Return its exit value, 4754 // or -1 on failure (e.g. can't fork a new process). 4755 // Unlike system(), this function can be called from signal handler. It 4756 // doesn't block SIGINT et al. 4757 int os::fork_and_exec(char* cmd) { 4758 const char * argv[4] = {"sh", "-c", cmd, NULL}; 4759 4760 // fork() in LinuxThreads/NPTL is not async-safe. It needs to run 4761 // pthread_atfork handlers and reset pthread library. All we need is a 4762 // separate process to execve. Make a direct syscall to fork process. 4763 // On IA64 there's no fork syscall, we have to use fork() and hope for 4764 // the best... 4765 pid_t pid = NOT_IA64(syscall(__NR_fork);) 4766 IA64_ONLY(fork();) 4767 4768 if (pid < 0) { 4769 // fork failed 4770 return -1; 4771 4772 } else if (pid == 0) { 4773 // child process 4774 4775 // execve() in LinuxThreads will call pthread_kill_other_threads_np() 4776 // first to kill every thread on the thread list. Because this list is 4777 // not reset by fork() (see notes above), execve() will instead kill 4778 // every thread in the parent process. We know this is the only thread 4779 // in the new process, so make a system call directly. 4780 // IA64 should use normal execve() from glibc to match the glibc fork() 4781 // above. 4782 NOT_IA64(syscall(__NR_execve, "/bin/sh", argv, environ);) 4783 IA64_ONLY(execve("/bin/sh", (char* const*)argv, environ);) 4784 4785 // execve failed 4786 _exit(-1); 4787 4788 } else { 4789 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't 4790 // care about the actual exit code, for now. 4791 4792 int status; 4793 4794 // Wait for the child process to exit. This returns immediately if 4795 // the child has already exited. */ 4796 while (waitpid(pid, &status, 0) < 0) { 4797 switch (errno) { 4798 case ECHILD: return 0; 4799 case EINTR: break; 4800 default: return -1; 4801 } 4802 } 4803 4804 if (WIFEXITED(status)) { 4805 // The child exited normally; get its exit code. 4806 return WEXITSTATUS(status); 4807 } else if (WIFSIGNALED(status)) { 4808 // The child exited because of a signal 4809 // The best value to return is 0x80 + signal number, 4810 // because that is what all Unix shells do, and because 4811 // it allows callers to distinguish between process exit and 4812 // process death by signal. 4813 return 0x80 + WTERMSIG(status); 4814 } else { 4815 // Unknown exit code; pass it through 4816 return status; 4817 } 4818 } 4819 }