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