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