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