1/*
2 * Copyright (c) 1999, 2017, 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#include "utilities/globalDefinitions.hpp"
26#include "prims/jvm.h"
27#include "runtime/frame.inline.hpp"
28#include "runtime/interfaceSupport.hpp"
29#include "runtime/os.hpp"
30#include "utilities/align.hpp"
31#include "utilities/macros.hpp"
32#include "utilities/vmError.hpp"
33
34#ifndef __APPLE__
35// POSIX unamed semaphores are not supported on OS X.
36#include "semaphore_posix.hpp"
37#endif
38
39#include <dlfcn.h>
40#include <pthread.h>
41#include <semaphore.h>
42#include <signal.h>
43#include <sys/resource.h>
44#include <sys/utsname.h>
45#include <time.h>
46#include <unistd.h>
47
48// Todo: provide a os::get_max_process_id() or similar. Number of processes
49// may have been configured, can be read more accurately from proc fs etc.
50#ifndef MAX_PID
51#define MAX_PID INT_MAX
52#endif
53#define IS_VALID_PID(p) (p > 0 && p < MAX_PID)
54
55// Check core dump limit and report possible place where core can be found
56void os::check_dump_limit(char* buffer, size_t bufferSize) {
57  if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && !CreateCoredumpOnCrash) {
58    jio_snprintf(buffer, bufferSize, "CreateCoredumpOnCrash is disabled from command line");
59    VMError::record_coredump_status(buffer, false);
60    return;
61  }
62
63  int n;
64  struct rlimit rlim;
65  bool success;
66
67  char core_path[PATH_MAX];
68  n = get_core_path(core_path, PATH_MAX);
69
70  if (n <= 0) {
71    jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id());
72    success = true;
73#ifdef LINUX
74  } else if (core_path[0] == '"') { // redirect to user process
75    jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path);
76    success = true;
77#endif
78  } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) {
79    jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path);
80    success = true;
81  } else {
82    switch(rlim.rlim_cur) {
83      case RLIM_INFINITY:
84        jio_snprintf(buffer, bufferSize, "%s", core_path);
85        success = true;
86        break;
87      case 0:
88        jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again");
89        success = false;
90        break;
91      default:
92        jio_snprintf(buffer, bufferSize, "%s (max size " UINT64_FORMAT " kB). To ensure a full core dump, try \"ulimit -c unlimited\" before starting Java again", core_path, uint64_t(rlim.rlim_cur) / 1024);
93        success = true;
94        break;
95    }
96  }
97
98  VMError::record_coredump_status(buffer, success);
99}
100
101int os::get_native_stack(address* stack, int frames, int toSkip) {
102  int frame_idx = 0;
103  int num_of_frames;  // number of frames captured
104  frame fr = os::current_frame();
105  while (fr.pc() && frame_idx < frames) {
106    if (toSkip > 0) {
107      toSkip --;
108    } else {
109      stack[frame_idx ++] = fr.pc();
110    }
111    if (fr.fp() == NULL || fr.cb() != NULL ||
112        fr.sender_pc() == NULL || os::is_first_C_frame(&fr)) break;
113
114    if (fr.sender_pc() && !os::is_first_C_frame(&fr)) {
115      fr = os::get_sender_for_C_frame(&fr);
116    } else {
117      break;
118    }
119  }
120  num_of_frames = frame_idx;
121  for (; frame_idx < frames; frame_idx ++) {
122    stack[frame_idx] = NULL;
123  }
124
125  return num_of_frames;
126}
127
128
129bool os::unsetenv(const char* name) {
130  assert(name != NULL, "Null pointer");
131  return (::unsetenv(name) == 0);
132}
133
134int os::get_last_error() {
135  return errno;
136}
137
138bool os::is_debugger_attached() {
139  // not implemented
140  return false;
141}
142
143void os::wait_for_keypress_at_exit(void) {
144  // don't do anything on posix platforms
145  return;
146}
147
148// Multiple threads can race in this code, and can remap over each other with MAP_FIXED,
149// so on posix, unmap the section at the start and at the end of the chunk that we mapped
150// rather than unmapping and remapping the whole chunk to get requested alignment.
151char* os::reserve_memory_aligned(size_t size, size_t alignment) {
152  assert((alignment & (os::vm_allocation_granularity() - 1)) == 0,
153      "Alignment must be a multiple of allocation granularity (page size)");
154  assert((size & (alignment -1)) == 0, "size must be 'alignment' aligned");
155
156  size_t extra_size = size + alignment;
157  assert(extra_size >= size, "overflow, size is too large to allow alignment");
158
159  char* extra_base = os::reserve_memory(extra_size, NULL, alignment);
160
161  if (extra_base == NULL) {
162    return NULL;
163  }
164
165  // Do manual alignment
166  char* aligned_base = align_up(extra_base, alignment);
167
168  // [  |                                       |  ]
169  // ^ extra_base
170  //    ^ extra_base + begin_offset == aligned_base
171  //     extra_base + begin_offset + size       ^
172  //                       extra_base + extra_size ^
173  // |<>| == begin_offset
174  //                              end_offset == |<>|
175  size_t begin_offset = aligned_base - extra_base;
176  size_t end_offset = (extra_base + extra_size) - (aligned_base + size);
177
178  if (begin_offset > 0) {
179      os::release_memory(extra_base, begin_offset);
180  }
181
182  if (end_offset > 0) {
183      os::release_memory(extra_base + begin_offset + size, end_offset);
184  }
185
186  return aligned_base;
187}
188
189int os::log_vsnprintf(char* buf, size_t len, const char* fmt, va_list args) {
190    return vsnprintf(buf, len, fmt, args);
191}
192
193int os::get_fileno(FILE* fp) {
194  return NOT_AIX(::)fileno(fp);
195}
196
197struct tm* os::gmtime_pd(const time_t* clock, struct tm*  res) {
198  return gmtime_r(clock, res);
199}
200
201void os::Posix::print_load_average(outputStream* st) {
202  st->print("load average:");
203  double loadavg[3];
204  os::loadavg(loadavg, 3);
205  st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]);
206  st->cr();
207}
208
209void os::Posix::print_rlimit_info(outputStream* st) {
210  st->print("rlimit:");
211  struct rlimit rlim;
212
213  st->print(" STACK ");
214  getrlimit(RLIMIT_STACK, &rlim);
215  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
216  else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024);
217
218  st->print(", CORE ");
219  getrlimit(RLIMIT_CORE, &rlim);
220  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
221  else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024);
222
223  // Isn't there on solaris
224#if defined(AIX)
225  st->print(", NPROC ");
226  st->print("%d", sysconf(_SC_CHILD_MAX));
227#elif !defined(SOLARIS)
228  st->print(", NPROC ");
229  getrlimit(RLIMIT_NPROC, &rlim);
230  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
231  else st->print(UINT64_FORMAT, uint64_t(rlim.rlim_cur));
232#endif
233
234  st->print(", NOFILE ");
235  getrlimit(RLIMIT_NOFILE, &rlim);
236  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
237  else st->print(UINT64_FORMAT, uint64_t(rlim.rlim_cur));
238
239  st->print(", AS ");
240  getrlimit(RLIMIT_AS, &rlim);
241  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
242  else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024);
243
244  st->print(", DATA ");
245  getrlimit(RLIMIT_DATA, &rlim);
246  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
247  else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024);
248
249  st->print(", FSIZE ");
250  getrlimit(RLIMIT_FSIZE, &rlim);
251  if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
252  else st->print(UINT64_FORMAT "k", uint64_t(rlim.rlim_cur) / 1024);
253
254  st->cr();
255}
256
257void os::Posix::print_uname_info(outputStream* st) {
258  // kernel
259  st->print("uname:");
260  struct utsname name;
261  uname(&name);
262  st->print("%s ", name.sysname);
263#ifdef ASSERT
264  st->print("%s ", name.nodename);
265#endif
266  st->print("%s ", name.release);
267  st->print("%s ", name.version);
268  st->print("%s", name.machine);
269  st->cr();
270}
271
272bool os::get_host_name(char* buf, size_t buflen) {
273  struct utsname name;
274  uname(&name);
275  jio_snprintf(buf, buflen, "%s", name.nodename);
276  return true;
277}
278
279bool os::has_allocatable_memory_limit(julong* limit) {
280  struct rlimit rlim;
281  int getrlimit_res = getrlimit(RLIMIT_AS, &rlim);
282  // if there was an error when calling getrlimit, assume that there is no limitation
283  // on virtual memory.
284  bool result;
285  if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) {
286    result = false;
287  } else {
288    *limit = (julong)rlim.rlim_cur;
289    result = true;
290  }
291#ifdef _LP64
292  return result;
293#else
294  // arbitrary virtual space limit for 32 bit Unices found by testing. If
295  // getrlimit above returned a limit, bound it with this limit. Otherwise
296  // directly use it.
297  const julong max_virtual_limit = (julong)3800*M;
298  if (result) {
299    *limit = MIN2(*limit, max_virtual_limit);
300  } else {
301    *limit = max_virtual_limit;
302  }
303
304  // bound by actually allocatable memory. The algorithm uses two bounds, an
305  // upper and a lower limit. The upper limit is the current highest amount of
306  // memory that could not be allocated, the lower limit is the current highest
307  // amount of memory that could be allocated.
308  // The algorithm iteratively refines the result by halving the difference
309  // between these limits, updating either the upper limit (if that value could
310  // not be allocated) or the lower limit (if the that value could be allocated)
311  // until the difference between these limits is "small".
312
313  // the minimum amount of memory we care about allocating.
314  const julong min_allocation_size = M;
315
316  julong upper_limit = *limit;
317
318  // first check a few trivial cases
319  if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) {
320    *limit = upper_limit;
321  } else if (!is_allocatable(min_allocation_size)) {
322    // we found that not even min_allocation_size is allocatable. Return it
323    // anyway. There is no point to search for a better value any more.
324    *limit = min_allocation_size;
325  } else {
326    // perform the binary search.
327    julong lower_limit = min_allocation_size;
328    while ((upper_limit - lower_limit) > min_allocation_size) {
329      julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit;
330      temp_limit = align_down(temp_limit, min_allocation_size);
331      if (is_allocatable(temp_limit)) {
332        lower_limit = temp_limit;
333      } else {
334        upper_limit = temp_limit;
335      }
336    }
337    *limit = lower_limit;
338  }
339  return true;
340#endif
341}
342
343const char* os::get_current_directory(char *buf, size_t buflen) {
344  return getcwd(buf, buflen);
345}
346
347FILE* os::open(int fd, const char* mode) {
348  return ::fdopen(fd, mode);
349}
350
351void os::flockfile(FILE* fp) {
352  ::flockfile(fp);
353}
354
355void os::funlockfile(FILE* fp) {
356  ::funlockfile(fp);
357}
358
359// Builds a platform dependent Agent_OnLoad_<lib_name> function name
360// which is used to find statically linked in agents.
361// Parameters:
362//            sym_name: Symbol in library we are looking for
363//            lib_name: Name of library to look in, NULL for shared libs.
364//            is_absolute_path == true if lib_name is absolute path to agent
365//                                     such as "/a/b/libL.so"
366//            == false if only the base name of the library is passed in
367//               such as "L"
368char* os::build_agent_function_name(const char *sym_name, const char *lib_name,
369                                    bool is_absolute_path) {
370  char *agent_entry_name;
371  size_t len;
372  size_t name_len;
373  size_t prefix_len = strlen(JNI_LIB_PREFIX);
374  size_t suffix_len = strlen(JNI_LIB_SUFFIX);
375  const char *start;
376
377  if (lib_name != NULL) {
378    name_len = strlen(lib_name);
379    if (is_absolute_path) {
380      // Need to strip path, prefix and suffix
381      if ((start = strrchr(lib_name, *os::file_separator())) != NULL) {
382        lib_name = ++start;
383      }
384      if (strlen(lib_name) <= (prefix_len + suffix_len)) {
385        return NULL;
386      }
387      lib_name += prefix_len;
388      name_len = strlen(lib_name) - suffix_len;
389    }
390  }
391  len = (lib_name != NULL ? name_len : 0) + strlen(sym_name) + 2;
392  agent_entry_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len, mtThread);
393  if (agent_entry_name == NULL) {
394    return NULL;
395  }
396  strcpy(agent_entry_name, sym_name);
397  if (lib_name != NULL) {
398    strcat(agent_entry_name, "_");
399    strncat(agent_entry_name, lib_name, name_len);
400  }
401  return agent_entry_name;
402}
403
404int os::sleep(Thread* thread, jlong millis, bool interruptible) {
405  assert(thread == Thread::current(),  "thread consistency check");
406
407  ParkEvent * const slp = thread->_SleepEvent ;
408  slp->reset() ;
409  OrderAccess::fence() ;
410
411  if (interruptible) {
412    jlong prevtime = javaTimeNanos();
413
414    for (;;) {
415      if (os::is_interrupted(thread, true)) {
416        return OS_INTRPT;
417      }
418
419      jlong newtime = javaTimeNanos();
420
421      if (newtime - prevtime < 0) {
422        // time moving backwards, should only happen if no monotonic clock
423        // not a guarantee() because JVM should not abort on kernel/glibc bugs
424        assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected in os::sleep(interruptible)");
425      } else {
426        millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
427      }
428
429      if (millis <= 0) {
430        return OS_OK;
431      }
432
433      prevtime = newtime;
434
435      {
436        assert(thread->is_Java_thread(), "sanity check");
437        JavaThread *jt = (JavaThread *) thread;
438        ThreadBlockInVM tbivm(jt);
439        OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
440
441        jt->set_suspend_equivalent();
442        // cleared by handle_special_suspend_equivalent_condition() or
443        // java_suspend_self() via check_and_wait_while_suspended()
444
445        slp->park(millis);
446
447        // were we externally suspended while we were waiting?
448        jt->check_and_wait_while_suspended();
449      }
450    }
451  } else {
452    OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
453    jlong prevtime = javaTimeNanos();
454
455    for (;;) {
456      // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
457      // the 1st iteration ...
458      jlong newtime = javaTimeNanos();
459
460      if (newtime - prevtime < 0) {
461        // time moving backwards, should only happen if no monotonic clock
462        // not a guarantee() because JVM should not abort on kernel/glibc bugs
463        assert(!os::supports_monotonic_clock(), "unexpected time moving backwards detected on os::sleep(!interruptible)");
464      } else {
465        millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
466      }
467
468      if (millis <= 0) break ;
469
470      prevtime = newtime;
471      slp->park(millis);
472    }
473    return OS_OK ;
474  }
475}
476
477////////////////////////////////////////////////////////////////////////////////
478// interrupt support
479
480void os::interrupt(Thread* thread) {
481  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
482    "possibility of dangling Thread pointer");
483
484  OSThread* osthread = thread->osthread();
485
486  if (!osthread->interrupted()) {
487    osthread->set_interrupted(true);
488    // More than one thread can get here with the same value of osthread,
489    // resulting in multiple notifications.  We do, however, want the store
490    // to interrupted() to be visible to other threads before we execute unpark().
491    OrderAccess::fence();
492    ParkEvent * const slp = thread->_SleepEvent ;
493    if (slp != NULL) slp->unpark() ;
494  }
495
496  // For JSR166. Unpark even if interrupt status already was set
497  if (thread->is_Java_thread())
498    ((JavaThread*)thread)->parker()->unpark();
499
500  ParkEvent * ev = thread->_ParkEvent ;
501  if (ev != NULL) ev->unpark() ;
502
503}
504
505bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
506  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
507    "possibility of dangling Thread pointer");
508
509  OSThread* osthread = thread->osthread();
510
511  bool interrupted = osthread->interrupted();
512
513  // NOTE that since there is no "lock" around the interrupt and
514  // is_interrupted operations, there is the possibility that the
515  // interrupted flag (in osThread) will be "false" but that the
516  // low-level events will be in the signaled state. This is
517  // intentional. The effect of this is that Object.wait() and
518  // LockSupport.park() will appear to have a spurious wakeup, which
519  // is allowed and not harmful, and the possibility is so rare that
520  // it is not worth the added complexity to add yet another lock.
521  // For the sleep event an explicit reset is performed on entry
522  // to os::sleep, so there is no early return. It has also been
523  // recommended not to put the interrupted flag into the "event"
524  // structure because it hides the issue.
525  if (interrupted && clear_interrupted) {
526    osthread->set_interrupted(false);
527    // consider thread->_SleepEvent->reset() ... optional optimization
528  }
529
530  return interrupted;
531}
532
533
534
535static const struct {
536  int sig; const char* name;
537}
538 g_signal_info[] =
539  {
540  {  SIGABRT,     "SIGABRT" },
541#ifdef SIGAIO
542  {  SIGAIO,      "SIGAIO" },
543#endif
544  {  SIGALRM,     "SIGALRM" },
545#ifdef SIGALRM1
546  {  SIGALRM1,    "SIGALRM1" },
547#endif
548  {  SIGBUS,      "SIGBUS" },
549#ifdef SIGCANCEL
550  {  SIGCANCEL,   "SIGCANCEL" },
551#endif
552  {  SIGCHLD,     "SIGCHLD" },
553#ifdef SIGCLD
554  {  SIGCLD,      "SIGCLD" },
555#endif
556  {  SIGCONT,     "SIGCONT" },
557#ifdef SIGCPUFAIL
558  {  SIGCPUFAIL,  "SIGCPUFAIL" },
559#endif
560#ifdef SIGDANGER
561  {  SIGDANGER,   "SIGDANGER" },
562#endif
563#ifdef SIGDIL
564  {  SIGDIL,      "SIGDIL" },
565#endif
566#ifdef SIGEMT
567  {  SIGEMT,      "SIGEMT" },
568#endif
569  {  SIGFPE,      "SIGFPE" },
570#ifdef SIGFREEZE
571  {  SIGFREEZE,   "SIGFREEZE" },
572#endif
573#ifdef SIGGFAULT
574  {  SIGGFAULT,   "SIGGFAULT" },
575#endif
576#ifdef SIGGRANT
577  {  SIGGRANT,    "SIGGRANT" },
578#endif
579  {  SIGHUP,      "SIGHUP" },
580  {  SIGILL,      "SIGILL" },
581  {  SIGINT,      "SIGINT" },
582#ifdef SIGIO
583  {  SIGIO,       "SIGIO" },
584#endif
585#ifdef SIGIOINT
586  {  SIGIOINT,    "SIGIOINT" },
587#endif
588#ifdef SIGIOT
589// SIGIOT is there for BSD compatibility, but on most Unices just a
590// synonym for SIGABRT. The result should be "SIGABRT", not
591// "SIGIOT".
592#if (SIGIOT != SIGABRT )
593  {  SIGIOT,      "SIGIOT" },
594#endif
595#endif
596#ifdef SIGKAP
597  {  SIGKAP,      "SIGKAP" },
598#endif
599  {  SIGKILL,     "SIGKILL" },
600#ifdef SIGLOST
601  {  SIGLOST,     "SIGLOST" },
602#endif
603#ifdef SIGLWP
604  {  SIGLWP,      "SIGLWP" },
605#endif
606#ifdef SIGLWPTIMER
607  {  SIGLWPTIMER, "SIGLWPTIMER" },
608#endif
609#ifdef SIGMIGRATE
610  {  SIGMIGRATE,  "SIGMIGRATE" },
611#endif
612#ifdef SIGMSG
613  {  SIGMSG,      "SIGMSG" },
614#endif
615  {  SIGPIPE,     "SIGPIPE" },
616#ifdef SIGPOLL
617  {  SIGPOLL,     "SIGPOLL" },
618#endif
619#ifdef SIGPRE
620  {  SIGPRE,      "SIGPRE" },
621#endif
622  {  SIGPROF,     "SIGPROF" },
623#ifdef SIGPTY
624  {  SIGPTY,      "SIGPTY" },
625#endif
626#ifdef SIGPWR
627  {  SIGPWR,      "SIGPWR" },
628#endif
629  {  SIGQUIT,     "SIGQUIT" },
630#ifdef SIGRECONFIG
631  {  SIGRECONFIG, "SIGRECONFIG" },
632#endif
633#ifdef SIGRECOVERY
634  {  SIGRECOVERY, "SIGRECOVERY" },
635#endif
636#ifdef SIGRESERVE
637  {  SIGRESERVE,  "SIGRESERVE" },
638#endif
639#ifdef SIGRETRACT
640  {  SIGRETRACT,  "SIGRETRACT" },
641#endif
642#ifdef SIGSAK
643  {  SIGSAK,      "SIGSAK" },
644#endif
645  {  SIGSEGV,     "SIGSEGV" },
646#ifdef SIGSOUND
647  {  SIGSOUND,    "SIGSOUND" },
648#endif
649#ifdef SIGSTKFLT
650  {  SIGSTKFLT,    "SIGSTKFLT" },
651#endif
652  {  SIGSTOP,     "SIGSTOP" },
653  {  SIGSYS,      "SIGSYS" },
654#ifdef SIGSYSERROR
655  {  SIGSYSERROR, "SIGSYSERROR" },
656#endif
657#ifdef SIGTALRM
658  {  SIGTALRM,    "SIGTALRM" },
659#endif
660  {  SIGTERM,     "SIGTERM" },
661#ifdef SIGTHAW
662  {  SIGTHAW,     "SIGTHAW" },
663#endif
664  {  SIGTRAP,     "SIGTRAP" },
665#ifdef SIGTSTP
666  {  SIGTSTP,     "SIGTSTP" },
667#endif
668  {  SIGTTIN,     "SIGTTIN" },
669  {  SIGTTOU,     "SIGTTOU" },
670#ifdef SIGURG
671  {  SIGURG,      "SIGURG" },
672#endif
673  {  SIGUSR1,     "SIGUSR1" },
674  {  SIGUSR2,     "SIGUSR2" },
675#ifdef SIGVIRT
676  {  SIGVIRT,     "SIGVIRT" },
677#endif
678  {  SIGVTALRM,   "SIGVTALRM" },
679#ifdef SIGWAITING
680  {  SIGWAITING,  "SIGWAITING" },
681#endif
682#ifdef SIGWINCH
683  {  SIGWINCH,    "SIGWINCH" },
684#endif
685#ifdef SIGWINDOW
686  {  SIGWINDOW,   "SIGWINDOW" },
687#endif
688  {  SIGXCPU,     "SIGXCPU" },
689  {  SIGXFSZ,     "SIGXFSZ" },
690#ifdef SIGXRES
691  {  SIGXRES,     "SIGXRES" },
692#endif
693  { -1, NULL }
694};
695
696// Returned string is a constant. For unknown signals "UNKNOWN" is returned.
697const char* os::Posix::get_signal_name(int sig, char* out, size_t outlen) {
698
699  const char* ret = NULL;
700
701#ifdef SIGRTMIN
702  if (sig >= SIGRTMIN && sig <= SIGRTMAX) {
703    if (sig == SIGRTMIN) {
704      ret = "SIGRTMIN";
705    } else if (sig == SIGRTMAX) {
706      ret = "SIGRTMAX";
707    } else {
708      jio_snprintf(out, outlen, "SIGRTMIN+%d", sig - SIGRTMIN);
709      return out;
710    }
711  }
712#endif
713
714  if (sig > 0) {
715    for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
716      if (g_signal_info[idx].sig == sig) {
717        ret = g_signal_info[idx].name;
718        break;
719      }
720    }
721  }
722
723  if (!ret) {
724    if (!is_valid_signal(sig)) {
725      ret = "INVALID";
726    } else {
727      ret = "UNKNOWN";
728    }
729  }
730
731  if (out && outlen > 0) {
732    strncpy(out, ret, outlen);
733    out[outlen - 1] = '\0';
734  }
735  return out;
736}
737
738int os::Posix::get_signal_number(const char* signal_name) {
739  char tmp[30];
740  const char* s = signal_name;
741  if (s[0] != 'S' || s[1] != 'I' || s[2] != 'G') {
742    jio_snprintf(tmp, sizeof(tmp), "SIG%s", signal_name);
743    s = tmp;
744  }
745  for (int idx = 0; g_signal_info[idx].sig != -1; idx ++) {
746    if (strcmp(g_signal_info[idx].name, s) == 0) {
747      return g_signal_info[idx].sig;
748    }
749  }
750  return -1;
751}
752
753int os::get_signal_number(const char* signal_name) {
754  return os::Posix::get_signal_number(signal_name);
755}
756
757// Returns true if signal number is valid.
758bool os::Posix::is_valid_signal(int sig) {
759  // MacOS not really POSIX compliant: sigaddset does not return
760  // an error for invalid signal numbers. However, MacOS does not
761  // support real time signals and simply seems to have just 33
762  // signals with no holes in the signal range.
763#ifdef __APPLE__
764  return sig >= 1 && sig < NSIG;
765#else
766  // Use sigaddset to check for signal validity.
767  sigset_t set;
768  sigemptyset(&set);
769  if (sigaddset(&set, sig) == -1 && errno == EINVAL) {
770    return false;
771  }
772  return true;
773#endif
774}
775
776// Returns:
777// NULL for an invalid signal number
778// "SIG<num>" for a valid but unknown signal number
779// signal name otherwise.
780const char* os::exception_name(int sig, char* buf, size_t size) {
781  if (!os::Posix::is_valid_signal(sig)) {
782    return NULL;
783  }
784  const char* const name = os::Posix::get_signal_name(sig, buf, size);
785  if (strcmp(name, "UNKNOWN") == 0) {
786    jio_snprintf(buf, size, "SIG%d", sig);
787  }
788  return buf;
789}
790
791#define NUM_IMPORTANT_SIGS 32
792// Returns one-line short description of a signal set in a user provided buffer.
793const char* os::Posix::describe_signal_set_short(const sigset_t* set, char* buffer, size_t buf_size) {
794  assert(buf_size == (NUM_IMPORTANT_SIGS + 1), "wrong buffer size");
795  // Note: for shortness, just print out the first 32. That should
796  // cover most of the useful ones, apart from realtime signals.
797  for (int sig = 1; sig <= NUM_IMPORTANT_SIGS; sig++) {
798    const int rc = sigismember(set, sig);
799    if (rc == -1 && errno == EINVAL) {
800      buffer[sig-1] = '?';
801    } else {
802      buffer[sig-1] = rc == 0 ? '0' : '1';
803    }
804  }
805  buffer[NUM_IMPORTANT_SIGS] = 0;
806  return buffer;
807}
808
809// Prints one-line description of a signal set.
810void os::Posix::print_signal_set_short(outputStream* st, const sigset_t* set) {
811  char buf[NUM_IMPORTANT_SIGS + 1];
812  os::Posix::describe_signal_set_short(set, buf, sizeof(buf));
813  st->print("%s", buf);
814}
815
816// Writes one-line description of a combination of sigaction.sa_flags into a user
817// provided buffer. Returns that buffer.
818const char* os::Posix::describe_sa_flags(int flags, char* buffer, size_t size) {
819  char* p = buffer;
820  size_t remaining = size;
821  bool first = true;
822  int idx = 0;
823
824  assert(buffer, "invalid argument");
825
826  if (size == 0) {
827    return buffer;
828  }
829
830  strncpy(buffer, "none", size);
831
832  const struct {
833    // NB: i is an unsigned int here because SA_RESETHAND is on some
834    // systems 0x80000000, which is implicitly unsigned.  Assignining
835    // it to an int field would be an overflow in unsigned-to-signed
836    // conversion.
837    unsigned int i;
838    const char* s;
839  } flaginfo [] = {
840    { SA_NOCLDSTOP, "SA_NOCLDSTOP" },
841    { SA_ONSTACK,   "SA_ONSTACK"   },
842    { SA_RESETHAND, "SA_RESETHAND" },
843    { SA_RESTART,   "SA_RESTART"   },
844    { SA_SIGINFO,   "SA_SIGINFO"   },
845    { SA_NOCLDWAIT, "SA_NOCLDWAIT" },
846    { SA_NODEFER,   "SA_NODEFER"   },
847#ifdef AIX
848    { SA_ONSTACK,   "SA_ONSTACK"   },
849    { SA_OLDSTYLE,  "SA_OLDSTYLE"  },
850#endif
851    { 0, NULL }
852  };
853
854  for (idx = 0; flaginfo[idx].s && remaining > 1; idx++) {
855    if (flags & flaginfo[idx].i) {
856      if (first) {
857        jio_snprintf(p, remaining, "%s", flaginfo[idx].s);
858        first = false;
859      } else {
860        jio_snprintf(p, remaining, "|%s", flaginfo[idx].s);
861      }
862      const size_t len = strlen(p);
863      p += len;
864      remaining -= len;
865    }
866  }
867
868  buffer[size - 1] = '\0';
869
870  return buffer;
871}
872
873// Prints one-line description of a combination of sigaction.sa_flags.
874void os::Posix::print_sa_flags(outputStream* st, int flags) {
875  char buffer[0x100];
876  os::Posix::describe_sa_flags(flags, buffer, sizeof(buffer));
877  st->print("%s", buffer);
878}
879
880// Helper function for os::Posix::print_siginfo_...():
881// return a textual description for signal code.
882struct enum_sigcode_desc_t {
883  const char* s_name;
884  const char* s_desc;
885};
886
887static bool get_signal_code_description(const siginfo_t* si, enum_sigcode_desc_t* out) {
888
889  const struct {
890    int sig; int code; const char* s_code; const char* s_desc;
891  } t1 [] = {
892    { SIGILL,  ILL_ILLOPC,   "ILL_ILLOPC",   "Illegal opcode." },
893    { SIGILL,  ILL_ILLOPN,   "ILL_ILLOPN",   "Illegal operand." },
894    { SIGILL,  ILL_ILLADR,   "ILL_ILLADR",   "Illegal addressing mode." },
895    { SIGILL,  ILL_ILLTRP,   "ILL_ILLTRP",   "Illegal trap." },
896    { SIGILL,  ILL_PRVOPC,   "ILL_PRVOPC",   "Privileged opcode." },
897    { SIGILL,  ILL_PRVREG,   "ILL_PRVREG",   "Privileged register." },
898    { SIGILL,  ILL_COPROC,   "ILL_COPROC",   "Coprocessor error." },
899    { SIGILL,  ILL_BADSTK,   "ILL_BADSTK",   "Internal stack error." },
900#if defined(IA64) && defined(LINUX)
901    { SIGILL,  ILL_BADIADDR, "ILL_BADIADDR", "Unimplemented instruction address" },
902    { SIGILL,  ILL_BREAK,    "ILL_BREAK",    "Application Break instruction" },
903#endif
904    { SIGFPE,  FPE_INTDIV,   "FPE_INTDIV",   "Integer divide by zero." },
905    { SIGFPE,  FPE_INTOVF,   "FPE_INTOVF",   "Integer overflow." },
906    { SIGFPE,  FPE_FLTDIV,   "FPE_FLTDIV",   "Floating-point divide by zero." },
907    { SIGFPE,  FPE_FLTOVF,   "FPE_FLTOVF",   "Floating-point overflow." },
908    { SIGFPE,  FPE_FLTUND,   "FPE_FLTUND",   "Floating-point underflow." },
909    { SIGFPE,  FPE_FLTRES,   "FPE_FLTRES",   "Floating-point inexact result." },
910    { SIGFPE,  FPE_FLTINV,   "FPE_FLTINV",   "Invalid floating-point operation." },
911    { SIGFPE,  FPE_FLTSUB,   "FPE_FLTSUB",   "Subscript out of range." },
912    { SIGSEGV, SEGV_MAPERR,  "SEGV_MAPERR",  "Address not mapped to object." },
913    { SIGSEGV, SEGV_ACCERR,  "SEGV_ACCERR",  "Invalid permissions for mapped object." },
914#ifdef AIX
915    // no explanation found what keyerr would be
916    { SIGSEGV, SEGV_KEYERR,  "SEGV_KEYERR",  "key error" },
917#endif
918#if defined(IA64) && !defined(AIX)
919    { SIGSEGV, SEGV_PSTKOVF, "SEGV_PSTKOVF", "Paragraph stack overflow" },
920#endif
921#if defined(__sparc) && defined(SOLARIS)
922// define Solaris Sparc M7 ADI SEGV signals
923#if !defined(SEGV_ACCADI)
924#define SEGV_ACCADI 3
925#endif
926    { SIGSEGV, SEGV_ACCADI,  "SEGV_ACCADI",  "ADI not enabled for mapped object." },
927#if !defined(SEGV_ACCDERR)
928#define SEGV_ACCDERR 4
929#endif
930    { SIGSEGV, SEGV_ACCDERR, "SEGV_ACCDERR", "ADI disrupting exception." },
931#if !defined(SEGV_ACCPERR)
932#define SEGV_ACCPERR 5
933#endif
934    { SIGSEGV, SEGV_ACCPERR, "SEGV_ACCPERR", "ADI precise exception." },
935#endif // defined(__sparc) && defined(SOLARIS)
936    { SIGBUS,  BUS_ADRALN,   "BUS_ADRALN",   "Invalid address alignment." },
937    { SIGBUS,  BUS_ADRERR,   "BUS_ADRERR",   "Nonexistent physical address." },
938    { SIGBUS,  BUS_OBJERR,   "BUS_OBJERR",   "Object-specific hardware error." },
939    { SIGTRAP, TRAP_BRKPT,   "TRAP_BRKPT",   "Process breakpoint." },
940    { SIGTRAP, TRAP_TRACE,   "TRAP_TRACE",   "Process trace trap." },
941    { SIGCHLD, CLD_EXITED,   "CLD_EXITED",   "Child has exited." },
942    { SIGCHLD, CLD_KILLED,   "CLD_KILLED",   "Child has terminated abnormally and did not create a core file." },
943    { SIGCHLD, CLD_DUMPED,   "CLD_DUMPED",   "Child has terminated abnormally and created a core file." },
944    { SIGCHLD, CLD_TRAPPED,  "CLD_TRAPPED",  "Traced child has trapped." },
945    { SIGCHLD, CLD_STOPPED,  "CLD_STOPPED",  "Child has stopped." },
946    { SIGCHLD, CLD_CONTINUED,"CLD_CONTINUED","Stopped child has continued." },
947#ifdef SIGPOLL
948    { SIGPOLL, POLL_OUT,     "POLL_OUT",     "Output buffers available." },
949    { SIGPOLL, POLL_MSG,     "POLL_MSG",     "Input message available." },
950    { SIGPOLL, POLL_ERR,     "POLL_ERR",     "I/O error." },
951    { SIGPOLL, POLL_PRI,     "POLL_PRI",     "High priority input available." },
952    { SIGPOLL, POLL_HUP,     "POLL_HUP",     "Device disconnected. [Option End]" },
953#endif
954    { -1, -1, NULL, NULL }
955  };
956
957  // Codes valid in any signal context.
958  const struct {
959    int code; const char* s_code; const char* s_desc;
960  } t2 [] = {
961    { SI_USER,      "SI_USER",     "Signal sent by kill()." },
962    { SI_QUEUE,     "SI_QUEUE",    "Signal sent by the sigqueue()." },
963    { SI_TIMER,     "SI_TIMER",    "Signal generated by expiration of a timer set by timer_settime()." },
964    { SI_ASYNCIO,   "SI_ASYNCIO",  "Signal generated by completion of an asynchronous I/O request." },
965    { SI_MESGQ,     "SI_MESGQ",    "Signal generated by arrival of a message on an empty message queue." },
966    // Linux specific
967#ifdef SI_TKILL
968    { SI_TKILL,     "SI_TKILL",    "Signal sent by tkill (pthread_kill)" },
969#endif
970#ifdef SI_DETHREAD
971    { SI_DETHREAD,  "SI_DETHREAD", "Signal sent by execve() killing subsidiary threads" },
972#endif
973#ifdef SI_KERNEL
974    { SI_KERNEL,    "SI_KERNEL",   "Signal sent by kernel." },
975#endif
976#ifdef SI_SIGIO
977    { SI_SIGIO,     "SI_SIGIO",    "Signal sent by queued SIGIO" },
978#endif
979
980#ifdef AIX
981    { SI_UNDEFINED, "SI_UNDEFINED","siginfo contains partial information" },
982    { SI_EMPTY,     "SI_EMPTY",    "siginfo contains no useful information" },
983#endif
984
985#ifdef __sun
986    { SI_NOINFO,    "SI_NOINFO",   "No signal information" },
987    { SI_RCTL,      "SI_RCTL",     "kernel generated signal via rctl action" },
988    { SI_LWP,       "SI_LWP",      "Signal sent via lwp_kill" },
989#endif
990
991    { -1, NULL, NULL }
992  };
993
994  const char* s_code = NULL;
995  const char* s_desc = NULL;
996
997  for (int i = 0; t1[i].sig != -1; i ++) {
998    if (t1[i].sig == si->si_signo && t1[i].code == si->si_code) {
999      s_code = t1[i].s_code;
1000      s_desc = t1[i].s_desc;
1001      break;
1002    }
1003  }
1004
1005  if (s_code == NULL) {
1006    for (int i = 0; t2[i].s_code != NULL; i ++) {
1007      if (t2[i].code == si->si_code) {
1008        s_code = t2[i].s_code;
1009        s_desc = t2[i].s_desc;
1010      }
1011    }
1012  }
1013
1014  if (s_code == NULL) {
1015    out->s_name = "unknown";
1016    out->s_desc = "unknown";
1017    return false;
1018  }
1019
1020  out->s_name = s_code;
1021  out->s_desc = s_desc;
1022
1023  return true;
1024}
1025
1026void os::print_siginfo(outputStream* os, const void* si0) {
1027
1028  const siginfo_t* const si = (const siginfo_t*) si0;
1029
1030  char buf[20];
1031  os->print("siginfo:");
1032
1033  if (!si) {
1034    os->print(" <null>");
1035    return;
1036  }
1037
1038  const int sig = si->si_signo;
1039
1040  os->print(" si_signo: %d (%s)", sig, os::Posix::get_signal_name(sig, buf, sizeof(buf)));
1041
1042  enum_sigcode_desc_t ed;
1043  get_signal_code_description(si, &ed);
1044  os->print(", si_code: %d (%s)", si->si_code, ed.s_name);
1045
1046  if (si->si_errno) {
1047    os->print(", si_errno: %d", si->si_errno);
1048  }
1049
1050  // Output additional information depending on the signal code.
1051
1052  // Note: Many implementations lump si_addr, si_pid, si_uid etc. together as unions,
1053  // so it depends on the context which member to use. For synchronous error signals,
1054  // we print si_addr, unless the signal was sent by another process or thread, in
1055  // which case we print out pid or tid of the sender.
1056  if (si->si_code == SI_USER || si->si_code == SI_QUEUE) {
1057    const pid_t pid = si->si_pid;
1058    os->print(", si_pid: %ld", (long) pid);
1059    if (IS_VALID_PID(pid)) {
1060      const pid_t me = getpid();
1061      if (me == pid) {
1062        os->print(" (current process)");
1063      }
1064    } else {
1065      os->print(" (invalid)");
1066    }
1067    os->print(", si_uid: %ld", (long) si->si_uid);
1068    if (sig == SIGCHLD) {
1069      os->print(", si_status: %d", si->si_status);
1070    }
1071  } else if (sig == SIGSEGV || sig == SIGBUS || sig == SIGILL ||
1072             sig == SIGTRAP || sig == SIGFPE) {
1073    os->print(", si_addr: " PTR_FORMAT, p2i(si->si_addr));
1074#ifdef SIGPOLL
1075  } else if (sig == SIGPOLL) {
1076    os->print(", si_band: %ld", si->si_band);
1077#endif
1078  }
1079
1080}
1081
1082int os::Posix::unblock_thread_signal_mask(const sigset_t *set) {
1083  return pthread_sigmask(SIG_UNBLOCK, set, NULL);
1084}
1085
1086address os::Posix::ucontext_get_pc(const ucontext_t* ctx) {
1087#if defined(AIX)
1088   return Aix::ucontext_get_pc(ctx);
1089#elif defined(BSD)
1090   return Bsd::ucontext_get_pc(ctx);
1091#elif defined(LINUX)
1092   return Linux::ucontext_get_pc(ctx);
1093#elif defined(SOLARIS)
1094   return Solaris::ucontext_get_pc(ctx);
1095#else
1096   VMError::report_and_die("unimplemented ucontext_get_pc");
1097#endif
1098}
1099
1100void os::Posix::ucontext_set_pc(ucontext_t* ctx, address pc) {
1101#if defined(AIX)
1102   Aix::ucontext_set_pc(ctx, pc);
1103#elif defined(BSD)
1104   Bsd::ucontext_set_pc(ctx, pc);
1105#elif defined(LINUX)
1106   Linux::ucontext_set_pc(ctx, pc);
1107#elif defined(SOLARIS)
1108   Solaris::ucontext_set_pc(ctx, pc);
1109#else
1110   VMError::report_and_die("unimplemented ucontext_get_pc");
1111#endif
1112}
1113
1114char* os::Posix::describe_pthread_attr(char* buf, size_t buflen, const pthread_attr_t* attr) {
1115  size_t stack_size = 0;
1116  size_t guard_size = 0;
1117  int detachstate = 0;
1118  pthread_attr_getstacksize(attr, &stack_size);
1119  pthread_attr_getguardsize(attr, &guard_size);
1120  // Work around linux NPTL implementation error, see also os::create_thread() in os_linux.cpp.
1121  LINUX_ONLY(stack_size -= guard_size);
1122  pthread_attr_getdetachstate(attr, &detachstate);
1123  jio_snprintf(buf, buflen, "stacksize: " SIZE_FORMAT "k, guardsize: " SIZE_FORMAT "k, %s",
1124    stack_size / 1024, guard_size / 1024,
1125    (detachstate == PTHREAD_CREATE_DETACHED ? "detached" : "joinable"));
1126  return buf;
1127}
1128
1129char* os::Posix::realpath(const char* filename, char* outbuf, size_t outbuflen) {
1130
1131  if (filename == NULL || outbuf == NULL || outbuflen < 1) {
1132    assert(false, "os::Posix::realpath: invalid arguments.");
1133    errno = EINVAL;
1134    return NULL;
1135  }
1136
1137  char* result = NULL;
1138
1139  // This assumes platform realpath() is implemented according to POSIX.1-2008.
1140  // POSIX.1-2008 allows to specify NULL for the output buffer, in which case
1141  // output buffer is dynamically allocated and must be ::free()'d by the caller.
1142  char* p = ::realpath(filename, NULL);
1143  if (p != NULL) {
1144    if (strlen(p) < outbuflen) {
1145      strcpy(outbuf, p);
1146      result = outbuf;
1147    } else {
1148      errno = ENAMETOOLONG;
1149    }
1150    ::free(p); // *not* os::free
1151  } else {
1152    // Fallback for platforms struggling with modern Posix standards (AIX 5.3, 6.1). If realpath
1153    // returns EINVAL, this may indicate that realpath is not POSIX.1-2008 compatible and
1154    // that it complains about the NULL we handed down as user buffer.
1155    // In this case, use the user provided buffer but at least check whether realpath caused
1156    // a memory overwrite.
1157    if (errno == EINVAL) {
1158      outbuf[outbuflen - 1] = '\0';
1159      p = ::realpath(filename, outbuf);
1160      if (p != NULL) {
1161        guarantee(outbuf[outbuflen - 1] == '\0', "realpath buffer overwrite detected.");
1162        result = p;
1163      }
1164    }
1165  }
1166  return result;
1167
1168}
1169
1170
1171// Check minimum allowable stack sizes for thread creation and to initialize
1172// the java system classes, including StackOverflowError - depends on page
1173// size.
1174// The space needed for frames during startup is platform dependent. It
1175// depends on word size, platform calling conventions, C frame layout and
1176// interpreter/C1/C2 design decisions. Therefore this is given in a
1177// platform (os/cpu) dependent constant.
1178// To this, space for guard mechanisms is added, which depends on the
1179// page size which again depends on the concrete system the VM is running
1180// on. Space for libc guard pages is not included in this size.
1181jint os::Posix::set_minimum_stack_sizes() {
1182  size_t os_min_stack_allowed = SOLARIS_ONLY(thr_min_stack()) NOT_SOLARIS(PTHREAD_STACK_MIN);
1183
1184  _java_thread_min_stack_allowed = _java_thread_min_stack_allowed +
1185                                   JavaThread::stack_guard_zone_size() +
1186                                   JavaThread::stack_shadow_zone_size();
1187
1188  _java_thread_min_stack_allowed = align_up(_java_thread_min_stack_allowed, vm_page_size());
1189  _java_thread_min_stack_allowed = MAX2(_java_thread_min_stack_allowed, os_min_stack_allowed);
1190
1191  size_t stack_size_in_bytes = ThreadStackSize * K;
1192  if (stack_size_in_bytes != 0 &&
1193      stack_size_in_bytes < _java_thread_min_stack_allowed) {
1194    // The '-Xss' and '-XX:ThreadStackSize=N' options both set
1195    // ThreadStackSize so we go with "Java thread stack size" instead
1196    // of "ThreadStackSize" to be more friendly.
1197    tty->print_cr("\nThe Java thread stack size specified is too small. "
1198                  "Specify at least " SIZE_FORMAT "k",
1199                  _java_thread_min_stack_allowed / K);
1200    return JNI_ERR;
1201  }
1202
1203  // Make the stack size a multiple of the page size so that
1204  // the yellow/red zones can be guarded.
1205  JavaThread::set_stack_size_at_create(align_up(stack_size_in_bytes, vm_page_size()));
1206
1207  // Reminder: a compiler thread is a Java thread.
1208  _compiler_thread_min_stack_allowed = _compiler_thread_min_stack_allowed +
1209                                       JavaThread::stack_guard_zone_size() +
1210                                       JavaThread::stack_shadow_zone_size();
1211
1212  _compiler_thread_min_stack_allowed = align_up(_compiler_thread_min_stack_allowed, vm_page_size());
1213  _compiler_thread_min_stack_allowed = MAX2(_compiler_thread_min_stack_allowed, os_min_stack_allowed);
1214
1215  stack_size_in_bytes = CompilerThreadStackSize * K;
1216  if (stack_size_in_bytes != 0 &&
1217      stack_size_in_bytes < _compiler_thread_min_stack_allowed) {
1218    tty->print_cr("\nThe CompilerThreadStackSize specified is too small. "
1219                  "Specify at least " SIZE_FORMAT "k",
1220                  _compiler_thread_min_stack_allowed / K);
1221    return JNI_ERR;
1222  }
1223
1224  _vm_internal_thread_min_stack_allowed = align_up(_vm_internal_thread_min_stack_allowed, vm_page_size());
1225  _vm_internal_thread_min_stack_allowed = MAX2(_vm_internal_thread_min_stack_allowed, os_min_stack_allowed);
1226
1227  stack_size_in_bytes = VMThreadStackSize * K;
1228  if (stack_size_in_bytes != 0 &&
1229      stack_size_in_bytes < _vm_internal_thread_min_stack_allowed) {
1230    tty->print_cr("\nThe VMThreadStackSize specified is too small. "
1231                  "Specify at least " SIZE_FORMAT "k",
1232                  _vm_internal_thread_min_stack_allowed / K);
1233    return JNI_ERR;
1234  }
1235  return JNI_OK;
1236}
1237
1238// Called when creating the thread.  The minimum stack sizes have already been calculated
1239size_t os::Posix::get_initial_stack_size(ThreadType thr_type, size_t req_stack_size) {
1240  size_t stack_size;
1241  if (req_stack_size == 0) {
1242    stack_size = default_stack_size(thr_type);
1243  } else {
1244    stack_size = req_stack_size;
1245  }
1246
1247  switch (thr_type) {
1248  case os::java_thread:
1249    // Java threads use ThreadStackSize which default value can be
1250    // changed with the flag -Xss
1251    if (req_stack_size == 0 && JavaThread::stack_size_at_create() > 0) {
1252      // no requested size and we have a more specific default value
1253      stack_size = JavaThread::stack_size_at_create();
1254    }
1255    stack_size = MAX2(stack_size,
1256                      _java_thread_min_stack_allowed);
1257    break;
1258  case os::compiler_thread:
1259    if (req_stack_size == 0 && CompilerThreadStackSize > 0) {
1260      // no requested size and we have a more specific default value
1261      stack_size = (size_t)(CompilerThreadStackSize * K);
1262    }
1263    stack_size = MAX2(stack_size,
1264                      _compiler_thread_min_stack_allowed);
1265    break;
1266  case os::vm_thread:
1267  case os::pgc_thread:
1268  case os::cgc_thread:
1269  case os::watcher_thread:
1270  default:  // presume the unknown thr_type is a VM internal
1271    if (req_stack_size == 0 && VMThreadStackSize > 0) {
1272      // no requested size and we have a more specific default value
1273      stack_size = (size_t)(VMThreadStackSize * K);
1274    }
1275
1276    stack_size = MAX2(stack_size,
1277                      _vm_internal_thread_min_stack_allowed);
1278    break;
1279  }
1280
1281  // pthread_attr_setstacksize() may require that the size be rounded up to the OS page size.
1282  // Be careful not to round up to 0. Align down in that case.
1283  if (stack_size <= SIZE_MAX - vm_page_size()) {
1284    stack_size = align_up(stack_size, vm_page_size());
1285  } else {
1286    stack_size = align_down(stack_size, vm_page_size());
1287  }
1288
1289  return stack_size;
1290}
1291
1292Thread* os::ThreadCrashProtection::_protected_thread = NULL;
1293os::ThreadCrashProtection* os::ThreadCrashProtection::_crash_protection = NULL;
1294volatile intptr_t os::ThreadCrashProtection::_crash_mux = 0;
1295
1296os::ThreadCrashProtection::ThreadCrashProtection() {
1297}
1298
1299/*
1300 * See the caveats for this class in os_posix.hpp
1301 * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
1302 * method and returns false. If none of the signals are raised, returns true.
1303 * The callback is supposed to provide the method that should be protected.
1304 */
1305bool os::ThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
1306  sigset_t saved_sig_mask;
1307
1308  Thread::muxAcquire(&_crash_mux, "CrashProtection");
1309
1310  _protected_thread = Thread::current_or_null();
1311  assert(_protected_thread != NULL, "Cannot crash protect a NULL thread");
1312
1313  // we cannot rely on sigsetjmp/siglongjmp to save/restore the signal mask
1314  // since on at least some systems (OS X) siglongjmp will restore the mask
1315  // for the process, not the thread
1316  pthread_sigmask(0, NULL, &saved_sig_mask);
1317  if (sigsetjmp(_jmpbuf, 0) == 0) {
1318    // make sure we can see in the signal handler that we have crash protection
1319    // installed
1320    _crash_protection = this;
1321    cb.call();
1322    // and clear the crash protection
1323    _crash_protection = NULL;
1324    _protected_thread = NULL;
1325    Thread::muxRelease(&_crash_mux);
1326    return true;
1327  }
1328  // this happens when we siglongjmp() back
1329  pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL);
1330  _crash_protection = NULL;
1331  _protected_thread = NULL;
1332  Thread::muxRelease(&_crash_mux);
1333  return false;
1334}
1335
1336void os::ThreadCrashProtection::restore() {
1337  assert(_crash_protection != NULL, "must have crash protection");
1338  siglongjmp(_jmpbuf, 1);
1339}
1340
1341void os::ThreadCrashProtection::check_crash_protection(int sig,
1342    Thread* thread) {
1343
1344  if (thread != NULL &&
1345      thread == _protected_thread &&
1346      _crash_protection != NULL) {
1347
1348    if (sig == SIGSEGV || sig == SIGBUS) {
1349      _crash_protection->restore();
1350    }
1351  }
1352}
1353
1354#define check_with_errno(check_type, cond, msg)                             \
1355  do {                                                                      \
1356    int err = errno;                                                        \
1357    check_type(cond, "%s; error='%s' (errno=%s)", msg, os::strerror(err),   \
1358               os::errno_name(err));                                        \
1359} while (false)
1360
1361#define assert_with_errno(cond, msg)    check_with_errno(assert, cond, msg)
1362#define guarantee_with_errno(cond, msg) check_with_errno(guarantee, cond, msg)
1363
1364// POSIX unamed semaphores are not supported on OS X.
1365#ifndef __APPLE__
1366
1367PosixSemaphore::PosixSemaphore(uint value) {
1368  int ret = sem_init(&_semaphore, 0, value);
1369
1370  guarantee_with_errno(ret == 0, "Failed to initialize semaphore");
1371}
1372
1373PosixSemaphore::~PosixSemaphore() {
1374  sem_destroy(&_semaphore);
1375}
1376
1377void PosixSemaphore::signal(uint count) {
1378  for (uint i = 0; i < count; i++) {
1379    int ret = sem_post(&_semaphore);
1380
1381    assert_with_errno(ret == 0, "sem_post failed");
1382  }
1383}
1384
1385void PosixSemaphore::wait() {
1386  int ret;
1387
1388  do {
1389    ret = sem_wait(&_semaphore);
1390  } while (ret != 0 && errno == EINTR);
1391
1392  assert_with_errno(ret == 0, "sem_wait failed");
1393}
1394
1395bool PosixSemaphore::trywait() {
1396  int ret;
1397
1398  do {
1399    ret = sem_trywait(&_semaphore);
1400  } while (ret != 0 && errno == EINTR);
1401
1402  assert_with_errno(ret == 0 || errno == EAGAIN, "trywait failed");
1403
1404  return ret == 0;
1405}
1406
1407bool PosixSemaphore::timedwait(struct timespec ts) {
1408  while (true) {
1409    int result = sem_timedwait(&_semaphore, &ts);
1410    if (result == 0) {
1411      return true;
1412    } else if (errno == EINTR) {
1413      continue;
1414    } else if (errno == ETIMEDOUT) {
1415      return false;
1416    } else {
1417      assert_with_errno(false, "timedwait failed");
1418      return false;
1419    }
1420  }
1421}
1422
1423#endif // __APPLE__
1424
1425
1426// Shared pthread_mutex/cond based PlatformEvent implementation.
1427// Not currently usable by Solaris.
1428
1429#ifndef SOLARIS
1430
1431// Shared condattr object for use with relative timed-waits. Will be associated
1432// with CLOCK_MONOTONIC if available to avoid issues with time-of-day changes,
1433// but otherwise whatever default is used by the platform - generally the
1434// time-of-day clock.
1435static pthread_condattr_t _condAttr[1];
1436
1437// Shared mutexattr to explicitly set the type to PTHREAD_MUTEX_NORMAL as not
1438// all systems (e.g. FreeBSD) map the default to "normal".
1439static pthread_mutexattr_t _mutexAttr[1];
1440
1441// common basic initialization that is always supported
1442static void pthread_init_common(void) {
1443  int status;
1444  if ((status = pthread_condattr_init(_condAttr)) != 0) {
1445    fatal("pthread_condattr_init: %s", os::strerror(status));
1446  }
1447  if ((status = pthread_mutexattr_init(_mutexAttr)) != 0) {
1448    fatal("pthread_mutexattr_init: %s", os::strerror(status));
1449  }
1450  if ((status = pthread_mutexattr_settype(_mutexAttr, PTHREAD_MUTEX_NORMAL)) != 0) {
1451    fatal("pthread_mutexattr_settype: %s", os::strerror(status));
1452  }
1453}
1454
1455// Not all POSIX types and API's are available on all notionally "posix"
1456// platforms. If we have build-time support then we will check for actual
1457// runtime support via dlopen/dlsym lookup. This allows for running on an
1458// older OS version compared to the build platform. But if there is no
1459// build time support then there cannot be any runtime support as we do not
1460// know what the runtime types would be (for example clockid_t might be an
1461// int or int64_t).
1462//
1463#ifdef SUPPORTS_CLOCK_MONOTONIC
1464
1465// This means we have clockid_t, clock_gettime et al and CLOCK_MONOTONIC
1466
1467static int (*_clock_gettime)(clockid_t, struct timespec *);
1468static int (*_pthread_condattr_setclock)(pthread_condattr_t *, clockid_t);
1469
1470static bool _use_clock_monotonic_condattr;
1471
1472// Determine what POSIX API's are present and do appropriate
1473// configuration.
1474void os::Posix::init(void) {
1475
1476  // NOTE: no logging available when this is called. Put logging
1477  // statements in init_2().
1478
1479  // Copied from os::Linux::clock_init(). The duplication is temporary.
1480
1481  // 1. Check for CLOCK_MONOTONIC support.
1482
1483  void* handle = NULL;
1484
1485  // For linux we need librt, for other OS we can find
1486  // this function in regular libc.
1487#ifdef NEEDS_LIBRT
1488  // We do dlopen's in this particular order due to bug in linux
1489  // dynamic loader (see 6348968) leading to crash on exit.
1490  handle = dlopen("librt.so.1", RTLD_LAZY);
1491  if (handle == NULL) {
1492    handle = dlopen("librt.so", RTLD_LAZY);
1493  }
1494#endif
1495
1496  if (handle == NULL) {
1497    handle = RTLD_DEFAULT;
1498  }
1499
1500  _clock_gettime = NULL;
1501
1502  int (*clock_getres_func)(clockid_t, struct timespec*) =
1503    (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres");
1504  int (*clock_gettime_func)(clockid_t, struct timespec*) =
1505    (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime");
1506  if (clock_getres_func != NULL && clock_gettime_func != NULL) {
1507    // We assume that if both clock_gettime and clock_getres support
1508    // CLOCK_MONOTONIC then the OS provides true high-res monotonic clock.
1509    struct timespec res;
1510    struct timespec tp;
1511    if (clock_getres_func(CLOCK_MONOTONIC, &res) == 0 &&
1512        clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) {
1513      // Yes, monotonic clock is supported.
1514      _clock_gettime = clock_gettime_func;
1515    } else {
1516#ifdef NEEDS_LIBRT
1517      // Close librt if there is no monotonic clock.
1518      if (handle != RTLD_DEFAULT) {
1519        dlclose(handle);
1520      }
1521#endif
1522    }
1523  }
1524
1525  // 2. Check for pthread_condattr_setclock support.
1526
1527  _pthread_condattr_setclock = NULL;
1528
1529  // libpthread is already loaded.
1530  int (*condattr_setclock_func)(pthread_condattr_t*, clockid_t) =
1531    (int (*)(pthread_condattr_t*, clockid_t))dlsym(RTLD_DEFAULT,
1532                                                   "pthread_condattr_setclock");
1533  if (condattr_setclock_func != NULL) {
1534    _pthread_condattr_setclock = condattr_setclock_func;
1535  }
1536
1537  // Now do general initialization.
1538
1539  pthread_init_common();
1540
1541  int status;
1542  if (_pthread_condattr_setclock != NULL && _clock_gettime != NULL) {
1543    if ((status = _pthread_condattr_setclock(_condAttr, CLOCK_MONOTONIC)) != 0) {
1544      if (status == EINVAL) {
1545        _use_clock_monotonic_condattr = false;
1546        warning("Unable to use monotonic clock with relative timed-waits" \
1547                " - changes to the time-of-day clock may have adverse affects");
1548      } else {
1549        fatal("pthread_condattr_setclock: %s", os::strerror(status));
1550      }
1551    } else {
1552      _use_clock_monotonic_condattr = true;
1553    }
1554  } else {
1555    _use_clock_monotonic_condattr = false;
1556  }
1557}
1558
1559void os::Posix::init_2(void) {
1560  log_info(os)("Use of CLOCK_MONOTONIC is%s supported",
1561               (_clock_gettime != NULL ? "" : " not"));
1562  log_info(os)("Use of pthread_condattr_setclock is%s supported",
1563               (_pthread_condattr_setclock != NULL ? "" : " not"));
1564  log_info(os)("Relative timed-wait using pthread_cond_timedwait is associated with %s",
1565               _use_clock_monotonic_condattr ? "CLOCK_MONOTONIC" : "the default clock");
1566}
1567
1568#else // !SUPPORTS_CLOCK_MONOTONIC
1569
1570void os::Posix::init(void) {
1571  pthread_init_common();
1572}
1573
1574void os::Posix::init_2(void) {
1575  log_info(os)("Use of CLOCK_MONOTONIC is not supported");
1576  log_info(os)("Use of pthread_condattr_setclock is not supported");
1577  log_info(os)("Relative timed-wait using pthread_cond_timedwait is associated with the default clock");
1578}
1579
1580#endif // SUPPORTS_CLOCK_MONOTONIC
1581
1582os::PlatformEvent::PlatformEvent() {
1583  int status = pthread_cond_init(_cond, _condAttr);
1584  assert_status(status == 0, status, "cond_init");
1585  status = pthread_mutex_init(_mutex, _mutexAttr);
1586  assert_status(status == 0, status, "mutex_init");
1587  _event   = 0;
1588  _nParked = 0;
1589}
1590
1591// Utility to convert the given timeout to an absolute timespec
1592// (based on the appropriate clock) to use with pthread_cond_timewait.
1593// The clock queried here must be the clock used to manage the
1594// timeout of the condition variable.
1595//
1596// The passed in timeout value is either a relative time in nanoseconds
1597// or an absolute time in milliseconds. A relative timeout will be
1598// associated with CLOCK_MONOTONIC if available; otherwise, or if absolute,
1599// the default time-of-day clock will be used.
1600
1601// Given time is a 64-bit value and the time_t used in the timespec is
1602// sometimes a signed-32-bit value we have to watch for overflow if times
1603// way in the future are given. Further on Solaris versions
1604// prior to 10 there is a restriction (see cond_timedwait) that the specified
1605// number of seconds, in abstime, is less than current_time + 100000000.
1606// As it will be over 20 years before "now + 100000000" will overflow we can
1607// ignore overflow and just impose a hard-limit on seconds using the value
1608// of "now + 100000000". This places a limit on the timeout of about 3.17
1609// years from "now".
1610//
1611#define MAX_SECS 100000000
1612
1613// Calculate a new absolute time that is "timeout" nanoseconds from "now".
1614// "unit" indicates the unit of "now_part_sec" (may be nanos or micros depending
1615// on which clock is being used).
1616static void calc_rel_time(timespec* abstime, jlong timeout, jlong now_sec,
1617                          jlong now_part_sec, jlong unit) {
1618  time_t max_secs = now_sec + MAX_SECS;
1619
1620  jlong seconds = timeout / NANOUNITS;
1621  timeout %= NANOUNITS; // remaining nanos
1622
1623  if (seconds >= MAX_SECS) {
1624    // More seconds than we can add, so pin to max_secs.
1625    abstime->tv_sec = max_secs;
1626    abstime->tv_nsec = 0;
1627  } else {
1628    abstime->tv_sec = now_sec  + seconds;
1629    long nanos = (now_part_sec * (NANOUNITS / unit)) + timeout;
1630    if (nanos >= NANOUNITS) { // overflow
1631      abstime->tv_sec += 1;
1632      nanos -= NANOUNITS;
1633    }
1634    abstime->tv_nsec = nanos;
1635  }
1636}
1637
1638// Unpack the given deadline in milliseconds since the epoch, into the given timespec.
1639// The current time in seconds is also passed in to enforce an upper bound as discussed above.
1640static void unpack_abs_time(timespec* abstime, jlong deadline, jlong now_sec) {
1641  time_t max_secs = now_sec + MAX_SECS;
1642
1643  jlong seconds = deadline / MILLIUNITS;
1644  jlong millis = deadline % MILLIUNITS;
1645
1646  if (seconds >= max_secs) {
1647    // Absolute seconds exceeds allowed max, so pin to max_secs.
1648    abstime->tv_sec = max_secs;
1649    abstime->tv_nsec = 0;
1650  } else {
1651    abstime->tv_sec = seconds;
1652    abstime->tv_nsec = millis * (NANOUNITS / MILLIUNITS);
1653  }
1654}
1655
1656static void to_abstime(timespec* abstime, jlong timeout, bool isAbsolute) {
1657  DEBUG_ONLY(int max_secs = MAX_SECS;)
1658
1659  if (timeout < 0) {
1660    timeout = 0;
1661  }
1662
1663#ifdef SUPPORTS_CLOCK_MONOTONIC
1664
1665  if (_use_clock_monotonic_condattr && !isAbsolute) {
1666    struct timespec now;
1667    int status = _clock_gettime(CLOCK_MONOTONIC, &now);
1668    assert_status(status == 0, status, "clock_gettime");
1669    calc_rel_time(abstime, timeout, now.tv_sec, now.tv_nsec, NANOUNITS);
1670    DEBUG_ONLY(max_secs += now.tv_sec;)
1671  } else {
1672
1673#else
1674
1675  { // Match the block scope.
1676
1677#endif // SUPPORTS_CLOCK_MONOTONIC
1678
1679    // Time-of-day clock is all we can reliably use.
1680    struct timeval now;
1681    int status = gettimeofday(&now, NULL);
1682    assert_status(status == 0, errno, "gettimeofday");
1683    if (isAbsolute) {
1684      unpack_abs_time(abstime, timeout, now.tv_sec);
1685    } else {
1686      calc_rel_time(abstime, timeout, now.tv_sec, now.tv_usec, MICROUNITS);
1687    }
1688    DEBUG_ONLY(max_secs += now.tv_sec;)
1689  }
1690
1691  assert(abstime->tv_sec >= 0, "tv_sec < 0");
1692  assert(abstime->tv_sec <= max_secs, "tv_sec > max_secs");
1693  assert(abstime->tv_nsec >= 0, "tv_nsec < 0");
1694  assert(abstime->tv_nsec < NANOUNITS, "tv_nsec >= NANOUNITS");
1695}
1696
1697// PlatformEvent
1698//
1699// Assumption:
1700//    Only one parker can exist on an event, which is why we allocate
1701//    them per-thread. Multiple unparkers can coexist.
1702//
1703// _event serves as a restricted-range semaphore.
1704//   -1 : thread is blocked, i.e. there is a waiter
1705//    0 : neutral: thread is running or ready,
1706//        could have been signaled after a wait started
1707//    1 : signaled - thread is running or ready
1708//
1709//    Having three states allows for some detection of bad usage - see
1710//    comments on unpark().
1711
1712void os::PlatformEvent::park() {       // AKA "down()"
1713  // Transitions for _event:
1714  //   -1 => -1 : illegal
1715  //    1 =>  0 : pass - return immediately
1716  //    0 => -1 : block; then set _event to 0 before returning
1717
1718  // Invariant: Only the thread associated with the PlatformEvent
1719  // may call park().
1720  assert(_nParked == 0, "invariant");
1721
1722  int v;
1723
1724  // atomically decrement _event
1725  for (;;) {
1726    v = _event;
1727    if (Atomic::cmpxchg(v - 1, &_event, v) == v) break;
1728  }
1729  guarantee(v >= 0, "invariant");
1730
1731  if (v == 0) { // Do this the hard way by blocking ...
1732    int status = pthread_mutex_lock(_mutex);
1733    assert_status(status == 0, status, "mutex_lock");
1734    guarantee(_nParked == 0, "invariant");
1735    ++_nParked;
1736    while (_event < 0) {
1737      // OS-level "spurious wakeups" are ignored
1738      status = pthread_cond_wait(_cond, _mutex);
1739      assert_status(status == 0, status, "cond_wait");
1740    }
1741    --_nParked;
1742
1743    _event = 0;
1744    status = pthread_mutex_unlock(_mutex);
1745    assert_status(status == 0, status, "mutex_unlock");
1746    // Paranoia to ensure our locked and lock-free paths interact
1747    // correctly with each other.
1748    OrderAccess::fence();
1749  }
1750  guarantee(_event >= 0, "invariant");
1751}
1752
1753int os::PlatformEvent::park(jlong millis) {
1754  // Transitions for _event:
1755  //   -1 => -1 : illegal
1756  //    1 =>  0 : pass - return immediately
1757  //    0 => -1 : block; then set _event to 0 before returning
1758
1759  // Invariant: Only the thread associated with the Event/PlatformEvent
1760  // may call park().
1761  assert(_nParked == 0, "invariant");
1762
1763  int v;
1764  // atomically decrement _event
1765  for (;;) {
1766    v = _event;
1767    if (Atomic::cmpxchg(v - 1, &_event, v) == v) break;
1768  }
1769  guarantee(v >= 0, "invariant");
1770
1771  if (v == 0) { // Do this the hard way by blocking ...
1772    struct timespec abst;
1773    to_abstime(&abst, millis * (NANOUNITS / MILLIUNITS), false);
1774
1775    int ret = OS_TIMEOUT;
1776    int status = pthread_mutex_lock(_mutex);
1777    assert_status(status == 0, status, "mutex_lock");
1778    guarantee(_nParked == 0, "invariant");
1779    ++_nParked;
1780
1781    while (_event < 0) {
1782      status = pthread_cond_timedwait(_cond, _mutex, &abst);
1783      assert_status(status == 0 || status == ETIMEDOUT,
1784                    status, "cond_timedwait");
1785      // OS-level "spurious wakeups" are ignored unless the archaic
1786      // FilterSpuriousWakeups is set false. That flag should be obsoleted.
1787      if (!FilterSpuriousWakeups) break;
1788      if (status == ETIMEDOUT) break;
1789    }
1790    --_nParked;
1791
1792    if (_event >= 0) {
1793      ret = OS_OK;
1794    }
1795
1796    _event = 0;
1797    status = pthread_mutex_unlock(_mutex);
1798    assert_status(status == 0, status, "mutex_unlock");
1799    // Paranoia to ensure our locked and lock-free paths interact
1800    // correctly with each other.
1801    OrderAccess::fence();
1802    return ret;
1803  }
1804  return OS_OK;
1805}
1806
1807void os::PlatformEvent::unpark() {
1808  // Transitions for _event:
1809  //    0 => 1 : just return
1810  //    1 => 1 : just return
1811  //   -1 => either 0 or 1; must signal target thread
1812  //         That is, we can safely transition _event from -1 to either
1813  //         0 or 1.
1814  // See also: "Semaphores in Plan 9" by Mullender & Cox
1815  //
1816  // Note: Forcing a transition from "-1" to "1" on an unpark() means
1817  // that it will take two back-to-back park() calls for the owning
1818  // thread to block. This has the benefit of forcing a spurious return
1819  // from the first park() call after an unpark() call which will help
1820  // shake out uses of park() and unpark() without checking state conditions
1821  // properly. This spurious return doesn't manifest itself in any user code
1822  // but only in the correctly written condition checking loops of ObjectMonitor,
1823  // Mutex/Monitor, Thread::muxAcquire and os::sleep
1824
1825  if (Atomic::xchg(1, &_event) >= 0) return;
1826
1827  int status = pthread_mutex_lock(_mutex);
1828  assert_status(status == 0, status, "mutex_lock");
1829  int anyWaiters = _nParked;
1830  assert(anyWaiters == 0 || anyWaiters == 1, "invariant");
1831  status = pthread_mutex_unlock(_mutex);
1832  assert_status(status == 0, status, "mutex_unlock");
1833
1834  // Note that we signal() *after* dropping the lock for "immortal" Events.
1835  // This is safe and avoids a common class of futile wakeups.  In rare
1836  // circumstances this can cause a thread to return prematurely from
1837  // cond_{timed}wait() but the spurious wakeup is benign and the victim
1838  // will simply re-test the condition and re-park itself.
1839  // This provides particular benefit if the underlying platform does not
1840  // provide wait morphing.
1841
1842  if (anyWaiters != 0) {
1843    status = pthread_cond_signal(_cond);
1844    assert_status(status == 0, status, "cond_signal");
1845  }
1846}
1847
1848// JSR166 support
1849
1850 os::PlatformParker::PlatformParker() {
1851  int status;
1852  status = pthread_cond_init(&_cond[REL_INDEX], _condAttr);
1853  assert_status(status == 0, status, "cond_init rel");
1854  status = pthread_cond_init(&_cond[ABS_INDEX], NULL);
1855  assert_status(status == 0, status, "cond_init abs");
1856  status = pthread_mutex_init(_mutex, _mutexAttr);
1857  assert_status(status == 0, status, "mutex_init");
1858  _cur_index = -1; // mark as unused
1859}
1860
1861// Parker::park decrements count if > 0, else does a condvar wait.  Unpark
1862// sets count to 1 and signals condvar.  Only one thread ever waits
1863// on the condvar. Contention seen when trying to park implies that someone
1864// is unparking you, so don't wait. And spurious returns are fine, so there
1865// is no need to track notifications.
1866
1867void Parker::park(bool isAbsolute, jlong time) {
1868
1869  // Optional fast-path check:
1870  // Return immediately if a permit is available.
1871  // We depend on Atomic::xchg() having full barrier semantics
1872  // since we are doing a lock-free update to _counter.
1873  if (Atomic::xchg(0, &_counter) > 0) return;
1874
1875  Thread* thread = Thread::current();
1876  assert(thread->is_Java_thread(), "Must be JavaThread");
1877  JavaThread *jt = (JavaThread *)thread;
1878
1879  // Optional optimization -- avoid state transitions if there's
1880  // an interrupt pending.
1881  if (Thread::is_interrupted(thread, false)) {
1882    return;
1883  }
1884
1885  // Next, demultiplex/decode time arguments
1886  struct timespec absTime;
1887  if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all
1888    return;
1889  }
1890  if (time > 0) {
1891    to_abstime(&absTime, time, isAbsolute);
1892  }
1893
1894  // Enter safepoint region
1895  // Beware of deadlocks such as 6317397.
1896  // The per-thread Parker:: mutex is a classic leaf-lock.
1897  // In particular a thread must never block on the Threads_lock while
1898  // holding the Parker:: mutex.  If safepoints are pending both the
1899  // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock.
1900  ThreadBlockInVM tbivm(jt);
1901
1902  // Don't wait if cannot get lock since interference arises from
1903  // unparking. Also re-check interrupt before trying wait.
1904  if (Thread::is_interrupted(thread, false) ||
1905      pthread_mutex_trylock(_mutex) != 0) {
1906    return;
1907  }
1908
1909  int status;
1910  if (_counter > 0)  { // no wait needed
1911    _counter = 0;
1912    status = pthread_mutex_unlock(_mutex);
1913    assert_status(status == 0, status, "invariant");
1914    // Paranoia to ensure our locked and lock-free paths interact
1915    // correctly with each other and Java-level accesses.
1916    OrderAccess::fence();
1917    return;
1918  }
1919
1920  OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
1921  jt->set_suspend_equivalent();
1922  // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
1923
1924  assert(_cur_index == -1, "invariant");
1925  if (time == 0) {
1926    _cur_index = REL_INDEX; // arbitrary choice when not timed
1927    status = pthread_cond_wait(&_cond[_cur_index], _mutex);
1928    assert_status(status == 0, status, "cond_timedwait");
1929  }
1930  else {
1931    _cur_index = isAbsolute ? ABS_INDEX : REL_INDEX;
1932    status = pthread_cond_timedwait(&_cond[_cur_index], _mutex, &absTime);
1933    assert_status(status == 0 || status == ETIMEDOUT,
1934                  status, "cond_timedwait");
1935  }
1936  _cur_index = -1;
1937
1938  _counter = 0;
1939  status = pthread_mutex_unlock(_mutex);
1940  assert_status(status == 0, status, "invariant");
1941  // Paranoia to ensure our locked and lock-free paths interact
1942  // correctly with each other and Java-level accesses.
1943  OrderAccess::fence();
1944
1945  // If externally suspended while waiting, re-suspend
1946  if (jt->handle_special_suspend_equivalent_condition()) {
1947    jt->java_suspend_self();
1948  }
1949}
1950
1951void Parker::unpark() {
1952  int status = pthread_mutex_lock(_mutex);
1953  assert_status(status == 0, status, "invariant");
1954  const int s = _counter;
1955  _counter = 1;
1956  // must capture correct index before unlocking
1957  int index = _cur_index;
1958  status = pthread_mutex_unlock(_mutex);
1959  assert_status(status == 0, status, "invariant");
1960
1961  // Note that we signal() *after* dropping the lock for "immortal" Events.
1962  // This is safe and avoids a common class of futile wakeups.  In rare
1963  // circumstances this can cause a thread to return prematurely from
1964  // cond_{timed}wait() but the spurious wakeup is benign and the victim
1965  // will simply re-test the condition and re-park itself.
1966  // This provides particular benefit if the underlying platform does not
1967  // provide wait morphing.
1968
1969  if (s < 1 && index != -1) {
1970    // thread is definitely parked
1971    status = pthread_cond_signal(&_cond[index]);
1972    assert_status(status == 0, status, "invariant");
1973  }
1974}
1975
1976
1977#endif // !SOLARIS
1978