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