Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/os/solaris/vm/os_solaris.cpp
32285 views
/*1* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324// no precompiled headers25#include "classfile/classLoader.hpp"26#include "classfile/systemDictionary.hpp"27#include "classfile/vmSymbols.hpp"28#include "code/icBuffer.hpp"29#include "code/vtableStubs.hpp"30#include "compiler/compileBroker.hpp"31#include "compiler/disassembler.hpp"32#include "interpreter/interpreter.hpp"33#include "jvm_solaris.h"34#include "memory/allocation.inline.hpp"35#include "memory/filemap.hpp"36#include "mutex_solaris.inline.hpp"37#include "oops/oop.inline.hpp"38#include "os_share_solaris.hpp"39#include "prims/jniFastGetField.hpp"40#include "prims/jvm.h"41#include "prims/jvm_misc.hpp"42#include "runtime/arguments.hpp"43#include "runtime/extendedPC.hpp"44#include "runtime/globals.hpp"45#include "runtime/interfaceSupport.hpp"46#include "runtime/java.hpp"47#include "runtime/javaCalls.hpp"48#include "runtime/mutexLocker.hpp"49#include "runtime/objectMonitor.hpp"50#include "runtime/orderAccess.inline.hpp"51#include "runtime/osThread.hpp"52#include "runtime/perfMemory.hpp"53#include "runtime/sharedRuntime.hpp"54#include "runtime/statSampler.hpp"55#include "runtime/stubRoutines.hpp"56#include "runtime/thread.inline.hpp"57#include "runtime/threadCritical.hpp"58#include "runtime/timer.hpp"59#include "services/attachListener.hpp"60#include "services/memTracker.hpp"61#include "services/runtimeService.hpp"62#include "utilities/decoder.hpp"63#include "utilities/defaultStream.hpp"64#include "utilities/events.hpp"65#include "utilities/growableArray.hpp"66#include "utilities/vmError.hpp"6768// put OS-includes here69# include <dlfcn.h>70# include <errno.h>71# include <exception>72# include <link.h>73# include <poll.h>74# include <pthread.h>75# include <pwd.h>76# include <schedctl.h>77# include <setjmp.h>78# include <signal.h>79# include <stdio.h>80# include <alloca.h>81# include <sys/filio.h>82# include <sys/ipc.h>83# include <sys/lwp.h>84# include <sys/machelf.h> // for elf Sym structure used by dladdr185# include <sys/mman.h>86# include <sys/processor.h>87# include <sys/procset.h>88# include <sys/pset.h>89# include <sys/resource.h>90# include <sys/shm.h>91# include <sys/socket.h>92# include <sys/stat.h>93# include <sys/systeminfo.h>94# include <sys/time.h>95# include <sys/times.h>96# include <sys/types.h>97# include <sys/wait.h>98# include <sys/utsname.h>99# include <thread.h>100# include <unistd.h>101# include <sys/priocntl.h>102# include <sys/rtpriocntl.h>103# include <sys/tspriocntl.h>104# include <sys/iapriocntl.h>105# include <sys/fxpriocntl.h>106# include <sys/loadavg.h>107# include <string.h>108# include <stdio.h>109110# define _STRUCTURED_PROC 1 // this gets us the new structured proc interfaces of 5.6 & later111# include <sys/procfs.h> // see comment in <sys/procfs.h>112113#define MAX_PATH (2 * K)114115// for timer info max values which include all bits116#define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)117118119// Here are some liblgrp types from sys/lgrp_user.h to be able to120// compile on older systems without this header file.121122#ifndef MADV_ACCESS_LWP123# define MADV_ACCESS_LWP 7 /* next LWP to access heavily */124#endif125#ifndef MADV_ACCESS_MANY126# define MADV_ACCESS_MANY 8 /* many processes to access heavily */127#endif128129#ifndef LGRP_RSRC_CPU130# define LGRP_RSRC_CPU 0 /* CPU resources */131#endif132#ifndef LGRP_RSRC_MEM133# define LGRP_RSRC_MEM 1 /* memory resources */134#endif135136// see thr_setprio(3T) for the basis of these numbers137#define MinimumPriority 0138#define NormalPriority 64139#define MaximumPriority 127140141// Values for ThreadPriorityPolicy == 1142int prio_policy1[CriticalPriority+1] = {143-99999, 0, 16, 32, 48, 64,14480, 96, 112, 124, 127, 127 };145146// System parameters used internally147static clock_t clock_tics_per_sec = 100;148149// Track if we have called enable_extended_FILE_stdio (on Solaris 10u4+)150static bool enabled_extended_FILE_stdio = false;151152// For diagnostics to print a message once. see run_periodic_checks153static bool check_addr0_done = false;154static sigset_t check_signal_done;155static bool check_signals = true;156157address os::Solaris::handler_start; // start pc of thr_sighndlrinfo158address os::Solaris::handler_end; // end pc of thr_sighndlrinfo159160address os::Solaris::_main_stack_base = NULL; // 4352906 workaround161162os::Solaris::pthread_setname_np_func_t os::Solaris::_pthread_setname_np = NULL;163164// "default" initializers for missing libc APIs165extern "C" {166static int lwp_mutex_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; }167static int lwp_mutex_destroy(mutex_t *mx) { return 0; }168169static int lwp_cond_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; }170static int lwp_cond_destroy(cond_t *cv) { return 0; }171}172173// "default" initializers for pthread-based synchronization174extern "C" {175static int pthread_mutex_default_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; }176static int pthread_cond_default_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; }177}178179static void unpackTime(timespec* absTime, bool isAbsolute, jlong time);180181static inline size_t adjust_stack_size(address base, size_t size) {182if ((ssize_t)size < 0) {183// 4759953: Compensate for ridiculous stack size.184size = max_intx;185}186if (size > (size_t)base) {187// 4812466: Make sure size doesn't allow the stack to wrap the address space.188size = (size_t)base;189}190return size;191}192193static inline stack_t get_stack_info() {194stack_t st;195int retval = thr_stksegment(&st);196st.ss_size = adjust_stack_size((address)st.ss_sp, st.ss_size);197assert(retval == 0, "incorrect return value from thr_stksegment");198assert((address)&st < (address)st.ss_sp, "Invalid stack base returned");199assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned");200return st;201}202203bool os::is_primordial_thread(void) {204int r = thr_main() ;205guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ;206return r == 1;207}208209address os::current_stack_base() {210bool _is_primordial_thread = is_primordial_thread();211212// Workaround 4352906, avoid calls to thr_stksegment by213// thr_main after the first one (it looks like we trash214// some data, causing the value for ss_sp to be incorrect).215if (!_is_primordial_thread || os::Solaris::_main_stack_base == NULL) {216stack_t st = get_stack_info();217if (_is_primordial_thread) {218// cache initial value of stack base219os::Solaris::_main_stack_base = (address)st.ss_sp;220}221return (address)st.ss_sp;222} else {223guarantee(os::Solaris::_main_stack_base != NULL, "Attempt to use null cached stack base");224return os::Solaris::_main_stack_base;225}226}227228size_t os::current_stack_size() {229size_t size;230231if (!is_primordial_thread()) {232size = get_stack_info().ss_size;233} else {234struct rlimit limits;235getrlimit(RLIMIT_STACK, &limits);236size = adjust_stack_size(os::Solaris::_main_stack_base, (size_t)limits.rlim_cur);237}238// base may not be page aligned239address base = current_stack_base();240address bottom = (address)align_size_up((intptr_t)(base - size), os::vm_page_size());;241return (size_t)(base - bottom);242}243244struct tm* os::localtime_pd(const time_t* clock, struct tm* res) {245return localtime_r(clock, res);246}247248// interruptible infrastructure249250// setup_interruptible saves the thread state before going into an251// interruptible system call.252// The saved state is used to restore the thread to253// its former state whether or not an interrupt is received.254// Used by classloader os::read255// os::restartable_read calls skip this layer and stay in _thread_in_native256257void os::Solaris::setup_interruptible(JavaThread* thread) {258259JavaThreadState thread_state = thread->thread_state();260261assert(thread_state != _thread_blocked, "Coming from the wrong thread");262assert(thread_state != _thread_in_native, "Native threads skip setup_interruptible");263OSThread* osthread = thread->osthread();264osthread->set_saved_interrupt_thread_state(thread_state);265thread->frame_anchor()->make_walkable(thread);266ThreadStateTransition::transition(thread, thread_state, _thread_blocked);267}268269// Version of setup_interruptible() for threads that are already in270// _thread_blocked. Used by os_sleep().271void os::Solaris::setup_interruptible_already_blocked(JavaThread* thread) {272thread->frame_anchor()->make_walkable(thread);273}274275JavaThread* os::Solaris::setup_interruptible() {276JavaThread* thread = (JavaThread*)ThreadLocalStorage::thread();277setup_interruptible(thread);278return thread;279}280281void os::Solaris::try_enable_extended_io() {282typedef int (*enable_extended_FILE_stdio_t)(int, int);283284if (!UseExtendedFileIO) {285return;286}287288enable_extended_FILE_stdio_t enabler =289(enable_extended_FILE_stdio_t) dlsym(RTLD_DEFAULT,290"enable_extended_FILE_stdio");291if (enabler) {292enabler(-1, -1);293}294}295296297#ifdef ASSERT298299JavaThread* os::Solaris::setup_interruptible_native() {300JavaThread* thread = (JavaThread*)ThreadLocalStorage::thread();301JavaThreadState thread_state = thread->thread_state();302assert(thread_state == _thread_in_native, "Assumed thread_in_native");303return thread;304}305306void os::Solaris::cleanup_interruptible_native(JavaThread* thread) {307JavaThreadState thread_state = thread->thread_state();308assert(thread_state == _thread_in_native, "Assumed thread_in_native");309}310#endif311312// cleanup_interruptible reverses the effects of setup_interruptible313// setup_interruptible_already_blocked() does not need any cleanup.314315void os::Solaris::cleanup_interruptible(JavaThread* thread) {316OSThread* osthread = thread->osthread();317318ThreadStateTransition::transition(thread, _thread_blocked, osthread->saved_interrupt_thread_state());319}320321// I/O interruption related counters called in _INTERRUPTIBLE322323void os::Solaris::bump_interrupted_before_count() {324RuntimeService::record_interrupted_before_count();325}326327void os::Solaris::bump_interrupted_during_count() {328RuntimeService::record_interrupted_during_count();329}330331static int _processors_online = 0;332333jint os::Solaris::_os_thread_limit = 0;334volatile jint os::Solaris::_os_thread_count = 0;335336julong os::available_memory() {337return Solaris::available_memory();338}339340julong os::Solaris::available_memory() {341return (julong)sysconf(_SC_AVPHYS_PAGES) * os::vm_page_size();342}343344julong os::Solaris::_physical_memory = 0;345346julong os::physical_memory() {347return Solaris::physical_memory();348}349350static hrtime_t first_hrtime = 0;351static const hrtime_t hrtime_hz = 1000*1000*1000;352static volatile hrtime_t max_hrtime = 0;353354355void os::Solaris::initialize_system_info() {356set_processor_count(sysconf(_SC_NPROCESSORS_CONF));357_processors_online = sysconf (_SC_NPROCESSORS_ONLN);358_physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE);359}360361int os::active_processor_count() {362// User has overridden the number of active processors363if (ActiveProcessorCount > 0) {364if (Verbose) {365tty->print_cr("active_processor_count: "366"active processor count set by user : %d",367ActiveProcessorCount);368}369return ActiveProcessorCount;370}371372int online_cpus = sysconf(_SC_NPROCESSORS_ONLN);373pid_t pid = getpid();374psetid_t pset = PS_NONE;375// Are we running in a processor set or is there any processor set around?376if (pset_bind(PS_QUERY, P_PID, pid, &pset) == 0) {377uint_t pset_cpus;378// Query the number of cpus available to us.379if (pset_info(pset, NULL, &pset_cpus, NULL) == 0) {380assert(pset_cpus > 0 && pset_cpus <= online_cpus, "sanity check");381_processors_online = pset_cpus;382return pset_cpus;383}384}385// Otherwise return number of online cpus386return online_cpus;387}388389static bool find_processors_in_pset(psetid_t pset,390processorid_t** id_array,391uint_t* id_length) {392bool result = false;393// Find the number of processors in the processor set.394if (pset_info(pset, NULL, id_length, NULL) == 0) {395// Make up an array to hold their ids.396*id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal);397// Fill in the array with their processor ids.398if (pset_info(pset, NULL, id_length, *id_array) == 0) {399result = true;400}401}402return result;403}404405// Callers of find_processors_online() must tolerate imprecise results --406// the system configuration can change asynchronously because of DR407// or explicit psradm operations.408//409// We also need to take care that the loop (below) terminates as the410// number of processors online can change between the _SC_NPROCESSORS_ONLN411// request and the loop that builds the list of processor ids. Unfortunately412// there's no reliable way to determine the maximum valid processor id,413// so we use a manifest constant, MAX_PROCESSOR_ID, instead. See p_online414// man pages, which claim the processor id set is "sparse, but415// not too sparse". MAX_PROCESSOR_ID is used to ensure that we eventually416// exit the loop.417//418// In the future we'll be able to use sysconf(_SC_CPUID_MAX), but that's419// not available on S8.0.420421static bool find_processors_online(processorid_t** id_array,422uint* id_length) {423const processorid_t MAX_PROCESSOR_ID = 100000 ;424// Find the number of processors online.425*id_length = sysconf(_SC_NPROCESSORS_ONLN);426// Make up an array to hold their ids.427*id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal);428// Processors need not be numbered consecutively.429long found = 0;430processorid_t next = 0;431while (found < *id_length && next < MAX_PROCESSOR_ID) {432processor_info_t info;433if (processor_info(next, &info) == 0) {434// NB, PI_NOINTR processors are effectively online ...435if (info.pi_state == P_ONLINE || info.pi_state == P_NOINTR) {436(*id_array)[found] = next;437found += 1;438}439}440next += 1;441}442if (found < *id_length) {443// The loop above didn't identify the expected number of processors.444// We could always retry the operation, calling sysconf(_SC_NPROCESSORS_ONLN)445// and re-running the loop, above, but there's no guarantee of progress446// if the system configuration is in flux. Instead, we just return what447// we've got. Note that in the worst case find_processors_online() could448// return an empty set. (As a fall-back in the case of the empty set we449// could just return the ID of the current processor).450*id_length = found ;451}452453return true;454}455456static bool assign_distribution(processorid_t* id_array,457uint id_length,458uint* distribution,459uint distribution_length) {460// We assume we can assign processorid_t's to uint's.461assert(sizeof(processorid_t) == sizeof(uint),462"can't convert processorid_t to uint");463// Quick check to see if we won't succeed.464if (id_length < distribution_length) {465return false;466}467// Assign processor ids to the distribution.468// Try to shuffle processors to distribute work across boards,469// assuming 4 processors per board.470const uint processors_per_board = ProcessDistributionStride;471// Find the maximum processor id.472processorid_t max_id = 0;473for (uint m = 0; m < id_length; m += 1) {474max_id = MAX2(max_id, id_array[m]);475}476// The next id, to limit loops.477const processorid_t limit_id = max_id + 1;478// Make up markers for available processors.479bool* available_id = NEW_C_HEAP_ARRAY(bool, limit_id, mtInternal);480for (uint c = 0; c < limit_id; c += 1) {481available_id[c] = false;482}483for (uint a = 0; a < id_length; a += 1) {484available_id[id_array[a]] = true;485}486// Step by "boards", then by "slot", copying to "assigned".487// NEEDS_CLEANUP: The assignment of processors should be stateful,488// remembering which processors have been assigned by489// previous calls, etc., so as to distribute several490// independent calls of this method. What we'd like is491// It would be nice to have an API that let us ask492// how many processes are bound to a processor,493// but we don't have that, either.494// In the short term, "board" is static so that495// subsequent distributions don't all start at board 0.496static uint board = 0;497uint assigned = 0;498// Until we've found enough processors ....499while (assigned < distribution_length) {500// ... find the next available processor in the board.501for (uint slot = 0; slot < processors_per_board; slot += 1) {502uint try_id = board * processors_per_board + slot;503if ((try_id < limit_id) && (available_id[try_id] == true)) {504distribution[assigned] = try_id;505available_id[try_id] = false;506assigned += 1;507break;508}509}510board += 1;511if (board * processors_per_board + 0 >= limit_id) {512board = 0;513}514}515if (available_id != NULL) {516FREE_C_HEAP_ARRAY(bool, available_id, mtInternal);517}518return true;519}520521void os::set_native_thread_name(const char *name) {522if (Solaris::_pthread_setname_np != NULL) {523// Only the first 31 bytes of 'name' are processed by pthread_setname_np524// but we explicitly copy into a size-limited buffer to avoid any525// possible overflow.526char buf[32];527snprintf(buf, sizeof(buf), "%s", name);528buf[sizeof(buf) - 1] = '\0';529Solaris::_pthread_setname_np(pthread_self(), buf);530}531}532533bool os::distribute_processes(uint length, uint* distribution) {534bool result = false;535// Find the processor id's of all the available CPUs.536processorid_t* id_array = NULL;537uint id_length = 0;538// There are some races between querying information and using it,539// since processor sets can change dynamically.540psetid_t pset = PS_NONE;541// Are we running in a processor set?542if ((pset_bind(PS_QUERY, P_PID, P_MYID, &pset) == 0) && pset != PS_NONE) {543result = find_processors_in_pset(pset, &id_array, &id_length);544} else {545result = find_processors_online(&id_array, &id_length);546}547if (result == true) {548if (id_length >= length) {549result = assign_distribution(id_array, id_length, distribution, length);550} else {551result = false;552}553}554if (id_array != NULL) {555FREE_C_HEAP_ARRAY(processorid_t, id_array, mtInternal);556}557return result;558}559560bool os::bind_to_processor(uint processor_id) {561// We assume that a processorid_t can be stored in a uint.562assert(sizeof(uint) == sizeof(processorid_t),563"can't convert uint to processorid_t");564int bind_result =565processor_bind(P_LWPID, // bind LWP.566P_MYID, // bind current LWP.567(processorid_t) processor_id, // id.568NULL); // don't return old binding.569return (bind_result == 0);570}571572bool os::getenv(const char* name, char* buffer, int len) {573char* val = ::getenv( name );574if ( val == NULL575|| strlen(val) + 1 > len ) {576if (len > 0) buffer[0] = 0; // return a null string577return false;578}579strcpy( buffer, val );580return true;581}582583584// Return true if user is running as root.585586bool os::have_special_privileges() {587static bool init = false;588static bool privileges = false;589if (!init) {590privileges = (getuid() != geteuid()) || (getgid() != getegid());591init = true;592}593return privileges;594}595596597void os::init_system_properties_values() {598// The next steps are taken in the product version:599//600// Obtain the JAVA_HOME value from the location of libjvm.so.601// This library should be located at:602// <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so.603//604// If "/jre/lib/" appears at the right place in the path, then we605// assume libjvm.so is installed in a JDK and we use this path.606//607// Otherwise exit with message: "Could not create the Java virtual machine."608//609// The following extra steps are taken in the debugging version:610//611// If "/jre/lib/" does NOT appear at the right place in the path612// instead of exit check for $JAVA_HOME environment variable.613//614// If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,615// then we append a fake suffix "hotspot/libjvm.so" to this path so616// it looks like libjvm.so is installed there617// <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.618//619// Otherwise exit.620//621// Important note: if the location of libjvm.so changes this622// code needs to be changed accordingly.623624// Base path of extensions installed on the system.625#define SYS_EXT_DIR "/usr/jdk/packages"626#define EXTENSIONS_DIR "/lib/ext"627#define ENDORSED_DIR "/lib/endorsed"628629char cpu_arch[12];630// Buffer that fits several sprintfs.631// Note that the space for the colon and the trailing null are provided632// by the nulls included by the sizeof operator.633const size_t bufsize =634MAX4((size_t)MAXPATHLEN, // For dll_dir & friends.635sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch), // invariant ld_library_path636(size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR), // extensions dir637(size_t)MAXPATHLEN + sizeof(ENDORSED_DIR)); // endorsed dir638char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);639640// sysclasspath, java_home, dll_dir641{642char *pslash;643os::jvm_path(buf, bufsize);644645// Found the full path to libjvm.so.646// Now cut the path to <java_home>/jre if we can.647*(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so.648pslash = strrchr(buf, '/');649if (pslash != NULL) {650*pslash = '\0'; // Get rid of /{client|server|hotspot}.651}652Arguments::set_dll_dir(buf);653654if (pslash != NULL) {655pslash = strrchr(buf, '/');656if (pslash != NULL) {657*pslash = '\0'; // Get rid of /<arch>.658pslash = strrchr(buf, '/');659if (pslash != NULL) {660*pslash = '\0'; // Get rid of /lib.661}662}663}664Arguments::set_java_home(buf);665set_boot_path('/', ':');666}667668// Where to look for native libraries.669{670// Use dlinfo() to determine the correct java.library.path.671//672// If we're launched by the Java launcher, and the user673// does not set java.library.path explicitly on the commandline,674// the Java launcher sets LD_LIBRARY_PATH for us and unsets675// LD_LIBRARY_PATH_32 and LD_LIBRARY_PATH_64. In this case676// dlinfo returns LD_LIBRARY_PATH + crle settings (including677// /usr/lib), which is exactly what we want.678//679// If the user does set java.library.path, it completely680// overwrites this setting, and always has.681//682// If we're not launched by the Java launcher, we may683// get here with any/all of the LD_LIBRARY_PATH[_32|64]684// settings. Again, dlinfo does exactly what we want.685686Dl_serinfo info_sz, *info = &info_sz;687Dl_serpath *path;688char *library_path;689char *common_path = buf;690691// Determine search path count and required buffer size.692if (dlinfo(RTLD_SELF, RTLD_DI_SERINFOSIZE, (void *)info) == -1) {693FREE_C_HEAP_ARRAY(char, buf, mtInternal);694vm_exit_during_initialization("dlinfo SERINFOSIZE request", dlerror());695}696697// Allocate new buffer and initialize.698info = (Dl_serinfo*)NEW_C_HEAP_ARRAY(char, info_sz.dls_size, mtInternal);699info->dls_size = info_sz.dls_size;700info->dls_cnt = info_sz.dls_cnt;701702// Obtain search path information.703if (dlinfo(RTLD_SELF, RTLD_DI_SERINFO, (void *)info) == -1) {704FREE_C_HEAP_ARRAY(char, buf, mtInternal);705FREE_C_HEAP_ARRAY(char, info, mtInternal);706vm_exit_during_initialization("dlinfo SERINFO request", dlerror());707}708709path = &info->dls_serpath[0];710711// Note: Due to a legacy implementation, most of the library path712// is set in the launcher. This was to accomodate linking restrictions713// on legacy Solaris implementations (which are no longer supported).714// Eventually, all the library path setting will be done here.715//716// However, to prevent the proliferation of improperly built native717// libraries, the new path component /usr/jdk/packages is added here.718719// Determine the actual CPU architecture.720sysinfo(SI_ARCHITECTURE, cpu_arch, sizeof(cpu_arch));721#ifdef _LP64722// If we are a 64-bit vm, perform the following translations:723// sparc -> sparcv9724// i386 -> amd64725if (strcmp(cpu_arch, "sparc") == 0) {726strcat(cpu_arch, "v9");727} else if (strcmp(cpu_arch, "i386") == 0) {728strcpy(cpu_arch, "amd64");729}730#endif731732// Construct the invariant part of ld_library_path.733sprintf(common_path, SYS_EXT_DIR "/lib/%s", cpu_arch);734735// Struct size is more than sufficient for the path components obtained736// through the dlinfo() call, so only add additional space for the path737// components explicitly added here.738size_t library_path_size = info->dls_size + strlen(common_path);739library_path = (char *)NEW_C_HEAP_ARRAY(char, library_path_size, mtInternal);740library_path[0] = '\0';741742// Construct the desired Java library path from the linker's library743// search path.744//745// For compatibility, it is optimal that we insert the additional path746// components specific to the Java VM after those components specified747// in LD_LIBRARY_PATH (if any) but before those added by the ld.so748// infrastructure.749if (info->dls_cnt == 0) { // Not sure this can happen, but allow for it.750strcpy(library_path, common_path);751} else {752int inserted = 0;753int i;754for (i = 0; i < info->dls_cnt; i++, path++) {755uint_t flags = path->dls_flags & LA_SER_MASK;756if (((flags & LA_SER_LIBPATH) == 0) && !inserted) {757strcat(library_path, common_path);758strcat(library_path, os::path_separator());759inserted = 1;760}761strcat(library_path, path->dls_name);762strcat(library_path, os::path_separator());763}764// Eliminate trailing path separator.765library_path[strlen(library_path)-1] = '\0';766}767768// happens before argument parsing - can't use a trace flag769// tty->print_raw("init_system_properties_values: native lib path: ");770// tty->print_raw_cr(library_path);771772// Callee copies into its own buffer.773Arguments::set_library_path(library_path);774775FREE_C_HEAP_ARRAY(char, library_path, mtInternal);776FREE_C_HEAP_ARRAY(char, info, mtInternal);777}778779// Extensions directories.780sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());781Arguments::set_ext_dirs(buf);782783// Endorsed standards default directory.784sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home());785Arguments::set_endorsed_dirs(buf);786787FREE_C_HEAP_ARRAY(char, buf, mtInternal);788789#undef SYS_EXT_DIR790#undef EXTENSIONS_DIR791#undef ENDORSED_DIR792}793794void os::breakpoint() {795BREAKPOINT;796}797798bool os::obsolete_option(const JavaVMOption *option)799{800if (!strncmp(option->optionString, "-Xt", 3)) {801return true;802} else if (!strncmp(option->optionString, "-Xtm", 4)) {803return true;804} else if (!strncmp(option->optionString, "-Xverifyheap", 12)) {805return true;806} else if (!strncmp(option->optionString, "-Xmaxjitcodesize", 16)) {807return true;808}809return false;810}811812bool os::Solaris::valid_stack_address(Thread* thread, address sp) {813address stackStart = (address)thread->stack_base();814address stackEnd = (address)(stackStart - (address)thread->stack_size());815if (sp < stackStart && sp >= stackEnd ) return true;816return false;817}818819extern "C" void breakpoint() {820// use debugger to set breakpoint here821}822823static thread_t main_thread;824825// Thread start routine for all new Java threads826extern "C" void* java_start(void* thread_addr) {827// Try to randomize the cache line index of hot stack frames.828// This helps when threads of the same stack traces evict each other's829// cache lines. The threads can be either from the same JVM instance, or830// from different JVM instances. The benefit is especially true for831// processors with hyperthreading technology.832static int counter = 0;833int pid = os::current_process_id();834alloca(((pid ^ counter++) & 7) * 128);835836int prio;837Thread* thread = (Thread*)thread_addr;838OSThread* osthr = thread->osthread();839840osthr->set_lwp_id( _lwp_self() ); // Store lwp in case we are bound841thread->_schedctl = (void *) schedctl_init () ;842843if (UseNUMA) {844int lgrp_id = os::numa_get_group_id();845if (lgrp_id != -1) {846thread->set_lgrp_id(lgrp_id);847}848}849850// If the creator called set priority before we started,851// we need to call set_native_priority now that we have an lwp.852// We used to get the priority from thr_getprio (we called853// thr_setprio way back in create_thread) and pass it to854// set_native_priority, but Solaris scales the priority855// in java_to_os_priority, so when we read it back here,856// we pass trash to set_native_priority instead of what's857// in java_to_os_priority. So we save the native priority858// in the osThread and recall it here.859860if ( osthr->thread_id() != -1 ) {861if ( UseThreadPriorities ) {862int prio = osthr->native_priority();863if (ThreadPriorityVerbose) {864tty->print_cr("Starting Thread " INTPTR_FORMAT ", LWP is "865INTPTR_FORMAT ", setting priority: %d\n",866osthr->thread_id(), osthr->lwp_id(), prio);867}868os::set_native_priority(thread, prio);869}870} else if (ThreadPriorityVerbose) {871warning("Can't set priority in _start routine, thread id hasn't been set\n");872}873874assert(osthr->get_state() == RUNNABLE, "invalid os thread state");875876// initialize signal mask for this thread877os::Solaris::hotspot_sigmask(thread);878879thread->run();880881// One less thread is executing882// When the VMThread gets here, the main thread may have already exited883// which frees the CodeHeap containing the Atomic::dec code884if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) {885Atomic::dec(&os::Solaris::_os_thread_count);886}887888if (UseDetachedThreads) {889thr_exit(NULL);890ShouldNotReachHere();891}892return NULL;893}894895static OSThread* create_os_thread(Thread* thread, thread_t thread_id) {896// Allocate the OSThread object897OSThread* osthread = new OSThread(NULL, NULL);898if (osthread == NULL) return NULL;899900// Store info on the Solaris thread into the OSThread901osthread->set_thread_id(thread_id);902osthread->set_lwp_id(_lwp_self());903thread->_schedctl = (void *) schedctl_init () ;904905if (UseNUMA) {906int lgrp_id = os::numa_get_group_id();907if (lgrp_id != -1) {908thread->set_lgrp_id(lgrp_id);909}910}911912if ( ThreadPriorityVerbose ) {913tty->print_cr("In create_os_thread, Thread " INTPTR_FORMAT ", LWP is " INTPTR_FORMAT "\n",914osthread->thread_id(), osthread->lwp_id() );915}916917// Initial thread state is INITIALIZED, not SUSPENDED918osthread->set_state(INITIALIZED);919920return osthread;921}922923void os::Solaris::hotspot_sigmask(Thread* thread) {924925//Save caller's signal mask926sigset_t sigmask;927thr_sigsetmask(SIG_SETMASK, NULL, &sigmask);928OSThread *osthread = thread->osthread();929osthread->set_caller_sigmask(sigmask);930931thr_sigsetmask(SIG_UNBLOCK, os::Solaris::unblocked_signals(), NULL);932if (!ReduceSignalUsage) {933if (thread->is_VM_thread()) {934// Only the VM thread handles BREAK_SIGNAL ...935thr_sigsetmask(SIG_UNBLOCK, vm_signals(), NULL);936} else {937// ... all other threads block BREAK_SIGNAL938assert(!sigismember(vm_signals(), SIGINT), "SIGINT should not be blocked");939thr_sigsetmask(SIG_BLOCK, vm_signals(), NULL);940}941}942}943944bool os::create_attached_thread(JavaThread* thread) {945#ifdef ASSERT946thread->verify_not_published();947#endif948OSThread* osthread = create_os_thread(thread, thr_self());949if (osthread == NULL) {950return false;951}952953// Initial thread state is RUNNABLE954osthread->set_state(RUNNABLE);955thread->set_osthread(osthread);956957// initialize signal mask for this thread958// and save the caller's signal mask959os::Solaris::hotspot_sigmask(thread);960961return true;962}963964bool os::create_main_thread(JavaThread* thread) {965#ifdef ASSERT966thread->verify_not_published();967#endif968if (_starting_thread == NULL) {969_starting_thread = create_os_thread(thread, main_thread);970if (_starting_thread == NULL) {971return false;972}973}974975// The primodial thread is runnable from the start976_starting_thread->set_state(RUNNABLE);977978thread->set_osthread(_starting_thread);979980// initialize signal mask for this thread981// and save the caller's signal mask982os::Solaris::hotspot_sigmask(thread);983984return true;985}986987// _T2_libthread is true if we believe we are running with the newer988// SunSoft lwp/libthread.so (2.8 patch, 2.9 default)989bool os::Solaris::_T2_libthread = false;990991bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) {992// Allocate the OSThread object993OSThread* osthread = new OSThread(NULL, NULL);994if (osthread == NULL) {995return false;996}997998if ( ThreadPriorityVerbose ) {999char *thrtyp;1000switch ( thr_type ) {1001case vm_thread:1002thrtyp = (char *)"vm";1003break;1004case cgc_thread:1005thrtyp = (char *)"cgc";1006break;1007case pgc_thread:1008thrtyp = (char *)"pgc";1009break;1010case java_thread:1011thrtyp = (char *)"java";1012break;1013case compiler_thread:1014thrtyp = (char *)"compiler";1015break;1016case watcher_thread:1017thrtyp = (char *)"watcher";1018break;1019default:1020thrtyp = (char *)"unknown";1021break;1022}1023tty->print_cr("In create_thread, creating a %s thread\n", thrtyp);1024}10251026// Calculate stack size if it's not specified by caller.1027if (stack_size == 0) {1028// The default stack size 1M (2M for LP64).1029stack_size = (BytesPerWord >> 2) * K * K;10301031switch (thr_type) {1032case os::java_thread:1033// Java threads use ThreadStackSize which default value can be changed with the flag -Xss1034if (JavaThread::stack_size_at_create() > 0) stack_size = JavaThread::stack_size_at_create();1035break;1036case os::compiler_thread:1037if (CompilerThreadStackSize > 0) {1038stack_size = (size_t)(CompilerThreadStackSize * K);1039break;1040} // else fall through:1041// use VMThreadStackSize if CompilerThreadStackSize is not defined1042case os::vm_thread:1043case os::pgc_thread:1044case os::cgc_thread:1045case os::watcher_thread:1046if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K);1047break;1048}1049}1050stack_size = MAX2(stack_size, os::Solaris::min_stack_allowed);10511052// Initial state is ALLOCATED but not INITIALIZED1053osthread->set_state(ALLOCATED);10541055if (os::Solaris::_os_thread_count > os::Solaris::_os_thread_limit) {1056// We got lots of threads. Check if we still have some address space left.1057// Need to be at least 5Mb of unreserved address space. We do check by1058// trying to reserve some.1059const size_t VirtualMemoryBangSize = 20*K*K;1060char* mem = os::reserve_memory(VirtualMemoryBangSize);1061if (mem == NULL) {1062delete osthread;1063return false;1064} else {1065// Release the memory again1066os::release_memory(mem, VirtualMemoryBangSize);1067}1068}10691070// Setup osthread because the child thread may need it.1071thread->set_osthread(osthread);10721073// Create the Solaris thread1074// explicit THR_BOUND for T2_libthread case in case1075// that assumption is not accurate, but our alternate signal stack1076// handling is based on it which must have bound threads1077thread_t tid = 0;1078long flags = (UseDetachedThreads ? THR_DETACHED : 0) | THR_SUSPENDED1079| ((UseBoundThreads || os::Solaris::T2_libthread() ||1080(thr_type == vm_thread) ||1081(thr_type == cgc_thread) ||1082(thr_type == pgc_thread) ||1083(thr_type == compiler_thread && BackgroundCompilation)) ?1084THR_BOUND : 0);1085int status;10861087// 4376845 -- libthread/kernel don't provide enough LWPs to utilize all CPUs.1088//1089// On multiprocessors systems, libthread sometimes under-provisions our1090// process with LWPs. On a 30-way systems, for instance, we could have1091// 50 user-level threads in ready state and only 2 or 3 LWPs assigned1092// to our process. This can result in under utilization of PEs.1093// I suspect the problem is related to libthread's LWP1094// pool management and to the kernel's SIGBLOCKING "last LWP parked"1095// upcall policy.1096//1097// The following code is palliative -- it attempts to ensure that our1098// process has sufficient LWPs to take advantage of multiple PEs.1099// Proper long-term cures include using user-level threads bound to LWPs1100// (THR_BOUND) or using LWP-based synchronization. Note that there is a1101// slight timing window with respect to sampling _os_thread_count, but1102// the race is benign. Also, we should periodically recompute1103// _processors_online as the min of SC_NPROCESSORS_ONLN and the1104// the number of PEs in our partition. You might be tempted to use1105// THR_NEW_LWP here, but I'd recommend against it as that could1106// result in undesirable growth of the libthread's LWP pool.1107// The fix below isn't sufficient; for instance, it doesn't take into count1108// LWPs parked on IO. It does, however, help certain CPU-bound benchmarks.1109//1110// Some pathologies this scheme doesn't handle:1111// * Threads can block, releasing the LWPs. The LWPs can age out.1112// When a large number of threads become ready again there aren't1113// enough LWPs available to service them. This can occur when the1114// number of ready threads oscillates.1115// * LWPs/Threads park on IO, thus taking the LWP out of circulation.1116//1117// Finally, we should call thr_setconcurrency() periodically to refresh1118// the LWP pool and thwart the LWP age-out mechanism.1119// The "+3" term provides a little slop -- we want to slightly overprovision.11201121if (AdjustConcurrency && os::Solaris::_os_thread_count < (_processors_online+3)) {1122if (!(flags & THR_BOUND)) {1123thr_setconcurrency (os::Solaris::_os_thread_count); // avoid starvation1124}1125}1126// Although this doesn't hurt, we should warn of undefined behavior1127// when using unbound T1 threads with schedctl(). This should never1128// happen, as the compiler and VM threads are always created bound1129DEBUG_ONLY(1130if ((VMThreadHintNoPreempt || CompilerThreadHintNoPreempt) &&1131(!os::Solaris::T2_libthread() && (!(flags & THR_BOUND))) &&1132((thr_type == vm_thread) || (thr_type == cgc_thread) ||1133(thr_type == pgc_thread) || (thr_type == compiler_thread && BackgroundCompilation))) {1134warning("schedctl behavior undefined when Compiler/VM/GC Threads are Unbound");1135}1136);113711381139// Mark that we don't have an lwp or thread id yet.1140// In case we attempt to set the priority before the thread starts.1141osthread->set_lwp_id(-1);1142osthread->set_thread_id(-1);11431144status = thr_create(NULL, stack_size, java_start, thread, flags, &tid);1145if (status != 0) {1146if (PrintMiscellaneous && (Verbose || WizardMode)) {1147perror("os::create_thread");1148}1149thread->set_osthread(NULL);1150// Need to clean up stuff we've allocated so far1151delete osthread;1152return false;1153}11541155Atomic::inc(&os::Solaris::_os_thread_count);11561157// Store info on the Solaris thread into the OSThread1158osthread->set_thread_id(tid);11591160// Remember that we created this thread so we can set priority on it1161osthread->set_vm_created();11621163// Set the default thread priority. If using bound threads, setting1164// lwp priority will be delayed until thread start.1165set_native_priority(thread,1166DefaultThreadPriority == -1 ?1167java_to_os_priority[NormPriority] :1168DefaultThreadPriority);11691170// Initial thread state is INITIALIZED, not SUSPENDED1171osthread->set_state(INITIALIZED);11721173// The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain1174return true;1175}11761177/* defined for >= Solaris 10. This allows builds on earlier versions1178* of Solaris to take advantage of the newly reserved Solaris JVM signals1179* With SIGJVM1, SIGJVM2, INTERRUPT_SIGNAL is SIGJVM1, ASYNC_SIGNAL is SIGJVM21180* and -XX:+UseAltSigs does nothing since these should have no conflict1181*/1182#if !defined(SIGJVM1)1183#define SIGJVM1 391184#define SIGJVM2 401185#endif11861187debug_only(static bool signal_sets_initialized = false);1188static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs;1189int os::Solaris::_SIGinterrupt = INTERRUPT_SIGNAL;1190int os::Solaris::_SIGasync = ASYNC_SIGNAL;11911192bool os::Solaris::is_sig_ignored(int sig) {1193struct sigaction oact;1194sigaction(sig, (struct sigaction*)NULL, &oact);1195void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction)1196: CAST_FROM_FN_PTR(void*, oact.sa_handler);1197if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN))1198return true;1199else1200return false;1201}12021203// Note: SIGRTMIN is a macro that calls sysconf() so it will1204// dynamically detect SIGRTMIN value for the system at runtime, not buildtime1205static bool isJVM1available() {1206return SIGJVM1 < SIGRTMIN;1207}12081209void os::Solaris::signal_sets_init() {1210// Should also have an assertion stating we are still single-threaded.1211assert(!signal_sets_initialized, "Already initialized");1212// Fill in signals that are necessarily unblocked for all threads in1213// the VM. Currently, we unblock the following signals:1214// SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden1215// by -Xrs (=ReduceSignalUsage));1216// BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all1217// other threads. The "ReduceSignalUsage" boolean tells us not to alter1218// the dispositions or masks wrt these signals.1219// Programs embedding the VM that want to use the above signals for their1220// own purposes must, at this time, use the "-Xrs" option to prevent1221// interference with shutdown hooks and BREAK_SIGNAL thread dumping.1222// (See bug 4345157, and other related bugs).1223// In reality, though, unblocking these signals is really a nop, since1224// these signals are not blocked by default.1225sigemptyset(&unblocked_sigs);1226sigemptyset(&allowdebug_blocked_sigs);1227sigaddset(&unblocked_sigs, SIGILL);1228sigaddset(&unblocked_sigs, SIGSEGV);1229sigaddset(&unblocked_sigs, SIGBUS);1230sigaddset(&unblocked_sigs, SIGFPE);12311232if (isJVM1available) {1233os::Solaris::set_SIGinterrupt(SIGJVM1);1234os::Solaris::set_SIGasync(SIGJVM2);1235} else if (UseAltSigs) {1236os::Solaris::set_SIGinterrupt(ALT_INTERRUPT_SIGNAL);1237os::Solaris::set_SIGasync(ALT_ASYNC_SIGNAL);1238} else {1239os::Solaris::set_SIGinterrupt(INTERRUPT_SIGNAL);1240os::Solaris::set_SIGasync(ASYNC_SIGNAL);1241}12421243sigaddset(&unblocked_sigs, os::Solaris::SIGinterrupt());1244sigaddset(&unblocked_sigs, os::Solaris::SIGasync());12451246if (!ReduceSignalUsage) {1247if (!os::Solaris::is_sig_ignored(SHUTDOWN1_SIGNAL)) {1248sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL);1249sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL);1250}1251if (!os::Solaris::is_sig_ignored(SHUTDOWN2_SIGNAL)) {1252sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL);1253sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL);1254}1255if (!os::Solaris::is_sig_ignored(SHUTDOWN3_SIGNAL)) {1256sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL);1257sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL);1258}1259}1260// Fill in signals that are blocked by all but the VM thread.1261sigemptyset(&vm_sigs);1262if (!ReduceSignalUsage)1263sigaddset(&vm_sigs, BREAK_SIGNAL);1264debug_only(signal_sets_initialized = true);12651266// For diagnostics only used in run_periodic_checks1267sigemptyset(&check_signal_done);1268}12691270// These are signals that are unblocked while a thread is running Java.1271// (For some reason, they get blocked by default.)1272sigset_t* os::Solaris::unblocked_signals() {1273assert(signal_sets_initialized, "Not initialized");1274return &unblocked_sigs;1275}12761277// These are the signals that are blocked while a (non-VM) thread is1278// running Java. Only the VM thread handles these signals.1279sigset_t* os::Solaris::vm_signals() {1280assert(signal_sets_initialized, "Not initialized");1281return &vm_sigs;1282}12831284// These are signals that are blocked during cond_wait to allow debugger in1285sigset_t* os::Solaris::allowdebug_blocked_signals() {1286assert(signal_sets_initialized, "Not initialized");1287return &allowdebug_blocked_sigs;1288}128912901291void _handle_uncaught_cxx_exception() {1292VMError err("An uncaught C++ exception");1293err.report_and_die();1294}129512961297// First crack at OS-specific initialization, from inside the new thread.1298void os::initialize_thread(Thread* thr) {1299if (is_primordial_thread()) {1300JavaThread* jt = (JavaThread *)thr;1301assert(jt != NULL,"Sanity check");1302size_t stack_size;1303address base = jt->stack_base();1304if (Arguments::created_by_java_launcher()) {1305// Use 2MB to allow for Solaris 7 64 bit mode.1306stack_size = JavaThread::stack_size_at_create() == 01307? 2048*K : JavaThread::stack_size_at_create();13081309// There are rare cases when we may have already used more than1310// the basic stack size allotment before this method is invoked.1311// Attempt to allow for a normally sized java_stack.1312size_t current_stack_offset = (size_t)(base - (address)&stack_size);1313stack_size += ReservedSpace::page_align_size_down(current_stack_offset);1314} else {1315// 6269555: If we were not created by a Java launcher, i.e. if we are1316// running embedded in a native application, treat the primordial thread1317// as much like a native attached thread as possible. This means using1318// the current stack size from thr_stksegment(), unless it is too large1319// to reliably setup guard pages. A reasonable max size is 8MB.1320size_t current_size = current_stack_size();1321// This should never happen, but just in case....1322if (current_size == 0) current_size = 2 * K * K;1323stack_size = current_size > (8 * K * K) ? (8 * K * K) : current_size;1324}1325address bottom = (address)align_size_up((intptr_t)(base - stack_size), os::vm_page_size());;1326stack_size = (size_t)(base - bottom);13271328assert(stack_size > 0, "Stack size calculation problem");13291330if (stack_size > jt->stack_size()) {1331NOT_PRODUCT(1332struct rlimit limits;1333getrlimit(RLIMIT_STACK, &limits);1334size_t size = adjust_stack_size(base, (size_t)limits.rlim_cur);1335assert(size >= jt->stack_size(), "Stack size problem in main thread");1336)1337tty->print_cr(1338"Stack size of %d Kb exceeds current limit of %d Kb.\n"1339"(Stack sizes are rounded up to a multiple of the system page size.)\n"1340"See limit(1) to increase the stack size limit.",1341stack_size / K, jt->stack_size() / K);1342vm_exit(1);1343}1344assert(jt->stack_size() >= stack_size,1345"Attempt to map more stack than was allocated");1346jt->set_stack_size(stack_size);1347}13481349// 5/22/01: Right now alternate signal stacks do not handle1350// throwing stack overflow exceptions, see bug 44631781351// Until a fix is found for this, T2 will NOT imply alternate signal1352// stacks.1353// If using T2 libthread threads, install an alternate signal stack.1354// Because alternate stacks associate with LWPs on Solaris,1355// see sigaltstack(2), if using UNBOUND threads, or if UseBoundThreads1356// we prefer to explicitly stack bang.1357// If not using T2 libthread, but using UseBoundThreads any threads1358// (primordial thread, jni_attachCurrentThread) we do not create,1359// probably are not bound, therefore they can not have an alternate1360// signal stack. Since our stack banging code is generated and1361// is shared across threads, all threads must be bound to allow1362// using alternate signal stacks. The alternative is to interpose1363// on _lwp_create to associate an alt sig stack with each LWP,1364// and this could be a problem when the JVM is embedded.1365// We would prefer to use alternate signal stacks with T21366// Since there is currently no accurate way to detect T21367// we do not. Assuming T2 when running T1 causes sig 11s or assertions1368// on installing alternate signal stacks136913701371// 05/09/03: removed alternate signal stack support for Solaris1372// The alternate signal stack mechanism is no longer needed to1373// handle stack overflow. This is now handled by allocating1374// guard pages (red zone) and stackbanging.1375// Initially the alternate signal stack mechanism was removed because1376// it did not work with T1 llibthread. Alternate1377// signal stacks MUST have all threads bound to lwps. Applications1378// can create their own threads and attach them without their being1379// bound under T1. This is frequently the case for the primordial thread.1380// If we were ever to reenable this mechanism we would need to1381// use the dynamic check for T2 libthread.13821383os::Solaris::init_thread_fpu_state();1384std::set_terminate(_handle_uncaught_cxx_exception);1385}1386138713881389// Free Solaris resources related to the OSThread1390void os::free_thread(OSThread* osthread) {1391assert(osthread != NULL, "os::free_thread but osthread not set");139213931394// We are told to free resources of the argument thread,1395// but we can only really operate on the current thread.1396// The main thread must take the VMThread down synchronously1397// before the main thread exits and frees up CodeHeap1398guarantee((Thread::current()->osthread() == osthread1399|| (osthread == VMThread::vm_thread()->osthread())), "os::free_thread but not current thread");1400if (Thread::current()->osthread() == osthread) {1401// Restore caller's signal mask1402sigset_t sigmask = osthread->caller_sigmask();1403thr_sigsetmask(SIG_SETMASK, &sigmask, NULL);1404}1405delete osthread;1406}14071408void os::pd_start_thread(Thread* thread) {1409int status = thr_continue(thread->osthread()->thread_id());1410assert_status(status == 0, status, "thr_continue failed");1411}141214131414intx os::current_thread_id() {1415return (intx)thr_self();1416}14171418static pid_t _initial_pid = 0;14191420int os::current_process_id() {1421return (int)(_initial_pid ? _initial_pid : getpid());1422}14231424// gethrtime() should be monotonic according to the documentation,1425// but some virtualized platforms are known to break this guarantee.1426// getTimeNanos() must be guaranteed not to move backwards, so we1427// are forced to add a check here.1428inline hrtime_t getTimeNanos() {1429const hrtime_t now = gethrtime();1430const hrtime_t prev = max_hrtime;1431if (now <= prev) {1432return prev; // same or retrograde time;1433}1434const hrtime_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&max_hrtime, prev);1435assert(obsv >= prev, "invariant"); // Monotonicity1436// If the CAS succeeded then we're done and return "now".1437// If the CAS failed and the observed value "obsv" is >= now then1438// we should return "obsv". If the CAS failed and now > obsv > prv then1439// some other thread raced this thread and installed a new value, in which case1440// we could either (a) retry the entire operation, (b) retry trying to install now1441// or (c) just return obsv. We use (c). No loop is required although in some cases1442// we might discard a higher "now" value in deference to a slightly lower but freshly1443// installed obsv value. That's entirely benign -- it admits no new orderings compared1444// to (a) or (b) -- and greatly reduces coherence traffic.1445// We might also condition (c) on the magnitude of the delta between obsv and now.1446// Avoiding excessive CAS operations to hot RW locations is critical.1447// See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate1448return (prev == obsv) ? now : obsv;1449}14501451// Time since start-up in seconds to a fine granularity.1452// Used by VMSelfDestructTimer and the MemProfiler.1453double os::elapsedTime() {1454return (double)(getTimeNanos() - first_hrtime) / (double)hrtime_hz;1455}14561457jlong os::elapsed_counter() {1458return (jlong)(getTimeNanos() - first_hrtime);1459}14601461jlong os::elapsed_frequency() {1462return hrtime_hz;1463}14641465// Return the real, user, and system times in seconds from an1466// arbitrary fixed point in the past.1467bool os::getTimesSecs(double* process_real_time,1468double* process_user_time,1469double* process_system_time) {1470struct tms ticks;1471clock_t real_ticks = times(&ticks);14721473if (real_ticks == (clock_t) (-1)) {1474return false;1475} else {1476double ticks_per_second = (double) clock_tics_per_sec;1477*process_user_time = ((double) ticks.tms_utime) / ticks_per_second;1478*process_system_time = ((double) ticks.tms_stime) / ticks_per_second;1479// For consistency return the real time from getTimeNanos()1480// converted to seconds.1481*process_real_time = ((double) getTimeNanos()) / ((double) NANOUNITS);14821483return true;1484}1485}14861487bool os::supports_vtime() { return true; }14881489bool os::enable_vtime() {1490int fd = ::open("/proc/self/ctl", O_WRONLY);1491if (fd == -1)1492return false;14931494long cmd[] = { PCSET, PR_MSACCT };1495int res = ::write(fd, cmd, sizeof(long) * 2);1496::close(fd);1497if (res != sizeof(long) * 2)1498return false;14991500return true;1501}15021503bool os::vtime_enabled() {1504int fd = ::open("/proc/self/status", O_RDONLY);1505if (fd == -1)1506return false;15071508pstatus_t status;1509int res = os::read(fd, (void*) &status, sizeof(pstatus_t));1510::close(fd);1511if (res != sizeof(pstatus_t))1512return false;15131514return status.pr_flags & PR_MSACCT;1515}15161517double os::elapsedVTime() {1518return (double)gethrvtime() / (double)hrtime_hz;1519}15201521// Used internally for comparisons only1522// getTimeMillis guaranteed to not move backwards on Solaris1523jlong getTimeMillis() {1524jlong nanotime = getTimeNanos();1525return (jlong)(nanotime / NANOSECS_PER_MILLISEC);1526}15271528// Must return millis since Jan 1 1970 for JVM_CurrentTimeMillis1529jlong os::javaTimeMillis() {1530timeval t;1531if (gettimeofday( &t, NULL) == -1)1532fatal(err_msg("os::javaTimeMillis: gettimeofday (%s)", strerror(errno)));1533return jlong(t.tv_sec) * 1000 + jlong(t.tv_usec) / 1000;1534}15351536jlong os::javaTimeNanos() {1537return (jlong)getTimeNanos();1538}15391540void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {1541info_ptr->max_value = ALL_64_BITS; // gethrtime() uses all 64 bits1542info_ptr->may_skip_backward = false; // not subject to resetting or drifting1543info_ptr->may_skip_forward = false; // not subject to resetting or drifting1544info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time1545}15461547char * os::local_time_string(char *buf, size_t buflen) {1548struct tm t;1549time_t long_time;1550time(&long_time);1551localtime_r(&long_time, &t);1552jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d",1553t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,1554t.tm_hour, t.tm_min, t.tm_sec);1555return buf;1556}15571558// Note: os::shutdown() might be called very early during initialization, or1559// called from signal handler. Before adding something to os::shutdown(), make1560// sure it is async-safe and can handle partially initialized VM.1561void os::shutdown() {15621563// allow PerfMemory to attempt cleanup of any persistent resources1564perfMemory_exit();15651566// needs to remove object in file system1567AttachListener::abort();15681569// flush buffered output, finish log files1570ostream_abort();15711572// Check for abort hook1573abort_hook_t abort_hook = Arguments::abort_hook();1574if (abort_hook != NULL) {1575abort_hook();1576}1577}15781579// Note: os::abort() might be called very early during initialization, or1580// called from signal handler. Before adding something to os::abort(), make1581// sure it is async-safe and can handle partially initialized VM.1582void os::abort(bool dump_core) {1583os::shutdown();1584if (dump_core) {1585#ifndef PRODUCT1586fdStream out(defaultStream::output_fd());1587out.print_raw("Current thread is ");1588char buf[16];1589jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id());1590out.print_raw_cr(buf);1591out.print_raw_cr("Dumping core ...");1592#endif1593::abort(); // dump core (for debugging)1594}15951596::exit(1);1597}15981599// Die immediately, no exit hook, no abort hook, no cleanup.1600void os::die() {1601::abort(); // dump core (for debugging)1602}16031604// DLL functions16051606const char* os::dll_file_extension() { return ".so"; }16071608// This must be hard coded because it's the system's temporary1609// directory not the java application's temp directory, ala java.io.tmpdir.1610const char* os::get_temp_directory() { return "/tmp"; }16111612static bool file_exists(const char* filename) {1613struct stat statbuf;1614if (filename == NULL || strlen(filename) == 0) {1615return false;1616}1617return os::stat(filename, &statbuf) == 0;1618}16191620bool os::dll_build_name(char* buffer, size_t buflen,1621const char* pname, const char* fname) {1622bool retval = false;1623const size_t pnamelen = pname ? strlen(pname) : 0;16241625// Return error on buffer overflow.1626if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {1627return retval;1628}16291630if (pnamelen == 0) {1631snprintf(buffer, buflen, "lib%s.so", fname);1632retval = true;1633} else if (strchr(pname, *os::path_separator()) != NULL) {1634int n;1635char** pelements = split_path(pname, &n);1636if (pelements == NULL) {1637return false;1638}1639for (int i = 0 ; i < n ; i++) {1640// really shouldn't be NULL but what the heck, check can't hurt1641if (pelements[i] == NULL || strlen(pelements[i]) == 0) {1642continue; // skip the empty path values1643}1644snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);1645if (file_exists(buffer)) {1646retval = true;1647break;1648}1649}1650// release the storage1651for (int i = 0 ; i < n ; i++) {1652if (pelements[i] != NULL) {1653FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal);1654}1655}1656if (pelements != NULL) {1657FREE_C_HEAP_ARRAY(char*, pelements, mtInternal);1658}1659} else {1660snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);1661retval = true;1662}1663return retval;1664}16651666// check if addr is inside libjvm.so1667bool os::address_is_in_vm(address addr) {1668static address libjvm_base_addr;1669Dl_info dlinfo;16701671if (libjvm_base_addr == NULL) {1672if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {1673libjvm_base_addr = (address)dlinfo.dli_fbase;1674}1675assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");1676}16771678if (dladdr((void *)addr, &dlinfo) != 0) {1679if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;1680}16811682return false;1683}16841685typedef int (*dladdr1_func_type) (void *, Dl_info *, void **, int);1686static dladdr1_func_type dladdr1_func = NULL;16871688bool os::dll_address_to_function_name(address addr, char *buf,1689int buflen, int * offset) {1690// buf is not optional, but offset is optional1691assert(buf != NULL, "sanity check");16921693Dl_info dlinfo;16941695// dladdr1_func was initialized in os::init()1696if (dladdr1_func != NULL) {1697// yes, we have dladdr116981699// Support for dladdr1 is checked at runtime; it may be1700// available even if the vm is built on a machine that does1701// not have dladdr1 support. Make sure there is a value for1702// RTLD_DL_SYMENT.1703#ifndef RTLD_DL_SYMENT1704#define RTLD_DL_SYMENT 11705#endif1706#ifdef _LP641707Elf64_Sym * info;1708#else1709Elf32_Sym * info;1710#endif1711if (dladdr1_func((void *)addr, &dlinfo, (void **)&info,1712RTLD_DL_SYMENT) != 0) {1713// see if we have a matching symbol that covers our address1714if (dlinfo.dli_saddr != NULL &&1715(char *)dlinfo.dli_saddr + info->st_size > (char *)addr) {1716if (dlinfo.dli_sname != NULL) {1717if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {1718jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);1719}1720if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;1721return true;1722}1723}1724// no matching symbol so try for just file info1725if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {1726if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),1727buf, buflen, offset, dlinfo.dli_fname)) {1728return true;1729}1730}1731}1732buf[0] = '\0';1733if (offset != NULL) *offset = -1;1734return false;1735}17361737// no, only dladdr is available1738if (dladdr((void *)addr, &dlinfo) != 0) {1739// see if we have a matching symbol1740if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {1741if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) {1742jio_snprintf(buf, buflen, dlinfo.dli_sname);1743}1744if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;1745return true;1746}1747// no matching symbol so try for just file info1748if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {1749if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),1750buf, buflen, offset, dlinfo.dli_fname)) {1751return true;1752}1753}1754}1755buf[0] = '\0';1756if (offset != NULL) *offset = -1;1757return false;1758}17591760bool os::dll_address_to_library_name(address addr, char* buf,1761int buflen, int* offset) {1762// buf is not optional, but offset is optional1763assert(buf != NULL, "sanity check");17641765Dl_info dlinfo;17661767if (dladdr((void*)addr, &dlinfo) != 0) {1768if (dlinfo.dli_fname != NULL) {1769jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);1770}1771if (dlinfo.dli_fbase != NULL && offset != NULL) {1772*offset = addr - (address)dlinfo.dli_fbase;1773}1774return true;1775}17761777buf[0] = '\0';1778if (offset) *offset = -1;1779return false;1780}17811782// Prints the names and full paths of all opened dynamic libraries1783// for current process1784void os::print_dll_info(outputStream * st) {1785Dl_info dli;1786void *handle;1787Link_map *map;1788Link_map *p;17891790st->print_cr("Dynamic libraries:"); st->flush();17911792if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 ||1793dli.dli_fname == NULL) {1794st->print_cr("Error: Cannot print dynamic libraries.");1795return;1796}1797handle = dlopen(dli.dli_fname, RTLD_LAZY);1798if (handle == NULL) {1799st->print_cr("Error: Cannot print dynamic libraries.");1800return;1801}1802dlinfo(handle, RTLD_DI_LINKMAP, &map);1803if (map == NULL) {1804st->print_cr("Error: Cannot print dynamic libraries.");1805return;1806}18071808while (map->l_prev != NULL)1809map = map->l_prev;18101811while (map != NULL) {1812st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);1813map = map->l_next;1814}18151816dlclose(handle);1817}18181819int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {1820Dl_info dli;1821// Sanity check?1822if (dladdr(CAST_FROM_FN_PTR(void *, os::get_loaded_modules_info), &dli) == 0 ||1823dli.dli_fname == NULL) {1824return 1;1825}18261827void * handle = dlopen(dli.dli_fname, RTLD_LAZY);1828if (handle == NULL) {1829return 1;1830}18311832Link_map *map;1833dlinfo(handle, RTLD_DI_LINKMAP, &map);1834if (map == NULL) {1835dlclose(handle);1836return 1;1837}18381839while (map->l_prev != NULL) {1840map = map->l_prev;1841}18421843while (map != NULL) {1844// Iterate through all map entries and call callback with fields of interest1845if(callback(map->l_name, (address)map->l_addr, (address)0, param)) {1846dlclose(handle);1847return 1;1848}1849map = map->l_next;1850}18511852dlclose(handle);1853return 0;1854}18551856// Loads .dll/.so and1857// in case of error it checks if .dll/.so was built for the1858// same architecture as Hotspot is running on18591860void * os::dll_load(const char *filename, char *ebuf, int ebuflen)1861{1862void * result= ::dlopen(filename, RTLD_LAZY);1863if (result != NULL) {1864// Successful loading1865return result;1866}18671868Elf32_Ehdr elf_head;18691870// Read system error message into ebuf1871// It may or may not be overwritten below1872::strncpy(ebuf, ::dlerror(), ebuflen-1);1873ebuf[ebuflen-1]='\0';1874int diag_msg_max_length=ebuflen-strlen(ebuf);1875char* diag_msg_buf=ebuf+strlen(ebuf);18761877if (diag_msg_max_length==0) {1878// No more space in ebuf for additional diagnostics message1879return NULL;1880}188118821883int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);18841885if (file_descriptor < 0) {1886// Can't open library, report dlerror() message1887return NULL;1888}18891890bool failed_to_read_elf_head=1891(sizeof(elf_head)!=1892(::read(file_descriptor, &elf_head,sizeof(elf_head)))) ;18931894::close(file_descriptor);1895if (failed_to_read_elf_head) {1896// file i/o error - report dlerror() msg1897return NULL;1898}18991900typedef struct {1901Elf32_Half code; // Actual value as defined in elf.h1902Elf32_Half compat_class; // Compatibility of archs at VM's sense1903char elf_class; // 32 or 64 bit1904char endianess; // MSB or LSB1905char* name; // String representation1906} arch_t;19071908static const arch_t arch_array[]={1909{EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},1910{EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},1911{EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},1912{EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},1913{EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},1914{EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},1915{EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},1916{EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},1917{EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},1918{EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM 32"}1919};19201921#if (defined IA32)1922static Elf32_Half running_arch_code=EM_386;1923#elif (defined AMD64)1924static Elf32_Half running_arch_code=EM_X86_64;1925#elif (defined IA64)1926static Elf32_Half running_arch_code=EM_IA_64;1927#elif (defined __sparc) && (defined _LP64)1928static Elf32_Half running_arch_code=EM_SPARCV9;1929#elif (defined __sparc) && (!defined _LP64)1930static Elf32_Half running_arch_code=EM_SPARC;1931#elif (defined __powerpc64__)1932static Elf32_Half running_arch_code=EM_PPC64;1933#elif (defined __powerpc__)1934static Elf32_Half running_arch_code=EM_PPC;1935#elif (defined ARM)1936static Elf32_Half running_arch_code=EM_ARM;1937#else1938#error Method os::dll_load requires that one of following is defined:\1939IA32, AMD64, IA64, __sparc, __powerpc__, ARM, ARM1940#endif19411942// Identify compatability class for VM's architecture and library's architecture1943// Obtain string descriptions for architectures19441945arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};1946int running_arch_index=-1;19471948for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) {1949if (running_arch_code == arch_array[i].code) {1950running_arch_index = i;1951}1952if (lib_arch.code == arch_array[i].code) {1953lib_arch.compat_class = arch_array[i].compat_class;1954lib_arch.name = arch_array[i].name;1955}1956}19571958assert(running_arch_index != -1,1959"Didn't find running architecture code (running_arch_code) in arch_array");1960if (running_arch_index == -1) {1961// Even though running architecture detection failed1962// we may still continue with reporting dlerror() message1963return NULL;1964}19651966if (lib_arch.endianess != arch_array[running_arch_index].endianess) {1967::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)");1968return NULL;1969}19701971if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {1972::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)");1973return NULL;1974}19751976if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {1977if ( lib_arch.name!=NULL ) {1978::snprintf(diag_msg_buf, diag_msg_max_length-1,1979" (Possible cause: can't load %s-bit .so on a %s-bit platform)",1980lib_arch.name, arch_array[running_arch_index].name);1981} else {1982::snprintf(diag_msg_buf, diag_msg_max_length-1,1983" (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)",1984lib_arch.code,1985arch_array[running_arch_index].name);1986}1987}19881989return NULL;1990}19911992void* os::dll_lookup(void* handle, const char* name) {1993return dlsym(handle, name);1994}19951996void* os::get_default_process_handle() {1997return (void*)::dlopen(NULL, RTLD_LAZY);1998}19992000int os::stat(const char *path, struct stat *sbuf) {2001char pathbuf[MAX_PATH];2002if (strlen(path) > MAX_PATH - 1) {2003errno = ENAMETOOLONG;2004return -1;2005}2006os::native_path(strcpy(pathbuf, path));2007return ::stat(pathbuf, sbuf);2008}20092010static bool _print_ascii_file(const char* filename, outputStream* st) {2011int fd = ::open(filename, O_RDONLY);2012if (fd == -1) {2013return false;2014}20152016char buf[32];2017int bytes;2018while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) {2019st->print_raw(buf, bytes);2020}20212022::close(fd);20232024return true;2025}20262027void os::print_os_info_brief(outputStream* st) {2028os::Solaris::print_distro_info(st);20292030os::Posix::print_uname_info(st);20312032os::Solaris::print_libversion_info(st);2033}20342035void os::print_os_info(outputStream* st) {2036st->print("OS:");20372038os::Solaris::print_distro_info(st);20392040os::Posix::print_uname_info(st);20412042os::Solaris::print_libversion_info(st);20432044os::Posix::print_rlimit_info(st);20452046os::Posix::print_load_average(st);2047}20482049void os::Solaris::print_distro_info(outputStream* st) {2050if (!_print_ascii_file("/etc/release", st)) {2051st->print("Solaris");2052}2053st->cr();2054}20552056void os::Solaris::print_libversion_info(outputStream* st) {2057if (os::Solaris::T2_libthread()) {2058st->print(" (T2 libthread)");2059}2060else {2061st->print(" (T1 libthread)");2062}2063st->cr();2064}20652066static bool check_addr0(outputStream* st) {2067jboolean status = false;2068int fd = ::open("/proc/self/map",O_RDONLY);2069if (fd >= 0) {2070prmap_t p;2071while(::read(fd, &p, sizeof(p)) > 0) {2072if (p.pr_vaddr == 0x0) {2073st->print("Warning: Address: 0x%x, Size: %dK, ",p.pr_vaddr, p.pr_size/1024, p.pr_mapname);2074st->print("Mapped file: %s, ", p.pr_mapname[0] == '\0' ? "None" : p.pr_mapname);2075st->print("Access:");2076st->print("%s",(p.pr_mflags & MA_READ) ? "r" : "-");2077st->print("%s",(p.pr_mflags & MA_WRITE) ? "w" : "-");2078st->print("%s",(p.pr_mflags & MA_EXEC) ? "x" : "-");2079st->cr();2080status = true;2081}2082}2083::close(fd);2084}2085return status;2086}20872088void os::pd_print_cpu_info(outputStream* st) {2089// Nothing to do for now.2090}20912092void os::print_memory_info(outputStream* st) {2093st->print("Memory:");2094st->print(" %dk page", os::vm_page_size()>>10);2095st->print(", physical " UINT64_FORMAT "k", os::physical_memory()>>10);2096st->print("(" UINT64_FORMAT "k free)", os::available_memory() >> 10);2097st->cr();2098if (VMError::fatal_error_in_progress()) {2099(void) check_addr0(st);2100}2101}21022103void os::print_siginfo(outputStream* st, void* siginfo) {2104const siginfo_t* si = (const siginfo_t*)siginfo;21052106os::Posix::print_siginfo_brief(st, si);21072108if (si && (si->si_signo == SIGBUS || si->si_signo == SIGSEGV) &&2109UseSharedSpaces) {2110FileMapInfo* mapinfo = FileMapInfo::current_info();2111if (mapinfo->is_in_shared_space(si->si_addr)) {2112st->print("\n\nError accessing class data sharing archive." \2113" Mapped file inaccessible during execution, " \2114" possible disk/network problem.");2115}2116}2117st->cr();2118}21192120// Moved from whole group, because we need them here for diagnostic2121// prints.2122#define OLDMAXSIGNUM 322123static int Maxsignum = 0;2124static int *ourSigFlags = NULL;21252126extern "C" void sigINTRHandler(int, siginfo_t*, void*);21272128int os::Solaris::get_our_sigflags(int sig) {2129assert(ourSigFlags!=NULL, "signal data structure not initialized");2130assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range");2131return ourSigFlags[sig];2132}21332134void os::Solaris::set_our_sigflags(int sig, int flags) {2135assert(ourSigFlags!=NULL, "signal data structure not initialized");2136assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range");2137ourSigFlags[sig] = flags;2138}213921402141static const char* get_signal_handler_name(address handler,2142char* buf, int buflen) {2143int offset;2144bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset);2145if (found) {2146// skip directory names2147const char *p1, *p2;2148p1 = buf;2149size_t len = strlen(os::file_separator());2150while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;2151jio_snprintf(buf, buflen, "%s+0x%x", p1, offset);2152} else {2153jio_snprintf(buf, buflen, PTR_FORMAT, handler);2154}2155return buf;2156}21572158static void print_signal_handler(outputStream* st, int sig,2159char* buf, size_t buflen) {2160struct sigaction sa;21612162sigaction(sig, NULL, &sa);21632164st->print("%s: ", os::exception_name(sig, buf, buflen));21652166address handler = (sa.sa_flags & SA_SIGINFO)2167? CAST_FROM_FN_PTR(address, sa.sa_sigaction)2168: CAST_FROM_FN_PTR(address, sa.sa_handler);21692170if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) {2171st->print("SIG_DFL");2172} else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) {2173st->print("SIG_IGN");2174} else {2175st->print("[%s]", get_signal_handler_name(handler, buf, buflen));2176}21772178st->print(", sa_mask[0]=");2179os::Posix::print_signal_set_short(st, &sa.sa_mask);21802181address rh = VMError::get_resetted_sighandler(sig);2182// May be, handler was resetted by VMError?2183if(rh != NULL) {2184handler = rh;2185sa.sa_flags = VMError::get_resetted_sigflags(sig);2186}21872188st->print(", sa_flags=");2189os::Posix::print_sa_flags(st, sa.sa_flags);21902191// Check: is it our handler?2192if(handler == CAST_FROM_FN_PTR(address, signalHandler) ||2193handler == CAST_FROM_FN_PTR(address, sigINTRHandler)) {2194// It is our signal handler2195// check for flags2196if(sa.sa_flags != os::Solaris::get_our_sigflags(sig)) {2197st->print(2198", flags was changed from " PTR32_FORMAT ", consider using jsig library",2199os::Solaris::get_our_sigflags(sig));2200}2201}2202st->cr();2203}22042205void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) {2206st->print_cr("Signal Handlers:");2207print_signal_handler(st, SIGSEGV, buf, buflen);2208print_signal_handler(st, SIGBUS , buf, buflen);2209print_signal_handler(st, SIGFPE , buf, buflen);2210print_signal_handler(st, SIGPIPE, buf, buflen);2211print_signal_handler(st, SIGXFSZ, buf, buflen);2212print_signal_handler(st, SIGILL , buf, buflen);2213print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen);2214print_signal_handler(st, ASYNC_SIGNAL, buf, buflen);2215print_signal_handler(st, BREAK_SIGNAL, buf, buflen);2216print_signal_handler(st, SHUTDOWN1_SIGNAL , buf, buflen);2217print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen);2218print_signal_handler(st, SHUTDOWN3_SIGNAL, buf, buflen);2219print_signal_handler(st, os::Solaris::SIGinterrupt(), buf, buflen);2220print_signal_handler(st, os::Solaris::SIGasync(), buf, buflen);2221}22222223static char saved_jvm_path[MAXPATHLEN] = { 0 };22242225// Find the full path to the current module, libjvm.so2226void os::jvm_path(char *buf, jint buflen) {2227// Error checking.2228if (buflen < MAXPATHLEN) {2229assert(false, "must use a large-enough buffer");2230buf[0] = '\0';2231return;2232}2233// Lazy resolve the path to current module.2234if (saved_jvm_path[0] != 0) {2235strcpy(buf, saved_jvm_path);2236return;2237}22382239Dl_info dlinfo;2240int ret = dladdr(CAST_FROM_FN_PTR(void *, os::jvm_path), &dlinfo);2241assert(ret != 0, "cannot locate libjvm");2242if (ret != 0 && dlinfo.dli_fname != NULL) {2243realpath((char *)dlinfo.dli_fname, buf);2244} else {2245buf[0] = '\0';2246return;2247}22482249if (Arguments::created_by_gamma_launcher()) {2250// Support for the gamma launcher. Typical value for buf is2251// "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so". If "/jre/lib/" appears at2252// the right place in the string, then assume we are installed in a JDK and2253// we're done. Otherwise, check for a JAVA_HOME environment variable and fix2254// up the path so it looks like libjvm.so is installed there (append a2255// fake suffix hotspot/libjvm.so).2256const char *p = buf + strlen(buf) - 1;2257for (int count = 0; p > buf && count < 5; ++count) {2258for (--p; p > buf && *p != '/'; --p)2259/* empty */ ;2260}22612262if (strncmp(p, "/jre/lib/", 9) != 0) {2263// Look for JAVA_HOME in the environment.2264char* java_home_var = ::getenv("JAVA_HOME");2265if (java_home_var != NULL && java_home_var[0] != 0) {2266char cpu_arch[12];2267char* jrelib_p;2268int len;2269sysinfo(SI_ARCHITECTURE, cpu_arch, sizeof(cpu_arch));2270#ifdef _LP642271// If we are on sparc running a 64-bit vm, look in jre/lib/sparcv9.2272if (strcmp(cpu_arch, "sparc") == 0) {2273strcat(cpu_arch, "v9");2274} else if (strcmp(cpu_arch, "i386") == 0) {2275strcpy(cpu_arch, "amd64");2276}2277#endif2278// Check the current module name "libjvm.so".2279p = strrchr(buf, '/');2280assert(strstr(p, "/libjvm") == p, "invalid library name");22812282realpath(java_home_var, buf);2283// determine if this is a legacy image or modules image2284// modules image doesn't have "jre" subdirectory2285len = strlen(buf);2286assert(len < buflen, "Ran out of buffer space");2287jrelib_p = buf + len;2288snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch);2289if (0 != access(buf, F_OK)) {2290snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch);2291}22922293if (0 == access(buf, F_OK)) {2294// Use current module name "libjvm.so"2295len = strlen(buf);2296snprintf(buf + len, buflen-len, "/hotspot/libjvm.so");2297} else {2298// Go back to path of .so2299realpath((char *)dlinfo.dli_fname, buf);2300}2301}2302}2303}23042305strncpy(saved_jvm_path, buf, MAXPATHLEN);2306}230723082309void os::print_jni_name_prefix_on(outputStream* st, int args_size) {2310// no prefix required, not even "_"2311}231223132314void os::print_jni_name_suffix_on(outputStream* st, int args_size) {2315// no suffix required2316}23172318// This method is a copy of JDK's sysGetLastErrorString2319// from src/solaris/hpi/src/system_md.c23202321size_t os::lasterror(char *buf, size_t len) {23222323if (errno == 0) return 0;23242325const char *s = ::strerror(errno);2326size_t n = ::strlen(s);2327if (n >= len) {2328n = len - 1;2329}2330::strncpy(buf, s, n);2331buf[n] = '\0';2332return n;2333}233423352336// sun.misc.Signal23372338extern "C" {2339static void UserHandler(int sig, void *siginfo, void *context) {2340// Ctrl-C is pressed during error reporting, likely because the error2341// handler fails to abort. Let VM die immediately.2342if (sig == SIGINT && is_error_reported()) {2343os::die();2344}23452346os::signal_notify(sig);2347// We do not need to reinstate the signal handler each time...2348}2349}23502351void* os::user_handler() {2352return CAST_FROM_FN_PTR(void*, UserHandler);2353}23542355class Semaphore : public StackObj {2356public:2357Semaphore();2358~Semaphore();2359void signal();2360void wait();2361bool trywait();2362bool timedwait(unsigned int sec, int nsec);2363private:2364sema_t _semaphore;2365};236623672368Semaphore::Semaphore() {2369sema_init(&_semaphore, 0, NULL, NULL);2370}23712372Semaphore::~Semaphore() {2373sema_destroy(&_semaphore);2374}23752376void Semaphore::signal() {2377sema_post(&_semaphore);2378}23792380void Semaphore::wait() {2381sema_wait(&_semaphore);2382}23832384bool Semaphore::trywait() {2385return sema_trywait(&_semaphore) == 0;2386}23872388bool Semaphore::timedwait(unsigned int sec, int nsec) {2389struct timespec ts;2390unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec);23912392while (1) {2393int result = sema_timedwait(&_semaphore, &ts);2394if (result == 0) {2395return true;2396} else if (errno == EINTR) {2397continue;2398} else if (errno == ETIME) {2399return false;2400} else {2401return false;2402}2403}2404}24052406extern "C" {2407typedef void (*sa_handler_t)(int);2408typedef void (*sa_sigaction_t)(int, siginfo_t *, void *);2409}24102411void* os::signal(int signal_number, void* handler) {2412struct sigaction sigAct, oldSigAct;2413sigfillset(&(sigAct.sa_mask));2414sigAct.sa_flags = SA_RESTART & ~SA_RESETHAND;2415sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler);24162417if (sigaction(signal_number, &sigAct, &oldSigAct))2418// -1 means registration failed2419return (void *)-1;24202421return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler);2422}24232424void os::signal_raise(int signal_number) {2425raise(signal_number);2426}24272428/*2429* The following code is moved from os.cpp for making this2430* code platform specific, which it is by its very nature.2431*/24322433// a counter for each possible signal value2434static int Sigexit = 0;2435static int Maxlibjsigsigs;2436static jint *pending_signals = NULL;2437static int *preinstalled_sigs = NULL;2438static struct sigaction *chainedsigactions = NULL;2439static sema_t sig_sem;2440typedef int (*version_getting_t)();2441version_getting_t os::Solaris::get_libjsig_version = NULL;2442static int libjsigversion = NULL;24432444int os::sigexitnum_pd() {2445assert(Sigexit > 0, "signal memory not yet initialized");2446return Sigexit;2447}24482449void os::Solaris::init_signal_mem() {2450// Initialize signal structures2451Maxsignum = SIGRTMAX;2452Sigexit = Maxsignum+1;2453assert(Maxsignum >0, "Unable to obtain max signal number");24542455Maxlibjsigsigs = Maxsignum;24562457// pending_signals has one int per signal2458// The additional signal is for SIGEXIT - exit signal to signal_thread2459pending_signals = (jint *)os::malloc(sizeof(jint) * (Sigexit+1), mtInternal);2460memset(pending_signals, 0, (sizeof(jint) * (Sigexit+1)));24612462if (UseSignalChaining) {2463chainedsigactions = (struct sigaction *)malloc(sizeof(struct sigaction)2464* (Maxsignum + 1), mtInternal);2465memset(chainedsigactions, 0, (sizeof(struct sigaction) * (Maxsignum + 1)));2466preinstalled_sigs = (int *)os::malloc(sizeof(int) * (Maxsignum + 1), mtInternal);2467memset(preinstalled_sigs, 0, (sizeof(int) * (Maxsignum + 1)));2468}2469ourSigFlags = (int*)malloc(sizeof(int) * (Maxsignum + 1 ), mtInternal);2470memset(ourSigFlags, 0, sizeof(int) * (Maxsignum + 1));2471}24722473void os::signal_init_pd() {2474int ret;24752476ret = ::sema_init(&sig_sem, 0, NULL, NULL);2477assert(ret == 0, "sema_init() failed");2478}24792480void os::signal_notify(int signal_number) {2481int ret;24822483Atomic::inc(&pending_signals[signal_number]);2484ret = ::sema_post(&sig_sem);2485assert(ret == 0, "sema_post() failed");2486}24872488static int check_pending_signals(bool wait_for_signal) {2489int ret;2490while (true) {2491for (int i = 0; i < Sigexit + 1; i++) {2492jint n = pending_signals[i];2493if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) {2494return i;2495}2496}2497if (!wait_for_signal) {2498return -1;2499}2500JavaThread *thread = JavaThread::current();2501ThreadBlockInVM tbivm(thread);25022503bool threadIsSuspended;2504do {2505thread->set_suspend_equivalent();2506// cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()2507while((ret = ::sema_wait(&sig_sem)) == EINTR)2508;2509assert(ret == 0, "sema_wait() failed");25102511// were we externally suspended while we were waiting?2512threadIsSuspended = thread->handle_special_suspend_equivalent_condition();2513if (threadIsSuspended) {2514//2515// The semaphore has been incremented, but while we were waiting2516// another thread suspended us. We don't want to continue running2517// while suspended because that would surprise the thread that2518// suspended us.2519//2520ret = ::sema_post(&sig_sem);2521assert(ret == 0, "sema_post() failed");25222523thread->java_suspend_self();2524}2525} while (threadIsSuspended);2526}2527}25282529int os::signal_lookup() {2530return check_pending_signals(false);2531}25322533int os::signal_wait() {2534return check_pending_signals(true);2535}25362537////////////////////////////////////////////////////////////////////////////////2538// Virtual Memory25392540static int page_size = -1;25412542// The mmap MAP_ALIGN flag is supported on Solaris 9 and later. init_2() will2543// clear this var if support is not available.2544static bool has_map_align = true;25452546int os::vm_page_size() {2547assert(page_size != -1, "must call os::init");2548return page_size;2549}25502551// Solaris allocates memory by pages.2552int os::vm_allocation_granularity() {2553assert(page_size != -1, "must call os::init");2554return page_size;2555}25562557static bool recoverable_mmap_error(int err) {2558// See if the error is one we can let the caller handle. This2559// list of errno values comes from the Solaris mmap(2) man page.2560switch (err) {2561case EBADF:2562case EINVAL:2563case ENOTSUP:2564// let the caller deal with these errors2565return true;25662567default:2568// Any remaining errors on this OS can cause our reserved mapping2569// to be lost. That can cause confusion where different data2570// structures think they have the same memory mapped. The worst2571// scenario is if both the VM and a library think they have the2572// same memory mapped.2573return false;2574}2575}25762577static void warn_fail_commit_memory(char* addr, size_t bytes, bool exec,2578int err) {2579warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT2580", %d) failed; error='%s' (errno=%d)", addr, bytes, exec,2581strerror(err), err);2582}25832584static void warn_fail_commit_memory(char* addr, size_t bytes,2585size_t alignment_hint, bool exec,2586int err) {2587warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT2588", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, bytes,2589alignment_hint, exec, strerror(err), err);2590}25912592int os::Solaris::commit_memory_impl(char* addr, size_t bytes, bool exec) {2593int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;2594size_t size = bytes;2595char *res = Solaris::mmap_chunk(addr, size, MAP_PRIVATE|MAP_FIXED, prot);2596if (res != NULL) {2597if (UseNUMAInterleaving) {2598numa_make_global(addr, bytes);2599}2600return 0;2601}26022603int err = errno; // save errno from mmap() call in mmap_chunk()26042605if (!recoverable_mmap_error(err)) {2606warn_fail_commit_memory(addr, bytes, exec, err);2607vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "committing reserved memory.");2608}26092610return err;2611}26122613bool os::pd_commit_memory(char* addr, size_t bytes, bool exec) {2614return Solaris::commit_memory_impl(addr, bytes, exec) == 0;2615}26162617void os::pd_commit_memory_or_exit(char* addr, size_t bytes, bool exec,2618const char* mesg) {2619assert(mesg != NULL, "mesg must be specified");2620int err = os::Solaris::commit_memory_impl(addr, bytes, exec);2621if (err != 0) {2622// the caller wants all commit errors to exit with the specified mesg:2623warn_fail_commit_memory(addr, bytes, exec, err);2624vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, mesg);2625}2626}26272628size_t os::Solaris::page_size_for_alignment(size_t alignment) {2629assert(is_size_aligned(alignment, (size_t) vm_page_size()),2630err_msg(SIZE_FORMAT " is not aligned to " SIZE_FORMAT,2631alignment, (size_t) vm_page_size()));26322633for (int i = 0; _page_sizes[i] != 0; i++) {2634if (is_size_aligned(alignment, _page_sizes[i])) {2635return _page_sizes[i];2636}2637}26382639return (size_t) vm_page_size();2640}26412642int os::Solaris::commit_memory_impl(char* addr, size_t bytes,2643size_t alignment_hint, bool exec) {2644int err = Solaris::commit_memory_impl(addr, bytes, exec);2645if (err == 0 && UseLargePages && alignment_hint > 0) {2646assert(is_size_aligned(bytes, alignment_hint),2647err_msg(SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, alignment_hint));26482649// The syscall memcntl requires an exact page size (see man memcntl for details).2650size_t page_size = page_size_for_alignment(alignment_hint);2651if (page_size > (size_t) vm_page_size()) {2652(void)Solaris::setup_large_pages(addr, bytes, page_size);2653}2654}2655return err;2656}26572658bool os::pd_commit_memory(char* addr, size_t bytes, size_t alignment_hint,2659bool exec) {2660return Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec) == 0;2661}26622663void os::pd_commit_memory_or_exit(char* addr, size_t bytes,2664size_t alignment_hint, bool exec,2665const char* mesg) {2666assert(mesg != NULL, "mesg must be specified");2667int err = os::Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec);2668if (err != 0) {2669// the caller wants all commit errors to exit with the specified mesg:2670warn_fail_commit_memory(addr, bytes, alignment_hint, exec, err);2671vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, mesg);2672}2673}26742675// Uncommit the pages in a specified region.2676void os::pd_free_memory(char* addr, size_t bytes, size_t alignment_hint) {2677if (madvise(addr, bytes, MADV_FREE) < 0) {2678debug_only(warning("MADV_FREE failed."));2679return;2680}2681}26822683bool os::pd_create_stack_guard_pages(char* addr, size_t size) {2684return os::commit_memory(addr, size, !ExecMem);2685}26862687bool os::remove_stack_guard_pages(char* addr, size_t size) {2688return os::uncommit_memory(addr, size);2689}26902691// Change the page size in a given range.2692void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {2693assert((intptr_t)addr % alignment_hint == 0, "Address should be aligned.");2694assert((intptr_t)(addr + bytes) % alignment_hint == 0, "End should be aligned.");2695if (UseLargePages) {2696Solaris::setup_large_pages(addr, bytes, alignment_hint);2697}2698}26992700// Tell the OS to make the range local to the first-touching LWP2701void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {2702assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned.");2703if (madvise(addr, bytes, MADV_ACCESS_LWP) < 0) {2704debug_only(warning("MADV_ACCESS_LWP failed."));2705}2706}27072708// Tell the OS that this range would be accessed from different LWPs.2709void os::numa_make_global(char *addr, size_t bytes) {2710assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned.");2711if (madvise(addr, bytes, MADV_ACCESS_MANY) < 0) {2712debug_only(warning("MADV_ACCESS_MANY failed."));2713}2714}27152716// Get the number of the locality groups.2717size_t os::numa_get_groups_num() {2718size_t n = Solaris::lgrp_nlgrps(Solaris::lgrp_cookie());2719return n != -1 ? n : 1;2720}27212722// Get a list of leaf locality groups. A leaf lgroup is group that2723// doesn't have any children. Typical leaf group is a CPU or a CPU/memory2724// board. An LWP is assigned to one of these groups upon creation.2725size_t os::numa_get_leaf_groups(int *ids, size_t size) {2726if ((ids[0] = Solaris::lgrp_root(Solaris::lgrp_cookie())) == -1) {2727ids[0] = 0;2728return 1;2729}2730int result_size = 0, top = 1, bottom = 0, cur = 0;2731for (int k = 0; k < size; k++) {2732int r = Solaris::lgrp_children(Solaris::lgrp_cookie(), ids[cur],2733(Solaris::lgrp_id_t*)&ids[top], size - top);2734if (r == -1) {2735ids[0] = 0;2736return 1;2737}2738if (!r) {2739// That's a leaf node.2740assert (bottom <= cur, "Sanity check");2741// Check if the node has memory2742if (Solaris::lgrp_resources(Solaris::lgrp_cookie(), ids[cur],2743NULL, 0, LGRP_RSRC_MEM) > 0) {2744ids[bottom++] = ids[cur];2745}2746}2747top += r;2748cur++;2749}2750if (bottom == 0) {2751// Handle a situation, when the OS reports no memory available.2752// Assume UMA architecture.2753ids[0] = 0;2754return 1;2755}2756return bottom;2757}27582759// Detect the topology change. Typically happens during CPU plugging-unplugging.2760bool os::numa_topology_changed() {2761int is_stale = Solaris::lgrp_cookie_stale(Solaris::lgrp_cookie());2762if (is_stale != -1 && is_stale) {2763Solaris::lgrp_fini(Solaris::lgrp_cookie());2764Solaris::lgrp_cookie_t c = Solaris::lgrp_init(Solaris::LGRP_VIEW_CALLER);2765assert(c != 0, "Failure to initialize LGRP API");2766Solaris::set_lgrp_cookie(c);2767return true;2768}2769return false;2770}27712772// Get the group id of the current LWP.2773int os::numa_get_group_id() {2774int lgrp_id = Solaris::lgrp_home(P_LWPID, P_MYID);2775if (lgrp_id == -1) {2776return 0;2777}2778const int size = os::numa_get_groups_num();2779int *ids = (int*)alloca(size * sizeof(int));27802781// Get the ids of all lgroups with memory; r is the count.2782int r = Solaris::lgrp_resources(Solaris::lgrp_cookie(), lgrp_id,2783(Solaris::lgrp_id_t*)ids, size, LGRP_RSRC_MEM);2784if (r <= 0) {2785return 0;2786}2787return ids[os::random() % r];2788}27892790// Request information about the page.2791bool os::get_page_info(char *start, page_info* info) {2792const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE };2793uint64_t addr = (uintptr_t)start;2794uint64_t outdata[2];2795uint_t validity = 0;27962797if (os::Solaris::meminfo(&addr, 1, info_types, 2, outdata, &validity) < 0) {2798return false;2799}28002801info->size = 0;2802info->lgrp_id = -1;28032804if ((validity & 1) != 0) {2805if ((validity & 2) != 0) {2806info->lgrp_id = outdata[0];2807}2808if ((validity & 4) != 0) {2809info->size = outdata[1];2810}2811return true;2812}2813return false;2814}28152816// Scan the pages from start to end until a page different than2817// the one described in the info parameter is encountered.2818char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) {2819const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE };2820const size_t types = sizeof(info_types) / sizeof(info_types[0]);2821uint64_t addrs[MAX_MEMINFO_CNT], outdata[types * MAX_MEMINFO_CNT + 1];2822uint_t validity[MAX_MEMINFO_CNT];28232824size_t page_size = MAX2((size_t)os::vm_page_size(), page_expected->size);2825uint64_t p = (uint64_t)start;2826while (p < (uint64_t)end) {2827addrs[0] = p;2828size_t addrs_count = 1;2829while (addrs_count < MAX_MEMINFO_CNT && addrs[addrs_count - 1] + page_size < (uint64_t)end) {2830addrs[addrs_count] = addrs[addrs_count - 1] + page_size;2831addrs_count++;2832}28332834if (os::Solaris::meminfo(addrs, addrs_count, info_types, types, outdata, validity) < 0) {2835return NULL;2836}28372838size_t i = 0;2839for (; i < addrs_count; i++) {2840if ((validity[i] & 1) != 0) {2841if ((validity[i] & 4) != 0) {2842if (outdata[types * i + 1] != page_expected->size) {2843break;2844}2845} else2846if (page_expected->size != 0) {2847break;2848}28492850if ((validity[i] & 2) != 0 && page_expected->lgrp_id > 0) {2851if (outdata[types * i] != page_expected->lgrp_id) {2852break;2853}2854}2855} else {2856return NULL;2857}2858}28592860if (i < addrs_count) {2861if ((validity[i] & 2) != 0) {2862page_found->lgrp_id = outdata[types * i];2863} else {2864page_found->lgrp_id = -1;2865}2866if ((validity[i] & 4) != 0) {2867page_found->size = outdata[types * i + 1];2868} else {2869page_found->size = 0;2870}2871return (char*)addrs[i];2872}28732874p = addrs[addrs_count - 1] + page_size;2875}2876return end;2877}28782879bool os::pd_uncommit_memory(char* addr, size_t bytes) {2880size_t size = bytes;2881// Map uncommitted pages PROT_NONE so we fail early if we touch an2882// uncommitted page. Otherwise, the read/write might succeed if we2883// have enough swap space to back the physical page.2884return2885NULL != Solaris::mmap_chunk(addr, size,2886MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE,2887PROT_NONE);2888}28892890char* os::Solaris::mmap_chunk(char *addr, size_t size, int flags, int prot) {2891char *b = (char *)mmap(addr, size, prot, flags, os::Solaris::_dev_zero_fd, 0);28922893if (b == MAP_FAILED) {2894return NULL;2895}2896return b;2897}28982899char* os::Solaris::anon_mmap(char* requested_addr, size_t bytes, size_t alignment_hint, bool fixed) {2900char* addr = requested_addr;2901int flags = MAP_PRIVATE | MAP_NORESERVE;29022903assert(!(fixed && (alignment_hint > 0)), "alignment hint meaningless with fixed mmap");29042905if (fixed) {2906flags |= MAP_FIXED;2907} else if (has_map_align && (alignment_hint > (size_t) vm_page_size())) {2908flags |= MAP_ALIGN;2909addr = (char*) alignment_hint;2910}29112912// Map uncommitted pages PROT_NONE so we fail early if we touch an2913// uncommitted page. Otherwise, the read/write might succeed if we2914// have enough swap space to back the physical page.2915return mmap_chunk(addr, bytes, flags, PROT_NONE);2916}29172918char* os::pd_reserve_memory(size_t bytes, char* requested_addr, size_t alignment_hint) {2919char* addr = Solaris::anon_mmap(requested_addr, bytes, alignment_hint, (requested_addr != NULL));29202921guarantee(requested_addr == NULL || requested_addr == addr,2922"OS failed to return requested mmap address.");2923return addr;2924}29252926// Reserve memory at an arbitrary address, only if that area is2927// available (and not reserved for something else).29282929char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) {2930const int max_tries = 10;2931char* base[max_tries];2932size_t size[max_tries];29332934// Solaris adds a gap between mmap'ed regions. The size of the gap2935// is dependent on the requested size and the MMU. Our initial gap2936// value here is just a guess and will be corrected later.2937bool had_top_overlap = false;2938bool have_adjusted_gap = false;2939size_t gap = 0x400000;29402941// Assert only that the size is a multiple of the page size, since2942// that's all that mmap requires, and since that's all we really know2943// about at this low abstraction level. If we need higher alignment,2944// we can either pass an alignment to this method or verify alignment2945// in one of the methods further up the call chain. See bug 5044738.2946assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");29472948// Since snv_84, Solaris attempts to honor the address hint - see 5003415.2949// Give it a try, if the kernel honors the hint we can return immediately.2950char* addr = Solaris::anon_mmap(requested_addr, bytes, 0, false);29512952volatile int err = errno;2953if (addr == requested_addr) {2954return addr;2955} else if (addr != NULL) {2956pd_unmap_memory(addr, bytes);2957}29582959if (PrintMiscellaneous && Verbose) {2960char buf[256];2961buf[0] = '\0';2962if (addr == NULL) {2963jio_snprintf(buf, sizeof(buf), ": %s", strerror(err));2964}2965warning("attempt_reserve_memory_at: couldn't reserve " SIZE_FORMAT " bytes at "2966PTR_FORMAT ": reserve_memory_helper returned " PTR_FORMAT2967"%s", bytes, requested_addr, addr, buf);2968}29692970// Address hint method didn't work. Fall back to the old method.2971// In theory, once SNV becomes our oldest supported platform, this2972// code will no longer be needed.2973//2974// Repeatedly allocate blocks until the block is allocated at the2975// right spot. Give up after max_tries.2976int i;2977for (i = 0; i < max_tries; ++i) {2978base[i] = reserve_memory(bytes);29792980if (base[i] != NULL) {2981// Is this the block we wanted?2982if (base[i] == requested_addr) {2983size[i] = bytes;2984break;2985}29862987// check that the gap value is right2988if (had_top_overlap && !have_adjusted_gap) {2989size_t actual_gap = base[i-1] - base[i] - bytes;2990if (gap != actual_gap) {2991// adjust the gap value and retry the last 2 allocations2992assert(i > 0, "gap adjustment code problem");2993have_adjusted_gap = true; // adjust the gap only once, just in case2994gap = actual_gap;2995if (PrintMiscellaneous && Verbose) {2996warning("attempt_reserve_memory_at: adjusted gap to 0x%lx", gap);2997}2998unmap_memory(base[i], bytes);2999unmap_memory(base[i-1], size[i-1]);3000i-=2;3001continue;3002}3003}30043005// Does this overlap the block we wanted? Give back the overlapped3006// parts and try again.3007//3008// There is still a bug in this code: if top_overlap == bytes,3009// the overlap is offset from requested region by the value of gap.3010// In this case giving back the overlapped part will not work,3011// because we'll give back the entire block at base[i] and3012// therefore the subsequent allocation will not generate a new gap.3013// This could be fixed with a new algorithm that used larger3014// or variable size chunks to find the requested region -3015// but such a change would introduce additional complications.3016// It's rare enough that the planets align for this bug,3017// so we'll just wait for a fix for 6204603/5003415 which3018// will provide a mmap flag to allow us to avoid this business.30193020size_t top_overlap = requested_addr + (bytes + gap) - base[i];3021if (top_overlap >= 0 && top_overlap < bytes) {3022had_top_overlap = true;3023unmap_memory(base[i], top_overlap);3024base[i] += top_overlap;3025size[i] = bytes - top_overlap;3026} else {3027size_t bottom_overlap = base[i] + bytes - requested_addr;3028if (bottom_overlap >= 0 && bottom_overlap < bytes) {3029if (PrintMiscellaneous && Verbose && bottom_overlap == 0) {3030warning("attempt_reserve_memory_at: possible alignment bug");3031}3032unmap_memory(requested_addr, bottom_overlap);3033size[i] = bytes - bottom_overlap;3034} else {3035size[i] = bytes;3036}3037}3038}3039}30403041// Give back the unused reserved pieces.30423043for (int j = 0; j < i; ++j) {3044if (base[j] != NULL) {3045unmap_memory(base[j], size[j]);3046}3047}30483049return (i < max_tries) ? requested_addr : NULL;3050}30513052bool os::pd_release_memory(char* addr, size_t bytes) {3053size_t size = bytes;3054return munmap(addr, size) == 0;3055}30563057static bool solaris_mprotect(char* addr, size_t bytes, int prot) {3058assert(addr == (char*)align_size_down((uintptr_t)addr, os::vm_page_size()),3059"addr must be page aligned");3060int retVal = mprotect(addr, bytes, prot);3061return retVal == 0;3062}30633064// Protect memory (Used to pass readonly pages through3065// JNI GetArray<type>Elements with empty arrays.)3066// Also, used for serialization page and for compressed oops null pointer3067// checking.3068bool os::protect_memory(char* addr, size_t bytes, ProtType prot,3069bool is_committed) {3070unsigned int p = 0;3071switch (prot) {3072case MEM_PROT_NONE: p = PROT_NONE; break;3073case MEM_PROT_READ: p = PROT_READ; break;3074case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break;3075case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break;3076default:3077ShouldNotReachHere();3078}3079// is_committed is unused.3080return solaris_mprotect(addr, bytes, p);3081}30823083// guard_memory and unguard_memory only happens within stack guard pages.3084// Since ISM pertains only to the heap, guard and unguard memory should not3085/// happen with an ISM region.3086bool os::guard_memory(char* addr, size_t bytes) {3087return solaris_mprotect(addr, bytes, PROT_NONE);3088}30893090bool os::unguard_memory(char* addr, size_t bytes) {3091return solaris_mprotect(addr, bytes, PROT_READ|PROT_WRITE);3092}30933094// Large page support3095static size_t _large_page_size = 0;30963097// Insertion sort for small arrays (descending order).3098static void insertion_sort_descending(size_t* array, int len) {3099for (int i = 0; i < len; i++) {3100size_t val = array[i];3101for (size_t key = i; key > 0 && array[key - 1] < val; --key) {3102size_t tmp = array[key];3103array[key] = array[key - 1];3104array[key - 1] = tmp;3105}3106}3107}31083109bool os::Solaris::mpss_sanity_check(bool warn, size_t* page_size) {3110const unsigned int usable_count = VM_Version::page_size_count();3111if (usable_count == 1) {3112return false;3113}31143115// Find the right getpagesizes interface. When solaris 11 is the minimum3116// build platform, getpagesizes() (without the '2') can be called directly.3117typedef int (*gps_t)(size_t[], int);3118gps_t gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes2"));3119if (gps_func == NULL) {3120gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes"));3121if (gps_func == NULL) {3122if (warn) {3123warning("MPSS is not supported by the operating system.");3124}3125return false;3126}3127}31283129// Fill the array of page sizes.3130int n = (*gps_func)(_page_sizes, page_sizes_max);3131assert(n > 0, "Solaris bug?");31323133if (n == page_sizes_max) {3134// Add a sentinel value (necessary only if the array was completely filled3135// since it is static (zeroed at initialization)).3136_page_sizes[--n] = 0;3137DEBUG_ONLY(warning("increase the size of the os::_page_sizes array.");)3138}3139assert(_page_sizes[n] == 0, "missing sentinel");3140trace_page_sizes("available page sizes", _page_sizes, n);31413142if (n == 1) return false; // Only one page size available.31433144// Skip sizes larger than 4M (or LargePageSizeInBytes if it was set) and3145// select up to usable_count elements. First sort the array, find the first3146// acceptable value, then copy the usable sizes to the top of the array and3147// trim the rest. Make sure to include the default page size :-).3148//3149// A better policy could get rid of the 4M limit by taking the sizes of the3150// important VM memory regions (java heap and possibly the code cache) into3151// account.3152insertion_sort_descending(_page_sizes, n);3153const size_t size_limit =3154FLAG_IS_DEFAULT(LargePageSizeInBytes) ? 4 * M : LargePageSizeInBytes;3155int beg;3156for (beg = 0; beg < n && _page_sizes[beg] > size_limit; ++beg) /* empty */ ;3157const int end = MIN2((int)usable_count, n) - 1;3158for (int cur = 0; cur < end; ++cur, ++beg) {3159_page_sizes[cur] = _page_sizes[beg];3160}3161_page_sizes[end] = vm_page_size();3162_page_sizes[end + 1] = 0;31633164if (_page_sizes[end] > _page_sizes[end - 1]) {3165// Default page size is not the smallest; sort again.3166insertion_sort_descending(_page_sizes, end + 1);3167}3168*page_size = _page_sizes[0];31693170trace_page_sizes("usable page sizes", _page_sizes, end + 1);3171return true;3172}31733174void os::large_page_init() {3175if (UseLargePages) {3176// print a warning if any large page related flag is specified on command line3177bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages) ||3178!FLAG_IS_DEFAULT(LargePageSizeInBytes);31793180UseLargePages = Solaris::mpss_sanity_check(warn_on_failure, &_large_page_size);3181}3182}31833184bool os::Solaris::is_valid_page_size(size_t bytes) {3185for (int i = 0; _page_sizes[i] != 0; i++) {3186if (_page_sizes[i] == bytes) {3187return true;3188}3189}3190return false;3191}31923193bool os::Solaris::setup_large_pages(caddr_t start, size_t bytes, size_t align) {3194assert(is_valid_page_size(align), err_msg(SIZE_FORMAT " is not a valid page size", align));3195assert(is_ptr_aligned((void*) start, align),3196err_msg(PTR_FORMAT " is not aligned to " SIZE_FORMAT, p2i((void*) start), align));3197assert(is_size_aligned(bytes, align),3198err_msg(SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, align));31993200// Signal to OS that we want large pages for addresses3201// from addr, addr + bytes3202struct memcntl_mha mpss_struct;3203mpss_struct.mha_cmd = MHA_MAPSIZE_VA;3204mpss_struct.mha_pagesize = align;3205mpss_struct.mha_flags = 0;3206// Upon successful completion, memcntl() returns 03207if (memcntl(start, bytes, MC_HAT_ADVISE, (caddr_t) &mpss_struct, 0, 0)) {3208debug_only(warning("Attempt to use MPSS failed."));3209return false;3210}3211return true;3212}32133214char* os::reserve_memory_special(size_t size, size_t alignment, char* addr, bool exec) {3215fatal("os::reserve_memory_special should not be called on Solaris.");3216return NULL;3217}32183219bool os::release_memory_special(char* base, size_t bytes) {3220fatal("os::release_memory_special should not be called on Solaris.");3221return false;3222}32233224size_t os::large_page_size() {3225return _large_page_size;3226}32273228// MPSS allows application to commit large page memory on demand; with ISM3229// the entire memory region must be allocated as shared memory.3230bool os::can_commit_large_page_memory() {3231return true;3232}32333234bool os::can_execute_large_page_memory() {3235return true;3236}32373238static int os_sleep(jlong millis, bool interruptible) {3239const jlong limit = INT_MAX;3240jlong prevtime;3241int res;32423243while (millis > limit) {3244if ((res = os_sleep(limit, interruptible)) != OS_OK)3245return res;3246millis -= limit;3247}32483249// Restart interrupted polls with new parameters until the proper delay3250// has been completed.32513252prevtime = getTimeMillis();32533254while (millis > 0) {3255jlong newtime;32563257if (!interruptible) {3258// Following assert fails for os::yield_all:3259// assert(!thread->is_Java_thread(), "must not be java thread");3260res = poll(NULL, 0, millis);3261} else {3262JavaThread *jt = JavaThread::current();32633264INTERRUPTIBLE_NORESTART_VM_ALWAYS(poll(NULL, 0, millis), res, jt,3265os::Solaris::clear_interrupted);3266}32673268// INTERRUPTIBLE_NORESTART_VM_ALWAYS returns res == OS_INTRPT for3269// thread.Interrupt.32703271// See c/r 6751923. Poll can return 0 before time3272// has elapsed if time is set via clock_settime (as NTP does).3273// res == 0 if poll timed out (see man poll RETURN VALUES)3274// using the logic below checks that we really did3275// sleep at least "millis" if not we'll sleep again.3276if( ( res == 0 ) || ((res == OS_ERR) && (errno == EINTR))) {3277newtime = getTimeMillis();3278assert(newtime >= prevtime, "time moving backwards");3279/* Doing prevtime and newtime in microseconds doesn't help precision,3280and trying to round up to avoid lost milliseconds can result in a3281too-short delay. */3282millis -= newtime - prevtime;3283if(millis <= 0)3284return OS_OK;3285prevtime = newtime;3286} else3287return res;3288}32893290return OS_OK;3291}32923293// Read calls from inside the vm need to perform state transitions3294size_t os::read(int fd, void *buf, unsigned int nBytes) {3295INTERRUPTIBLE_RETURN_INT_VM(::read(fd, buf, nBytes), os::Solaris::clear_interrupted);3296}32973298size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) {3299size_t res;3300JavaThread* thread = (JavaThread*)Thread::current();3301assert(thread->thread_state() == _thread_in_vm, "Assumed _thread_in_vm");3302ThreadBlockInVM tbiv(thread);3303RESTARTABLE(::pread(fd, buf, (size_t) nBytes, offset), res);3304return res;3305}33063307size_t os::restartable_read(int fd, void *buf, unsigned int nBytes) {3308INTERRUPTIBLE_RETURN_INT(::read(fd, buf, nBytes), os::Solaris::clear_interrupted);3309}33103311int os::sleep(Thread* thread, jlong millis, bool interruptible) {3312assert(thread == Thread::current(), "thread consistency check");33133314// TODO-FIXME: this should be removed.3315// On Solaris machines (especially 2.5.1) we found that sometimes the VM gets into a live lock3316// situation with a JavaThread being starved out of a lwp. The kernel doesn't seem to generate3317// a SIGWAITING signal which would enable the threads library to create a new lwp for the starving3318// thread. We suspect that because the Watcher thread keeps waking up at periodic intervals the kernel3319// is fooled into believing that the system is making progress. In the code below we block the3320// the watcher thread while safepoint is in progress so that it would not appear as though the3321// system is making progress.3322if (!Solaris::T2_libthread() &&3323thread->is_Watcher_thread() && SafepointSynchronize::is_synchronizing() && !Arguments::has_profile()) {3324// We now try to acquire the threads lock. Since this lock is held by the VM thread during3325// the entire safepoint, the watcher thread will line up here during the safepoint.3326Threads_lock->lock_without_safepoint_check();3327Threads_lock->unlock();3328}33293330if (thread->is_Java_thread()) {3331// This is a JavaThread so we honor the _thread_blocked protocol3332// even for sleeps of 0 milliseconds. This was originally done3333// as a workaround for bug 4338139. However, now we also do it3334// to honor the suspend-equivalent protocol.33353336JavaThread *jt = (JavaThread *) thread;3337ThreadBlockInVM tbivm(jt);33383339jt->set_suspend_equivalent();3340// cleared by handle_special_suspend_equivalent_condition() or3341// java_suspend_self() via check_and_wait_while_suspended()33423343int ret_code;3344if (millis <= 0) {3345thr_yield();3346ret_code = 0;3347} else {3348// The original sleep() implementation did not create an3349// OSThreadWaitState helper for sleeps of 0 milliseconds.3350// I'm preserving that decision for now.3351OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);33523353ret_code = os_sleep(millis, interruptible);3354}33553356// were we externally suspended while we were waiting?3357jt->check_and_wait_while_suspended();33583359return ret_code;3360}33613362// non-JavaThread from this point on:33633364if (millis <= 0) {3365thr_yield();3366return 0;3367}33683369OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);33703371return os_sleep(millis, interruptible);3372}33733374void os::naked_short_sleep(jlong ms) {3375assert(ms < 1000, "Un-interruptable sleep, short time use only");33763377// usleep is deprecated and removed from POSIX, in favour of nanosleep, but3378// Solaris requires -lrt for this.3379usleep((ms * 1000));33803381return;3382}33833384// Sleep forever; naked call to OS-specific sleep; use with CAUTION3385void os::infinite_sleep() {3386while (true) { // sleep forever ...3387::sleep(100); // ... 100 seconds at a time3388}3389}33903391// Used to convert frequent JVM_Yield() to nops3392bool os::dont_yield() {3393if (DontYieldALot) {3394static hrtime_t last_time = 0;3395hrtime_t diff = getTimeNanos() - last_time;33963397if (diff < DontYieldALotInterval * 1000000)3398return true;33993400last_time += diff;34013402return false;3403}3404else {3405return false;3406}3407}34083409// Caveat: Solaris os::yield() causes a thread-state transition whereas3410// the linux and win32 implementations do not. This should be checked.34113412void os::yield() {3413// Yields to all threads with same or greater priority3414os::sleep(Thread::current(), 0, false);3415}34163417// Note that yield semantics are defined by the scheduling class to which3418// the thread currently belongs. Typically, yield will _not yield to3419// other equal or higher priority threads that reside on the dispatch queues3420// of other CPUs.34213422os::YieldResult os::NakedYield() { thr_yield(); return os::YIELD_UNKNOWN; }342334243425// On Solaris we found that yield_all doesn't always yield to all other threads.3426// There have been cases where there is a thread ready to execute but it doesn't3427// get an lwp as the VM thread continues to spin with sleeps of 1 millisecond.3428// The 1 millisecond wait doesn't seem long enough for the kernel to issue a3429// SIGWAITING signal which will cause a new lwp to be created. So we count the3430// number of times yield_all is called in the one loop and increase the sleep3431// time after 8 attempts. If this fails too we increase the concurrency level3432// so that the starving thread would get an lwp34333434void os::yield_all(int attempts) {3435// Yields to all threads, including threads with lower priorities3436if (attempts == 0) {3437os::sleep(Thread::current(), 1, false);3438} else {3439int iterations = attempts % 30;3440if (iterations == 0 && !os::Solaris::T2_libthread()) {3441// thr_setconcurrency and _getconcurrency make sense only under T1.3442int noofLWPS = thr_getconcurrency();3443if (noofLWPS < (Threads::number_of_threads() + 2)) {3444thr_setconcurrency(thr_getconcurrency() + 1);3445}3446} else if (iterations < 25) {3447os::sleep(Thread::current(), 1, false);3448} else {3449os::sleep(Thread::current(), 10, false);3450}3451}3452}34533454// Called from the tight loops to possibly influence time-sharing heuristics3455void os::loop_breaker(int attempts) {3456os::yield_all(attempts);3457}345834593460// Interface for setting lwp priorities. If we are using T2 libthread,3461// which forces the use of BoundThreads or we manually set UseBoundThreads,3462// all of our threads will be assigned to real lwp's. Using the thr_setprio3463// function is meaningless in this mode so we must adjust the real lwp's priority3464// The routines below implement the getting and setting of lwp priorities.3465//3466// Note: There are three priority scales used on Solaris. Java priotities3467// which range from 1 to 10, libthread "thr_setprio" scale which range3468// from 0 to 127, and the current scheduling class of the process we3469// are running in. This is typically from -60 to +60.3470// The setting of the lwp priorities in done after a call to thr_setprio3471// so Java priorities are mapped to libthread priorities and we map from3472// the latter to lwp priorities. We don't keep priorities stored in3473// Java priorities since some of our worker threads want to set priorities3474// higher than all Java threads.3475//3476// For related information:3477// (1) man -s 2 priocntl3478// (2) man -s 4 priocntl3479// (3) man dispadmin3480// = librt.so3481// = libthread/common/rtsched.c - thrp_setlwpprio().3482// = ps -cL <pid> ... to validate priority.3483// = sched_get_priority_min and _max3484// pthread_create3485// sched_setparam3486// pthread_setschedparam3487//3488// Assumptions:3489// + We assume that all threads in the process belong to the same3490// scheduling class. IE. an homogenous process.3491// + Must be root or in IA group to change change "interactive" attribute.3492// Priocntl() will fail silently. The only indication of failure is when3493// we read-back the value and notice that it hasn't changed.3494// + Interactive threads enter the runq at the head, non-interactive at the tail.3495// + For RT, change timeslice as well. Invariant:3496// constant "priority integral"3497// Konst == TimeSlice * (60-Priority)3498// Given a priority, compute appropriate timeslice.3499// + Higher numerical values have higher priority.35003501// sched class attributes3502typedef struct {3503int schedPolicy; // classID3504int maxPrio;3505int minPrio;3506} SchedInfo;350735083509static SchedInfo tsLimits, iaLimits, rtLimits, fxLimits;35103511#ifdef ASSERT3512static int ReadBackValidate = 1;3513#endif3514static int myClass = 0;3515static int myMin = 0;3516static int myMax = 0;3517static int myCur = 0;3518static bool priocntl_enable = false;35193520static const int criticalPrio = 60; // FX/60 is critical thread class/priority on T43521static int java_MaxPriority_to_os_priority = 0; // Saved mapping352235233524// lwp_priocntl_init3525//3526// Try to determine the priority scale for our process.3527//3528// Return errno or 0 if OK.3529//3530static int lwp_priocntl_init () {3531int rslt;3532pcinfo_t ClassInfo;3533pcparms_t ParmInfo;3534int i;35353536if (!UseThreadPriorities) return 0;35373538// We are using Bound threads, we need to determine our priority ranges3539if (os::Solaris::T2_libthread() || UseBoundThreads) {3540// If ThreadPriorityPolicy is 1, switch tables3541if (ThreadPriorityPolicy == 1) {3542for (i = 0 ; i < CriticalPriority+1; i++)3543os::java_to_os_priority[i] = prio_policy1[i];3544}3545if (UseCriticalJavaThreadPriority) {3546// MaxPriority always maps to the FX scheduling class and criticalPrio.3547// See set_native_priority() and set_lwp_class_and_priority().3548// Save original MaxPriority mapping in case attempt to3549// use critical priority fails.3550java_MaxPriority_to_os_priority = os::java_to_os_priority[MaxPriority];3551// Set negative to distinguish from other priorities3552os::java_to_os_priority[MaxPriority] = -criticalPrio;3553}3554}3555// Not using Bound Threads, set to ThreadPolicy 13556else {3557for ( i = 0 ; i < CriticalPriority+1; i++ ) {3558os::java_to_os_priority[i] = prio_policy1[i];3559}3560return 0;3561}35623563// Get IDs for a set of well-known scheduling classes.3564// TODO-FIXME: GETCLINFO returns the current # of classes in the3565// the system. We should have a loop that iterates over the3566// classID values, which are known to be "small" integers.35673568strcpy(ClassInfo.pc_clname, "TS");3569ClassInfo.pc_cid = -1;3570rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);3571if (rslt < 0) return errno;3572assert(ClassInfo.pc_cid != -1, "cid for TS class is -1");3573tsLimits.schedPolicy = ClassInfo.pc_cid;3574tsLimits.maxPrio = ((tsinfo_t*)ClassInfo.pc_clinfo)->ts_maxupri;3575tsLimits.minPrio = -tsLimits.maxPrio;35763577strcpy(ClassInfo.pc_clname, "IA");3578ClassInfo.pc_cid = -1;3579rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);3580if (rslt < 0) return errno;3581assert(ClassInfo.pc_cid != -1, "cid for IA class is -1");3582iaLimits.schedPolicy = ClassInfo.pc_cid;3583iaLimits.maxPrio = ((iainfo_t*)ClassInfo.pc_clinfo)->ia_maxupri;3584iaLimits.minPrio = -iaLimits.maxPrio;35853586strcpy(ClassInfo.pc_clname, "RT");3587ClassInfo.pc_cid = -1;3588rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);3589if (rslt < 0) return errno;3590assert(ClassInfo.pc_cid != -1, "cid for RT class is -1");3591rtLimits.schedPolicy = ClassInfo.pc_cid;3592rtLimits.maxPrio = ((rtinfo_t*)ClassInfo.pc_clinfo)->rt_maxpri;3593rtLimits.minPrio = 0;35943595strcpy(ClassInfo.pc_clname, "FX");3596ClassInfo.pc_cid = -1;3597rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);3598if (rslt < 0) return errno;3599assert(ClassInfo.pc_cid != -1, "cid for FX class is -1");3600fxLimits.schedPolicy = ClassInfo.pc_cid;3601fxLimits.maxPrio = ((fxinfo_t*)ClassInfo.pc_clinfo)->fx_maxupri;3602fxLimits.minPrio = 0;36033604// Query our "current" scheduling class.3605// This will normally be IA, TS or, rarely, FX or RT.3606memset(&ParmInfo, 0, sizeof(ParmInfo));3607ParmInfo.pc_cid = PC_CLNULL;3608rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);3609if (rslt < 0) return errno;3610myClass = ParmInfo.pc_cid;36113612// We now know our scheduling classId, get specific information3613// about the class.3614ClassInfo.pc_cid = myClass;3615ClassInfo.pc_clname[0] = 0;3616rslt = priocntl((idtype)0, 0, PC_GETCLINFO, (caddr_t)&ClassInfo);3617if (rslt < 0) return errno;36183619if (ThreadPriorityVerbose) {3620tty->print_cr("lwp_priocntl_init: Class=%d(%s)...", myClass, ClassInfo.pc_clname);3621}36223623memset(&ParmInfo, 0, sizeof(pcparms_t));3624ParmInfo.pc_cid = PC_CLNULL;3625rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);3626if (rslt < 0) return errno;36273628if (ParmInfo.pc_cid == rtLimits.schedPolicy) {3629myMin = rtLimits.minPrio;3630myMax = rtLimits.maxPrio;3631} else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {3632iaparms_t *iaInfo = (iaparms_t*)ParmInfo.pc_clparms;3633myMin = iaLimits.minPrio;3634myMax = iaLimits.maxPrio;3635myMax = MIN2(myMax, (int)iaInfo->ia_uprilim); // clamp - restrict3636} else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {3637tsparms_t *tsInfo = (tsparms_t*)ParmInfo.pc_clparms;3638myMin = tsLimits.minPrio;3639myMax = tsLimits.maxPrio;3640myMax = MIN2(myMax, (int)tsInfo->ts_uprilim); // clamp - restrict3641} else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {3642fxparms_t *fxInfo = (fxparms_t*)ParmInfo.pc_clparms;3643myMin = fxLimits.minPrio;3644myMax = fxLimits.maxPrio;3645myMax = MIN2(myMax, (int)fxInfo->fx_uprilim); // clamp - restrict3646} else {3647// No clue - punt3648if (ThreadPriorityVerbose)3649tty->print_cr ("Unknown scheduling class: %s ... \n", ClassInfo.pc_clname);3650return EINVAL; // no clue, punt3651}36523653if (ThreadPriorityVerbose) {3654tty->print_cr ("Thread priority Range: [%d..%d]\n", myMin, myMax);3655}36563657priocntl_enable = true; // Enable changing priorities3658return 0;3659}36603661#define IAPRI(x) ((iaparms_t *)((x).pc_clparms))3662#define RTPRI(x) ((rtparms_t *)((x).pc_clparms))3663#define TSPRI(x) ((tsparms_t *)((x).pc_clparms))3664#define FXPRI(x) ((fxparms_t *)((x).pc_clparms))366536663667// scale_to_lwp_priority3668//3669// Convert from the libthread "thr_setprio" scale to our current3670// lwp scheduling class scale.3671//3672static3673int scale_to_lwp_priority (int rMin, int rMax, int x)3674{3675int v;36763677if (x == 127) return rMax; // avoid round-down3678v = (((x*(rMax-rMin)))/128)+rMin;3679return v;3680}368136823683// set_lwp_class_and_priority3684//3685// Set the class and priority of the lwp. This call should only3686// be made when using bound threads (T2 threads are bound by default).3687//3688int set_lwp_class_and_priority(int ThreadID, int lwpid,3689int newPrio, int new_class, bool scale) {3690int rslt;3691int Actual, Expected, prv;3692pcparms_t ParmInfo; // for GET-SET3693#ifdef ASSERT3694pcparms_t ReadBack; // for readback3695#endif36963697// Set priority via PC_GETPARMS, update, PC_SETPARMS3698// Query current values.3699// TODO: accelerate this by eliminating the PC_GETPARMS call.3700// Cache "pcparms_t" in global ParmCache.3701// TODO: elide set-to-same-value37023703// If something went wrong on init, don't change priorities.3704if ( !priocntl_enable ) {3705if (ThreadPriorityVerbose)3706tty->print_cr("Trying to set priority but init failed, ignoring");3707return EINVAL;3708}37093710// If lwp hasn't started yet, just return3711// the _start routine will call us again.3712if ( lwpid <= 0 ) {3713if (ThreadPriorityVerbose) {3714tty->print_cr ("deferring the set_lwp_class_and_priority of thread "3715INTPTR_FORMAT " to %d, lwpid not set",3716ThreadID, newPrio);3717}3718return 0;3719}37203721if (ThreadPriorityVerbose) {3722tty->print_cr ("set_lwp_class_and_priority("3723INTPTR_FORMAT "@" INTPTR_FORMAT " %d) ",3724ThreadID, lwpid, newPrio);3725}37263727memset(&ParmInfo, 0, sizeof(pcparms_t));3728ParmInfo.pc_cid = PC_CLNULL;3729rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ParmInfo);3730if (rslt < 0) return errno;37313732int cur_class = ParmInfo.pc_cid;3733ParmInfo.pc_cid = (id_t)new_class;37343735if (new_class == rtLimits.schedPolicy) {3736rtparms_t *rtInfo = (rtparms_t*)ParmInfo.pc_clparms;3737rtInfo->rt_pri = scale ? scale_to_lwp_priority(rtLimits.minPrio,3738rtLimits.maxPrio, newPrio)3739: newPrio;3740rtInfo->rt_tqsecs = RT_NOCHANGE;3741rtInfo->rt_tqnsecs = RT_NOCHANGE;3742if (ThreadPriorityVerbose) {3743tty->print_cr("RT: %d->%d\n", newPrio, rtInfo->rt_pri);3744}3745} else if (new_class == iaLimits.schedPolicy) {3746iaparms_t* iaInfo = (iaparms_t*)ParmInfo.pc_clparms;3747int maxClamped = MIN2(iaLimits.maxPrio,3748cur_class == new_class3749? (int)iaInfo->ia_uprilim : iaLimits.maxPrio);3750iaInfo->ia_upri = scale ? scale_to_lwp_priority(iaLimits.minPrio,3751maxClamped, newPrio)3752: newPrio;3753iaInfo->ia_uprilim = cur_class == new_class3754? IA_NOCHANGE : (pri_t)iaLimits.maxPrio;3755iaInfo->ia_mode = IA_NOCHANGE;3756if (ThreadPriorityVerbose) {3757tty->print_cr("IA: [%d...%d] %d->%d\n",3758iaLimits.minPrio, maxClamped, newPrio, iaInfo->ia_upri);3759}3760} else if (new_class == tsLimits.schedPolicy) {3761tsparms_t* tsInfo = (tsparms_t*)ParmInfo.pc_clparms;3762int maxClamped = MIN2(tsLimits.maxPrio,3763cur_class == new_class3764? (int)tsInfo->ts_uprilim : tsLimits.maxPrio);3765tsInfo->ts_upri = scale ? scale_to_lwp_priority(tsLimits.minPrio,3766maxClamped, newPrio)3767: newPrio;3768tsInfo->ts_uprilim = cur_class == new_class3769? TS_NOCHANGE : (pri_t)tsLimits.maxPrio;3770if (ThreadPriorityVerbose) {3771tty->print_cr("TS: [%d...%d] %d->%d\n",3772tsLimits.minPrio, maxClamped, newPrio, tsInfo->ts_upri);3773}3774} else if (new_class == fxLimits.schedPolicy) {3775fxparms_t* fxInfo = (fxparms_t*)ParmInfo.pc_clparms;3776int maxClamped = MIN2(fxLimits.maxPrio,3777cur_class == new_class3778? (int)fxInfo->fx_uprilim : fxLimits.maxPrio);3779fxInfo->fx_upri = scale ? scale_to_lwp_priority(fxLimits.minPrio,3780maxClamped, newPrio)3781: newPrio;3782fxInfo->fx_uprilim = cur_class == new_class3783? FX_NOCHANGE : (pri_t)fxLimits.maxPrio;3784fxInfo->fx_tqsecs = FX_NOCHANGE;3785fxInfo->fx_tqnsecs = FX_NOCHANGE;3786if (ThreadPriorityVerbose) {3787tty->print_cr("FX: [%d...%d] %d->%d\n",3788fxLimits.minPrio, maxClamped, newPrio, fxInfo->fx_upri);3789}3790} else {3791if (ThreadPriorityVerbose) {3792tty->print_cr("Unknown new scheduling class %d\n", new_class);3793}3794return EINVAL; // no clue, punt3795}37963797rslt = priocntl(P_LWPID, lwpid, PC_SETPARMS, (caddr_t)&ParmInfo);3798if (ThreadPriorityVerbose && rslt) {3799tty->print_cr ("PC_SETPARMS ->%d %d\n", rslt, errno);3800}3801if (rslt < 0) return errno;38023803#ifdef ASSERT3804// Sanity check: read back what we just attempted to set.3805// In theory it could have changed in the interim ...3806//3807// The priocntl system call is tricky.3808// Sometimes it'll validate the priority value argument and3809// return EINVAL if unhappy. At other times it fails silently.3810// Readbacks are prudent.38113812if (!ReadBackValidate) return 0;38133814memset(&ReadBack, 0, sizeof(pcparms_t));3815ReadBack.pc_cid = PC_CLNULL;3816rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ReadBack);3817assert(rslt >= 0, "priocntl failed");3818Actual = Expected = 0xBAD;3819assert(ParmInfo.pc_cid == ReadBack.pc_cid, "cid's don't match");3820if (ParmInfo.pc_cid == rtLimits.schedPolicy) {3821Actual = RTPRI(ReadBack)->rt_pri;3822Expected = RTPRI(ParmInfo)->rt_pri;3823} else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {3824Actual = IAPRI(ReadBack)->ia_upri;3825Expected = IAPRI(ParmInfo)->ia_upri;3826} else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {3827Actual = TSPRI(ReadBack)->ts_upri;3828Expected = TSPRI(ParmInfo)->ts_upri;3829} else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {3830Actual = FXPRI(ReadBack)->fx_upri;3831Expected = FXPRI(ParmInfo)->fx_upri;3832} else {3833if (ThreadPriorityVerbose) {3834tty->print_cr("set_lwp_class_and_priority: unexpected class in readback: %d\n",3835ParmInfo.pc_cid);3836}3837}38383839if (Actual != Expected) {3840if (ThreadPriorityVerbose) {3841tty->print_cr ("set_lwp_class_and_priority(%d %d) Class=%d: actual=%d vs expected=%d\n",3842lwpid, newPrio, ReadBack.pc_cid, Actual, Expected);3843}3844}3845#endif38463847return 0;3848}38493850// Solaris only gives access to 128 real priorities at a time,3851// so we expand Java's ten to fill this range. This would be better3852// if we dynamically adjusted relative priorities.3853//3854// The ThreadPriorityPolicy option allows us to select 2 different3855// priority scales.3856//3857// ThreadPriorityPolicy=03858// Since the Solaris' default priority is MaximumPriority, we do not3859// set a priority lower than Max unless a priority lower than3860// NormPriority is requested.3861//3862// ThreadPriorityPolicy=13863// This mode causes the priority table to get filled with3864// linear values. NormPriority get's mapped to 50% of the3865// Maximum priority an so on. This will cause VM threads3866// to get unfair treatment against other Solaris processes3867// which do not explicitly alter their thread priorities.3868//38693870int os::java_to_os_priority[CriticalPriority + 1] = {3871-99999, // 0 Entry should never be used387238730, // 1 MinPriority387432, // 2387564, // 33876387796, // 43878127, // 5 NormPriority3879127, // 638803881127, // 73882127, // 83883127, // 9 NearMaxPriority38843885127, // 10 MaxPriority38863887-criticalPrio // 11 CriticalPriority3888};38893890OSReturn os::set_native_priority(Thread* thread, int newpri) {3891OSThread* osthread = thread->osthread();38923893// Save requested priority in case the thread hasn't been started3894osthread->set_native_priority(newpri);38953896// Check for critical priority request3897bool fxcritical = false;3898if (newpri == -criticalPrio) {3899fxcritical = true;3900newpri = criticalPrio;3901}39023903assert(newpri >= MinimumPriority && newpri <= MaximumPriority, "bad priority mapping");3904if (!UseThreadPriorities) return OS_OK;39053906int status = 0;39073908if (!fxcritical) {3909// Use thr_setprio only if we have a priority that thr_setprio understands3910status = thr_setprio(thread->osthread()->thread_id(), newpri);3911}39123913if (os::Solaris::T2_libthread() ||3914(UseBoundThreads && osthread->is_vm_created())) {3915int lwp_status =3916set_lwp_class_and_priority(osthread->thread_id(),3917osthread->lwp_id(),3918newpri,3919fxcritical ? fxLimits.schedPolicy : myClass,3920!fxcritical);3921if (lwp_status != 0 && fxcritical) {3922// Try again, this time without changing the scheduling class3923newpri = java_MaxPriority_to_os_priority;3924lwp_status = set_lwp_class_and_priority(osthread->thread_id(),3925osthread->lwp_id(),3926newpri, myClass, false);3927}3928status |= lwp_status;3929}3930return (status == 0) ? OS_OK : OS_ERR;3931}393239333934OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {3935int p;3936if ( !UseThreadPriorities ) {3937*priority_ptr = NormalPriority;3938return OS_OK;3939}3940int status = thr_getprio(thread->osthread()->thread_id(), &p);3941if (status != 0) {3942return OS_ERR;3943}3944*priority_ptr = p;3945return OS_OK;3946}394739483949// Hint to the underlying OS that a task switch would not be good.3950// Void return because it's a hint and can fail.3951void os::hint_no_preempt() {3952schedctl_start(schedctl_init());3953}39543955static void resume_clear_context(OSThread *osthread) {3956osthread->set_ucontext(NULL);3957}39583959static void suspend_save_context(OSThread *osthread, ucontext_t* context) {3960osthread->set_ucontext(context);3961}39623963static Semaphore sr_semaphore;39643965void os::Solaris::SR_handler(Thread* thread, ucontext_t* uc) {3966// Save and restore errno to avoid confusing native code with EINTR3967// after sigsuspend.3968int old_errno = errno;39693970OSThread* osthread = thread->osthread();3971assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");39723973os::SuspendResume::State current = osthread->sr.state();3974if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {3975suspend_save_context(osthread, uc);39763977// attempt to switch the state, we assume we had a SUSPEND_REQUEST3978os::SuspendResume::State state = osthread->sr.suspended();3979if (state == os::SuspendResume::SR_SUSPENDED) {3980sigset_t suspend_set; // signals for sigsuspend()39813982// get current set of blocked signals and unblock resume signal3983thr_sigsetmask(SIG_BLOCK, NULL, &suspend_set);3984sigdelset(&suspend_set, os::Solaris::SIGasync());39853986sr_semaphore.signal();3987// wait here until we are resumed3988while (1) {3989sigsuspend(&suspend_set);39903991os::SuspendResume::State result = osthread->sr.running();3992if (result == os::SuspendResume::SR_RUNNING) {3993sr_semaphore.signal();3994break;3995}3996}39973998} else if (state == os::SuspendResume::SR_RUNNING) {3999// request was cancelled, continue4000} else {4001ShouldNotReachHere();4002}40034004resume_clear_context(osthread);4005} else if (current == os::SuspendResume::SR_RUNNING) {4006// request was cancelled, continue4007} else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {4008// ignore4009} else {4010// ignore4011}40124013errno = old_errno;4014}401540164017void os::interrupt(Thread* thread) {4018assert(Thread::current() == thread || Threads_lock->owned_by_self(), "possibility of dangling Thread pointer");40194020OSThread* osthread = thread->osthread();40214022int isInterrupted = osthread->interrupted();4023if (!isInterrupted) {4024osthread->set_interrupted(true);4025OrderAccess::fence();4026// os::sleep() is implemented with either poll (NULL,0,timeout) or4027// by parking on _SleepEvent. If the former, thr_kill will unwedge4028// the sleeper by SIGINTR, otherwise the unpark() will wake the sleeper.4029ParkEvent * const slp = thread->_SleepEvent ;4030if (slp != NULL) slp->unpark() ;4031}40324033// For JSR166: unpark after setting status but before thr_kill -dl4034if (thread->is_Java_thread()) {4035((JavaThread*)thread)->parker()->unpark();4036}40374038// Handle interruptible wait() ...4039ParkEvent * const ev = thread->_ParkEvent ;4040if (ev != NULL) ev->unpark() ;40414042// When events are used everywhere for os::sleep, then this thr_kill4043// will only be needed if UseVMInterruptibleIO is true.40444045if (!isInterrupted) {4046int status = thr_kill(osthread->thread_id(), os::Solaris::SIGinterrupt());4047assert_status(status == 0, status, "thr_kill");40484049// Bump thread interruption counter4050RuntimeService::record_thread_interrupt_signaled_count();4051}4052}405340544055bool os::is_interrupted(Thread* thread, bool clear_interrupted) {4056assert(Thread::current() == thread || Threads_lock->owned_by_self(), "possibility of dangling Thread pointer");40574058OSThread* osthread = thread->osthread();40594060bool res = osthread->interrupted();40614062// NOTE that since there is no "lock" around these two operations,4063// there is the possibility that the interrupted flag will be4064// "false" but that the interrupt event will be set. This is4065// intentional. The effect of this is that Object.wait() will appear4066// to have a spurious wakeup, which is not harmful, and the4067// possibility is so rare that it is not worth the added complexity4068// to add yet another lock. It has also been recommended not to put4069// the interrupted flag into the os::Solaris::Event structure,4070// because it hides the issue.4071if (res && clear_interrupted) {4072osthread->set_interrupted(false);4073}4074return res;4075}407640774078void os::print_statistics() {4079}40804081int os::message_box(const char* title, const char* message) {4082int i;4083fdStream err(defaultStream::error_fd());4084for (i = 0; i < 78; i++) err.print_raw("=");4085err.cr();4086err.print_raw_cr(title);4087for (i = 0; i < 78; i++) err.print_raw("-");4088err.cr();4089err.print_raw_cr(message);4090for (i = 0; i < 78; i++) err.print_raw("=");4091err.cr();40924093char buf[16];4094// Prevent process from exiting upon "read error" without consuming all CPU4095while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }40964097return buf[0] == 'y' || buf[0] == 'Y';4098}40994100static int sr_notify(OSThread* osthread) {4101int status = thr_kill(osthread->thread_id(), os::Solaris::SIGasync());4102assert_status(status == 0, status, "thr_kill");4103return status;4104}41054106// "Randomly" selected value for how long we want to spin4107// before bailing out on suspending a thread, also how often4108// we send a signal to a thread we want to resume4109static const int RANDOMLY_LARGE_INTEGER = 1000000;4110static const int RANDOMLY_LARGE_INTEGER2 = 100;41114112static bool do_suspend(OSThread* osthread) {4113assert(osthread->sr.is_running(), "thread should be running");4114assert(!sr_semaphore.trywait(), "semaphore has invalid state");41154116// mark as suspended and send signal4117if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {4118// failed to switch, state wasn't running?4119ShouldNotReachHere();4120return false;4121}41224123if (sr_notify(osthread) != 0) {4124ShouldNotReachHere();4125}41264127// managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED4128while (true) {4129if (sr_semaphore.timedwait(0, 2000 * NANOSECS_PER_MILLISEC)) {4130break;4131} else {4132// timeout4133os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();4134if (cancelled == os::SuspendResume::SR_RUNNING) {4135return false;4136} else if (cancelled == os::SuspendResume::SR_SUSPENDED) {4137// make sure that we consume the signal on the semaphore as well4138sr_semaphore.wait();4139break;4140} else {4141ShouldNotReachHere();4142return false;4143}4144}4145}41464147guarantee(osthread->sr.is_suspended(), "Must be suspended");4148return true;4149}41504151static void do_resume(OSThread* osthread) {4152assert(osthread->sr.is_suspended(), "thread should be suspended");4153assert(!sr_semaphore.trywait(), "invalid semaphore state");41544155if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {4156// failed to switch to WAKEUP_REQUEST4157ShouldNotReachHere();4158return;4159}41604161while (true) {4162if (sr_notify(osthread) == 0) {4163if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {4164if (osthread->sr.is_running()) {4165return;4166}4167}4168} else {4169ShouldNotReachHere();4170}4171}41724173guarantee(osthread->sr.is_running(), "Must be running!");4174}41754176void os::SuspendedThreadTask::internal_do_task() {4177if (do_suspend(_thread->osthread())) {4178SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());4179do_task(context);4180do_resume(_thread->osthread());4181}4182}41834184class PcFetcher : public os::SuspendedThreadTask {4185public:4186PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}4187ExtendedPC result();4188protected:4189void do_task(const os::SuspendedThreadTaskContext& context);4190private:4191ExtendedPC _epc;4192};41934194ExtendedPC PcFetcher::result() {4195guarantee(is_done(), "task is not done yet.");4196return _epc;4197}41984199void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {4200Thread* thread = context.thread();4201OSThread* osthread = thread->osthread();4202if (osthread->ucontext() != NULL) {4203_epc = os::Solaris::ucontext_get_pc((ucontext_t *) context.ucontext());4204} else {4205// NULL context is unexpected, double-check this is the VMThread4206guarantee(thread->is_VM_thread(), "can only be called for VMThread");4207}4208}42094210// A lightweight implementation that does not suspend the target thread and4211// thus returns only a hint. Used for profiling only!4212ExtendedPC os::get_thread_pc(Thread* thread) {4213// Make sure that it is called by the watcher and the Threads lock is owned.4214assert(Thread::current()->is_Watcher_thread(), "Must be watcher and own Threads_lock");4215// For now, is only used to profile the VM Thread4216assert(thread->is_VM_thread(), "Can only be called for VMThread");4217PcFetcher fetcher(thread);4218fetcher.run();4219return fetcher.result();4220}422142224223// This does not do anything on Solaris. This is basically a hook for being4224// able to use structured exception handling (thread-local exception filters) on, e.g., Win32.4225void os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, JavaCallArguments* args, Thread* thread) {4226f(value, method, args, thread);4227}42284229// This routine may be used by user applications as a "hook" to catch signals.4230// The user-defined signal handler must pass unrecognized signals to this4231// routine, and if it returns true (non-zero), then the signal handler must4232// return immediately. If the flag "abort_if_unrecognized" is true, then this4233// routine will never retun false (zero), but instead will execute a VM panic4234// routine kill the process.4235//4236// If this routine returns false, it is OK to call it again. This allows4237// the user-defined signal handler to perform checks either before or after4238// the VM performs its own checks. Naturally, the user code would be making4239// a serious error if it tried to handle an exception (such as a null check4240// or breakpoint) that the VM was generating for its own correct operation.4241//4242// This routine may recognize any of the following kinds of signals:4243// SIGBUS, SIGSEGV, SIGILL, SIGFPE, BREAK_SIGNAL, SIGPIPE, SIGXFSZ,4244// os::Solaris::SIGasync4245// It should be consulted by handlers for any of those signals.4246// It explicitly does not recognize os::Solaris::SIGinterrupt4247//4248// The caller of this routine must pass in the three arguments supplied4249// to the function referred to in the "sa_sigaction" (not the "sa_handler")4250// field of the structure passed to sigaction(). This routine assumes that4251// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.4252//4253// Note that the VM will print warnings if it detects conflicting signal4254// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".4255//4256extern "C" JNIEXPORT int4257JVM_handle_solaris_signal(int signo, siginfo_t* siginfo, void* ucontext,4258int abort_if_unrecognized);425942604261void signalHandler(int sig, siginfo_t* info, void* ucVoid) {4262int orig_errno = errno; // Preserve errno value over signal handler.4263JVM_handle_solaris_signal(sig, info, ucVoid, true);4264errno = orig_errno;4265}42664267/* Do not delete - if guarantee is ever removed, a signal handler (even empty)4268is needed to provoke threads blocked on IO to return an EINTR4269Note: this explicitly does NOT call JVM_handle_solaris_signal and4270does NOT participate in signal chaining due to requirement for4271NOT setting SA_RESTART to make EINTR work. */4272extern "C" void sigINTRHandler(int sig, siginfo_t* info, void* ucVoid) {4273if (UseSignalChaining) {4274struct sigaction *actp = os::Solaris::get_chained_signal_action(sig);4275if (actp && actp->sa_handler) {4276vm_exit_during_initialization("Signal chaining detected for VM interrupt signal, try -XX:+UseAltSigs");4277}4278}4279}42804281// This boolean allows users to forward their own non-matching signals4282// to JVM_handle_solaris_signal, harmlessly.4283bool os::Solaris::signal_handlers_are_installed = false;42844285// For signal-chaining4286bool os::Solaris::libjsig_is_loaded = false;4287typedef struct sigaction *(*get_signal_t)(int);4288get_signal_t os::Solaris::get_signal_action = NULL;42894290struct sigaction* os::Solaris::get_chained_signal_action(int sig) {4291struct sigaction *actp = NULL;42924293if ((libjsig_is_loaded) && (sig <= Maxlibjsigsigs)) {4294// Retrieve the old signal handler from libjsig4295actp = (*get_signal_action)(sig);4296}4297if (actp == NULL) {4298// Retrieve the preinstalled signal handler from jvm4299actp = get_preinstalled_handler(sig);4300}43014302return actp;4303}43044305static bool call_chained_handler(struct sigaction *actp, int sig,4306siginfo_t *siginfo, void *context) {4307// Call the old signal handler4308if (actp->sa_handler == SIG_DFL) {4309// It's more reasonable to let jvm treat it as an unexpected exception4310// instead of taking the default action.4311return false;4312} else if (actp->sa_handler != SIG_IGN) {4313if ((actp->sa_flags & SA_NODEFER) == 0) {4314// automaticlly block the signal4315sigaddset(&(actp->sa_mask), sig);4316}43174318sa_handler_t hand;4319sa_sigaction_t sa;4320bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;4321// retrieve the chained handler4322if (siginfo_flag_set) {4323sa = actp->sa_sigaction;4324} else {4325hand = actp->sa_handler;4326}43274328if ((actp->sa_flags & SA_RESETHAND) != 0) {4329actp->sa_handler = SIG_DFL;4330}43314332// try to honor the signal mask4333sigset_t oset;4334thr_sigsetmask(SIG_SETMASK, &(actp->sa_mask), &oset);43354336// call into the chained handler4337if (siginfo_flag_set) {4338(*sa)(sig, siginfo, context);4339} else {4340(*hand)(sig);4341}43424343// restore the signal mask4344thr_sigsetmask(SIG_SETMASK, &oset, 0);4345}4346// Tell jvm's signal handler the signal is taken care of.4347return true;4348}43494350bool os::Solaris::chained_handler(int sig, siginfo_t* siginfo, void* context) {4351bool chained = false;4352// signal-chaining4353if (UseSignalChaining) {4354struct sigaction *actp = get_chained_signal_action(sig);4355if (actp != NULL) {4356chained = call_chained_handler(actp, sig, siginfo, context);4357}4358}4359return chained;4360}43614362struct sigaction* os::Solaris::get_preinstalled_handler(int sig) {4363assert((chainedsigactions != (struct sigaction *)NULL) && (preinstalled_sigs != (int *)NULL) , "signals not yet initialized");4364if (preinstalled_sigs[sig] != 0) {4365return &chainedsigactions[sig];4366}4367return NULL;4368}43694370void os::Solaris::save_preinstalled_handler(int sig, struct sigaction& oldAct) {43714372assert(sig > 0 && sig <= Maxsignum, "vm signal out of expected range");4373assert((chainedsigactions != (struct sigaction *)NULL) && (preinstalled_sigs != (int *)NULL) , "signals not yet initialized");4374chainedsigactions[sig] = oldAct;4375preinstalled_sigs[sig] = 1;4376}43774378void os::Solaris::set_signal_handler(int sig, bool set_installed, bool oktochain) {4379// Check for overwrite.4380struct sigaction oldAct;4381sigaction(sig, (struct sigaction*)NULL, &oldAct);4382void* oldhand = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)4383: CAST_FROM_FN_PTR(void*, oldAct.sa_handler);4384if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&4385oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&4386oldhand != CAST_FROM_FN_PTR(void*, signalHandler)) {4387if (AllowUserSignalHandlers || !set_installed) {4388// Do not overwrite; user takes responsibility to forward to us.4389return;4390} else if (UseSignalChaining) {4391if (oktochain) {4392// save the old handler in jvm4393save_preinstalled_handler(sig, oldAct);4394} else {4395vm_exit_during_initialization("Signal chaining not allowed for VM interrupt signal, try -XX:+UseAltSigs.");4396}4397// libjsig also interposes the sigaction() call below and saves the4398// old sigaction on it own.4399} else {4400fatal(err_msg("Encountered unexpected pre-existing sigaction handler "4401"%#lx for signal %d.", (long)oldhand, sig));4402}4403}44044405struct sigaction sigAct;4406sigfillset(&(sigAct.sa_mask));4407sigAct.sa_handler = SIG_DFL;44084409sigAct.sa_sigaction = signalHandler;4410// Handle SIGSEGV on alternate signal stack if4411// not using stack banging4412if (!UseStackBanging && sig == SIGSEGV) {4413sigAct.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;4414// Interruptible i/o requires SA_RESTART cleared so EINTR4415// is returned instead of restarting system calls4416} else if (sig == os::Solaris::SIGinterrupt()) {4417sigemptyset(&sigAct.sa_mask);4418sigAct.sa_handler = NULL;4419sigAct.sa_flags = SA_SIGINFO;4420sigAct.sa_sigaction = sigINTRHandler;4421} else {4422sigAct.sa_flags = SA_SIGINFO | SA_RESTART;4423}4424os::Solaris::set_our_sigflags(sig, sigAct.sa_flags);44254426sigaction(sig, &sigAct, &oldAct);44274428void* oldhand2 = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)4429: CAST_FROM_FN_PTR(void*, oldAct.sa_handler);4430assert(oldhand2 == oldhand, "no concurrent signal handler installation");4431}443244334434#define DO_SIGNAL_CHECK(sig) \4435if (!sigismember(&check_signal_done, sig)) \4436os::Solaris::check_signal_handler(sig)44374438// This method is a periodic task to check for misbehaving JNI applications4439// under CheckJNI, we can add any periodic checks here44404441void os::run_periodic_checks() {4442// A big source of grief is hijacking virt. addr 0x0 on Solaris,4443// thereby preventing a NULL checks.4444if(!check_addr0_done) check_addr0_done = check_addr0(tty);44454446if (check_signals == false) return;44474448// SEGV and BUS if overridden could potentially prevent4449// generation of hs*.log in the event of a crash, debugging4450// such a case can be very challenging, so we absolutely4451// check for the following for a good measure:4452DO_SIGNAL_CHECK(SIGSEGV);4453DO_SIGNAL_CHECK(SIGILL);4454DO_SIGNAL_CHECK(SIGFPE);4455DO_SIGNAL_CHECK(SIGBUS);4456DO_SIGNAL_CHECK(SIGPIPE);4457DO_SIGNAL_CHECK(SIGXFSZ);44584459// ReduceSignalUsage allows the user to override these handlers4460// see comments at the very top and jvm_solaris.h4461if (!ReduceSignalUsage) {4462DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);4463DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);4464DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);4465DO_SIGNAL_CHECK(BREAK_SIGNAL);4466}44674468// See comments above for using JVM1/JVM2 and UseAltSigs4469DO_SIGNAL_CHECK(os::Solaris::SIGinterrupt());4470DO_SIGNAL_CHECK(os::Solaris::SIGasync());44714472}44734474typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);44754476static os_sigaction_t os_sigaction = NULL;44774478void os::Solaris::check_signal_handler(int sig) {4479char buf[O_BUFLEN];4480address jvmHandler = NULL;44814482struct sigaction act;4483if (os_sigaction == NULL) {4484// only trust the default sigaction, in case it has been interposed4485os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");4486if (os_sigaction == NULL) return;4487}44884489os_sigaction(sig, (struct sigaction*)NULL, &act);44904491address thisHandler = (act.sa_flags & SA_SIGINFO)4492? CAST_FROM_FN_PTR(address, act.sa_sigaction)4493: CAST_FROM_FN_PTR(address, act.sa_handler) ;449444954496switch(sig) {4497case SIGSEGV:4498case SIGBUS:4499case SIGFPE:4500case SIGPIPE:4501case SIGXFSZ:4502case SIGILL:4503jvmHandler = CAST_FROM_FN_PTR(address, signalHandler);4504break;45054506case SHUTDOWN1_SIGNAL:4507case SHUTDOWN2_SIGNAL:4508case SHUTDOWN3_SIGNAL:4509case BREAK_SIGNAL:4510jvmHandler = (address)user_handler();4511break;45124513default:4514int intrsig = os::Solaris::SIGinterrupt();4515int asynsig = os::Solaris::SIGasync();45164517if (sig == intrsig) {4518jvmHandler = CAST_FROM_FN_PTR(address, sigINTRHandler);4519} else if (sig == asynsig) {4520jvmHandler = CAST_FROM_FN_PTR(address, signalHandler);4521} else {4522return;4523}4524break;4525}452645274528if (thisHandler != jvmHandler) {4529tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));4530tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));4531tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));4532// No need to check this sig any longer4533sigaddset(&check_signal_done, sig);4534// Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN4535if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {4536tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",4537exception_name(sig, buf, O_BUFLEN));4538}4539} else if(os::Solaris::get_our_sigflags(sig) != 0 && act.sa_flags != os::Solaris::get_our_sigflags(sig)) {4540tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));4541tty->print("expected:" PTR32_FORMAT, os::Solaris::get_our_sigflags(sig));4542tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags);4543// No need to check this sig any longer4544sigaddset(&check_signal_done, sig);4545}45464547// Print all the signal handler state4548if (sigismember(&check_signal_done, sig)) {4549print_signal_handlers(tty, buf, O_BUFLEN);4550}45514552}45534554void os::Solaris::install_signal_handlers() {4555bool libjsigdone = false;4556signal_handlers_are_installed = true;45574558// signal-chaining4559typedef void (*signal_setting_t)();4560signal_setting_t begin_signal_setting = NULL;4561signal_setting_t end_signal_setting = NULL;4562begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,4563dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));4564if (begin_signal_setting != NULL) {4565end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,4566dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));4567get_signal_action = CAST_TO_FN_PTR(get_signal_t,4568dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));4569get_libjsig_version = CAST_TO_FN_PTR(version_getting_t,4570dlsym(RTLD_DEFAULT, "JVM_get_libjsig_version"));4571libjsig_is_loaded = true;4572if (os::Solaris::get_libjsig_version != NULL) {4573libjsigversion = (*os::Solaris::get_libjsig_version)();4574}4575assert(UseSignalChaining, "should enable signal-chaining");4576}4577if (libjsig_is_loaded) {4578// Tell libjsig jvm is setting signal handlers4579(*begin_signal_setting)();4580}45814582set_signal_handler(SIGSEGV, true, true);4583set_signal_handler(SIGPIPE, true, true);4584set_signal_handler(SIGXFSZ, true, true);4585set_signal_handler(SIGBUS, true, true);4586set_signal_handler(SIGILL, true, true);4587set_signal_handler(SIGFPE, true, true);458845894590if (os::Solaris::SIGinterrupt() > OLDMAXSIGNUM || os::Solaris::SIGasync() > OLDMAXSIGNUM) {45914592// Pre-1.4.1 Libjsig limited to signal chaining signals <= 32 so4593// can not register overridable signals which might be > 324594if (libjsig_is_loaded && libjsigversion <= JSIG_VERSION_1_4_1) {4595// Tell libjsig jvm has finished setting signal handlers4596(*end_signal_setting)();4597libjsigdone = true;4598}4599}46004601// Never ok to chain our SIGinterrupt4602set_signal_handler(os::Solaris::SIGinterrupt(), true, false);4603set_signal_handler(os::Solaris::SIGasync(), true, true);46044605if (libjsig_is_loaded && !libjsigdone) {4606// Tell libjsig jvm finishes setting signal handlers4607(*end_signal_setting)();4608}46094610// We don't activate signal checker if libjsig is in place, we trust ourselves4611// and if UserSignalHandler is installed all bets are off.4612// Log that signal checking is off only if -verbose:jni is specified.4613if (CheckJNICalls) {4614if (libjsig_is_loaded) {4615if (PrintJNIResolving) {4616tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");4617}4618check_signals = false;4619}4620if (AllowUserSignalHandlers) {4621if (PrintJNIResolving) {4622tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");4623}4624check_signals = false;4625}4626}4627}462846294630void report_error(const char* file_name, int line_no, const char* title, const char* format, ...);46314632const char * signames[] = {4633"SIG0",4634"SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP",4635"SIGABRT", "SIGEMT", "SIGFPE", "SIGKILL", "SIGBUS",4636"SIGSEGV", "SIGSYS", "SIGPIPE", "SIGALRM", "SIGTERM",4637"SIGUSR1", "SIGUSR2", "SIGCLD", "SIGPWR", "SIGWINCH",4638"SIGURG", "SIGPOLL", "SIGSTOP", "SIGTSTP", "SIGCONT",4639"SIGTTIN", "SIGTTOU", "SIGVTALRM", "SIGPROF", "SIGXCPU",4640"SIGXFSZ", "SIGWAITING", "SIGLWP", "SIGFREEZE", "SIGTHAW",4641"SIGCANCEL", "SIGLOST"4642};46434644const char* os::exception_name(int exception_code, char* buf, size_t size) {4645if (0 < exception_code && exception_code <= SIGRTMAX) {4646// signal4647if (exception_code < sizeof(signames)/sizeof(const char*)) {4648jio_snprintf(buf, size, "%s", signames[exception_code]);4649} else {4650jio_snprintf(buf, size, "SIG%d", exception_code);4651}4652return buf;4653} else {4654return NULL;4655}4656}46574658// (Static) wrappers for the new libthread API4659int_fnP_thread_t_iP_uP_stack_tP_gregset_t os::Solaris::_thr_getstate;4660int_fnP_thread_t_i_gregset_t os::Solaris::_thr_setstate;4661int_fnP_thread_t_i os::Solaris::_thr_setmutator;4662int_fnP_thread_t os::Solaris::_thr_suspend_mutator;4663int_fnP_thread_t os::Solaris::_thr_continue_mutator;46644665// (Static) wrapper for getisax(2) call.4666os::Solaris::getisax_func_t os::Solaris::_getisax = 0;46674668// (Static) wrappers for the liblgrp API4669os::Solaris::lgrp_home_func_t os::Solaris::_lgrp_home;4670os::Solaris::lgrp_init_func_t os::Solaris::_lgrp_init;4671os::Solaris::lgrp_fini_func_t os::Solaris::_lgrp_fini;4672os::Solaris::lgrp_root_func_t os::Solaris::_lgrp_root;4673os::Solaris::lgrp_children_func_t os::Solaris::_lgrp_children;4674os::Solaris::lgrp_resources_func_t os::Solaris::_lgrp_resources;4675os::Solaris::lgrp_nlgrps_func_t os::Solaris::_lgrp_nlgrps;4676os::Solaris::lgrp_cookie_stale_func_t os::Solaris::_lgrp_cookie_stale;4677os::Solaris::lgrp_cookie_t os::Solaris::_lgrp_cookie = 0;46784679// (Static) wrapper for meminfo() call.4680os::Solaris::meminfo_func_t os::Solaris::_meminfo = 0;46814682static address resolve_symbol_lazy(const char* name) {4683address addr = (address) dlsym(RTLD_DEFAULT, name);4684if(addr == NULL) {4685// RTLD_DEFAULT was not defined on some early versions of 2.5.14686addr = (address) dlsym(RTLD_NEXT, name);4687}4688return addr;4689}46904691static address resolve_symbol(const char* name) {4692address addr = resolve_symbol_lazy(name);4693if(addr == NULL) {4694fatal(dlerror());4695}4696return addr;4697}4698469947004701// isT2_libthread()4702//4703// Routine to determine if we are currently using the new T2 libthread.4704//4705// We determine if we are using T2 by reading /proc/self/lstatus and4706// looking for a thread with the ASLWP bit set. If we find this status4707// bit set, we must assume that we are NOT using T2. The T2 team4708// has approved this algorithm.4709//4710// We need to determine if we are running with the new T2 libthread4711// since setting native thread priorities is handled differently4712// when using this library. All threads created using T2 are bound4713// threads. Calling thr_setprio is meaningless in this case.4714//4715bool isT2_libthread() {4716static prheader_t * lwpArray = NULL;4717static int lwpSize = 0;4718static int lwpFile = -1;4719lwpstatus_t * that;4720char lwpName [128];4721bool isT2 = false;47224723#define ADR(x) ((uintptr_t)(x))4724#define LWPINDEX(ary,ix) ((lwpstatus_t *)(((ary)->pr_entsize * (ix)) + (ADR((ary) + 1))))47254726lwpFile = ::open("/proc/self/lstatus", O_RDONLY, 0);4727if (lwpFile < 0) {4728if (ThreadPriorityVerbose) warning ("Couldn't open /proc/self/lstatus\n");4729return false;4730}4731lwpSize = 16*1024;4732for (;;) {4733::lseek64 (lwpFile, 0, SEEK_SET);4734lwpArray = (prheader_t *)NEW_C_HEAP_ARRAY(char, lwpSize, mtInternal);4735if (::read(lwpFile, lwpArray, lwpSize) < 0) {4736if (ThreadPriorityVerbose) warning("Error reading /proc/self/lstatus\n");4737break;4738}4739if ((lwpArray->pr_nent * lwpArray->pr_entsize) <= lwpSize) {4740// We got a good snapshot - now iterate over the list.4741int aslwpcount = 0;4742for (int i = 0; i < lwpArray->pr_nent; i++ ) {4743that = LWPINDEX(lwpArray,i);4744if (that->pr_flags & PR_ASLWP) {4745aslwpcount++;4746}4747}4748if (aslwpcount == 0) isT2 = true;4749break;4750}4751lwpSize = lwpArray->pr_nent * lwpArray->pr_entsize;4752FREE_C_HEAP_ARRAY(char, lwpArray, mtInternal); // retry.4753}47544755FREE_C_HEAP_ARRAY(char, lwpArray, mtInternal);4756::close (lwpFile);4757if (ThreadPriorityVerbose) {4758if (isT2) tty->print_cr("We are running with a T2 libthread\n");4759else tty->print_cr("We are not running with a T2 libthread\n");4760}4761return isT2;4762}476347644765void os::Solaris::libthread_init() {4766address func = (address)dlsym(RTLD_DEFAULT, "_thr_suspend_allmutators");47674768// Determine if we are running with the new T2 libthread4769os::Solaris::set_T2_libthread(isT2_libthread());47704771lwp_priocntl_init();47724773// RTLD_DEFAULT was not defined on some early versions of 5.5.14774if(func == NULL) {4775func = (address) dlsym(RTLD_NEXT, "_thr_suspend_allmutators");4776// Guarantee that this VM is running on an new enough OS (5.6 or4777// later) that it will have a new enough libthread.so.4778guarantee(func != NULL, "libthread.so is too old.");4779}47804781// Initialize the new libthread getstate API wrappers4782func = resolve_symbol("thr_getstate");4783os::Solaris::set_thr_getstate(CAST_TO_FN_PTR(int_fnP_thread_t_iP_uP_stack_tP_gregset_t, func));47844785func = resolve_symbol("thr_setstate");4786os::Solaris::set_thr_setstate(CAST_TO_FN_PTR(int_fnP_thread_t_i_gregset_t, func));47874788func = resolve_symbol("thr_setmutator");4789os::Solaris::set_thr_setmutator(CAST_TO_FN_PTR(int_fnP_thread_t_i, func));47904791func = resolve_symbol("thr_suspend_mutator");4792os::Solaris::set_thr_suspend_mutator(CAST_TO_FN_PTR(int_fnP_thread_t, func));47934794func = resolve_symbol("thr_continue_mutator");4795os::Solaris::set_thr_continue_mutator(CAST_TO_FN_PTR(int_fnP_thread_t, func));47964797int size;4798void (*handler_info_func)(address *, int *);4799handler_info_func = CAST_TO_FN_PTR(void (*)(address *, int *), resolve_symbol("thr_sighndlrinfo"));4800handler_info_func(&handler_start, &size);4801handler_end = handler_start + size;4802}480348044805int_fnP_mutex_tP os::Solaris::_mutex_lock;4806int_fnP_mutex_tP os::Solaris::_mutex_trylock;4807int_fnP_mutex_tP os::Solaris::_mutex_unlock;4808int_fnP_mutex_tP_i_vP os::Solaris::_mutex_init;4809int_fnP_mutex_tP os::Solaris::_mutex_destroy;4810int os::Solaris::_mutex_scope = USYNC_THREAD;48114812int_fnP_cond_tP_mutex_tP_timestruc_tP os::Solaris::_cond_timedwait;4813int_fnP_cond_tP_mutex_tP os::Solaris::_cond_wait;4814int_fnP_cond_tP os::Solaris::_cond_signal;4815int_fnP_cond_tP os::Solaris::_cond_broadcast;4816int_fnP_cond_tP_i_vP os::Solaris::_cond_init;4817int_fnP_cond_tP os::Solaris::_cond_destroy;4818int os::Solaris::_cond_scope = USYNC_THREAD;48194820void os::Solaris::synchronization_init() {4821if(UseLWPSynchronization) {4822os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_lock")));4823os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_trylock")));4824os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_unlock")));4825os::Solaris::set_mutex_init(lwp_mutex_init);4826os::Solaris::set_mutex_destroy(lwp_mutex_destroy);4827os::Solaris::set_mutex_scope(USYNC_THREAD);48284829os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("_lwp_cond_timedwait")));4830os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("_lwp_cond_wait")));4831os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_signal")));4832os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_broadcast")));4833os::Solaris::set_cond_init(lwp_cond_init);4834os::Solaris::set_cond_destroy(lwp_cond_destroy);4835os::Solaris::set_cond_scope(USYNC_THREAD);4836}4837else {4838os::Solaris::set_mutex_scope(USYNC_THREAD);4839os::Solaris::set_cond_scope(USYNC_THREAD);48404841if(UsePthreads) {4842os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_lock")));4843os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_trylock")));4844os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_unlock")));4845os::Solaris::set_mutex_init(pthread_mutex_default_init);4846os::Solaris::set_mutex_destroy(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_destroy")));48474848os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("pthread_cond_timedwait")));4849os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("pthread_cond_wait")));4850os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_signal")));4851os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_broadcast")));4852os::Solaris::set_cond_init(pthread_cond_default_init);4853os::Solaris::set_cond_destroy(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_destroy")));4854}4855else {4856os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_lock")));4857os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_trylock")));4858os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_unlock")));4859os::Solaris::set_mutex_init(::mutex_init);4860os::Solaris::set_mutex_destroy(::mutex_destroy);48614862os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("cond_timedwait")));4863os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("cond_wait")));4864os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_signal")));4865os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_broadcast")));4866os::Solaris::set_cond_init(::cond_init);4867os::Solaris::set_cond_destroy(::cond_destroy);4868}4869}4870}48714872bool os::Solaris::liblgrp_init() {4873void *handle = dlopen("liblgrp.so.1", RTLD_LAZY);4874if (handle != NULL) {4875os::Solaris::set_lgrp_home(CAST_TO_FN_PTR(lgrp_home_func_t, dlsym(handle, "lgrp_home")));4876os::Solaris::set_lgrp_init(CAST_TO_FN_PTR(lgrp_init_func_t, dlsym(handle, "lgrp_init")));4877os::Solaris::set_lgrp_fini(CAST_TO_FN_PTR(lgrp_fini_func_t, dlsym(handle, "lgrp_fini")));4878os::Solaris::set_lgrp_root(CAST_TO_FN_PTR(lgrp_root_func_t, dlsym(handle, "lgrp_root")));4879os::Solaris::set_lgrp_children(CAST_TO_FN_PTR(lgrp_children_func_t, dlsym(handle, "lgrp_children")));4880os::Solaris::set_lgrp_resources(CAST_TO_FN_PTR(lgrp_resources_func_t, dlsym(handle, "lgrp_resources")));4881os::Solaris::set_lgrp_nlgrps(CAST_TO_FN_PTR(lgrp_nlgrps_func_t, dlsym(handle, "lgrp_nlgrps")));4882os::Solaris::set_lgrp_cookie_stale(CAST_TO_FN_PTR(lgrp_cookie_stale_func_t,4883dlsym(handle, "lgrp_cookie_stale")));48844885lgrp_cookie_t c = lgrp_init(LGRP_VIEW_CALLER);4886set_lgrp_cookie(c);4887return true;4888}4889return false;4890}48914892void os::Solaris::misc_sym_init() {4893address func;48944895// getisax4896func = resolve_symbol_lazy("getisax");4897if (func != NULL) {4898os::Solaris::_getisax = CAST_TO_FN_PTR(getisax_func_t, func);4899}49004901// meminfo4902func = resolve_symbol_lazy("meminfo");4903if (func != NULL) {4904os::Solaris::set_meminfo(CAST_TO_FN_PTR(meminfo_func_t, func));4905}4906}49074908uint_t os::Solaris::getisax(uint32_t* array, uint_t n) {4909assert(_getisax != NULL, "_getisax not set");4910return _getisax(array, n);4911}49124913// int pset_getloadavg(psetid_t pset, double loadavg[], int nelem);4914typedef long (*pset_getloadavg_type)(psetid_t pset, double loadavg[], int nelem);4915static pset_getloadavg_type pset_getloadavg_ptr = NULL;49164917void init_pset_getloadavg_ptr(void) {4918pset_getloadavg_ptr =4919(pset_getloadavg_type)dlsym(RTLD_DEFAULT, "pset_getloadavg");4920if (PrintMiscellaneous && Verbose && pset_getloadavg_ptr == NULL) {4921warning("pset_getloadavg function not found");4922}4923}49244925int os::Solaris::_dev_zero_fd = -1;49264927// this is called _before_ the global arguments have been parsed4928void os::init(void) {4929_initial_pid = getpid();49304931max_hrtime = first_hrtime = gethrtime();49324933init_random(1234567);49344935page_size = sysconf(_SC_PAGESIZE);4936if (page_size == -1)4937fatal(err_msg("os_solaris.cpp: os::init: sysconf failed (%s)",4938strerror(errno)));4939init_page_sizes((size_t) page_size);49404941Solaris::initialize_system_info();49424943// Initialize misc. symbols as soon as possible, so we can use them4944// if we need them.4945Solaris::misc_sym_init();49464947int fd = ::open("/dev/zero", O_RDWR);4948if (fd < 0) {4949fatal(err_msg("os::init: cannot open /dev/zero (%s)", strerror(errno)));4950} else {4951Solaris::set_dev_zero_fd(fd);49524953// Close on exec, child won't inherit.4954fcntl(fd, F_SETFD, FD_CLOEXEC);4955}49564957clock_tics_per_sec = CLK_TCK;49584959// check if dladdr1() exists; dladdr1 can provide more information than4960// dladdr for os::dll_address_to_function_name. It comes with SunOS 5.94961// and is available on linker patches for 5.7 and 5.8.4962// libdl.so must have been loaded, this call is just an entry lookup4963void * hdl = dlopen("libdl.so", RTLD_NOW);4964if (hdl)4965dladdr1_func = CAST_TO_FN_PTR(dladdr1_func_type, dlsym(hdl, "dladdr1"));49664967// (Solaris only) this switches to calls that actually do locking.4968ThreadCritical::initialize();49694970// main_thread points to the thread that created/loaded the JVM.4971main_thread = thr_self();49724973// Constant minimum stack size allowed. It must be at least4974// the minimum of what the OS supports (thr_min_stack()), and4975// enough to allow the thread to get to user bytecode execution.4976Solaris::min_stack_allowed = MAX2(thr_min_stack(), Solaris::min_stack_allowed);49774978// retrieve entry point for pthread_setname_np4979void * handle = dlopen("libc.so.1", RTLD_LAZY);4980if (handle != NULL) {4981Solaris::_pthread_setname_np =4982(Solaris::pthread_setname_np_func_t)dlsym(handle, "pthread_setname_np");4983}4984// If the pagesize of the VM is greater than 8K determine the appropriate4985// number of initial guard pages. The user can change this with the4986// command line arguments, if needed.4987if (vm_page_size() > 8*K) {4988StackYellowPages = 1;4989StackRedPages = 1;4990StackShadowPages = round_to((StackShadowPages*8*K), vm_page_size()) / vm_page_size();4991}4992}49934994// To install functions for atexit system call4995extern "C" {4996static void perfMemory_exit_helper() {4997perfMemory_exit();4998}4999}50005001// this is called _after_ the global arguments have been parsed5002jint os::init_2(void) {5003// try to enable extended file IO ASAP, see 64312785004os::Solaris::try_enable_extended_io();50055006// Allocate a single page and mark it as readable for safepoint polling. Also5007// use this first mmap call to check support for MAP_ALIGN.5008address polling_page = (address)Solaris::mmap_chunk((char*)page_size,5009page_size,5010MAP_PRIVATE | MAP_ALIGN,5011PROT_READ);5012if (polling_page == NULL) {5013has_map_align = false;5014polling_page = (address)Solaris::mmap_chunk(NULL, page_size, MAP_PRIVATE,5015PROT_READ);5016}50175018os::set_polling_page(polling_page);50195020#ifndef PRODUCT5021if( Verbose && PrintMiscellaneous )5022tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);5023#endif50245025if (!UseMembar) {5026address mem_serialize_page = (address)Solaris::mmap_chunk( NULL, page_size, MAP_PRIVATE, PROT_READ | PROT_WRITE );5027guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page");5028os::set_memory_serialize_page( mem_serialize_page );50295030#ifndef PRODUCT5031if(Verbose && PrintMiscellaneous)5032tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);5033#endif5034}50355036// Check minimum allowable stack size for thread creation and to initialize5037// the java system classes, including StackOverflowError - depends on page5038// size. Add a page for compiler2 recursion in main thread.5039// Add in 2*BytesPerWord times page size to account for VM stack during5040// class initialization depending on 32 or 64 bit VM.5041os::Solaris::min_stack_allowed = MAX2(os::Solaris::min_stack_allowed,5042(size_t)(StackYellowPages+StackRedPages+StackShadowPages+50432*BytesPerWord COMPILER2_PRESENT(+1)) * page_size);50445045size_t threadStackSizeInBytes = ThreadStackSize * K;5046if (threadStackSizeInBytes != 0 &&5047threadStackSizeInBytes < os::Solaris::min_stack_allowed) {5048tty->print_cr("\nThe stack size specified is too small, Specify at least %dk",5049os::Solaris::min_stack_allowed/K);5050return JNI_ERR;5051}50525053// For 64kbps there will be a 64kb page size, which makes5054// the usable default stack size quite a bit less. Increase the5055// stack for 64kb (or any > than 8kb) pages, this increases5056// virtual memory fragmentation (since we're not creating the5057// stack on a power of 2 boundary. The real fix for this5058// should be to fix the guard page mechanism.50595060if (vm_page_size() > 8*K) {5061threadStackSizeInBytes = (threadStackSizeInBytes != 0)5062? threadStackSizeInBytes +5063((StackYellowPages + StackRedPages) * vm_page_size())5064: 0;5065ThreadStackSize = threadStackSizeInBytes/K;5066}50675068// Make the stack size a multiple of the page size so that5069// the yellow/red zones can be guarded.5070JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,5071vm_page_size()));50725073Solaris::libthread_init();50745075if (UseNUMA) {5076if (!Solaris::liblgrp_init()) {5077UseNUMA = false;5078} else {5079size_t lgrp_limit = os::numa_get_groups_num();5080int *lgrp_ids = NEW_C_HEAP_ARRAY(int, lgrp_limit, mtInternal);5081size_t lgrp_num = os::numa_get_leaf_groups(lgrp_ids, lgrp_limit);5082FREE_C_HEAP_ARRAY(int, lgrp_ids, mtInternal);5083if (lgrp_num < 2) {5084// There's only one locality group, disable NUMA.5085UseNUMA = false;5086}5087}5088if (!UseNUMA && ForceNUMA) {5089UseNUMA = true;5090}5091}50925093Solaris::signal_sets_init();5094Solaris::init_signal_mem();5095Solaris::install_signal_handlers();50965097if (libjsigversion < JSIG_VERSION_1_4_1) {5098Maxlibjsigsigs = OLDMAXSIGNUM;5099}51005101// initialize synchronization primitives to use either thread or5102// lwp synchronization (controlled by UseLWPSynchronization)5103Solaris::synchronization_init();51045105if (MaxFDLimit) {5106// set the number of file descriptors to max. print out error5107// if getrlimit/setrlimit fails but continue regardless.5108struct rlimit nbr_files;5109int status = getrlimit(RLIMIT_NOFILE, &nbr_files);5110if (status != 0) {5111if (PrintMiscellaneous && (Verbose || WizardMode))5112perror("os::init_2 getrlimit failed");5113} else {5114nbr_files.rlim_cur = nbr_files.rlim_max;5115status = setrlimit(RLIMIT_NOFILE, &nbr_files);5116if (status != 0) {5117if (PrintMiscellaneous && (Verbose || WizardMode))5118perror("os::init_2 setrlimit failed");5119}5120}5121}51225123// Calculate theoretical max. size of Threads to guard gainst5124// artifical out-of-memory situations, where all available address-5125// space has been reserved by thread stacks. Default stack size is 1Mb.5126size_t pre_thread_stack_size = (JavaThread::stack_size_at_create()) ?5127JavaThread::stack_size_at_create() : (1*K*K);5128assert(pre_thread_stack_size != 0, "Must have a stack");5129// Solaris has a maximum of 4Gb of user programs. Calculate the thread limit when5130// we should start doing Virtual Memory banging. Currently when the threads will5131// have used all but 200Mb of space.5132size_t max_address_space = ((unsigned int)4 * K * K * K) - (200 * K * K);5133Solaris::_os_thread_limit = max_address_space / pre_thread_stack_size;51345135// at-exit methods are called in the reverse order of their registration.5136// In Solaris 7 and earlier, atexit functions are called on return from5137// main or as a result of a call to exit(3C). There can be only 32 of5138// these functions registered and atexit() does not set errno. In Solaris5139// 8 and later, there is no limit to the number of functions registered5140// and atexit() sets errno. In addition, in Solaris 8 and later, atexit5141// functions are called upon dlclose(3DL) in addition to return from main5142// and exit(3C).51435144if (PerfAllowAtExitRegistration) {5145// only register atexit functions if PerfAllowAtExitRegistration is set.5146// atexit functions can be delayed until process exit time, which5147// can be problematic for embedded VM situations. Embedded VMs should5148// call DestroyJavaVM() to assure that VM resources are released.51495150// note: perfMemory_exit_helper atexit function may be removed in5151// the future if the appropriate cleanup code can be added to the5152// VM_Exit VMOperation's doit method.5153if (atexit(perfMemory_exit_helper) != 0) {5154warning("os::init2 atexit(perfMemory_exit_helper) failed");5155}5156}51575158// Init pset_loadavg function pointer5159init_pset_getloadavg_ptr();51605161return JNI_OK;5162}51635164// Mark the polling page as unreadable5165void os::make_polling_page_unreadable(void) {5166if( mprotect((char *)_polling_page, page_size, PROT_NONE) != 0 )5167fatal("Could not disable polling page");5168};51695170// Mark the polling page as readable5171void os::make_polling_page_readable(void) {5172if( mprotect((char *)_polling_page, page_size, PROT_READ) != 0 )5173fatal("Could not enable polling page");5174};51755176// OS interface.51775178bool os::check_heap(bool force) { return true; }51795180typedef int (*vsnprintf_t)(char* buf, size_t count, const char* fmt, va_list argptr);5181static vsnprintf_t sol_vsnprintf = NULL;51825183int local_vsnprintf(char* buf, size_t count, const char* fmt, va_list argptr) {5184if (!sol_vsnprintf) {5185//search for the named symbol in the objects that were loaded after libjvm5186void* where = RTLD_NEXT;5187if ((sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "__vsnprintf"))) == NULL)5188sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "vsnprintf"));5189if (!sol_vsnprintf){5190//search for the named symbol in the objects that were loaded before libjvm5191where = RTLD_DEFAULT;5192if ((sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "__vsnprintf"))) == NULL)5193sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "vsnprintf"));5194assert(sol_vsnprintf != NULL, "vsnprintf not found");5195}5196}5197return (*sol_vsnprintf)(buf, count, fmt, argptr);5198}519952005201// Is a (classpath) directory empty?5202bool os::dir_is_empty(const char* path) {5203DIR *dir = NULL;5204struct dirent *ptr;52055206dir = opendir(path);5207if (dir == NULL) return true;52085209/* Scan the directory */5210bool result = true;5211while (result && (ptr = readdir(dir)) != NULL) {5212if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {5213result = false;5214}5215}5216closedir(dir);5217return result;5218}52195220// This code originates from JDK's sysOpen and open64_w5221// from src/solaris/hpi/src/system_md.c52225223#ifndef O_DELETE5224#define O_DELETE 0x100005225#endif52265227// Open a file. Unlink the file immediately after open returns5228// if the specified oflag has the O_DELETE flag set.5229// O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c52305231int os::open(const char *path, int oflag, int mode) {5232if (strlen(path) > MAX_PATH - 1) {5233errno = ENAMETOOLONG;5234return -1;5235}5236int fd;5237int o_delete = (oflag & O_DELETE);5238oflag = oflag & ~O_DELETE;52395240fd = ::open64(path, oflag, mode);5241if (fd == -1) return -1;52425243//If the open succeeded, the file might still be a directory5244{5245struct stat64 buf64;5246int ret = ::fstat64(fd, &buf64);5247int st_mode = buf64.st_mode;52485249if (ret != -1) {5250if ((st_mode & S_IFMT) == S_IFDIR) {5251errno = EISDIR;5252::close(fd);5253return -1;5254}5255} else {5256::close(fd);5257return -1;5258}5259}5260/*5261* 32-bit Solaris systems suffer from:5262*5263* - an historical default soft limit of 256 per-process file5264* descriptors that is too low for many Java programs.5265*5266* - a design flaw where file descriptors created using stdio5267* fopen must be less than 256, _even_ when the first limit above5268* has been raised. This can cause calls to fopen (but not calls to5269* open, for example) to fail mysteriously, perhaps in 3rd party5270* native code (although the JDK itself uses fopen). One can hardly5271* criticize them for using this most standard of all functions.5272*5273* We attempt to make everything work anyways by:5274*5275* - raising the soft limit on per-process file descriptors beyond5276* 2565277*5278* - As of Solaris 10u4, we can request that Solaris raise the 2565279* stdio fopen limit by calling function enable_extended_FILE_stdio.5280* This is done in init_2 and recorded in enabled_extended_FILE_stdio5281*5282* - If we are stuck on an old (pre 10u4) Solaris system, we can5283* workaround the bug by remapping non-stdio file descriptors below5284* 256 to ones beyond 256, which is done below.5285*5286* See:5287* 1085341: 32-bit stdio routines should support file descriptors >2555288* 6533291: Work around 32-bit Solaris stdio limit of 256 open files5289* 6431278: Netbeans crash on 32 bit Solaris: need to call5290* enable_extended_FILE_stdio() in VM initialisation5291* Giri Mandalika's blog5292* http://technopark02.blogspot.com/2005_05_01_archive.html5293*/5294#ifndef _LP645295if ((!enabled_extended_FILE_stdio) && fd < 256) {5296int newfd = ::fcntl(fd, F_DUPFD, 256);5297if (newfd != -1) {5298::close(fd);5299fd = newfd;5300}5301}5302#endif // 32-bit Solaris5303/*5304* All file descriptors that are opened in the JVM and not5305* specifically destined for a subprocess should have the5306* close-on-exec flag set. If we don't set it, then careless 3rd5307* party native code might fork and exec without closing all5308* appropriate file descriptors (e.g. as we do in closeDescriptors in5309* UNIXProcess.c), and this in turn might:5310*5311* - cause end-of-file to fail to be detected on some file5312* descriptors, resulting in mysterious hangs, or5313*5314* - might cause an fopen in the subprocess to fail on a system5315* suffering from bug 1085341.5316*5317* (Yes, the default setting of the close-on-exec flag is a Unix5318* design flaw)5319*5320* See:5321* 1085341: 32-bit stdio routines should support file descriptors >2555322* 4843136: (process) pipe file descriptor from Runtime.exec not being closed5323* 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 95324*/5325#ifdef FD_CLOEXEC5326{5327int flags = ::fcntl(fd, F_GETFD);5328if (flags != -1)5329::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);5330}5331#endif53325333if (o_delete != 0) {5334::unlink(path);5335}5336return fd;5337}53385339// create binary file, rewriting existing file if required5340int os::create_binary_file(const char* path, bool rewrite_existing) {5341int oflags = O_WRONLY | O_CREAT;5342if (!rewrite_existing) {5343oflags |= O_EXCL;5344}5345return ::open64(path, oflags, S_IREAD | S_IWRITE);5346}53475348// return current position of file pointer5349jlong os::current_file_offset(int fd) {5350return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);5351}53525353// move file pointer to the specified offset5354jlong os::seek_to_file_offset(int fd, jlong offset) {5355return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);5356}53575358jlong os::lseek(int fd, jlong offset, int whence) {5359return (jlong) ::lseek64(fd, offset, whence);5360}53615362char * os::native_path(char *path) {5363return path;5364}53655366int os::ftruncate(int fd, jlong length) {5367return ::ftruncate64(fd, length);5368}53695370int os::fsync(int fd) {5371RESTARTABLE_RETURN_INT(::fsync(fd));5372}53735374int os::available(int fd, jlong *bytes) {5375jlong cur, end;5376int mode;5377struct stat64 buf64;53785379if (::fstat64(fd, &buf64) >= 0) {5380mode = buf64.st_mode;5381if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {5382/*5383* XXX: is the following call interruptible? If so, this might5384* need to go through the INTERRUPT_IO() wrapper as for other5385* blocking, interruptible calls in this file.5386*/5387int n,ioctl_return;53885389INTERRUPTIBLE(::ioctl(fd, FIONREAD, &n),ioctl_return,os::Solaris::clear_interrupted);5390if (ioctl_return>= 0) {5391*bytes = n;5392return 1;5393}5394}5395}5396if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {5397return 0;5398} else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {5399return 0;5400} else if (::lseek64(fd, cur, SEEK_SET) == -1) {5401return 0;5402}5403*bytes = end - cur;5404return 1;5405}54065407// Map a block of memory.5408char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,5409char *addr, size_t bytes, bool read_only,5410bool allow_exec) {5411int prot;5412int flags;54135414if (read_only) {5415prot = PROT_READ;5416flags = MAP_SHARED;5417} else {5418prot = PROT_READ | PROT_WRITE;5419flags = MAP_PRIVATE;5420}54215422if (allow_exec) {5423prot |= PROT_EXEC;5424}54255426if (addr != NULL) {5427flags |= MAP_FIXED;5428}54295430char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,5431fd, file_offset);5432if (mapped_address == MAP_FAILED) {5433return NULL;5434}5435return mapped_address;5436}543754385439// Remap a block of memory.5440char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,5441char *addr, size_t bytes, bool read_only,5442bool allow_exec) {5443// same as map_memory() on this OS5444return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,5445allow_exec);5446}544754485449// Unmap a block of memory.5450bool os::pd_unmap_memory(char* addr, size_t bytes) {5451return munmap(addr, bytes) == 0;5452}54535454void os::pause() {5455char filename[MAX_PATH];5456if (PauseAtStartupFile && PauseAtStartupFile[0]) {5457jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);5458} else {5459jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());5460}54615462int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);5463if (fd != -1) {5464struct stat buf;5465::close(fd);5466while (::stat(filename, &buf) == 0) {5467(void)::poll(NULL, 0, 100);5468}5469} else {5470jio_fprintf(stderr,5471"Could not open pause file '%s', continuing immediately.\n", filename);5472}5473}54745475#ifndef PRODUCT5476#ifdef INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS5477// Turn this on if you need to trace synch operations.5478// Set RECORD_SYNCH_LIMIT to a large-enough value,5479// and call record_synch_enable and record_synch_disable5480// around the computation of interest.54815482void record_synch(char* name, bool returning); // defined below54835484class RecordSynch {5485char* _name;5486public:5487RecordSynch(char* name) :_name(name)5488{ record_synch(_name, false); }5489~RecordSynch() { record_synch(_name, true); }5490};54915492#define CHECK_SYNCH_OP(ret, name, params, args, inner) \5493extern "C" ret name params { \5494typedef ret name##_t params; \5495static name##_t* implem = NULL; \5496static int callcount = 0; \5497if (implem == NULL) { \5498implem = (name##_t*) dlsym(RTLD_NEXT, #name); \5499if (implem == NULL) fatal(dlerror()); \5500} \5501++callcount; \5502RecordSynch _rs(#name); \5503inner; \5504return implem args; \5505}5506// in dbx, examine callcounts this way:5507// for n in $(eval whereis callcount | awk '{print $2}'); do print $n; done55085509#define CHECK_POINTER_OK(p) \5510(!Universe::is_fully_initialized() || !Universe::is_reserved_heap((oop)(p)))5511#define CHECK_MU \5512if (!CHECK_POINTER_OK(mu)) fatal("Mutex must be in C heap only.");5513#define CHECK_CV \5514if (!CHECK_POINTER_OK(cv)) fatal("Condvar must be in C heap only.");5515#define CHECK_P(p) \5516if (!CHECK_POINTER_OK(p)) fatal(false, "Pointer must be in C heap only.");55175518#define CHECK_MUTEX(mutex_op) \5519CHECK_SYNCH_OP(int, mutex_op, (mutex_t *mu), (mu), CHECK_MU);55205521CHECK_MUTEX( mutex_lock)5522CHECK_MUTEX( _mutex_lock)5523CHECK_MUTEX( mutex_unlock)5524CHECK_MUTEX(_mutex_unlock)5525CHECK_MUTEX( mutex_trylock)5526CHECK_MUTEX(_mutex_trylock)55275528#define CHECK_COND(cond_op) \5529CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu), (cv, mu), CHECK_MU;CHECK_CV);55305531CHECK_COND( cond_wait);5532CHECK_COND(_cond_wait);5533CHECK_COND(_cond_wait_cancel);55345535#define CHECK_COND2(cond_op) \5536CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu, timestruc_t* ts), (cv, mu, ts), CHECK_MU;CHECK_CV);55375538CHECK_COND2( cond_timedwait);5539CHECK_COND2(_cond_timedwait);5540CHECK_COND2(_cond_timedwait_cancel);55415542// do the _lwp_* versions too5543#define mutex_t lwp_mutex_t5544#define cond_t lwp_cond_t5545CHECK_MUTEX( _lwp_mutex_lock)5546CHECK_MUTEX( _lwp_mutex_unlock)5547CHECK_MUTEX( _lwp_mutex_trylock)5548CHECK_MUTEX( __lwp_mutex_lock)5549CHECK_MUTEX( __lwp_mutex_unlock)5550CHECK_MUTEX( __lwp_mutex_trylock)5551CHECK_MUTEX(___lwp_mutex_lock)5552CHECK_MUTEX(___lwp_mutex_unlock)55535554CHECK_COND( _lwp_cond_wait);5555CHECK_COND( __lwp_cond_wait);5556CHECK_COND(___lwp_cond_wait);55575558CHECK_COND2( _lwp_cond_timedwait);5559CHECK_COND2( __lwp_cond_timedwait);5560#undef mutex_t5561#undef cond_t55625563CHECK_SYNCH_OP(int, _lwp_suspend2, (int lwp, int *n), (lwp, n), 0);5564CHECK_SYNCH_OP(int,__lwp_suspend2, (int lwp, int *n), (lwp, n), 0);5565CHECK_SYNCH_OP(int, _lwp_kill, (int lwp, int n), (lwp, n), 0);5566CHECK_SYNCH_OP(int,__lwp_kill, (int lwp, int n), (lwp, n), 0);5567CHECK_SYNCH_OP(int, _lwp_sema_wait, (lwp_sema_t* p), (p), CHECK_P(p));5568CHECK_SYNCH_OP(int,__lwp_sema_wait, (lwp_sema_t* p), (p), CHECK_P(p));5569CHECK_SYNCH_OP(int, _lwp_cond_broadcast, (lwp_cond_t* cv), (cv), CHECK_CV);5570CHECK_SYNCH_OP(int,__lwp_cond_broadcast, (lwp_cond_t* cv), (cv), CHECK_CV);557155725573// recording machinery:55745575enum { RECORD_SYNCH_LIMIT = 200 };5576char* record_synch_name[RECORD_SYNCH_LIMIT];5577void* record_synch_arg0ptr[RECORD_SYNCH_LIMIT];5578bool record_synch_returning[RECORD_SYNCH_LIMIT];5579thread_t record_synch_thread[RECORD_SYNCH_LIMIT];5580int record_synch_count = 0;5581bool record_synch_enabled = false;55825583// in dbx, examine recorded data this way:5584// for n in name arg0ptr returning thread; do print record_synch_$n[0..record_synch_count-1]; done55855586void record_synch(char* name, bool returning) {5587if (record_synch_enabled) {5588if (record_synch_count < RECORD_SYNCH_LIMIT) {5589record_synch_name[record_synch_count] = name;5590record_synch_returning[record_synch_count] = returning;5591record_synch_thread[record_synch_count] = thr_self();5592record_synch_arg0ptr[record_synch_count] = &name;5593record_synch_count++;5594}5595// put more checking code here:5596// ...5597}5598}55995600void record_synch_enable() {5601// start collecting trace data, if not already doing so5602if (!record_synch_enabled) record_synch_count = 0;5603record_synch_enabled = true;5604}56055606void record_synch_disable() {5607// stop collecting trace data5608record_synch_enabled = false;5609}56105611#endif // INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS5612#endif // PRODUCT56135614const intptr_t thr_time_off = (intptr_t)(&((prusage_t *)(NULL))->pr_utime);5615const intptr_t thr_time_size = (intptr_t)(&((prusage_t *)(NULL))->pr_ttime) -5616(intptr_t)(&((prusage_t *)(NULL))->pr_utime);561756185619// JVMTI & JVM monitoring and management support5620// The thread_cpu_time() and current_thread_cpu_time() are only5621// supported if is_thread_cpu_time_supported() returns true.5622// They are not supported on Solaris T1.56235624// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)5625// are used by JVM M&M and JVMTI to get user+sys or user CPU time5626// of a thread.5627//5628// current_thread_cpu_time() and thread_cpu_time(Thread *)5629// returns the fast estimate available on the platform.56305631// hrtime_t gethrvtime() return value includes5632// user time but does not include system time5633jlong os::current_thread_cpu_time() {5634return (jlong) gethrvtime();5635}56365637jlong os::thread_cpu_time(Thread *thread) {5638// return user level CPU time only to be consistent with5639// what current_thread_cpu_time returns.5640// thread_cpu_time_info() must be changed if this changes5641return os::thread_cpu_time(thread, false /* user time only */);5642}56435644jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {5645if (user_sys_cpu_time) {5646return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);5647} else {5648return os::current_thread_cpu_time();5649}5650}56515652jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {5653char proc_name[64];5654int count;5655prusage_t prusage;5656jlong lwp_time;5657int fd;56585659sprintf(proc_name, "/proc/%d/lwp/%d/lwpusage",5660getpid(),5661thread->osthread()->lwp_id());5662fd = ::open(proc_name, O_RDONLY);5663if ( fd == -1 ) return -1;56645665do {5666count = ::pread(fd,5667(void *)&prusage.pr_utime,5668thr_time_size,5669thr_time_off);5670} while (count < 0 && errno == EINTR);5671::close(fd);5672if ( count < 0 ) return -1;56735674if (user_sys_cpu_time) {5675// user + system CPU time5676lwp_time = (((jlong)prusage.pr_stime.tv_sec +5677(jlong)prusage.pr_utime.tv_sec) * (jlong)1000000000) +5678(jlong)prusage.pr_stime.tv_nsec +5679(jlong)prusage.pr_utime.tv_nsec;5680} else {5681// user level CPU time only5682lwp_time = ((jlong)prusage.pr_utime.tv_sec * (jlong)1000000000) +5683(jlong)prusage.pr_utime.tv_nsec;5684}56855686return(lwp_time);5687}56885689void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {5690info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits5691info_ptr->may_skip_backward = false; // elapsed time not wall time5692info_ptr->may_skip_forward = false; // elapsed time not wall time5693info_ptr->kind = JVMTI_TIMER_USER_CPU; // only user time is returned5694}56955696void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {5697info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits5698info_ptr->may_skip_backward = false; // elapsed time not wall time5699info_ptr->may_skip_forward = false; // elapsed time not wall time5700info_ptr->kind = JVMTI_TIMER_USER_CPU; // only user time is returned5701}57025703bool os::is_thread_cpu_time_supported() {5704if ( os::Solaris::T2_libthread() || UseBoundThreads ) {5705return true;5706} else {5707return false;5708}5709}57105711// System loadavg support. Returns -1 if load average cannot be obtained.5712// Return the load average for our processor set if the primitive exists5713// (Solaris 9 and later). Otherwise just return system wide loadavg.5714int os::loadavg(double loadavg[], int nelem) {5715if (pset_getloadavg_ptr != NULL) {5716return (*pset_getloadavg_ptr)(PS_MYID, loadavg, nelem);5717} else {5718return ::getloadavg(loadavg, nelem);5719}5720}57215722//---------------------------------------------------------------------------------57235724bool os::find(address addr, outputStream* st) {5725Dl_info dlinfo;5726memset(&dlinfo, 0, sizeof(dlinfo));5727if (dladdr(addr, &dlinfo) != 0) {5728st->print(PTR_FORMAT ": ", addr);5729if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {5730st->print("%s+%#lx", dlinfo.dli_sname, addr-(intptr_t)dlinfo.dli_saddr);5731} else if (dlinfo.dli_fbase != NULL)5732st->print("<offset %#lx>", addr-(intptr_t)dlinfo.dli_fbase);5733else5734st->print("<absolute address>");5735if (dlinfo.dli_fname != NULL) {5736st->print(" in %s", dlinfo.dli_fname);5737}5738if (dlinfo.dli_fbase != NULL) {5739st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);5740}5741st->cr();57425743if (Verbose) {5744// decode some bytes around the PC5745address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());5746address end = clamp_address_in_page(addr+40, addr, os::vm_page_size());5747address lowest = (address) dlinfo.dli_sname;5748if (!lowest) lowest = (address) dlinfo.dli_fbase;5749if (begin < lowest) begin = lowest;5750Dl_info dlinfo2;5751if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr5752&& end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)5753end = (address) dlinfo2.dli_saddr;5754Disassembler::decode(begin, end, st);5755}5756return true;5757}5758return false;5759}57605761// Following function has been added to support HotSparc's libjvm.so running5762// under Solaris production JDK 1.2.2 / 1.3.0. These came from5763// src/solaris/hpi/native_threads in the EVM codebase.5764//5765// NOTE: This is no longer needed in the 1.3.1 and 1.4 production release5766// libraries and should thus be removed. We will leave it behind for a while5767// until we no longer want to able to run on top of 1.3.0 Solaris production5768// JDK. See 4341971.57695770#define STACK_SLACK 0x80057715772extern "C" {5773intptr_t sysThreadAvailableStackWithSlack() {5774stack_t st;5775intptr_t retval, stack_top;5776retval = thr_stksegment(&st);5777assert(retval == 0, "incorrect return value from thr_stksegment");5778assert((address)&st < (address)st.ss_sp, "Invalid stack base returned");5779assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned");5780stack_top=(intptr_t)st.ss_sp-st.ss_size;5781return ((intptr_t)&stack_top - stack_top - STACK_SLACK);5782}5783}57845785// ObjectMonitor park-unpark infrastructure ...5786//5787// We implement Solaris and Linux PlatformEvents with the5788// obvious condvar-mutex-flag triple.5789// Another alternative that works quite well is pipes:5790// Each PlatformEvent consists of a pipe-pair.5791// The thread associated with the PlatformEvent5792// calls park(), which reads from the input end of the pipe.5793// Unpark() writes into the other end of the pipe.5794// The write-side of the pipe must be set NDELAY.5795// Unfortunately pipes consume a large # of handles.5796// Native solaris lwp_park() and lwp_unpark() work nicely, too.5797// Using pipes for the 1st few threads might be workable, however.5798//5799// park() is permitted to return spuriously.5800// Callers of park() should wrap the call to park() in5801// an appropriate loop. A litmus test for the correct5802// usage of park is the following: if park() were modified5803// to immediately return 0 your code should still work,5804// albeit degenerating to a spin loop.5805//5806// An interesting optimization for park() is to use a trylock()5807// to attempt to acquire the mutex. If the trylock() fails5808// then we know that a concurrent unpark() operation is in-progress.5809// in that case the park() code could simply set _count to 05810// and return immediately. The subsequent park() operation *might*5811// return immediately. That's harmless as the caller of park() is5812// expected to loop. By using trylock() we will have avoided a5813// avoided a context switch caused by contention on the per-thread mutex.5814//5815// TODO-FIXME:5816// 1. Reconcile Doug's JSR166 j.u.c park-unpark with the5817// objectmonitor implementation.5818// 2. Collapse the JSR166 parker event, and the5819// objectmonitor ParkEvent into a single "Event" construct.5820// 3. In park() and unpark() add:5821// assert (Thread::current() == AssociatedWith).5822// 4. add spurious wakeup injection on a -XX:EarlyParkReturn=N switch.5823// 1-out-of-N park() operations will return immediately.5824//5825// _Event transitions in park()5826// -1 => -1 : illegal5827// 1 => 0 : pass - return immediately5828// 0 => -1 : block5829//5830// _Event serves as a restricted-range semaphore.5831//5832// Another possible encoding of _Event would be with5833// explicit "PARKED" == 01b and "SIGNALED" == 10b bits.5834//5835// TODO-FIXME: add DTRACE probes for:5836// 1. Tx parks5837// 2. Ty unparks Tx5838// 3. Tx resumes from park583958405841// value determined through experimentation5842#define ROUNDINGFIX 1158435844// utility to compute the abstime argument to timedwait.5845// TODO-FIXME: switch from compute_abstime() to unpackTime().58465847static timestruc_t* compute_abstime(timestruc_t* abstime, jlong millis) {5848// millis is the relative timeout time5849// abstime will be the absolute timeout time5850if (millis < 0) millis = 0;5851struct timeval now;5852int status = gettimeofday(&now, NULL);5853assert(status == 0, "gettimeofday");5854jlong seconds = millis / 1000;5855jlong max_wait_period;58565857if (UseLWPSynchronization) {5858// forward port of fix for 4275818 (not sleeping long enough)5859// There was a bug in Solaris 6, 7 and pre-patch 5 of 8 where5860// _lwp_cond_timedwait() used a round_down algorithm rather5861// than a round_up. For millis less than our roundfactor5862// it rounded down to 0 which doesn't meet the spec.5863// For millis > roundfactor we may return a bit sooner, but5864// since we can not accurately identify the patch level and5865// this has already been fixed in Solaris 9 and 8 we will5866// leave it alone rather than always rounding down.58675868if (millis > 0 && millis < ROUNDINGFIX) millis = ROUNDINGFIX;5869// It appears that when we go directly through Solaris _lwp_cond_timedwait()5870// the acceptable max time threshold is smaller than for libthread on 2.5.1 and 2.65871max_wait_period = 21000000;5872} else {5873max_wait_period = 50000000;5874}5875millis %= 1000;5876if (seconds > max_wait_period) { // see man cond_timedwait(3T)5877seconds = max_wait_period;5878}5879abstime->tv_sec = now.tv_sec + seconds;5880long usec = now.tv_usec + millis * 1000;5881if (usec >= 1000000) {5882abstime->tv_sec += 1;5883usec -= 1000000;5884}5885abstime->tv_nsec = usec * 1000;5886return abstime;5887}58885889// Test-and-clear _Event, always leaves _Event set to 0, returns immediately.5890// Conceptually TryPark() should be equivalent to park(0).58915892int os::PlatformEvent::TryPark() {5893for (;;) {5894const int v = _Event ;5895guarantee ((v == 0) || (v == 1), "invariant") ;5896if (Atomic::cmpxchg (0, &_Event, v) == v) return v ;5897}5898}58995900void os::PlatformEvent::park() { // AKA: down()5901// Invariant: Only the thread associated with the Event/PlatformEvent5902// may call park().5903int v ;5904for (;;) {5905v = _Event ;5906if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;5907}5908guarantee (v >= 0, "invariant") ;5909if (v == 0) {5910// Do this the hard way by blocking ...5911// See http://monaco.sfbay/detail.jsf?cr=5094058.5912// TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking.5913// Only for SPARC >= V8PlusA5914#if defined(__sparc) && defined(COMPILER2)5915if (ClearFPUAtPark) { _mark_fpu_nosave() ; }5916#endif5917int status = os::Solaris::mutex_lock(_mutex);5918assert_status(status == 0, status, "mutex_lock");5919guarantee (_nParked == 0, "invariant") ;5920++ _nParked ;5921while (_Event < 0) {5922// for some reason, under 2.7 lwp_cond_wait() may return ETIME ...5923// Treat this the same as if the wait was interrupted5924// With usr/lib/lwp going to kernel, always handle ETIME5925status = os::Solaris::cond_wait(_cond, _mutex);5926if (status == ETIME) status = EINTR ;5927assert_status(status == 0 || status == EINTR, status, "cond_wait");5928}5929-- _nParked ;5930_Event = 0 ;5931status = os::Solaris::mutex_unlock(_mutex);5932assert_status(status == 0, status, "mutex_unlock");5933// Paranoia to ensure our locked and lock-free paths interact5934// correctly with each other.5935OrderAccess::fence();5936}5937}59385939int os::PlatformEvent::park(jlong millis) {5940guarantee (_nParked == 0, "invariant") ;5941int v ;5942for (;;) {5943v = _Event ;5944if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ;5945}5946guarantee (v >= 0, "invariant") ;5947if (v != 0) return OS_OK ;59485949int ret = OS_TIMEOUT;5950timestruc_t abst;5951compute_abstime (&abst, millis);59525953// See http://monaco.sfbay/detail.jsf?cr=5094058.5954// For Solaris SPARC set fprs.FEF=0 prior to parking.5955// Only for SPARC >= V8PlusA5956#if defined(__sparc) && defined(COMPILER2)5957if (ClearFPUAtPark) { _mark_fpu_nosave() ; }5958#endif5959int status = os::Solaris::mutex_lock(_mutex);5960assert_status(status == 0, status, "mutex_lock");5961guarantee (_nParked == 0, "invariant") ;5962++ _nParked ;5963while (_Event < 0) {5964int status = os::Solaris::cond_timedwait(_cond, _mutex, &abst);5965assert_status(status == 0 || status == EINTR ||5966status == ETIME || status == ETIMEDOUT,5967status, "cond_timedwait");5968if (!FilterSpuriousWakeups) break ; // previous semantics5969if (status == ETIME || status == ETIMEDOUT) break ;5970// We consume and ignore EINTR and spurious wakeups.5971}5972-- _nParked ;5973if (_Event >= 0) ret = OS_OK ;5974_Event = 0 ;5975status = os::Solaris::mutex_unlock(_mutex);5976assert_status(status == 0, status, "mutex_unlock");5977// Paranoia to ensure our locked and lock-free paths interact5978// correctly with each other.5979OrderAccess::fence();5980return ret;5981}59825983void os::PlatformEvent::unpark() {5984// Transitions for _Event:5985// 0 :=> 15986// 1 :=> 15987// -1 :=> either 0 or 1; must signal target thread5988// That is, we can safely transition _Event from -1 to either5989// 0 or 1. Forcing 1 is slightly more efficient for back-to-back5990// unpark() calls.5991// See also: "Semaphores in Plan 9" by Mullender & Cox5992//5993// Note: Forcing a transition from "-1" to "1" on an unpark() means5994// that it will take two back-to-back park() calls for the owning5995// thread to block. This has the benefit of forcing a spurious return5996// from the first park() call after an unpark() call which will help5997// shake out uses of park() and unpark() without condition variables.59985999if (Atomic::xchg(1, &_Event) >= 0) return;60006001// If the thread associated with the event was parked, wake it.6002// Wait for the thread assoc with the PlatformEvent to vacate.6003int status = os::Solaris::mutex_lock(_mutex);6004assert_status(status == 0, status, "mutex_lock");6005int AnyWaiters = _nParked;6006status = os::Solaris::mutex_unlock(_mutex);6007assert_status(status == 0, status, "mutex_unlock");6008guarantee(AnyWaiters == 0 || AnyWaiters == 1, "invariant");6009if (AnyWaiters != 0) {6010// We intentional signal *after* dropping the lock6011// to avoid a common class of futile wakeups.6012status = os::Solaris::cond_signal(_cond);6013assert_status(status == 0, status, "cond_signal");6014}6015}60166017// JSR1666018// -------------------------------------------------------60196020/*6021* The solaris and linux implementations of park/unpark are fairly6022* conservative for now, but can be improved. They currently use a6023* mutex/condvar pair, plus _counter.6024* Park decrements _counter if > 0, else does a condvar wait. Unpark6025* sets count to 1 and signals condvar. Only one thread ever waits6026* on the condvar. Contention seen when trying to park implies that someone6027* is unparking you, so don't wait. And spurious returns are fine, so there6028* is no need to track notifications.6029*/60306031#define MAX_SECS 1000000006032/*6033* This code is common to linux and solaris and will be moved to a6034* common place in dolphin.6035*6036* The passed in time value is either a relative time in nanoseconds6037* or an absolute time in milliseconds. Either way it has to be unpacked6038* into suitable seconds and nanoseconds components and stored in the6039* given timespec structure.6040* Given time is a 64-bit value and the time_t used in the timespec is only6041* a signed-32-bit value (except on 64-bit Linux) we have to watch for6042* overflow if times way in the future are given. Further on Solaris versions6043* prior to 10 there is a restriction (see cond_timedwait) that the specified6044* number of seconds, in abstime, is less than current_time + 100,000,000.6045* As it will be 28 years before "now + 100000000" will overflow we can6046* ignore overflow and just impose a hard-limit on seconds using the value6047* of "now + 100,000,000". This places a limit on the timeout of about 3.176048* years from "now".6049*/6050static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {6051assert (time > 0, "convertTime");60526053struct timeval now;6054int status = gettimeofday(&now, NULL);6055assert(status == 0, "gettimeofday");60566057time_t max_secs = now.tv_sec + MAX_SECS;60586059if (isAbsolute) {6060jlong secs = time / 1000;6061if (secs > max_secs) {6062absTime->tv_sec = max_secs;6063}6064else {6065absTime->tv_sec = secs;6066}6067absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;6068}6069else {6070jlong secs = time / NANOSECS_PER_SEC;6071if (secs >= MAX_SECS) {6072absTime->tv_sec = max_secs;6073absTime->tv_nsec = 0;6074}6075else {6076absTime->tv_sec = now.tv_sec + secs;6077absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;6078if (absTime->tv_nsec >= NANOSECS_PER_SEC) {6079absTime->tv_nsec -= NANOSECS_PER_SEC;6080++absTime->tv_sec; // note: this must be <= max_secs6081}6082}6083}6084assert(absTime->tv_sec >= 0, "tv_sec < 0");6085assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");6086assert(absTime->tv_nsec >= 0, "tv_nsec < 0");6087assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");6088}60896090void Parker::park(bool isAbsolute, jlong time) {6091// Ideally we'd do something useful while spinning, such6092// as calling unpackTime().60936094// Optional fast-path check:6095// Return immediately if a permit is available.6096// We depend on Atomic::xchg() having full barrier semantics6097// since we are doing a lock-free update to _counter.6098if (Atomic::xchg(0, &_counter) > 0) return;60996100// Optional fast-exit: Check interrupt before trying to wait6101Thread* thread = Thread::current();6102assert(thread->is_Java_thread(), "Must be JavaThread");6103JavaThread *jt = (JavaThread *)thread;6104if (Thread::is_interrupted(thread, false)) {6105return;6106}61076108// First, demultiplex/decode time arguments6109timespec absTime;6110if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all6111return;6112}6113if (time > 0) {6114// Warning: this code might be exposed to the old Solaris time6115// round-down bugs. Grep "roundingFix" for details.6116unpackTime(&absTime, isAbsolute, time);6117}61186119// Enter safepoint region6120// Beware of deadlocks such as 6317397.6121// The per-thread Parker:: _mutex is a classic leaf-lock.6122// In particular a thread must never block on the Threads_lock while6123// holding the Parker:: mutex. If safepoints are pending both the6124// the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.6125ThreadBlockInVM tbivm(jt);61266127// Don't wait if cannot get lock since interference arises from6128// unblocking. Also. check interrupt before trying wait6129if (Thread::is_interrupted(thread, false) ||6130os::Solaris::mutex_trylock(_mutex) != 0) {6131return;6132}61336134int status ;61356136if (_counter > 0) { // no wait needed6137_counter = 0;6138status = os::Solaris::mutex_unlock(_mutex);6139assert (status == 0, "invariant") ;6140// Paranoia to ensure our locked and lock-free paths interact6141// correctly with each other and Java-level accesses.6142OrderAccess::fence();6143return;6144}61456146#ifdef ASSERT6147// Don't catch signals while blocked; let the running threads have the signals.6148// (This allows a debugger to break into the running thread.)6149sigset_t oldsigs;6150sigset_t* allowdebug_blocked = os::Solaris::allowdebug_blocked_signals();6151thr_sigsetmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);6152#endif61536154OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);6155jt->set_suspend_equivalent();6156// cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()61576158// Do this the hard way by blocking ...6159// See http://monaco.sfbay/detail.jsf?cr=5094058.6160// TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking.6161// Only for SPARC >= V8PlusA6162#if defined(__sparc) && defined(COMPILER2)6163if (ClearFPUAtPark) { _mark_fpu_nosave() ; }6164#endif61656166if (time == 0) {6167status = os::Solaris::cond_wait (_cond, _mutex) ;6168} else {6169status = os::Solaris::cond_timedwait (_cond, _mutex, &absTime);6170}6171// Note that an untimed cond_wait() can sometimes return ETIME on older6172// versions of the Solaris.6173assert_status(status == 0 || status == EINTR ||6174status == ETIME || status == ETIMEDOUT,6175status, "cond_timedwait");61766177#ifdef ASSERT6178thr_sigsetmask(SIG_SETMASK, &oldsigs, NULL);6179#endif6180_counter = 0 ;6181status = os::Solaris::mutex_unlock(_mutex);6182assert_status(status == 0, status, "mutex_unlock") ;6183// Paranoia to ensure our locked and lock-free paths interact6184// correctly with each other and Java-level accesses.6185OrderAccess::fence();61866187// If externally suspended while waiting, re-suspend6188if (jt->handle_special_suspend_equivalent_condition()) {6189jt->java_suspend_self();6190}6191}61926193void Parker::unpark() {6194int s, status ;6195status = os::Solaris::mutex_lock (_mutex) ;6196assert (status == 0, "invariant") ;6197s = _counter;6198_counter = 1;6199status = os::Solaris::mutex_unlock (_mutex) ;6200assert (status == 0, "invariant") ;62016202if (s < 1) {6203status = os::Solaris::cond_signal (_cond) ;6204assert (status == 0, "invariant") ;6205}6206}62076208extern char** environ;62096210// Run the specified command in a separate process. Return its exit value,6211// or -1 on failure (e.g. can't fork a new process).6212// Unlike system(), this function can be called from signal handler. It6213// doesn't block SIGINT et al.6214int os::fork_and_exec(char* cmd, bool use_vfork_if_available) {6215char * argv[4];6216argv[0] = (char *)"sh";6217argv[1] = (char *)"-c";6218argv[2] = cmd;6219argv[3] = NULL;62206221// fork is async-safe, fork1 is not so can't use in signal handler6222pid_t pid;6223Thread* t = ThreadLocalStorage::get_thread_slow();6224if (t != NULL && t->is_inside_signal_handler()) {6225pid = fork();6226} else {6227pid = fork1();6228}62296230if (pid < 0) {6231// fork failed6232warning("fork failed: %s", strerror(errno));6233return -1;62346235} else if (pid == 0) {6236// child process62376238// try to be consistent with system(), which uses "/usr/bin/sh" on Solaris6239execve("/usr/bin/sh", argv, environ);62406241// execve failed6242_exit(-1);62436244} else {6245// copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't6246// care about the actual exit code, for now.62476248int status;62496250// Wait for the child process to exit. This returns immediately if6251// the child has already exited. */6252while (waitpid(pid, &status, 0) < 0) {6253switch (errno) {6254case ECHILD: return 0;6255case EINTR: break;6256default: return -1;6257}6258}62596260if (WIFEXITED(status)) {6261// The child exited normally; get its exit code.6262return WEXITSTATUS(status);6263} else if (WIFSIGNALED(status)) {6264// The child exited because of a signal6265// The best value to return is 0x80 + signal number,6266// because that is what all Unix shells do, and because6267// it allows callers to distinguish between process exit and6268// process death by signal.6269return 0x80 + WTERMSIG(status);6270} else {6271// Unknown exit code; pass it through6272return status;6273}6274}6275}62766277// is_headless_jre()6278//6279// Test for the existence of xawt/libmawt.so or libawt_xawt.so6280// in order to report if we are running in a headless jre6281//6282// Since JDK8 xawt/libmawt.so was moved into the same directory6283// as libawt.so, and renamed libawt_xawt.so6284//6285bool os::is_headless_jre() {6286struct stat statbuf;6287char buf[MAXPATHLEN];6288char libmawtpath[MAXPATHLEN];6289const char *xawtstr = "/xawt/libmawt.so";6290const char *new_xawtstr = "/libawt_xawt.so";6291char *p;62926293// Get path to libjvm.so6294os::jvm_path(buf, sizeof(buf));62956296// Get rid of libjvm.so6297p = strrchr(buf, '/');6298if (p == NULL) return false;6299else *p = '\0';63006301// Get rid of client or server6302p = strrchr(buf, '/');6303if (p == NULL) return false;6304else *p = '\0';63056306// check xawt/libmawt.so6307strcpy(libmawtpath, buf);6308strcat(libmawtpath, xawtstr);6309if (::stat(libmawtpath, &statbuf) == 0) return false;63106311// check libawt_xawt.so6312strcpy(libmawtpath, buf);6313strcat(libmawtpath, new_xawtstr);6314if (::stat(libmawtpath, &statbuf) == 0) return false;63156316return true;6317}63186319size_t os::write(int fd, const void *buf, unsigned int nBytes) {6320INTERRUPTIBLE_RETURN_INT(::write(fd, buf, nBytes), os::Solaris::clear_interrupted);6321}63226323int os::close(int fd) {6324return ::close(fd);6325}63266327int os::socket_close(int fd) {6328return ::close(fd);6329}63306331int os::recv(int fd, char* buf, size_t nBytes, uint flags) {6332INTERRUPTIBLE_RETURN_INT((int)::recv(fd, buf, nBytes, flags), os::Solaris::clear_interrupted);6333}63346335int os::send(int fd, char* buf, size_t nBytes, uint flags) {6336INTERRUPTIBLE_RETURN_INT((int)::send(fd, buf, nBytes, flags), os::Solaris::clear_interrupted);6337}63386339int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) {6340RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags));6341}63426343// As both poll and select can be interrupted by signals, we have to be6344// prepared to restart the system call after updating the timeout, unless6345// a poll() is done with timeout == -1, in which case we repeat with this6346// "wait forever" value.63476348int os::timeout(int fd, long timeout) {6349int res;6350struct timeval t;6351julong prevtime, newtime;6352static const char* aNull = 0;6353struct pollfd pfd;6354pfd.fd = fd;6355pfd.events = POLLIN;63566357gettimeofday(&t, &aNull);6358prevtime = ((julong)t.tv_sec * 1000) + t.tv_usec / 1000;63596360for(;;) {6361INTERRUPTIBLE_NORESTART(::poll(&pfd, 1, timeout), res, os::Solaris::clear_interrupted);6362if(res == OS_ERR && errno == EINTR) {6363if(timeout != -1) {6364gettimeofday(&t, &aNull);6365newtime = ((julong)t.tv_sec * 1000) + t.tv_usec /1000;6366timeout -= newtime - prevtime;6367if(timeout <= 0)6368return OS_OK;6369prevtime = newtime;6370}6371} else return res;6372}6373}63746375int os::connect(int fd, struct sockaddr *him, socklen_t len) {6376int _result;6377INTERRUPTIBLE_NORESTART(::connect(fd, him, len), _result,\6378os::Solaris::clear_interrupted);63796380// Depending on when thread interruption is reset, _result could be6381// one of two values when errno == EINTR63826383if (((_result == OS_INTRPT) || (_result == OS_ERR))6384&& (errno == EINTR)) {6385/* restarting a connect() changes its errno semantics */6386INTERRUPTIBLE(::connect(fd, him, len), _result,\6387os::Solaris::clear_interrupted);6388/* undo these changes */6389if (_result == OS_ERR) {6390if (errno == EALREADY) {6391errno = EINPROGRESS; /* fall through */6392} else if (errno == EISCONN) {6393errno = 0;6394return OS_OK;6395}6396}6397}6398return _result;6399}64006401int os::accept(int fd, struct sockaddr* him, socklen_t* len) {6402if (fd < 0) {6403return OS_ERR;6404}6405INTERRUPTIBLE_RETURN_INT((int)::accept(fd, him, len),\6406os::Solaris::clear_interrupted);6407}64086409int os::recvfrom(int fd, char* buf, size_t nBytes, uint flags,6410sockaddr* from, socklen_t* fromlen) {6411INTERRUPTIBLE_RETURN_INT((int)::recvfrom(fd, buf, nBytes, flags, from, fromlen),\6412os::Solaris::clear_interrupted);6413}64146415int os::sendto(int fd, char* buf, size_t len, uint flags,6416struct sockaddr* to, socklen_t tolen) {6417INTERRUPTIBLE_RETURN_INT((int)::sendto(fd, buf, len, flags, to, tolen),\6418os::Solaris::clear_interrupted);6419}64206421int os::socket_available(int fd, jint *pbytes) {6422if (fd < 0) {6423return OS_OK;6424}6425int ret;6426RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);6427// note: ioctl can return 0 when successful, JVM_SocketAvailable6428// is expected to return 0 on failure and 1 on success to the jdk.6429return (ret == OS_ERR) ? 0 : 1;6430}64316432int os::bind(int fd, struct sockaddr* him, socklen_t len) {6433INTERRUPTIBLE_RETURN_INT_NORESTART(::bind(fd, him, len),\6434os::Solaris::clear_interrupted);6435}64366437// Get the default path to the core file6438// Returns the length of the string6439int os::get_core_path(char* buffer, size_t bufferSize) {6440const char* p = get_current_directory(buffer, bufferSize);64416442if (p == NULL) {6443assert(p != NULL, "failed to get current directory");6444return 0;6445}64466447return strlen(buffer);6448}64496450#ifndef PRODUCT6451void TestReserveMemorySpecial_test() {6452// No tests available for this platform6453}6454#endif645564566457