os_solaris.cpp revision 6692:4f9fa4b62c18
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// Note that yield semantics are defined by the scheduling class to which
3177// the thread currently belongs.  Typically, yield will _not yield to
3178// other equal or higher priority threads that reside on the dispatch queues
3179// of other CPUs.
3180
3181void os::naked_yield() {
3182  thr_yield();
3183}
3184
3185// Interface for setting lwp priorities.  If we are using T2 libthread,
3186// which forces the use of BoundThreads or we manually set UseBoundThreads,
3187// all of our threads will be assigned to real lwp's.  Using the thr_setprio
3188// function is meaningless in this mode so we must adjust the real lwp's priority
3189// The routines below implement the getting and setting of lwp priorities.
3190//
3191// Note: T2 is now the only supported libthread. UseBoundThreads flag is
3192//       being deprecated and all threads are now BoundThreads
3193//
3194// Note: There are three priority scales used on Solaris.  Java priotities
3195//       which range from 1 to 10, libthread "thr_setprio" scale which range
3196//       from 0 to 127, and the current scheduling class of the process we
3197//       are running in.  This is typically from -60 to +60.
3198//       The setting of the lwp priorities in done after a call to thr_setprio
3199//       so Java priorities are mapped to libthread priorities and we map from
3200//       the latter to lwp priorities.  We don't keep priorities stored in
3201//       Java priorities since some of our worker threads want to set priorities
3202//       higher than all Java threads.
3203//
3204// For related information:
3205// (1)  man -s 2 priocntl
3206// (2)  man -s 4 priocntl
3207// (3)  man dispadmin
3208// =    librt.so
3209// =    libthread/common/rtsched.c - thrp_setlwpprio().
3210// =    ps -cL <pid> ... to validate priority.
3211// =    sched_get_priority_min and _max
3212//              pthread_create
3213//              sched_setparam
3214//              pthread_setschedparam
3215//
3216// Assumptions:
3217// +    We assume that all threads in the process belong to the same
3218//              scheduling class.   IE. an homogenous process.
3219// +    Must be root or in IA group to change change "interactive" attribute.
3220//              Priocntl() will fail silently.  The only indication of failure is when
3221//              we read-back the value and notice that it hasn't changed.
3222// +    Interactive threads enter the runq at the head, non-interactive at the tail.
3223// +    For RT, change timeslice as well.  Invariant:
3224//              constant "priority integral"
3225//              Konst == TimeSlice * (60-Priority)
3226//              Given a priority, compute appropriate timeslice.
3227// +    Higher numerical values have higher priority.
3228
3229// sched class attributes
3230typedef struct {
3231        int   schedPolicy;              // classID
3232        int   maxPrio;
3233        int   minPrio;
3234} SchedInfo;
3235
3236
3237static SchedInfo tsLimits, iaLimits, rtLimits, fxLimits;
3238
3239#ifdef ASSERT
3240static int  ReadBackValidate = 1;
3241#endif
3242static int  myClass     = 0;
3243static int  myMin       = 0;
3244static int  myMax       = 0;
3245static int  myCur       = 0;
3246static bool priocntl_enable = false;
3247
3248static const int criticalPrio = 60; // FX/60 is critical thread class/priority on T4
3249static int java_MaxPriority_to_os_priority = 0; // Saved mapping
3250
3251
3252// lwp_priocntl_init
3253//
3254// Try to determine the priority scale for our process.
3255//
3256// Return errno or 0 if OK.
3257//
3258static int lwp_priocntl_init() {
3259  int rslt;
3260  pcinfo_t ClassInfo;
3261  pcparms_t ParmInfo;
3262  int i;
3263
3264  if (!UseThreadPriorities) return 0;
3265
3266  // If ThreadPriorityPolicy is 1, switch tables
3267  if (ThreadPriorityPolicy == 1) {
3268    for (i = 0; i < CriticalPriority+1; i++)
3269      os::java_to_os_priority[i] = prio_policy1[i];
3270  }
3271  if (UseCriticalJavaThreadPriority) {
3272    // MaxPriority always maps to the FX scheduling class and criticalPrio.
3273    // See set_native_priority() and set_lwp_class_and_priority().
3274    // Save original MaxPriority mapping in case attempt to
3275    // use critical priority fails.
3276    java_MaxPriority_to_os_priority = os::java_to_os_priority[MaxPriority];
3277    // Set negative to distinguish from other priorities
3278    os::java_to_os_priority[MaxPriority] = -criticalPrio;
3279  }
3280
3281  // Get IDs for a set of well-known scheduling classes.
3282  // TODO-FIXME: GETCLINFO returns the current # of classes in the
3283  // the system.  We should have a loop that iterates over the
3284  // classID values, which are known to be "small" integers.
3285
3286  strcpy(ClassInfo.pc_clname, "TS");
3287  ClassInfo.pc_cid = -1;
3288  rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3289  if (rslt < 0) return errno;
3290  assert(ClassInfo.pc_cid != -1, "cid for TS class is -1");
3291  tsLimits.schedPolicy = ClassInfo.pc_cid;
3292  tsLimits.maxPrio = ((tsinfo_t*)ClassInfo.pc_clinfo)->ts_maxupri;
3293  tsLimits.minPrio = -tsLimits.maxPrio;
3294
3295  strcpy(ClassInfo.pc_clname, "IA");
3296  ClassInfo.pc_cid = -1;
3297  rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3298  if (rslt < 0) return errno;
3299  assert(ClassInfo.pc_cid != -1, "cid for IA class is -1");
3300  iaLimits.schedPolicy = ClassInfo.pc_cid;
3301  iaLimits.maxPrio = ((iainfo_t*)ClassInfo.pc_clinfo)->ia_maxupri;
3302  iaLimits.minPrio = -iaLimits.maxPrio;
3303
3304  strcpy(ClassInfo.pc_clname, "RT");
3305  ClassInfo.pc_cid = -1;
3306  rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3307  if (rslt < 0) return errno;
3308  assert(ClassInfo.pc_cid != -1, "cid for RT class is -1");
3309  rtLimits.schedPolicy = ClassInfo.pc_cid;
3310  rtLimits.maxPrio = ((rtinfo_t*)ClassInfo.pc_clinfo)->rt_maxpri;
3311  rtLimits.minPrio = 0;
3312
3313  strcpy(ClassInfo.pc_clname, "FX");
3314  ClassInfo.pc_cid = -1;
3315  rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo);
3316  if (rslt < 0) return errno;
3317  assert(ClassInfo.pc_cid != -1, "cid for FX class is -1");
3318  fxLimits.schedPolicy = ClassInfo.pc_cid;
3319  fxLimits.maxPrio = ((fxinfo_t*)ClassInfo.pc_clinfo)->fx_maxupri;
3320  fxLimits.minPrio = 0;
3321
3322  // Query our "current" scheduling class.
3323  // This will normally be IA, TS or, rarely, FX or RT.
3324  memset(&ParmInfo, 0, sizeof(ParmInfo));
3325  ParmInfo.pc_cid = PC_CLNULL;
3326  rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);
3327  if (rslt < 0) return errno;
3328  myClass = ParmInfo.pc_cid;
3329
3330  // We now know our scheduling classId, get specific information
3331  // about the class.
3332  ClassInfo.pc_cid = myClass;
3333  ClassInfo.pc_clname[0] = 0;
3334  rslt = priocntl((idtype)0, 0, PC_GETCLINFO, (caddr_t)&ClassInfo);
3335  if (rslt < 0) return errno;
3336
3337  if (ThreadPriorityVerbose) {
3338    tty->print_cr("lwp_priocntl_init: Class=%d(%s)...", myClass, ClassInfo.pc_clname);
3339  }
3340
3341  memset(&ParmInfo, 0, sizeof(pcparms_t));
3342  ParmInfo.pc_cid = PC_CLNULL;
3343  rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo);
3344  if (rslt < 0) return errno;
3345
3346  if (ParmInfo.pc_cid == rtLimits.schedPolicy) {
3347    myMin = rtLimits.minPrio;
3348    myMax = rtLimits.maxPrio;
3349  } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {
3350    iaparms_t *iaInfo  = (iaparms_t*)ParmInfo.pc_clparms;
3351    myMin = iaLimits.minPrio;
3352    myMax = iaLimits.maxPrio;
3353    myMax = MIN2(myMax, (int)iaInfo->ia_uprilim);       // clamp - restrict
3354  } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {
3355    tsparms_t *tsInfo  = (tsparms_t*)ParmInfo.pc_clparms;
3356    myMin = tsLimits.minPrio;
3357    myMax = tsLimits.maxPrio;
3358    myMax = MIN2(myMax, (int)tsInfo->ts_uprilim);       // clamp - restrict
3359  } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {
3360    fxparms_t *fxInfo = (fxparms_t*)ParmInfo.pc_clparms;
3361    myMin = fxLimits.minPrio;
3362    myMax = fxLimits.maxPrio;
3363    myMax = MIN2(myMax, (int)fxInfo->fx_uprilim);       // clamp - restrict
3364  } else {
3365    // No clue - punt
3366    if (ThreadPriorityVerbose)
3367      tty->print_cr("Unknown scheduling class: %s ... \n", ClassInfo.pc_clname);
3368    return EINVAL;      // no clue, punt
3369  }
3370
3371  if (ThreadPriorityVerbose) {
3372    tty->print_cr("Thread priority Range: [%d..%d]\n", myMin, myMax);
3373  }
3374
3375  priocntl_enable = true;  // Enable changing priorities
3376  return 0;
3377}
3378
3379#define IAPRI(x)        ((iaparms_t *)((x).pc_clparms))
3380#define RTPRI(x)        ((rtparms_t *)((x).pc_clparms))
3381#define TSPRI(x)        ((tsparms_t *)((x).pc_clparms))
3382#define FXPRI(x)        ((fxparms_t *)((x).pc_clparms))
3383
3384
3385// scale_to_lwp_priority
3386//
3387// Convert from the libthread "thr_setprio" scale to our current
3388// lwp scheduling class scale.
3389//
3390static
3391int     scale_to_lwp_priority (int rMin, int rMax, int x)
3392{
3393  int v;
3394
3395  if (x == 127) return rMax;            // avoid round-down
3396    v = (((x*(rMax-rMin)))/128)+rMin;
3397  return v;
3398}
3399
3400
3401// set_lwp_class_and_priority
3402int set_lwp_class_and_priority(int ThreadID, int lwpid,
3403                               int newPrio, int new_class, bool scale) {
3404  int rslt;
3405  int Actual, Expected, prv;
3406  pcparms_t ParmInfo;                   // for GET-SET
3407#ifdef ASSERT
3408  pcparms_t ReadBack;                   // for readback
3409#endif
3410
3411  // Set priority via PC_GETPARMS, update, PC_SETPARMS
3412  // Query current values.
3413  // TODO: accelerate this by eliminating the PC_GETPARMS call.
3414  // Cache "pcparms_t" in global ParmCache.
3415  // TODO: elide set-to-same-value
3416
3417  // If something went wrong on init, don't change priorities.
3418  if (!priocntl_enable) {
3419    if (ThreadPriorityVerbose)
3420      tty->print_cr("Trying to set priority but init failed, ignoring");
3421    return EINVAL;
3422  }
3423
3424  // If lwp hasn't started yet, just return
3425  // the _start routine will call us again.
3426  if (lwpid <= 0) {
3427    if (ThreadPriorityVerbose) {
3428      tty->print_cr("deferring the set_lwp_class_and_priority of thread "
3429                     INTPTR_FORMAT " to %d, lwpid not set",
3430                     ThreadID, newPrio);
3431    }
3432    return 0;
3433  }
3434
3435  if (ThreadPriorityVerbose) {
3436    tty->print_cr ("set_lwp_class_and_priority("
3437                   INTPTR_FORMAT "@" INTPTR_FORMAT " %d) ",
3438                   ThreadID, lwpid, newPrio);
3439  }
3440
3441  memset(&ParmInfo, 0, sizeof(pcparms_t));
3442  ParmInfo.pc_cid = PC_CLNULL;
3443  rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ParmInfo);
3444  if (rslt < 0) return errno;
3445
3446  int cur_class = ParmInfo.pc_cid;
3447  ParmInfo.pc_cid = (id_t)new_class;
3448
3449  if (new_class == rtLimits.schedPolicy) {
3450    rtparms_t *rtInfo  = (rtparms_t*)ParmInfo.pc_clparms;
3451    rtInfo->rt_pri     = scale ? scale_to_lwp_priority(rtLimits.minPrio,
3452                                                       rtLimits.maxPrio, newPrio)
3453                               : newPrio;
3454    rtInfo->rt_tqsecs  = RT_NOCHANGE;
3455    rtInfo->rt_tqnsecs = RT_NOCHANGE;
3456    if (ThreadPriorityVerbose) {
3457      tty->print_cr("RT: %d->%d\n", newPrio, rtInfo->rt_pri);
3458    }
3459  } else if (new_class == iaLimits.schedPolicy) {
3460    iaparms_t* iaInfo  = (iaparms_t*)ParmInfo.pc_clparms;
3461    int maxClamped     = MIN2(iaLimits.maxPrio,
3462                              cur_class == new_class
3463                                ? (int)iaInfo->ia_uprilim : iaLimits.maxPrio);
3464    iaInfo->ia_upri    = scale ? scale_to_lwp_priority(iaLimits.minPrio,
3465                                                       maxClamped, newPrio)
3466                               : newPrio;
3467    iaInfo->ia_uprilim = cur_class == new_class
3468                           ? IA_NOCHANGE : (pri_t)iaLimits.maxPrio;
3469    iaInfo->ia_mode    = IA_NOCHANGE;
3470    if (ThreadPriorityVerbose) {
3471      tty->print_cr("IA: [%d...%d] %d->%d\n",
3472                    iaLimits.minPrio, maxClamped, newPrio, iaInfo->ia_upri);
3473    }
3474  } else if (new_class == tsLimits.schedPolicy) {
3475    tsparms_t* tsInfo  = (tsparms_t*)ParmInfo.pc_clparms;
3476    int maxClamped     = MIN2(tsLimits.maxPrio,
3477                              cur_class == new_class
3478                                ? (int)tsInfo->ts_uprilim : tsLimits.maxPrio);
3479    tsInfo->ts_upri    = scale ? scale_to_lwp_priority(tsLimits.minPrio,
3480                                                       maxClamped, newPrio)
3481                               : newPrio;
3482    tsInfo->ts_uprilim = cur_class == new_class
3483                           ? TS_NOCHANGE : (pri_t)tsLimits.maxPrio;
3484    if (ThreadPriorityVerbose) {
3485      tty->print_cr("TS: [%d...%d] %d->%d\n",
3486                    tsLimits.minPrio, maxClamped, newPrio, tsInfo->ts_upri);
3487    }
3488  } else if (new_class == fxLimits.schedPolicy) {
3489    fxparms_t* fxInfo  = (fxparms_t*)ParmInfo.pc_clparms;
3490    int maxClamped     = MIN2(fxLimits.maxPrio,
3491                              cur_class == new_class
3492                                ? (int)fxInfo->fx_uprilim : fxLimits.maxPrio);
3493    fxInfo->fx_upri    = scale ? scale_to_lwp_priority(fxLimits.minPrio,
3494                                                       maxClamped, newPrio)
3495                               : newPrio;
3496    fxInfo->fx_uprilim = cur_class == new_class
3497                           ? FX_NOCHANGE : (pri_t)fxLimits.maxPrio;
3498    fxInfo->fx_tqsecs  = FX_NOCHANGE;
3499    fxInfo->fx_tqnsecs = FX_NOCHANGE;
3500    if (ThreadPriorityVerbose) {
3501      tty->print_cr("FX: [%d...%d] %d->%d\n",
3502                    fxLimits.minPrio, maxClamped, newPrio, fxInfo->fx_upri);
3503    }
3504  } else {
3505    if (ThreadPriorityVerbose) {
3506      tty->print_cr("Unknown new scheduling class %d\n", new_class);
3507    }
3508    return EINVAL;    // no clue, punt
3509  }
3510
3511  rslt = priocntl(P_LWPID, lwpid, PC_SETPARMS, (caddr_t)&ParmInfo);
3512  if (ThreadPriorityVerbose && rslt) {
3513    tty->print_cr ("PC_SETPARMS ->%d %d\n", rslt, errno);
3514  }
3515  if (rslt < 0) return errno;
3516
3517#ifdef ASSERT
3518  // Sanity check: read back what we just attempted to set.
3519  // In theory it could have changed in the interim ...
3520  //
3521  // The priocntl system call is tricky.
3522  // Sometimes it'll validate the priority value argument and
3523  // return EINVAL if unhappy.  At other times it fails silently.
3524  // Readbacks are prudent.
3525
3526  if (!ReadBackValidate) return 0;
3527
3528  memset(&ReadBack, 0, sizeof(pcparms_t));
3529  ReadBack.pc_cid = PC_CLNULL;
3530  rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ReadBack);
3531  assert(rslt >= 0, "priocntl failed");
3532  Actual = Expected = 0xBAD;
3533  assert(ParmInfo.pc_cid == ReadBack.pc_cid, "cid's don't match");
3534  if (ParmInfo.pc_cid == rtLimits.schedPolicy) {
3535    Actual   = RTPRI(ReadBack)->rt_pri;
3536    Expected = RTPRI(ParmInfo)->rt_pri;
3537  } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) {
3538    Actual   = IAPRI(ReadBack)->ia_upri;
3539    Expected = IAPRI(ParmInfo)->ia_upri;
3540  } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) {
3541    Actual   = TSPRI(ReadBack)->ts_upri;
3542    Expected = TSPRI(ParmInfo)->ts_upri;
3543  } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) {
3544    Actual   = FXPRI(ReadBack)->fx_upri;
3545    Expected = FXPRI(ParmInfo)->fx_upri;
3546  } else {
3547    if (ThreadPriorityVerbose) {
3548      tty->print_cr("set_lwp_class_and_priority: unexpected class in readback: %d\n",
3549                    ParmInfo.pc_cid);
3550    }
3551  }
3552
3553  if (Actual != Expected) {
3554    if (ThreadPriorityVerbose) {
3555      tty->print_cr ("set_lwp_class_and_priority(%d %d) Class=%d: actual=%d vs expected=%d\n",
3556                     lwpid, newPrio, ReadBack.pc_cid, Actual, Expected);
3557    }
3558  }
3559#endif
3560
3561  return 0;
3562}
3563
3564// Solaris only gives access to 128 real priorities at a time,
3565// so we expand Java's ten to fill this range.  This would be better
3566// if we dynamically adjusted relative priorities.
3567//
3568// The ThreadPriorityPolicy option allows us to select 2 different
3569// priority scales.
3570//
3571// ThreadPriorityPolicy=0
3572// Since the Solaris' default priority is MaximumPriority, we do not
3573// set a priority lower than Max unless a priority lower than
3574// NormPriority is requested.
3575//
3576// ThreadPriorityPolicy=1
3577// This mode causes the priority table to get filled with
3578// linear values.  NormPriority get's mapped to 50% of the
3579// Maximum priority an so on.  This will cause VM threads
3580// to get unfair treatment against other Solaris processes
3581// which do not explicitly alter their thread priorities.
3582//
3583
3584int os::java_to_os_priority[CriticalPriority + 1] = {
3585  -99999,         // 0 Entry should never be used
3586
3587  0,              // 1 MinPriority
3588  32,             // 2
3589  64,             // 3
3590
3591  96,             // 4
3592  127,            // 5 NormPriority
3593  127,            // 6
3594
3595  127,            // 7
3596  127,            // 8
3597  127,            // 9 NearMaxPriority
3598
3599  127,            // 10 MaxPriority
3600
3601  -criticalPrio   // 11 CriticalPriority
3602};
3603
3604OSReturn os::set_native_priority(Thread* thread, int newpri) {
3605  OSThread* osthread = thread->osthread();
3606
3607  // Save requested priority in case the thread hasn't been started
3608  osthread->set_native_priority(newpri);
3609
3610  // Check for critical priority request
3611  bool fxcritical = false;
3612  if (newpri == -criticalPrio) {
3613    fxcritical = true;
3614    newpri = criticalPrio;
3615  }
3616
3617  assert(newpri >= MinimumPriority && newpri <= MaximumPriority, "bad priority mapping");
3618  if (!UseThreadPriorities) return OS_OK;
3619
3620  int status = 0;
3621
3622  if (!fxcritical) {
3623    // Use thr_setprio only if we have a priority that thr_setprio understands
3624    status = thr_setprio(thread->osthread()->thread_id(), newpri);
3625  }
3626
3627  int lwp_status =
3628          set_lwp_class_and_priority(osthread->thread_id(),
3629          osthread->lwp_id(),
3630          newpri,
3631          fxcritical ? fxLimits.schedPolicy : myClass,
3632          !fxcritical);
3633  if (lwp_status != 0 && fxcritical) {
3634    // Try again, this time without changing the scheduling class
3635    newpri = java_MaxPriority_to_os_priority;
3636    lwp_status = set_lwp_class_and_priority(osthread->thread_id(),
3637            osthread->lwp_id(),
3638            newpri, myClass, false);
3639  }
3640  status |= lwp_status;
3641  return (status == 0) ? OS_OK : OS_ERR;
3642}
3643
3644
3645OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
3646  int p;
3647  if (!UseThreadPriorities) {
3648    *priority_ptr = NormalPriority;
3649    return OS_OK;
3650  }
3651  int status = thr_getprio(thread->osthread()->thread_id(), &p);
3652  if (status != 0) {
3653    return OS_ERR;
3654  }
3655  *priority_ptr = p;
3656  return OS_OK;
3657}
3658
3659
3660// Hint to the underlying OS that a task switch would not be good.
3661// Void return because it's a hint and can fail.
3662void os::hint_no_preempt() {
3663  schedctl_start(schedctl_init());
3664}
3665
3666static void resume_clear_context(OSThread *osthread) {
3667  osthread->set_ucontext(NULL);
3668}
3669
3670static void suspend_save_context(OSThread *osthread, ucontext_t* context) {
3671  osthread->set_ucontext(context);
3672}
3673
3674static Semaphore sr_semaphore;
3675
3676void os::Solaris::SR_handler(Thread* thread, ucontext_t* uc) {
3677  // Save and restore errno to avoid confusing native code with EINTR
3678  // after sigsuspend.
3679  int old_errno = errno;
3680
3681  OSThread* osthread = thread->osthread();
3682  assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread");
3683
3684  os::SuspendResume::State current = osthread->sr.state();
3685  if (current == os::SuspendResume::SR_SUSPEND_REQUEST) {
3686    suspend_save_context(osthread, uc);
3687
3688    // attempt to switch the state, we assume we had a SUSPEND_REQUEST
3689    os::SuspendResume::State state = osthread->sr.suspended();
3690    if (state == os::SuspendResume::SR_SUSPENDED) {
3691      sigset_t suspend_set;  // signals for sigsuspend()
3692
3693      // get current set of blocked signals and unblock resume signal
3694      thr_sigsetmask(SIG_BLOCK, NULL, &suspend_set);
3695      sigdelset(&suspend_set, os::Solaris::SIGasync());
3696
3697      sr_semaphore.signal();
3698      // wait here until we are resumed
3699      while (1) {
3700        sigsuspend(&suspend_set);
3701
3702        os::SuspendResume::State result = osthread->sr.running();
3703        if (result == os::SuspendResume::SR_RUNNING) {
3704          sr_semaphore.signal();
3705          break;
3706        }
3707      }
3708
3709    } else if (state == os::SuspendResume::SR_RUNNING) {
3710      // request was cancelled, continue
3711    } else {
3712      ShouldNotReachHere();
3713    }
3714
3715    resume_clear_context(osthread);
3716  } else if (current == os::SuspendResume::SR_RUNNING) {
3717    // request was cancelled, continue
3718  } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) {
3719    // ignore
3720  } else {
3721    // ignore
3722  }
3723
3724  errno = old_errno;
3725}
3726
3727void os::print_statistics() {
3728}
3729
3730int os::message_box(const char* title, const char* message) {
3731  int i;
3732  fdStream err(defaultStream::error_fd());
3733  for (i = 0; i < 78; i++) err.print_raw("=");
3734  err.cr();
3735  err.print_raw_cr(title);
3736  for (i = 0; i < 78; i++) err.print_raw("-");
3737  err.cr();
3738  err.print_raw_cr(message);
3739  for (i = 0; i < 78; i++) err.print_raw("=");
3740  err.cr();
3741
3742  char buf[16];
3743  // Prevent process from exiting upon "read error" without consuming all CPU
3744  while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
3745
3746  return buf[0] == 'y' || buf[0] == 'Y';
3747}
3748
3749static int sr_notify(OSThread* osthread) {
3750  int status = thr_kill(osthread->thread_id(), os::Solaris::SIGasync());
3751  assert_status(status == 0, status, "thr_kill");
3752  return status;
3753}
3754
3755// "Randomly" selected value for how long we want to spin
3756// before bailing out on suspending a thread, also how often
3757// we send a signal to a thread we want to resume
3758static const int RANDOMLY_LARGE_INTEGER = 1000000;
3759static const int RANDOMLY_LARGE_INTEGER2 = 100;
3760
3761static bool do_suspend(OSThread* osthread) {
3762  assert(osthread->sr.is_running(), "thread should be running");
3763  assert(!sr_semaphore.trywait(), "semaphore has invalid state");
3764
3765  // mark as suspended and send signal
3766  if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) {
3767    // failed to switch, state wasn't running?
3768    ShouldNotReachHere();
3769    return false;
3770  }
3771
3772  if (sr_notify(osthread) != 0) {
3773    ShouldNotReachHere();
3774  }
3775
3776  // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED
3777  while (true) {
3778    if (sr_semaphore.timedwait(0, 2000 * NANOSECS_PER_MILLISEC)) {
3779      break;
3780    } else {
3781      // timeout
3782      os::SuspendResume::State cancelled = osthread->sr.cancel_suspend();
3783      if (cancelled == os::SuspendResume::SR_RUNNING) {
3784        return false;
3785      } else if (cancelled == os::SuspendResume::SR_SUSPENDED) {
3786        // make sure that we consume the signal on the semaphore as well
3787        sr_semaphore.wait();
3788        break;
3789      } else {
3790        ShouldNotReachHere();
3791        return false;
3792      }
3793    }
3794  }
3795
3796  guarantee(osthread->sr.is_suspended(), "Must be suspended");
3797  return true;
3798}
3799
3800static void do_resume(OSThread* osthread) {
3801  assert(osthread->sr.is_suspended(), "thread should be suspended");
3802  assert(!sr_semaphore.trywait(), "invalid semaphore state");
3803
3804  if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) {
3805    // failed to switch to WAKEUP_REQUEST
3806    ShouldNotReachHere();
3807    return;
3808  }
3809
3810  while (true) {
3811    if (sr_notify(osthread) == 0) {
3812      if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) {
3813        if (osthread->sr.is_running()) {
3814          return;
3815        }
3816      }
3817    } else {
3818      ShouldNotReachHere();
3819    }
3820  }
3821
3822  guarantee(osthread->sr.is_running(), "Must be running!");
3823}
3824
3825void os::SuspendedThreadTask::internal_do_task() {
3826  if (do_suspend(_thread->osthread())) {
3827    SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext());
3828    do_task(context);
3829    do_resume(_thread->osthread());
3830  }
3831}
3832
3833class PcFetcher : public os::SuspendedThreadTask {
3834public:
3835  PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {}
3836  ExtendedPC result();
3837protected:
3838  void do_task(const os::SuspendedThreadTaskContext& context);
3839private:
3840  ExtendedPC _epc;
3841};
3842
3843ExtendedPC PcFetcher::result() {
3844  guarantee(is_done(), "task is not done yet.");
3845  return _epc;
3846}
3847
3848void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) {
3849  Thread* thread = context.thread();
3850  OSThread* osthread = thread->osthread();
3851  if (osthread->ucontext() != NULL) {
3852    _epc = os::Solaris::ucontext_get_pc((ucontext_t *) context.ucontext());
3853  } else {
3854    // NULL context is unexpected, double-check this is the VMThread
3855    guarantee(thread->is_VM_thread(), "can only be called for VMThread");
3856  }
3857}
3858
3859// A lightweight implementation that does not suspend the target thread and
3860// thus returns only a hint. Used for profiling only!
3861ExtendedPC os::get_thread_pc(Thread* thread) {
3862  // Make sure that it is called by the watcher and the Threads lock is owned.
3863  assert(Thread::current()->is_Watcher_thread(), "Must be watcher and own Threads_lock");
3864  // For now, is only used to profile the VM Thread
3865  assert(thread->is_VM_thread(), "Can only be called for VMThread");
3866  PcFetcher fetcher(thread);
3867  fetcher.run();
3868  return fetcher.result();
3869}
3870
3871
3872// This does not do anything on Solaris. This is basically a hook for being
3873// able to use structured exception handling (thread-local exception filters) on, e.g., Win32.
3874void os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, JavaCallArguments* args, Thread* thread) {
3875  f(value, method, args, thread);
3876}
3877
3878// This routine may be used by user applications as a "hook" to catch signals.
3879// The user-defined signal handler must pass unrecognized signals to this
3880// routine, and if it returns true (non-zero), then the signal handler must
3881// return immediately.  If the flag "abort_if_unrecognized" is true, then this
3882// routine will never retun false (zero), but instead will execute a VM panic
3883// routine kill the process.
3884//
3885// If this routine returns false, it is OK to call it again.  This allows
3886// the user-defined signal handler to perform checks either before or after
3887// the VM performs its own checks.  Naturally, the user code would be making
3888// a serious error if it tried to handle an exception (such as a null check
3889// or breakpoint) that the VM was generating for its own correct operation.
3890//
3891// This routine may recognize any of the following kinds of signals:
3892// SIGBUS, SIGSEGV, SIGILL, SIGFPE, BREAK_SIGNAL, SIGPIPE, SIGXFSZ,
3893// os::Solaris::SIGasync
3894// It should be consulted by handlers for any of those signals.
3895// It explicitly does not recognize os::Solaris::SIGinterrupt
3896//
3897// The caller of this routine must pass in the three arguments supplied
3898// to the function referred to in the "sa_sigaction" (not the "sa_handler")
3899// field of the structure passed to sigaction().  This routine assumes that
3900// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART.
3901//
3902// Note that the VM will print warnings if it detects conflicting signal
3903// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers".
3904//
3905extern "C" JNIEXPORT int
3906JVM_handle_solaris_signal(int signo, siginfo_t* siginfo, void* ucontext,
3907                          int abort_if_unrecognized);
3908
3909
3910void signalHandler(int sig, siginfo_t* info, void* ucVoid) {
3911  int orig_errno = errno;  // Preserve errno value over signal handler.
3912  JVM_handle_solaris_signal(sig, info, ucVoid, true);
3913  errno = orig_errno;
3914}
3915
3916/* Do not delete - if guarantee is ever removed,  a signal handler (even empty)
3917   is needed to provoke threads blocked on IO to return an EINTR
3918   Note: this explicitly does NOT call JVM_handle_solaris_signal and
3919   does NOT participate in signal chaining due to requirement for
3920   NOT setting SA_RESTART to make EINTR work. */
3921extern "C" void sigINTRHandler(int sig, siginfo_t* info, void* ucVoid) {
3922   if (UseSignalChaining) {
3923      struct sigaction *actp = os::Solaris::get_chained_signal_action(sig);
3924      if (actp && actp->sa_handler) {
3925        vm_exit_during_initialization("Signal chaining detected for VM interrupt signal, try -XX:+UseAltSigs");
3926      }
3927   }
3928}
3929
3930// This boolean allows users to forward their own non-matching signals
3931// to JVM_handle_solaris_signal, harmlessly.
3932bool os::Solaris::signal_handlers_are_installed = false;
3933
3934// For signal-chaining
3935bool os::Solaris::libjsig_is_loaded = false;
3936typedef struct sigaction *(*get_signal_t)(int);
3937get_signal_t os::Solaris::get_signal_action = NULL;
3938
3939struct sigaction* os::Solaris::get_chained_signal_action(int sig) {
3940  struct sigaction *actp = NULL;
3941
3942  if ((libjsig_is_loaded)  && (sig <= Maxlibjsigsigs)) {
3943    // Retrieve the old signal handler from libjsig
3944    actp = (*get_signal_action)(sig);
3945  }
3946  if (actp == NULL) {
3947    // Retrieve the preinstalled signal handler from jvm
3948    actp = get_preinstalled_handler(sig);
3949  }
3950
3951  return actp;
3952}
3953
3954static bool call_chained_handler(struct sigaction *actp, int sig,
3955                                 siginfo_t *siginfo, void *context) {
3956  // Call the old signal handler
3957  if (actp->sa_handler == SIG_DFL) {
3958    // It's more reasonable to let jvm treat it as an unexpected exception
3959    // instead of taking the default action.
3960    return false;
3961  } else if (actp->sa_handler != SIG_IGN) {
3962    if ((actp->sa_flags & SA_NODEFER) == 0) {
3963      // automaticlly block the signal
3964      sigaddset(&(actp->sa_mask), sig);
3965    }
3966
3967    sa_handler_t hand;
3968    sa_sigaction_t sa;
3969    bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0;
3970    // retrieve the chained handler
3971    if (siginfo_flag_set) {
3972      sa = actp->sa_sigaction;
3973    } else {
3974      hand = actp->sa_handler;
3975    }
3976
3977    if ((actp->sa_flags & SA_RESETHAND) != 0) {
3978      actp->sa_handler = SIG_DFL;
3979    }
3980
3981    // try to honor the signal mask
3982    sigset_t oset;
3983    thr_sigsetmask(SIG_SETMASK, &(actp->sa_mask), &oset);
3984
3985    // call into the chained handler
3986    if (siginfo_flag_set) {
3987      (*sa)(sig, siginfo, context);
3988    } else {
3989      (*hand)(sig);
3990    }
3991
3992    // restore the signal mask
3993    thr_sigsetmask(SIG_SETMASK, &oset, 0);
3994  }
3995  // Tell jvm's signal handler the signal is taken care of.
3996  return true;
3997}
3998
3999bool os::Solaris::chained_handler(int sig, siginfo_t* siginfo, void* context) {
4000  bool chained = false;
4001  // signal-chaining
4002  if (UseSignalChaining) {
4003    struct sigaction *actp = get_chained_signal_action(sig);
4004    if (actp != NULL) {
4005      chained = call_chained_handler(actp, sig, siginfo, context);
4006    }
4007  }
4008  return chained;
4009}
4010
4011struct sigaction* os::Solaris::get_preinstalled_handler(int sig) {
4012  assert((chainedsigactions != (struct sigaction *)NULL) && (preinstalled_sigs != (int *)NULL) , "signals not yet initialized");
4013  if (preinstalled_sigs[sig] != 0) {
4014    return &chainedsigactions[sig];
4015  }
4016  return NULL;
4017}
4018
4019void os::Solaris::save_preinstalled_handler(int sig, struct sigaction& oldAct) {
4020
4021  assert(sig > 0 && sig <= Maxsignum, "vm signal out of expected range");
4022  assert((chainedsigactions != (struct sigaction *)NULL) && (preinstalled_sigs != (int *)NULL) , "signals not yet initialized");
4023  chainedsigactions[sig] = oldAct;
4024  preinstalled_sigs[sig] = 1;
4025}
4026
4027void os::Solaris::set_signal_handler(int sig, bool set_installed, bool oktochain) {
4028  // Check for overwrite.
4029  struct sigaction oldAct;
4030  sigaction(sig, (struct sigaction*)NULL, &oldAct);
4031  void* oldhand = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*,  oldAct.sa_sigaction)
4032                                      : CAST_FROM_FN_PTR(void*,  oldAct.sa_handler);
4033  if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) &&
4034      oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) &&
4035      oldhand != CAST_FROM_FN_PTR(void*, signalHandler)) {
4036    if (AllowUserSignalHandlers || !set_installed) {
4037      // Do not overwrite; user takes responsibility to forward to us.
4038      return;
4039    } else if (UseSignalChaining) {
4040      if (oktochain) {
4041        // save the old handler in jvm
4042        save_preinstalled_handler(sig, oldAct);
4043      } else {
4044        vm_exit_during_initialization("Signal chaining not allowed for VM interrupt signal, try -XX:+UseAltSigs.");
4045      }
4046      // libjsig also interposes the sigaction() call below and saves the
4047      // old sigaction on it own.
4048    } else {
4049      fatal(err_msg("Encountered unexpected pre-existing sigaction handler "
4050                    "%#lx for signal %d.", (long)oldhand, sig));
4051    }
4052  }
4053
4054  struct sigaction sigAct;
4055  sigfillset(&(sigAct.sa_mask));
4056  sigAct.sa_handler = SIG_DFL;
4057
4058  sigAct.sa_sigaction = signalHandler;
4059  // Handle SIGSEGV on alternate signal stack if
4060  // not using stack banging
4061  if (!UseStackBanging && sig == SIGSEGV) {
4062    sigAct.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK;
4063  // Interruptible i/o requires SA_RESTART cleared so EINTR
4064  // is returned instead of restarting system calls
4065  } else if (sig == os::Solaris::SIGinterrupt()) {
4066    sigemptyset(&sigAct.sa_mask);
4067    sigAct.sa_handler = NULL;
4068    sigAct.sa_flags = SA_SIGINFO;
4069    sigAct.sa_sigaction = sigINTRHandler;
4070  } else {
4071    sigAct.sa_flags = SA_SIGINFO | SA_RESTART;
4072  }
4073  os::Solaris::set_our_sigflags(sig, sigAct.sa_flags);
4074
4075  sigaction(sig, &sigAct, &oldAct);
4076
4077  void* oldhand2 = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction)
4078                                       : CAST_FROM_FN_PTR(void*, oldAct.sa_handler);
4079  assert(oldhand2 == oldhand, "no concurrent signal handler installation");
4080}
4081
4082
4083#define DO_SIGNAL_CHECK(sig) \
4084  if (!sigismember(&check_signal_done, sig)) \
4085    os::Solaris::check_signal_handler(sig)
4086
4087// This method is a periodic task to check for misbehaving JNI applications
4088// under CheckJNI, we can add any periodic checks here
4089
4090void os::run_periodic_checks() {
4091  // A big source of grief is hijacking virt. addr 0x0 on Solaris,
4092  // thereby preventing a NULL checks.
4093  if (!check_addr0_done) check_addr0_done = check_addr0(tty);
4094
4095  if (check_signals == false) return;
4096
4097  // SEGV and BUS if overridden could potentially prevent
4098  // generation of hs*.log in the event of a crash, debugging
4099  // such a case can be very challenging, so we absolutely
4100  // check for the following for a good measure:
4101  DO_SIGNAL_CHECK(SIGSEGV);
4102  DO_SIGNAL_CHECK(SIGILL);
4103  DO_SIGNAL_CHECK(SIGFPE);
4104  DO_SIGNAL_CHECK(SIGBUS);
4105  DO_SIGNAL_CHECK(SIGPIPE);
4106  DO_SIGNAL_CHECK(SIGXFSZ);
4107
4108  // ReduceSignalUsage allows the user to override these handlers
4109  // see comments at the very top and jvm_solaris.h
4110  if (!ReduceSignalUsage) {
4111    DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL);
4112    DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL);
4113    DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL);
4114    DO_SIGNAL_CHECK(BREAK_SIGNAL);
4115  }
4116
4117  // See comments above for using JVM1/JVM2 and UseAltSigs
4118  DO_SIGNAL_CHECK(os::Solaris::SIGinterrupt());
4119  DO_SIGNAL_CHECK(os::Solaris::SIGasync());
4120
4121}
4122
4123typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *);
4124
4125static os_sigaction_t os_sigaction = NULL;
4126
4127void os::Solaris::check_signal_handler(int sig) {
4128  char buf[O_BUFLEN];
4129  address jvmHandler = NULL;
4130
4131  struct sigaction act;
4132  if (os_sigaction == NULL) {
4133    // only trust the default sigaction, in case it has been interposed
4134    os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction");
4135    if (os_sigaction == NULL) return;
4136  }
4137
4138  os_sigaction(sig, (struct sigaction*)NULL, &act);
4139
4140  address thisHandler = (act.sa_flags & SA_SIGINFO)
4141    ? CAST_FROM_FN_PTR(address, act.sa_sigaction)
4142    : CAST_FROM_FN_PTR(address, act.sa_handler);
4143
4144
4145  switch (sig) {
4146    case SIGSEGV:
4147    case SIGBUS:
4148    case SIGFPE:
4149    case SIGPIPE:
4150    case SIGXFSZ:
4151    case SIGILL:
4152      jvmHandler = CAST_FROM_FN_PTR(address, signalHandler);
4153      break;
4154
4155    case SHUTDOWN1_SIGNAL:
4156    case SHUTDOWN2_SIGNAL:
4157    case SHUTDOWN3_SIGNAL:
4158    case BREAK_SIGNAL:
4159      jvmHandler = (address)user_handler();
4160      break;
4161
4162    default:
4163      int intrsig = os::Solaris::SIGinterrupt();
4164      int asynsig = os::Solaris::SIGasync();
4165
4166      if (sig == intrsig) {
4167        jvmHandler = CAST_FROM_FN_PTR(address, sigINTRHandler);
4168      } else if (sig == asynsig) {
4169        jvmHandler = CAST_FROM_FN_PTR(address, signalHandler);
4170      } else {
4171        return;
4172      }
4173      break;
4174  }
4175
4176
4177  if (thisHandler != jvmHandler) {
4178    tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN));
4179    tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN));
4180    tty->print_cr("  found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN));
4181    // No need to check this sig any longer
4182    sigaddset(&check_signal_done, sig);
4183    // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN
4184    if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) {
4185      tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell",
4186                    exception_name(sig, buf, O_BUFLEN));
4187    }
4188  } else if(os::Solaris::get_our_sigflags(sig) != 0 && act.sa_flags != os::Solaris::get_our_sigflags(sig)) {
4189    tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN));
4190    tty->print("expected:" PTR32_FORMAT, os::Solaris::get_our_sigflags(sig));
4191    tty->print_cr("  found:" PTR32_FORMAT, act.sa_flags);
4192    // No need to check this sig any longer
4193    sigaddset(&check_signal_done, sig);
4194  }
4195
4196  // Print all the signal handler state
4197  if (sigismember(&check_signal_done, sig)) {
4198    print_signal_handlers(tty, buf, O_BUFLEN);
4199  }
4200
4201}
4202
4203void os::Solaris::install_signal_handlers() {
4204  bool libjsigdone = false;
4205  signal_handlers_are_installed = true;
4206
4207  // signal-chaining
4208  typedef void (*signal_setting_t)();
4209  signal_setting_t begin_signal_setting = NULL;
4210  signal_setting_t end_signal_setting = NULL;
4211  begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4212                                        dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting"));
4213  if (begin_signal_setting != NULL) {
4214    end_signal_setting = CAST_TO_FN_PTR(signal_setting_t,
4215                                        dlsym(RTLD_DEFAULT, "JVM_end_signal_setting"));
4216    get_signal_action = CAST_TO_FN_PTR(get_signal_t,
4217                                       dlsym(RTLD_DEFAULT, "JVM_get_signal_action"));
4218    get_libjsig_version = CAST_TO_FN_PTR(version_getting_t,
4219                                         dlsym(RTLD_DEFAULT, "JVM_get_libjsig_version"));
4220    libjsig_is_loaded = true;
4221    if (os::Solaris::get_libjsig_version != NULL) {
4222      libjsigversion =  (*os::Solaris::get_libjsig_version)();
4223    }
4224    assert(UseSignalChaining, "should enable signal-chaining");
4225  }
4226  if (libjsig_is_loaded) {
4227    // Tell libjsig jvm is setting signal handlers
4228    (*begin_signal_setting)();
4229  }
4230
4231  set_signal_handler(SIGSEGV, true, true);
4232  set_signal_handler(SIGPIPE, true, true);
4233  set_signal_handler(SIGXFSZ, true, true);
4234  set_signal_handler(SIGBUS, true, true);
4235  set_signal_handler(SIGILL, true, true);
4236  set_signal_handler(SIGFPE, true, true);
4237
4238
4239  if (os::Solaris::SIGinterrupt() > OLDMAXSIGNUM || os::Solaris::SIGasync() > OLDMAXSIGNUM) {
4240
4241    // Pre-1.4.1 Libjsig limited to signal chaining signals <= 32 so
4242    // can not register overridable signals which might be > 32
4243    if (libjsig_is_loaded && libjsigversion <= JSIG_VERSION_1_4_1) {
4244    // Tell libjsig jvm has finished setting signal handlers
4245      (*end_signal_setting)();
4246      libjsigdone = true;
4247    }
4248  }
4249
4250  // Never ok to chain our SIGinterrupt
4251  set_signal_handler(os::Solaris::SIGinterrupt(), true, false);
4252  set_signal_handler(os::Solaris::SIGasync(), true, true);
4253
4254  if (libjsig_is_loaded && !libjsigdone) {
4255    // Tell libjsig jvm finishes setting signal handlers
4256    (*end_signal_setting)();
4257  }
4258
4259  // We don't activate signal checker if libjsig is in place, we trust ourselves
4260  // and if UserSignalHandler is installed all bets are off.
4261  // Log that signal checking is off only if -verbose:jni is specified.
4262  if (CheckJNICalls) {
4263    if (libjsig_is_loaded) {
4264      if (PrintJNIResolving) {
4265        tty->print_cr("Info: libjsig is activated, all active signal checking is disabled");
4266      }
4267      check_signals = false;
4268    }
4269    if (AllowUserSignalHandlers) {
4270      if (PrintJNIResolving) {
4271        tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled");
4272      }
4273      check_signals = false;
4274    }
4275  }
4276}
4277
4278
4279void report_error(const char* file_name, int line_no, const char* title, const char* format, ...);
4280
4281const char * signames[] = {
4282  "SIG0",
4283  "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP",
4284  "SIGABRT", "SIGEMT", "SIGFPE", "SIGKILL", "SIGBUS",
4285  "SIGSEGV", "SIGSYS", "SIGPIPE", "SIGALRM", "SIGTERM",
4286  "SIGUSR1", "SIGUSR2", "SIGCLD", "SIGPWR", "SIGWINCH",
4287  "SIGURG", "SIGPOLL", "SIGSTOP", "SIGTSTP", "SIGCONT",
4288  "SIGTTIN", "SIGTTOU", "SIGVTALRM", "SIGPROF", "SIGXCPU",
4289  "SIGXFSZ", "SIGWAITING", "SIGLWP", "SIGFREEZE", "SIGTHAW",
4290  "SIGCANCEL", "SIGLOST"
4291};
4292
4293const char* os::exception_name(int exception_code, char* buf, size_t size) {
4294  if (0 < exception_code && exception_code <= SIGRTMAX) {
4295    // signal
4296    if (exception_code < sizeof(signames)/sizeof(const char*)) {
4297       jio_snprintf(buf, size, "%s", signames[exception_code]);
4298    } else {
4299       jio_snprintf(buf, size, "SIG%d", exception_code);
4300    }
4301    return buf;
4302  } else {
4303    return NULL;
4304  }
4305}
4306
4307// (Static) wrapper for getisax(2) call.
4308os::Solaris::getisax_func_t os::Solaris::_getisax = 0;
4309
4310// (Static) wrappers for the liblgrp API
4311os::Solaris::lgrp_home_func_t os::Solaris::_lgrp_home;
4312os::Solaris::lgrp_init_func_t os::Solaris::_lgrp_init;
4313os::Solaris::lgrp_fini_func_t os::Solaris::_lgrp_fini;
4314os::Solaris::lgrp_root_func_t os::Solaris::_lgrp_root;
4315os::Solaris::lgrp_children_func_t os::Solaris::_lgrp_children;
4316os::Solaris::lgrp_resources_func_t os::Solaris::_lgrp_resources;
4317os::Solaris::lgrp_nlgrps_func_t os::Solaris::_lgrp_nlgrps;
4318os::Solaris::lgrp_cookie_stale_func_t os::Solaris::_lgrp_cookie_stale;
4319os::Solaris::lgrp_cookie_t os::Solaris::_lgrp_cookie = 0;
4320
4321// (Static) wrapper for meminfo() call.
4322os::Solaris::meminfo_func_t os::Solaris::_meminfo = 0;
4323
4324static address resolve_symbol_lazy(const char* name) {
4325  address addr = (address) dlsym(RTLD_DEFAULT, name);
4326  if (addr == NULL) {
4327    // RTLD_DEFAULT was not defined on some early versions of 2.5.1
4328    addr = (address) dlsym(RTLD_NEXT, name);
4329  }
4330  return addr;
4331}
4332
4333static address resolve_symbol(const char* name) {
4334  address addr = resolve_symbol_lazy(name);
4335  if (addr == NULL) {
4336    fatal(dlerror());
4337  }
4338  return addr;
4339}
4340
4341void os::Solaris::libthread_init() {
4342  address func = (address)dlsym(RTLD_DEFAULT, "_thr_suspend_allmutators");
4343
4344  lwp_priocntl_init();
4345
4346  // RTLD_DEFAULT was not defined on some early versions of 5.5.1
4347  if (func == NULL) {
4348    func = (address) dlsym(RTLD_NEXT, "_thr_suspend_allmutators");
4349    // Guarantee that this VM is running on an new enough OS (5.6 or
4350    // later) that it will have a new enough libthread.so.
4351    guarantee(func != NULL, "libthread.so is too old.");
4352  }
4353
4354  int size;
4355  void (*handler_info_func)(address *, int *);
4356  handler_info_func = CAST_TO_FN_PTR(void (*)(address *, int *), resolve_symbol("thr_sighndlrinfo"));
4357  handler_info_func(&handler_start, &size);
4358  handler_end = handler_start + size;
4359}
4360
4361
4362int_fnP_mutex_tP os::Solaris::_mutex_lock;
4363int_fnP_mutex_tP os::Solaris::_mutex_trylock;
4364int_fnP_mutex_tP os::Solaris::_mutex_unlock;
4365int_fnP_mutex_tP_i_vP os::Solaris::_mutex_init;
4366int_fnP_mutex_tP os::Solaris::_mutex_destroy;
4367int os::Solaris::_mutex_scope = USYNC_THREAD;
4368
4369int_fnP_cond_tP_mutex_tP_timestruc_tP os::Solaris::_cond_timedwait;
4370int_fnP_cond_tP_mutex_tP os::Solaris::_cond_wait;
4371int_fnP_cond_tP os::Solaris::_cond_signal;
4372int_fnP_cond_tP os::Solaris::_cond_broadcast;
4373int_fnP_cond_tP_i_vP os::Solaris::_cond_init;
4374int_fnP_cond_tP os::Solaris::_cond_destroy;
4375int os::Solaris::_cond_scope = USYNC_THREAD;
4376
4377void os::Solaris::synchronization_init() {
4378  if (UseLWPSynchronization) {
4379    os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_lock")));
4380    os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_trylock")));
4381    os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_unlock")));
4382    os::Solaris::set_mutex_init(lwp_mutex_init);
4383    os::Solaris::set_mutex_destroy(lwp_mutex_destroy);
4384    os::Solaris::set_mutex_scope(USYNC_THREAD);
4385
4386    os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("_lwp_cond_timedwait")));
4387    os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("_lwp_cond_wait")));
4388    os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_signal")));
4389    os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_broadcast")));
4390    os::Solaris::set_cond_init(lwp_cond_init);
4391    os::Solaris::set_cond_destroy(lwp_cond_destroy);
4392    os::Solaris::set_cond_scope(USYNC_THREAD);
4393  }
4394  else {
4395    os::Solaris::set_mutex_scope(USYNC_THREAD);
4396    os::Solaris::set_cond_scope(USYNC_THREAD);
4397
4398    if (UsePthreads) {
4399      os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_lock")));
4400      os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_trylock")));
4401      os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_unlock")));
4402      os::Solaris::set_mutex_init(pthread_mutex_default_init);
4403      os::Solaris::set_mutex_destroy(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_destroy")));
4404
4405      os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("pthread_cond_timedwait")));
4406      os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("pthread_cond_wait")));
4407      os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_signal")));
4408      os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_broadcast")));
4409      os::Solaris::set_cond_init(pthread_cond_default_init);
4410      os::Solaris::set_cond_destroy(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_destroy")));
4411    }
4412    else {
4413      os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_lock")));
4414      os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_trylock")));
4415      os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_unlock")));
4416      os::Solaris::set_mutex_init(::mutex_init);
4417      os::Solaris::set_mutex_destroy(::mutex_destroy);
4418
4419      os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("cond_timedwait")));
4420      os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("cond_wait")));
4421      os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_signal")));
4422      os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_broadcast")));
4423      os::Solaris::set_cond_init(::cond_init);
4424      os::Solaris::set_cond_destroy(::cond_destroy);
4425    }
4426  }
4427}
4428
4429bool os::Solaris::liblgrp_init() {
4430  void *handle = dlopen("liblgrp.so.1", RTLD_LAZY);
4431  if (handle != NULL) {
4432    os::Solaris::set_lgrp_home(CAST_TO_FN_PTR(lgrp_home_func_t, dlsym(handle, "lgrp_home")));
4433    os::Solaris::set_lgrp_init(CAST_TO_FN_PTR(lgrp_init_func_t, dlsym(handle, "lgrp_init")));
4434    os::Solaris::set_lgrp_fini(CAST_TO_FN_PTR(lgrp_fini_func_t, dlsym(handle, "lgrp_fini")));
4435    os::Solaris::set_lgrp_root(CAST_TO_FN_PTR(lgrp_root_func_t, dlsym(handle, "lgrp_root")));
4436    os::Solaris::set_lgrp_children(CAST_TO_FN_PTR(lgrp_children_func_t, dlsym(handle, "lgrp_children")));
4437    os::Solaris::set_lgrp_resources(CAST_TO_FN_PTR(lgrp_resources_func_t, dlsym(handle, "lgrp_resources")));
4438    os::Solaris::set_lgrp_nlgrps(CAST_TO_FN_PTR(lgrp_nlgrps_func_t, dlsym(handle, "lgrp_nlgrps")));
4439    os::Solaris::set_lgrp_cookie_stale(CAST_TO_FN_PTR(lgrp_cookie_stale_func_t,
4440                                       dlsym(handle, "lgrp_cookie_stale")));
4441
4442    lgrp_cookie_t c = lgrp_init(LGRP_VIEW_CALLER);
4443    set_lgrp_cookie(c);
4444    return true;
4445  }
4446  return false;
4447}
4448
4449void os::Solaris::misc_sym_init() {
4450  address func;
4451
4452  // getisax
4453  func = resolve_symbol_lazy("getisax");
4454  if (func != NULL) {
4455    os::Solaris::_getisax = CAST_TO_FN_PTR(getisax_func_t, func);
4456  }
4457
4458  // meminfo
4459  func = resolve_symbol_lazy("meminfo");
4460  if (func != NULL) {
4461    os::Solaris::set_meminfo(CAST_TO_FN_PTR(meminfo_func_t, func));
4462  }
4463}
4464
4465uint_t os::Solaris::getisax(uint32_t* array, uint_t n) {
4466  assert(_getisax != NULL, "_getisax not set");
4467  return _getisax(array, n);
4468}
4469
4470// int pset_getloadavg(psetid_t pset, double loadavg[], int nelem);
4471typedef long (*pset_getloadavg_type)(psetid_t pset, double loadavg[], int nelem);
4472static pset_getloadavg_type pset_getloadavg_ptr = NULL;
4473
4474void init_pset_getloadavg_ptr(void) {
4475  pset_getloadavg_ptr =
4476    (pset_getloadavg_type)dlsym(RTLD_DEFAULT, "pset_getloadavg");
4477  if (PrintMiscellaneous && Verbose && pset_getloadavg_ptr == NULL) {
4478    warning("pset_getloadavg function not found");
4479  }
4480}
4481
4482int os::Solaris::_dev_zero_fd = -1;
4483
4484// this is called _before_ the global arguments have been parsed
4485void os::init(void) {
4486  _initial_pid = getpid();
4487
4488  max_hrtime = first_hrtime = gethrtime();
4489
4490  init_random(1234567);
4491
4492  page_size = sysconf(_SC_PAGESIZE);
4493  if (page_size == -1)
4494    fatal(err_msg("os_solaris.cpp: os::init: sysconf failed (%s)",
4495                  strerror(errno)));
4496  init_page_sizes((size_t) page_size);
4497
4498  Solaris::initialize_system_info();
4499
4500  // Initialize misc. symbols as soon as possible, so we can use them
4501  // if we need them.
4502  Solaris::misc_sym_init();
4503
4504  int fd = ::open("/dev/zero", O_RDWR);
4505  if (fd < 0) {
4506    fatal(err_msg("os::init: cannot open /dev/zero (%s)", strerror(errno)));
4507  } else {
4508    Solaris::set_dev_zero_fd(fd);
4509
4510    // Close on exec, child won't inherit.
4511    fcntl(fd, F_SETFD, FD_CLOEXEC);
4512  }
4513
4514  clock_tics_per_sec = CLK_TCK;
4515
4516  // check if dladdr1() exists; dladdr1 can provide more information than
4517  // dladdr for os::dll_address_to_function_name. It comes with SunOS 5.9
4518  // and is available on linker patches for 5.7 and 5.8.
4519  // libdl.so must have been loaded, this call is just an entry lookup
4520  void * hdl = dlopen("libdl.so", RTLD_NOW);
4521  if (hdl)
4522    dladdr1_func = CAST_TO_FN_PTR(dladdr1_func_type, dlsym(hdl, "dladdr1"));
4523
4524  // (Solaris only) this switches to calls that actually do locking.
4525  ThreadCritical::initialize();
4526
4527  main_thread = thr_self();
4528
4529  // Constant minimum stack size allowed. It must be at least
4530  // the minimum of what the OS supports (thr_min_stack()), and
4531  // enough to allow the thread to get to user bytecode execution.
4532  Solaris::min_stack_allowed = MAX2(thr_min_stack(), Solaris::min_stack_allowed);
4533  // If the pagesize of the VM is greater than 8K determine the appropriate
4534  // number of initial guard pages.  The user can change this with the
4535  // command line arguments, if needed.
4536  if (vm_page_size() > 8*K) {
4537    StackYellowPages = 1;
4538    StackRedPages = 1;
4539    StackShadowPages = round_to((StackShadowPages*8*K), vm_page_size()) / vm_page_size();
4540  }
4541}
4542
4543// To install functions for atexit system call
4544extern "C" {
4545  static void perfMemory_exit_helper() {
4546    perfMemory_exit();
4547  }
4548}
4549
4550// this is called _after_ the global arguments have been parsed
4551jint os::init_2(void) {
4552  // try to enable extended file IO ASAP, see 6431278
4553  os::Solaris::try_enable_extended_io();
4554
4555  // Allocate a single page and mark it as readable for safepoint polling.  Also
4556  // use this first mmap call to check support for MAP_ALIGN.
4557  address polling_page = (address)Solaris::mmap_chunk((char*)page_size,
4558                                                      page_size,
4559                                                      MAP_PRIVATE | MAP_ALIGN,
4560                                                      PROT_READ);
4561  if (polling_page == NULL) {
4562    has_map_align = false;
4563    polling_page = (address)Solaris::mmap_chunk(NULL, page_size, MAP_PRIVATE,
4564                                                PROT_READ);
4565  }
4566
4567  os::set_polling_page(polling_page);
4568
4569#ifndef PRODUCT
4570  if (Verbose && PrintMiscellaneous)
4571    tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page);
4572#endif
4573
4574  if (!UseMembar) {
4575    address mem_serialize_page = (address)Solaris::mmap_chunk(NULL, page_size, MAP_PRIVATE, PROT_READ | PROT_WRITE);
4576    guarantee(mem_serialize_page != NULL, "mmap Failed for memory serialize page");
4577    os::set_memory_serialize_page(mem_serialize_page);
4578
4579#ifndef PRODUCT
4580    if (Verbose && PrintMiscellaneous)
4581      tty->print("[Memory Serialize  Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page);
4582#endif
4583  }
4584
4585  // Check minimum allowable stack size for thread creation and to initialize
4586  // the java system classes, including StackOverflowError - depends on page
4587  // size.  Add a page for compiler2 recursion in main thread.
4588  // Add in 2*BytesPerWord times page size to account for VM stack during
4589  // class initialization depending on 32 or 64 bit VM.
4590  os::Solaris::min_stack_allowed = MAX2(os::Solaris::min_stack_allowed,
4591            (size_t)(StackYellowPages+StackRedPages+StackShadowPages+
4592                    2*BytesPerWord COMPILER2_PRESENT(+1)) * page_size);
4593
4594  size_t threadStackSizeInBytes = ThreadStackSize * K;
4595  if (threadStackSizeInBytes != 0 &&
4596    threadStackSizeInBytes < os::Solaris::min_stack_allowed) {
4597    tty->print_cr("\nThe stack size specified is too small, Specify at least %dk",
4598                  os::Solaris::min_stack_allowed/K);
4599    return JNI_ERR;
4600  }
4601
4602  // For 64kbps there will be a 64kb page size, which makes
4603  // the usable default stack size quite a bit less.  Increase the
4604  // stack for 64kb (or any > than 8kb) pages, this increases
4605  // virtual memory fragmentation (since we're not creating the
4606  // stack on a power of 2 boundary.  The real fix for this
4607  // should be to fix the guard page mechanism.
4608
4609  if (vm_page_size() > 8*K) {
4610      threadStackSizeInBytes = (threadStackSizeInBytes != 0)
4611         ? threadStackSizeInBytes +
4612           ((StackYellowPages + StackRedPages) * vm_page_size())
4613         : 0;
4614      ThreadStackSize = threadStackSizeInBytes/K;
4615  }
4616
4617  // Make the stack size a multiple of the page size so that
4618  // the yellow/red zones can be guarded.
4619  JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
4620        vm_page_size()));
4621
4622  Solaris::libthread_init();
4623
4624  if (UseNUMA) {
4625    if (!Solaris::liblgrp_init()) {
4626      UseNUMA = false;
4627    } else {
4628      size_t lgrp_limit = os::numa_get_groups_num();
4629      int *lgrp_ids = NEW_C_HEAP_ARRAY(int, lgrp_limit, mtInternal);
4630      size_t lgrp_num = os::numa_get_leaf_groups(lgrp_ids, lgrp_limit);
4631      FREE_C_HEAP_ARRAY(int, lgrp_ids, mtInternal);
4632      if (lgrp_num < 2) {
4633        // There's only one locality group, disable NUMA.
4634        UseNUMA = false;
4635      }
4636    }
4637    if (!UseNUMA && ForceNUMA) {
4638      UseNUMA = true;
4639    }
4640  }
4641
4642  Solaris::signal_sets_init();
4643  Solaris::init_signal_mem();
4644  Solaris::install_signal_handlers();
4645
4646  if (libjsigversion < JSIG_VERSION_1_4_1) {
4647    Maxlibjsigsigs = OLDMAXSIGNUM;
4648  }
4649
4650  // initialize synchronization primitives to use either thread or
4651  // lwp synchronization (controlled by UseLWPSynchronization)
4652  Solaris::synchronization_init();
4653
4654  if (MaxFDLimit) {
4655    // set the number of file descriptors to max. print out error
4656    // if getrlimit/setrlimit fails but continue regardless.
4657    struct rlimit nbr_files;
4658    int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
4659    if (status != 0) {
4660      if (PrintMiscellaneous && (Verbose || WizardMode))
4661        perror("os::init_2 getrlimit failed");
4662    } else {
4663      nbr_files.rlim_cur = nbr_files.rlim_max;
4664      status = setrlimit(RLIMIT_NOFILE, &nbr_files);
4665      if (status != 0) {
4666        if (PrintMiscellaneous && (Verbose || WizardMode))
4667          perror("os::init_2 setrlimit failed");
4668      }
4669    }
4670  }
4671
4672  // Calculate theoretical max. size of Threads to guard gainst
4673  // artifical out-of-memory situations, where all available address-
4674  // space has been reserved by thread stacks. Default stack size is 1Mb.
4675  size_t pre_thread_stack_size = (JavaThread::stack_size_at_create()) ?
4676    JavaThread::stack_size_at_create() : (1*K*K);
4677  assert(pre_thread_stack_size != 0, "Must have a stack");
4678  // Solaris has a maximum of 4Gb of user programs. Calculate the thread limit when
4679  // we should start doing Virtual Memory banging. Currently when the threads will
4680  // have used all but 200Mb of space.
4681  size_t max_address_space = ((unsigned int)4 * K * K * K) - (200 * K * K);
4682  Solaris::_os_thread_limit = max_address_space / pre_thread_stack_size;
4683
4684  // at-exit methods are called in the reverse order of their registration.
4685  // In Solaris 7 and earlier, atexit functions are called on return from
4686  // main or as a result of a call to exit(3C). There can be only 32 of
4687  // these functions registered and atexit() does not set errno. In Solaris
4688  // 8 and later, there is no limit to the number of functions registered
4689  // and atexit() sets errno. In addition, in Solaris 8 and later, atexit
4690  // functions are called upon dlclose(3DL) in addition to return from main
4691  // and exit(3C).
4692
4693  if (PerfAllowAtExitRegistration) {
4694    // only register atexit functions if PerfAllowAtExitRegistration is set.
4695    // atexit functions can be delayed until process exit time, which
4696    // can be problematic for embedded VM situations. Embedded VMs should
4697    // call DestroyJavaVM() to assure that VM resources are released.
4698
4699    // note: perfMemory_exit_helper atexit function may be removed in
4700    // the future if the appropriate cleanup code can be added to the
4701    // VM_Exit VMOperation's doit method.
4702    if (atexit(perfMemory_exit_helper) != 0) {
4703      warning("os::init2 atexit(perfMemory_exit_helper) failed");
4704    }
4705  }
4706
4707  // Init pset_loadavg function pointer
4708  init_pset_getloadavg_ptr();
4709
4710  return JNI_OK;
4711}
4712
4713void os::init_3(void) {
4714  return;
4715}
4716
4717// Mark the polling page as unreadable
4718void os::make_polling_page_unreadable(void) {
4719  if (mprotect((char *)_polling_page, page_size, PROT_NONE) != 0)
4720    fatal("Could not disable polling page");
4721};
4722
4723// Mark the polling page as readable
4724void os::make_polling_page_readable(void) {
4725  if (mprotect((char *)_polling_page, page_size, PROT_READ) != 0)
4726    fatal("Could not enable polling page");
4727};
4728
4729// OS interface.
4730
4731bool os::check_heap(bool force) { return true; }
4732
4733typedef int (*vsnprintf_t)(char* buf, size_t count, const char* fmt, va_list argptr);
4734static vsnprintf_t sol_vsnprintf = NULL;
4735
4736int local_vsnprintf(char* buf, size_t count, const char* fmt, va_list argptr) {
4737  if (!sol_vsnprintf) {
4738    //search  for the named symbol in the objects that were loaded after libjvm
4739    void* where = RTLD_NEXT;
4740    if ((sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "__vsnprintf"))) == NULL)
4741        sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "vsnprintf"));
4742    if (!sol_vsnprintf){
4743      //search  for the named symbol in the objects that were loaded before libjvm
4744      where = RTLD_DEFAULT;
4745      if ((sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "__vsnprintf"))) == NULL)
4746        sol_vsnprintf = CAST_TO_FN_PTR(vsnprintf_t, dlsym(where, "vsnprintf"));
4747      assert(sol_vsnprintf != NULL, "vsnprintf not found");
4748    }
4749  }
4750  return (*sol_vsnprintf)(buf, count, fmt, argptr);
4751}
4752
4753
4754// Is a (classpath) directory empty?
4755bool os::dir_is_empty(const char* path) {
4756  DIR *dir = NULL;
4757  struct dirent *ptr;
4758
4759  dir = opendir(path);
4760  if (dir == NULL) return true;
4761
4762  /* Scan the directory */
4763  bool result = true;
4764  char buf[sizeof(struct dirent) + MAX_PATH];
4765  struct dirent *dbuf = (struct dirent *) buf;
4766  while (result && (ptr = readdir(dir, dbuf)) != NULL) {
4767    if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
4768      result = false;
4769    }
4770  }
4771  closedir(dir);
4772  return result;
4773}
4774
4775// This code originates from JDK's sysOpen and open64_w
4776// from src/solaris/hpi/src/system_md.c
4777
4778#ifndef O_DELETE
4779#define O_DELETE 0x10000
4780#endif
4781
4782// Open a file. Unlink the file immediately after open returns
4783// if the specified oflag has the O_DELETE flag set.
4784// O_DELETE is used only in j2se/src/share/native/java/util/zip/ZipFile.c
4785
4786int os::open(const char *path, int oflag, int mode) {
4787  if (strlen(path) > MAX_PATH - 1) {
4788    errno = ENAMETOOLONG;
4789    return -1;
4790  }
4791  int fd;
4792  int o_delete = (oflag & O_DELETE);
4793  oflag = oflag & ~O_DELETE;
4794
4795  fd = ::open64(path, oflag, mode);
4796  if (fd == -1) return -1;
4797
4798  //If the open succeeded, the file might still be a directory
4799  {
4800    struct stat64 buf64;
4801    int ret = ::fstat64(fd, &buf64);
4802    int st_mode = buf64.st_mode;
4803
4804    if (ret != -1) {
4805      if ((st_mode & S_IFMT) == S_IFDIR) {
4806        errno = EISDIR;
4807        ::close(fd);
4808        return -1;
4809      }
4810    } else {
4811      ::close(fd);
4812      return -1;
4813    }
4814  }
4815    /*
4816     * 32-bit Solaris systems suffer from:
4817     *
4818     * - an historical default soft limit of 256 per-process file
4819     *   descriptors that is too low for many Java programs.
4820     *
4821     * - a design flaw where file descriptors created using stdio
4822     *   fopen must be less than 256, _even_ when the first limit above
4823     *   has been raised.  This can cause calls to fopen (but not calls to
4824     *   open, for example) to fail mysteriously, perhaps in 3rd party
4825     *   native code (although the JDK itself uses fopen).  One can hardly
4826     *   criticize them for using this most standard of all functions.
4827     *
4828     * We attempt to make everything work anyways by:
4829     *
4830     * - raising the soft limit on per-process file descriptors beyond
4831     *   256
4832     *
4833     * - As of Solaris 10u4, we can request that Solaris raise the 256
4834     *   stdio fopen limit by calling function enable_extended_FILE_stdio.
4835     *   This is done in init_2 and recorded in enabled_extended_FILE_stdio
4836     *
4837     * - If we are stuck on an old (pre 10u4) Solaris system, we can
4838     *   workaround the bug by remapping non-stdio file descriptors below
4839     *   256 to ones beyond 256, which is done below.
4840     *
4841     * See:
4842     * 1085341: 32-bit stdio routines should support file descriptors >255
4843     * 6533291: Work around 32-bit Solaris stdio limit of 256 open files
4844     * 6431278: Netbeans crash on 32 bit Solaris: need to call
4845     *          enable_extended_FILE_stdio() in VM initialisation
4846     * Giri Mandalika's blog
4847     * http://technopark02.blogspot.com/2005_05_01_archive.html
4848     */
4849#ifndef  _LP64
4850     if ((!enabled_extended_FILE_stdio) && fd < 256) {
4851         int newfd = ::fcntl(fd, F_DUPFD, 256);
4852         if (newfd != -1) {
4853             ::close(fd);
4854             fd = newfd;
4855         }
4856     }
4857#endif // 32-bit Solaris
4858    /*
4859     * All file descriptors that are opened in the JVM and not
4860     * specifically destined for a subprocess should have the
4861     * close-on-exec flag set.  If we don't set it, then careless 3rd
4862     * party native code might fork and exec without closing all
4863     * appropriate file descriptors (e.g. as we do in closeDescriptors in
4864     * UNIXProcess.c), and this in turn might:
4865     *
4866     * - cause end-of-file to fail to be detected on some file
4867     *   descriptors, resulting in mysterious hangs, or
4868     *
4869     * - might cause an fopen in the subprocess to fail on a system
4870     *   suffering from bug 1085341.
4871     *
4872     * (Yes, the default setting of the close-on-exec flag is a Unix
4873     * design flaw)
4874     *
4875     * See:
4876     * 1085341: 32-bit stdio routines should support file descriptors >255
4877     * 4843136: (process) pipe file descriptor from Runtime.exec not being closed
4878     * 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
4879     */
4880#ifdef FD_CLOEXEC
4881    {
4882        int flags = ::fcntl(fd, F_GETFD);
4883        if (flags != -1)
4884            ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4885    }
4886#endif
4887
4888  if (o_delete != 0) {
4889    ::unlink(path);
4890  }
4891  return fd;
4892}
4893
4894// create binary file, rewriting existing file if required
4895int os::create_binary_file(const char* path, bool rewrite_existing) {
4896  int oflags = O_WRONLY | O_CREAT;
4897  if (!rewrite_existing) {
4898    oflags |= O_EXCL;
4899  }
4900  return ::open64(path, oflags, S_IREAD | S_IWRITE);
4901}
4902
4903// return current position of file pointer
4904jlong os::current_file_offset(int fd) {
4905  return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
4906}
4907
4908// move file pointer to the specified offset
4909jlong os::seek_to_file_offset(int fd, jlong offset) {
4910  return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
4911}
4912
4913jlong os::lseek(int fd, jlong offset, int whence) {
4914  return (jlong) ::lseek64(fd, offset, whence);
4915}
4916
4917char * os::native_path(char *path) {
4918  return path;
4919}
4920
4921int os::ftruncate(int fd, jlong length) {
4922  return ::ftruncate64(fd, length);
4923}
4924
4925int os::fsync(int fd)  {
4926  RESTARTABLE_RETURN_INT(::fsync(fd));
4927}
4928
4929int os::available(int fd, jlong *bytes) {
4930  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
4931          "Assumed _thread_in_native");
4932  jlong cur, end;
4933  int mode;
4934  struct stat64 buf64;
4935
4936  if (::fstat64(fd, &buf64) >= 0) {
4937    mode = buf64.st_mode;
4938    if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
4939      int n,ioctl_return;
4940
4941      RESTARTABLE(::ioctl(fd, FIONREAD, &n), ioctl_return);
4942      if (ioctl_return>= 0) {
4943          *bytes = n;
4944        return 1;
4945      }
4946    }
4947  }
4948  if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
4949    return 0;
4950  } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
4951    return 0;
4952  } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
4953    return 0;
4954  }
4955  *bytes = end - cur;
4956  return 1;
4957}
4958
4959// Map a block of memory.
4960char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
4961                     char *addr, size_t bytes, bool read_only,
4962                     bool allow_exec) {
4963  int prot;
4964  int flags;
4965
4966  if (read_only) {
4967    prot = PROT_READ;
4968    flags = MAP_SHARED;
4969  } else {
4970    prot = PROT_READ | PROT_WRITE;
4971    flags = MAP_PRIVATE;
4972  }
4973
4974  if (allow_exec) {
4975    prot |= PROT_EXEC;
4976  }
4977
4978  if (addr != NULL) {
4979    flags |= MAP_FIXED;
4980  }
4981
4982  char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
4983                                     fd, file_offset);
4984  if (mapped_address == MAP_FAILED) {
4985    return NULL;
4986  }
4987  return mapped_address;
4988}
4989
4990
4991// Remap a block of memory.
4992char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
4993                       char *addr, size_t bytes, bool read_only,
4994                       bool allow_exec) {
4995  // same as map_memory() on this OS
4996  return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
4997                        allow_exec);
4998}
4999
5000
5001// Unmap a block of memory.
5002bool os::pd_unmap_memory(char* addr, size_t bytes) {
5003  return munmap(addr, bytes) == 0;
5004}
5005
5006void os::pause() {
5007  char filename[MAX_PATH];
5008  if (PauseAtStartupFile && PauseAtStartupFile[0]) {
5009    jio_snprintf(filename, MAX_PATH, PauseAtStartupFile);
5010  } else {
5011    jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
5012  }
5013
5014  int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
5015  if (fd != -1) {
5016    struct stat buf;
5017    ::close(fd);
5018    while (::stat(filename, &buf) == 0) {
5019      (void)::poll(NULL, 0, 100);
5020    }
5021  } else {
5022    jio_fprintf(stderr,
5023      "Could not open pause file '%s', continuing immediately.\n", filename);
5024  }
5025}
5026
5027#ifndef PRODUCT
5028#ifdef INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS
5029// Turn this on if you need to trace synch operations.
5030// Set RECORD_SYNCH_LIMIT to a large-enough value,
5031// and call record_synch_enable and record_synch_disable
5032// around the computation of interest.
5033
5034void record_synch(char* name, bool returning);  // defined below
5035
5036class RecordSynch {
5037  char* _name;
5038 public:
5039  RecordSynch(char* name) :_name(name)
5040                 { record_synch(_name, false); }
5041  ~RecordSynch() { record_synch(_name,   true);  }
5042};
5043
5044#define CHECK_SYNCH_OP(ret, name, params, args, inner)          \
5045extern "C" ret name params {                                    \
5046  typedef ret name##_t params;                                  \
5047  static name##_t* implem = NULL;                               \
5048  static int callcount = 0;                                     \
5049  if (implem == NULL) {                                         \
5050    implem = (name##_t*) dlsym(RTLD_NEXT, #name);               \
5051    if (implem == NULL)  fatal(dlerror());                      \
5052  }                                                             \
5053  ++callcount;                                                  \
5054  RecordSynch _rs(#name);                                       \
5055  inner;                                                        \
5056  return implem args;                                           \
5057}
5058// in dbx, examine callcounts this way:
5059// for n in $(eval whereis callcount | awk '{print $2}'); do print $n; done
5060
5061#define CHECK_POINTER_OK(p) \
5062  (!Universe::is_fully_initialized() || !Universe::is_reserved_heap((oop)(p)))
5063#define CHECK_MU \
5064  if (!CHECK_POINTER_OK(mu)) fatal("Mutex must be in C heap only.");
5065#define CHECK_CV \
5066  if (!CHECK_POINTER_OK(cv)) fatal("Condvar must be in C heap only.");
5067#define CHECK_P(p) \
5068  if (!CHECK_POINTER_OK(p))  fatal(false,  "Pointer must be in C heap only.");
5069
5070#define CHECK_MUTEX(mutex_op) \
5071CHECK_SYNCH_OP(int, mutex_op, (mutex_t *mu), (mu), CHECK_MU);
5072
5073CHECK_MUTEX(   mutex_lock)
5074CHECK_MUTEX(  _mutex_lock)
5075CHECK_MUTEX( mutex_unlock)
5076CHECK_MUTEX(_mutex_unlock)
5077CHECK_MUTEX( mutex_trylock)
5078CHECK_MUTEX(_mutex_trylock)
5079
5080#define CHECK_COND(cond_op) \
5081CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu), (cv, mu), CHECK_MU;CHECK_CV);
5082
5083CHECK_COND( cond_wait);
5084CHECK_COND(_cond_wait);
5085CHECK_COND(_cond_wait_cancel);
5086
5087#define CHECK_COND2(cond_op) \
5088CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu, timestruc_t* ts), (cv, mu, ts), CHECK_MU;CHECK_CV);
5089
5090CHECK_COND2( cond_timedwait);
5091CHECK_COND2(_cond_timedwait);
5092CHECK_COND2(_cond_timedwait_cancel);
5093
5094// do the _lwp_* versions too
5095#define mutex_t lwp_mutex_t
5096#define cond_t  lwp_cond_t
5097CHECK_MUTEX(  _lwp_mutex_lock)
5098CHECK_MUTEX(  _lwp_mutex_unlock)
5099CHECK_MUTEX(  _lwp_mutex_trylock)
5100CHECK_MUTEX( __lwp_mutex_lock)
5101CHECK_MUTEX( __lwp_mutex_unlock)
5102CHECK_MUTEX( __lwp_mutex_trylock)
5103CHECK_MUTEX(___lwp_mutex_lock)
5104CHECK_MUTEX(___lwp_mutex_unlock)
5105
5106CHECK_COND(  _lwp_cond_wait);
5107CHECK_COND( __lwp_cond_wait);
5108CHECK_COND(___lwp_cond_wait);
5109
5110CHECK_COND2(  _lwp_cond_timedwait);
5111CHECK_COND2( __lwp_cond_timedwait);
5112#undef mutex_t
5113#undef cond_t
5114
5115CHECK_SYNCH_OP(int, _lwp_suspend2,       (int lwp, int *n), (lwp, n), 0);
5116CHECK_SYNCH_OP(int,__lwp_suspend2,       (int lwp, int *n), (lwp, n), 0);
5117CHECK_SYNCH_OP(int, _lwp_kill,           (int lwp, int n),  (lwp, n), 0);
5118CHECK_SYNCH_OP(int,__lwp_kill,           (int lwp, int n),  (lwp, n), 0);
5119CHECK_SYNCH_OP(int, _lwp_sema_wait,      (lwp_sema_t* p),   (p),  CHECK_P(p));
5120CHECK_SYNCH_OP(int,__lwp_sema_wait,      (lwp_sema_t* p),   (p),  CHECK_P(p));
5121CHECK_SYNCH_OP(int, _lwp_cond_broadcast, (lwp_cond_t* cv),  (cv), CHECK_CV);
5122CHECK_SYNCH_OP(int,__lwp_cond_broadcast, (lwp_cond_t* cv),  (cv), CHECK_CV);
5123
5124
5125// recording machinery:
5126
5127enum { RECORD_SYNCH_LIMIT = 200 };
5128char* record_synch_name[RECORD_SYNCH_LIMIT];
5129void* record_synch_arg0ptr[RECORD_SYNCH_LIMIT];
5130bool record_synch_returning[RECORD_SYNCH_LIMIT];
5131thread_t record_synch_thread[RECORD_SYNCH_LIMIT];
5132int record_synch_count = 0;
5133bool record_synch_enabled = false;
5134
5135// in dbx, examine recorded data this way:
5136// for n in name arg0ptr returning thread; do print record_synch_$n[0..record_synch_count-1]; done
5137
5138void record_synch(char* name, bool returning) {
5139  if (record_synch_enabled) {
5140    if (record_synch_count < RECORD_SYNCH_LIMIT) {
5141      record_synch_name[record_synch_count] = name;
5142      record_synch_returning[record_synch_count] = returning;
5143      record_synch_thread[record_synch_count] = thr_self();
5144      record_synch_arg0ptr[record_synch_count] = &name;
5145      record_synch_count++;
5146    }
5147    // put more checking code here:
5148    // ...
5149  }
5150}
5151
5152void record_synch_enable() {
5153  // start collecting trace data, if not already doing so
5154  if (!record_synch_enabled)  record_synch_count = 0;
5155  record_synch_enabled = true;
5156}
5157
5158void record_synch_disable() {
5159  // stop collecting trace data
5160  record_synch_enabled = false;
5161}
5162
5163#endif // INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS
5164#endif // PRODUCT
5165
5166const intptr_t thr_time_off  = (intptr_t)(&((prusage_t *)(NULL))->pr_utime);
5167const intptr_t thr_time_size = (intptr_t)(&((prusage_t *)(NULL))->pr_ttime) -
5168                               (intptr_t)(&((prusage_t *)(NULL))->pr_utime);
5169
5170
5171// JVMTI & JVM monitoring and management support
5172// The thread_cpu_time() and current_thread_cpu_time() are only
5173// supported if is_thread_cpu_time_supported() returns true.
5174// They are not supported on Solaris T1.
5175
5176// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
5177// are used by JVM M&M and JVMTI to get user+sys or user CPU time
5178// of a thread.
5179//
5180// current_thread_cpu_time() and thread_cpu_time(Thread *)
5181// returns the fast estimate available on the platform.
5182
5183// hrtime_t gethrvtime() return value includes
5184// user time but does not include system time
5185jlong os::current_thread_cpu_time() {
5186  return (jlong) gethrvtime();
5187}
5188
5189jlong os::thread_cpu_time(Thread *thread) {
5190  // return user level CPU time only to be consistent with
5191  // what current_thread_cpu_time returns.
5192  // thread_cpu_time_info() must be changed if this changes
5193  return os::thread_cpu_time(thread, false /* user time only */);
5194}
5195
5196jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
5197  if (user_sys_cpu_time) {
5198    return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
5199  } else {
5200    return os::current_thread_cpu_time();
5201  }
5202}
5203
5204jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5205  char proc_name[64];
5206  int count;
5207  prusage_t prusage;
5208  jlong lwp_time;
5209  int fd;
5210
5211  sprintf(proc_name, "/proc/%d/lwp/%d/lwpusage",
5212                     getpid(),
5213                     thread->osthread()->lwp_id());
5214  fd = ::open(proc_name, O_RDONLY);
5215  if (fd == -1) return -1;
5216
5217  do {
5218    count = ::pread(fd,
5219                  (void *)&prusage.pr_utime,
5220                  thr_time_size,
5221                  thr_time_off);
5222  } while (count < 0 && errno == EINTR);
5223  ::close(fd);
5224  if (count < 0) return -1;
5225
5226  if (user_sys_cpu_time) {
5227    // user + system CPU time
5228    lwp_time = (((jlong)prusage.pr_stime.tv_sec +
5229                 (jlong)prusage.pr_utime.tv_sec) * (jlong)1000000000) +
5230                 (jlong)prusage.pr_stime.tv_nsec +
5231                 (jlong)prusage.pr_utime.tv_nsec;
5232  } else {
5233    // user level CPU time only
5234    lwp_time = ((jlong)prusage.pr_utime.tv_sec * (jlong)1000000000) +
5235                (jlong)prusage.pr_utime.tv_nsec;
5236  }
5237
5238  return (lwp_time);
5239}
5240
5241void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5242  info_ptr->max_value = ALL_64_BITS;      // will not wrap in less than 64 bits
5243  info_ptr->may_skip_backward = false;    // elapsed time not wall time
5244  info_ptr->may_skip_forward = false;     // elapsed time not wall time
5245  info_ptr->kind = JVMTI_TIMER_USER_CPU;  // only user time is returned
5246}
5247
5248void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5249  info_ptr->max_value = ALL_64_BITS;      // will not wrap in less than 64 bits
5250  info_ptr->may_skip_backward = false;    // elapsed time not wall time
5251  info_ptr->may_skip_forward = false;     // elapsed time not wall time
5252  info_ptr->kind = JVMTI_TIMER_USER_CPU;  // only user time is returned
5253}
5254
5255bool os::is_thread_cpu_time_supported() {
5256  return true;
5257}
5258
5259// System loadavg support.  Returns -1 if load average cannot be obtained.
5260// Return the load average for our processor set if the primitive exists
5261// (Solaris 9 and later).  Otherwise just return system wide loadavg.
5262int os::loadavg(double loadavg[], int nelem) {
5263  if (pset_getloadavg_ptr != NULL) {
5264    return (*pset_getloadavg_ptr)(PS_MYID, loadavg, nelem);
5265  } else {
5266    return ::getloadavg(loadavg, nelem);
5267  }
5268}
5269
5270//---------------------------------------------------------------------------------
5271
5272bool os::find(address addr, outputStream* st) {
5273  Dl_info dlinfo;
5274  memset(&dlinfo, 0, sizeof(dlinfo));
5275  if (dladdr(addr, &dlinfo) != 0) {
5276    st->print(PTR_FORMAT ": ", addr);
5277    if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
5278      st->print("%s+%#lx", dlinfo.dli_sname, addr-(intptr_t)dlinfo.dli_saddr);
5279    } else if (dlinfo.dli_fbase != NULL)
5280      st->print("<offset %#lx>", addr-(intptr_t)dlinfo.dli_fbase);
5281    else
5282      st->print("<absolute address>");
5283    if (dlinfo.dli_fname != NULL) {
5284      st->print(" in %s", dlinfo.dli_fname);
5285    }
5286    if (dlinfo.dli_fbase != NULL) {
5287      st->print(" at " PTR_FORMAT, dlinfo.dli_fbase);
5288    }
5289    st->cr();
5290
5291    if (Verbose) {
5292      // decode some bytes around the PC
5293      address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
5294      address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
5295      address       lowest = (address) dlinfo.dli_sname;
5296      if (!lowest)  lowest = (address) dlinfo.dli_fbase;
5297      if (begin < lowest)  begin = lowest;
5298      Dl_info dlinfo2;
5299      if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
5300          && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin)
5301        end = (address) dlinfo2.dli_saddr;
5302      Disassembler::decode(begin, end, st);
5303    }
5304    return true;
5305  }
5306  return false;
5307}
5308
5309// Following function has been added to support HotSparc's libjvm.so running
5310// under Solaris production JDK 1.2.2 / 1.3.0.  These came from
5311// src/solaris/hpi/native_threads in the EVM codebase.
5312//
5313// NOTE: This is no longer needed in the 1.3.1 and 1.4 production release
5314// libraries and should thus be removed. We will leave it behind for a while
5315// until we no longer want to able to run on top of 1.3.0 Solaris production
5316// JDK. See 4341971.
5317
5318#define STACK_SLACK 0x800
5319
5320extern "C" {
5321  intptr_t sysThreadAvailableStackWithSlack() {
5322    stack_t st;
5323    intptr_t retval, stack_top;
5324    retval = thr_stksegment(&st);
5325    assert(retval == 0, "incorrect return value from thr_stksegment");
5326    assert((address)&st < (address)st.ss_sp, "Invalid stack base returned");
5327    assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned");
5328    stack_top=(intptr_t)st.ss_sp-st.ss_size;
5329    return ((intptr_t)&stack_top - stack_top - STACK_SLACK);
5330  }
5331}
5332
5333// ObjectMonitor park-unpark infrastructure ...
5334//
5335// We implement Solaris and Linux PlatformEvents with the
5336// obvious condvar-mutex-flag triple.
5337// Another alternative that works quite well is pipes:
5338// Each PlatformEvent consists of a pipe-pair.
5339// The thread associated with the PlatformEvent
5340// calls park(), which reads from the input end of the pipe.
5341// Unpark() writes into the other end of the pipe.
5342// The write-side of the pipe must be set NDELAY.
5343// Unfortunately pipes consume a large # of handles.
5344// Native solaris lwp_park() and lwp_unpark() work nicely, too.
5345// Using pipes for the 1st few threads might be workable, however.
5346//
5347// park() is permitted to return spuriously.
5348// Callers of park() should wrap the call to park() in
5349// an appropriate loop.  A litmus test for the correct
5350// usage of park is the following: if park() were modified
5351// to immediately return 0 your code should still work,
5352// albeit degenerating to a spin loop.
5353//
5354// An interesting optimization for park() is to use a trylock()
5355// to attempt to acquire the mutex.  If the trylock() fails
5356// then we know that a concurrent unpark() operation is in-progress.
5357// in that case the park() code could simply set _count to 0
5358// and return immediately.  The subsequent park() operation *might*
5359// return immediately.  That's harmless as the caller of park() is
5360// expected to loop.  By using trylock() we will have avoided a
5361// avoided a context switch caused by contention on the per-thread mutex.
5362//
5363// TODO-FIXME:
5364// 1.  Reconcile Doug's JSR166 j.u.c park-unpark with the
5365//     objectmonitor implementation.
5366// 2.  Collapse the JSR166 parker event, and the
5367//     objectmonitor ParkEvent into a single "Event" construct.
5368// 3.  In park() and unpark() add:
5369//     assert (Thread::current() == AssociatedWith).
5370// 4.  add spurious wakeup injection on a -XX:EarlyParkReturn=N switch.
5371//     1-out-of-N park() operations will return immediately.
5372//
5373// _Event transitions in park()
5374//   -1 => -1 : illegal
5375//    1 =>  0 : pass - return immediately
5376//    0 => -1 : block
5377//
5378// _Event serves as a restricted-range semaphore.
5379//
5380// Another possible encoding of _Event would be with
5381// explicit "PARKED" == 01b and "SIGNALED" == 10b bits.
5382//
5383// TODO-FIXME: add DTRACE probes for:
5384// 1.   Tx parks
5385// 2.   Ty unparks Tx
5386// 3.   Tx resumes from park
5387
5388
5389// value determined through experimentation
5390#define ROUNDINGFIX 11
5391
5392// utility to compute the abstime argument to timedwait.
5393// TODO-FIXME: switch from compute_abstime() to unpackTime().
5394
5395static timestruc_t* compute_abstime(timestruc_t* abstime, jlong millis) {
5396  // millis is the relative timeout time
5397  // abstime will be the absolute timeout time
5398  if (millis < 0)  millis = 0;
5399  struct timeval now;
5400  int status = gettimeofday(&now, NULL);
5401  assert(status == 0, "gettimeofday");
5402  jlong seconds = millis / 1000;
5403  jlong max_wait_period;
5404
5405  if (UseLWPSynchronization) {
5406    // forward port of fix for 4275818 (not sleeping long enough)
5407    // There was a bug in Solaris 6, 7 and pre-patch 5 of 8 where
5408    // _lwp_cond_timedwait() used a round_down algorithm rather
5409    // than a round_up. For millis less than our roundfactor
5410    // it rounded down to 0 which doesn't meet the spec.
5411    // For millis > roundfactor we may return a bit sooner, but
5412    // since we can not accurately identify the patch level and
5413    // this has already been fixed in Solaris 9 and 8 we will
5414    // leave it alone rather than always rounding down.
5415
5416    if (millis > 0 && millis < ROUNDINGFIX) millis = ROUNDINGFIX;
5417       // It appears that when we go directly through Solaris _lwp_cond_timedwait()
5418           // the acceptable max time threshold is smaller than for libthread on 2.5.1 and 2.6
5419           max_wait_period = 21000000;
5420  } else {
5421    max_wait_period = 50000000;
5422  }
5423  millis %= 1000;
5424  if (seconds > max_wait_period) {      // see man cond_timedwait(3T)
5425     seconds = max_wait_period;
5426  }
5427  abstime->tv_sec = now.tv_sec  + seconds;
5428  long       usec = now.tv_usec + millis * 1000;
5429  if (usec >= 1000000) {
5430    abstime->tv_sec += 1;
5431    usec -= 1000000;
5432  }
5433  abstime->tv_nsec = usec * 1000;
5434  return abstime;
5435}
5436
5437void os::PlatformEvent::park() {           // AKA: down()
5438  // Invariant: Only the thread associated with the Event/PlatformEvent
5439  // may call park().
5440  assert(_nParked == 0, "invariant");
5441
5442  int v;
5443  for (;;) {
5444      v = _Event;
5445      if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
5446  }
5447  guarantee(v >= 0, "invariant");
5448  if (v == 0) {
5449     // Do this the hard way by blocking ...
5450     // See http://monaco.sfbay/detail.jsf?cr=5094058.
5451     // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking.
5452     // Only for SPARC >= V8PlusA
5453#if defined(__sparc) && defined(COMPILER2)
5454     if (ClearFPUAtPark) { _mark_fpu_nosave(); }
5455#endif
5456     int status = os::Solaris::mutex_lock(_mutex);
5457     assert_status(status == 0, status, "mutex_lock");
5458     guarantee(_nParked == 0, "invariant");
5459     ++_nParked;
5460     while (_Event < 0) {
5461        // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
5462        // Treat this the same as if the wait was interrupted
5463        // With usr/lib/lwp going to kernel, always handle ETIME
5464        status = os::Solaris::cond_wait(_cond, _mutex);
5465        if (status == ETIME) status = EINTR;
5466        assert_status(status == 0 || status == EINTR, status, "cond_wait");
5467     }
5468     --_nParked;
5469     _Event = 0;
5470     status = os::Solaris::mutex_unlock(_mutex);
5471     assert_status(status == 0, status, "mutex_unlock");
5472    // Paranoia to ensure our locked and lock-free paths interact
5473    // correctly with each other.
5474    OrderAccess::fence();
5475  }
5476}
5477
5478int os::PlatformEvent::park(jlong millis) {
5479  guarantee(_nParked == 0, "invariant");
5480  int v;
5481  for (;;) {
5482      v = _Event;
5483      if (Atomic::cmpxchg(v-1, &_Event, v) == v) break;
5484  }
5485  guarantee(v >= 0, "invariant");
5486  if (v != 0) return OS_OK;
5487
5488  int ret = OS_TIMEOUT;
5489  timestruc_t abst;
5490  compute_abstime(&abst, millis);
5491
5492  // See http://monaco.sfbay/detail.jsf?cr=5094058.
5493  // For Solaris SPARC set fprs.FEF=0 prior to parking.
5494  // Only for SPARC >= V8PlusA
5495#if defined(__sparc) && defined(COMPILER2)
5496 if (ClearFPUAtPark) { _mark_fpu_nosave(); }
5497#endif
5498  int status = os::Solaris::mutex_lock(_mutex);
5499  assert_status(status == 0, status, "mutex_lock");
5500  guarantee(_nParked == 0, "invariant");
5501  ++_nParked;
5502  while (_Event < 0) {
5503     int status = os::Solaris::cond_timedwait(_cond, _mutex, &abst);
5504     assert_status(status == 0 || status == EINTR ||
5505                   status == ETIME || status == ETIMEDOUT,
5506                   status, "cond_timedwait");
5507     if (!FilterSpuriousWakeups) break;                // previous semantics
5508     if (status == ETIME || status == ETIMEDOUT) break;
5509     // We consume and ignore EINTR and spurious wakeups.
5510  }
5511  --_nParked;
5512  if (_Event >= 0) ret = OS_OK;
5513  _Event = 0;
5514  status = os::Solaris::mutex_unlock(_mutex);
5515  assert_status(status == 0, status, "mutex_unlock");
5516  // Paranoia to ensure our locked and lock-free paths interact
5517  // correctly with each other.
5518  OrderAccess::fence();
5519  return ret;
5520}
5521
5522void os::PlatformEvent::unpark() {
5523  // Transitions for _Event:
5524  //    0 :=> 1
5525  //    1 :=> 1
5526  //   -1 :=> either 0 or 1; must signal target thread
5527  //          That is, we can safely transition _Event from -1 to either
5528  //          0 or 1.
5529  // See also: "Semaphores in Plan 9" by Mullender & Cox
5530  //
5531  // Note: Forcing a transition from "-1" to "1" on an unpark() means
5532  // that it will take two back-to-back park() calls for the owning
5533  // thread to block. This has the benefit of forcing a spurious return
5534  // from the first park() call after an unpark() call which will help
5535  // shake out uses of park() and unpark() without condition variables.
5536
5537  if (Atomic::xchg(1, &_Event) >= 0) return;
5538
5539  // If the thread associated with the event was parked, wake it.
5540  // Wait for the thread assoc with the PlatformEvent to vacate.
5541  int status = os::Solaris::mutex_lock(_mutex);
5542  assert_status(status == 0, status, "mutex_lock");
5543  int AnyWaiters = _nParked;
5544  status = os::Solaris::mutex_unlock(_mutex);
5545  assert_status(status == 0, status, "mutex_unlock");
5546  guarantee(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
5547  if (AnyWaiters != 0) {
5548    // We intentional signal *after* dropping the lock
5549    // to avoid a common class of futile wakeups.
5550    status = os::Solaris::cond_signal(_cond);
5551    assert_status(status == 0, status, "cond_signal");
5552  }
5553}
5554
5555// JSR166
5556// -------------------------------------------------------
5557
5558/*
5559 * The solaris and linux implementations of park/unpark are fairly
5560 * conservative for now, but can be improved. They currently use a
5561 * mutex/condvar pair, plus _counter.
5562 * Park decrements _counter if > 0, else does a condvar wait.  Unpark
5563 * sets count to 1 and signals condvar.  Only one thread ever waits
5564 * on the condvar. Contention seen when trying to park implies that someone
5565 * is unparking you, so don't wait. And spurious returns are fine, so there
5566 * is no need to track notifications.
5567 */
5568
5569#define MAX_SECS 100000000
5570/*
5571 * This code is common to linux and solaris and will be moved to a
5572 * common place in dolphin.
5573 *
5574 * The passed in time value is either a relative time in nanoseconds
5575 * or an absolute time in milliseconds. Either way it has to be unpacked
5576 * into suitable seconds and nanoseconds components and stored in the
5577 * given timespec structure.
5578 * Given time is a 64-bit value and the time_t used in the timespec is only
5579 * a signed-32-bit value (except on 64-bit Linux) we have to watch for
5580 * overflow if times way in the future are given. Further on Solaris versions
5581 * prior to 10 there is a restriction (see cond_timedwait) that the specified
5582 * number of seconds, in abstime, is less than current_time  + 100,000,000.
5583 * As it will be 28 years before "now + 100000000" will overflow we can
5584 * ignore overflow and just impose a hard-limit on seconds using the value
5585 * of "now + 100,000,000". This places a limit on the timeout of about 3.17
5586 * years from "now".
5587 */
5588static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
5589  assert(time > 0, "convertTime");
5590
5591  struct timeval now;
5592  int status = gettimeofday(&now, NULL);
5593  assert(status == 0, "gettimeofday");
5594
5595  time_t max_secs = now.tv_sec + MAX_SECS;
5596
5597  if (isAbsolute) {
5598    jlong secs = time / 1000;
5599    if (secs > max_secs) {
5600      absTime->tv_sec = max_secs;
5601    }
5602    else {
5603      absTime->tv_sec = secs;
5604    }
5605    absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC;
5606  }
5607  else {
5608    jlong secs = time / NANOSECS_PER_SEC;
5609    if (secs >= MAX_SECS) {
5610      absTime->tv_sec = max_secs;
5611      absTime->tv_nsec = 0;
5612    }
5613    else {
5614      absTime->tv_sec = now.tv_sec + secs;
5615      absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000;
5616      if (absTime->tv_nsec >= NANOSECS_PER_SEC) {
5617        absTime->tv_nsec -= NANOSECS_PER_SEC;
5618        ++absTime->tv_sec; // note: this must be <= max_secs
5619      }
5620    }
5621  }
5622  assert(absTime->tv_sec >= 0, "tv_sec < 0");
5623  assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs");
5624  assert(absTime->tv_nsec >= 0, "tv_nsec < 0");
5625  assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec");
5626}
5627
5628void Parker::park(bool isAbsolute, jlong time) {
5629  // Ideally we'd do something useful while spinning, such
5630  // as calling unpackTime().
5631
5632  // Optional fast-path check:
5633  // Return immediately if a permit is available.
5634  // We depend on Atomic::xchg() having full barrier semantics
5635  // since we are doing a lock-free update to _counter.
5636  if (Atomic::xchg(0, &_counter) > 0) return;
5637
5638  // Optional fast-exit: Check interrupt before trying to wait
5639  Thread* thread = Thread::current();
5640  assert(thread->is_Java_thread(), "Must be JavaThread");
5641  JavaThread *jt = (JavaThread *)thread;
5642  if (Thread::is_interrupted(thread, false)) {
5643    return;
5644  }
5645
5646  // First, demultiplex/decode time arguments
5647  timespec absTime;
5648  if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all
5649    return;
5650  }
5651  if (time > 0) {
5652    // Warning: this code might be exposed to the old Solaris time
5653    // round-down bugs.  Grep "roundingFix" for details.
5654    unpackTime(&absTime, isAbsolute, time);
5655  }
5656
5657  // Enter safepoint region
5658  // Beware of deadlocks such as 6317397.
5659  // The per-thread Parker:: _mutex is a classic leaf-lock.
5660  // In particular a thread must never block on the Threads_lock while
5661  // holding the Parker:: mutex.  If safepoints are pending both the
5662  // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
5663  ThreadBlockInVM tbivm(jt);
5664
5665  // Don't wait if cannot get lock since interference arises from
5666  // unblocking.  Also. check interrupt before trying wait
5667  if (Thread::is_interrupted(thread, false) ||
5668      os::Solaris::mutex_trylock(_mutex) != 0) {
5669    return;
5670  }
5671
5672  int status;
5673
5674  if (_counter > 0)  { // no wait needed
5675    _counter = 0;
5676    status = os::Solaris::mutex_unlock(_mutex);
5677    assert(status == 0, "invariant");
5678    // Paranoia to ensure our locked and lock-free paths interact
5679    // correctly with each other and Java-level accesses.
5680    OrderAccess::fence();
5681    return;
5682  }
5683
5684#ifdef ASSERT
5685  // Don't catch signals while blocked; let the running threads have the signals.
5686  // (This allows a debugger to break into the running thread.)
5687  sigset_t oldsigs;
5688  sigset_t* allowdebug_blocked = os::Solaris::allowdebug_blocked_signals();
5689  thr_sigsetmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
5690#endif
5691
5692  OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
5693  jt->set_suspend_equivalent();
5694  // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
5695
5696  // Do this the hard way by blocking ...
5697  // See http://monaco.sfbay/detail.jsf?cr=5094058.
5698  // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking.
5699  // Only for SPARC >= V8PlusA
5700#if defined(__sparc) && defined(COMPILER2)
5701  if (ClearFPUAtPark) { _mark_fpu_nosave(); }
5702#endif
5703
5704  if (time == 0) {
5705    status = os::Solaris::cond_wait(_cond, _mutex);
5706  } else {
5707    status = os::Solaris::cond_timedwait (_cond, _mutex, &absTime);
5708  }
5709  // Note that an untimed cond_wait() can sometimes return ETIME on older
5710  // versions of the Solaris.
5711  assert_status(status == 0 || status == EINTR ||
5712                status == ETIME || status == ETIMEDOUT,
5713                status, "cond_timedwait");
5714
5715#ifdef ASSERT
5716  thr_sigsetmask(SIG_SETMASK, &oldsigs, NULL);
5717#endif
5718  _counter = 0;
5719  status = os::Solaris::mutex_unlock(_mutex);
5720  assert_status(status == 0, status, "mutex_unlock");
5721  // Paranoia to ensure our locked and lock-free paths interact
5722  // correctly with each other and Java-level accesses.
5723  OrderAccess::fence();
5724
5725  // If externally suspended while waiting, re-suspend
5726  if (jt->handle_special_suspend_equivalent_condition()) {
5727    jt->java_suspend_self();
5728  }
5729}
5730
5731void Parker::unpark() {
5732  int status = os::Solaris::mutex_lock(_mutex);
5733  assert(status == 0, "invariant");
5734  const int s = _counter;
5735  _counter = 1;
5736  status = os::Solaris::mutex_unlock(_mutex);
5737  assert(status == 0, "invariant");
5738
5739  if (s < 1) {
5740    status = os::Solaris::cond_signal(_cond);
5741    assert(status == 0, "invariant");
5742  }
5743}
5744
5745extern char** environ;
5746
5747// Run the specified command in a separate process. Return its exit value,
5748// or -1 on failure (e.g. can't fork a new process).
5749// Unlike system(), this function can be called from signal handler. It
5750// doesn't block SIGINT et al.
5751int os::fork_and_exec(char* cmd) {
5752  char * argv[4];
5753  argv[0] = (char *)"sh";
5754  argv[1] = (char *)"-c";
5755  argv[2] = cmd;
5756  argv[3] = NULL;
5757
5758  // fork is async-safe, fork1 is not so can't use in signal handler
5759  pid_t pid;
5760  Thread* t = ThreadLocalStorage::get_thread_slow();
5761  if (t != NULL && t->is_inside_signal_handler()) {
5762    pid = fork();
5763  } else {
5764    pid = fork1();
5765  }
5766
5767  if (pid < 0) {
5768    // fork failed
5769    warning("fork failed: %s", strerror(errno));
5770    return -1;
5771
5772  } else if (pid == 0) {
5773    // child process
5774
5775    // try to be consistent with system(), which uses "/usr/bin/sh" on Solaris
5776    execve("/usr/bin/sh", argv, environ);
5777
5778    // execve failed
5779    _exit(-1);
5780
5781  } else  {
5782    // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't
5783    // care about the actual exit code, for now.
5784
5785    int status;
5786
5787    // Wait for the child process to exit.  This returns immediately if
5788    // the child has already exited. */
5789    while (waitpid(pid, &status, 0) < 0) {
5790        switch (errno) {
5791        case ECHILD: return 0;
5792        case EINTR: break;
5793        default: return -1;
5794        }
5795    }
5796
5797    if (WIFEXITED(status)) {
5798       // The child exited normally; get its exit code.
5799       return WEXITSTATUS(status);
5800    } else if (WIFSIGNALED(status)) {
5801       // The child exited because of a signal
5802       // The best value to return is 0x80 + signal number,
5803       // because that is what all Unix shells do, and because
5804       // it allows callers to distinguish between process exit and
5805       // process death by signal.
5806       return 0x80 + WTERMSIG(status);
5807    } else {
5808       // Unknown exit code; pass it through
5809       return status;
5810    }
5811  }
5812}
5813
5814// is_headless_jre()
5815//
5816// Test for the existence of xawt/libmawt.so or libawt_xawt.so
5817// in order to report if we are running in a headless jre
5818//
5819// Since JDK8 xawt/libmawt.so was moved into the same directory
5820// as libawt.so, and renamed libawt_xawt.so
5821//
5822bool os::is_headless_jre() {
5823    struct stat statbuf;
5824    char buf[MAXPATHLEN];
5825    char libmawtpath[MAXPATHLEN];
5826    const char *xawtstr  = "/xawt/libmawt.so";
5827    const char *new_xawtstr = "/libawt_xawt.so";
5828    char *p;
5829
5830    // Get path to libjvm.so
5831    os::jvm_path(buf, sizeof(buf));
5832
5833    // Get rid of libjvm.so
5834    p = strrchr(buf, '/');
5835    if (p == NULL) return false;
5836    else *p = '\0';
5837
5838    // Get rid of client or server
5839    p = strrchr(buf, '/');
5840    if (p == NULL) return false;
5841    else *p = '\0';
5842
5843    // check xawt/libmawt.so
5844    strcpy(libmawtpath, buf);
5845    strcat(libmawtpath, xawtstr);
5846    if (::stat(libmawtpath, &statbuf) == 0) return false;
5847
5848    // check libawt_xawt.so
5849    strcpy(libmawtpath, buf);
5850    strcat(libmawtpath, new_xawtstr);
5851    if (::stat(libmawtpath, &statbuf) == 0) return false;
5852
5853    return true;
5854}
5855
5856size_t os::write(int fd, const void *buf, unsigned int nBytes) {
5857  size_t res;
5858  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5859          "Assumed _thread_in_native");
5860  RESTARTABLE((size_t) ::write(fd, buf, (size_t) nBytes), res);
5861  return res;
5862}
5863
5864int os::close(int fd) {
5865  return ::close(fd);
5866}
5867
5868int os::socket_close(int fd) {
5869  return ::close(fd);
5870}
5871
5872int os::recv(int fd, char* buf, size_t nBytes, uint flags) {
5873  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5874          "Assumed _thread_in_native");
5875  RESTARTABLE_RETURN_INT((int)::recv(fd, buf, nBytes, flags));
5876}
5877
5878int os::send(int fd, char* buf, size_t nBytes, uint flags) {
5879  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5880          "Assumed _thread_in_native");
5881  RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags));
5882}
5883
5884int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) {
5885  RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags));
5886}
5887
5888// As both poll and select can be interrupted by signals, we have to be
5889// prepared to restart the system call after updating the timeout, unless
5890// a poll() is done with timeout == -1, in which case we repeat with this
5891// "wait forever" value.
5892
5893int os::timeout(int fd, long timeout) {
5894  int res;
5895  struct timeval t;
5896  julong prevtime, newtime;
5897  static const char* aNull = 0;
5898  struct pollfd pfd;
5899  pfd.fd = fd;
5900  pfd.events = POLLIN;
5901
5902  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5903          "Assumed _thread_in_native");
5904
5905  gettimeofday(&t, &aNull);
5906  prevtime = ((julong)t.tv_sec * 1000)  +  t.tv_usec / 1000;
5907
5908  for (;;) {
5909    res = ::poll(&pfd, 1, timeout);
5910    if (res == OS_ERR && errno == EINTR) {
5911        if (timeout != -1) {
5912          gettimeofday(&t, &aNull);
5913          newtime = ((julong)t.tv_sec * 1000)  +  t.tv_usec /1000;
5914          timeout -= newtime - prevtime;
5915          if (timeout <= 0)
5916            return OS_OK;
5917          prevtime = newtime;
5918        }
5919    } else return res;
5920  }
5921}
5922
5923int os::connect(int fd, struct sockaddr *him, socklen_t len) {
5924  int _result;
5925  _result = ::connect(fd, him, len);
5926
5927  // On Solaris, when a connect() call is interrupted, the connection
5928  // can be established asynchronously (see 6343810). Subsequent calls
5929  // to connect() must check the errno value which has the semantic
5930  // described below (copied from the connect() man page). Handling
5931  // of asynchronously established connections is required for both
5932  // blocking and non-blocking sockets.
5933  //     EINTR            The  connection  attempt  was   interrupted
5934  //                      before  any data arrived by the delivery of
5935  //                      a signal. The connection, however, will  be
5936  //                      established asynchronously.
5937  //
5938  //     EINPROGRESS      The socket is non-blocking, and the connec-
5939  //                      tion  cannot  be completed immediately.
5940  //
5941  //     EALREADY         The socket is non-blocking,  and a previous
5942  //                      connection  attempt  has  not yet been com-
5943  //                      pleted.
5944  //
5945  //     EISCONN          The socket is already connected.
5946  if (_result == OS_ERR && errno == EINTR) {
5947     /* restarting a connect() changes its errno semantics */
5948     RESTARTABLE(::connect(fd, him, len), _result);
5949     /* undo these changes */
5950     if (_result == OS_ERR) {
5951       if (errno == EALREADY) {
5952         errno = EINPROGRESS; /* fall through */
5953       } else if (errno == EISCONN) {
5954         errno = 0;
5955         return OS_OK;
5956       }
5957     }
5958   }
5959   return _result;
5960 }
5961
5962int os::accept(int fd, struct sockaddr* him, socklen_t* len) {
5963  if (fd < 0) {
5964    return OS_ERR;
5965  }
5966  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5967          "Assumed _thread_in_native");
5968  RESTARTABLE_RETURN_INT((int)::accept(fd, him, len));
5969}
5970
5971int os::recvfrom(int fd, char* buf, size_t nBytes, uint flags,
5972                 sockaddr* from, socklen_t* fromlen) {
5973  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5974          "Assumed _thread_in_native");
5975  RESTARTABLE_RETURN_INT((int)::recvfrom(fd, buf, nBytes, flags, from, fromlen));
5976}
5977
5978int os::sendto(int fd, char* buf, size_t len, uint flags,
5979               struct sockaddr* to, socklen_t tolen) {
5980  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5981          "Assumed _thread_in_native");
5982  RESTARTABLE_RETURN_INT((int)::sendto(fd, buf, len, flags, to, tolen));
5983}
5984
5985int os::socket_available(int fd, jint *pbytes) {
5986  if (fd < 0) {
5987    return OS_OK;
5988  }
5989  int ret;
5990  RESTARTABLE(::ioctl(fd, FIONREAD, pbytes), ret);
5991  // note: ioctl can return 0 when successful, JVM_SocketAvailable
5992  // is expected to return 0 on failure and 1 on success to the jdk.
5993  return (ret == OS_ERR) ? 0 : 1;
5994}
5995
5996int os::bind(int fd, struct sockaddr* him, socklen_t len) {
5997  assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native,
5998          "Assumed _thread_in_native");
5999   return ::bind(fd, him, len);
6000}
6001
6002// Get the default path to the core file
6003// Returns the length of the string
6004int os::get_core_path(char* buffer, size_t bufferSize) {
6005  const char* p = get_current_directory(buffer, bufferSize);
6006
6007  if (p == NULL) {
6008    assert(p != NULL, "failed to get current directory");
6009    return 0;
6010  }
6011
6012  return strlen(buffer);
6013}
6014
6015#ifndef PRODUCT
6016void TestReserveMemorySpecial_test() {
6017  // No tests available for this platform
6018}
6019#endif
6020