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