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