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