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