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