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