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