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