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