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