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