1 /* 2 * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "utilities/globalDefinitions.hpp" 26 #include "prims/jvm.h" 27 #include "semaphore_posix.hpp" 28 #include "runtime/frame.inline.hpp" 29 #include "runtime/interfaceSupport.hpp" 30 #include "runtime/os.hpp" 31 #include "utilities/macros.hpp" 32 #include "utilities/vmError.hpp" 33 34 #include <dlfcn.h> 35 #include <pthread.h> 36 #include <semaphore.h> 37 #include <signal.h> 38 #include <sys/resource.h> 39 #include <sys/utsname.h> 40 #include <time.h> 41 #include <unistd.h> 42 43 // Todo: provide a os::get_max_process_id() or similar. Number of processes 44 // may have been configured, can be read more accurately from proc fs etc. 45 #ifndef MAX_PID 46 #define MAX_PID INT_MAX 47 #endif 48 #define IS_VALID_PID(p) (p > 0 && p < MAX_PID) 49 50 // Check core dump limit and report possible place where core can be found 51 void os::check_dump_limit(char* buffer, size_t bufferSize) { 52 if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && !CreateCoredumpOnCrash) { 53 jio_snprintf(buffer, bufferSize, "CreateCoredumpOnCrash is disabled from command line"); 54 VMError::record_coredump_status(buffer, false); 55 return; 56 } 57 58 int n; 59 struct rlimit rlim; 60 bool success; 61 62 char core_path[PATH_MAX]; 63 n = get_core_path(core_path, PATH_MAX); 64 65 if (n <= 0) { 66 jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id()); 67 success = true; 68 #ifdef LINUX 69 } else if (core_path[0] == '"') { // redirect to user process 70 jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path); 71 success = true; 72 #endif 73 } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) { 74 jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path); 75 success = true; 76 } else { 77 switch(rlim.rlim_cur) { 78 case RLIM_INFINITY: 79 jio_snprintf(buffer, bufferSize, "%s", core_path); 80 success = true; 81 break; 82 case 0: 83 jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again"); 84 success = false; 85 break; 86 default: 87 jio_snprintf(buffer, bufferSize, "%s (max size " UINT64_FORMAT " kB). To ensure a full core dump, try \"ulimit -c unlimited\" before starting Java again", core_path, uint64_t(rlim.rlim_cur) / 1024); 88 success = true; 89 break; 90 } 91 } 92 93 VMError::record_coredump_status(buffer, success); 94 } 95 96 int os::get_native_stack(address* stack, int frames, int toSkip) { 97 int frame_idx = 0; 98 int num_of_frames; // number of frames captured 99 frame fr = os::current_frame(); 100 while (fr.pc() && frame_idx < frames) { 101 if (toSkip > 0) { 102 toSkip --; 103 } else { 104 stack[frame_idx ++] = fr.pc(); 105 } 106 if (fr.fp() == NULL || fr.cb() != NULL || 107 fr.sender_pc() == NULL || os::is_first_C_frame(&fr)) break; 108 109 if (fr.sender_pc() && !os::is_first_C_frame(&fr)) { 110 fr = os::get_sender_for_C_frame(&fr); 111 } else { 112 break; 113 } 114 } 115 num_of_frames = frame_idx; 116 for (; frame_idx < frames; frame_idx ++) { 117 stack[frame_idx] = NULL; 118 } 119 120 return num_of_frames; 121 } 122 123 124 bool os::unsetenv(const char* name) { 125 assert(name != NULL, "Null pointer"); 126 return (::unsetenv(name) == 0); 127 } 128 129 int os::get_last_error() { 130 return errno; 131 } 132 133 bool os::is_debugger_attached() { 134 // not implemented 135 return false; 136 } 137 138 void os::wait_for_keypress_at_exit(void) { 139 // don't do anything on posix platforms 140 return; 141 } 142 143 // Multiple threads can race in this code, and can remap over each other with MAP_FIXED, 144 // so on posix, unmap the section at the start and at the end of the chunk that we mapped 145 // rather than unmapping and remapping the whole chunk to get requested alignment. 146 char* os::reserve_memory_aligned(size_t size, size_t alignment) { 147 assert((alignment & (os::vm_allocation_granularity() - 1)) == 0, 148 "Alignment must be a multiple of allocation granularity (page size)"); 149 assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned"); 150 151 size_t extra_size = size + alignment; 152 assert(extra_size >= size, "overflow, size is too large to allow alignment"); 153 154 char* extra_base = os::reserve_memory(extra_size, NULL, alignment); 155 156 if (extra_base == NULL) { 157 return NULL; 158 } 159 160 // Do manual alignment 161 char* aligned_base = (char*) align_size_up((uintptr_t) extra_base, alignment); 162 163 // [ | | ] 164 // ^ extra_base 165 // ^ extra_base + begin_offset == aligned_base 166 // extra_base + begin_offset + size ^ 167 // extra_base + extra_size ^ 168 // |<>| == begin_offset 169 // end_offset == |<>| 170 size_t begin_offset = aligned_base - extra_base; 171 size_t end_offset = (extra_base + extra_size) - (aligned_base + size); 172 173 if (begin_offset > 0) { 174 os::release_memory(extra_base, begin_offset); 175 } 176 177 if (end_offset > 0) { 178 os::release_memory(extra_base + begin_offset + size, end_offset); 179 } 180 181 return aligned_base; 182 } 183 184 int os::log_vsnprintf(char* buf, size_t len, const char* fmt, va_list args) { 185 return vsnprintf(buf, len, fmt, args); 186 } 187 188 int os::get_fileno(FILE* fp) { 189 return NOT_AIX(::)fileno(fp); 190 } 191 192 struct tm* os::gmtime_pd(const time_t* clock, struct tm* res) { 193 return gmtime_r(clock, res); 194 } 195 196 void os::Posix::print_load_average(outputStream* st) { 197 st->print("load average:"); 198 double loadavg[3]; 199 os::loadavg(loadavg, 3); 200 st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]); 201 st->cr(); 202 } 203 204 void os::Posix::print_rlimit_info(outputStream* st) { 205 st->print("rlimit:"); 206 struct rlimit rlim; 207 208 st->print(" STACK "); 209 getrlimit(RLIMIT_STACK, &rlim); 210 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 211 else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024); 212 213 st->print(", CORE "); 214 getrlimit(RLIMIT_CORE, &rlim); 215 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 216 else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024); 217 218 // Isn't there on solaris 219 #if defined(AIX) 220 st->print(", NPROC "); 221 st->print("%d", sysconf(_SC_CHILD_MAX)); 222 #elif !defined(SOLARIS) 223 st->print(", NPROC "); 224 getrlimit(RLIMIT_NPROC, &rlim); 225 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 226 else st->print(UINT64_FORMAT, uint64_t(rlim.rlim_cur)); 227 #endif 228 229 st->print(", NOFILE "); 230 getrlimit(RLIMIT_NOFILE, &rlim); 231 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 232 else st->print(UINT64_FORMAT, uint64_t(rlim.rlim_cur)); 233 234 st->print(", AS "); 235 getrlimit(RLIMIT_AS, &rlim); 236 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 237 else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024); 238 239 st->print(", DATA "); 240 getrlimit(RLIMIT_DATA, &rlim); 241 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 242 else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024); 243 244 st->print(", FSIZE "); 245 getrlimit(RLIMIT_FSIZE, &rlim); 246 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); 247 else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024); 248 249 st->cr(); 250 } 251 252 void os::Posix::print_uname_info(outputStream* st) { 253 // kernel 254 st->print("uname:"); 255 struct utsname name; 256 uname(&name); 257 st->print("%s ", name.sysname); 258 #ifdef ASSERT 259 st->print("%s ", name.nodename); 260 #endif 261 st->print("%s ", name.release); 262 st->print("%s ", name.version); 263 st->print("%s", name.machine); 264 st->cr(); 265 } 266 267 bool os::get_host_name(char* buf, size_t buflen) { 268 struct utsname name; 269 uname(&name); 270 jio_snprintf(buf, buflen, "%s", name.nodename); 271 return true; 272 } 273 274 bool os::has_allocatable_memory_limit(julong* limit) { 275 struct rlimit rlim; 276 int getrlimit_res = getrlimit(RLIMIT_AS, &rlim); 277 // if there was an error when calling getrlimit, assume that there is no limitation 278 // on virtual memory. 279 bool result; 280 if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) { 281 result = false; 282 } else { 283 *limit = (julong)rlim.rlim_cur; 284 result = true; 285 } 286 #ifdef _LP64 287 return result; 288 #else 289 // arbitrary virtual space limit for 32 bit Unices found by testing. If 290 // getrlimit above returned a limit, bound it with this limit. Otherwise 291 // directly use it. 292 const julong max_virtual_limit = (julong)3800*M; 293 if (result) { 294 *limit = MIN2(*limit, max_virtual_limit); 295 } else { 296 *limit = max_virtual_limit; 297 } 298 299 // bound by actually allocatable memory. The algorithm uses two bounds, an 300 // upper and a lower limit. The upper limit is the current highest amount of 301 // memory that could not be allocated, the lower limit is the current highest 302 // amount of memory that could be allocated. 303 // The algorithm iteratively refines the result by halving the difference 304 // between these limits, updating either the upper limit (if that value could 305 // not be allocated) or the lower limit (if the that value could be allocated) 306 // until the difference between these limits is "small". 307 308 // the minimum amount of memory we care about allocating. 309 const julong min_allocation_size = M; 310 311 julong upper_limit = *limit; 312 313 // first check a few trivial cases 314 if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) { 315 *limit = upper_limit; 316 } else if (!is_allocatable(min_allocation_size)) { 317 // we found that not even min_allocation_size is allocatable. Return it 318 // anyway. There is no point to search for a better value any more. 319 *limit = min_allocation_size; 320 } else { 321 // perform the binary search. 322 julong lower_limit = min_allocation_size; 323 while ((upper_limit - lower_limit) > min_allocation_size) { 324 julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit; 325 temp_limit = align_size_down_(temp_limit, min_allocation_size); 326 if (is_allocatable(temp_limit)) { 327 lower_limit = temp_limit; 328 } else { 329 upper_limit = temp_limit; 330 } 331 } 332 *limit = lower_limit; 333 } 334 return true; 335 #endif 336 } 337 338 const char* os::get_current_directory(char *buf, size_t buflen) { 339 return getcwd(buf, buflen); 340 } 341 342 FILE* os::open(int fd, const char* mode) { 343 return ::fdopen(fd, mode); 344 } 345 346 void os::flockfile(FILE* fp) { 347 ::flockfile(fp); 348 } 349 350 void os::funlockfile(FILE* fp) { 351 ::funlockfile(fp); 352 } 353 354 // Builds a platform dependent Agent_OnLoad_<lib_name> function name 355 // which is used to find statically linked in agents. 356 // Parameters: 357 // sym_name: Symbol in library we are looking for 358 // lib_name: Name of library to look in, NULL for shared libs. 359 // is_absolute_path == true if lib_name is absolute path to agent 360 // such as "/a/b/libL.so" 361 // == false if only the base name of the library is passed in 362 // such as "L" 363 char* os::build_agent_function_name(const char *sym_name, const char *lib_name, 364 bool is_absolute_path) { 365 char *agent_entry_name; 366 size_t len; 367 size_t name_len; 368 size_t prefix_len = strlen(JNI_LIB_PREFIX); 369 size_t suffix_len = strlen(JNI_LIB_SUFFIX); 370 const char *start; 371 372 if (lib_name != NULL) { 373 name_len = strlen(lib_name); 374 if (is_absolute_path) { 375 // Need to strip path, prefix and suffix 376 if ((start = strrchr(lib_name, *os::file_separator())) != NULL) { 377 lib_name = ++start; 378 } 379 if (strlen(lib_name) <= (prefix_len + suffix_len)) { 380 return NULL; 381 } 382 lib_name += prefix_len; 383 name_len = strlen(lib_name) - suffix_len; 384 } 385 } 386 len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2; 387 agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread); 388 if (agent_entry_name == NULL) { 389 return NULL; 390 } 391 strcpy(agent_entry_name, sym_name); 392 if (lib_name != NULL) { 393 strcat(agent_entry_name, "_"); 394 strncat(agent_entry_name, lib_name, name_len); 395 } 396 return agent_entry_name; 397 } 398 399 int os::sleep(Thread* thread, jlong millis, bool interruptible) { 400 assert(thread == Thread::current(), "thread consistency check"); 401 402 ParkEvent * const slp = thread->_SleepEvent ; 403 slp->reset() ; 404 OrderAccess::fence() ; 405 406 if (interruptible) { 407 jlong prevtime = javaTimeNanos(); 408 409 for (;;) { 410 if (os::is_interrupted(thread, true)) { 411 return OS_INTRPT; 412 } 413 414 jlong newtime = javaTimeNanos(); 415 416 if (newtime - prevtime < 0) { 417 // time moving backwards, should only happen if no monotonic clock 418 // not a guarantee() because JVM should not abort on kernel/glibc bugs 419 assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected in os::sleep(interruptible)"); 420 } else { 421 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; 422 } 423 424 if (millis <= 0) { 425 return OS_OK; 426 } 427 428 prevtime = newtime; 429 430 { 431 assert(thread->is_Java_thread(), "sanity check"); 432 JavaThread *jt = (JavaThread *) thread; 433 ThreadBlockInVM tbivm(jt); 434 OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */); 435 436 jt->set_suspend_equivalent(); 437 // cleared by handle_special_suspend_equivalent_condition() or 438 // java_suspend_self() via check_and_wait_while_suspended() 439 440 slp->park(millis); 441 442 // were we externally suspended while we were waiting? 443 jt->check_and_wait_while_suspended(); 444 } 445 } 446 } else { 447 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 448 jlong prevtime = javaTimeNanos(); 449 450 for (;;) { 451 // It'd be nice to avoid the back-to-back javaTimeNanos() calls on 452 // the 1st iteration ... 453 jlong newtime = javaTimeNanos(); 454 455 if (newtime - prevtime < 0) { 456 // time moving backwards, should only happen if no monotonic clock 457 // not a guarantee() because JVM should not abort on kernel/glibc bugs 458 assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected on os::sleep(!interruptible)"); 459 } else { 460 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; 461 } 462 463 if (millis <= 0) break ; 464 465 prevtime = newtime; 466 slp->park(millis); 467 } 468 return OS_OK ; 469 } 470 } 471 472 //////////////////////////////////////////////////////////////////////////////// 473 // interrupt support 474 475 void os::interrupt(Thread* thread) { 476 assert(Thread::current() == thread || Threads_lock->owned_by_self(), 477 "possibility of dangling Thread pointer"); 478 479 OSThread* osthread = thread->osthread(); 480 481 if (!osthread->interrupted()) { 482 osthread->set_interrupted(true); 483 // More than one thread can get here with the same value of osthread, 484 // resulting in multiple notifications. We do, however, want the store 485 // to interrupted() to be visible to other threads before we execute unpark(). 486 OrderAccess::fence(); 487 ParkEvent * const slp = thread->_SleepEvent ; 488 if (slp != NULL) slp->unpark() ; 489 } 490 491 // For JSR166. Unpark even if interrupt status already was set 492 if (thread->is_Java_thread()) 493 ((JavaThread*)thread)->parker()->unpark(); 494 495 ParkEvent * ev = thread->_ParkEvent ; 496 if (ev != NULL) ev->unpark() ; 497 498 } 499 500 bool os::is_interrupted(Thread* thread, bool clear_interrupted) { 501 assert(Thread::current() == thread || Threads_lock->owned_by_self(), 502 "possibility of dangling Thread pointer"); 503 504 OSThread* osthread = thread->osthread(); 505 506 bool interrupted = osthread->interrupted(); 507 508 // NOTE that since there is no "lock" around the interrupt and 509 // is_interrupted operations, there is the possibility that the 510 // interrupted flag (in osThread) will be "false" but that the 511 // low-level events will be in the signaled state. This is 512 // intentional. The effect of this is that Object.wait() and 513 // LockSupport.park() will appear to have a spurious wakeup, which 514 // is allowed and not harmful, and the possibility is so rare that 515 // it is not worth the added complexity to add yet another lock. 516 // For the sleep event an explicit reset is performed on entry 517 // to os::sleep, so there is no early return. It has also been 518 // recommended not to put the interrupted flag into the "event" 519 // structure because it hides the issue. 520 if (interrupted && clear_interrupted) { 521 osthread->set_interrupted(false); 522 // consider thread->_SleepEvent->reset() ... optional optimization 523 } 524 525 return interrupted; 526 } 527 528 529 530 static const struct { 531 int sig; const char* name; 532 } 533 g_signal_info[] = 534 { 535 { SIGABRT, "SIGABRT" }, 536 #ifdef SIGAIO 537 { SIGAIO, "SIGAIO" }, 538 #endif 539 { SIGALRM, "SIGALRM" }, 540 #ifdef SIGALRM1 541 { SIGALRM1, "SIGALRM1" }, 542 #endif 543 { SIGBUS, "SIGBUS" }, 544 #ifdef SIGCANCEL 545 { SIGCANCEL, "SIGCANCEL" }, 546 #endif 547 { SIGCHLD, "SIGCHLD" }, 548 #ifdef SIGCLD 549 { SIGCLD, "SIGCLD" }, 550 #endif 551 { SIGCONT, "SIGCONT" }, 552 #ifdef SIGCPUFAIL 553 { SIGCPUFAIL, "SIGCPUFAIL" }, 554 #endif 555 #ifdef SIGDANGER 556 { SIGDANGER, "SIGDANGER" }, 557 #endif 558 #ifdef SIGDIL 559 { SIGDIL, "SIGDIL" }, 560 #endif 561 #ifdef SIGEMT 562 { SIGEMT, "SIGEMT" }, 563 #endif 564 { SIGFPE, "SIGFPE" }, 565 #ifdef SIGFREEZE 566 { SIGFREEZE, "SIGFREEZE" }, 567 #endif 568 #ifdef SIGGFAULT 569 { SIGGFAULT, "SIGGFAULT" }, 570 #endif 571 #ifdef SIGGRANT 572 { SIGGRANT, "SIGGRANT" }, 573 #endif 574 { SIGHUP, "SIGHUP" }, 575 { SIGILL, "SIGILL" }, 576 { SIGINT, "SIGINT" }, 577 #ifdef SIGIO 578 { SIGIO, "SIGIO" }, 579 #endif 580 #ifdef SIGIOINT 581 { SIGIOINT, "SIGIOINT" }, 582 #endif 583 #ifdef SIGIOT 584 // SIGIOT is there for BSD compatibility, but on most Unices just a 585 // synonym for SIGABRT. The result should be "SIGABRT", not 586 // "SIGIOT". 587 #if (SIGIOT != SIGABRT ) 588 { SIGIOT, "SIGIOT" }, 589 #endif 590 #endif 591 #ifdef SIGKAP 592 { SIGKAP, "SIGKAP" }, 593 #endif 594 { SIGKILL, "SIGKILL" }, 595 #ifdef SIGLOST 596 { SIGLOST, "SIGLOST" }, 597 #endif 598 #ifdef SIGLWP 599 { SIGLWP, "SIGLWP" }, 600 #endif 601 #ifdef SIGLWPTIMER 602 { SIGLWPTIMER, "SIGLWPTIMER" }, 603 #endif 604 #ifdef SIGMIGRATE 605 { SIGMIGRATE, "SIGMIGRATE" }, 606 #endif 607 #ifdef SIGMSG 608 { SIGMSG, "SIGMSG" }, 609 #endif 610 { SIGPIPE, "SIGPIPE" }, 611 #ifdef SIGPOLL 612 { SIGPOLL, "SIGPOLL" }, 613 #endif 614 #ifdef SIGPRE 615 { SIGPRE, "SIGPRE" }, 616 #endif 617 { SIGPROF, "SIGPROF" }, 618 #ifdef SIGPTY 619 { SIGPTY, "SIGPTY" }, 620 #endif 621 #ifdef SIGPWR 622 { SIGPWR, "SIGPWR" }, 623 #endif 624 { SIGQUIT, "SIGQUIT" }, 625 #ifdef SIGRECONFIG 626 { SIGRECONFIG, "SIGRECONFIG" }, 627 #endif 628 #ifdef SIGRECOVERY 629 { SIGRECOVERY, "SIGRECOVERY" }, 630 #endif 631 #ifdef SIGRESERVE 632 { SIGRESERVE, "SIGRESERVE" }, 633 #endif 634 #ifdef SIGRETRACT 635 { SIGRETRACT, "SIGRETRACT" }, 636 #endif 637 #ifdef SIGSAK 638 { SIGSAK, "SIGSAK" }, 639 #endif 640 { SIGSEGV, "SIGSEGV" }, 641 #ifdef SIGSOUND 642 { SIGSOUND, "SIGSOUND" }, 643 #endif 644 #ifdef SIGSTKFLT 645 { SIGSTKFLT, "SIGSTKFLT" }, 646 #endif 647 { SIGSTOP, "SIGSTOP" }, 648 { SIGSYS, "SIGSYS" }, 649 #ifdef SIGSYSERROR 650 { SIGSYSERROR, "SIGSYSERROR" }, 651 #endif 652 #ifdef SIGTALRM 653 { SIGTALRM, "SIGTALRM" }, 654 #endif 655 { SIGTERM, "SIGTERM" }, 656 #ifdef SIGTHAW 657 { SIGTHAW, "SIGTHAW" }, 658 #endif 659 { SIGTRAP, "SIGTRAP" }, 660 #ifdef SIGTSTP 661 { SIGTSTP, "SIGTSTP" }, 662 #endif 663 { SIGTTIN, "SIGTTIN" }, 664 { SIGTTOU, "SIGTTOU" }, 665 #ifdef SIGURG 666 { SIGURG, "SIGURG" }, 667 #endif 668 { SIGUSR1, "SIGUSR1" }, 669 { SIGUSR2, "SIGUSR2" }, 670 #ifdef SIGVIRT 671 { SIGVIRT, "SIGVIRT" }, 672 #endif 673 { SIGVTALRM, "SIGVTALRM" }, 674 #ifdef SIGWAITING 675 { SIGWAITING, "SIGWAITING" }, 676 #endif 677 #ifdef SIGWINCH 678 { SIGWINCH, "SIGWINCH" }, 679 #endif 680 #ifdef SIGWINDOW 681 { SIGWINDOW, "SIGWINDOW" }, 682 #endif 683 { SIGXCPU, "SIGXCPU" }, 684 { SIGXFSZ, "SIGXFSZ" }, 685 #ifdef SIGXRES 686 { SIGXRES, "SIGXRES" }, 687 #endif 688 { -1, NULL } 689 }; 690 691 // Returned string is a constant. For unknown signals "UNKNOWN" is returned. 692 const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) { 693 694 const char* ret = NULL; 695 696 #ifdef SIGRTMIN 697 if (sig >= SIGRTMIN && sig <= SIGRTMAX) { 698 if (sig == SIGRTMIN) { 699 ret = "SIGRTMIN"; 700 } else if (sig == SIGRTMAX) { 701 ret = "SIGRTMAX"; 702 } else { 703 jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN); 704 return out; 705 } 706 } 707 #endif 708 709 if (sig > 0) { 710 for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) { 711 if (g_signal_info[idx].sig == sig) { 712 ret = g_signal_info[idx].name; 713 break; 714 } 715 } 716 } 717 718 if (!ret) { 719 if (!is_valid_signal(sig)) { 720 ret = "INVALID"; 721 } else { 722 ret = "UNKNOWN"; 723 } 724 } 725 726 if (out && outlen > 0) { 727 strncpy(out, ret, outlen); 728 out[outlen - 1] = '\0'; 729 } 730 return out; 731 } 732 733 int os::Posix::get_signal_number(const char* signal_name) { 734 char tmp[30]; 735 const char* s = signal_name; 736 if (s[0] != 'S' || s[1] != 'I' || s[2] != 'G') { 737 jio_snprintf(tmp, sizeof(tmp), "SIG%s", signal_name); 738 s = tmp; 739 } 740 for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) { 741 if (strcmp(g_signal_info[idx].name, s) == 0) { 742 return g_signal_info[idx].sig; 743 } 744 } 745 return -1; 746 } 747 748 int os::get_signal_number(const char* signal_name) { 749 return os::Posix::get_signal_number(signal_name); 750 } 751 752 // Returns true if signal number is valid. 753 bool os::Posix::is_valid_signal(int sig) { 754 // MacOS not really POSIX compliant: sigaddset does not return 755 // an error for invalid signal numbers. However, MacOS does not 756 // support real time signals and simply seems to have just 33 757 // signals with no holes in the signal range. 758 #ifdef __APPLE__ 759 return sig >= 1 && sig < NSIG; 760 #else 761 // Use sigaddset to check for signal validity. 762 sigset_t set; 763 if (sigaddset(&set, sig) == -1 && errno == EINVAL) { 764 return false; 765 } 766 return true; 767 #endif 768 } 769 770 // Returns: 771 // NULL for an invalid signal number 772 // "SIG<num>" for a valid but unknown signal number 773 // signal name otherwise. 774 const char* os::exception_name(int sig, char* buf, size_t size) { 775 if (!os::Posix::is_valid_signal(sig)) { 776 return NULL; 777 } 778 const char* const name = os::Posix::get_signal_name(sig, buf, size); 779 if (strcmp(name, "UNKNOWN") == 0) { 780 jio_snprintf(buf, size, "SIG%d", sig); 781 } 782 return buf; 783 } 784 785 #define NUM_IMPORTANT_SIGS 32 786 // Returns one-line short description of a signal set in a user provided buffer. 787 const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) { 788 assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size"); 789 // Note: for shortness, just print out the first 32. That should 790 // cover most of the useful ones, apart from realtime signals. 791 for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) { 792 const int rc = sigismember(set, sig); 793 if (rc == -1 && errno == EINVAL) { 794 buffer[sig-1] = '?'; 795 } else { 796 buffer[sig-1] = rc == 0 ? '0' : '1'; 797 } 798 } 799 buffer[NUM_IMPORTANT_SIGS] = 0; 800 return buffer; 801 } 802 803 // Prints one-line description of a signal set. 804 void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) { 805 char buf[NUM_IMPORTANT_SIGS + 1]; 806 os::Posix::describe_signal_set_short(set, buf, sizeof(buf)); 807 st->print("%s", buf); 808 } 809 810 // Writes one-line description of a combination of sigaction.sa_flags into a user 811 // provided buffer. Returns that buffer. 812 const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) { 813 char* p = buffer; 814 size_t remaining = size; 815 bool first = true; 816 int idx = 0; 817 818 assert(buffer, "invalid argument"); 819 820 if (size == 0) { 821 return buffer; 822 } 823 824 strncpy(buffer, "none", size); 825 826 const struct { 827 // NB: i is an unsigned int here because SA_RESETHAND is on some 828 // systems 0x80000000, which is implicitly unsigned. Assignining 829 // it to an int field would be an overflow in unsigned-to-signed 830 // conversion. 831 unsigned int i; 832 const char* s; 833 } flaginfo [] = { 834 { SA_NOCLDSTOP, "SA_NOCLDSTOP" }, 835 { SA_ONSTACK, "SA_ONSTACK" }, 836 { SA_RESETHAND, "SA_RESETHAND" }, 837 { SA_RESTART, "SA_RESTART" }, 838 { SA_SIGINFO, "SA_SIGINFO" }, 839 { SA_NOCLDWAIT, "SA_NOCLDWAIT" }, 840 { SA_NODEFER, "SA_NODEFER" }, 841 #ifdef AIX 842 { SA_ONSTACK, "SA_ONSTACK" }, 843 { SA_OLDSTYLE, "SA_OLDSTYLE" }, 844 #endif 845 { 0, NULL } 846 }; 847 848 for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) { 849 if (flags & flaginfo[idx].i) { 850 if (first) { 851 jio_snprintf(p, remaining, "%s", flaginfo[idx].s); 852 first = false; 853 } else { 854 jio_snprintf(p, remaining, "|%s", flaginfo[idx].s); 855 } 856 const size_t len = strlen(p); 857 p += len; 858 remaining -= len; 859 } 860 } 861 862 buffer[size - 1] = '\0'; 863 864 return buffer; 865 } 866 867 // Prints one-line description of a combination of sigaction.sa_flags. 868 void os::Posix::print_sa_flags(outputStream* st, int flags) { 869 char buffer[0x100]; 870 os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer)); 871 st->print("%s", buffer); 872 } 873 874 // Helper function for os::Posix::print_siginfo_...(): 875 // return a textual description for signal code. 876 struct enum_sigcode_desc_t { 877 const char* s_name; 878 const char* s_desc; 879 }; 880 881 static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) { 882 883 const struct { 884 int sig; int code; const char* s_code; const char* s_desc; 885 } t1 [] = { 886 { SIGILL, ILL_ILLOPC, "ILL_ILLOPC", "Illegal opcode." }, 887 { SIGILL, ILL_ILLOPN, "ILL_ILLOPN", "Illegal operand." }, 888 { SIGILL, ILL_ILLADR, "ILL_ILLADR", "Illegal addressing mode." }, 889 { SIGILL, ILL_ILLTRP, "ILL_ILLTRP", "Illegal trap." }, 890 { SIGILL, ILL_PRVOPC, "ILL_PRVOPC", "Privileged opcode." }, 891 { SIGILL, ILL_PRVREG, "ILL_PRVREG", "Privileged register." }, 892 { SIGILL, ILL_COPROC, "ILL_COPROC", "Coprocessor error." }, 893 { SIGILL, ILL_BADSTK, "ILL_BADSTK", "Internal stack error." }, 894 #if defined(IA64) && defined(LINUX) 895 { SIGILL, ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" }, 896 { SIGILL, ILL_BREAK, "ILL_BREAK", "Application Break instruction" }, 897 #endif 898 { SIGFPE, FPE_INTDIV, "FPE_INTDIV", "Integer divide by zero." }, 899 { SIGFPE, FPE_INTOVF, "FPE_INTOVF", "Integer overflow." }, 900 { SIGFPE, FPE_FLTDIV, "FPE_FLTDIV", "Floating-point divide by zero." }, 901 { SIGFPE, FPE_FLTOVF, "FPE_FLTOVF", "Floating-point overflow." }, 902 { SIGFPE, FPE_FLTUND, "FPE_FLTUND", "Floating-point underflow." }, 903 { SIGFPE, FPE_FLTRES, "FPE_FLTRES", "Floating-point inexact result." }, 904 { SIGFPE, FPE_FLTINV, "FPE_FLTINV", "Invalid floating-point operation." }, 905 { SIGFPE, FPE_FLTSUB, "FPE_FLTSUB", "Subscript out of range." }, 906 { SIGSEGV, SEGV_MAPERR, "SEGV_MAPERR", "Address not mapped to object." }, 907 { SIGSEGV, SEGV_ACCERR, "SEGV_ACCERR", "Invalid permissions for mapped object." }, 908 #ifdef AIX 909 // no explanation found what keyerr would be 910 { SIGSEGV, SEGV_KEYERR, "SEGV_KEYERR", "key error" }, 911 #endif 912 #if defined(IA64) && !defined(AIX) 913 { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" }, 914 #endif 915 #if defined(__sparc) && defined(SOLARIS) 916 // define Solaris Sparc M7 ADI SEGV signals 917 #if !defined(SEGV_ACCADI) 918 #define SEGV_ACCADI 3 919 #endif 920 { SIGSEGV, SEGV_ACCADI, "SEGV_ACCADI", "ADI not enabled for mapped object." }, 921 #if !defined(SEGV_ACCDERR) 922 #define SEGV_ACCDERR 4 923 #endif 924 { SIGSEGV, SEGV_ACCDERR, "SEGV_ACCDERR", "ADI disrupting exception." }, 925 #if !defined(SEGV_ACCPERR) 926 #define SEGV_ACCPERR 5 927 #endif 928 { SIGSEGV, SEGV_ACCPERR, "SEGV_ACCPERR", "ADI precise exception." }, 929 #endif // defined(__sparc) && defined(SOLARIS) 930 { SIGBUS, BUS_ADRALN, "BUS_ADRALN", "Invalid address alignment." }, 931 { SIGBUS, BUS_ADRERR, "BUS_ADRERR", "Nonexistent physical address." }, 932 { SIGBUS, BUS_OBJERR, "BUS_OBJERR", "Object-specific hardware error." }, 933 { SIGTRAP, TRAP_BRKPT, "TRAP_BRKPT", "Process breakpoint." }, 934 { SIGTRAP, TRAP_TRACE, "TRAP_TRACE", "Process trace trap." }, 935 { SIGCHLD, CLD_EXITED, "CLD_EXITED", "Child has exited." }, 936 { SIGCHLD, CLD_KILLED, "CLD_KILLED", "Child has terminated abnormally and did not create a core file." }, 937 { SIGCHLD, CLD_DUMPED, "CLD_DUMPED", "Child has terminated abnormally and created a core file." }, 938 { SIGCHLD, CLD_TRAPPED, "CLD_TRAPPED", "Traced child has trapped." }, 939 { SIGCHLD, CLD_STOPPED, "CLD_STOPPED", "Child has stopped." }, 940 { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." }, 941 #ifdef SIGPOLL 942 { SIGPOLL, POLL_OUT, "POLL_OUT", "Output buffers available." }, 943 { SIGPOLL, POLL_MSG, "POLL_MSG", "Input message available." }, 944 { SIGPOLL, POLL_ERR, "POLL_ERR", "I/O error." }, 945 { SIGPOLL, POLL_PRI, "POLL_PRI", "High priority input available." }, 946 { SIGPOLL, POLL_HUP, "POLL_HUP", "Device disconnected. [Option End]" }, 947 #endif 948 { -1, -1, NULL, NULL } 949 }; 950 951 // Codes valid in any signal context. 952 const struct { 953 int code; const char* s_code; const char* s_desc; 954 } t2 [] = { 955 { SI_USER, "SI_USER", "Signal sent by kill()." }, 956 { SI_QUEUE, "SI_QUEUE", "Signal sent by the sigqueue()." }, 957 { SI_TIMER, "SI_TIMER", "Signal generated by expiration of a timer set by timer_settime()." }, 958 { SI_ASYNCIO, "SI_ASYNCIO", "Signal generated by completion of an asynchronous I/O request." }, 959 { SI_MESGQ, "SI_MESGQ", "Signal generated by arrival of a message on an empty message queue." }, 960 // Linux specific 961 #ifdef SI_TKILL 962 { SI_TKILL, "SI_TKILL", "Signal sent by tkill (pthread_kill)" }, 963 #endif 964 #ifdef SI_DETHREAD 965 { SI_DETHREAD, "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" }, 966 #endif 967 #ifdef SI_KERNEL 968 { SI_KERNEL, "SI_KERNEL", "Signal sent by kernel." }, 969 #endif 970 #ifdef SI_SIGIO 971 { SI_SIGIO, "SI_SIGIO", "Signal sent by queued SIGIO" }, 972 #endif 973 974 #ifdef AIX 975 { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" }, 976 { SI_EMPTY, "SI_EMPTY", "siginfo contains no useful information" }, 977 #endif 978 979 #ifdef __sun 980 { SI_NOINFO, "SI_NOINFO", "No signal information" }, 981 { SI_RCTL, "SI_RCTL", "kernel generated signal via rctl action" }, 982 { SI_LWP, "SI_LWP", "Signal sent via lwp_kill" }, 983 #endif 984 985 { -1, NULL, NULL } 986 }; 987 988 const char* s_code = NULL; 989 const char* s_desc = NULL; 990 991 for (int i = 0; t1[i].sig != -1; i ++) { 992 if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) { 993 s_code = t1[i].s_code; 994 s_desc = t1[i].s_desc; 995 break; 996 } 997 } 998 999 if (s_code == NULL) { 1000 for (int i = 0; t2[i].s_code != NULL; i ++) { 1001 if (t2[i].code == si->si_code) { 1002 s_code = t2[i].s_code; 1003 s_desc = t2[i].s_desc; 1004 } 1005 } 1006 } 1007 1008 if (s_code == NULL) { 1009 out->s_name = "unknown"; 1010 out->s_desc = "unknown"; 1011 return false; 1012 } 1013 1014 out->s_name = s_code; 1015 out->s_desc = s_desc; 1016 1017 return true; 1018 } 1019 1020 void os::print_siginfo(outputStream* os, const void* si0) { 1021 1022 const siginfo_t* const si = (const siginfo_t*) si0; 1023 1024 char buf[20]; 1025 os->print("siginfo:"); 1026 1027 if (!si) { 1028 os->print(" <null>"); 1029 return; 1030 } 1031 1032 const int sig = si->si_signo; 1033 1034 os->print(" si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf))); 1035 1036 enum_sigcode_desc_t ed; 1037 get_signal_code_description(si, &ed); 1038 os->print(", si_code: %d (%s)", si->si_code, ed.s_name); 1039 1040 if (si->si_errno) { 1041 os->print(", si_errno: %d", si->si_errno); 1042 } 1043 1044 // Output additional information depending on the signal code. 1045 1046 // Note: Many implementations lump si_addr, si_pid, si_uid etc. together as unions, 1047 // so it depends on the context which member to use. For synchronous error signals, 1048 // we print si_addr, unless the signal was sent by another process or thread, in 1049 // which case we print out pid or tid of the sender. 1050 if (si->si_code == SI_USER || si->si_code == SI_QUEUE) { 1051 const pid_t pid = si->si_pid; 1052 os->print(", si_pid: %ld", (long) pid); 1053 if (IS_VALID_PID(pid)) { 1054 const pid_t me = getpid(); 1055 if (me == pid) { 1056 os->print(" (current process)"); 1057 } 1058 } else { 1059 os->print(" (invalid)"); 1060 } 1061 os->print(", si_uid: %ld", (long) si->si_uid); 1062 if (sig == SIGCHLD) { 1063 os->print(", si_status: %d", si->si_status); 1064 } 1065 } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL || 1066 sig == SIGTRAP || sig == SIGFPE) { 1067 os->print(", si_addr: " PTR_FORMAT, p2i(si->si_addr)); 1068 #ifdef SIGPOLL 1069 } else if (sig == SIGPOLL) { 1070 os->print(", si_band: %ld", si->si_band); 1071 #endif 1072 } 1073 1074 } 1075 1076 int os::Posix::unblock_thread_signal_mask(const sigset_t *set) { 1077 return pthread_sigmask(SIG_UNBLOCK, set, NULL); 1078 } 1079 1080 address os::Posix::ucontext_get_pc(const ucontext_t* ctx) { 1081 #if defined(AIX) 1082 return Aix::ucontext_get_pc(ctx); 1083 #elif defined(BSD) 1084 return Bsd::ucontext_get_pc(ctx); 1085 #elif defined(LINUX) 1086 return Linux::ucontext_get_pc(ctx); 1087 #elif defined(SOLARIS) 1088 return Solaris::ucontext_get_pc(ctx); 1089 #else 1090 VMError::report_and_die("unimplemented ucontext_get_pc"); 1091 #endif 1092 } 1093 1094 void os::Posix::ucontext_set_pc(ucontext_t* ctx, address pc) { 1095 #if defined(AIX) 1096 Aix::ucontext_set_pc(ctx, pc); 1097 #elif defined(BSD) 1098 Bsd::ucontext_set_pc(ctx, pc); 1099 #elif defined(LINUX) 1100 Linux::ucontext_set_pc(ctx, pc); 1101 #elif defined(SOLARIS) 1102 Solaris::ucontext_set_pc(ctx, pc); 1103 #else 1104 VMError::report_and_die("unimplemented ucontext_get_pc"); 1105 #endif 1106 } 1107 1108 char* os::Posix::describe_pthread_attr(char* buf, size_t buflen, const pthread_attr_t* attr) { 1109 size_t stack_size = 0; 1110 size_t guard_size = 0; 1111 int detachstate = 0; 1112 pthread_attr_getstacksize(attr, &stack_size); 1113 pthread_attr_getguardsize(attr, &guard_size); 1114 // Work around linux NPTL implementation error, see also os::create_thread() in os_linux.cpp. 1115 LINUX_ONLY(stack_size -= guard_size); 1116 pthread_attr_getdetachstate(attr, &detachstate); 1117 jio_snprintf(buf, buflen, "stacksize: " SIZE_FORMAT "k, guardsize: " SIZE_FORMAT "k, %s", 1118 stack_size / 1024, guard_size / 1024, 1119 (detachstate == PTHREAD_CREATE_DETACHED ? "detached" : "joinable")); 1120 return buf; 1121 } 1122 1123 char* os::Posix::realpath(const char* filename, char* outbuf, size_t outbuflen) { 1124 1125 if (filename == NULL || outbuf == NULL || outbuflen < 1) { 1126 assert(false, "os::Posix::realpath: invalid arguments."); 1127 errno = EINVAL; 1128 return NULL; 1129 } 1130 1131 char* result = NULL; 1132 1133 // This assumes platform realpath() is implemented according to POSIX.1-2008. 1134 // POSIX.1-2008 allows to specify NULL for the output buffer, in which case 1135 // output buffer is dynamically allocated and must be ::free()'d by the caller. 1136 char* p = ::realpath(filename, NULL); 1137 if (p != NULL) { 1138 if (strlen(p) < outbuflen) { 1139 strcpy(outbuf, p); 1140 result = outbuf; 1141 } else { 1142 errno = ENAMETOOLONG; 1143 } 1144 ::free(p); // *not* os::free 1145 } else { 1146 // Fallback for platforms struggling with modern Posix standards (AIX 5.3, 6.1). If realpath 1147 // returns EINVAL, this may indicate that realpath is not POSIX.1-2008 compatible and 1148 // that it complains about the NULL we handed down as user buffer. 1149 // In this case, use the user provided buffer but at least check whether realpath caused 1150 // a memory overwrite. 1151 if (errno == EINVAL) { 1152 outbuf[outbuflen - 1] = '\0'; 1153 p = ::realpath(filename, outbuf); 1154 if (p != NULL) { 1155 guarantee(outbuf[outbuflen - 1] == '\0', "realpath buffer overwrite detected."); 1156 result = p; 1157 } 1158 } 1159 } 1160 return result; 1161 1162 } 1163 1164 1165 // Check minimum allowable stack sizes for thread creation and to initialize 1166 // the java system classes, including StackOverflowError - depends on page 1167 // size. 1168 // The space needed for frames during startup is platform dependent. It 1169 // depends on word size, platform calling conventions, C frame layout and 1170 // interpreter/C1/C2 design decisions. Therefore this is given in a 1171 // platform (os/cpu) dependent constant. 1172 // To this, space for guard mechanisms is added, which depends on the 1173 // page size which again depends on the concrete system the VM is running 1174 // on. Space for libc guard pages is not included in this size. 1175 jint os::Posix::set_minimum_stack_sizes() { 1176 size_t os_min_stack_allowed = SOLARIS_ONLY(thr_min_stack()) NOT_SOLARIS(PTHREAD_STACK_MIN); 1177 1178 _java_thread_min_stack_allowed = _java_thread_min_stack_allowed + 1179 JavaThread::stack_guard_zone_size() + 1180 JavaThread::stack_shadow_zone_size(); 1181 1182 _java_thread_min_stack_allowed = align_size_up(_java_thread_min_stack_allowed, vm_page_size()); 1183 _java_thread_min_stack_allowed = MAX2(_java_thread_min_stack_allowed, os_min_stack_allowed); 1184 1185 size_t stack_size_in_bytes = ThreadStackSize * K; 1186 if (stack_size_in_bytes != 0 && 1187 stack_size_in_bytes < _java_thread_min_stack_allowed) { 1188 // The '-Xss' and '-XX:ThreadStackSize=N' options both set 1189 // ThreadStackSize so we go with "Java thread stack size" instead 1190 // of "ThreadStackSize" to be more friendly. 1191 tty->print_cr("\nThe Java thread stack size specified is too small. " 1192 "Specify at least " SIZE_FORMAT "k", 1193 _java_thread_min_stack_allowed / K); 1194 return JNI_ERR; 1195 } 1196 1197 // Make the stack size a multiple of the page size so that 1198 // the yellow/red zones can be guarded. 1199 JavaThread::set_stack_size_at_create(round_to(stack_size_in_bytes, vm_page_size())); 1200 1201 // Reminder: a compiler thread is a Java thread. 1202 _compiler_thread_min_stack_allowed = _compiler_thread_min_stack_allowed + 1203 JavaThread::stack_guard_zone_size() + 1204 JavaThread::stack_shadow_zone_size(); 1205 1206 _compiler_thread_min_stack_allowed = align_size_up(_compiler_thread_min_stack_allowed, vm_page_size()); 1207 _compiler_thread_min_stack_allowed = MAX2(_compiler_thread_min_stack_allowed, os_min_stack_allowed); 1208 1209 stack_size_in_bytes = CompilerThreadStackSize * K; 1210 if (stack_size_in_bytes != 0 && 1211 stack_size_in_bytes < _compiler_thread_min_stack_allowed) { 1212 tty->print_cr("\nThe CompilerThreadStackSize specified is too small. " 1213 "Specify at least " SIZE_FORMAT "k", 1214 _compiler_thread_min_stack_allowed / K); 1215 return JNI_ERR; 1216 } 1217 1218 _vm_internal_thread_min_stack_allowed = align_size_up(_vm_internal_thread_min_stack_allowed, vm_page_size()); 1219 _vm_internal_thread_min_stack_allowed = MAX2(_vm_internal_thread_min_stack_allowed, os_min_stack_allowed); 1220 1221 stack_size_in_bytes = VMThreadStackSize * K; 1222 if (stack_size_in_bytes != 0 && 1223 stack_size_in_bytes < _vm_internal_thread_min_stack_allowed) { 1224 tty->print_cr("\nThe VMThreadStackSize specified is too small. " 1225 "Specify at least " SIZE_FORMAT "k", 1226 _vm_internal_thread_min_stack_allowed / K); 1227 return JNI_ERR; 1228 } 1229 return JNI_OK; 1230 } 1231 1232 // Called when creating the thread. The minimum stack sizes have already been calculated 1233 size_t os::Posix::get_initial_stack_size(ThreadType thr_type, size_t req_stack_size) { 1234 size_t stack_size; 1235 if (req_stack_size == 0) { 1236 stack_size = default_stack_size(thr_type); 1237 } else { 1238 stack_size = req_stack_size; 1239 } 1240 1241 switch (thr_type) { 1242 case os::java_thread: 1243 // Java threads use ThreadStackSize which default value can be 1244 // changed with the flag -Xss 1245 if (req_stack_size == 0 && JavaThread::stack_size_at_create() > 0) { 1246 // no requested size and we have a more specific default value 1247 stack_size = JavaThread::stack_size_at_create(); 1248 } 1249 stack_size = MAX2(stack_size, 1250 _java_thread_min_stack_allowed); 1251 break; 1252 case os::compiler_thread: 1253 if (req_stack_size == 0 && CompilerThreadStackSize > 0) { 1254 // no requested size and we have a more specific default value 1255 stack_size = (size_t)(CompilerThreadStackSize * K); 1256 } 1257 stack_size = MAX2(stack_size, 1258 _compiler_thread_min_stack_allowed); 1259 break; 1260 case os::vm_thread: 1261 case os::pgc_thread: 1262 case os::cgc_thread: 1263 case os::watcher_thread: 1264 default: // presume the unknown thr_type is a VM internal 1265 if (req_stack_size == 0 && VMThreadStackSize > 0) { 1266 // no requested size and we have a more specific default value 1267 stack_size = (size_t)(VMThreadStackSize * K); 1268 } 1269 1270 stack_size = MAX2(stack_size, 1271 _vm_internal_thread_min_stack_allowed); 1272 break; 1273 } 1274 1275 // pthread_attr_setstacksize() may require that the size be rounded up to the OS page size. 1276 // Be careful not to round up to 0. Align down in that case. 1277 if (stack_size <= SIZE_MAX - vm_page_size()) { 1278 stack_size = align_size_up(stack_size, vm_page_size()); 1279 } else { 1280 stack_size = align_size_down(stack_size, vm_page_size()); 1281 } 1282 1283 return stack_size; 1284 } 1285 1286 os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() { 1287 assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread"); 1288 } 1289 1290 /* 1291 * See the caveats for this class in os_posix.hpp 1292 * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this 1293 * method and returns false. If none of the signals are raised, returns true. 1294 * The callback is supposed to provide the method that should be protected. 1295 */ 1296 bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) { 1297 sigset_t saved_sig_mask; 1298 1299 assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread"); 1300 assert(!WatcherThread::watcher_thread()->has_crash_protection(), 1301 "crash_protection already set?"); 1302 1303 // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask 1304 // since on at least some systems (OS X) siglongjmp will restore the mask 1305 // for the process, not the thread 1306 pthread_sigmask(0, NULL, &saved_sig_mask); 1307 if (sigsetjmp(_jmpbuf, 0) == 0) { 1308 // make sure we can see in the signal handler that we have crash protection 1309 // installed 1310 WatcherThread::watcher_thread()->set_crash_protection(this); 1311 cb.call(); 1312 // and clear the crash protection 1313 WatcherThread::watcher_thread()->set_crash_protection(NULL); 1314 return true; 1315 } 1316 // this happens when we siglongjmp() back 1317 pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL); 1318 WatcherThread::watcher_thread()->set_crash_protection(NULL); 1319 return false; 1320 } 1321 1322 void os::WatcherThreadCrashProtection::restore() { 1323 assert(WatcherThread::watcher_thread()->has_crash_protection(), 1324 "must have crash protection"); 1325 1326 siglongjmp(_jmpbuf, 1); 1327 } 1328 1329 void os::WatcherThreadCrashProtection::check_crash_protection(int sig, 1330 Thread* thread) { 1331 1332 if (thread != NULL && 1333 thread->is_Watcher_thread() && 1334 WatcherThread::watcher_thread()->has_crash_protection()) { 1335 1336 if (sig == SIGSEGV || sig == SIGBUS) { 1337 WatcherThread::watcher_thread()->crash_protection()->restore(); 1338 } 1339 } 1340 } 1341 1342 #define check_with_errno(check_type, cond, msg) \ 1343 do { \ 1344 int err = errno; \ 1345 check_type(cond, "%s; error='%s' (errno=%s)", msg, os::strerror(err), \ 1346 os::errno_name(err)); \ 1347 } while (false) 1348 1349 #define assert_with_errno(cond, msg) check_with_errno(assert, cond, msg) 1350 #define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg) 1351 1352 // POSIX unamed semaphores are not supported on OS X. 1353 #ifndef __APPLE__ 1354 1355 PosixSemaphore::PosixSemaphore(uint value) { 1356 int ret = sem_init(&_semaphore, 0, value); 1357 1358 guarantee_with_errno(ret == 0, "Failed to initialize semaphore"); 1359 } 1360 1361 PosixSemaphore::~PosixSemaphore() { 1362 sem_destroy(&_semaphore); 1363 } 1364 1365 void PosixSemaphore::signal(uint count) { 1366 for (uint i = 0; i < count; i++) { 1367 int ret = sem_post(&_semaphore); 1368 1369 assert_with_errno(ret == 0, "sem_post failed"); 1370 } 1371 } 1372 1373 void PosixSemaphore::wait() { 1374 int ret; 1375 1376 do { 1377 ret = sem_wait(&_semaphore); 1378 } while (ret != 0 && errno == EINTR); 1379 1380 assert_with_errno(ret == 0, "sem_wait failed"); 1381 } 1382 1383 bool PosixSemaphore::trywait() { 1384 int ret; 1385 1386 do { 1387 ret = sem_trywait(&_semaphore); 1388 } while (ret != 0 && errno == EINTR); 1389 1390 assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed"); 1391 1392 return ret == 0; 1393 } 1394 1395 bool PosixSemaphore::timedwait(struct timespec ts) { 1396 while (true) { 1397 int result = sem_timedwait(&_semaphore, &ts); 1398 if (result == 0) { 1399 return true; 1400 } else if (errno == EINTR) { 1401 continue; 1402 } else if (errno == ETIMEDOUT) { 1403 return false; 1404 } else { 1405 assert_with_errno(false, "timedwait failed"); 1406 return false; 1407 } 1408 } 1409 } 1410 1411 #endif // __APPLE__ 1412 1413 1414 // Shared pthread_mutex/cond based PlatformEvent implementation. 1415 // Not currently usable by Solaris. 1416 1417 #ifndef SOLARIS 1418 1419 // Shared condattr object for use with relative timed-waits. Will be associated 1420 // with CLOCK_MONOTONIC if available to avoid issues with time-of-day changes, 1421 // but otherwise whatever default is used by the platform - generally the 1422 // time-of-day clock. 1423 static pthread_condattr_t _condAttr[1]; 1424 1425 // Shared mutexattr to explicitly set the type to PTHREAD_MUTEX_NORMAL as not 1426 // all systems (e.g. FreeBSD) map the default to "normal". 1427 static pthread_mutexattr_t _mutexAttr[1]; 1428 1429 // common basic initialization that is always supported 1430 static void pthread_init_common(void) { 1431 int status; 1432 if ((status = pthread_condattr_init(_condAttr)) != 0) { 1433 fatal("pthread_condattr_init: %s", os::strerror(status)); 1434 } 1435 if ((status = pthread_mutexattr_init(_mutexAttr)) != 0) { 1436 fatal("pthread_mutexattr_init: %s", os::strerror(status)); 1437 } 1438 if ((status = pthread_mutexattr_settype(_mutexAttr, PTHREAD_MUTEX_NORMAL)) != 0) { 1439 fatal("pthread_mutexattr_settype: %s", os::strerror(status)); 1440 } 1441 } 1442 1443 // Not all POSIX types and API's are available on all notionally "posix" 1444 // platforms. If we have build-time support then we will check for actual 1445 // runtime support via dlopen/dlsym lookup. This allows for running on an 1446 // older OS version compared to the build platform. But if there is no 1447 // build time support then there cannot be any runtime support as we do not 1448 // know what the runtime types would be (for example clockid_t might be an 1449 // int or int64_t). 1450 // 1451 #ifdef SUPPORTS_CLOCK_MONOTONIC 1452 1453 // This means we have clockid_t, clock_gettime et al and CLOCK_MONOTONIC 1454 1455 static int (*_clock_gettime)(clockid_t, struct timespec *); 1456 static int (*_pthread_condattr_setclock)(pthread_condattr_t *, clockid_t); 1457 1458 static bool _use_clock_monotonic_condattr; 1459 1460 // Determine what POSIX API's are present and do appropriate 1461 // configuration. 1462 void os::Posix::init(void) { 1463 1464 // NOTE: no logging available when this is called. Put logging 1465 // statements in init_2(). 1466 1467 // Copied from os::Linux::clock_init(). The duplication is temporary. 1468 1469 // 1. Check for CLOCK_MONOTONIC support. 1470 1471 void* handle = NULL; 1472 1473 // For linux we need librt, for other OS we can find 1474 // this function in regular libc. 1475 #ifdef NEEDS_LIBRT 1476 // We do dlopen's in this particular order due to bug in linux 1477 // dynamic loader (see 6348968) leading to crash on exit. 1478 handle = dlopen("librt.so.1", RTLD_LAZY); 1479 if (handle == NULL) { 1480 handle = dlopen("librt.so", RTLD_LAZY); 1481 } 1482 #endif 1483 1484 if (handle == NULL) { 1485 handle = RTLD_DEFAULT; 1486 } 1487 1488 _clock_gettime = NULL; 1489 1490 int (*clock_getres_func)(clockid_t, struct timespec*) = 1491 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres"); 1492 int (*clock_gettime_func)(clockid_t, struct timespec*) = 1493 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime"); 1494 if (clock_getres_func != NULL && clock_gettime_func != NULL) { 1495 // We assume that if both clock_gettime and clock_getres support 1496 // CLOCK_MONOTONIC then the OS provides true high-res monotonic clock. 1497 struct timespec res; 1498 struct timespec tp; 1499 if (clock_getres_func(CLOCK_MONOTONIC, &res) == 0 && 1500 clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) { 1501 // Yes, monotonic clock is supported. 1502 _clock_gettime = clock_gettime_func; 1503 } else { 1504 #ifdef NEEDS_LIBRT 1505 // Close librt if there is no monotonic clock. 1506 if (handle != RTLD_DEFAULT) { 1507 dlclose(handle); 1508 } 1509 #endif 1510 } 1511 } 1512 1513 // 2. Check for pthread_condattr_setclock support. 1514 1515 _pthread_condattr_setclock = NULL; 1516 1517 // libpthread is already loaded. 1518 int (*condattr_setclock_func)(pthread_condattr_t*, clockid_t) = 1519 (int (*)(pthread_condattr_t*, clockid_t))dlsym(RTLD_DEFAULT, 1520 "pthread_condattr_setclock"); 1521 if (condattr_setclock_func != NULL) { 1522 _pthread_condattr_setclock = condattr_setclock_func; 1523 } 1524 1525 // Now do general initialization. 1526 1527 pthread_init_common(); 1528 1529 int status; 1530 if (_pthread_condattr_setclock != NULL && _clock_gettime != NULL) { 1531 if ((status = _pthread_condattr_setclock(_condAttr, CLOCK_MONOTONIC)) != 0) { 1532 if (status == EINVAL) { 1533 _use_clock_monotonic_condattr = false; 1534 warning("Unable to use monotonic clock with relative timed-waits" \ 1535 " - changes to the time-of-day clock may have adverse affects"); 1536 } else { 1537 fatal("pthread_condattr_setclock: %s", os::strerror(status)); 1538 } 1539 } else { 1540 _use_clock_monotonic_condattr = true; 1541 } 1542 } else { 1543 _use_clock_monotonic_condattr = false; 1544 } 1545 } 1546 1547 void os::Posix::init_2(void) { 1548 log_info(os)("Use of CLOCK_MONOTONIC is%s supported", 1549 (_clock_gettime != NULL ? "" : " not")); 1550 log_info(os)("Use of pthread_condattr_setclock is%s supported", 1551 (_pthread_condattr_setclock != NULL ? "" : " not")); 1552 log_info(os)("Relative timed-wait using pthread_cond_timedwait is associated with %s", 1553 _use_clock_monotonic_condattr ? "CLOCK_MONOTONIC" : "the default clock"); 1554 } 1555 1556 #else // !SUPPORTS_CLOCK_MONOTONIC 1557 1558 void os::Posix::init(void) { 1559 pthread_init_common(); 1560 } 1561 1562 void os::Posix::init_2(void) { 1563 log_info(os)("Use of CLOCK_MONOTONIC is not supported"); 1564 log_info(os)("Use of pthread_condattr_setclock is not supported"); 1565 log_info(os)("Relative timed-wait using pthread_cond_timedwait is associated with the default clock"); 1566 } 1567 1568 #endif // SUPPORTS_CLOCK_MONOTONIC 1569 1570 os::PlatformEvent::PlatformEvent() { 1571 int status = pthread_cond_init(_cond, _condAttr); 1572 assert_status(status == 0, status, "cond_init"); 1573 status = pthread_mutex_init(_mutex, _mutexAttr); 1574 assert_status(status == 0, status, "mutex_init"); 1575 _event = 0; 1576 _nParked = 0; 1577 } 1578 1579 // Utility to convert the given timeout to an absolute timespec 1580 // (based on the appropriate clock) to use with pthread_cond_timewait. 1581 // The clock queried here must be the clock used to manage the 1582 // timeout of the condition variable. 1583 // 1584 // The passed in timeout value is either a relative time in nanoseconds 1585 // or an absolute time in milliseconds. A relative timeout will be 1586 // associated with CLOCK_MONOTONIC if available; otherwise, or if absolute, 1587 // the default time-of-day clock will be used. 1588 1589 // Given time is a 64-bit value and the time_t used in the timespec is 1590 // sometimes a signed-32-bit value we have to watch for overflow if times 1591 // way in the future are given. Further on Solaris versions 1592 // prior to 10 there is a restriction (see cond_timedwait) that the specified 1593 // number of seconds, in abstime, is less than current_time + 100000000. 1594 // As it will be over 20 years before "now + 100000000" will overflow we can 1595 // ignore overflow and just impose a hard-limit on seconds using the value 1596 // of "now + 100000000". This places a limit on the timeout of about 3.17 1597 // years from "now". 1598 // 1599 #define MAX_SECS 100000000 1600 1601 // Calculate a new absolute time that is "timeout" nanoseconds from "now". 1602 // "unit" indicates the unit of "now_part_sec" (may be nanos or micros depending 1603 // on which clock is being used). 1604 static void calc_rel_time(timespec* abstime, jlong timeout, jlong now_sec, 1605 jlong now_part_sec, jlong unit) { 1606 time_t max_secs = now_sec + MAX_SECS; 1607 1608 jlong seconds = timeout / NANOUNITS; 1609 timeout %= NANOUNITS; // remaining nanos 1610 1611 if (seconds >= MAX_SECS) { 1612 // More seconds than we can add, so pin to max_secs. 1613 abstime->tv_sec = max_secs; 1614 abstime->tv_nsec = 0; 1615 } else { 1616 abstime->tv_sec = now_sec + seconds; 1617 long nanos = (now_part_sec * (NANOUNITS / unit)) + timeout; 1618 if (nanos >= NANOUNITS) { // overflow 1619 abstime->tv_sec += 1; 1620 nanos -= NANOUNITS; 1621 } 1622 abstime->tv_nsec = nanos; 1623 } 1624 } 1625 1626 // Unpack the given deadline in milliseconds since the epoch, into the given timespec. 1627 // The current time in seconds is also passed in to enforce an upper bound as discussed above. 1628 static void unpack_abs_time(timespec* abstime, jlong deadline, jlong now_sec) { 1629 time_t max_secs = now_sec + MAX_SECS; 1630 1631 jlong seconds = deadline / MILLIUNITS; 1632 jlong millis = deadline % MILLIUNITS; 1633 1634 if (seconds >= max_secs) { 1635 // Absolute seconds exceeds allowed max, so pin to max_secs. 1636 abstime->tv_sec = max_secs; 1637 abstime->tv_nsec = 0; 1638 } else { 1639 abstime->tv_sec = seconds; 1640 abstime->tv_nsec = millis * (NANOUNITS / MILLIUNITS); 1641 } 1642 } 1643 1644 static void to_abstime(timespec* abstime, jlong timeout, bool isAbsolute) { 1645 DEBUG_ONLY(int max_secs = MAX_SECS;) 1646 1647 if (timeout < 0) { 1648 timeout = 0; 1649 } 1650 1651 #ifdef SUPPORTS_CLOCK_MONOTONIC 1652 1653 if (_use_clock_monotonic_condattr && !isAbsolute) { 1654 struct timespec now; 1655 int status = _clock_gettime(CLOCK_MONOTONIC, &now); 1656 assert_status(status == 0, status, "clock_gettime"); 1657 calc_rel_time(abstime, timeout, now.tv_sec, now.tv_nsec, NANOUNITS); 1658 DEBUG_ONLY(max_secs += now.tv_sec;) 1659 } else { 1660 1661 #else 1662 1663 { // Match the block scope. 1664 1665 #endif // SUPPORTS_CLOCK_MONOTONIC 1666 1667 // Time-of-day clock is all we can reliably use. 1668 struct timeval now; 1669 int status = gettimeofday(&now, NULL); 1670 assert_status(status == 0, errno, "gettimeofday"); 1671 if (isAbsolute) { 1672 unpack_abs_time(abstime, timeout, now.tv_sec); 1673 } else { 1674 calc_rel_time(abstime, timeout, now.tv_sec, now.tv_usec, MICROUNITS); 1675 } 1676 DEBUG_ONLY(max_secs += now.tv_sec;) 1677 } 1678 1679 assert(abstime->tv_sec >= 0, "tv_sec < 0"); 1680 assert(abstime->tv_sec <= max_secs, "tv_sec > max_secs"); 1681 assert(abstime->tv_nsec >= 0, "tv_nsec < 0"); 1682 assert(abstime->tv_nsec < NANOUNITS, "tv_nsec >= NANOUNITS"); 1683 } 1684 1685 // PlatformEvent 1686 // 1687 // Assumption: 1688 // Only one parker can exist on an event, which is why we allocate 1689 // them per-thread. Multiple unparkers can coexist. 1690 // 1691 // _event serves as a restricted-range semaphore. 1692 // -1 : thread is blocked, i.e. there is a waiter 1693 // 0 : neutral: thread is running or ready, 1694 // could have been signaled after a wait started 1695 // 1 : signaled - thread is running or ready 1696 // 1697 // Having three states allows for some detection of bad usage - see 1698 // comments on unpark(). 1699 1700 void os::PlatformEvent::park() { // AKA "down()" 1701 // Transitions for _event: 1702 // -1 => -1 : illegal 1703 // 1 => 0 : pass - return immediately 1704 // 0 => -1 : block; then set _event to 0 before returning 1705 1706 // Invariant: Only the thread associated with the PlatformEvent 1707 // may call park(). 1708 assert(_nParked == 0, "invariant"); 1709 1710 int v; 1711 1712 // atomically decrement _event 1713 for (;;) { 1714 v = _event; 1715 if (Atomic::cmpxchg(v - 1, &_event, v) == v) break; 1716 } 1717 guarantee(v >= 0, "invariant"); 1718 1719 if (v == 0) { // Do this the hard way by blocking ... 1720 int status = pthread_mutex_lock(_mutex); 1721 assert_status(status == 0, status, "mutex_lock"); 1722 guarantee(_nParked == 0, "invariant"); 1723 ++_nParked; 1724 while (_event < 0) { 1725 // OS-level "spurious wakeups" are ignored 1726 status = pthread_cond_wait(_cond, _mutex); 1727 assert_status(status == 0, status, "cond_wait"); 1728 } 1729 --_nParked; 1730 1731 _event = 0; 1732 status = pthread_mutex_unlock(_mutex); 1733 assert_status(status == 0, status, "mutex_unlock"); 1734 // Paranoia to ensure our locked and lock-free paths interact 1735 // correctly with each other. 1736 OrderAccess::fence(); 1737 } 1738 guarantee(_event >= 0, "invariant"); 1739 } 1740 1741 int os::PlatformEvent::park(jlong millis) { 1742 // Transitions for _event: 1743 // -1 => -1 : illegal 1744 // 1 => 0 : pass - return immediately 1745 // 0 => -1 : block; then set _event to 0 before returning 1746 1747 // Invariant: Only the thread associated with the Event/PlatformEvent 1748 // may call park(). 1749 assert(_nParked == 0, "invariant"); 1750 1751 int v; 1752 // atomically decrement _event 1753 for (;;) { 1754 v = _event; 1755 if (Atomic::cmpxchg(v - 1, &_event, v) == v) break; 1756 } 1757 guarantee(v >= 0, "invariant"); 1758 1759 if (v == 0) { // Do this the hard way by blocking ... 1760 struct timespec abst; 1761 to_abstime(&abst, millis * (NANOUNITS / MILLIUNITS), false); 1762 1763 int ret = OS_TIMEOUT; 1764 int status = pthread_mutex_lock(_mutex); 1765 assert_status(status == 0, status, "mutex_lock"); 1766 guarantee(_nParked == 0, "invariant"); 1767 ++_nParked; 1768 1769 while (_event < 0) { 1770 status = pthread_cond_timedwait(_cond, _mutex, &abst); 1771 assert_status(status == 0 || status == ETIMEDOUT, 1772 status, "cond_timedwait"); 1773 // OS-level "spurious wakeups" are ignored unless the archaic 1774 // FilterSpuriousWakeups is set false. That flag should be obsoleted. 1775 if (!FilterSpuriousWakeups) break; 1776 if (status == ETIMEDOUT) break; 1777 } 1778 --_nParked; 1779 1780 if (_event >= 0) { 1781 ret = OS_OK; 1782 } 1783 1784 _event = 0; 1785 status = pthread_mutex_unlock(_mutex); 1786 assert_status(status == 0, status, "mutex_unlock"); 1787 // Paranoia to ensure our locked and lock-free paths interact 1788 // correctly with each other. 1789 OrderAccess::fence(); 1790 return ret; 1791 } 1792 return OS_OK; 1793 } 1794 1795 void os::PlatformEvent::unpark() { 1796 // Transitions for _event: 1797 // 0 => 1 : just return 1798 // 1 => 1 : just return 1799 // -1 => either 0 or 1; must signal target thread 1800 // That is, we can safely transition _event from -1 to either 1801 // 0 or 1. 1802 // See also: "Semaphores in Plan 9" by Mullender & Cox 1803 // 1804 // Note: Forcing a transition from "-1" to "1" on an unpark() means 1805 // that it will take two back-to-back park() calls for the owning 1806 // thread to block. This has the benefit of forcing a spurious return 1807 // from the first park() call after an unpark() call which will help 1808 // shake out uses of park() and unpark() without checking state conditions 1809 // properly. This spurious return doesn't manifest itself in any user code 1810 // but only in the correctly written condition checking loops of ObjectMonitor, 1811 // Mutex/Monitor, Thread::muxAcquire and os::sleep 1812 1813 if (Atomic::xchg(1, &_event) >= 0) return; 1814 1815 int status = pthread_mutex_lock(_mutex); 1816 assert_status(status == 0, status, "mutex_lock"); 1817 int anyWaiters = _nParked; 1818 assert(anyWaiters == 0 || anyWaiters == 1, "invariant"); 1819 status = pthread_mutex_unlock(_mutex); 1820 assert_status(status == 0, status, "mutex_unlock"); 1821 1822 // Note that we signal() *after* dropping the lock for "immortal" Events. 1823 // This is safe and avoids a common class of futile wakeups. In rare 1824 // circumstances this can cause a thread to return prematurely from 1825 // cond_{timed}wait() but the spurious wakeup is benign and the victim 1826 // will simply re-test the condition and re-park itself. 1827 // This provides particular benefit if the underlying platform does not 1828 // provide wait morphing. 1829 1830 if (anyWaiters != 0) { 1831 status = pthread_cond_signal(_cond); 1832 assert_status(status == 0, status, "cond_signal"); 1833 } 1834 } 1835 1836 // JSR166 support 1837 1838 os::PlatformParker::PlatformParker() { 1839 int status; 1840 status = pthread_cond_init(&_cond[REL_INDEX], _condAttr); 1841 assert_status(status == 0, status, "cond_init rel"); 1842 status = pthread_cond_init(&_cond[ABS_INDEX], NULL); 1843 assert_status(status == 0, status, "cond_init abs"); 1844 status = pthread_mutex_init(_mutex, _mutexAttr); 1845 assert_status(status == 0, status, "mutex_init"); 1846 _cur_index = -1; // mark as unused 1847 } 1848 1849 // Parker::park decrements count if > 0, else does a condvar wait. Unpark 1850 // sets count to 1 and signals condvar. Only one thread ever waits 1851 // on the condvar. Contention seen when trying to park implies that someone 1852 // is unparking you, so don't wait. And spurious returns are fine, so there 1853 // is no need to track notifications. 1854 1855 void Parker::park(bool isAbsolute, jlong time) { 1856 1857 // Optional fast-path check: 1858 // Return immediately if a permit is available. 1859 // We depend on Atomic::xchg() having full barrier semantics 1860 // since we are doing a lock-free update to _counter. 1861 if (Atomic::xchg(0, &_counter) > 0) return; 1862 1863 Thread* thread = Thread::current(); 1864 assert(thread->is_Java_thread(), "Must be JavaThread"); 1865 JavaThread *jt = (JavaThread *)thread; 1866 1867 // Optional optimization -- avoid state transitions if there's 1868 // an interrupt pending. 1869 if (Thread::is_interrupted(thread, false)) { 1870 return; 1871 } 1872 1873 // Next, demultiplex/decode time arguments 1874 struct timespec absTime; 1875 if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all 1876 return; 1877 } 1878 if (time > 0) { 1879 to_abstime(&absTime, time, isAbsolute); 1880 } 1881 1882 // Enter safepoint region 1883 // Beware of deadlocks such as 6317397. 1884 // The per-thread Parker:: mutex is a classic leaf-lock. 1885 // In particular a thread must never block on the Threads_lock while 1886 // holding the Parker:: mutex. If safepoints are pending both the 1887 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. 1888 ThreadBlockInVM tbivm(jt); 1889 1890 // Don't wait if cannot get lock since interference arises from 1891 // unparking. Also re-check interrupt before trying wait. 1892 if (Thread::is_interrupted(thread, false) || 1893 pthread_mutex_trylock(_mutex) != 0) { 1894 return; 1895 } 1896 1897 int status; 1898 if (_counter > 0) { // no wait needed 1899 _counter = 0; 1900 status = pthread_mutex_unlock(_mutex); 1901 assert_status(status == 0, status, "invariant"); 1902 // Paranoia to ensure our locked and lock-free paths interact 1903 // correctly with each other and Java-level accesses. 1904 OrderAccess::fence(); 1905 return; 1906 } 1907 1908 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 1909 jt->set_suspend_equivalent(); 1910 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 1911 1912 assert(_cur_index == -1, "invariant"); 1913 if (time == 0) { 1914 _cur_index = REL_INDEX; // arbitrary choice when not timed 1915 status = pthread_cond_wait(&_cond[_cur_index], _mutex); 1916 assert_status(status == 0, status, "cond_timedwait"); 1917 } 1918 else { 1919 _cur_index = isAbsolute ? ABS_INDEX : REL_INDEX; 1920 status = pthread_cond_timedwait(&_cond[_cur_index], _mutex, &absTime); 1921 assert_status(status == 0 || status == ETIMEDOUT, 1922 status, "cond_timedwait"); 1923 } 1924 _cur_index = -1; 1925 1926 _counter = 0; 1927 status = pthread_mutex_unlock(_mutex); 1928 assert_status(status == 0, status, "invariant"); 1929 // Paranoia to ensure our locked and lock-free paths interact 1930 // correctly with each other and Java-level accesses. 1931 OrderAccess::fence(); 1932 1933 // If externally suspended while waiting, re-suspend 1934 if (jt->handle_special_suspend_equivalent_condition()) { 1935 jt->java_suspend_self(); 1936 } 1937 } 1938 1939 void Parker::unpark() { 1940 int status = pthread_mutex_lock(_mutex); 1941 assert_status(status == 0, status, "invariant"); 1942 const int s = _counter; 1943 _counter = 1; 1944 // must capture correct index before unlocking 1945 int index = _cur_index; 1946 status = pthread_mutex_unlock(_mutex); 1947 assert_status(status == 0, status, "invariant"); 1948 1949 // Note that we signal() *after* dropping the lock for "immortal" Events. 1950 // This is safe and avoids a common class of futile wakeups. In rare 1951 // circumstances this can cause a thread to return prematurely from 1952 // cond_{timed}wait() but the spurious wakeup is benign and the victim 1953 // will simply re-test the condition and re-park itself. 1954 // This provides particular benefit if the underlying platform does not 1955 // provide wait morphing. 1956 1957 if (s < 1 && index != -1) { 1958 // thread is definitely parked 1959 status = pthread_cond_signal(&_cond[index]); 1960 assert_status(status == 0, status, "invariant"); 1961 } 1962 } 1963 1964 1965 #endif // !SOLARIS