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