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