1 /*
   2  * Copyright (c) 1997, 2018, 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 // no precompiled headers
  26 #include "jvm.h"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/icBuffer.hpp"
  31 #include "code/vtableStubs.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/disassembler.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "logging/log.hpp"
  36 #include "memory/allocation.inline.hpp"
  37 #include "memory/filemap.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "os_share_solaris.hpp"
  40 #include "os_solaris.inline.hpp"
  41 #include "prims/jniFastGetField.hpp"
  42 #include "prims/jvm_misc.hpp"
  43 #include "runtime/arguments.hpp"
  44 #include "runtime/atomic.hpp"
  45 #include "runtime/extendedPC.hpp"
  46 #include "runtime/globals.hpp"
  47 #include "runtime/interfaceSupport.inline.hpp"
  48 #include "runtime/java.hpp"
  49 #include "runtime/javaCalls.hpp"
  50 #include "runtime/mutexLocker.hpp"
  51 #include "runtime/objectMonitor.hpp"
  52 #include "runtime/orderAccess.hpp"
  53 #include "runtime/osThread.hpp"
  54 #include "runtime/perfMemory.hpp"
  55 #include "runtime/sharedRuntime.hpp"
  56 #include "runtime/statSampler.hpp"
  57 #include "runtime/stubRoutines.hpp"
  58 #include "runtime/thread.inline.hpp"
  59 #include "runtime/threadCritical.hpp"
  60 #include "runtime/timer.hpp"
  61 #include "runtime/vm_version.hpp"
  62 #include "semaphore_posix.hpp"
  63 #include "services/attachListener.hpp"
  64 #include "services/memTracker.hpp"
  65 #include "services/runtimeService.hpp"
  66 #include "utilities/align.hpp"
  67 #include "utilities/decoder.hpp"
  68 #include "utilities/defaultStream.hpp"
  69 #include "utilities/events.hpp"
  70 #include "utilities/growableArray.hpp"
  71 #include "utilities/macros.hpp"
  72 #include "utilities/vmError.hpp"
  73 
  74 // put OS-includes here
  75 # include <dlfcn.h>
  76 # include <errno.h>
  77 # include <exception>
  78 # include <link.h>
  79 # include <poll.h>
  80 # include <pthread.h>
  81 # include <setjmp.h>
  82 # include <signal.h>
  83 # include <stdio.h>
  84 # include <alloca.h>
  85 # include <sys/filio.h>
  86 # include <sys/ipc.h>
  87 # include <sys/lwp.h>
  88 # include <sys/machelf.h>     // for elf Sym structure used by dladdr1
  89 # include <sys/mman.h>
  90 # include <sys/processor.h>
  91 # include <sys/procset.h>
  92 # include <sys/pset.h>
  93 # include <sys/resource.h>
  94 # include <sys/shm.h>
  95 # include <sys/socket.h>
  96 # include <sys/stat.h>
  97 # include <sys/systeminfo.h>
  98 # include <sys/time.h>
  99 # include <sys/times.h>
 100 # include <sys/types.h>
 101 # include <sys/wait.h>
 102 # include <sys/utsname.h>
 103 # include <thread.h>
 104 # include <unistd.h>
 105 # include <sys/priocntl.h>
 106 # include <sys/rtpriocntl.h>
 107 # include <sys/tspriocntl.h>
 108 # include <sys/iapriocntl.h>
 109 # include <sys/fxpriocntl.h>
 110 # include <sys/loadavg.h>
 111 # include <string.h>
 112 # include <stdio.h>
 113 
 114 # define _STRUCTURED_PROC 1  //  this gets us the new structured proc interfaces of 5.6 & later
 115 # include <sys/procfs.h>     //  see comment in <sys/procfs.h>
 116 
 117 #define MAX_PATH (2 * K)
 118 
 119 // for timer info max values which include all bits
 120 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
 121 
 122 
 123 // Here are some liblgrp types from sys/lgrp_user.h to be able to
 124 // compile on older systems without this header file.
 125 
 126 #ifndef MADV_ACCESS_LWP
 127   #define  MADV_ACCESS_LWP   7       /* next LWP to access heavily */
 128 #endif
 129 #ifndef MADV_ACCESS_MANY
 130   #define  MADV_ACCESS_MANY  8       /* many processes to access heavily */
 131 #endif
 132 
 133 #ifndef LGRP_RSRC_CPU
 134   #define LGRP_RSRC_CPU      0       /* CPU resources */
 135 #endif
 136 #ifndef LGRP_RSRC_MEM
 137   #define LGRP_RSRC_MEM      1       /* memory resources */
 138 #endif
 139 
 140 // Values for ThreadPriorityPolicy == 1
 141 int prio_policy1[CriticalPriority+1] = {
 142   -99999,  0, 16,  32,  48,  64,
 143           80, 96, 112, 124, 127, 127 };
 144 
 145 // System parameters used internally
 146 static clock_t clock_tics_per_sec = 100;
 147 
 148 // Track if we have called enable_extended_FILE_stdio (on Solaris 10u4+)
 149 static bool enabled_extended_FILE_stdio = false;
 150 
 151 // For diagnostics to print a message once. see run_periodic_checks
 152 static bool check_addr0_done = false;
 153 static sigset_t check_signal_done;
 154 static bool check_signals = true;
 155 
 156 address os::Solaris::handler_start;  // start pc of thr_sighndlrinfo
 157 address os::Solaris::handler_end;    // end pc of thr_sighndlrinfo
 158 
 159 address os::Solaris::_main_stack_base = NULL;  // 4352906 workaround
 160 
 161 os::Solaris::pthread_setname_np_func_t os::Solaris::_pthread_setname_np = NULL;
 162 
 163 // "default" initializers for missing libc APIs
 164 extern "C" {
 165   static int lwp_mutex_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; }
 166   static int lwp_mutex_destroy(mutex_t *mx)                 { return 0; }
 167 
 168   static int lwp_cond_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; }
 169   static int lwp_cond_destroy(cond_t *cv)                   { return 0; }
 170 }
 171 
 172 // "default" initializers for pthread-based synchronization
 173 extern "C" {
 174   static int pthread_mutex_default_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; }
 175   static int pthread_cond_default_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; }
 176 }
 177 
 178 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);
 179 
 180 static inline size_t adjust_stack_size(address base, size_t size) {
 181   if ((ssize_t)size < 0) {
 182     // 4759953: Compensate for ridiculous stack size.
 183     size = max_intx;
 184   }
 185   if (size > (size_t)base) {
 186     // 4812466: Make sure size doesn't allow the stack to wrap the address space.
 187     size = (size_t)base;
 188   }
 189   return size;
 190 }
 191 
 192 static inline stack_t get_stack_info() {
 193   stack_t st;
 194   int retval = thr_stksegment(&st);
 195   st.ss_size = adjust_stack_size((address)st.ss_sp, st.ss_size);
 196   assert(retval == 0, "incorrect return value from thr_stksegment");
 197   assert((address)&st < (address)st.ss_sp, "Invalid stack base returned");
 198   assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned");
 199   return st;
 200 }
 201 
 202 static void _handle_uncaught_cxx_exception() {
 203   VMError::report_and_die("An uncaught C++ exception");
 204 }
 205 
 206 bool os::is_primordial_thread(void) {
 207   int r = thr_main();
 208   guarantee(r == 0 || r == 1, "CR6501650 or CR6493689");
 209   return r == 1;
 210 }
 211 
 212 address os::current_stack_base() {
 213   bool _is_primordial_thread = is_primordial_thread();
 214 
 215   // Workaround 4352906, avoid calls to thr_stksegment by
 216   // thr_main after the first one (it looks like we trash
 217   // some data, causing the value for ss_sp to be incorrect).
 218   if (!_is_primordial_thread || os::Solaris::_main_stack_base == NULL) {
 219     stack_t st = get_stack_info();
 220     if (_is_primordial_thread) {
 221       // cache initial value of stack base
 222       os::Solaris::_main_stack_base = (address)st.ss_sp;
 223     }
 224     return (address)st.ss_sp;
 225   } else {
 226     guarantee(os::Solaris::_main_stack_base != NULL, "Attempt to use null cached stack base");
 227     return os::Solaris::_main_stack_base;
 228   }
 229 }
 230 
 231 size_t os::current_stack_size() {
 232   size_t size;
 233 
 234   if (!is_primordial_thread()) {
 235     size = get_stack_info().ss_size;
 236   } else {
 237     struct rlimit limits;
 238     getrlimit(RLIMIT_STACK, &limits);
 239     size = adjust_stack_size(os::Solaris::_main_stack_base, (size_t)limits.rlim_cur);
 240   }
 241   // base may not be page aligned
 242   address base = current_stack_base();
 243   address bottom = align_up(base - size, os::vm_page_size());;
 244   return (size_t)(base - bottom);
 245 }
 246 
 247 struct tm* os::localtime_pd(const time_t* clock, struct tm*  res) {
 248   return localtime_r(clock, res);
 249 }
 250 
 251 void os::Solaris::try_enable_extended_io() {
 252   typedef int (*enable_extended_FILE_stdio_t)(int, int);
 253 
 254   if (!UseExtendedFileIO) {
 255     return;
 256   }
 257 
 258   enable_extended_FILE_stdio_t enabler =
 259     (enable_extended_FILE_stdio_t) dlsym(RTLD_DEFAULT,
 260                                          "enable_extended_FILE_stdio");
 261   if (enabler) {
 262     enabler(-1, -1);
 263   }
 264 }
 265 
 266 static int _processors_online = 0;
 267 
 268 jint os::Solaris::_os_thread_limit = 0;
 269 volatile jint os::Solaris::_os_thread_count = 0;
 270 
 271 julong os::available_memory() {
 272   return Solaris::available_memory();
 273 }
 274 
 275 julong os::Solaris::available_memory() {
 276   return (julong)sysconf(_SC_AVPHYS_PAGES) * os::vm_page_size();
 277 }
 278 
 279 julong os::Solaris::_physical_memory = 0;
 280 
 281 julong os::physical_memory() {
 282   return Solaris::physical_memory();
 283 }
 284 
 285 static hrtime_t first_hrtime = 0;
 286 static const hrtime_t hrtime_hz = 1000*1000*1000;
 287 static volatile hrtime_t max_hrtime = 0;
 288 
 289 
 290 void os::Solaris::initialize_system_info() {
 291   set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
 292   _processors_online = sysconf(_SC_NPROCESSORS_ONLN);
 293   _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) *
 294                                      (julong)sysconf(_SC_PAGESIZE);
 295 }
 296 
 297 uint os::processor_id() {
 298   const processorid_t id = ::getcpuid();
 299   assert(id >= 0 && id < _processor_count, "Invalid processor id");
 300   return (uint)id;
 301 }
 302 
 303 int os::active_processor_count() {
 304   // User has overridden the number of active processors
 305   if (ActiveProcessorCount > 0) {
 306     log_trace(os)("active_processor_count: "
 307                   "active processor count set by user : %d",
 308                   ActiveProcessorCount);
 309     return ActiveProcessorCount;
 310   }
 311 
 312   int online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
 313   pid_t pid = getpid();
 314   psetid_t pset = PS_NONE;
 315   // Are we running in a processor set or is there any processor set around?
 316   if (pset_bind(PS_QUERY, P_PID, pid, &pset) == 0) {
 317     uint_t pset_cpus;
 318     // Query the number of cpus available to us.
 319     if (pset_info(pset, NULL, &pset_cpus, NULL) == 0) {
 320       assert(pset_cpus > 0 && pset_cpus <= online_cpus, "sanity check");
 321       _processors_online = pset_cpus;
 322       return pset_cpus;
 323     }
 324   }
 325   // Otherwise return number of online cpus
 326   return online_cpus;
 327 }
 328 
 329 static bool find_processors_in_pset(psetid_t        pset,
 330                                     processorid_t** id_array,
 331                                     uint_t*         id_length) {
 332   bool result = false;
 333   // Find the number of processors in the processor set.
 334   if (pset_info(pset, NULL, id_length, NULL) == 0) {
 335     // Make up an array to hold their ids.
 336     *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal);
 337     // Fill in the array with their processor ids.
 338     if (pset_info(pset, NULL, id_length, *id_array) == 0) {
 339       result = true;
 340     }
 341   }
 342   return result;
 343 }
 344 
 345 // Callers of find_processors_online() must tolerate imprecise results --
 346 // the system configuration can change asynchronously because of DR
 347 // or explicit psradm operations.
 348 //
 349 // We also need to take care that the loop (below) terminates as the
 350 // number of processors online can change between the _SC_NPROCESSORS_ONLN
 351 // request and the loop that builds the list of processor ids.   Unfortunately
 352 // there's no reliable way to determine the maximum valid processor id,
 353 // so we use a manifest constant, MAX_PROCESSOR_ID, instead.  See p_online
 354 // man pages, which claim the processor id set is "sparse, but
 355 // not too sparse".  MAX_PROCESSOR_ID is used to ensure that we eventually
 356 // exit the loop.
 357 //
 358 // In the future we'll be able to use sysconf(_SC_CPUID_MAX), but that's
 359 // not available on S8.0.
 360 
 361 static bool find_processors_online(processorid_t** id_array,
 362                                    uint*           id_length) {
 363   const processorid_t MAX_PROCESSOR_ID = 100000;
 364   // Find the number of processors online.
 365   *id_length = sysconf(_SC_NPROCESSORS_ONLN);
 366   // Make up an array to hold their ids.
 367   *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal);
 368   // Processors need not be numbered consecutively.
 369   long found = 0;
 370   processorid_t next = 0;
 371   while (found < *id_length && next < MAX_PROCESSOR_ID) {
 372     processor_info_t info;
 373     if (processor_info(next, &info) == 0) {
 374       // NB, PI_NOINTR processors are effectively online ...
 375       if (info.pi_state == P_ONLINE || info.pi_state == P_NOINTR) {
 376         (*id_array)[found] = next;
 377         found += 1;
 378       }
 379     }
 380     next += 1;
 381   }
 382   if (found < *id_length) {
 383     // The loop above didn't identify the expected number of processors.
 384     // We could always retry the operation, calling sysconf(_SC_NPROCESSORS_ONLN)
 385     // and re-running the loop, above, but there's no guarantee of progress
 386     // if the system configuration is in flux.  Instead, we just return what
 387     // we've got.  Note that in the worst case find_processors_online() could
 388     // return an empty set.  (As a fall-back in the case of the empty set we
 389     // could just return the ID of the current processor).
 390     *id_length = found;
 391   }
 392 
 393   return true;
 394 }
 395 
 396 static bool assign_distribution(processorid_t* id_array,
 397                                 uint           id_length,
 398                                 uint*          distribution,
 399                                 uint           distribution_length) {
 400   // We assume we can assign processorid_t's to uint's.
 401   assert(sizeof(processorid_t) == sizeof(uint),
 402          "can't convert processorid_t to uint");
 403   // Quick check to see if we won't succeed.
 404   if (id_length < distribution_length) {
 405     return false;
 406   }
 407   // Assign processor ids to the distribution.
 408   // Try to shuffle processors to distribute work across boards,
 409   // assuming 4 processors per board.
 410   const uint processors_per_board = ProcessDistributionStride;
 411   // Find the maximum processor id.
 412   processorid_t max_id = 0;
 413   for (uint m = 0; m < id_length; m += 1) {
 414     max_id = MAX2(max_id, id_array[m]);
 415   }
 416   // The next id, to limit loops.
 417   const processorid_t limit_id = max_id + 1;
 418   // Make up markers for available processors.
 419   bool* available_id = NEW_C_HEAP_ARRAY(bool, limit_id, mtInternal);
 420   for (uint c = 0; c < limit_id; c += 1) {
 421     available_id[c] = false;
 422   }
 423   for (uint a = 0; a < id_length; a += 1) {
 424     available_id[id_array[a]] = true;
 425   }
 426   // Step by "boards", then by "slot", copying to "assigned".
 427   // NEEDS_CLEANUP: The assignment of processors should be stateful,
 428   //                remembering which processors have been assigned by
 429   //                previous calls, etc., so as to distribute several
 430   //                independent calls of this method.  What we'd like is
 431   //                It would be nice to have an API that let us ask
 432   //                how many processes are bound to a processor,
 433   //                but we don't have that, either.
 434   //                In the short term, "board" is static so that
 435   //                subsequent distributions don't all start at board 0.
 436   static uint board = 0;
 437   uint assigned = 0;
 438   // Until we've found enough processors ....
 439   while (assigned < distribution_length) {
 440     // ... find the next available processor in the board.
 441     for (uint slot = 0; slot < processors_per_board; slot += 1) {
 442       uint try_id = board * processors_per_board + slot;
 443       if ((try_id < limit_id) && (available_id[try_id] == true)) {
 444         distribution[assigned] = try_id;
 445         available_id[try_id] = false;
 446         assigned += 1;
 447         break;
 448       }
 449     }
 450     board += 1;
 451     if (board * processors_per_board + 0 >= limit_id) {
 452       board = 0;
 453     }
 454   }
 455   if (available_id != NULL) {
 456     FREE_C_HEAP_ARRAY(bool, available_id);
 457   }
 458   return true;
 459 }
 460 
 461 void os::set_native_thread_name(const char *name) {
 462   if (Solaris::_pthread_setname_np != NULL) {
 463     // Only the first 31 bytes of 'name' are processed by pthread_setname_np
 464     // but we explicitly copy into a size-limited buffer to avoid any
 465     // possible overflow.
 466     char buf[32];
 467     snprintf(buf, sizeof(buf), "%s", name);
 468     buf[sizeof(buf) - 1] = '\0';
 469     Solaris::_pthread_setname_np(pthread_self(), buf);
 470   }
 471 }
 472 
 473 bool os::distribute_processes(uint length, uint* distribution) {
 474   bool result = false;
 475   // Find the processor id's of all the available CPUs.
 476   processorid_t* id_array  = NULL;
 477   uint           id_length = 0;
 478   // There are some races between querying information and using it,
 479   // since processor sets can change dynamically.
 480   psetid_t pset = PS_NONE;
 481   // Are we running in a processor set?
 482   if ((pset_bind(PS_QUERY, P_PID, P_MYID, &pset) == 0) && pset != PS_NONE) {
 483     result = find_processors_in_pset(pset, &id_array, &id_length);
 484   } else {
 485     result = find_processors_online(&id_array, &id_length);
 486   }
 487   if (result == true) {
 488     if (id_length >= length) {
 489       result = assign_distribution(id_array, id_length, distribution, length);
 490     } else {
 491       result = false;
 492     }
 493   }
 494   if (id_array != NULL) {
 495     FREE_C_HEAP_ARRAY(processorid_t, id_array);
 496   }
 497   return result;
 498 }
 499 
 500 bool os::bind_to_processor(uint processor_id) {
 501   // We assume that a processorid_t can be stored in a uint.
 502   assert(sizeof(uint) == sizeof(processorid_t),
 503          "can't convert uint to processorid_t");
 504   int bind_result =
 505     processor_bind(P_LWPID,                       // bind LWP.
 506                    P_MYID,                        // bind current LWP.
 507                    (processorid_t) processor_id,  // id.
 508                    NULL);                         // don't return old binding.
 509   return (bind_result == 0);
 510 }
 511 
 512 // Return true if user is running as root.
 513 
 514 bool os::have_special_privileges() {
 515   static bool init = false;
 516   static bool privileges = false;
 517   if (!init) {
 518     privileges = (getuid() != geteuid()) || (getgid() != getegid());
 519     init = true;
 520   }
 521   return privileges;
 522 }
 523 
 524 
 525 void os::init_system_properties_values() {
 526   // The next steps are taken in the product version:
 527   //
 528   // Obtain the JAVA_HOME value from the location of libjvm.so.
 529   // This library should be located at:
 530   // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.
 531   //
 532   // If "/jre/lib/" appears at the right place in the path, then we
 533   // assume libjvm.so is installed in a JDK and we use this path.
 534   //
 535   // Otherwise exit with message: "Could not create the Java virtual machine."
 536   //
 537   // The following extra steps are taken in the debugging version:
 538   //
 539   // If "/jre/lib/" does NOT appear at the right place in the path
 540   // instead of exit check for $JAVA_HOME environment variable.
 541   //
 542   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
 543   // then we append a fake suffix "hotspot/libjvm.so" to this path so
 544   // it looks like libjvm.so is installed there
 545   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
 546   //
 547   // Otherwise exit.
 548   //
 549   // Important note: if the location of libjvm.so changes this
 550   // code needs to be changed accordingly.
 551 
 552 // Base path of extensions installed on the system.
 553 #define SYS_EXT_DIR     "/usr/jdk/packages"
 554 #define EXTENSIONS_DIR  "/lib/ext"
 555 
 556   // Buffer that fits several sprintfs.
 557   // Note that the space for the colon and the trailing null are provided
 558   // by the nulls included by the sizeof operator.
 559   const size_t bufsize =
 560     MAX3((size_t)MAXPATHLEN,  // For dll_dir & friends.
 561          sizeof(SYS_EXT_DIR) + sizeof("/lib/"), // invariant ld_library_path
 562          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir
 563   char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
 564 
 565   // sysclasspath, java_home, dll_dir
 566   {
 567     char *pslash;
 568     os::jvm_path(buf, bufsize);
 569 
 570     // Found the full path to libjvm.so.
 571     // Now cut the path to <java_home>/jre if we can.
 572     *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.
 573     pslash = strrchr(buf, '/');
 574     if (pslash != NULL) {
 575       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
 576     }
 577     Arguments::set_dll_dir(buf);
 578 
 579     if (pslash != NULL) {
 580       pslash = strrchr(buf, '/');
 581       if (pslash != NULL) {
 582         *pslash = '\0';        // Get rid of /lib.
 583       }
 584     }
 585     Arguments::set_java_home(buf);
 586     if (!set_boot_path('/', ':')) {
 587       vm_exit_during_initialization("Failed setting boot class path.", NULL);
 588     }
 589   }
 590 
 591   // Where to look for native libraries.
 592   {
 593     // Use dlinfo() to determine the correct java.library.path.
 594     //
 595     // If we're launched by the Java launcher, and the user
 596     // does not set java.library.path explicitly on the commandline,
 597     // the Java launcher sets LD_LIBRARY_PATH for us and unsets
 598     // LD_LIBRARY_PATH_32 and LD_LIBRARY_PATH_64.  In this case
 599     // dlinfo returns LD_LIBRARY_PATH + crle settings (including
 600     // /usr/lib), which is exactly what we want.
 601     //
 602     // If the user does set java.library.path, it completely
 603     // overwrites this setting, and always has.
 604     //
 605     // If we're not launched by the Java launcher, we may
 606     // get here with any/all of the LD_LIBRARY_PATH[_32|64]
 607     // settings.  Again, dlinfo does exactly what we want.
 608 
 609     Dl_serinfo     info_sz, *info = &info_sz;
 610     Dl_serpath     *path;
 611     char           *library_path;
 612     char           *common_path = buf;
 613 
 614     // Determine search path count and required buffer size.
 615     if (dlinfo(RTLD_SELF, RTLD_DI_SERINFOSIZE, (void *)info) == -1) {
 616       FREE_C_HEAP_ARRAY(char, buf);
 617       vm_exit_during_initialization("dlinfo SERINFOSIZE request", dlerror());
 618     }
 619 
 620     // Allocate new buffer and initialize.
 621     info = (Dl_serinfo*)NEW_C_HEAP_ARRAY(char, info_sz.dls_size, mtInternal);
 622     info->dls_size = info_sz.dls_size;
 623     info->dls_cnt = info_sz.dls_cnt;
 624 
 625     // Obtain search path information.
 626     if (dlinfo(RTLD_SELF, RTLD_DI_SERINFO, (void *)info) == -1) {
 627       FREE_C_HEAP_ARRAY(char, buf);
 628       FREE_C_HEAP_ARRAY(char, info);
 629       vm_exit_during_initialization("dlinfo SERINFO request", dlerror());
 630     }
 631 
 632     path = &info->dls_serpath[0];
 633 
 634     // Note: Due to a legacy implementation, most of the library path
 635     // is set in the launcher. This was to accomodate linking restrictions
 636     // on legacy Solaris implementations (which are no longer supported).
 637     // Eventually, all the library path setting will be done here.
 638     //
 639     // However, to prevent the proliferation of improperly built native
 640     // libraries, the new path component /usr/jdk/packages is added here.
 641 
 642     // Construct the invariant part of ld_library_path.
 643     sprintf(common_path, SYS_EXT_DIR "/lib");
 644 
 645     // Struct size is more than sufficient for the path components obtained
 646     // through the dlinfo() call, so only add additional space for the path
 647     // components explicitly added here.
 648     size_t library_path_size = info->dls_size + strlen(common_path);
 649     library_path = (char *)NEW_C_HEAP_ARRAY(char, library_path_size, mtInternal);
 650     library_path[0] = '\0';
 651 
 652     // Construct the desired Java library path from the linker's library
 653     // search path.
 654     //
 655     // For compatibility, it is optimal that we insert the additional path
 656     // components specific to the Java VM after those components specified
 657     // in LD_LIBRARY_PATH (if any) but before those added by the ld.so
 658     // infrastructure.
 659     if (info->dls_cnt == 0) { // Not sure this can happen, but allow for it.
 660       strcpy(library_path, common_path);
 661     } else {
 662       int inserted = 0;
 663       int i;
 664       for (i = 0; i < info->dls_cnt; i++, path++) {
 665         uint_t flags = path->dls_flags & LA_SER_MASK;
 666         if (((flags & LA_SER_LIBPATH) == 0) && !inserted) {
 667           strcat(library_path, common_path);
 668           strcat(library_path, os::path_separator());
 669           inserted = 1;
 670         }
 671         strcat(library_path, path->dls_name);
 672         strcat(library_path, os::path_separator());
 673       }
 674       // Eliminate trailing path separator.
 675       library_path[strlen(library_path)-1] = '\0';
 676     }
 677 
 678     // happens before argument parsing - can't use a trace flag
 679     // tty->print_raw("init_system_properties_values: native lib path: ");
 680     // tty->print_raw_cr(library_path);
 681 
 682     // Callee copies into its own buffer.
 683     Arguments::set_library_path(library_path);
 684 
 685     FREE_C_HEAP_ARRAY(char, library_path);
 686     FREE_C_HEAP_ARRAY(char, info);
 687   }
 688 
 689   // Extensions directories.
 690   sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
 691   Arguments::set_ext_dirs(buf);
 692 
 693   FREE_C_HEAP_ARRAY(char, buf);
 694 
 695 #undef SYS_EXT_DIR
 696 #undef EXTENSIONS_DIR
 697 }
 698 
 699 void os::breakpoint() {
 700   BREAKPOINT;
 701 }
 702 
 703 bool os::Solaris::valid_stack_address(Thread* thread, address sp) {
 704   address  stackStart  = (address)thread->stack_base();
 705   address  stackEnd    = (address)(stackStart - (address)thread->stack_size());
 706   if (sp < stackStart && sp >= stackEnd) return true;
 707   return false;
 708 }
 709 
 710 extern "C" void breakpoint() {
 711   // use debugger to set breakpoint here
 712 }
 713 
 714 static thread_t main_thread;
 715 
 716 // Thread start routine for all newly created threads
 717 extern "C" void* thread_native_entry(void* thread_addr) {
 718 
 719   Thread* thread = (Thread*)thread_addr;
 720 
 721   thread->record_stack_base_and_size();
 722 
 723   // Try to randomize the cache line index of hot stack frames.
 724   // This helps when threads of the same stack traces evict each other's
 725   // cache lines. The threads can be either from the same JVM instance, or
 726   // from different JVM instances. The benefit is especially true for
 727   // processors with hyperthreading technology.
 728   static int counter = 0;
 729   int pid = os::current_process_id();
 730   alloca(((pid ^ counter++) & 7) * 128);
 731 
 732   int prio;
 733 
 734   thread->initialize_thread_current();
 735 
 736   OSThread* osthr = thread->osthread();
 737 
 738   osthr->set_lwp_id(_lwp_self());  // Store lwp in case we are bound
 739 
 740   log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ").",
 741     os::current_thread_id());
 742 
 743   if (UseNUMA) {
 744     int lgrp_id = os::numa_get_group_id();
 745     if (lgrp_id != -1) {
 746       thread->set_lgrp_id(lgrp_id);
 747     }
 748   }
 749 
 750   // Our priority was set when we were created, and stored in the
 751   // osthread, but couldn't be passed through to our LWP until now.
 752   // So read back the priority and set it again.
 753 
 754   if (osthr->thread_id() != -1) {
 755     if (UseThreadPriorities) {
 756       int prio = osthr->native_priority();
 757       if (ThreadPriorityVerbose) {
 758         tty->print_cr("Starting Thread " INTPTR_FORMAT ", LWP is "
 759                       INTPTR_FORMAT ", setting priority: %d\n",
 760                       osthr->thread_id(), osthr->lwp_id(), prio);
 761       }
 762       os::set_native_priority(thread, prio);
 763     }
 764   } else if (ThreadPriorityVerbose) {
 765     warning("Can't set priority in _start routine, thread id hasn't been set\n");
 766   }
 767 
 768   assert(osthr->get_state() == RUNNABLE, "invalid os thread state");
 769 
 770   // initialize signal mask for this thread
 771   os::Solaris::hotspot_sigmask(thread);
 772 
 773   os::Solaris::init_thread_fpu_state();
 774   std::set_terminate(_handle_uncaught_cxx_exception);
 775 
 776   thread->call_run();
 777 
 778   // Note: at this point the thread object may already have deleted itself.
 779   // Do not dereference it from here on out.
 780 
 781   // One less thread is executing
 782   // When the VMThread gets here, the main thread may have already exited
 783   // which frees the CodeHeap containing the Atomic::dec code
 784   if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {
 785     Atomic::dec(&os::Solaris::_os_thread_count);
 786   }
 787 
 788   log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ").", os::current_thread_id());
 789 
 790   if (UseDetachedThreads) {
 791     thr_exit(NULL);
 792     ShouldNotReachHere();
 793   }
 794   return NULL;
 795 }
 796 
 797 static OSThread* create_os_thread(Thread* thread, thread_t thread_id) {
 798   // Allocate the OSThread object
 799   OSThread* osthread = new OSThread(NULL, NULL);
 800   if (osthread == NULL) return NULL;
 801 
 802   // Store info on the Solaris thread into the OSThread
 803   osthread->set_thread_id(thread_id);
 804   osthread->set_lwp_id(_lwp_self());
 805 
 806   if (UseNUMA) {
 807     int lgrp_id = os::numa_get_group_id();
 808     if (lgrp_id != -1) {
 809       thread->set_lgrp_id(lgrp_id);
 810     }
 811   }
 812 
 813   if (ThreadPriorityVerbose) {
 814     tty->print_cr("In create_os_thread, Thread " INTPTR_FORMAT ", LWP is " INTPTR_FORMAT "\n",
 815                   osthread->thread_id(), osthread->lwp_id());
 816   }
 817 
 818   // Initial thread state is INITIALIZED, not SUSPENDED
 819   osthread->set_state(INITIALIZED);
 820 
 821   return osthread;
 822 }
 823 
 824 void os::Solaris::hotspot_sigmask(Thread* thread) {
 825   //Save caller's signal mask
 826   sigset_t sigmask;
 827   pthread_sigmask(SIG_SETMASK, NULL, &sigmask);
 828   OSThread *osthread = thread->osthread();
 829   osthread->set_caller_sigmask(sigmask);
 830 
 831   pthread_sigmask(SIG_UNBLOCK, os::Solaris::unblocked_signals(), NULL);
 832   if (!ReduceSignalUsage) {
 833     if (thread->is_VM_thread()) {
 834       // Only the VM thread handles BREAK_SIGNAL ...
 835       pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL);
 836     } else {
 837       // ... all other threads block BREAK_SIGNAL
 838       assert(!sigismember(vm_signals(), SIGINT), "SIGINT should not be blocked");
 839       pthread_sigmask(SIG_BLOCK, vm_signals(), NULL);
 840     }
 841   }
 842 }
 843 
 844 bool os::create_attached_thread(JavaThread* thread) {
 845 #ifdef ASSERT
 846   thread->verify_not_published();
 847 #endif
 848   OSThread* osthread = create_os_thread(thread, thr_self());
 849   if (osthread == NULL) {
 850     return false;
 851   }
 852 
 853   // Initial thread state is RUNNABLE
 854   osthread->set_state(RUNNABLE);
 855   thread->set_osthread(osthread);
 856 
 857   // initialize signal mask for this thread
 858   // and save the caller's signal mask
 859   os::Solaris::hotspot_sigmask(thread);
 860 
 861   log_info(os, thread)("Thread attached (tid: " UINTX_FORMAT ").",
 862     os::current_thread_id());
 863 
 864   return true;
 865 }
 866 
 867 bool os::create_main_thread(JavaThread* thread) {
 868 #ifdef ASSERT
 869   thread->verify_not_published();
 870 #endif
 871   if (_starting_thread == NULL) {
 872     _starting_thread = create_os_thread(thread, main_thread);
 873     if (_starting_thread == NULL) {
 874       return false;
 875     }
 876   }
 877 
 878   // The primodial thread is runnable from the start
 879   _starting_thread->set_state(RUNNABLE);
 880 
 881   thread->set_osthread(_starting_thread);
 882 
 883   // initialize signal mask for this thread
 884   // and save the caller's signal mask
 885   os::Solaris::hotspot_sigmask(thread);
 886 
 887   return true;
 888 }
 889 
 890 // Helper function to trace thread attributes, similar to os::Posix::describe_pthread_attr()
 891 static char* describe_thr_create_attributes(char* buf, size_t buflen,
 892                                             size_t stacksize, long flags) {
 893   stringStream ss(buf, buflen);
 894   ss.print("stacksize: " SIZE_FORMAT "k, ", stacksize / 1024);
 895   ss.print("flags: ");
 896   #define PRINT_FLAG(f) if (flags & f) ss.print( #f " ");
 897   #define ALL(X) \
 898     X(THR_SUSPENDED) \
 899     X(THR_DETACHED) \
 900     X(THR_BOUND) \
 901     X(THR_NEW_LWP) \
 902     X(THR_DAEMON)
 903   ALL(PRINT_FLAG)
 904   #undef ALL
 905   #undef PRINT_FLAG
 906   return buf;
 907 }
 908 
 909 // return default stack size for thr_type
 910 size_t os::Posix::default_stack_size(os::ThreadType thr_type) {
 911   // default stack size when not specified by caller is 1M (2M for LP64)
 912   size_t s = (BytesPerWord >> 2) * K * K;
 913   return s;
 914 }
 915 
 916 bool os::create_thread(Thread* thread, ThreadType thr_type,
 917                        size_t req_stack_size) {
 918   // Allocate the OSThread object
 919   OSThread* osthread = new OSThread(NULL, NULL);
 920   if (osthread == NULL) {
 921     return false;
 922   }
 923 
 924   if (ThreadPriorityVerbose) {
 925     char *thrtyp;
 926     switch (thr_type) {
 927     case vm_thread:
 928       thrtyp = (char *)"vm";
 929       break;
 930     case cgc_thread:
 931       thrtyp = (char *)"cgc";
 932       break;
 933     case pgc_thread:
 934       thrtyp = (char *)"pgc";
 935       break;
 936     case java_thread:
 937       thrtyp = (char *)"java";
 938       break;
 939     case compiler_thread:
 940       thrtyp = (char *)"compiler";
 941       break;
 942     case watcher_thread:
 943       thrtyp = (char *)"watcher";
 944       break;
 945     default:
 946       thrtyp = (char *)"unknown";
 947       break;
 948     }
 949     tty->print_cr("In create_thread, creating a %s thread\n", thrtyp);
 950   }
 951 
 952   // calculate stack size if it's not specified by caller
 953   size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);
 954 
 955   // Initial state is ALLOCATED but not INITIALIZED
 956   osthread->set_state(ALLOCATED);
 957 
 958   if (os::Solaris::_os_thread_count > os::Solaris::_os_thread_limit) {
 959     // We got lots of threads. Check if we still have some address space left.
 960     // Need to be at least 5Mb of unreserved address space. We do check by
 961     // trying to reserve some.
 962     const size_t VirtualMemoryBangSize = 20*K*K;
 963     char* mem = os::reserve_memory(VirtualMemoryBangSize);
 964     if (mem == NULL) {
 965       delete osthread;
 966       return false;
 967     } else {
 968       // Release the memory again
 969       os::release_memory(mem, VirtualMemoryBangSize);
 970     }
 971   }
 972 
 973   // Setup osthread because the child thread may need it.
 974   thread->set_osthread(osthread);
 975 
 976   // Create the Solaris thread
 977   thread_t tid = 0;
 978   long     flags = (UseDetachedThreads ? THR_DETACHED : 0) | THR_SUSPENDED;
 979   int      status;
 980 
 981   // Mark that we don't have an lwp or thread id yet.
 982   // In case we attempt to set the priority before the thread starts.
 983   osthread->set_lwp_id(-1);
 984   osthread->set_thread_id(-1);
 985 
 986   status = thr_create(NULL, stack_size, thread_native_entry, thread, flags, &tid);
 987 
 988   char buf[64];
 989   if (status == 0) {
 990     log_info(os, thread)("Thread started (tid: " UINTX_FORMAT ", attributes: %s). ",
 991       (uintx) tid, describe_thr_create_attributes(buf, sizeof(buf), stack_size, flags));
 992   } else {
 993     log_warning(os, thread)("Failed to start thread - thr_create failed (%s) for attributes: %s.",
 994       os::errno_name(status), describe_thr_create_attributes(buf, sizeof(buf), stack_size, flags));
 995   }
 996 
 997   if (status != 0) {
 998     thread->set_osthread(NULL);
 999     // Need to clean up stuff we've allocated so far
1000     delete osthread;
1001     return false;
1002   }
1003 
1004   Atomic::inc(&os::Solaris::_os_thread_count);
1005 
1006   // Store info on the Solaris thread into the OSThread
1007   osthread->set_thread_id(tid);
1008 
1009   // Remember that we created this thread so we can set priority on it
1010   osthread->set_vm_created();
1011 
1012   // Most thread types will set an explicit priority before starting the thread,
1013   // but for those that don't we need a valid value to read back in thread_native_entry.
1014   osthread->set_native_priority(NormPriority);
1015 
1016   // Initial thread state is INITIALIZED, not SUSPENDED
1017   osthread->set_state(INITIALIZED);
1018 
1019   // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain
1020   return true;
1021 }
1022 
1023 debug_only(static bool signal_sets_initialized = false);
1024 static sigset_t unblocked_sigs, vm_sigs;
1025 
1026 void os::Solaris::signal_sets_init() {
1027   // Should also have an assertion stating we are still single-threaded.
1028   assert(!signal_sets_initialized, "Already initialized");
1029   // Fill in signals that are necessarily unblocked for all threads in
1030   // the VM. Currently, we unblock the following signals:
1031   // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden
1032   //                         by -Xrs (=ReduceSignalUsage));
1033   // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all
1034   // other threads. The "ReduceSignalUsage" boolean tells us not to alter
1035   // the dispositions or masks wrt these signals.
1036   // Programs embedding the VM that want to use the above signals for their
1037   // own purposes must, at this time, use the "-Xrs" option to prevent
1038   // interference with shutdown hooks and BREAK_SIGNAL thread dumping.
1039   // (See bug 4345157, and other related bugs).
1040   // In reality, though, unblocking these signals is really a nop, since
1041   // these signals are not blocked by default.
1042   sigemptyset(&unblocked_sigs);
1043   sigaddset(&unblocked_sigs, SIGILL);
1044   sigaddset(&unblocked_sigs, SIGSEGV);
1045   sigaddset(&unblocked_sigs, SIGBUS);
1046   sigaddset(&unblocked_sigs, SIGFPE);
1047   sigaddset(&unblocked_sigs, ASYNC_SIGNAL);
1048 
1049   if (!ReduceSignalUsage) {
1050     if (!os::Posix::is_sig_ignored(SHUTDOWN1_SIGNAL)) {
1051       sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);
1052     }
1053     if (!os::Posix::is_sig_ignored(SHUTDOWN2_SIGNAL)) {
1054       sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);
1055     }
1056     if (!os::Posix::is_sig_ignored(SHUTDOWN3_SIGNAL)) {
1057       sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);
1058     }
1059   }
1060   // Fill in signals that are blocked by all but the VM thread.
1061   sigemptyset(&vm_sigs);
1062   if (!ReduceSignalUsage) {
1063     sigaddset(&vm_sigs, BREAK_SIGNAL);
1064   }
1065   debug_only(signal_sets_initialized = true);
1066 
1067   // For diagnostics only used in run_periodic_checks
1068   sigemptyset(&check_signal_done);
1069 }
1070 
1071 // These are signals that are unblocked while a thread is running Java.
1072 // (For some reason, they get blocked by default.)
1073 sigset_t* os::Solaris::unblocked_signals() {
1074   assert(signal_sets_initialized, "Not initialized");
1075   return &unblocked_sigs;
1076 }
1077 
1078 // These are the signals that are blocked while a (non-VM) thread is
1079 // running Java. Only the VM thread handles these signals.
1080 sigset_t* os::Solaris::vm_signals() {
1081   assert(signal_sets_initialized, "Not initialized");
1082   return &vm_sigs;
1083 }
1084 
1085 // CR 7190089: on Solaris, primordial thread's stack needs adjusting.
1086 // Without the adjustment, stack size is incorrect if stack is set to unlimited (ulimit -s unlimited).
1087 void os::Solaris::correct_stack_boundaries_for_primordial_thread(Thread* thr) {
1088   assert(is_primordial_thread(), "Call only for primordial thread");
1089 
1090   JavaThread* jt = (JavaThread *)thr;
1091   assert(jt != NULL, "Sanity check");
1092   size_t stack_size;
1093   address base = jt->stack_base();
1094   if (Arguments::created_by_java_launcher()) {
1095     // Use 2MB to allow for Solaris 7 64 bit mode.
1096     stack_size = JavaThread::stack_size_at_create() == 0
1097       ? 2048*K : JavaThread::stack_size_at_create();
1098 
1099     // There are rare cases when we may have already used more than
1100     // the basic stack size allotment before this method is invoked.
1101     // Attempt to allow for a normally sized java_stack.
1102     size_t current_stack_offset = (size_t)(base - (address)&stack_size);
1103     stack_size += ReservedSpace::page_align_size_down(current_stack_offset);
1104   } else {
1105     // 6269555: If we were not created by a Java launcher, i.e. if we are
1106     // running embedded in a native application, treat the primordial thread
1107     // as much like a native attached thread as possible.  This means using
1108     // the current stack size from thr_stksegment(), unless it is too large
1109     // to reliably setup guard pages.  A reasonable max size is 8MB.
1110     size_t current_size = os::current_stack_size();
1111     // This should never happen, but just in case....
1112     if (current_size == 0) current_size = 2 * K * K;
1113     stack_size = current_size > (8 * K * K) ? (8 * K * K) : current_size;
1114   }
1115   address bottom = align_up(base - stack_size, os::vm_page_size());;
1116   stack_size = (size_t)(base - bottom);
1117 
1118   assert(stack_size > 0, "Stack size calculation problem");
1119 
1120   if (stack_size > jt->stack_size()) {
1121 #ifndef PRODUCT
1122     struct rlimit limits;
1123     getrlimit(RLIMIT_STACK, &limits);
1124     size_t size = adjust_stack_size(base, (size_t)limits.rlim_cur);
1125     assert(size >= jt->stack_size(), "Stack size problem in main thread");
1126 #endif
1127     tty->print_cr("Stack size of %d Kb exceeds current limit of %d Kb.\n"
1128                   "(Stack sizes are rounded up to a multiple of the system page size.)\n"
1129                   "See limit(1) to increase the stack size limit.",
1130                   stack_size / K, jt->stack_size() / K);
1131     vm_exit(1);
1132   }
1133   assert(jt->stack_size() >= stack_size,
1134          "Attempt to map more stack than was allocated");
1135   jt->set_stack_size(stack_size);
1136 
1137 }
1138 
1139 
1140 
1141 // Free Solaris resources related to the OSThread
1142 void os::free_thread(OSThread* osthread) {
1143   assert(osthread != NULL, "os::free_thread but osthread not set");
1144 
1145   // We are told to free resources of the argument thread,
1146   // but we can only really operate on the current thread.
1147   assert(Thread::current()->osthread() == osthread,
1148          "os::free_thread but not current thread");
1149 
1150   // Restore caller's signal mask
1151   sigset_t sigmask = osthread->caller_sigmask();
1152   pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
1153 
1154   delete osthread;
1155 }
1156 
1157 void os::pd_start_thread(Thread* thread) {
1158   int status = thr_continue(thread->osthread()->thread_id());
1159   assert_status(status == 0, status, "thr_continue failed");
1160 }
1161 
1162 
1163 intx os::current_thread_id() {
1164   return (intx)thr_self();
1165 }
1166 
1167 static pid_t _initial_pid = 0;
1168 
1169 int os::current_process_id() {
1170   return (int)(_initial_pid ? _initial_pid : getpid());
1171 }
1172 
1173 // gethrtime() should be monotonic according to the documentation,
1174 // but some virtualized platforms are known to break this guarantee.
1175 // getTimeNanos() must be guaranteed not to move backwards, so we
1176 // are forced to add a check here.
1177 inline hrtime_t getTimeNanos() {
1178   const hrtime_t now = gethrtime();
1179   const hrtime_t prev = max_hrtime;
1180   if (now <= prev) {
1181     return prev;   // same or retrograde time;
1182   }
1183   const hrtime_t obsv = Atomic::cmpxchg(now, &max_hrtime, prev);
1184   assert(obsv >= prev, "invariant");   // Monotonicity
1185   // If the CAS succeeded then we're done and return "now".
1186   // If the CAS failed and the observed value "obsv" is >= now then
1187   // we should return "obsv".  If the CAS failed and now > obsv > prv then
1188   // some other thread raced this thread and installed a new value, in which case
1189   // we could either (a) retry the entire operation, (b) retry trying to install now
1190   // or (c) just return obsv.  We use (c).   No loop is required although in some cases
1191   // we might discard a higher "now" value in deference to a slightly lower but freshly
1192   // installed obsv value.   That's entirely benign -- it admits no new orderings compared
1193   // to (a) or (b) -- and greatly reduces coherence traffic.
1194   // We might also condition (c) on the magnitude of the delta between obsv and now.
1195   // Avoiding excessive CAS operations to hot RW locations is critical.
1196   // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
1197   return (prev == obsv) ? now : obsv;
1198 }
1199 
1200 // Time since start-up in seconds to a fine granularity.
1201 // Used by VMSelfDestructTimer and the MemProfiler.
1202 double os::elapsedTime() {
1203   return (double)(getTimeNanos() - first_hrtime) / (double)hrtime_hz;
1204 }
1205 
1206 jlong os::elapsed_counter() {
1207   return (jlong)(getTimeNanos() - first_hrtime);
1208 }
1209 
1210 jlong os::elapsed_frequency() {
1211   return hrtime_hz;
1212 }
1213 
1214 // Return the real, user, and system times in seconds from an
1215 // arbitrary fixed point in the past.
1216 bool os::getTimesSecs(double* process_real_time,
1217                       double* process_user_time,
1218                       double* process_system_time) {
1219   struct tms ticks;
1220   clock_t real_ticks = times(&ticks);
1221 
1222   if (real_ticks == (clock_t) (-1)) {
1223     return false;
1224   } else {
1225     double ticks_per_second = (double) clock_tics_per_sec;
1226     *process_user_time = ((double) ticks.tms_utime) / ticks_per_second;
1227     *process_system_time = ((double) ticks.tms_stime) / ticks_per_second;
1228     // For consistency return the real time from getTimeNanos()
1229     // converted to seconds.
1230     *process_real_time = ((double) getTimeNanos()) / ((double) NANOUNITS);
1231 
1232     return true;
1233   }
1234 }
1235 
1236 bool os::supports_vtime() { return true; }
1237 bool os::enable_vtime() { return false; }
1238 bool os::vtime_enabled() { return false; }
1239 
1240 double os::elapsedVTime() {
1241   return (double)gethrvtime() / (double)hrtime_hz;
1242 }
1243 
1244 // Must return millis since Jan 1 1970 for JVM_CurrentTimeMillis
1245 jlong os::javaTimeMillis() {
1246   timeval t;
1247   if (gettimeofday(&t, NULL) == -1) {
1248     fatal("os::javaTimeMillis: gettimeofday (%s)", os::strerror(errno));
1249   }
1250   return jlong(t.tv_sec) * 1000  +  jlong(t.tv_usec) / 1000;
1251 }
1252 
1253 // Must return seconds+nanos since Jan 1 1970. This must use the same
1254 // time source as javaTimeMillis and can't use get_nsec_fromepoch as
1255 // we need better than 1ms accuracy
1256 void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) {
1257   timeval t;
1258   if (gettimeofday(&t, NULL) == -1) {
1259     fatal("os::javaTimeSystemUTC: gettimeofday (%s)", os::strerror(errno));
1260   }
1261   seconds = jlong(t.tv_sec);
1262   nanos = jlong(t.tv_usec) * 1000;
1263 }
1264 
1265 
1266 jlong os::javaTimeNanos() {
1267   return (jlong)getTimeNanos();
1268 }
1269 
1270 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
1271   info_ptr->max_value = ALL_64_BITS;      // gethrtime() uses all 64 bits
1272   info_ptr->may_skip_backward = false;    // not subject to resetting or drifting
1273   info_ptr->may_skip_forward = false;     // not subject to resetting or drifting
1274   info_ptr->kind = JVMTI_TIMER_ELAPSED;   // elapsed not CPU time
1275 }
1276 
1277 char * os::local_time_string(char *buf, size_t buflen) {
1278   struct tm t;
1279   time_t long_time;
1280   time(&long_time);
1281   localtime_r(&long_time, &t);
1282   jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",
1283                t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
1284                t.tm_hour, t.tm_min, t.tm_sec);
1285   return buf;
1286 }
1287 
1288 // Note: os::shutdown() might be called very early during initialization, or
1289 // called from signal handler. Before adding something to os::shutdown(), make
1290 // sure it is async-safe and can handle partially initialized VM.
1291 void os::shutdown() {
1292 
1293   // allow PerfMemory to attempt cleanup of any persistent resources
1294   perfMemory_exit();
1295 
1296   // needs to remove object in file system
1297   AttachListener::abort();
1298 
1299   // flush buffered output, finish log files
1300   ostream_abort();
1301 
1302   // Check for abort hook
1303   abort_hook_t abort_hook = Arguments::abort_hook();
1304   if (abort_hook != NULL) {
1305     abort_hook();
1306   }
1307 }
1308 
1309 // Note: os::abort() might be called very early during initialization, or
1310 // called from signal handler. Before adding something to os::abort(), make
1311 // sure it is async-safe and can handle partially initialized VM.
1312 void os::abort(bool dump_core, void* siginfo, const void* context) {
1313   os::shutdown();
1314   if (dump_core) {
1315 #ifndef PRODUCT
1316     fdStream out(defaultStream::output_fd());
1317     out.print_raw("Current thread is ");
1318     char buf[16];
1319     jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());
1320     out.print_raw_cr(buf);
1321     out.print_raw_cr("Dumping core ...");
1322 #endif
1323     ::abort(); // dump core (for debugging)
1324   }
1325 
1326   ::exit(1);
1327 }
1328 
1329 // Die immediately, no exit hook, no abort hook, no cleanup.
1330 void os::die() {
1331   ::abort(); // dump core (for debugging)
1332 }
1333 
1334 // DLL functions
1335 
1336 const char* os::dll_file_extension() { return ".so"; }
1337 
1338 // This must be hard coded because it's the system's temporary
1339 // directory not the java application's temp directory, ala java.io.tmpdir.
1340 const char* os::get_temp_directory() { return "/tmp"; }
1341 
1342 // check if addr is inside libjvm.so
1343 bool os::address_is_in_vm(address addr) {
1344   static address libjvm_base_addr;
1345   Dl_info dlinfo;
1346 
1347   if (libjvm_base_addr == NULL) {
1348     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1349       libjvm_base_addr = (address)dlinfo.dli_fbase;
1350     }
1351     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1352   }
1353 
1354   if (dladdr((void *)addr, &dlinfo) != 0) {
1355     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1356   }
1357 
1358   return false;
1359 }
1360 
1361 typedef int (*dladdr1_func_type)(void *, Dl_info *, void **, int);
1362 static dladdr1_func_type dladdr1_func = NULL;
1363 
1364 bool os::dll_address_to_function_name(address addr, char *buf,
1365                                       int buflen, int * offset,
1366                                       bool demangle) {
1367   // buf is not optional, but offset is optional
1368   assert(buf != NULL, "sanity check");
1369 
1370   Dl_info dlinfo;
1371 
1372   // dladdr1_func was initialized in os::init()
1373   if (dladdr1_func != NULL) {
1374     // yes, we have dladdr1
1375 
1376     // Support for dladdr1 is checked at runtime; it may be
1377     // available even if the vm is built on a machine that does
1378     // not have dladdr1 support.  Make sure there is a value for
1379     // RTLD_DL_SYMENT.
1380 #ifndef RTLD_DL_SYMENT
1381   #define RTLD_DL_SYMENT 1
1382 #endif
1383 #ifdef _LP64
1384     Elf64_Sym * info;
1385 #else
1386     Elf32_Sym * info;
1387 #endif
1388     if (dladdr1_func((void *)addr, &dlinfo, (void **)&info,
1389                      RTLD_DL_SYMENT) != 0) {
1390       // see if we have a matching symbol that covers our address
1391       if (dlinfo.dli_saddr != NULL &&
1392           (char *)dlinfo.dli_saddr + info->st_size > (char *)addr) {
1393         if (dlinfo.dli_sname != NULL) {
1394           if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1395             jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1396           }
1397           if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1398           return true;
1399         }
1400       }
1401       // no matching symbol so try for just file info
1402       if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1403         if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1404                             buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1405           return true;
1406         }
1407       }
1408     }
1409     buf[0] = '\0';
1410     if (offset != NULL) *offset  = -1;
1411     return false;
1412   }
1413 
1414   // no, only dladdr is available
1415   if (dladdr((void *)addr, &dlinfo) != 0) {
1416     // see if we have a matching symbol
1417     if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1418       if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1419         jio_snprintf(buf, buflen, dlinfo.dli_sname);
1420       }
1421       if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1422       return true;
1423     }
1424     // no matching symbol so try for just file info
1425     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1426       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1427                           buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1428         return true;
1429       }
1430     }
1431   }
1432   buf[0] = '\0';
1433   if (offset != NULL) *offset  = -1;
1434   return false;
1435 }
1436 
1437 bool os::dll_address_to_library_name(address addr, char* buf,
1438                                      int buflen, int* offset) {
1439   // buf is not optional, but offset is optional
1440   assert(buf != NULL, "sanity check");
1441 
1442   Dl_info dlinfo;
1443 
1444   if (dladdr((void*)addr, &dlinfo) != 0) {
1445     if (dlinfo.dli_fname != NULL) {
1446       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1447     }
1448     if (dlinfo.dli_fbase != NULL && offset != NULL) {
1449       *offset = addr - (address)dlinfo.dli_fbase;
1450     }
1451     return true;
1452   }
1453 
1454   buf[0] = '\0';
1455   if (offset) *offset = -1;
1456   return false;
1457 }
1458 
1459 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {
1460   Dl_info dli;
1461   // Sanity check?
1462   if (dladdr(CAST_FROM_FN_PTR(void *, os::get_loaded_modules_info), &dli) == 0 ||
1463       dli.dli_fname == NULL) {
1464     return 1;
1465   }
1466 
1467   void * handle = dlopen(dli.dli_fname, RTLD_LAZY);
1468   if (handle == NULL) {
1469     return 1;
1470   }
1471 
1472   Link_map *map;
1473   dlinfo(handle, RTLD_DI_LINKMAP, &map);
1474   if (map == NULL) {
1475     dlclose(handle);
1476     return 1;
1477   }
1478 
1479   while (map->l_prev != NULL) {
1480     map = map->l_prev;
1481   }
1482 
1483   while (map != NULL) {
1484     // Iterate through all map entries and call callback with fields of interest
1485     if(callback(map->l_name, (address)map->l_addr, (address)0, param)) {
1486       dlclose(handle);
1487       return 1;
1488     }
1489     map = map->l_next;
1490   }
1491 
1492   dlclose(handle);
1493   return 0;
1494 }
1495 
1496 int _print_dll_info_cb(const char * name, address base_address, address top_address, void * param) {
1497   outputStream * out = (outputStream *) param;
1498   out->print_cr(PTR_FORMAT " \t%s", base_address, name);
1499   return 0;
1500 }
1501 
1502 void os::print_dll_info(outputStream * st) {
1503   st->print_cr("Dynamic libraries:"); st->flush();
1504   if (get_loaded_modules_info(_print_dll_info_cb, (void *)st)) {
1505     st->print_cr("Error: Cannot print dynamic libraries.");
1506   }
1507 }
1508 
1509 // Loads .dll/.so and
1510 // in case of error it checks if .dll/.so was built for the
1511 // same architecture as Hotspot is running on
1512 
1513 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1514   void * result= ::dlopen(filename, RTLD_LAZY);
1515   if (result != NULL) {
1516     // Successful loading
1517     return result;
1518   }
1519 
1520   Elf32_Ehdr elf_head;
1521 
1522   // Read system error message into ebuf
1523   // It may or may not be overwritten below
1524   ::strncpy(ebuf, ::dlerror(), ebuflen-1);
1525   ebuf[ebuflen-1]='\0';
1526   int diag_msg_max_length=ebuflen-strlen(ebuf);
1527   char* diag_msg_buf=ebuf+strlen(ebuf);
1528 
1529   if (diag_msg_max_length==0) {
1530     // No more space in ebuf for additional diagnostics message
1531     return NULL;
1532   }
1533 
1534 
1535   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1536 
1537   if (file_descriptor < 0) {
1538     // Can't open library, report dlerror() message
1539     return NULL;
1540   }
1541 
1542   bool failed_to_read_elf_head=
1543     (sizeof(elf_head)!=
1544      (::read(file_descriptor, &elf_head,sizeof(elf_head))));
1545 
1546   ::close(file_descriptor);
1547   if (failed_to_read_elf_head) {
1548     // file i/o error - report dlerror() msg
1549     return NULL;
1550   }
1551 
1552   typedef struct {
1553     Elf32_Half    code;         // Actual value as defined in elf.h
1554     Elf32_Half    compat_class; // Compatibility of archs at VM's sense
1555     unsigned char elf_class;    // 32 or 64 bit
1556     unsigned char endianess;    // MSB or LSB
1557     char*         name;         // String representation
1558   } arch_t;
1559 
1560   static const arch_t arch_array[]={
1561     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1562     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1563     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1564     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1565     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1566     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1567     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1568     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1569     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1570     {EM_ARM,         EM_ARM,     ELFCLASS32, ELFDATA2LSB, (char*)"ARM 32"}
1571   };
1572 
1573 #if  (defined IA32)
1574   static  Elf32_Half running_arch_code=EM_386;
1575 #elif   (defined AMD64)
1576   static  Elf32_Half running_arch_code=EM_X86_64;
1577 #elif  (defined IA64)
1578   static  Elf32_Half running_arch_code=EM_IA_64;
1579 #elif  (defined __sparc) && (defined _LP64)
1580   static  Elf32_Half running_arch_code=EM_SPARCV9;
1581 #elif  (defined __sparc) && (!defined _LP64)
1582   static  Elf32_Half running_arch_code=EM_SPARC;
1583 #elif  (defined __powerpc64__)
1584   static  Elf32_Half running_arch_code=EM_PPC64;
1585 #elif  (defined __powerpc__)
1586   static  Elf32_Half running_arch_code=EM_PPC;
1587 #elif (defined ARM)
1588   static  Elf32_Half running_arch_code=EM_ARM;
1589 #else
1590   #error Method os::dll_load requires that one of following is defined:\
1591        IA32, AMD64, IA64, __sparc, __powerpc__, ARM, ARM
1592 #endif
1593 
1594   // Identify compatability class for VM's architecture and library's architecture
1595   // Obtain string descriptions for architectures
1596 
1597   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1598   int running_arch_index=-1;
1599 
1600   for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) {
1601     if (running_arch_code == arch_array[i].code) {
1602       running_arch_index    = i;
1603     }
1604     if (lib_arch.code == arch_array[i].code) {
1605       lib_arch.compat_class = arch_array[i].compat_class;
1606       lib_arch.name         = arch_array[i].name;
1607     }
1608   }
1609 
1610   assert(running_arch_index != -1,
1611          "Didn't find running architecture code (running_arch_code) in arch_array");
1612   if (running_arch_index == -1) {
1613     // Even though running architecture detection failed
1614     // we may still continue with reporting dlerror() message
1615     return NULL;
1616   }
1617 
1618   if (lib_arch.endianess != arch_array[running_arch_index].endianess) {
1619     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");
1620     return NULL;
1621   }
1622 
1623   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1624     ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");
1625     return NULL;
1626   }
1627 
1628   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1629     if (lib_arch.name!=NULL) {
1630       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1631                  " (Possible cause: can't load %s-bit .so on a %s-bit platform)",
1632                  lib_arch.name, arch_array[running_arch_index].name);
1633     } else {
1634       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1635                  " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",
1636                  lib_arch.code,
1637                  arch_array[running_arch_index].name);
1638     }
1639   }
1640 
1641   return NULL;
1642 }
1643 
1644 void* os::dll_lookup(void* handle, const char* name) {
1645   return dlsym(handle, name);
1646 }
1647 
1648 void* os::get_default_process_handle() {
1649   return (void*)::dlopen(NULL, RTLD_LAZY);
1650 }
1651 
1652 static inline time_t get_mtime(const char* filename) {
1653   struct stat st;
1654   int ret = os::stat(filename, &st);
1655   assert(ret == 0, "failed to stat() file '%s': %s", filename, os::strerror(errno));
1656   return st.st_mtime;
1657 }
1658 
1659 int os::compare_file_modified_times(const char* file1, const char* file2) {
1660   time_t t1 = get_mtime(file1);
1661   time_t t2 = get_mtime(file2);
1662   return t1 - t2;
1663 }
1664 
1665 static bool _print_ascii_file(const char* filename, outputStream* st) {
1666   int fd = ::open(filename, O_RDONLY);
1667   if (fd == -1) {
1668     return false;
1669   }
1670 
1671   char buf[32];
1672   int bytes;
1673   while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {
1674     st->print_raw(buf, bytes);
1675   }
1676 
1677   ::close(fd);
1678 
1679   return true;
1680 }
1681 
1682 void os::print_os_info_brief(outputStream* st) {
1683   os::Solaris::print_distro_info(st);
1684 
1685   os::Posix::print_uname_info(st);
1686 
1687   os::Solaris::print_libversion_info(st);
1688 }
1689 
1690 void os::print_os_info(outputStream* st) {
1691   st->print("OS:");
1692 
1693   os::Solaris::print_distro_info(st);
1694 
1695   os::Posix::print_uname_info(st);
1696 
1697   os::Solaris::print_libversion_info(st);
1698 
1699   os::Posix::print_rlimit_info(st);
1700 
1701   os::Posix::print_load_average(st);
1702 }
1703 
1704 void os::Solaris::print_distro_info(outputStream* st) {
1705   if (!_print_ascii_file("/etc/release", st)) {
1706     st->print("Solaris");
1707   }
1708   st->cr();
1709 }
1710 
1711 void os::get_summary_os_info(char* buf, size_t buflen) {
1712   strncpy(buf, "Solaris", buflen);  // default to plain solaris
1713   FILE* fp = fopen("/etc/release", "r");
1714   if (fp != NULL) {
1715     char tmp[256];
1716     // Only get the first line and chop out everything but the os name.
1717     if (fgets(tmp, sizeof(tmp), fp)) {
1718       char* ptr = tmp;
1719       // skip past whitespace characters
1720       while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')) ptr++;
1721       if (*ptr != '\0') {
1722         char* nl = strchr(ptr, '\n');
1723         if (nl != NULL) *nl = '\0';
1724         strncpy(buf, ptr, buflen);
1725       }
1726     }
1727     fclose(fp);
1728   }
1729 }
1730 
1731 void os::Solaris::print_libversion_info(outputStream* st) {
1732   st->print("  (T2 libthread)");
1733   st->cr();
1734 }
1735 
1736 static bool check_addr0(outputStream* st) {
1737   jboolean status = false;
1738   const int read_chunk = 200;
1739   int ret = 0;
1740   int nmap = 0;
1741   int fd = ::open("/proc/self/map",O_RDONLY);
1742   if (fd >= 0) {
1743     prmap_t *p = NULL;
1744     char *mbuff = (char *) calloc(read_chunk, sizeof(prmap_t));
1745     if (NULL == mbuff) {
1746       ::close(fd);
1747       return status;
1748     }
1749     while ((ret = ::read(fd, mbuff, read_chunk*sizeof(prmap_t))) > 0) {
1750       //check if read() has not read partial data
1751       if( 0 != ret % sizeof(prmap_t)){
1752         break;
1753       }
1754       nmap = ret / sizeof(prmap_t);
1755       p = (prmap_t *)mbuff;
1756       for(int i = 0; i < nmap; i++){
1757         if (p->pr_vaddr == 0x0) {
1758           st->print("Warning: Address: " PTR_FORMAT ", Size: " SIZE_FORMAT "K, ",p->pr_vaddr, p->pr_size/1024);
1759           st->print("Mapped file: %s, ", p->pr_mapname[0] == '\0' ? "None" : p->pr_mapname);
1760           st->print("Access: ");
1761           st->print("%s",(p->pr_mflags & MA_READ)  ? "r" : "-");
1762           st->print("%s",(p->pr_mflags & MA_WRITE) ? "w" : "-");
1763           st->print("%s",(p->pr_mflags & MA_EXEC)  ? "x" : "-");
1764           st->cr();
1765           status = true;
1766         }
1767         p++;
1768       }
1769     }
1770     free(mbuff);
1771     ::close(fd);
1772   }
1773   return status;
1774 }
1775 
1776 void os::get_summary_cpu_info(char* buf, size_t buflen) {
1777   // Get MHz with system call. We don't seem to already have this.
1778   processor_info_t stats;
1779   processorid_t id = getcpuid();
1780   int clock = 0;
1781   if (processor_info(id, &stats) != -1) {
1782     clock = stats.pi_clock;  // pi_processor_type isn't more informative than below
1783   }
1784 #ifdef AMD64
1785   snprintf(buf, buflen, "x86 64 bit %d MHz", clock);
1786 #else
1787   // must be sparc
1788   snprintf(buf, buflen, "Sparcv9 64 bit %d MHz", clock);
1789 #endif
1790 }
1791 
1792 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
1793   // Nothing to do for now.
1794 }
1795 
1796 void os::print_memory_info(outputStream* st) {
1797   st->print("Memory:");
1798   st->print(" %dk page", os::vm_page_size()>>10);
1799   st->print(", physical " UINT64_FORMAT "k", os::physical_memory()>>10);
1800   st->print("(" UINT64_FORMAT "k free)", os::available_memory() >> 10);
1801   st->cr();
1802   (void) check_addr0(st);
1803 }
1804 
1805 // Moved from whole group, because we need them here for diagnostic
1806 // prints.
1807 static int Maxsignum = 0;
1808 static int *ourSigFlags = NULL;
1809 
1810 int os::Solaris::get_our_sigflags(int sig) {
1811   assert(ourSigFlags!=NULL, "signal data structure not initialized");
1812   assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range");
1813   return ourSigFlags[sig];
1814 }
1815 
1816 void os::Solaris::set_our_sigflags(int sig, int flags) {
1817   assert(ourSigFlags!=NULL, "signal data structure not initialized");
1818   assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range");
1819   ourSigFlags[sig] = flags;
1820 }
1821 
1822 
1823 static const char* get_signal_handler_name(address handler,
1824                                            char* buf, int buflen) {
1825   int offset;
1826   bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);
1827   if (found) {
1828     // skip directory names
1829     const char *p1, *p2;
1830     p1 = buf;
1831     size_t len = strlen(os::file_separator());
1832     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
1833     jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);
1834   } else {
1835     jio_snprintf(buf, buflen, PTR_FORMAT, handler);
1836   }
1837   return buf;
1838 }
1839 
1840 static void print_signal_handler(outputStream* st, int sig,
1841                                  char* buf, size_t buflen) {
1842   struct sigaction sa;
1843 
1844   sigaction(sig, NULL, &sa);
1845 
1846   st->print("%s: ", os::exception_name(sig, buf, buflen));
1847 
1848   address handler = (sa.sa_flags & SA_SIGINFO)
1849                   ? CAST_FROM_FN_PTR(address, sa.sa_sigaction)
1850                   : CAST_FROM_FN_PTR(address, sa.sa_handler);
1851 
1852   if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {
1853     st->print("SIG_DFL");
1854   } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {
1855     st->print("SIG_IGN");
1856   } else {
1857     st->print("[%s]", get_signal_handler_name(handler, buf, buflen));
1858   }
1859 
1860   st->print(", sa_mask[0]=");
1861   os::Posix::print_signal_set_short(st, &sa.sa_mask);
1862 
1863   address rh = VMError::get_resetted_sighandler(sig);
1864   // May be, handler was resetted by VMError?
1865   if (rh != NULL) {
1866     handler = rh;
1867     sa.sa_flags = VMError::get_resetted_sigflags(sig);
1868   }
1869 
1870   st->print(", sa_flags=");
1871   os::Posix::print_sa_flags(st, sa.sa_flags);
1872 
1873   // Check: is it our handler?
1874   if (handler == CAST_FROM_FN_PTR(address, signalHandler)) {
1875     // It is our signal handler
1876     // check for flags
1877     if (sa.sa_flags != os::Solaris::get_our_sigflags(sig)) {
1878       st->print(
1879                 ", flags was changed from " PTR32_FORMAT ", consider using jsig library",
1880                 os::Solaris::get_our_sigflags(sig));
1881     }
1882   }
1883   st->cr();
1884 }
1885 
1886 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {
1887   st->print_cr("Signal Handlers:");
1888   print_signal_handler(st, SIGSEGV, buf, buflen);
1889   print_signal_handler(st, SIGBUS , buf, buflen);
1890   print_signal_handler(st, SIGFPE , buf, buflen);
1891   print_signal_handler(st, SIGPIPE, buf, buflen);
1892   print_signal_handler(st, SIGXFSZ, buf, buflen);
1893   print_signal_handler(st, SIGILL , buf, buflen);
1894   print_signal_handler(st, ASYNC_SIGNAL, buf, buflen);
1895   print_signal_handler(st, BREAK_SIGNAL, buf, buflen);
1896   print_signal_handler(st, SHUTDOWN1_SIGNAL , buf, buflen);
1897   print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);
1898   print_signal_handler(st, SHUTDOWN3_SIGNAL, buf, buflen);
1899 }
1900 
1901 static char saved_jvm_path[MAXPATHLEN] = { 0 };
1902 
1903 // Find the full path to the current module, libjvm.so
1904 void os::jvm_path(char *buf, jint buflen) {
1905   // Error checking.
1906   if (buflen < MAXPATHLEN) {
1907     assert(false, "must use a large-enough buffer");
1908     buf[0] = '\0';
1909     return;
1910   }
1911   // Lazy resolve the path to current module.
1912   if (saved_jvm_path[0] != 0) {
1913     strcpy(buf, saved_jvm_path);
1914     return;
1915   }
1916 
1917   Dl_info dlinfo;
1918   int ret = dladdr(CAST_FROM_FN_PTR(void *, os::jvm_path), &dlinfo);
1919   assert(ret != 0, "cannot locate libjvm");
1920   if (ret != 0 && dlinfo.dli_fname != NULL) {
1921     if (os::Posix::realpath((char *)dlinfo.dli_fname, buf, buflen) == NULL) {
1922       return;
1923     }
1924   } else {
1925     buf[0] = '\0';
1926     return;
1927   }
1928 
1929   if (Arguments::sun_java_launcher_is_altjvm()) {
1930     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
1931     // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so".
1932     // If "/jre/lib/" appears at the right place in the string, then
1933     // assume we are installed in a JDK and we're done.  Otherwise, check
1934     // for a JAVA_HOME environment variable and fix up the path so it
1935     // looks like libjvm.so is installed there (append a fake suffix
1936     // hotspot/libjvm.so).
1937     const char *p = buf + strlen(buf) - 1;
1938     for (int count = 0; p > buf && count < 5; ++count) {
1939       for (--p; p > buf && *p != '/'; --p)
1940         /* empty */ ;
1941     }
1942 
1943     if (strncmp(p, "/jre/lib/", 9) != 0) {
1944       // Look for JAVA_HOME in the environment.
1945       char* java_home_var = ::getenv("JAVA_HOME");
1946       if (java_home_var != NULL && java_home_var[0] != 0) {
1947         char* jrelib_p;
1948         int   len;
1949 
1950         // Check the current module name "libjvm.so".
1951         p = strrchr(buf, '/');
1952         assert(strstr(p, "/libjvm") == p, "invalid library name");
1953 
1954         if (os::Posix::realpath(java_home_var, buf, buflen) == NULL) {
1955           return;
1956         }
1957         // determine if this is a legacy image or modules image
1958         // modules image doesn't have "jre" subdirectory
1959         len = strlen(buf);
1960         assert(len < buflen, "Ran out of buffer space");
1961         jrelib_p = buf + len;
1962         snprintf(jrelib_p, buflen-len, "/jre/lib");
1963         if (0 != access(buf, F_OK)) {
1964           snprintf(jrelib_p, buflen-len, "/lib");
1965         }
1966 
1967         if (0 == access(buf, F_OK)) {
1968           // Use current module name "libjvm.so"
1969           len = strlen(buf);
1970           snprintf(buf + len, buflen-len, "/hotspot/libjvm.so");
1971         } else {
1972           // Go back to path of .so
1973           if (os::Posix::realpath((char *)dlinfo.dli_fname, buf, buflen) == NULL) {
1974             return;
1975           }
1976         }
1977       }
1978     }
1979   }
1980 
1981   strncpy(saved_jvm_path, buf, MAXPATHLEN);
1982   saved_jvm_path[MAXPATHLEN - 1] = '\0';
1983 }
1984 
1985 
1986 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
1987   // no prefix required, not even "_"
1988 }
1989 
1990 
1991 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
1992   // no suffix required
1993 }
1994 
1995 // sun.misc.Signal
1996 
1997 extern "C" {
1998   static void UserHandler(int sig, void *siginfo, void *context) {
1999     // Ctrl-C is pressed during error reporting, likely because the error
2000     // handler fails to abort. Let VM die immediately.
2001     if (sig == SIGINT && VMError::is_error_reported()) {
2002       os::die();
2003     }
2004 
2005     os::signal_notify(sig);
2006     // We do not need to reinstate the signal handler each time...
2007   }
2008 }
2009 
2010 void* os::user_handler() {
2011   return CAST_FROM_FN_PTR(void*, UserHandler);
2012 }
2013 
2014 static struct timespec create_semaphore_timespec(unsigned int sec, int nsec) {
2015   struct timespec ts;
2016   unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);
2017 
2018   return ts;
2019 }
2020 
2021 extern "C" {
2022   typedef void (*sa_handler_t)(int);
2023   typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);
2024 }
2025 
2026 void* os::signal(int signal_number, void* handler) {
2027   struct sigaction sigAct, oldSigAct;
2028   sigfillset(&(sigAct.sa_mask));
2029   sigAct.sa_flags = SA_RESTART & ~SA_RESETHAND;
2030   sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);
2031 
2032   if (sigaction(signal_number, &sigAct, &oldSigAct)) {
2033     // -1 means registration failed
2034     return (void *)-1;
2035   }
2036 
2037   return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);
2038 }
2039 
2040 void os::signal_raise(int signal_number) {
2041   raise(signal_number);
2042 }
2043 
2044 // The following code is moved from os.cpp for making this
2045 // code platform specific, which it is by its very nature.
2046 
2047 // a counter for each possible signal value
2048 static int Sigexit = 0;
2049 static jint *pending_signals = NULL;
2050 static int *preinstalled_sigs = NULL;
2051 static struct sigaction *chainedsigactions = NULL;
2052 static Semaphore* sig_sem = NULL;
2053 
2054 int os::sigexitnum_pd() {
2055   assert(Sigexit > 0, "signal memory not yet initialized");
2056   return Sigexit;
2057 }
2058 
2059 void os::Solaris::init_signal_mem() {
2060   // Initialize signal structures
2061   Maxsignum = SIGRTMAX;
2062   Sigexit = Maxsignum+1;
2063   assert(Maxsignum >0, "Unable to obtain max signal number");
2064 
2065   // Initialize signal structures
2066   // pending_signals has one int per signal
2067   // The additional signal is for SIGEXIT - exit signal to signal_thread
2068   pending_signals = (jint *)os::malloc(sizeof(jint) * (Sigexit+1), mtInternal);
2069   memset(pending_signals, 0, (sizeof(jint) * (Sigexit+1)));
2070 
2071   if (UseSignalChaining) {
2072     chainedsigactions = (struct sigaction *)malloc(sizeof(struct sigaction)
2073                                                    * (Maxsignum + 1), mtInternal);
2074     memset(chainedsigactions, 0, (sizeof(struct sigaction) * (Maxsignum + 1)));
2075     preinstalled_sigs = (int *)os::malloc(sizeof(int) * (Maxsignum + 1), mtInternal);
2076     memset(preinstalled_sigs, 0, (sizeof(int) * (Maxsignum + 1)));
2077   }
2078   ourSigFlags = (int*)malloc(sizeof(int) * (Maxsignum + 1), mtInternal);
2079   memset(ourSigFlags, 0, sizeof(int) * (Maxsignum + 1));
2080 }
2081 
2082 static void jdk_misc_signal_init() {
2083   // Initialize signal semaphore
2084   sig_sem = new Semaphore();
2085 }
2086 
2087 void os::signal_notify(int sig) {
2088   if (sig_sem != NULL) {
2089     Atomic::inc(&pending_signals[sig]);
2090     sig_sem->signal();
2091   } else {
2092     // Signal thread is not created with ReduceSignalUsage and jdk_misc_signal_init
2093     // initialization isn't called.
2094     assert(ReduceSignalUsage, "signal semaphore should be created");
2095   }
2096 }
2097 
2098 static int check_pending_signals() {
2099   int ret;
2100   while (true) {
2101     for (int i = 0; i < Sigexit + 1; i++) {
2102       jint n = pending_signals[i];
2103       if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {
2104         return i;
2105       }
2106     }
2107     JavaThread *thread = JavaThread::current();
2108     ThreadBlockInVM tbivm(thread);
2109 
2110     bool threadIsSuspended;
2111     do {
2112       thread->set_suspend_equivalent();
2113       sig_sem->wait();
2114 
2115       // were we externally suspended while we were waiting?
2116       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
2117       if (threadIsSuspended) {
2118         // The semaphore has been incremented, but while we were waiting
2119         // another thread suspended us. We don't want to continue running
2120         // while suspended because that would surprise the thread that
2121         // suspended us.
2122         sig_sem->signal();
2123 
2124         thread->java_suspend_self();
2125       }
2126     } while (threadIsSuspended);
2127   }
2128 }
2129 
2130 int os::signal_wait() {
2131   return check_pending_signals();
2132 }
2133 
2134 ////////////////////////////////////////////////////////////////////////////////
2135 // Virtual Memory
2136 
2137 static int page_size = -1;
2138 
2139 int os::vm_page_size() {
2140   assert(page_size != -1, "must call os::init");
2141   return page_size;
2142 }
2143 
2144 // Solaris allocates memory by pages.
2145 int os::vm_allocation_granularity() {
2146   assert(page_size != -1, "must call os::init");
2147   return page_size;
2148 }
2149 
2150 static bool recoverable_mmap_error(int err) {
2151   // See if the error is one we can let the caller handle. This
2152   // list of errno values comes from the Solaris mmap(2) man page.
2153   switch (err) {
2154   case EBADF:
2155   case EINVAL:
2156   case ENOTSUP:
2157     // let the caller deal with these errors
2158     return true;
2159 
2160   default:
2161     // Any remaining errors on this OS can cause our reserved mapping
2162     // to be lost. That can cause confusion where different data
2163     // structures think they have the same memory mapped. The worst
2164     // scenario is if both the VM and a library think they have the
2165     // same memory mapped.
2166     return false;
2167   }
2168 }
2169 
2170 static void warn_fail_commit_memory(char* addr, size_t bytes, bool exec,
2171                                     int err) {
2172   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2173           ", %d) failed; error='%s' (errno=%d)", addr, bytes, exec,
2174           os::strerror(err), err);
2175 }
2176 
2177 static void warn_fail_commit_memory(char* addr, size_t bytes,
2178                                     size_t alignment_hint, bool exec,
2179                                     int err) {
2180   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2181           ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, bytes,
2182           alignment_hint, exec, os::strerror(err), err);
2183 }
2184 
2185 int os::Solaris::commit_memory_impl(char* addr, size_t bytes, bool exec) {
2186   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2187   size_t size = bytes;
2188   char *res = Solaris::mmap_chunk(addr, size, MAP_PRIVATE|MAP_FIXED, prot);
2189   if (res != NULL) {
2190     if (UseNUMAInterleaving) {
2191       numa_make_global(addr, bytes);
2192     }
2193     return 0;
2194   }
2195 
2196   int err = errno;  // save errno from mmap() call in mmap_chunk()
2197 
2198   if (!recoverable_mmap_error(err)) {
2199     warn_fail_commit_memory(addr, bytes, exec, err);
2200     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "committing reserved memory.");
2201   }
2202 
2203   return err;
2204 }
2205 
2206 bool os::pd_commit_memory(char* addr, size_t bytes, bool exec) {
2207   return Solaris::commit_memory_impl(addr, bytes, exec) == 0;
2208 }
2209 
2210 void os::pd_commit_memory_or_exit(char* addr, size_t bytes, bool exec,
2211                                   const char* mesg) {
2212   assert(mesg != NULL, "mesg must be specified");
2213   int err = os::Solaris::commit_memory_impl(addr, bytes, exec);
2214   if (err != 0) {
2215     // the caller wants all commit errors to exit with the specified mesg:
2216     warn_fail_commit_memory(addr, bytes, exec, err);
2217     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "%s", mesg);
2218   }
2219 }
2220 
2221 size_t os::Solaris::page_size_for_alignment(size_t alignment) {
2222   assert(is_aligned(alignment, (size_t) vm_page_size()),
2223          SIZE_FORMAT " is not aligned to " SIZE_FORMAT,
2224          alignment, (size_t) vm_page_size());
2225 
2226   for (int i = 0; _page_sizes[i] != 0; i++) {
2227     if (is_aligned(alignment, _page_sizes[i])) {
2228       return _page_sizes[i];
2229     }
2230   }
2231 
2232   return (size_t) vm_page_size();
2233 }
2234 
2235 int os::Solaris::commit_memory_impl(char* addr, size_t bytes,
2236                                     size_t alignment_hint, bool exec) {
2237   int err = Solaris::commit_memory_impl(addr, bytes, exec);
2238   if (err == 0 && UseLargePages && alignment_hint > 0) {
2239     assert(is_aligned(bytes, alignment_hint),
2240            SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, alignment_hint);
2241 
2242     // The syscall memcntl requires an exact page size (see man memcntl for details).
2243     size_t page_size = page_size_for_alignment(alignment_hint);
2244     if (page_size > (size_t) vm_page_size()) {
2245       (void)Solaris::setup_large_pages(addr, bytes, page_size);
2246     }
2247   }
2248   return err;
2249 }
2250 
2251 bool os::pd_commit_memory(char* addr, size_t bytes, size_t alignment_hint,
2252                           bool exec) {
2253   return Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec) == 0;
2254 }
2255 
2256 void os::pd_commit_memory_or_exit(char* addr, size_t bytes,
2257                                   size_t alignment_hint, bool exec,
2258                                   const char* mesg) {
2259   assert(mesg != NULL, "mesg must be specified");
2260   int err = os::Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec);
2261   if (err != 0) {
2262     // the caller wants all commit errors to exit with the specified mesg:
2263     warn_fail_commit_memory(addr, bytes, alignment_hint, exec, err);
2264     vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "%s", mesg);
2265   }
2266 }
2267 
2268 // Uncommit the pages in a specified region.
2269 void os::pd_free_memory(char* addr, size_t bytes, size_t alignment_hint) {
2270   if (madvise(addr, bytes, MADV_FREE) < 0) {
2271     debug_only(warning("MADV_FREE failed."));
2272     return;
2273   }
2274 }
2275 
2276 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
2277   return os::commit_memory(addr, size, !ExecMem);
2278 }
2279 
2280 bool os::remove_stack_guard_pages(char* addr, size_t size) {
2281   return os::uncommit_memory(addr, size);
2282 }
2283 
2284 // Change the page size in a given range.
2285 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2286   assert((intptr_t)addr % alignment_hint == 0, "Address should be aligned.");
2287   assert((intptr_t)(addr + bytes) % alignment_hint == 0, "End should be aligned.");
2288   if (UseLargePages) {
2289     size_t page_size = Solaris::page_size_for_alignment(alignment_hint);
2290     if (page_size > (size_t) vm_page_size()) {
2291       Solaris::setup_large_pages(addr, bytes, page_size);
2292     }
2293   }
2294 }
2295 
2296 // Tell the OS to make the range local to the first-touching LWP
2297 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2298   assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned.");
2299   if (madvise(addr, bytes, MADV_ACCESS_LWP) < 0) {
2300     debug_only(warning("MADV_ACCESS_LWP failed."));
2301   }
2302 }
2303 
2304 // Tell the OS that this range would be accessed from different LWPs.
2305 void os::numa_make_global(char *addr, size_t bytes) {
2306   assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned.");
2307   if (madvise(addr, bytes, MADV_ACCESS_MANY) < 0) {
2308     debug_only(warning("MADV_ACCESS_MANY failed."));
2309   }
2310 }
2311 
2312 // Get the number of the locality groups.
2313 size_t os::numa_get_groups_num() {
2314   size_t n = Solaris::lgrp_nlgrps(Solaris::lgrp_cookie());
2315   return n != -1 ? n : 1;
2316 }
2317 
2318 // Get a list of leaf locality groups. A leaf lgroup is group that
2319 // doesn't have any children. Typical leaf group is a CPU or a CPU/memory
2320 // board. An LWP is assigned to one of these groups upon creation.
2321 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2322   if ((ids[0] = Solaris::lgrp_root(Solaris::lgrp_cookie())) == -1) {
2323     ids[0] = 0;
2324     return 1;
2325   }
2326   int result_size = 0, top = 1, bottom = 0, cur = 0;
2327   for (int k = 0; k < size; k++) {
2328     int r = Solaris::lgrp_children(Solaris::lgrp_cookie(), ids[cur],
2329                                    (Solaris::lgrp_id_t*)&ids[top], size - top);
2330     if (r == -1) {
2331       ids[0] = 0;
2332       return 1;
2333     }
2334     if (!r) {
2335       // That's a leaf node.
2336       assert(bottom <= cur, "Sanity check");
2337       // Check if the node has memory
2338       if (Solaris::lgrp_resources(Solaris::lgrp_cookie(), ids[cur],
2339                                   NULL, 0, LGRP_RSRC_MEM) > 0) {
2340         ids[bottom++] = ids[cur];
2341       }
2342     }
2343     top += r;
2344     cur++;
2345   }
2346   if (bottom == 0) {
2347     // Handle a situation, when the OS reports no memory available.
2348     // Assume UMA architecture.
2349     ids[0] = 0;
2350     return 1;
2351   }
2352   return bottom;
2353 }
2354 
2355 // Detect the topology change. Typically happens during CPU plugging-unplugging.
2356 bool os::numa_topology_changed() {
2357   int is_stale = Solaris::lgrp_cookie_stale(Solaris::lgrp_cookie());
2358   if (is_stale != -1 && is_stale) {
2359     Solaris::lgrp_fini(Solaris::lgrp_cookie());
2360     Solaris::lgrp_cookie_t c = Solaris::lgrp_init(Solaris::LGRP_VIEW_CALLER);
2361     assert(c != 0, "Failure to initialize LGRP API");
2362     Solaris::set_lgrp_cookie(c);
2363     return true;
2364   }
2365   return false;
2366 }
2367 
2368 // Get the group id of the current LWP.
2369 int os::numa_get_group_id() {
2370   int lgrp_id = Solaris::lgrp_home(P_LWPID, P_MYID);
2371   if (lgrp_id == -1) {
2372     return 0;
2373   }
2374   const int size = os::numa_get_groups_num();
2375   int *ids = (int*)alloca(size * sizeof(int));
2376 
2377   // Get the ids of all lgroups with memory; r is the count.
2378   int r = Solaris::lgrp_resources(Solaris::lgrp_cookie(), lgrp_id,
2379                                   (Solaris::lgrp_id_t*)ids, size, LGRP_RSRC_MEM);
2380   if (r <= 0) {
2381     return 0;
2382   }
2383   return ids[os::random() % r];
2384 }
2385 
2386 // Request information about the page.
2387 bool os::get_page_info(char *start, page_info* info) {
2388   const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE };
2389   uint64_t addr = (uintptr_t)start;
2390   uint64_t outdata[2];
2391   uint_t validity = 0;
2392 
2393   if (meminfo(&addr, 1, info_types, 2, outdata, &validity) < 0) {
2394     return false;
2395   }
2396 
2397   info->size = 0;
2398   info->lgrp_id = -1;
2399 
2400   if ((validity & 1) != 0) {
2401     if ((validity & 2) != 0) {
2402       info->lgrp_id = outdata[0];
2403     }
2404     if ((validity & 4) != 0) {
2405       info->size = outdata[1];
2406     }
2407     return true;
2408   }
2409   return false;
2410 }
2411 
2412 // Scan the pages from start to end until a page different than
2413 // the one described in the info parameter is encountered.
2414 char *os::scan_pages(char *start, char* end, page_info* page_expected,
2415                      page_info* page_found) {
2416   const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE };
2417   const size_t types = sizeof(info_types) / sizeof(info_types[0]);
2418   uint64_t addrs[MAX_MEMINFO_CNT], outdata[types * MAX_MEMINFO_CNT + 1];
2419   uint_t validity[MAX_MEMINFO_CNT];
2420 
2421   size_t page_size = MAX2((size_t)os::vm_page_size(), page_expected->size);
2422   uint64_t p = (uint64_t)start;
2423   while (p < (uint64_t)end) {
2424     addrs[0] = p;
2425     size_t addrs_count = 1;
2426     while (addrs_count < MAX_MEMINFO_CNT && addrs[addrs_count - 1] + page_size < (uint64_t)end) {
2427       addrs[addrs_count] = addrs[addrs_count - 1] + page_size;
2428       addrs_count++;
2429     }
2430 
2431     if (meminfo(addrs, addrs_count, info_types, types, outdata, validity) < 0) {
2432       return NULL;
2433     }
2434 
2435     size_t i = 0;
2436     for (; i < addrs_count; i++) {
2437       if ((validity[i] & 1) != 0) {
2438         if ((validity[i] & 4) != 0) {
2439           if (outdata[types * i + 1] != page_expected->size) {
2440             break;
2441           }
2442         } else if (page_expected->size != 0) {
2443           break;
2444         }
2445 
2446         if ((validity[i] & 2) != 0 && page_expected->lgrp_id > 0) {
2447           if (outdata[types * i] != page_expected->lgrp_id) {
2448             break;
2449           }
2450         }
2451       } else {
2452         return NULL;
2453       }
2454     }
2455 
2456     if (i < addrs_count) {
2457       if ((validity[i] & 2) != 0) {
2458         page_found->lgrp_id = outdata[types * i];
2459       } else {
2460         page_found->lgrp_id = -1;
2461       }
2462       if ((validity[i] & 4) != 0) {
2463         page_found->size = outdata[types * i + 1];
2464       } else {
2465         page_found->size = 0;
2466       }
2467       return (char*)addrs[i];
2468     }
2469 
2470     p = addrs[addrs_count - 1] + page_size;
2471   }
2472   return end;
2473 }
2474 
2475 bool os::pd_uncommit_memory(char* addr, size_t bytes) {
2476   size_t size = bytes;
2477   // Map uncommitted pages PROT_NONE so we fail early if we touch an
2478   // uncommitted page. Otherwise, the read/write might succeed if we
2479   // have enough swap space to back the physical page.
2480   return
2481     NULL != Solaris::mmap_chunk(addr, size,
2482                                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE,
2483                                 PROT_NONE);
2484 }
2485 
2486 char* os::Solaris::mmap_chunk(char *addr, size_t size, int flags, int prot) {
2487   char *b = (char *)mmap(addr, size, prot, flags, os::Solaris::_dev_zero_fd, 0);
2488 
2489   if (b == MAP_FAILED) {
2490     return NULL;
2491   }
2492   return b;
2493 }
2494 
2495 char* os::Solaris::anon_mmap(char* requested_addr, size_t bytes,
2496                              size_t alignment_hint, bool fixed) {
2497   char* addr = requested_addr;
2498   int flags = MAP_PRIVATE | MAP_NORESERVE;
2499 
2500   assert(!(fixed && (alignment_hint > 0)),
2501          "alignment hint meaningless with fixed mmap");
2502 
2503   if (fixed) {
2504     flags |= MAP_FIXED;
2505   } else if (alignment_hint > (size_t) vm_page_size()) {
2506     flags |= MAP_ALIGN;
2507     addr = (char*) alignment_hint;
2508   }
2509 
2510   // Map uncommitted pages PROT_NONE so we fail early if we touch an
2511   // uncommitted page. Otherwise, the read/write might succeed if we
2512   // have enough swap space to back the physical page.
2513   return mmap_chunk(addr, bytes, flags, PROT_NONE);
2514 }
2515 
2516 char* os::pd_reserve_memory(size_t bytes, char* requested_addr,
2517                             size_t alignment_hint) {
2518   char* addr = Solaris::anon_mmap(requested_addr, bytes, alignment_hint,
2519                                   (requested_addr != NULL));
2520 
2521   guarantee(requested_addr == NULL || requested_addr == addr,
2522             "OS failed to return requested mmap address.");
2523   return addr;
2524 }
2525 
2526 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr, int file_desc) {
2527   assert(file_desc >= 0, "file_desc is not valid");
2528   char* result = pd_attempt_reserve_memory_at(bytes, requested_addr);
2529   if (result != NULL) {
2530     if (replace_existing_mapping_with_file_mapping(result, bytes, file_desc) == NULL) {
2531       vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory"));
2532     }
2533   }
2534   return result;
2535 }
2536 
2537 // Reserve memory at an arbitrary address, only if that area is
2538 // available (and not reserved for something else).
2539 
2540 char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {
2541   const int max_tries = 10;
2542   char* base[max_tries];
2543   size_t size[max_tries];
2544 
2545   // Solaris adds a gap between mmap'ed regions.  The size of the gap
2546   // is dependent on the requested size and the MMU.  Our initial gap
2547   // value here is just a guess and will be corrected later.
2548   bool had_top_overlap = false;
2549   bool have_adjusted_gap = false;
2550   size_t gap = 0x400000;
2551 
2552   // Assert only that the size is a multiple of the page size, since
2553   // that's all that mmap requires, and since that's all we really know
2554   // about at this low abstraction level.  If we need higher alignment,
2555   // we can either pass an alignment to this method or verify alignment
2556   // in one of the methods further up the call chain.  See bug 5044738.
2557   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
2558 
2559   // Since snv_84, Solaris attempts to honor the address hint - see 5003415.
2560   // Give it a try, if the kernel honors the hint we can return immediately.
2561   char* addr = Solaris::anon_mmap(requested_addr, bytes, 0, false);
2562 
2563   volatile int err = errno;
2564   if (addr == requested_addr) {
2565     return addr;
2566   } else if (addr != NULL) {
2567     pd_unmap_memory(addr, bytes);
2568   }
2569 
2570   if (log_is_enabled(Warning, os)) {
2571     char buf[256];
2572     buf[0] = '\0';
2573     if (addr == NULL) {
2574       jio_snprintf(buf, sizeof(buf), ": %s", os::strerror(err));
2575     }
2576     log_info(os)("attempt_reserve_memory_at: couldn't reserve " SIZE_FORMAT " bytes at "
2577             PTR_FORMAT ": reserve_memory_helper returned " PTR_FORMAT
2578             "%s", bytes, requested_addr, addr, buf);
2579   }
2580 
2581   // Address hint method didn't work.  Fall back to the old method.
2582   // In theory, once SNV becomes our oldest supported platform, this
2583   // code will no longer be needed.
2584   //
2585   // Repeatedly allocate blocks until the block is allocated at the
2586   // right spot. Give up after max_tries.
2587   int i;
2588   for (i = 0; i < max_tries; ++i) {
2589     base[i] = reserve_memory(bytes);
2590 
2591     if (base[i] != NULL) {
2592       // Is this the block we wanted?
2593       if (base[i] == requested_addr) {
2594         size[i] = bytes;
2595         break;
2596       }
2597 
2598       // check that the gap value is right
2599       if (had_top_overlap && !have_adjusted_gap) {
2600         size_t actual_gap = base[i-1] - base[i] - bytes;
2601         if (gap != actual_gap) {
2602           // adjust the gap value and retry the last 2 allocations
2603           assert(i > 0, "gap adjustment code problem");
2604           have_adjusted_gap = true;  // adjust the gap only once, just in case
2605           gap = actual_gap;
2606           log_info(os)("attempt_reserve_memory_at: adjusted gap to 0x%lx", gap);
2607           unmap_memory(base[i], bytes);
2608           unmap_memory(base[i-1], size[i-1]);
2609           i-=2;
2610           continue;
2611         }
2612       }
2613 
2614       // Does this overlap the block we wanted? Give back the overlapped
2615       // parts and try again.
2616       //
2617       // There is still a bug in this code: if top_overlap == bytes,
2618       // the overlap is offset from requested region by the value of gap.
2619       // In this case giving back the overlapped part will not work,
2620       // because we'll give back the entire block at base[i] and
2621       // therefore the subsequent allocation will not generate a new gap.
2622       // This could be fixed with a new algorithm that used larger
2623       // or variable size chunks to find the requested region -
2624       // but such a change would introduce additional complications.
2625       // It's rare enough that the planets align for this bug,
2626       // so we'll just wait for a fix for 6204603/5003415 which
2627       // will provide a mmap flag to allow us to avoid this business.
2628 
2629       size_t top_overlap = requested_addr + (bytes + gap) - base[i];
2630       if (top_overlap >= 0 && top_overlap < bytes) {
2631         had_top_overlap = true;
2632         unmap_memory(base[i], top_overlap);
2633         base[i] += top_overlap;
2634         size[i] = bytes - top_overlap;
2635       } else {
2636         size_t bottom_overlap = base[i] + bytes - requested_addr;
2637         if (bottom_overlap >= 0 && bottom_overlap < bytes) {
2638           if (bottom_overlap == 0) {
2639             log_info(os)("attempt_reserve_memory_at: possible alignment bug");
2640           }
2641           unmap_memory(requested_addr, bottom_overlap);
2642           size[i] = bytes - bottom_overlap;
2643         } else {
2644           size[i] = bytes;
2645         }
2646       }
2647     }
2648   }
2649 
2650   // Give back the unused reserved pieces.
2651 
2652   for (int j = 0; j < i; ++j) {
2653     if (base[j] != NULL) {
2654       unmap_memory(base[j], size[j]);
2655     }
2656   }
2657 
2658   return (i < max_tries) ? requested_addr : NULL;
2659 }
2660 
2661 bool os::pd_release_memory(char* addr, size_t bytes) {
2662   size_t size = bytes;
2663   return munmap(addr, size) == 0;
2664 }
2665 
2666 static bool solaris_mprotect(char* addr, size_t bytes, int prot) {
2667   assert(addr == (char*)align_down((uintptr_t)addr, os::vm_page_size()),
2668          "addr must be page aligned");
2669   int retVal = mprotect(addr, bytes, prot);
2670   return retVal == 0;
2671 }
2672 
2673 // Protect memory (Used to pass readonly pages through
2674 // JNI GetArray<type>Elements with empty arrays.)
2675 // Also, used for serialization page and for compressed oops null pointer
2676 // checking.
2677 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
2678                         bool is_committed) {
2679   unsigned int p = 0;
2680   switch (prot) {
2681   case MEM_PROT_NONE: p = PROT_NONE; break;
2682   case MEM_PROT_READ: p = PROT_READ; break;
2683   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
2684   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
2685   default:
2686     ShouldNotReachHere();
2687   }
2688   // is_committed is unused.
2689   return solaris_mprotect(addr, bytes, p);
2690 }
2691 
2692 // guard_memory and unguard_memory only happens within stack guard pages.
2693 // Since ISM pertains only to the heap, guard and unguard memory should not
2694 /// happen with an ISM region.
2695 bool os::guard_memory(char* addr, size_t bytes) {
2696   return solaris_mprotect(addr, bytes, PROT_NONE);
2697 }
2698 
2699 bool os::unguard_memory(char* addr, size_t bytes) {
2700   return solaris_mprotect(addr, bytes, PROT_READ|PROT_WRITE);
2701 }
2702 
2703 // Large page support
2704 static size_t _large_page_size = 0;
2705 
2706 // Insertion sort for small arrays (descending order).
2707 static void insertion_sort_descending(size_t* array, int len) {
2708   for (int i = 0; i < len; i++) {
2709     size_t val = array[i];
2710     for (size_t key = i; key > 0 && array[key - 1] < val; --key) {
2711       size_t tmp = array[key];
2712       array[key] = array[key - 1];
2713       array[key - 1] = tmp;
2714     }
2715   }
2716 }
2717 
2718 bool os::Solaris::mpss_sanity_check(bool warn, size_t* page_size) {
2719   const unsigned int usable_count = VM_Version::page_size_count();
2720   if (usable_count == 1) {
2721     return false;
2722   }
2723 
2724   // Find the right getpagesizes interface.  When solaris 11 is the minimum
2725   // build platform, getpagesizes() (without the '2') can be called directly.
2726   typedef int (*gps_t)(size_t[], int);
2727   gps_t gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes2"));
2728   if (gps_func == NULL) {
2729     gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes"));
2730     if (gps_func == NULL) {
2731       if (warn) {
2732         warning("MPSS is not supported by the operating system.");
2733       }
2734       return false;
2735     }
2736   }
2737 
2738   // Fill the array of page sizes.
2739   int n = (*gps_func)(_page_sizes, page_sizes_max);
2740   assert(n > 0, "Solaris bug?");
2741 
2742   if (n == page_sizes_max) {
2743     // Add a sentinel value (necessary only if the array was completely filled
2744     // since it is static (zeroed at initialization)).
2745     _page_sizes[--n] = 0;
2746     DEBUG_ONLY(warning("increase the size of the os::_page_sizes array.");)
2747   }
2748   assert(_page_sizes[n] == 0, "missing sentinel");
2749   trace_page_sizes("available page sizes", _page_sizes, n);
2750 
2751   if (n == 1) return false;     // Only one page size available.
2752 
2753   // Skip sizes larger than 4M (or LargePageSizeInBytes if it was set) and
2754   // select up to usable_count elements.  First sort the array, find the first
2755   // acceptable value, then copy the usable sizes to the top of the array and
2756   // trim the rest.  Make sure to include the default page size :-).
2757   //
2758   // A better policy could get rid of the 4M limit by taking the sizes of the
2759   // important VM memory regions (java heap and possibly the code cache) into
2760   // account.
2761   insertion_sort_descending(_page_sizes, n);
2762   const size_t size_limit =
2763     FLAG_IS_DEFAULT(LargePageSizeInBytes) ? 4 * M : LargePageSizeInBytes;
2764   int beg;
2765   for (beg = 0; beg < n && _page_sizes[beg] > size_limit; ++beg) /* empty */;
2766   const int end = MIN2((int)usable_count, n) - 1;
2767   for (int cur = 0; cur < end; ++cur, ++beg) {
2768     _page_sizes[cur] = _page_sizes[beg];
2769   }
2770   _page_sizes[end] = vm_page_size();
2771   _page_sizes[end + 1] = 0;
2772 
2773   if (_page_sizes[end] > _page_sizes[end - 1]) {
2774     // Default page size is not the smallest; sort again.
2775     insertion_sort_descending(_page_sizes, end + 1);
2776   }
2777   *page_size = _page_sizes[0];
2778 
2779   trace_page_sizes("usable page sizes", _page_sizes, end + 1);
2780   return true;
2781 }
2782 
2783 void os::large_page_init() {
2784   if (UseLargePages) {
2785     // print a warning if any large page related flag is specified on command line
2786     bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages)        ||
2787                            !FLAG_IS_DEFAULT(LargePageSizeInBytes);
2788 
2789     UseLargePages = Solaris::mpss_sanity_check(warn_on_failure, &_large_page_size);
2790   }
2791 }
2792 
2793 bool os::Solaris::is_valid_page_size(size_t bytes) {
2794   for (int i = 0; _page_sizes[i] != 0; i++) {
2795     if (_page_sizes[i] == bytes) {
2796       return true;
2797     }
2798   }
2799   return false;
2800 }
2801 
2802 bool os::Solaris::setup_large_pages(caddr_t start, size_t bytes, size_t align) {
2803   assert(is_valid_page_size(align), SIZE_FORMAT " is not a valid page size", align);
2804   assert(is_aligned((void*) start, align),
2805          PTR_FORMAT " is not aligned to " SIZE_FORMAT, p2i((void*) start), align);
2806   assert(is_aligned(bytes, align),
2807          SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, align);
2808 
2809   // Signal to OS that we want large pages for addresses
2810   // from addr, addr + bytes
2811   struct memcntl_mha mpss_struct;
2812   mpss_struct.mha_cmd = MHA_MAPSIZE_VA;
2813   mpss_struct.mha_pagesize = align;
2814   mpss_struct.mha_flags = 0;
2815   // Upon successful completion, memcntl() returns 0
2816   if (memcntl(start, bytes, MC_HAT_ADVISE, (caddr_t) &mpss_struct, 0, 0)) {
2817     debug_only(warning("Attempt to use MPSS failed."));
2818     return false;
2819   }
2820   return true;
2821 }
2822 
2823 char* os::reserve_memory_special(size_t size, size_t alignment, char* addr, bool exec) {
2824   fatal("os::reserve_memory_special should not be called on Solaris.");
2825   return NULL;
2826 }
2827 
2828 bool os::release_memory_special(char* base, size_t bytes) {
2829   fatal("os::release_memory_special should not be called on Solaris.");
2830   return false;
2831 }
2832 
2833 size_t os::large_page_size() {
2834   return _large_page_size;
2835 }
2836 
2837 // MPSS allows application to commit large page memory on demand; with ISM
2838 // the entire memory region must be allocated as shared memory.
2839 bool os::can_commit_large_page_memory() {
2840   return true;
2841 }
2842 
2843 bool os::can_execute_large_page_memory() {
2844   return true;
2845 }
2846 
2847 // Read calls from inside the vm need to perform state transitions
2848 size_t os::read(int fd, void *buf, unsigned int nBytes) {
2849   size_t res;
2850   JavaThread* thread = (JavaThread*)Thread::current();
2851   assert(thread->thread_state() == _thread_in_vm, "Assumed _thread_in_vm");
2852   ThreadBlockInVM tbiv(thread);
2853   RESTARTABLE(::read(fd, buf, (size_t) nBytes), res);
2854   return res;
2855 }
2856 
2857 size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) {
2858   size_t res;
2859   JavaThread* thread = (JavaThread*)Thread::current();
2860   assert(thread->thread_state() == _thread_in_vm, "Assumed _thread_in_vm");
2861   ThreadBlockInVM tbiv(thread);
2862   RESTARTABLE(::pread(fd, buf, (size_t) nBytes, offset), res);
2863   return res;
2864 }
2865 
2866 size_t os::restartable_read(int fd, void *buf, unsigned int nBytes) {
2867   size_t res;
2868   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
2869          "Assumed _thread_in_native");
2870   RESTARTABLE(::read(fd, buf, (size_t) nBytes), res);
2871   return res;
2872 }
2873 
2874 void os::naked_short_sleep(jlong ms) {
2875   assert(ms < 1000, "Un-interruptable sleep, short time use only");
2876 
2877   // usleep is deprecated and removed from POSIX, in favour of nanosleep, but
2878   // Solaris requires -lrt for this.
2879   usleep((ms * 1000));
2880 
2881   return;
2882 }
2883 
2884 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
2885 void os::infinite_sleep() {
2886   while (true) {    // sleep forever ...
2887     ::sleep(100);   // ... 100 seconds at a time
2888   }
2889 }
2890 
2891 // Used to convert frequent JVM_Yield() to nops
2892 bool os::dont_yield() {
2893   if (DontYieldALot) {
2894     static hrtime_t last_time = 0;
2895     hrtime_t diff = getTimeNanos() - last_time;
2896 
2897     if (diff < DontYieldALotInterval * 1000000) {
2898       return true;
2899     }
2900 
2901     last_time += diff;
2902 
2903     return false;
2904   } else {
2905     return false;
2906   }
2907 }
2908 
2909 // Note that yield semantics are defined by the scheduling class to which
2910 // the thread currently belongs.  Typically, yield will _not yield to
2911 // other equal or higher priority threads that reside on the dispatch queues
2912 // of other CPUs.
2913 
2914 void os::naked_yield() {
2915   thr_yield();
2916 }
2917 
2918 // Interface for setting lwp priorities.  We are using T2 libthread,
2919 // which forces the use of bound threads, so all of our threads will
2920 // be assigned to real lwp's.  Using the thr_setprio function is
2921 // meaningless in this mode so we must adjust the real lwp's priority.
2922 // The routines below implement the getting and setting of lwp priorities.
2923 //
2924 // Note: There are three priority scales used on Solaris.  Java priotities
2925 //       which range from 1 to 10, libthread "thr_setprio" scale which range
2926 //       from 0 to 127, and the current scheduling class of the process we
2927 //       are running in.  This is typically from -60 to +60.
2928 //       The setting of the lwp priorities in done after a call to thr_setprio
2929 //       so Java priorities are mapped to libthread priorities and we map from
2930 //       the latter to lwp priorities.  We don't keep priorities stored in
2931 //       Java priorities since some of our worker threads want to set priorities
2932 //       higher than all Java threads.
2933 //
2934 // For related information:
2935 // (1)  man -s 2 priocntl
2936 // (2)  man -s 4 priocntl
2937 // (3)  man dispadmin
2938 // =    librt.so
2939 // =    libthread/common/rtsched.c - thrp_setlwpprio().
2940 // =    ps -cL <pid> ... to validate priority.
2941 // =    sched_get_priority_min and _max
2942 //              pthread_create
2943 //              sched_setparam
2944 //              pthread_setschedparam
2945 //
2946 // Assumptions:
2947 // +    We assume that all threads in the process belong to the same
2948 //              scheduling class.   IE. an homogenous process.
2949 // +    Must be root or in IA group to change change "interactive" attribute.
2950 //              Priocntl() will fail silently.  The only indication of failure is when
2951 //              we read-back the value and notice that it hasn't changed.
2952 // +    Interactive threads enter the runq at the head, non-interactive at the tail.
2953 // +    For RT, change timeslice as well.  Invariant:
2954 //              constant "priority integral"
2955 //              Konst == TimeSlice * (60-Priority)
2956 //              Given a priority, compute appropriate timeslice.
2957 // +    Higher numerical values have higher priority.
2958 
2959 // sched class attributes
2960 typedef struct {
2961   int   schedPolicy;              // classID
2962   int   maxPrio;
2963   int   minPrio;
2964 } SchedInfo;
2965 
2966 
2967 static SchedInfo tsLimits, iaLimits, rtLimits, fxLimits;
2968 
2969 #ifdef ASSERT
2970 static int  ReadBackValidate = 1;
2971 #endif
2972 static int  myClass     = 0;
2973 static int  myMin       = 0;
2974 static int  myMax       = 0;
2975 static int  myCur       = 0;
2976 static bool priocntl_enable = false;
2977 
2978 static const int criticalPrio = FXCriticalPriority;
2979 static int java_MaxPriority_to_os_priority = 0; // Saved mapping
2980 
2981 
2982 // lwp_priocntl_init
2983 //
2984 // Try to determine the priority scale for our process.
2985 //
2986 // Return errno or 0 if OK.
2987 //
2988 static int lwp_priocntl_init() {
2989   int rslt;
2990   pcinfo_t ClassInfo;
2991   pcparms_t ParmInfo;
2992   int i;
2993 
2994   if (!UseThreadPriorities) return 0;
2995 
2996   // If ThreadPriorityPolicy is 1, switch tables
2997   if (ThreadPriorityPolicy == 1) {
2998     for (i = 0; i < CriticalPriority+1; i++)
2999       os::java_to_os_priority[i] = prio_policy1[i];
3000   }
3001   if (UseCriticalJavaThreadPriority) {
3002     // MaxPriority always maps to the FX scheduling class and criticalPrio.
3003     // See set_native_priority() and set_lwp_class_and_priority().
3004     // Save original MaxPriority mapping in case attempt to
3005     // use critical priority fails.
3006     java_MaxPriority_to_os_priority = os::java_to_os_priority[MaxPriority];
3007     // Set negative to distinguish from other priorities
3008     os::java_to_os_priority[MaxPriority] = -criticalPrio;
3009   }
3010 
3011   // Get IDs for a set of well-known scheduling classes.
3012   // TODO-FIXME: GETCLINFO returns the current # of classes in the
3013   // the system.  We should have a loop that iterates over the
3014   // classID values, which are known to be "small" integers.
3015 
3016   strcpy(ClassInfo.pc_clname, "TS");
3017   ClassInfo.pc_cid = -1;
3018   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3019   if (rslt < 0) return errno;
3020   assert(ClassInfo.pc_cid != -1, "cid for TS class is -1");
3021   tsLimits.schedPolicy = ClassInfo.pc_cid;
3022   tsLimits.maxPrio = ((tsinfo_t*)ClassInfo.pc_clinfo)->ts_maxupri;
3023   tsLimits.minPrio = -tsLimits.maxPrio;
3024 
3025   strcpy(ClassInfo.pc_clname, "IA");
3026   ClassInfo.pc_cid = -1;
3027   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3028   if (rslt < 0) return errno;
3029   assert(ClassInfo.pc_cid != -1, "cid for IA class is -1");
3030   iaLimits.schedPolicy = ClassInfo.pc_cid;
3031   iaLimits.maxPrio = ((iainfo_t*)ClassInfo.pc_clinfo)->ia_maxupri;
3032   iaLimits.minPrio = -iaLimits.maxPrio;
3033 
3034   strcpy(ClassInfo.pc_clname, "RT");
3035   ClassInfo.pc_cid = -1;
3036   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3037   if (rslt < 0) return errno;
3038   assert(ClassInfo.pc_cid != -1, "cid for RT class is -1");
3039   rtLimits.schedPolicy = ClassInfo.pc_cid;
3040   rtLimits.maxPrio = ((rtinfo_t*)ClassInfo.pc_clinfo)->rt_maxpri;
3041   rtLimits.minPrio = 0;
3042 
3043   strcpy(ClassInfo.pc_clname, "FX");
3044   ClassInfo.pc_cid = -1;
3045   rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3046   if (rslt < 0) return errno;
3047   assert(ClassInfo.pc_cid != -1, "cid for FX class is -1");
3048   fxLimits.schedPolicy = ClassInfo.pc_cid;
3049   fxLimits.maxPrio = ((fxinfo_t*)ClassInfo.pc_clinfo)->fx_maxupri;
3050   fxLimits.minPrio = 0;
3051 
3052   // Query our "current" scheduling class.
3053   // This will normally be IA, TS or, rarely, FX or RT.
3054   memset(&ParmInfo, 0, sizeof(ParmInfo));
3055   ParmInfo.pc_cid = PC_CLNULL;
3056   rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);
3057   if (rslt < 0) return errno;
3058   myClass = ParmInfo.pc_cid;
3059 
3060   // We now know our scheduling classId, get specific information
3061   // about the class.
3062   ClassInfo.pc_cid = myClass;
3063   ClassInfo.pc_clname[0] = 0;
3064   rslt = priocntl((idtype)0, 0, PC_GETCLINFO, (caddr_t)&ClassInfo);
3065   if (rslt < 0) return errno;
3066 
3067   if (ThreadPriorityVerbose) {
3068     tty->print_cr("lwp_priocntl_init: Class=%d(%s)...", myClass, ClassInfo.pc_clname);
3069   }
3070 
3071   memset(&ParmInfo, 0, sizeof(pcparms_t));
3072   ParmInfo.pc_cid = PC_CLNULL;
3073   rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);
3074   if (rslt < 0) return errno;
3075 
3076   if (ParmInfo.pc_cid == rtLimits.schedPolicy) {
3077     myMin = rtLimits.minPrio;
3078     myMax = rtLimits.maxPrio;
3079   } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {
3080     iaparms_t *iaInfo  = (iaparms_t*)ParmInfo.pc_clparms;
3081     myMin = iaLimits.minPrio;
3082     myMax = iaLimits.maxPrio;
3083     myMax = MIN2(myMax, (int)iaInfo->ia_uprilim);       // clamp - restrict
3084   } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {
3085     tsparms_t *tsInfo  = (tsparms_t*)ParmInfo.pc_clparms;
3086     myMin = tsLimits.minPrio;
3087     myMax = tsLimits.maxPrio;
3088     myMax = MIN2(myMax, (int)tsInfo->ts_uprilim);       // clamp - restrict
3089   } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {
3090     fxparms_t *fxInfo = (fxparms_t*)ParmInfo.pc_clparms;
3091     myMin = fxLimits.minPrio;
3092     myMax = fxLimits.maxPrio;
3093     myMax = MIN2(myMax, (int)fxInfo->fx_uprilim);       // clamp - restrict
3094   } else {
3095     // No clue - punt
3096     if (ThreadPriorityVerbose) {
3097       tty->print_cr("Unknown scheduling class: %s ... \n",
3098                     ClassInfo.pc_clname);
3099     }
3100     return EINVAL;      // no clue, punt
3101   }
3102 
3103   if (ThreadPriorityVerbose) {
3104     tty->print_cr("Thread priority Range: [%d..%d]\n", myMin, myMax);
3105   }
3106 
3107   priocntl_enable = true;  // Enable changing priorities
3108   return 0;
3109 }
3110 
3111 #define IAPRI(x)        ((iaparms_t *)((x).pc_clparms))
3112 #define RTPRI(x)        ((rtparms_t *)((x).pc_clparms))
3113 #define TSPRI(x)        ((tsparms_t *)((x).pc_clparms))
3114 #define FXPRI(x)        ((fxparms_t *)((x).pc_clparms))
3115 
3116 
3117 // scale_to_lwp_priority
3118 //
3119 // Convert from the libthread "thr_setprio" scale to our current
3120 // lwp scheduling class scale.
3121 //
3122 static int scale_to_lwp_priority(int rMin, int rMax, int x) {
3123   int v;
3124 
3125   if (x == 127) return rMax;            // avoid round-down
3126   v = (((x*(rMax-rMin)))/128)+rMin;
3127   return v;
3128 }
3129 
3130 
3131 // set_lwp_class_and_priority
3132 int set_lwp_class_and_priority(int ThreadID, int lwpid,
3133                                int newPrio, int new_class, bool scale) {
3134   int rslt;
3135   int Actual, Expected, prv;
3136   pcparms_t ParmInfo;                   // for GET-SET
3137 #ifdef ASSERT
3138   pcparms_t ReadBack;                   // for readback
3139 #endif
3140 
3141   // Set priority via PC_GETPARMS, update, PC_SETPARMS
3142   // Query current values.
3143   // TODO: accelerate this by eliminating the PC_GETPARMS call.
3144   // Cache "pcparms_t" in global ParmCache.
3145   // TODO: elide set-to-same-value
3146 
3147   // If something went wrong on init, don't change priorities.
3148   if (!priocntl_enable) {
3149     if (ThreadPriorityVerbose) {
3150       tty->print_cr("Trying to set priority but init failed, ignoring");
3151     }
3152     return EINVAL;
3153   }
3154 
3155   // If lwp hasn't started yet, just return
3156   // the _start routine will call us again.
3157   if (lwpid <= 0) {
3158     if (ThreadPriorityVerbose) {
3159       tty->print_cr("deferring the set_lwp_class_and_priority of thread "
3160                     INTPTR_FORMAT " to %d, lwpid not set",
3161                     ThreadID, newPrio);
3162     }
3163     return 0;
3164   }
3165 
3166   if (ThreadPriorityVerbose) {
3167     tty->print_cr ("set_lwp_class_and_priority("
3168                    INTPTR_FORMAT "@" INTPTR_FORMAT " %d) ",
3169                    ThreadID, lwpid, newPrio);
3170   }
3171 
3172   memset(&ParmInfo, 0, sizeof(pcparms_t));
3173   ParmInfo.pc_cid = PC_CLNULL;
3174   rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ParmInfo);
3175   if (rslt < 0) return errno;
3176 
3177   int cur_class = ParmInfo.pc_cid;
3178   ParmInfo.pc_cid = (id_t)new_class;
3179 
3180   if (new_class == rtLimits.schedPolicy) {
3181     rtparms_t *rtInfo  = (rtparms_t*)ParmInfo.pc_clparms;
3182     rtInfo->rt_pri     = scale ? scale_to_lwp_priority(rtLimits.minPrio,
3183                                                        rtLimits.maxPrio, newPrio)
3184                                : newPrio;
3185     rtInfo->rt_tqsecs  = RT_NOCHANGE;
3186     rtInfo->rt_tqnsecs = RT_NOCHANGE;
3187     if (ThreadPriorityVerbose) {
3188       tty->print_cr("RT: %d->%d\n", newPrio, rtInfo->rt_pri);
3189     }
3190   } else if (new_class == iaLimits.schedPolicy) {
3191     iaparms_t* iaInfo  = (iaparms_t*)ParmInfo.pc_clparms;
3192     int maxClamped     = MIN2(iaLimits.maxPrio,
3193                               cur_class == new_class
3194                               ? (int)iaInfo->ia_uprilim : iaLimits.maxPrio);
3195     iaInfo->ia_upri    = scale ? scale_to_lwp_priority(iaLimits.minPrio,
3196                                                        maxClamped, newPrio)
3197                                : newPrio;
3198     iaInfo->ia_uprilim = cur_class == new_class
3199                            ? IA_NOCHANGE : (pri_t)iaLimits.maxPrio;
3200     iaInfo->ia_mode    = IA_NOCHANGE;
3201     if (ThreadPriorityVerbose) {
3202       tty->print_cr("IA: [%d...%d] %d->%d\n",
3203                     iaLimits.minPrio, maxClamped, newPrio, iaInfo->ia_upri);
3204     }
3205   } else if (new_class == tsLimits.schedPolicy) {
3206     tsparms_t* tsInfo  = (tsparms_t*)ParmInfo.pc_clparms;
3207     int maxClamped     = MIN2(tsLimits.maxPrio,
3208                               cur_class == new_class
3209                               ? (int)tsInfo->ts_uprilim : tsLimits.maxPrio);
3210     tsInfo->ts_upri    = scale ? scale_to_lwp_priority(tsLimits.minPrio,
3211                                                        maxClamped, newPrio)
3212                                : newPrio;
3213     tsInfo->ts_uprilim = cur_class == new_class
3214                            ? TS_NOCHANGE : (pri_t)tsLimits.maxPrio;
3215     if (ThreadPriorityVerbose) {
3216       tty->print_cr("TS: [%d...%d] %d->%d\n",
3217                     tsLimits.minPrio, maxClamped, newPrio, tsInfo->ts_upri);
3218     }
3219   } else if (new_class == fxLimits.schedPolicy) {
3220     fxparms_t* fxInfo  = (fxparms_t*)ParmInfo.pc_clparms;
3221     int maxClamped     = MIN2(fxLimits.maxPrio,
3222                               cur_class == new_class
3223                               ? (int)fxInfo->fx_uprilim : fxLimits.maxPrio);
3224     fxInfo->fx_upri    = scale ? scale_to_lwp_priority(fxLimits.minPrio,
3225                                                        maxClamped, newPrio)
3226                                : newPrio;
3227     fxInfo->fx_uprilim = cur_class == new_class
3228                            ? FX_NOCHANGE : (pri_t)fxLimits.maxPrio;
3229     fxInfo->fx_tqsecs  = FX_NOCHANGE;
3230     fxInfo->fx_tqnsecs = FX_NOCHANGE;
3231     if (ThreadPriorityVerbose) {
3232       tty->print_cr("FX: [%d...%d] %d->%d\n",
3233                     fxLimits.minPrio, maxClamped, newPrio, fxInfo->fx_upri);
3234     }
3235   } else {
3236     if (ThreadPriorityVerbose) {
3237       tty->print_cr("Unknown new scheduling class %d\n", new_class);
3238     }
3239     return EINVAL;    // no clue, punt
3240   }
3241 
3242   rslt = priocntl(P_LWPID, lwpid, PC_SETPARMS, (caddr_t)&ParmInfo);
3243   if (ThreadPriorityVerbose && rslt) {
3244     tty->print_cr ("PC_SETPARMS ->%d %d\n", rslt, errno);
3245   }
3246   if (rslt < 0) return errno;
3247 
3248 #ifdef ASSERT
3249   // Sanity check: read back what we just attempted to set.
3250   // In theory it could have changed in the interim ...
3251   //
3252   // The priocntl system call is tricky.
3253   // Sometimes it'll validate the priority value argument and
3254   // return EINVAL if unhappy.  At other times it fails silently.
3255   // Readbacks are prudent.
3256 
3257   if (!ReadBackValidate) return 0;
3258 
3259   memset(&ReadBack, 0, sizeof(pcparms_t));
3260   ReadBack.pc_cid = PC_CLNULL;
3261   rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ReadBack);
3262   assert(rslt >= 0, "priocntl failed");
3263   Actual = Expected = 0xBAD;
3264   assert(ParmInfo.pc_cid == ReadBack.pc_cid, "cid's don't match");
3265   if (ParmInfo.pc_cid == rtLimits.schedPolicy) {
3266     Actual   = RTPRI(ReadBack)->rt_pri;
3267     Expected = RTPRI(ParmInfo)->rt_pri;
3268   } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {
3269     Actual   = IAPRI(ReadBack)->ia_upri;
3270     Expected = IAPRI(ParmInfo)->ia_upri;
3271   } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {
3272     Actual   = TSPRI(ReadBack)->ts_upri;
3273     Expected = TSPRI(ParmInfo)->ts_upri;
3274   } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {
3275     Actual   = FXPRI(ReadBack)->fx_upri;
3276     Expected = FXPRI(ParmInfo)->fx_upri;
3277   } else {
3278     if (ThreadPriorityVerbose) {
3279       tty->print_cr("set_lwp_class_and_priority: unexpected class in readback: %d\n",
3280                     ParmInfo.pc_cid);
3281     }
3282   }
3283 
3284   if (Actual != Expected) {
3285     if (ThreadPriorityVerbose) {
3286       tty->print_cr ("set_lwp_class_and_priority(%d %d) Class=%d: actual=%d vs expected=%d\n",
3287                      lwpid, newPrio, ReadBack.pc_cid, Actual, Expected);
3288     }
3289   }
3290 #endif
3291 
3292   return 0;
3293 }
3294 
3295 // Solaris only gives access to 128 real priorities at a time,
3296 // so we expand Java's ten to fill this range.  This would be better
3297 // if we dynamically adjusted relative priorities.
3298 //
3299 // The ThreadPriorityPolicy option allows us to select 2 different
3300 // priority scales.
3301 //
3302 // ThreadPriorityPolicy=0
3303 // Since the Solaris' default priority is MaximumPriority, we do not
3304 // set a priority lower than Max unless a priority lower than
3305 // NormPriority is requested.
3306 //
3307 // ThreadPriorityPolicy=1
3308 // This mode causes the priority table to get filled with
3309 // linear values.  NormPriority get's mapped to 50% of the
3310 // Maximum priority an so on.  This will cause VM threads
3311 // to get unfair treatment against other Solaris processes
3312 // which do not explicitly alter their thread priorities.
3313 
3314 int os::java_to_os_priority[CriticalPriority + 1] = {
3315   -99999,         // 0 Entry should never be used
3316 
3317   0,              // 1 MinPriority
3318   32,             // 2
3319   64,             // 3
3320 
3321   96,             // 4
3322   127,            // 5 NormPriority
3323   127,            // 6
3324 
3325   127,            // 7
3326   127,            // 8
3327   127,            // 9 NearMaxPriority
3328 
3329   127,            // 10 MaxPriority
3330 
3331   -criticalPrio   // 11 CriticalPriority
3332 };
3333 
3334 OSReturn os::set_native_priority(Thread* thread, int newpri) {
3335   OSThread* osthread = thread->osthread();
3336 
3337   // Save requested priority in case the thread hasn't been started
3338   osthread->set_native_priority(newpri);
3339 
3340   // Check for critical priority request
3341   bool fxcritical = false;
3342   if (newpri == -criticalPrio) {
3343     fxcritical = true;
3344     newpri = criticalPrio;
3345   }
3346 
3347   assert(newpri >= MinimumPriority && newpri <= MaximumPriority, "bad priority mapping");
3348   if (!UseThreadPriorities) return OS_OK;
3349 
3350   int status = 0;
3351 
3352   if (!fxcritical) {
3353     // Use thr_setprio only if we have a priority that thr_setprio understands
3354     status = thr_setprio(thread->osthread()->thread_id(), newpri);
3355   }
3356 
3357   int lwp_status =
3358           set_lwp_class_and_priority(osthread->thread_id(),
3359                                      osthread->lwp_id(),
3360                                      newpri,
3361                                      fxcritical ? fxLimits.schedPolicy : myClass,
3362                                      !fxcritical);
3363   if (lwp_status != 0 && fxcritical) {
3364     // Try again, this time without changing the scheduling class
3365     newpri = java_MaxPriority_to_os_priority;
3366     lwp_status = set_lwp_class_and_priority(osthread->thread_id(),
3367                                             osthread->lwp_id(),
3368                                             newpri, myClass, false);
3369   }
3370   status |= lwp_status;
3371   return (status == 0) ? OS_OK : OS_ERR;
3372 }
3373 
3374 
3375 OSReturn os::get_native_priority(const Thread* const thread,
3376                                  int *priority_ptr) {
3377   int p;
3378   if (!UseThreadPriorities) {
3379     *priority_ptr = NormalPriority;
3380     return OS_OK;
3381   }
3382   int status = thr_getprio(thread->osthread()->thread_id(), &p);
3383   if (status != 0) {
3384     return OS_ERR;
3385   }
3386   *priority_ptr = p;
3387   return OS_OK;
3388 }
3389 
3390 ////////////////////////////////////////////////////////////////////////////////
3391 // suspend/resume support
3392 
3393 //  The low-level signal-based suspend/resume support is a remnant from the
3394 //  old VM-suspension that used to be for java-suspension, safepoints etc,
3395 //  within hotspot. Currently used by JFR's OSThreadSampler
3396 //
3397 //  The remaining code is greatly simplified from the more general suspension
3398 //  code that used to be used.
3399 //
3400 //  The protocol is quite simple:
3401 //  - suspend:
3402 //      - sends a signal to the target thread
3403 //      - polls the suspend state of the osthread using a yield loop
3404 //      - target thread signal handler (SR_handler) sets suspend state
3405 //        and blocks in sigsuspend until continued
3406 //  - resume:
3407 //      - sets target osthread state to continue
3408 //      - sends signal to end the sigsuspend loop in the SR_handler
3409 //
3410 //  Note that the SR_lock plays no role in this suspend/resume protocol,
3411 //  but is checked for NULL in SR_handler as a thread termination indicator.
3412 //  The SR_lock is, however, used by JavaThread::java_suspend()/java_resume() APIs.
3413 //
3414 //  Note that resume_clear_context() and suspend_save_context() are needed
3415 //  by SR_handler(), so that fetch_frame_from_ucontext() works,
3416 //  which in part is used by:
3417 //    - Forte Analyzer: AsyncGetCallTrace()
3418 //    - StackBanging: get_frame_at_stack_banging_point()
3419 //    - JFR: get_topframe()-->....-->get_valid_uc_in_signal_handler()
3420 
3421 static void resume_clear_context(OSThread *osthread) {
3422   osthread->set_ucontext(NULL);
3423 }
3424 
3425 static void suspend_save_context(OSThread *osthread, ucontext_t* context) {
3426   osthread->set_ucontext(context);
3427 }
3428 
3429 static PosixSemaphore sr_semaphore;
3430 
3431 void os::Solaris::SR_handler(Thread* thread, ucontext_t* context) {
3432   // Save and restore errno to avoid confusing native code with EINTR
3433   // after sigsuspend.
3434   int old_errno = errno;
3435 
3436   OSThread* osthread = thread->osthread();
3437   assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
3438 
3439   os::SuspendResume::State current = osthread->sr.state();
3440   if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
3441     suspend_save_context(osthread, context);
3442 
3443     // attempt to switch the state, we assume we had a SUSPEND_REQUEST
3444     os::SuspendResume::State state = osthread->sr.suspended();
3445     if (state == os::SuspendResume::SR_SUSPENDED) {
3446       sigset_t suspend_set;  // signals for sigsuspend()
3447 
3448       // get current set of blocked signals and unblock resume signal
3449       pthread_sigmask(SIG_BLOCK, NULL, &suspend_set);
3450       sigdelset(&suspend_set, ASYNC_SIGNAL);
3451 
3452       sr_semaphore.signal();
3453       // wait here until we are resumed
3454       while (1) {
3455         sigsuspend(&suspend_set);
3456 
3457         os::SuspendResume::State result = osthread->sr.running();
3458         if (result == os::SuspendResume::SR_RUNNING) {
3459           sr_semaphore.signal();
3460           break;
3461         }
3462       }
3463 
3464     } else if (state == os::SuspendResume::SR_RUNNING) {
3465       // request was cancelled, continue
3466     } else {
3467       ShouldNotReachHere();
3468     }
3469 
3470     resume_clear_context(osthread);
3471   } else if (current == os::SuspendResume::SR_RUNNING) {
3472     // request was cancelled, continue
3473   } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
3474     // ignore
3475   } else {
3476     // ignore
3477   }
3478 
3479   errno = old_errno;
3480 }
3481 
3482 void os::print_statistics() {
3483 }
3484 
3485 bool os::message_box(const char* title, const char* message) {
3486   int i;
3487   fdStream err(defaultStream::error_fd());
3488   for (i = 0; i < 78; i++) err.print_raw("=");
3489   err.cr();
3490   err.print_raw_cr(title);
3491   for (i = 0; i < 78; i++) err.print_raw("-");
3492   err.cr();
3493   err.print_raw_cr(message);
3494   for (i = 0; i < 78; i++) err.print_raw("=");
3495   err.cr();
3496 
3497   char buf[16];
3498   // Prevent process from exiting upon "read error" without consuming all CPU
3499   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
3500 
3501   return buf[0] == 'y' || buf[0] == 'Y';
3502 }
3503 
3504 static int sr_notify(OSThread* osthread) {
3505   int status = thr_kill(osthread->thread_id(), ASYNC_SIGNAL);
3506   assert_status(status == 0, status, "thr_kill");
3507   return status;
3508 }
3509 
3510 // "Randomly" selected value for how long we want to spin
3511 // before bailing out on suspending a thread, also how often
3512 // we send a signal to a thread we want to resume
3513 static const int RANDOMLY_LARGE_INTEGER = 1000000;
3514 static const int RANDOMLY_LARGE_INTEGER2 = 100;
3515 
3516 static bool do_suspend(OSThread* osthread) {
3517   assert(osthread->sr.is_running(), "thread should be running");
3518   assert(!sr_semaphore.trywait(), "semaphore has invalid state");
3519 
3520   // mark as suspended and send signal
3521   if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
3522     // failed to switch, state wasn't running?
3523     ShouldNotReachHere();
3524     return false;
3525   }
3526 
3527   if (sr_notify(osthread) != 0) {
3528     ShouldNotReachHere();
3529   }
3530 
3531   // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
3532   while (true) {
3533     if (sr_semaphore.timedwait(create_semaphore_timespec(0, 2000 * NANOSECS_PER_MILLISEC))) {
3534       break;
3535     } else {
3536       // timeout
3537       os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
3538       if (cancelled == os::SuspendResume::SR_RUNNING) {
3539         return false;
3540       } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
3541         // make sure that we consume the signal on the semaphore as well
3542         sr_semaphore.wait();
3543         break;
3544       } else {
3545         ShouldNotReachHere();
3546         return false;
3547       }
3548     }
3549   }
3550 
3551   guarantee(osthread->sr.is_suspended(), "Must be suspended");
3552   return true;
3553 }
3554 
3555 static void do_resume(OSThread* osthread) {
3556   assert(osthread->sr.is_suspended(), "thread should be suspended");
3557   assert(!sr_semaphore.trywait(), "invalid semaphore state");
3558 
3559   if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
3560     // failed to switch to WAKEUP_REQUEST
3561     ShouldNotReachHere();
3562     return;
3563   }
3564 
3565   while (true) {
3566     if (sr_notify(osthread) == 0) {
3567       if (sr_semaphore.timedwait(create_semaphore_timespec(0, 2 * NANOSECS_PER_MILLISEC))) {
3568         if (osthread->sr.is_running()) {
3569           return;
3570         }
3571       }
3572     } else {
3573       ShouldNotReachHere();
3574     }
3575   }
3576 
3577   guarantee(osthread->sr.is_running(), "Must be running!");
3578 }
3579 
3580 void os::SuspendedThreadTask::internal_do_task() {
3581   if (do_suspend(_thread->osthread())) {
3582     SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
3583     do_task(context);
3584     do_resume(_thread->osthread());
3585   }
3586 }
3587 
3588 // This does not do anything on Solaris. This is basically a hook for being
3589 // able to use structured exception handling (thread-local exception filters) on, e.g., Win32.
3590 void os::os_exception_wrapper(java_call_t f, JavaValue* value,
3591                               const methodHandle& method, JavaCallArguments* args,
3592                               Thread* thread) {
3593   f(value, method, args, thread);
3594 }
3595 
3596 // This routine may be used by user applications as a "hook" to catch signals.
3597 // The user-defined signal handler must pass unrecognized signals to this
3598 // routine, and if it returns true (non-zero), then the signal handler must
3599 // return immediately.  If the flag "abort_if_unrecognized" is true, then this
3600 // routine will never retun false (zero), but instead will execute a VM panic
3601 // routine kill the process.
3602 //
3603 // If this routine returns false, it is OK to call it again.  This allows
3604 // the user-defined signal handler to perform checks either before or after
3605 // the VM performs its own checks.  Naturally, the user code would be making
3606 // a serious error if it tried to handle an exception (such as a null check
3607 // or breakpoint) that the VM was generating for its own correct operation.
3608 //
3609 // This routine may recognize any of the following kinds of signals:
3610 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, BREAK_SIGNAL, SIGPIPE, SIGXFSZ,
3611 // ASYNC_SIGNAL.
3612 // It should be consulted by handlers for any of those signals.
3613 //
3614 // The caller of this routine must pass in the three arguments supplied
3615 // to the function referred to in the "sa_sigaction" (not the "sa_handler")
3616 // field of the structure passed to sigaction().  This routine assumes that
3617 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
3618 //
3619 // Note that the VM will print warnings if it detects conflicting signal
3620 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
3621 //
3622 extern "C" JNIEXPORT int JVM_handle_solaris_signal(int signo,
3623                                                    siginfo_t* siginfo,
3624                                                    void* ucontext,
3625                                                    int abort_if_unrecognized);
3626 
3627 
3628 void signalHandler(int sig, siginfo_t* info, void* ucVoid) {
3629   int orig_errno = errno;  // Preserve errno value over signal handler.
3630   JVM_handle_solaris_signal(sig, info, ucVoid, true);
3631   errno = orig_errno;
3632 }
3633 
3634 // This boolean allows users to forward their own non-matching signals
3635 // to JVM_handle_solaris_signal, harmlessly.
3636 bool os::Solaris::signal_handlers_are_installed = false;
3637 
3638 // For signal-chaining
3639 bool os::Solaris::libjsig_is_loaded = false;
3640 typedef struct sigaction *(*get_signal_t)(int);
3641 get_signal_t os::Solaris::get_signal_action = NULL;
3642 
3643 struct sigaction* os::Solaris::get_chained_signal_action(int sig) {
3644   struct sigaction *actp = NULL;
3645 
3646   if ((libjsig_is_loaded)  && (sig <= Maxsignum)) {
3647     // Retrieve the old signal handler from libjsig
3648     actp = (*get_signal_action)(sig);
3649   }
3650   if (actp == NULL) {
3651     // Retrieve the preinstalled signal handler from jvm
3652     actp = get_preinstalled_handler(sig);
3653   }
3654 
3655   return actp;
3656 }
3657 
3658 static bool call_chained_handler(struct sigaction *actp, int sig,
3659                                  siginfo_t *siginfo, void *context) {
3660   // Call the old signal handler
3661   if (actp->sa_handler == SIG_DFL) {
3662     // It's more reasonable to let jvm treat it as an unexpected exception
3663     // instead of taking the default action.
3664     return false;
3665   } else if (actp->sa_handler != SIG_IGN) {
3666     if ((actp->sa_flags & SA_NODEFER) == 0) {
3667       // automaticlly block the signal
3668       sigaddset(&(actp->sa_mask), sig);
3669     }
3670 
3671     sa_handler_t hand;
3672     sa_sigaction_t sa;
3673     bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
3674     // retrieve the chained handler
3675     if (siginfo_flag_set) {
3676       sa = actp->sa_sigaction;
3677     } else {
3678       hand = actp->sa_handler;
3679     }
3680 
3681     if ((actp->sa_flags & SA_RESETHAND) != 0) {
3682       actp->sa_handler = SIG_DFL;
3683     }
3684 
3685     // try to honor the signal mask
3686     sigset_t oset;
3687     pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset);
3688 
3689     // call into the chained handler
3690     if (siginfo_flag_set) {
3691       (*sa)(sig, siginfo, context);
3692     } else {
3693       (*hand)(sig);
3694     }
3695 
3696     // restore the signal mask
3697     pthread_sigmask(SIG_SETMASK, &oset, 0);
3698   }
3699   // Tell jvm's signal handler the signal is taken care of.
3700   return true;
3701 }
3702 
3703 bool os::Solaris::chained_handler(int sig, siginfo_t* siginfo, void* context) {
3704   bool chained = false;
3705   // signal-chaining
3706   if (UseSignalChaining) {
3707     struct sigaction *actp = get_chained_signal_action(sig);
3708     if (actp != NULL) {
3709       chained = call_chained_handler(actp, sig, siginfo, context);
3710     }
3711   }
3712   return chained;
3713 }
3714 
3715 struct sigaction* os::Solaris::get_preinstalled_handler(int sig) {
3716   assert((chainedsigactions != (struct sigaction *)NULL) &&
3717          (preinstalled_sigs != (int *)NULL), "signals not yet initialized");
3718   if (preinstalled_sigs[sig] != 0) {
3719     return &chainedsigactions[sig];
3720   }
3721   return NULL;
3722 }
3723 
3724 void os::Solaris::save_preinstalled_handler(int sig,
3725                                             struct sigaction& oldAct) {
3726   assert(sig > 0 && sig <= Maxsignum, "vm signal out of expected range");
3727   assert((chainedsigactions != (struct sigaction *)NULL) &&
3728          (preinstalled_sigs != (int *)NULL), "signals not yet initialized");
3729   chainedsigactions[sig] = oldAct;
3730   preinstalled_sigs[sig] = 1;
3731 }
3732 
3733 void os::Solaris::set_signal_handler(int sig, bool set_installed,
3734                                      bool oktochain) {
3735   // Check for overwrite.
3736   struct sigaction oldAct;
3737   sigaction(sig, (struct sigaction*)NULL, &oldAct);
3738   void* oldhand =
3739       oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
3740                           : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
3741   if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
3742       oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
3743       oldhand != CAST_FROM_FN_PTR(void*, signalHandler)) {
3744     if (AllowUserSignalHandlers || !set_installed) {
3745       // Do not overwrite; user takes responsibility to forward to us.
3746       return;
3747     } else if (UseSignalChaining) {
3748       if (oktochain) {
3749         // save the old handler in jvm
3750         save_preinstalled_handler(sig, oldAct);
3751       } else {
3752         vm_exit_during_initialization("Signal chaining not allowed for VM interrupt signal.");
3753       }
3754       // libjsig also interposes the sigaction() call below and saves the
3755       // old sigaction on it own.
3756     } else {
3757       fatal("Encountered unexpected pre-existing sigaction handler "
3758             "%#lx for signal %d.", (long)oldhand, sig);
3759     }
3760   }
3761 
3762   struct sigaction sigAct;
3763   sigfillset(&(sigAct.sa_mask));
3764   sigAct.sa_handler = SIG_DFL;
3765 
3766   sigAct.sa_sigaction = signalHandler;
3767   // Handle SIGSEGV on alternate signal stack if
3768   // not using stack banging
3769   if (!UseStackBanging && sig == SIGSEGV) {
3770     sigAct.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;
3771   } else {
3772     sigAct.sa_flags = SA_SIGINFO | SA_RESTART;
3773   }
3774   os::Solaris::set_our_sigflags(sig, sigAct.sa_flags);
3775 
3776   sigaction(sig, &sigAct, &oldAct);
3777 
3778   void* oldhand2 = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
3779                                        : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
3780   assert(oldhand2 == oldhand, "no concurrent signal handler installation");
3781 }
3782 
3783 
3784 #define DO_SIGNAL_CHECK(sig)                      \
3785   do {                                            \
3786     if (!sigismember(&check_signal_done, sig)) {  \
3787       os::Solaris::check_signal_handler(sig);     \
3788     }                                             \
3789   } while (0)
3790 
3791 // This method is a periodic task to check for misbehaving JNI applications
3792 // under CheckJNI, we can add any periodic checks here
3793 
3794 void os::run_periodic_checks() {
3795   // A big source of grief is hijacking virt. addr 0x0 on Solaris,
3796   // thereby preventing a NULL checks.
3797   if (!check_addr0_done) check_addr0_done = check_addr0(tty);
3798 
3799   if (check_signals == false) return;
3800 
3801   // SEGV and BUS if overridden could potentially prevent
3802   // generation of hs*.log in the event of a crash, debugging
3803   // such a case can be very challenging, so we absolutely
3804   // check for the following for a good measure:
3805   DO_SIGNAL_CHECK(SIGSEGV);
3806   DO_SIGNAL_CHECK(SIGILL);
3807   DO_SIGNAL_CHECK(SIGFPE);
3808   DO_SIGNAL_CHECK(SIGBUS);
3809   DO_SIGNAL_CHECK(SIGPIPE);
3810   DO_SIGNAL_CHECK(SIGXFSZ);
3811   DO_SIGNAL_CHECK(ASYNC_SIGNAL);
3812 
3813   // ReduceSignalUsage allows the user to override these handlers
3814   // see comments at the very top and jvm_solaris.h
3815   if (!ReduceSignalUsage) {
3816     DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
3817     DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
3818     DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
3819     DO_SIGNAL_CHECK(BREAK_SIGNAL);
3820   }
3821 }
3822 
3823 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
3824 
3825 static os_sigaction_t os_sigaction = NULL;
3826 
3827 void os::Solaris::check_signal_handler(int sig) {
3828   char buf[O_BUFLEN];
3829   address jvmHandler = NULL;
3830 
3831   struct sigaction act;
3832   if (os_sigaction == NULL) {
3833     // only trust the default sigaction, in case it has been interposed
3834     os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
3835     if (os_sigaction == NULL) return;
3836   }
3837 
3838   os_sigaction(sig, (struct sigaction*)NULL, &act);
3839 
3840   address thisHandler = (act.sa_flags & SA_SIGINFO)
3841     ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
3842     : CAST_FROM_FN_PTR(address, act.sa_handler);
3843 
3844 
3845   switch (sig) {
3846   case SIGSEGV:
3847   case SIGBUS:
3848   case SIGFPE:
3849   case SIGPIPE:
3850   case SIGXFSZ:
3851   case SIGILL:
3852   case ASYNC_SIGNAL:
3853     jvmHandler = CAST_FROM_FN_PTR(address, signalHandler);
3854     break;
3855 
3856   case SHUTDOWN1_SIGNAL:
3857   case SHUTDOWN2_SIGNAL:
3858   case SHUTDOWN3_SIGNAL:
3859   case BREAK_SIGNAL:
3860     jvmHandler = (address)user_handler();
3861     break;
3862 
3863   default:
3864       return;
3865   }
3866 
3867   if (thisHandler != jvmHandler) {
3868     tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
3869     tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
3870     tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
3871     // No need to check this sig any longer
3872     sigaddset(&check_signal_done, sig);
3873     // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
3874     if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
3875       tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",
3876                     exception_name(sig, buf, O_BUFLEN));
3877     }
3878   } else if(os::Solaris::get_our_sigflags(sig) != 0 && act.sa_flags != os::Solaris::get_our_sigflags(sig)) {
3879     tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
3880     tty->print("expected:");
3881     os::Posix::print_sa_flags(tty, os::Solaris::get_our_sigflags(sig));
3882     tty->cr();
3883     tty->print("  found:");
3884     os::Posix::print_sa_flags(tty, act.sa_flags);
3885     tty->cr();
3886     // No need to check this sig any longer
3887     sigaddset(&check_signal_done, sig);
3888   }
3889 
3890   // Print all the signal handler state
3891   if (sigismember(&check_signal_done, sig)) {
3892     print_signal_handlers(tty, buf, O_BUFLEN);
3893   }
3894 
3895 }
3896 
3897 void os::Solaris::install_signal_handlers() {
3898   signal_handlers_are_installed = true;
3899 
3900   // signal-chaining
3901   typedef void (*signal_setting_t)();
3902   signal_setting_t begin_signal_setting = NULL;
3903   signal_setting_t end_signal_setting = NULL;
3904   begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3905                                         dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
3906   if (begin_signal_setting != NULL) {
3907     end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
3908                                         dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
3909     get_signal_action = CAST_TO_FN_PTR(get_signal_t,
3910                                        dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
3911     libjsig_is_loaded = true;
3912     assert(UseSignalChaining, "should enable signal-chaining");
3913   }
3914   if (libjsig_is_loaded) {
3915     // Tell libjsig jvm is setting signal handlers
3916     (*begin_signal_setting)();
3917   }
3918 
3919   set_signal_handler(SIGSEGV, true, true);
3920   set_signal_handler(SIGPIPE, true, true);
3921   set_signal_handler(SIGXFSZ, true, true);
3922   set_signal_handler(SIGBUS, true, true);
3923   set_signal_handler(SIGILL, true, true);
3924   set_signal_handler(SIGFPE, true, true);
3925   set_signal_handler(ASYNC_SIGNAL, true, true);
3926 
3927   if (libjsig_is_loaded) {
3928     // Tell libjsig jvm finishes setting signal handlers
3929     (*end_signal_setting)();
3930   }
3931 
3932   // We don't activate signal checker if libjsig is in place, we trust ourselves
3933   // and if UserSignalHandler is installed all bets are off.
3934   // Log that signal checking is off only if -verbose:jni is specified.
3935   if (CheckJNICalls) {
3936     if (libjsig_is_loaded) {
3937       if (PrintJNIResolving) {
3938         tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
3939       }
3940       check_signals = false;
3941     }
3942     if (AllowUserSignalHandlers) {
3943       if (PrintJNIResolving) {
3944         tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
3945       }
3946       check_signals = false;
3947     }
3948   }
3949 }
3950 
3951 
3952 void report_error(const char* file_name, int line_no, const char* title,
3953                   const char* format, ...);
3954 
3955 // (Static) wrappers for the liblgrp API
3956 os::Solaris::lgrp_home_func_t os::Solaris::_lgrp_home;
3957 os::Solaris::lgrp_init_func_t os::Solaris::_lgrp_init;
3958 os::Solaris::lgrp_fini_func_t os::Solaris::_lgrp_fini;
3959 os::Solaris::lgrp_root_func_t os::Solaris::_lgrp_root;
3960 os::Solaris::lgrp_children_func_t os::Solaris::_lgrp_children;
3961 os::Solaris::lgrp_resources_func_t os::Solaris::_lgrp_resources;
3962 os::Solaris::lgrp_nlgrps_func_t os::Solaris::_lgrp_nlgrps;
3963 os::Solaris::lgrp_cookie_stale_func_t os::Solaris::_lgrp_cookie_stale;
3964 os::Solaris::lgrp_cookie_t os::Solaris::_lgrp_cookie = 0;
3965 
3966 static address resolve_symbol_lazy(const char* name) {
3967   address addr = (address) dlsym(RTLD_DEFAULT, name);
3968   if (addr == NULL) {
3969     // RTLD_DEFAULT was not defined on some early versions of 2.5.1
3970     addr = (address) dlsym(RTLD_NEXT, name);
3971   }
3972   return addr;
3973 }
3974 
3975 static address resolve_symbol(const char* name) {
3976   address addr = resolve_symbol_lazy(name);
3977   if (addr == NULL) {
3978     fatal(dlerror());
3979   }
3980   return addr;
3981 }
3982 
3983 void os::Solaris::libthread_init() {
3984   address func = (address)dlsym(RTLD_DEFAULT, "_thr_suspend_allmutators");
3985 
3986   lwp_priocntl_init();
3987 
3988   // RTLD_DEFAULT was not defined on some early versions of 5.5.1
3989   if (func == NULL) {
3990     func = (address) dlsym(RTLD_NEXT, "_thr_suspend_allmutators");
3991     // Guarantee that this VM is running on an new enough OS (5.6 or
3992     // later) that it will have a new enough libthread.so.
3993     guarantee(func != NULL, "libthread.so is too old.");
3994   }
3995 
3996   int size;
3997   void (*handler_info_func)(address *, int *);
3998   handler_info_func = CAST_TO_FN_PTR(void (*)(address *, int *), resolve_symbol("thr_sighndlrinfo"));
3999   handler_info_func(&handler_start, &size);
4000   handler_end = handler_start + size;
4001 }
4002 
4003 
4004 int_fnP_mutex_tP os::Solaris::_mutex_lock;
4005 int_fnP_mutex_tP os::Solaris::_mutex_trylock;
4006 int_fnP_mutex_tP os::Solaris::_mutex_unlock;
4007 int_fnP_mutex_tP_i_vP os::Solaris::_mutex_init;
4008 int_fnP_mutex_tP os::Solaris::_mutex_destroy;
4009 int os::Solaris::_mutex_scope = USYNC_THREAD;
4010 
4011 int_fnP_cond_tP_mutex_tP_timestruc_tP os::Solaris::_cond_timedwait;
4012 int_fnP_cond_tP_mutex_tP os::Solaris::_cond_wait;
4013 int_fnP_cond_tP os::Solaris::_cond_signal;
4014 int_fnP_cond_tP os::Solaris::_cond_broadcast;
4015 int_fnP_cond_tP_i_vP os::Solaris::_cond_init;
4016 int_fnP_cond_tP os::Solaris::_cond_destroy;
4017 int os::Solaris::_cond_scope = USYNC_THREAD;
4018 bool os::Solaris::_synchronization_initialized;
4019 
4020 void os::Solaris::synchronization_init() {
4021   if (UseLWPSynchronization) {
4022     os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_lock")));
4023     os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_trylock")));
4024     os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_unlock")));
4025     os::Solaris::set_mutex_init(lwp_mutex_init);
4026     os::Solaris::set_mutex_destroy(lwp_mutex_destroy);
4027     os::Solaris::set_mutex_scope(USYNC_THREAD);
4028 
4029     os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("_lwp_cond_timedwait")));
4030     os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("_lwp_cond_wait")));
4031     os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_signal")));
4032     os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_broadcast")));
4033     os::Solaris::set_cond_init(lwp_cond_init);
4034     os::Solaris::set_cond_destroy(lwp_cond_destroy);
4035     os::Solaris::set_cond_scope(USYNC_THREAD);
4036   } else {
4037     os::Solaris::set_mutex_scope(USYNC_THREAD);
4038     os::Solaris::set_cond_scope(USYNC_THREAD);
4039 
4040     if (UsePthreads) {
4041       os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_lock")));
4042       os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_trylock")));
4043       os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_unlock")));
4044       os::Solaris::set_mutex_init(pthread_mutex_default_init);
4045       os::Solaris::set_mutex_destroy(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_destroy")));
4046 
4047       os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("pthread_cond_timedwait")));
4048       os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("pthread_cond_wait")));
4049       os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_signal")));
4050       os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_broadcast")));
4051       os::Solaris::set_cond_init(pthread_cond_default_init);
4052       os::Solaris::set_cond_destroy(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_destroy")));
4053     } else {
4054       os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_lock")));
4055       os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_trylock")));
4056       os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_unlock")));
4057       os::Solaris::set_mutex_init(::mutex_init);
4058       os::Solaris::set_mutex_destroy(::mutex_destroy);
4059 
4060       os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("cond_timedwait")));
4061       os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("cond_wait")));
4062       os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_signal")));
4063       os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_broadcast")));
4064       os::Solaris::set_cond_init(::cond_init);
4065       os::Solaris::set_cond_destroy(::cond_destroy);
4066     }
4067   }
4068   _synchronization_initialized = true;
4069 }
4070 
4071 bool os::Solaris::liblgrp_init() {
4072   void *handle = dlopen("liblgrp.so.1", RTLD_LAZY);
4073   if (handle != NULL) {
4074     os::Solaris::set_lgrp_home(CAST_TO_FN_PTR(lgrp_home_func_t, dlsym(handle, "lgrp_home")));
4075     os::Solaris::set_lgrp_init(CAST_TO_FN_PTR(lgrp_init_func_t, dlsym(handle, "lgrp_init")));
4076     os::Solaris::set_lgrp_fini(CAST_TO_FN_PTR(lgrp_fini_func_t, dlsym(handle, "lgrp_fini")));
4077     os::Solaris::set_lgrp_root(CAST_TO_FN_PTR(lgrp_root_func_t, dlsym(handle, "lgrp_root")));
4078     os::Solaris::set_lgrp_children(CAST_TO_FN_PTR(lgrp_children_func_t, dlsym(handle, "lgrp_children")));
4079     os::Solaris::set_lgrp_resources(CAST_TO_FN_PTR(lgrp_resources_func_t, dlsym(handle, "lgrp_resources")));
4080     os::Solaris::set_lgrp_nlgrps(CAST_TO_FN_PTR(lgrp_nlgrps_func_t, dlsym(handle, "lgrp_nlgrps")));
4081     os::Solaris::set_lgrp_cookie_stale(CAST_TO_FN_PTR(lgrp_cookie_stale_func_t,
4082                                                       dlsym(handle, "lgrp_cookie_stale")));
4083 
4084     lgrp_cookie_t c = lgrp_init(LGRP_VIEW_CALLER);
4085     set_lgrp_cookie(c);
4086     return true;
4087   }
4088   return false;
4089 }
4090 
4091 // int pset_getloadavg(psetid_t pset, double loadavg[], int nelem);
4092 typedef long (*pset_getloadavg_type)(psetid_t pset, double loadavg[], int nelem);
4093 static pset_getloadavg_type pset_getloadavg_ptr = NULL;
4094 
4095 void init_pset_getloadavg_ptr(void) {
4096   pset_getloadavg_ptr =
4097     (pset_getloadavg_type)dlsym(RTLD_DEFAULT, "pset_getloadavg");
4098   if (pset_getloadavg_ptr == NULL) {
4099     log_warning(os)("pset_getloadavg function not found");
4100   }
4101 }
4102 
4103 int os::Solaris::_dev_zero_fd = -1;
4104 
4105 // this is called _before_ the global arguments have been parsed
4106 void os::init(void) {
4107   _initial_pid = getpid();
4108 
4109   max_hrtime = first_hrtime = gethrtime();
4110 
4111   init_random(1234567);
4112 
4113   page_size = sysconf(_SC_PAGESIZE);
4114   if (page_size == -1) {
4115     fatal("os_solaris.cpp: os::init: sysconf failed (%s)", os::strerror(errno));
4116   }
4117   init_page_sizes((size_t) page_size);
4118 
4119   Solaris::initialize_system_info();
4120 
4121   int fd = ::open("/dev/zero", O_RDWR);
4122   if (fd < 0) {
4123     fatal("os::init: cannot open /dev/zero (%s)", os::strerror(errno));
4124   } else {
4125     Solaris::set_dev_zero_fd(fd);
4126 
4127     // Close on exec, child won't inherit.
4128     fcntl(fd, F_SETFD, FD_CLOEXEC);
4129   }
4130 
4131   clock_tics_per_sec = CLK_TCK;
4132 
4133   // check if dladdr1() exists; dladdr1 can provide more information than
4134   // dladdr for os::dll_address_to_function_name. It comes with SunOS 5.9
4135   // and is available on linker patches for 5.7 and 5.8.
4136   // libdl.so must have been loaded, this call is just an entry lookup
4137   void * hdl = dlopen("libdl.so", RTLD_NOW);
4138   if (hdl) {
4139     dladdr1_func = CAST_TO_FN_PTR(dladdr1_func_type, dlsym(hdl, "dladdr1"));
4140   }
4141 
4142   // main_thread points to the thread that created/loaded the JVM.
4143   main_thread = thr_self();
4144 
4145   // dynamic lookup of functions that may not be available in our lowest
4146   // supported Solaris release
4147   void * handle = dlopen("libc.so.1", RTLD_LAZY);
4148   if (handle != NULL) {
4149     Solaris::_pthread_setname_np =  // from 11.3
4150         (Solaris::pthread_setname_np_func_t)dlsym(handle, "pthread_setname_np");
4151   }
4152 }
4153 
4154 // To install functions for atexit system call
4155 extern "C" {
4156   static void perfMemory_exit_helper() {
4157     perfMemory_exit();
4158   }
4159 }
4160 
4161 // this is called _after_ the global arguments have been parsed
4162 jint os::init_2(void) {
4163   // try to enable extended file IO ASAP, see 6431278
4164   os::Solaris::try_enable_extended_io();
4165 
4166   // Check and sets minimum stack sizes against command line options
4167   if (Posix::set_minimum_stack_sizes() == JNI_ERR) {
4168     return JNI_ERR;
4169   }
4170 
4171   Solaris::libthread_init();
4172 
4173   if (UseNUMA) {
4174     if (!Solaris::liblgrp_init()) {
4175       UseNUMA = false;
4176     } else {
4177       size_t lgrp_limit = os::numa_get_groups_num();
4178       int *lgrp_ids = NEW_C_HEAP_ARRAY(int, lgrp_limit, mtInternal);
4179       size_t lgrp_num = os::numa_get_leaf_groups(lgrp_ids, lgrp_limit);
4180       FREE_C_HEAP_ARRAY(int, lgrp_ids);
4181       if (lgrp_num < 2) {
4182         // There's only one locality group, disable NUMA.
4183         UseNUMA = false;
4184       }
4185     }
4186     if (!UseNUMA && ForceNUMA) {
4187       UseNUMA = true;
4188     }
4189   }
4190 
4191   Solaris::signal_sets_init();
4192   Solaris::init_signal_mem();
4193   Solaris::install_signal_handlers();
4194   // Initialize data for jdk.internal.misc.Signal
4195   if (!ReduceSignalUsage) {
4196     jdk_misc_signal_init();
4197   }
4198 
4199   // initialize synchronization primitives to use either thread or
4200   // lwp synchronization (controlled by UseLWPSynchronization)
4201   Solaris::synchronization_init();
4202   DEBUG_ONLY(os::set_mutex_init_done();)
4203 
4204   if (MaxFDLimit) {
4205     // set the number of file descriptors to max. print out error
4206     // if getrlimit/setrlimit fails but continue regardless.
4207     struct rlimit nbr_files;
4208     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
4209     if (status != 0) {
4210       log_info(os)("os::init_2 getrlimit failed: %s", os::strerror(errno));
4211     } else {
4212       nbr_files.rlim_cur = nbr_files.rlim_max;
4213       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
4214       if (status != 0) {
4215         log_info(os)("os::init_2 setrlimit failed: %s", os::strerror(errno));
4216       }
4217     }
4218   }
4219 
4220   // Calculate theoretical max. size of Threads to guard gainst
4221   // artifical out-of-memory situations, where all available address-
4222   // space has been reserved by thread stacks. Default stack size is 1Mb.
4223   size_t pre_thread_stack_size = (JavaThread::stack_size_at_create()) ?
4224     JavaThread::stack_size_at_create() : (1*K*K);
4225   assert(pre_thread_stack_size != 0, "Must have a stack");
4226   // Solaris has a maximum of 4Gb of user programs. Calculate the thread limit when
4227   // we should start doing Virtual Memory banging. Currently when the threads will
4228   // have used all but 200Mb of space.
4229   size_t max_address_space = ((unsigned int)4 * K * K * K) - (200 * K * K);
4230   Solaris::_os_thread_limit = max_address_space / pre_thread_stack_size;
4231 
4232   // at-exit methods are called in the reverse order of their registration.
4233   // In Solaris 7 and earlier, atexit functions are called on return from
4234   // main or as a result of a call to exit(3C). There can be only 32 of
4235   // these functions registered and atexit() does not set errno. In Solaris
4236   // 8 and later, there is no limit to the number of functions registered
4237   // and atexit() sets errno. In addition, in Solaris 8 and later, atexit
4238   // functions are called upon dlclose(3DL) in addition to return from main
4239   // and exit(3C).
4240 
4241   if (PerfAllowAtExitRegistration) {
4242     // only register atexit functions if PerfAllowAtExitRegistration is set.
4243     // atexit functions can be delayed until process exit time, which
4244     // can be problematic for embedded VM situations. Embedded VMs should
4245     // call DestroyJavaVM() to assure that VM resources are released.
4246 
4247     // note: perfMemory_exit_helper atexit function may be removed in
4248     // the future if the appropriate cleanup code can be added to the
4249     // VM_Exit VMOperation's doit method.
4250     if (atexit(perfMemory_exit_helper) != 0) {
4251       warning("os::init2 atexit(perfMemory_exit_helper) failed");
4252     }
4253   }
4254 
4255   // Init pset_loadavg function pointer
4256   init_pset_getloadavg_ptr();
4257 
4258   return JNI_OK;
4259 }
4260 
4261 // Mark the polling page as unreadable
4262 void os::make_polling_page_unreadable(void) {
4263   if (mprotect((char *)_polling_page, page_size, PROT_NONE) != 0) {
4264     fatal("Could not disable polling page");
4265   }
4266 }
4267 
4268 // Mark the polling page as readable
4269 void os::make_polling_page_readable(void) {
4270   if (mprotect((char *)_polling_page, page_size, PROT_READ) != 0) {
4271     fatal("Could not enable polling page");
4272   }
4273 }
4274 
4275 // Is a (classpath) directory empty?
4276 bool os::dir_is_empty(const char* path) {
4277   DIR *dir = NULL;
4278   struct dirent *ptr;
4279 
4280   dir = opendir(path);
4281   if (dir == NULL) return true;
4282 
4283   // Scan the directory
4284   bool result = true;
4285   while (result && (ptr = readdir(dir)) != NULL) {
4286     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
4287       result = false;
4288     }
4289   }
4290   closedir(dir);
4291   return result;
4292 }
4293 
4294 // This code originates from JDK's sysOpen and open64_w
4295 // from src/solaris/hpi/src/system_md.c
4296 
4297 int os::open(const char *path, int oflag, int mode) {
4298   if (strlen(path) > MAX_PATH - 1) {
4299     errno = ENAMETOOLONG;
4300     return -1;
4301   }
4302   int fd;
4303 
4304   fd = ::open64(path, oflag, mode);
4305   if (fd == -1) return -1;
4306 
4307   // If the open succeeded, the file might still be a directory
4308   {
4309     struct stat64 buf64;
4310     int ret = ::fstat64(fd, &buf64);
4311     int st_mode = buf64.st_mode;
4312 
4313     if (ret != -1) {
4314       if ((st_mode & S_IFMT) == S_IFDIR) {
4315         errno = EISDIR;
4316         ::close(fd);
4317         return -1;
4318       }
4319     } else {
4320       ::close(fd);
4321       return -1;
4322     }
4323   }
4324 
4325   // 32-bit Solaris systems suffer from:
4326   //
4327   // - an historical default soft limit of 256 per-process file
4328   //   descriptors that is too low for many Java programs.
4329   //
4330   // - a design flaw where file descriptors created using stdio
4331   //   fopen must be less than 256, _even_ when the first limit above
4332   //   has been raised.  This can cause calls to fopen (but not calls to
4333   //   open, for example) to fail mysteriously, perhaps in 3rd party
4334   //   native code (although the JDK itself uses fopen).  One can hardly
4335   //   criticize them for using this most standard of all functions.
4336   //
4337   // We attempt to make everything work anyways by:
4338   //
4339   // - raising the soft limit on per-process file descriptors beyond
4340   //   256
4341   //
4342   // - As of Solaris 10u4, we can request that Solaris raise the 256
4343   //   stdio fopen limit by calling function enable_extended_FILE_stdio.
4344   //   This is done in init_2 and recorded in enabled_extended_FILE_stdio
4345   //
4346   // - If we are stuck on an old (pre 10u4) Solaris system, we can
4347   //   workaround the bug by remapping non-stdio file descriptors below
4348   //   256 to ones beyond 256, which is done below.
4349   //
4350   // See:
4351   // 1085341: 32-bit stdio routines should support file descriptors >255
4352   // 6533291: Work around 32-bit Solaris stdio limit of 256 open files
4353   // 6431278: Netbeans crash on 32 bit Solaris: need to call
4354   //          enable_extended_FILE_stdio() in VM initialisation
4355   // Giri Mandalika's blog
4356   // http://technopark02.blogspot.com/2005_05_01_archive.html
4357   //
4358 #ifndef  _LP64
4359   if ((!enabled_extended_FILE_stdio) && fd < 256) {
4360     int newfd = ::fcntl(fd, F_DUPFD, 256);
4361     if (newfd != -1) {
4362       ::close(fd);
4363       fd = newfd;
4364     }
4365   }
4366 #endif // 32-bit Solaris
4367 
4368   // All file descriptors that are opened in the JVM and not
4369   // specifically destined for a subprocess should have the
4370   // close-on-exec flag set.  If we don't set it, then careless 3rd
4371   // party native code might fork and exec without closing all
4372   // appropriate file descriptors (e.g. as we do in closeDescriptors in
4373   // UNIXProcess.c), and this in turn might:
4374   //
4375   // - cause end-of-file to fail to be detected on some file
4376   //   descriptors, resulting in mysterious hangs, or
4377   //
4378   // - might cause an fopen in the subprocess to fail on a system
4379   //   suffering from bug 1085341.
4380   //
4381   // (Yes, the default setting of the close-on-exec flag is a Unix
4382   // design flaw)
4383   //
4384   // See:
4385   // 1085341: 32-bit stdio routines should support file descriptors >255
4386   // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
4387   // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
4388   //
4389 #ifdef FD_CLOEXEC
4390   {
4391     int flags = ::fcntl(fd, F_GETFD);
4392     if (flags != -1) {
4393       ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4394     }
4395   }
4396 #endif
4397 
4398   return fd;
4399 }
4400 
4401 // create binary file, rewriting existing file if required
4402 int os::create_binary_file(const char* path, bool rewrite_existing) {
4403   int oflags = O_WRONLY | O_CREAT;
4404   if (!rewrite_existing) {
4405     oflags |= O_EXCL;
4406   }
4407   return ::open64(path, oflags, S_IREAD | S_IWRITE);
4408 }
4409 
4410 // return current position of file pointer
4411 jlong os::current_file_offset(int fd) {
4412   return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
4413 }
4414 
4415 // move file pointer to the specified offset
4416 jlong os::seek_to_file_offset(int fd, jlong offset) {
4417   return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
4418 }
4419 
4420 jlong os::lseek(int fd, jlong offset, int whence) {
4421   return (jlong) ::lseek64(fd, offset, whence);
4422 }
4423 
4424 int os::ftruncate(int fd, jlong length) {
4425   return ::ftruncate64(fd, length);
4426 }
4427 
4428 int os::fsync(int fd)  {
4429   RESTARTABLE_RETURN_INT(::fsync(fd));
4430 }
4431 
4432 int os::available(int fd, jlong *bytes) {
4433   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
4434          "Assumed _thread_in_native");
4435   jlong cur, end;
4436   int mode;
4437   struct stat64 buf64;
4438 
4439   if (::fstat64(fd, &buf64) >= 0) {
4440     mode = buf64.st_mode;
4441     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
4442       int n,ioctl_return;
4443 
4444       RESTARTABLE(::ioctl(fd, FIONREAD, &n), ioctl_return);
4445       if (ioctl_return>= 0) {
4446         *bytes = n;
4447         return 1;
4448       }
4449     }
4450   }
4451   if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
4452     return 0;
4453   } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
4454     return 0;
4455   } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
4456     return 0;
4457   }
4458   *bytes = end - cur;
4459   return 1;
4460 }
4461 
4462 // Map a block of memory.
4463 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
4464                         char *addr, size_t bytes, bool read_only,
4465                         bool allow_exec) {
4466   int prot;
4467   int flags;
4468 
4469   if (read_only) {
4470     prot = PROT_READ;
4471     flags = MAP_SHARED;
4472   } else {
4473     prot = PROT_READ | PROT_WRITE;
4474     flags = MAP_PRIVATE;
4475   }
4476 
4477   if (allow_exec) {
4478     prot |= PROT_EXEC;
4479   }
4480 
4481   if (addr != NULL) {
4482     flags |= MAP_FIXED;
4483   }
4484 
4485   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
4486                                      fd, file_offset);
4487   if (mapped_address == MAP_FAILED) {
4488     return NULL;
4489   }
4490   return mapped_address;
4491 }
4492 
4493 
4494 // Remap a block of memory.
4495 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
4496                           char *addr, size_t bytes, bool read_only,
4497                           bool allow_exec) {
4498   // same as map_memory() on this OS
4499   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
4500                         allow_exec);
4501 }
4502 
4503 
4504 // Unmap a block of memory.
4505 bool os::pd_unmap_memory(char* addr, size_t bytes) {
4506   return munmap(addr, bytes) == 0;
4507 }
4508 
4509 void os::pause() {
4510   char filename[MAX_PATH];
4511   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
4512     jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
4513   } else {
4514     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
4515   }
4516 
4517   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
4518   if (fd != -1) {
4519     struct stat buf;
4520     ::close(fd);
4521     while (::stat(filename, &buf) == 0) {
4522       (void)::poll(NULL, 0, 100);
4523     }
4524   } else {
4525     jio_fprintf(stderr,
4526                 "Could not open pause file '%s', continuing immediately.\n", filename);
4527   }
4528 }
4529 
4530 #ifndef PRODUCT
4531 #ifdef INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS
4532 // Turn this on if you need to trace synch operations.
4533 // Set RECORD_SYNCH_LIMIT to a large-enough value,
4534 // and call record_synch_enable and record_synch_disable
4535 // around the computation of interest.
4536 
4537 void record_synch(char* name, bool returning);  // defined below
4538 
4539 class RecordSynch {
4540   char* _name;
4541  public:
4542   RecordSynch(char* name) :_name(name) { record_synch(_name, false); }
4543   ~RecordSynch()                       { record_synch(_name, true); }
4544 };
4545 
4546 #define CHECK_SYNCH_OP(ret, name, params, args, inner)          \
4547 extern "C" ret name params {                                    \
4548   typedef ret name##_t params;                                  \
4549   static name##_t* implem = NULL;                               \
4550   static int callcount = 0;                                     \
4551   if (implem == NULL) {                                         \
4552     implem = (name##_t*) dlsym(RTLD_NEXT, #name);               \
4553     if (implem == NULL)  fatal(dlerror());                      \
4554   }                                                             \
4555   ++callcount;                                                  \
4556   RecordSynch _rs(#name);                                       \
4557   inner;                                                        \
4558   return implem args;                                           \
4559 }
4560 // in dbx, examine callcounts this way:
4561 // for n in $(eval whereis callcount | awk '{print $2}'); do print $n; done
4562 
4563 #define CHECK_POINTER_OK(p) \
4564   (!Universe::is_fully_initialized() || !Universe::is_reserved_heap((oop)(p)))
4565 #define CHECK_MU \
4566   if (!CHECK_POINTER_OK(mu)) fatal("Mutex must be in C heap only.");
4567 #define CHECK_CV \
4568   if (!CHECK_POINTER_OK(cv)) fatal("Condvar must be in C heap only.");
4569 #define CHECK_P(p) \
4570   if (!CHECK_POINTER_OK(p))  fatal(false,  "Pointer must be in C heap only.");
4571 
4572 #define CHECK_MUTEX(mutex_op) \
4573   CHECK_SYNCH_OP(int, mutex_op, (mutex_t *mu), (mu), CHECK_MU);
4574 
4575 CHECK_MUTEX(   mutex_lock)
4576 CHECK_MUTEX(  _mutex_lock)
4577 CHECK_MUTEX( mutex_unlock)
4578 CHECK_MUTEX(_mutex_unlock)
4579 CHECK_MUTEX( mutex_trylock)
4580 CHECK_MUTEX(_mutex_trylock)
4581 
4582 #define CHECK_COND(cond_op) \
4583   CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu), (cv, mu), CHECK_MU; CHECK_CV);
4584 
4585 CHECK_COND( cond_wait);
4586 CHECK_COND(_cond_wait);
4587 CHECK_COND(_cond_wait_cancel);
4588 
4589 #define CHECK_COND2(cond_op) \
4590   CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu, timestruc_t* ts), (cv, mu, ts), CHECK_MU; CHECK_CV);
4591 
4592 CHECK_COND2( cond_timedwait);
4593 CHECK_COND2(_cond_timedwait);
4594 CHECK_COND2(_cond_timedwait_cancel);
4595 
4596 // do the _lwp_* versions too
4597 #define mutex_t lwp_mutex_t
4598 #define cond_t  lwp_cond_t
4599 CHECK_MUTEX(  _lwp_mutex_lock)
4600 CHECK_MUTEX(  _lwp_mutex_unlock)
4601 CHECK_MUTEX(  _lwp_mutex_trylock)
4602 CHECK_MUTEX( __lwp_mutex_lock)
4603 CHECK_MUTEX( __lwp_mutex_unlock)
4604 CHECK_MUTEX( __lwp_mutex_trylock)
4605 CHECK_MUTEX(___lwp_mutex_lock)
4606 CHECK_MUTEX(___lwp_mutex_unlock)
4607 
4608 CHECK_COND(  _lwp_cond_wait);
4609 CHECK_COND( __lwp_cond_wait);
4610 CHECK_COND(___lwp_cond_wait);
4611 
4612 CHECK_COND2(  _lwp_cond_timedwait);
4613 CHECK_COND2( __lwp_cond_timedwait);
4614 #undef mutex_t
4615 #undef cond_t
4616 
4617 CHECK_SYNCH_OP(int, _lwp_suspend2,       (int lwp, int *n), (lwp, n), 0);
4618 CHECK_SYNCH_OP(int,__lwp_suspend2,       (int lwp, int *n), (lwp, n), 0);
4619 CHECK_SYNCH_OP(int, _lwp_kill,           (int lwp, int n),  (lwp, n), 0);
4620 CHECK_SYNCH_OP(int,__lwp_kill,           (int lwp, int n),  (lwp, n), 0);
4621 CHECK_SYNCH_OP(int, _lwp_sema_wait,      (lwp_sema_t* p),   (p),  CHECK_P(p));
4622 CHECK_SYNCH_OP(int,__lwp_sema_wait,      (lwp_sema_t* p),   (p),  CHECK_P(p));
4623 CHECK_SYNCH_OP(int, _lwp_cond_broadcast, (lwp_cond_t* cv),  (cv), CHECK_CV);
4624 CHECK_SYNCH_OP(int,__lwp_cond_broadcast, (lwp_cond_t* cv),  (cv), CHECK_CV);
4625 
4626 
4627 // recording machinery:
4628 
4629 enum { RECORD_SYNCH_LIMIT = 200 };
4630 char* record_synch_name[RECORD_SYNCH_LIMIT];
4631 void* record_synch_arg0ptr[RECORD_SYNCH_LIMIT];
4632 bool record_synch_returning[RECORD_SYNCH_LIMIT];
4633 thread_t record_synch_thread[RECORD_SYNCH_LIMIT];
4634 int record_synch_count = 0;
4635 bool record_synch_enabled = false;
4636 
4637 // in dbx, examine recorded data this way:
4638 // for n in name arg0ptr returning thread; do print record_synch_$n[0..record_synch_count-1]; done
4639 
4640 void record_synch(char* name, bool returning) {
4641   if (record_synch_enabled) {
4642     if (record_synch_count < RECORD_SYNCH_LIMIT) {
4643       record_synch_name[record_synch_count] = name;
4644       record_synch_returning[record_synch_count] = returning;
4645       record_synch_thread[record_synch_count] = thr_self();
4646       record_synch_arg0ptr[record_synch_count] = &name;
4647       record_synch_count++;
4648     }
4649     // put more checking code here:
4650     // ...
4651   }
4652 }
4653 
4654 void record_synch_enable() {
4655   // start collecting trace data, if not already doing so
4656   if (!record_synch_enabled)  record_synch_count = 0;
4657   record_synch_enabled = true;
4658 }
4659 
4660 void record_synch_disable() {
4661   // stop collecting trace data
4662   record_synch_enabled = false;
4663 }
4664 
4665 #endif // INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS
4666 #endif // PRODUCT
4667 
4668 const intptr_t thr_time_off  = (intptr_t)(&((prusage_t *)(NULL))->pr_utime);
4669 const intptr_t thr_time_size = (intptr_t)(&((prusage_t *)(NULL))->pr_ttime) -
4670                                (intptr_t)(&((prusage_t *)(NULL))->pr_utime);
4671 
4672 
4673 // JVMTI & JVM monitoring and management support
4674 // The thread_cpu_time() and current_thread_cpu_time() are only
4675 // supported if is_thread_cpu_time_supported() returns true.
4676 // They are not supported on Solaris T1.
4677 
4678 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
4679 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
4680 // of a thread.
4681 //
4682 // current_thread_cpu_time() and thread_cpu_time(Thread *)
4683 // returns the fast estimate available on the platform.
4684 
4685 // hrtime_t gethrvtime() return value includes
4686 // user time but does not include system time
4687 jlong os::current_thread_cpu_time() {
4688   return (jlong) gethrvtime();
4689 }
4690 
4691 jlong os::thread_cpu_time(Thread *thread) {
4692   // return user level CPU time only to be consistent with
4693   // what current_thread_cpu_time returns.
4694   // thread_cpu_time_info() must be changed if this changes
4695   return os::thread_cpu_time(thread, false /* user time only */);
4696 }
4697 
4698 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
4699   if (user_sys_cpu_time) {
4700     return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
4701   } else {
4702     return os::current_thread_cpu_time();
4703   }
4704 }
4705 
4706 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
4707   char proc_name[64];
4708   int count;
4709   prusage_t prusage;
4710   jlong lwp_time;
4711   int fd;
4712 
4713   sprintf(proc_name, "/proc/%d/lwp/%d/lwpusage",
4714           getpid(),
4715           thread->osthread()->lwp_id());
4716   fd = ::open(proc_name, O_RDONLY);
4717   if (fd == -1) return -1;
4718 
4719   do {
4720     count = ::pread(fd,
4721                     (void *)&prusage.pr_utime,
4722                     thr_time_size,
4723                     thr_time_off);
4724   } while (count < 0 && errno == EINTR);
4725   ::close(fd);
4726   if (count < 0) return -1;
4727 
4728   if (user_sys_cpu_time) {
4729     // user + system CPU time
4730     lwp_time = (((jlong)prusage.pr_stime.tv_sec +
4731                  (jlong)prusage.pr_utime.tv_sec) * (jlong)1000000000) +
4732                  (jlong)prusage.pr_stime.tv_nsec +
4733                  (jlong)prusage.pr_utime.tv_nsec;
4734   } else {
4735     // user level CPU time only
4736     lwp_time = ((jlong)prusage.pr_utime.tv_sec * (jlong)1000000000) +
4737                 (jlong)prusage.pr_utime.tv_nsec;
4738   }
4739 
4740   return (lwp_time);
4741 }
4742 
4743 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4744   info_ptr->max_value = ALL_64_BITS;      // will not wrap in less than 64 bits
4745   info_ptr->may_skip_backward = false;    // elapsed time not wall time
4746   info_ptr->may_skip_forward = false;     // elapsed time not wall time
4747   info_ptr->kind = JVMTI_TIMER_USER_CPU;  // only user time is returned
4748 }
4749 
4750 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
4751   info_ptr->max_value = ALL_64_BITS;      // will not wrap in less than 64 bits
4752   info_ptr->may_skip_backward = false;    // elapsed time not wall time
4753   info_ptr->may_skip_forward = false;     // elapsed time not wall time
4754   info_ptr->kind = JVMTI_TIMER_USER_CPU;  // only user time is returned
4755 }
4756 
4757 bool os::is_thread_cpu_time_supported() {
4758   return true;
4759 }
4760 
4761 // System loadavg support.  Returns -1 if load average cannot be obtained.
4762 // Return the load average for our processor set if the primitive exists
4763 // (Solaris 9 and later).  Otherwise just return system wide loadavg.
4764 int os::loadavg(double loadavg[], int nelem) {
4765   if (pset_getloadavg_ptr != NULL) {
4766     return (*pset_getloadavg_ptr)(PS_MYID, loadavg, nelem);
4767   } else {
4768     return ::getloadavg(loadavg, nelem);
4769   }
4770 }
4771 
4772 //---------------------------------------------------------------------------------
4773 
4774 bool os::find(address addr, outputStream* st) {
4775   Dl_info dlinfo;
4776   memset(&dlinfo, 0, sizeof(dlinfo));
4777   if (dladdr(addr, &dlinfo) != 0) {
4778     st->print(PTR_FORMAT ": ", addr);
4779     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
4780       st->print("%s+%#lx", dlinfo.dli_sname, addr-(intptr_t)dlinfo.dli_saddr);
4781     } else if (dlinfo.dli_fbase != NULL) {
4782       st->print("<offset %#lx>", addr-(intptr_t)dlinfo.dli_fbase);
4783     } else {
4784       st->print("<absolute address>");
4785     }
4786     if (dlinfo.dli_fname != NULL) {
4787       st->print(" in %s", dlinfo.dli_fname);
4788     }
4789     if (dlinfo.dli_fbase != NULL) {
4790       st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
4791     }
4792     st->cr();
4793 
4794     if (Verbose) {
4795       // decode some bytes around the PC
4796       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
4797       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
4798       address       lowest = (address) dlinfo.dli_sname;
4799       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
4800       if (begin < lowest)  begin = lowest;
4801       Dl_info dlinfo2;
4802       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
4803           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
4804         end = (address) dlinfo2.dli_saddr;
4805       }
4806       Disassembler::decode(begin, end, st);
4807     }
4808     return true;
4809   }
4810   return false;
4811 }
4812 
4813 // Following function has been added to support HotSparc's libjvm.so running
4814 // under Solaris production JDK 1.2.2 / 1.3.0.  These came from
4815 // src/solaris/hpi/native_threads in the EVM codebase.
4816 //
4817 // NOTE: This is no longer needed in the 1.3.1 and 1.4 production release
4818 // libraries and should thus be removed. We will leave it behind for a while
4819 // until we no longer want to able to run on top of 1.3.0 Solaris production
4820 // JDK. See 4341971.
4821 
4822 #define STACK_SLACK 0x800
4823 
4824 extern "C" {
4825   intptr_t sysThreadAvailableStackWithSlack() {
4826     stack_t st;
4827     intptr_t retval, stack_top;
4828     retval = thr_stksegment(&st);
4829     assert(retval == 0, "incorrect return value from thr_stksegment");
4830     assert((address)&st < (address)st.ss_sp, "Invalid stack base returned");
4831     assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned");
4832     stack_top=(intptr_t)st.ss_sp-st.ss_size;
4833     return ((intptr_t)&stack_top - stack_top - STACK_SLACK);
4834   }
4835 }
4836 
4837 // ObjectMonitor park-unpark infrastructure ...
4838 //
4839 // We implement Solaris and Linux PlatformEvents with the
4840 // obvious condvar-mutex-flag triple.
4841 // Another alternative that works quite well is pipes:
4842 // Each PlatformEvent consists of a pipe-pair.
4843 // The thread associated with the PlatformEvent
4844 // calls park(), which reads from the input end of the pipe.
4845 // Unpark() writes into the other end of the pipe.
4846 // The write-side of the pipe must be set NDELAY.
4847 // Unfortunately pipes consume a large # of handles.
4848 // Native solaris lwp_park() and lwp_unpark() work nicely, too.
4849 // Using pipes for the 1st few threads might be workable, however.
4850 //
4851 // park() is permitted to return spuriously.
4852 // Callers of park() should wrap the call to park() in
4853 // an appropriate loop.  A litmus test for the correct
4854 // usage of park is the following: if park() were modified
4855 // to immediately return 0 your code should still work,
4856 // albeit degenerating to a spin loop.
4857 //
4858 // In a sense, park()-unpark() just provides more polite spinning
4859 // and polling with the key difference over naive spinning being
4860 // that a parked thread needs to be explicitly unparked() in order
4861 // to wake up and to poll the underlying condition.
4862 //
4863 // Assumption:
4864 //    Only one parker can exist on an event, which is why we allocate
4865 //    them per-thread. Multiple unparkers can coexist.
4866 //
4867 // _Event transitions in park()
4868 //   -1 => -1 : illegal
4869 //    1 =>  0 : pass - return immediately
4870 //    0 => -1 : block; then set _Event to 0 before returning
4871 //
4872 // _Event transitions in unpark()
4873 //    0 => 1 : just return
4874 //    1 => 1 : just return
4875 //   -1 => either 0 or 1; must signal target thread
4876 //         That is, we can safely transition _Event from -1 to either
4877 //         0 or 1.
4878 //
4879 // _Event serves as a restricted-range semaphore.
4880 //   -1 : thread is blocked, i.e. there is a waiter
4881 //    0 : neutral: thread is running or ready,
4882 //        could have been signaled after a wait started
4883 //    1 : signaled - thread is running or ready
4884 //
4885 // Another possible encoding of _Event would be with
4886 // explicit "PARKED" == 01b and "SIGNALED" == 10b bits.
4887 //
4888 // TODO-FIXME: add DTRACE probes for:
4889 // 1.   Tx parks
4890 // 2.   Ty unparks Tx
4891 // 3.   Tx resumes from park
4892 
4893 
4894 // value determined through experimentation
4895 #define ROUNDINGFIX 11
4896 
4897 // utility to compute the abstime argument to timedwait.
4898 // TODO-FIXME: switch from compute_abstime() to unpackTime().
4899 
4900 static timestruc_t* compute_abstime(timestruc_t* abstime, jlong millis) {
4901   // millis is the relative timeout time
4902   // abstime will be the absolute timeout time
4903   if (millis < 0)  millis = 0;
4904   struct timeval now;
4905   int status = gettimeofday(&now, NULL);
4906   assert(status == 0, "gettimeofday");
4907   jlong seconds = millis / 1000;
4908   jlong max_wait_period;
4909 
4910   if (UseLWPSynchronization) {
4911     // forward port of fix for 4275818 (not sleeping long enough)
4912     // There was a bug in Solaris 6, 7 and pre-patch 5 of 8 where
4913     // _lwp_cond_timedwait() used a round_down algorithm rather
4914     // than a round_up. For millis less than our roundfactor
4915     // it rounded down to 0 which doesn't meet the spec.
4916     // For millis > roundfactor we may return a bit sooner, but
4917     // since we can not accurately identify the patch level and
4918     // this has already been fixed in Solaris 9 and 8 we will
4919     // leave it alone rather than always rounding down.
4920 
4921     if (millis > 0 && millis < ROUNDINGFIX) millis = ROUNDINGFIX;
4922     // It appears that when we go directly through Solaris _lwp_cond_timedwait()
4923     // the acceptable max time threshold is smaller than for libthread on 2.5.1 and 2.6
4924     max_wait_period = 21000000;
4925   } else {
4926     max_wait_period = 50000000;
4927   }
4928   millis %= 1000;
4929   if (seconds > max_wait_period) {      // see man cond_timedwait(3T)
4930     seconds = max_wait_period;
4931   }
4932   abstime->tv_sec = now.tv_sec  + seconds;
4933   long       usec = now.tv_usec + millis * 1000;
4934   if (usec >= 1000000) {
4935     abstime->tv_sec += 1;
4936     usec -= 1000000;
4937   }
4938   abstime->tv_nsec = usec * 1000;
4939   return abstime;
4940 }
4941 
4942 void os::PlatformEvent::park() {           // AKA: down()
4943   // Transitions for _Event:
4944   //   -1 => -1 : illegal
4945   //    1 =>  0 : pass - return immediately
4946   //    0 => -1 : block; then set _Event to 0 before returning
4947 
4948   // Invariant: Only the thread associated with the Event/PlatformEvent
4949   // may call park().
4950   assert(_nParked == 0, "invariant");
4951 
4952   int v;
4953   for (;;) {
4954     v = _Event;
4955     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
4956   }
4957   guarantee(v >= 0, "invariant");
4958   if (v == 0) {
4959     // Do this the hard way by blocking ...
4960     // See http://monaco.sfbay/detail.jsf?cr=5094058.
4961     int status = os::Solaris::mutex_lock(_mutex);
4962     assert_status(status == 0, status, "mutex_lock");
4963     guarantee(_nParked == 0, "invariant");
4964     ++_nParked;
4965     while (_Event < 0) {
4966       // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
4967       // Treat this the same as if the wait was interrupted
4968       // With usr/lib/lwp going to kernel, always handle ETIME
4969       status = os::Solaris::cond_wait(_cond, _mutex);
4970       if (status == ETIME) status = EINTR;
4971       assert_status(status == 0 || status == EINTR, status, "cond_wait");
4972     }
4973     --_nParked;
4974     _Event = 0;
4975     status = os::Solaris::mutex_unlock(_mutex);
4976     assert_status(status == 0, status, "mutex_unlock");
4977     // Paranoia to ensure our locked and lock-free paths interact
4978     // correctly with each other.
4979     OrderAccess::fence();
4980   }
4981 }
4982 
4983 int os::PlatformEvent::park(jlong millis) {
4984   // Transitions for _Event:
4985   //   -1 => -1 : illegal
4986   //    1 =>  0 : pass - return immediately
4987   //    0 => -1 : block; then set _Event to 0 before returning
4988 
4989   guarantee(_nParked == 0, "invariant");
4990   int v;
4991   for (;;) {
4992     v = _Event;
4993     if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
4994   }
4995   guarantee(v >= 0, "invariant");
4996   if (v != 0) return OS_OK;
4997 
4998   int ret = OS_TIMEOUT;
4999   timestruc_t abst;
5000   compute_abstime(&abst, millis);
5001 
5002   // See http://monaco.sfbay/detail.jsf?cr=5094058.
5003   int status = os::Solaris::mutex_lock(_mutex);
5004   assert_status(status == 0, status, "mutex_lock");
5005   guarantee(_nParked == 0, "invariant");
5006   ++_nParked;
5007   while (_Event < 0) {
5008     int status = os::Solaris::cond_timedwait(_cond, _mutex, &abst);
5009     assert_status(status == 0 || status == EINTR ||
5010                   status == ETIME || status == ETIMEDOUT,
5011                   status, "cond_timedwait");
5012     if (!FilterSpuriousWakeups) break;                // previous semantics
5013     if (status == ETIME || status == ETIMEDOUT) break;
5014     // We consume and ignore EINTR and spurious wakeups.
5015   }
5016   --_nParked;
5017   if (_Event >= 0) ret = OS_OK;
5018   _Event = 0;
5019   status = os::Solaris::mutex_unlock(_mutex);
5020   assert_status(status == 0, status, "mutex_unlock");
5021   // Paranoia to ensure our locked and lock-free paths interact
5022   // correctly with each other.
5023   OrderAccess::fence();
5024   return ret;
5025 }
5026 
5027 void os::PlatformEvent::unpark() {
5028   // Transitions for _Event:
5029   //    0 => 1 : just return
5030   //    1 => 1 : just return
5031   //   -1 => either 0 or 1; must signal target thread
5032   //         That is, we can safely transition _Event from -1 to either
5033   //         0 or 1.
5034   // See also: "Semaphores in Plan 9" by Mullender & Cox
5035   //
5036   // Note: Forcing a transition from "-1" to "1" on an unpark() means
5037   // that it will take two back-to-back park() calls for the owning
5038   // thread to block. This has the benefit of forcing a spurious return
5039   // from the first park() call after an unpark() call which will help
5040   // shake out uses of park() and unpark() without condition variables.
5041 
5042   if (Atomic::xchg(1, &_Event) >= 0) return;
5043 
5044   // If the thread associated with the event was parked, wake it.
5045   // Wait for the thread assoc with the PlatformEvent to vacate.
5046   int status = os::Solaris::mutex_lock(_mutex);
5047   assert_status(status == 0, status, "mutex_lock");
5048   int AnyWaiters = _nParked;
5049   status = os::Solaris::mutex_unlock(_mutex);
5050   assert_status(status == 0, status, "mutex_unlock");
5051   guarantee(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
5052   if (AnyWaiters != 0) {
5053     // Note that we signal() *after* dropping the lock for "immortal" Events.
5054     // This is safe and avoids a common class of  futile wakeups.  In rare
5055     // circumstances this can cause a thread to return prematurely from
5056     // cond_{timed}wait() but the spurious wakeup is benign and the victim
5057     // will simply re-test the condition and re-park itself.
5058     // This provides particular benefit if the underlying platform does not
5059     // provide wait morphing.
5060     status = os::Solaris::cond_signal(_cond);
5061     assert_status(status == 0, status, "cond_signal");
5062   }
5063 }
5064 
5065 // JSR166
5066 // -------------------------------------------------------
5067 
5068 // The solaris and linux implementations of park/unpark are fairly
5069 // conservative for now, but can be improved. They currently use a
5070 // mutex/condvar pair, plus _counter.
5071 // Park decrements _counter if > 0, else does a condvar wait.  Unpark
5072 // sets count to 1 and signals condvar.  Only one thread ever waits
5073 // on the condvar. Contention seen when trying to park implies that someone
5074 // is unparking you, so don't wait. And spurious returns are fine, so there
5075 // is no need to track notifications.
5076 
5077 #define MAX_SECS 100000000
5078 
5079 // This code is common to linux and solaris and will be moved to a
5080 // common place in dolphin.
5081 //
5082 // The passed in time value is either a relative time in nanoseconds
5083 // or an absolute time in milliseconds. Either way it has to be unpacked
5084 // into suitable seconds and nanoseconds components and stored in the
5085 // given timespec structure.
5086 // Given time is a 64-bit value and the time_t used in the timespec is only
5087 // a signed-32-bit value (except on 64-bit Linux) we have to watch for
5088 // overflow if times way in the future are given. Further on Solaris versions
5089 // prior to 10 there is a restriction (see cond_timedwait) that the specified
5090 // number of seconds, in abstime, is less than current_time  + 100,000,000.
5091 // As it will be 28 years before "now + 100000000" will overflow we can
5092 // ignore overflow and just impose a hard-limit on seconds using the value
5093 // of "now + 100,000,000". This places a limit on the timeout of about 3.17
5094 // years from "now".
5095 //
5096 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
5097   assert(time > 0, "convertTime");
5098 
5099   struct timeval now;
5100   int status = gettimeofday(&now, NULL);
5101   assert(status == 0, "gettimeofday");
5102 
5103   time_t max_secs = now.tv_sec + MAX_SECS;
5104 
5105   if (isAbsolute) {
5106     jlong secs = time / 1000;
5107     if (secs > max_secs) {
5108       absTime->tv_sec = max_secs;
5109     } else {
5110       absTime->tv_sec = secs;
5111     }
5112     absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
5113   } else {
5114     jlong secs = time / NANOSECS_PER_SEC;
5115     if (secs >= MAX_SECS) {
5116       absTime->tv_sec = max_secs;
5117       absTime->tv_nsec = 0;
5118     } else {
5119       absTime->tv_sec = now.tv_sec + secs;
5120       absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
5121       if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
5122         absTime->tv_nsec -= NANOSECS_PER_SEC;
5123         ++absTime->tv_sec; // note: this must be <= max_secs
5124       }
5125     }
5126   }
5127   assert(absTime->tv_sec >= 0, "tv_sec < 0");
5128   assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
5129   assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
5130   assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
5131 }
5132 
5133 void Parker::park(bool isAbsolute, jlong time) {
5134   // Ideally we'd do something useful while spinning, such
5135   // as calling unpackTime().
5136 
5137   // Optional fast-path check:
5138   // Return immediately if a permit is available.
5139   // We depend on Atomic::xchg() having full barrier semantics
5140   // since we are doing a lock-free update to _counter.
5141   if (Atomic::xchg(0, &_counter) > 0) return;
5142 
5143   // Optional fast-exit: Check interrupt before trying to wait
5144   Thread* thread = Thread::current();
5145   assert(thread->is_Java_thread(), "Must be JavaThread");
5146   JavaThread *jt = (JavaThread *)thread;
5147   if (Thread::is_interrupted(thread, false)) {
5148     return;
5149   }
5150 
5151   // First, demultiplex/decode time arguments
5152   timespec absTime;
5153   if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all
5154     return;
5155   }
5156   if (time > 0) {
5157     // Warning: this code might be exposed to the old Solaris time
5158     // round-down bugs.  Grep "roundingFix" for details.
5159     unpackTime(&absTime, isAbsolute, time);
5160   }
5161 
5162   // Enter safepoint region
5163   // Beware of deadlocks such as 6317397.
5164   // The per-thread Parker:: _mutex is a classic leaf-lock.
5165   // In particular a thread must never block on the Threads_lock while
5166   // holding the Parker:: mutex.  If safepoints are pending both the
5167   // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
5168   ThreadBlockInVM tbivm(jt);
5169 
5170   // Don't wait if cannot get lock since interference arises from
5171   // unblocking.  Also. check interrupt before trying wait
5172   if (Thread::is_interrupted(thread, false) ||
5173       os::Solaris::mutex_trylock(_mutex) != 0) {
5174     return;
5175   }
5176 
5177   int status;
5178 
5179   if (_counter > 0)  { // no wait needed
5180     _counter = 0;
5181     status = os::Solaris::mutex_unlock(_mutex);
5182     assert(status == 0, "invariant");
5183     // Paranoia to ensure our locked and lock-free paths interact
5184     // correctly with each other and Java-level accesses.
5185     OrderAccess::fence();
5186     return;
5187   }
5188 
5189   OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
5190   jt->set_suspend_equivalent();
5191   // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
5192 
5193   // Do this the hard way by blocking ...
5194   // See http://monaco.sfbay/detail.jsf?cr=5094058.
5195   if (time == 0) {
5196     status = os::Solaris::cond_wait(_cond, _mutex);
5197   } else {
5198     status = os::Solaris::cond_timedwait (_cond, _mutex, &absTime);
5199   }
5200   // Note that an untimed cond_wait() can sometimes return ETIME on older
5201   // versions of the Solaris.
5202   assert_status(status == 0 || status == EINTR ||
5203                 status == ETIME || status == ETIMEDOUT,
5204                 status, "cond_timedwait");
5205 
5206   _counter = 0;
5207   status = os::Solaris::mutex_unlock(_mutex);
5208   assert_status(status == 0, status, "mutex_unlock");
5209   // Paranoia to ensure our locked and lock-free paths interact
5210   // correctly with each other and Java-level accesses.
5211   OrderAccess::fence();
5212 
5213   // If externally suspended while waiting, re-suspend
5214   if (jt->handle_special_suspend_equivalent_condition()) {
5215     jt->java_suspend_self();
5216   }
5217 }
5218 
5219 void Parker::unpark() {
5220   int status = os::Solaris::mutex_lock(_mutex);
5221   assert(status == 0, "invariant");
5222   const int s = _counter;
5223   _counter = 1;
5224   status = os::Solaris::mutex_unlock(_mutex);
5225   assert(status == 0, "invariant");
5226 
5227   if (s < 1) {
5228     status = os::Solaris::cond_signal(_cond);
5229     assert(status == 0, "invariant");
5230   }
5231 }
5232 
5233 extern char** environ;
5234 
5235 // Run the specified command in a separate process. Return its exit value,
5236 // or -1 on failure (e.g. can't fork a new process).
5237 // Unlike system(), this function can be called from signal handler. It
5238 // doesn't block SIGINT et al.
5239 int os::fork_and_exec(char* cmd, bool use_vfork_if_available) {
5240   char * argv[4];
5241   argv[0] = (char *)"sh";
5242   argv[1] = (char *)"-c";
5243   argv[2] = cmd;
5244   argv[3] = NULL;
5245 
5246   // fork is async-safe, fork1 is not so can't use in signal handler
5247   pid_t pid;
5248   Thread* t = Thread::current_or_null_safe();
5249   if (t != NULL && t->is_inside_signal_handler()) {
5250     pid = fork();
5251   } else {
5252     pid = fork1();
5253   }
5254 
5255   if (pid < 0) {
5256     // fork failed
5257     warning("fork failed: %s", os::strerror(errno));
5258     return -1;
5259 
5260   } else if (pid == 0) {
5261     // child process
5262 
5263     // try to be consistent with system(), which uses "/usr/bin/sh" on Solaris
5264     execve("/usr/bin/sh", argv, environ);
5265 
5266     // execve failed
5267     _exit(-1);
5268 
5269   } else  {
5270     // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
5271     // care about the actual exit code, for now.
5272 
5273     int status;
5274 
5275     // Wait for the child process to exit.  This returns immediately if
5276     // the child has already exited. */
5277     while (waitpid(pid, &status, 0) < 0) {
5278       switch (errno) {
5279       case ECHILD: return 0;
5280       case EINTR: break;
5281       default: return -1;
5282       }
5283     }
5284 
5285     if (WIFEXITED(status)) {
5286       // The child exited normally; get its exit code.
5287       return WEXITSTATUS(status);
5288     } else if (WIFSIGNALED(status)) {
5289       // The child exited because of a signal
5290       // The best value to return is 0x80 + signal number,
5291       // because that is what all Unix shells do, and because
5292       // it allows callers to distinguish between process exit and
5293       // process death by signal.
5294       return 0x80 + WTERMSIG(status);
5295     } else {
5296       // Unknown exit code; pass it through
5297       return status;
5298     }
5299   }
5300 }
5301 
5302 size_t os::write(int fd, const void *buf, unsigned int nBytes) {
5303   size_t res;
5304   RESTARTABLE((size_t) ::write(fd, buf, (size_t) nBytes), res);
5305   return res;
5306 }
5307 
5308 int os::close(int fd) {
5309   return ::close(fd);
5310 }
5311 
5312 int os::socket_close(int fd) {
5313   return ::close(fd);
5314 }
5315 
5316 int os::recv(int fd, char* buf, size_t nBytes, uint flags) {
5317   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5318          "Assumed _thread_in_native");
5319   RESTARTABLE_RETURN_INT((int)::recv(fd, buf, nBytes, flags));
5320 }
5321 
5322 int os::send(int fd, char* buf, size_t nBytes, uint flags) {
5323   assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5324          "Assumed _thread_in_native");
5325   RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags));
5326 }
5327 
5328 int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) {
5329   RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags));
5330 }
5331 
5332 // As both poll and select can be interrupted by signals, we have to be
5333 // prepared to restart the system call after updating the timeout, unless
5334 // a poll() is done with timeout == -1, in which case we repeat with this
5335 // "wait forever" value.
5336 
5337 int os::connect(int fd, struct sockaddr *him, socklen_t len) {
5338   int _result;
5339   _result = ::connect(fd, him, len);
5340 
5341   // On Solaris, when a connect() call is interrupted, the connection
5342   // can be established asynchronously (see 6343810). Subsequent calls
5343   // to connect() must check the errno value which has the semantic
5344   // described below (copied from the connect() man page). Handling
5345   // of asynchronously established connections is required for both
5346   // blocking and non-blocking sockets.
5347   //     EINTR            The  connection  attempt  was   interrupted
5348   //                      before  any data arrived by the delivery of
5349   //                      a signal. The connection, however, will  be
5350   //                      established asynchronously.
5351   //
5352   //     EINPROGRESS      The socket is non-blocking, and the connec-
5353   //                      tion  cannot  be completed immediately.
5354   //
5355   //     EALREADY         The socket is non-blocking,  and a previous
5356   //                      connection  attempt  has  not yet been com-
5357   //                      pleted.
5358   //
5359   //     EISCONN          The socket is already connected.
5360   if (_result == OS_ERR && errno == EINTR) {
5361     // restarting a connect() changes its errno semantics
5362     RESTARTABLE(::connect(fd, him, len), _result);
5363     // undo these changes
5364     if (_result == OS_ERR) {
5365       if (errno == EALREADY) {
5366         errno = EINPROGRESS; // fall through
5367       } else if (errno == EISCONN) {
5368         errno = 0;
5369         return OS_OK;
5370       }
5371     }
5372   }
5373   return _result;
5374 }
5375 
5376 // Get the default path to the core file
5377 // Returns the length of the string
5378 int os::get_core_path(char* buffer, size_t bufferSize) {
5379   const char* p = get_current_directory(buffer, bufferSize);
5380 
5381   if (p == NULL) {
5382     assert(p != NULL, "failed to get current directory");
5383     return 0;
5384   }
5385 
5386   jio_snprintf(buffer, bufferSize, "%s/core or core.%d",
5387                                               p, current_process_id());
5388 
5389   return strlen(buffer);
5390 }
5391 
5392 #ifndef PRODUCT
5393 void TestReserveMemorySpecial_test() {
5394   // No tests available for this platform
5395 }
5396 #endif
5397 
5398 bool os::start_debugging(char *buf, int buflen) {
5399   int len = (int)strlen(buf);
5400   char *p = &buf[len];
5401 
5402   jio_snprintf(p, buflen-len,
5403                "\n\n"
5404                "Do you want to debug the problem?\n\n"
5405                "To debug, run 'dbx - %d'; then switch to thread " INTX_FORMAT "\n"
5406                "Enter 'yes' to launch dbx automatically (PATH must include dbx)\n"
5407                "Otherwise, press RETURN to abort...",
5408                os::current_process_id(), os::current_thread_id());
5409 
5410   bool yes = os::message_box("Unexpected Error", buf);
5411 
5412   if (yes) {
5413     // yes, user asked VM to launch debugger
5414     jio_snprintf(buf, sizeof(buf), "dbx - %d", os::current_process_id());
5415 
5416     os::fork_and_exec(buf);
5417     yes = false;
5418   }
5419   return yes;
5420 }