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