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