$OpenBSD: patch-hotspot_src_os_bsd_vm_os_bsd_cpp,v 1.12 2011/01/11 15:47:49 kurt Exp $
--- hotspot/src/os/bsd/vm/os_bsd.cpp.orig	Tue Jan  4 18:25:16 2011
+++ hotspot/src/os/bsd/vm/os_bsd.cpp	Tue Jan  4 18:34:25 2011
@@ -46,20 +46,42 @@
 # include <sys/utsname.h>
 # include <sys/socket.h>
 # include <sys/wait.h>
+# include <time.h>
 # include <pwd.h>
 # include <poll.h>
 # include <semaphore.h>
 # include <fcntl.h>
 # include <string.h>
+#ifdef _ALLBSD_SOURCE
+# include <sys/param.h>
+# include <sys/sysctl.h>
+#else
 # include <syscall.h>
 # include <sys/sysinfo.h>
 # include <gnu/libc-version.h>
+#endif
 # include <sys/ipc.h>
 # include <sys/shm.h>
-# include <link.h>
 # include <stdint.h>
 # include <inttypes.h>
 
+#ifndef __APPLE__
+# include <link.h>
+#endif
+
+#if defined(__FreeBSD__) || defined(__NetBSD__)
+# include <elf.h>
+#endif
+
+#ifdef __APPLE__
+#include <mach/mach.h> // semaphore_* API
+#include <mach-o/dyld.h>
+#endif
+
+#ifndef MAP_ANONYMOUS
+#define MAP_ANONYMOUS MAP_ANON
+#endif
+
 #define MAX_PATH    (2 * K)
 
 // for timer info max values which include all bits
@@ -70,19 +92,25 @@
 // global variables
 julong os::Bsd::_physical_memory = 0;
 
+#ifndef _ALLBSD_SOURCE
 address   os::Bsd::_initial_thread_stack_bottom = NULL;
 uintptr_t os::Bsd::_initial_thread_stack_size   = 0;
+#endif
 
 int (*os::Bsd::_clock_gettime)(clockid_t, struct timespec *) = NULL;
+#ifndef _ALLBSD_SOURCE
 int (*os::Bsd::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL;
 Mutex* os::Bsd::_createThread_lock = NULL;
+#endif
 pthread_t os::Bsd::_main_thread;
 int os::Bsd::_page_size = -1;
+#ifndef _ALLBSD_SOURCE
 bool os::Bsd::_is_floating_stack = false;
 bool os::Bsd::_is_NPTL = false;
 bool os::Bsd::_supports_fast_thread_cpu_time = false;
 const char * os::Bsd::_glibc_version = NULL;
 const char * os::Bsd::_libpthread_version = NULL;
+#endif
 
 static jlong initial_time_count=0;
 
@@ -100,8 +128,6 @@ static pid_t _initial_pid = 0;
 static int SR_signum = SIGUSR2;
 sigset_t SR_sigset;
 
-/* Used to protect dlsym() calls */
-static pthread_mutex_t dl_mutex;
 
 ////////////////////////////////////////////////////////////////////////////////
 // utility functions
@@ -114,11 +140,16 @@ julong os::available_memory() {
 }
 
 julong os::Bsd::available_memory() {
+#ifdef _ALLBSD_SOURCE
+  // XXXBSD: this is just a stopgap implementation
+  return physical_memory() >> 2;
+#else
   // values in struct sysinfo are "unsigned long"
   struct sysinfo si;
   sysinfo(&si);
 
   return (julong)si.freeram * si.mem_unit;
+#endif
 }
 
 julong os::physical_memory() {
@@ -166,6 +197,7 @@ bool os::have_special_privileges() {
 }
 
 
+#ifndef _ALLBSD_SOURCE
 #ifndef SYS_gettid
 // i386: 224, ia64: 1105, amd64: 186, sparc 143
 #ifdef __ia64__
@@ -180,6 +212,7 @@ bool os::have_special_privileges() {
 #error define gettid for the arch
 #endif
 #endif
+#endif
 
 // Cpu architecture string
 #if   defined(ZERO)
@@ -205,6 +238,7 @@ static char cpu_arch[] = "sparc";
 #endif
 
 
+#ifndef _ALLBSD_SOURCE
 // pid_t gettid()
 //
 // Returns the kernel thread id of the currently running thread. Kernel
@@ -231,8 +265,49 @@ static bool unsafe_chroot_detected = false;
 static const char *unstable_chroot_error = "/proc file system not found.\n"
                      "Java may be unstable running multithreaded in a chroot "
                      "environment on Bsd when /proc filesystem is not mounted.";
+#endif
 
+#ifdef _ALLBSD_SOURCE
 void os::Bsd::initialize_system_info() {
+  int mib[2];
+  size_t len;
+  int cpu_val;
+  u_long mem_val;
+
+  /* get processors count via hw.ncpus sysctl */
+  mib[0] = CTL_HW;
+  mib[1] = HW_NCPU;
+  len = sizeof(cpu_val);
+  if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
+       set_processor_count(cpu_val);
+  }
+  else {
+       set_processor_count(1);   // fallback
+  }
+
+  /* get physical memory via hw.usermem sysctl (hw.usermem is used
+   * instead of hw.physmem because we need size of allocatable memory
+   */
+  mib[0] = CTL_HW;
+  mib[1] = HW_USERMEM;
+  len = sizeof(mem_val);
+  if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1)
+       _physical_memory = mem_val;
+  else
+       _physical_memory = 256*1024*1024;       // fallback (XXXBSD?)
+
+#ifdef __OpenBSD__
+  {
+       // limit _physical_memory memory view on OpenBSD since
+       // datasize rlimit restricts us anyway.
+       struct rlimit limits;
+       getrlimit(RLIMIT_DATA, &limits);
+       _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur);
+  }
+#endif
+}
+#else
+void os::Bsd::initialize_system_info() {
   set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
   if (processor_count() == 1) {
     pid_t pid = os::Bsd::gettid();
@@ -248,6 +323,7 @@ void os::Bsd::initialize_system_info() {
   _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE);
   assert(processor_count() > 0, "bsd error");
 }
+#endif
 
 void os::init_system_properties_values() {
 //  char arch[12];
@@ -291,9 +367,7 @@ void os::init_system_properties_values() {
  *        ...
  *        7: The default directories, normally /lib and /usr/lib.
  */
-#if defined(AMD64) || defined(_LP64) && (defined(SPARC) || defined(PPC) || defined(S390))
-#define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib"
-#else
+#ifndef DEFAULT_LIBPATH
 #define DEFAULT_LIBPATH "/lib:/usr/lib"
 #endif
 
@@ -372,7 +446,11 @@ void os::init_system_properties_values() {
          * should always exist (until the legacy problem cited above is
          * addressed).
          */
+#ifdef __APPLE__
+        char *v = getenv("DYLD_LIBRARY_PATH");
+#else
         char *v = getenv("LD_LIBRARY_PATH");
+#endif
         if (v != NULL) {
             char *t = ld_library_path;
             /* That's +1 for the colon and +1 for the trailing '\0' */
@@ -531,6 +609,7 @@ void os::Bsd::hotspot_sigmask(Thread* thread) {
   }
 }
 
+#ifndef _ALLBSD_SOURCE
 //////////////////////////////////////////////////////////////////////////////
 // detecting pthread library
 
@@ -694,6 +773,7 @@ bool os::Bsd::manually_expand_stack(JavaThread * t, ad
   }
   return false;
 }
+#endif
 
 //////////////////////////////////////////////////////////////////////////////
 // create new thread
@@ -702,6 +782,9 @@ static address highest_vm_reserved_address();
 
 // check if it's safe to start a new thread
 static bool _thread_safety_check(Thread* thread) {
+#ifdef _ALLBSD_SOURCE
+    return true;
+#else
   if (os::Bsd::is_BsdThreads() && !os::Bsd::is_floating_stack()) {
     // Fixed stack BsdThreads (SuSE Bsd/x86, and some versions of Redhat)
     //   Heap is mmap'ed at lower end of memory space. Thread stacks are
@@ -735,6 +818,7 @@ static bool _thread_safety_check(Thread* thread) {
     //   here, that means enough space has been reserved for stack.
     return true;
   }
+#endif
 }
 
 // Thread start routine for all newly created threads
@@ -762,6 +846,10 @@ static void *java_start(Thread *thread) {
     return NULL;
   }
 
+#ifdef _ALLBSD_SOURCE
+  // thread_id is pthread_id on BSD
+  osthread->set_thread_id(::pthread_self());
+#else
   // thread_id is kernel thread id (similar to Solaris LWP id)
   osthread->set_thread_id(os::Bsd::gettid());
 
@@ -771,6 +859,7 @@ static void *java_start(Thread *thread) {
       thread->set_lgrp_id(lgrp_id);
     }
   }
+#endif
   // initialize signal mask for this thread
   os::Bsd::hotspot_sigmask(thread);
 
@@ -853,17 +942,22 @@ bool os::create_thread(Thread* thread, ThreadType thr_
     // let pthread_create() pick the default value.
   }
 
+#ifndef _ALLBSD_SOURCE
   // glibc guard page
   pthread_attr_setguardsize(&attr, os::Bsd::default_guard_size(thr_type));
+#endif
 
   ThreadState state;
 
   {
+
+#ifndef _ALLBSD_SOURCE
     // Serialize thread creation if we are running with fixed stack BsdThreads
     bool lock = os::Bsd::is_BsdThreads() && !os::Bsd::is_floating_stack();
     if (lock) {
       os::Bsd::createThread_lock()->lock_without_safepoint_check();
     }
+#endif
 
     pthread_t tid;
     int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread);
@@ -877,7 +971,9 @@ bool os::create_thread(Thread* thread, ThreadType thr_
       // Need to clean up stuff we've allocated so far
       thread->set_osthread(NULL);
       delete osthread;
+#ifndef _ALLBSD_SOURCE
       if (lock) os::Bsd::createThread_lock()->unlock();
+#endif
       return false;
     }
 
@@ -893,9 +989,11 @@ bool os::create_thread(Thread* thread, ThreadType thr_
       }
     }
 
+#ifndef _ALLBSD_SOURCE
     if (lock) {
       os::Bsd::createThread_lock()->unlock();
     }
+#endif
   }
 
   // Aborted due to thread limit being reached
@@ -933,7 +1031,11 @@ bool os::create_attached_thread(JavaThread* thread) {
   }
 
   // Store pthread info into the OSThread
+#ifdef _ALLBSD_SOURCE
+  osthread->set_thread_id(::pthread_self());
+#else
   osthread->set_thread_id(os::Bsd::gettid());
+#endif
   osthread->set_pthread_id(::pthread_self());
 
   // initialize floating point control register
@@ -944,6 +1046,7 @@ bool os::create_attached_thread(JavaThread* thread) {
 
   thread->set_osthread(osthread);
 
+#ifndef _ALLBSD_SOURCE
   if (UseNUMA) {
     int lgrp_id = os::numa_get_group_id();
     if (lgrp_id != -1) {
@@ -970,6 +1073,7 @@ bool os::create_attached_thread(JavaThread* thread) {
     os::Bsd::manually_expand_stack(jt, addr);
     osthread->clear_expanding_stack();
   }
+#endif
 
   // initialize signal mask for this thread
   // and save the caller's signal mask
@@ -1028,6 +1132,7 @@ extern "C" Thread* get_thread() {
 //////////////////////////////////////////////////////////////////////////////
 // initial thread
 
+#ifndef _ALLBSD_SOURCE
 // Check if current thread is the initial thread, similar to Solaris thr_main.
 bool os::Bsd::is_initial_thread(void) {
   char dummy;
@@ -1264,6 +1369,7 @@ void os::Bsd::capture_initial_stack(size_t max_size) {
   _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size());
   _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size;
 }
+#endif
 
 ////////////////////////////////////////////////////////////////////////////////
 // time support
@@ -1285,9 +1391,7 @@ jlong os::elapsed_frequency() {
   return (1000 * 1000);
 }
 
-// For now, we say that bsd does not support vtime.  I have no idea
-// whether it can actually be made to (DLD, 9/13/05).
-
+// XXX: For now, code this as if BSD does not support vtime.
 bool os::supports_vtime() { return false; }
 bool os::enable_vtime()   { return false; }
 bool os::vtime_enabled()  { return false; }
@@ -1307,7 +1411,22 @@ jlong os::javaTimeMillis() {
 #define CLOCK_MONOTONIC (1)
 #endif
 
+#ifdef __APPLE__
 void os::Bsd::clock_init() {
+	// XXXDARWIN: Investigate replacement monotonic clock
+}
+#elif defined(_ALLBSD_SOURCE)
+void os::Bsd::clock_init() {
+  struct timespec res;
+  struct timespec tp;
+  if (::clock_getres(CLOCK_MONOTONIC, &res) == 0 &&
+      ::clock_gettime(CLOCK_MONOTONIC, &tp)  == 0) {
+    // yes, monotonic clock is supported
+    _clock_gettime = ::clock_gettime;
+  }
+}
+#else
+void os::Bsd::clock_init() {
   // we do dlopen's in this particular order due to bug in bsd
   // dynamical loader (see 6348968) leading to crash on exit
   void* handle = dlopen("librt.so.1", RTLD_LAZY);
@@ -1342,7 +1461,9 @@ void os::Bsd::clock_init() {
     }
   }
 }
+#endif
 
+#ifndef _ALLBSD_SOURCE
 #ifndef SYS_clock_getres
 
 #if defined(IA32) || defined(AMD64)
@@ -1383,6 +1504,7 @@ void os::Bsd::fast_thread_clock_init() {
     _pthread_getcpuclockid = pthread_getcpuclockid_func;
   }
 }
+#endif
 
 jlong os::javaTimeNanos() {
   if (Bsd::supports_monotonic_clock()) {
@@ -1533,8 +1655,15 @@ int os::current_process_id() {
 
 // DLL functions
 
-const char* os::dll_file_extension() { return ".so"; }
+#define JNI_LIB_PREFIX "lib"
+#ifdef __APPLE__
+#define JNI_LIB_SUFFIX ".dylib"
+#else
+#define JNI_LIB_SUFFIX ".so"
+#endif
 
+const char* os::dll_file_extension() { return JNI_LIB_SUFFIX; }
+
 const char* os::get_temp_directory() {
   const char *prop = Arguments::get_property("java.io.tmpdir");
   return prop == NULL ? "/tmp" : prop;
@@ -1554,13 +1683,13 @@ void os::dll_build_name(char* buffer, size_t buflen,
   const size_t pnamelen = pname ? strlen(pname) : 0;
 
   // Quietly truncate on buffer overflow.  Should be an error.
-  if (pnamelen + strlen(fname) + 10 > (size_t) buflen) {
+  if (pnamelen + strlen(fname) + strlen(JNI_LIB_PREFIX) + strlen(JNI_LIB_SUFFIX) + 2 > buflen) {
       *buffer = '\0';
       return;
   }
 
   if (pnamelen == 0) {
-    snprintf(buffer, buflen, "lib%s.so", fname);
+    snprintf(buffer, buflen, JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, fname);
   } else if (strchr(pname, *os::path_separator()) != NULL) {
     int n;
     char** pelements = split_path(pname, &n);
@@ -1569,7 +1698,8 @@ void os::dll_build_name(char* buffer, size_t buflen,
       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
         continue; // skip the empty path values
       }
-      snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname);
+      snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX,
+          pelements[i], fname);
       if (file_exists(buffer)) {
         break;
       }
@@ -1584,7 +1714,7 @@ void os::dll_build_name(char* buffer, size_t buflen,
       FREE_C_HEAP_ARRAY(char*, pelements);
     }
   } else {
-    snprintf(buffer, buflen, "%s/lib%s.so", pname, fname);
+    snprintf(buffer, buflen, "%s/" JNI_LIB_PREFIX "%s" JNI_LIB_SUFFIX, pname, fname);
   }
 }
 
@@ -1625,6 +1755,23 @@ bool os::dll_address_to_function_name(address addr, ch
   }
 }
 
+#ifdef _ALLBSD_SOURCE
+// ported from solaris version
+bool os::dll_address_to_library_name(address addr, char* buf,
+                                     int buflen, int* offset) {
+  Dl_info dlinfo;
+
+  if (dladdr((void*)addr, &dlinfo)){
+     if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
+     if (offset) *offset = addr - (address)dlinfo.dli_fbase;
+     return true;
+  } else {
+     if (buf) buf[0] = '\0';
+     if (offset) *offset = -1;
+     return false;
+  }
+}
+#else
 struct _address_to_library_name {
   address addr;          // input : memory address
   size_t  buflen;        //         size of fname
@@ -1699,11 +1846,27 @@ bool os::dll_address_to_library_name(address addr, cha
      return false;
   }
 }
+#endif
 
   // Loads .dll/.so and
   // in case of error it checks if .dll/.so was built for the
   // same architecture as Hotspot is running on
+ 
+#ifdef __APPLE__
+void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
+  void * result= ::dlopen(filename, RTLD_LAZY);
+  if (result != NULL) {
+    // Successful loading
+    return result;
+  }
 
+  // Read system error message into ebuf
+  ::strncpy(ebuf, ::dlerror(), ebuflen-1);
+  ebuf[ebuflen-1]='\0';
+
+  return NULL;
+}
+#else
 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
 {
   void * result= ::dlopen(filename, RTLD_LAZY);
@@ -1756,6 +1919,26 @@ void * os::dll_load(const char *filename, char *ebuf, 
   #define EM_486          6               /* Intel 80486 */
   #endif
 
+  #ifndef EM_MIPS_RS3_LE
+  #define EM_MIPS_RS3_LE  10              /* MIPS */
+  #endif
+
+  #ifndef EM_PPC64
+  #define EM_PPC64        21              /* PowerPC64 */
+  #endif
+
+  #ifndef EM_S390
+  #define EM_S390         22              /* IBM System/390 */
+  #endif
+
+  #ifndef EM_IA_64
+  #define EM_IA_64        50              /* HP/Intel IA-64 */ 
+  #endif
+
+  #ifndef EM_X86_64
+  #define EM_X86_64       62              /* AMD x86-64 */ 
+  #endif
+
   static const arch_t arch_array[]={
     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
@@ -1859,17 +2042,11 @@ void * os::dll_load(const char *filename, char *ebuf, 
 
   return NULL;
 }
+#endif /* !__APPLE__ */
 
-/*
- * glibc-2.0 libdl is not MT safe.  If you are building with any glibc,
- * chances are you might want to run the generated bits against glibc-2.0
- * libdl.so, so always use locking for any version of glibc.
- */
+// XXX: Do we need a lock around this as per Linux?
 void* os::dll_lookup(void* handle, const char* name) {
-  pthread_mutex_lock(&dl_mutex);
-  void* res = dlsym(handle, name);
-  pthread_mutex_unlock(&dl_mutex);
-  return res;
+  return dlsym(handle, name);
 }
 
 
@@ -1892,7 +2069,51 @@ bool _print_ascii_file(const char* filename, outputStr
 
 void os::print_dll_info(outputStream *st) {
    st->print_cr("Dynamic libraries:");
+#ifdef _ALLBSD_SOURCE
+#ifdef RTLD_DI_LINKMAP
+    Dl_info dli;
+    void *handle;
+    Link_map *map;
+    Link_map *p;
 
+    if (!dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli)) {
+        st->print_cr("Error: Cannot print dynamic libraries.");
+        return;
+    }
+    handle = dlopen(dli.dli_fname, RTLD_LAZY);
+    if (handle == NULL) {
+        st->print_cr("Error: Cannot print dynamic libraries.");
+        return;
+    }
+    dlinfo(handle, RTLD_DI_LINKMAP, &map);
+    if (map == NULL) {
+        st->print_cr("Error: Cannot print dynamic libraries.");
+        return;
+    }
+
+    while (map->l_prev != NULL)
+        map = map->l_prev;
+
+    while (map != NULL) {
+        st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name);
+        map = map->l_next;
+    }
+
+    dlclose(handle);
+#elif defined(__APPLE__)
+    uint32_t count;
+    uint32_t i;
+
+    count = _dyld_image_count();
+    for (i = 1; i < count; i++) {
+        const char *name = _dyld_get_image_name(i);
+        intptr_t slide = _dyld_get_image_vmaddr_slide(i);
+        st->print_cr(PTR_FORMAT " \t%s", slide, name);
+    }
+#else
+   st->print_cr("Error: Cannot print dynamic libraries.");
+#endif
+#else
    char fname[32];
    pid_t pid = os::Bsd::gettid();
 
@@ -1901,6 +2122,7 @@ void os::print_dll_info(outputStream *st) {
    if (!_print_ascii_file(fname, st)) {
      st->print("Can not get library information for pid = %d\n", pid);
    }
+#endif
 }
 
 
@@ -1935,6 +2157,7 @@ void os::print_os_info(outputStream* st) {
   st->print(name.machine);
   st->cr();
 
+#ifndef _ALLBSD_SOURCE
   // Print warning if unsafe chroot environment detected
   if (unsafe_chroot_detected) {
     st->print("WARNING!! ");
@@ -1949,6 +2172,7 @@ void os::print_os_info(outputStream* st) {
      st->print("(%s stack)", os::Bsd::is_floating_stack() ? "floating" : "fixed");
   }
   st->cr();
+#endif
 
   // rlimit
   st->print("rlimit:");
@@ -1974,6 +2198,7 @@ void os::print_os_info(outputStream* st) {
   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
   else st->print("%d", rlim.rlim_cur);
 
+#ifndef _ALLBSD_SOURCE
   st->print(", AS ");
   getrlimit(RLIMIT_AS, &rlim);
   if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity");
@@ -1986,11 +2211,7 @@ void os::print_os_info(outputStream* st) {
   os::loadavg(loadavg, 3);
   st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]);
   st->cr();
-
-  // meminfo
-  st->print("\n/proc/meminfo:\n");
-  _print_ascii_file("/proc/meminfo", st);
-  st->cr();
+#endif
 }
 
 void os::print_memory_info(outputStream* st) {
@@ -1998,19 +2219,28 @@ void os::print_memory_info(outputStream* st) {
   st->print("Memory:");
   st->print(" %dk page", os::vm_page_size()>>10);
 
+#ifndef _ALLBSD_SOURCE
   // values in struct sysinfo are "unsigned long"
   struct sysinfo si;
   sysinfo(&si);
+#endif
 
   st->print(", physical " UINT64_FORMAT "k",
             os::physical_memory() >> 10);
   st->print("(" UINT64_FORMAT "k free)",
             os::available_memory() >> 10);
+#ifndef _ALLBSD_SOURCE
   st->print(", swap " UINT64_FORMAT "k",
             ((jlong)si.totalswap * si.mem_unit) >> 10);
   st->print("(" UINT64_FORMAT "k free)",
             ((jlong)si.freeswap * si.mem_unit) >> 10);
+#endif
   st->cr();
+
+  // meminfo
+  st->print("\n/proc/meminfo:\n");
+  _print_ascii_file("/proc/meminfo", st);
+  st->cr();
 }
 
 // Taken from /usr/include/bits/siginfo.h  Supposed to be architecture specific
@@ -2252,19 +2482,29 @@ int os::sigexitnum_pd() {
 static volatile jint pending_signals[NSIG+1] = { 0 };
 
 // Bsd(POSIX) specific hand shaking semaphore.
+#ifdef __APPLE__
+static semaphore_t sig_sem;
+#define SEM_INIT(sem, value)	semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO, value)
+#define SEM_WAIT(sem)		semaphore_wait(sem);
+#define SEM_POST(sem)		semaphore_signal(sem);
+#else
 static sem_t sig_sem;
+#define SEM_INIT(sem, value)	sem_init(&sem, 0, value)
+#define SEM_WAIT(sem)		sem_wait(&sem);
+#define SEM_POST(sem)		sem_post(&sem);
+#endif
 
 void os::signal_init_pd() {
   // Initialize signal structures
   ::memset((void*)pending_signals, 0, sizeof(pending_signals));
 
   // Initialize signal semaphore
-  ::sem_init(&sig_sem, 0, 0);
+  ::SEM_INIT(sig_sem, 0);
 }
 
 void os::signal_notify(int sig) {
   Atomic::inc(&pending_signals[sig]);
-  ::sem_post(&sig_sem);
+  ::SEM_POST(sig_sem);
 }
 
 static int check_pending_signals(bool wait) {
@@ -2286,7 +2526,7 @@ static int check_pending_signals(bool wait) {
     do {
       thread->set_suspend_equivalent();
       // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self()
-      ::sem_wait(&sig_sem);
+      ::SEM_WAIT(sig_sem);
 
       // were we externally suspended while we were waiting?
       threadIsSuspended = thread->handle_special_suspend_equivalent_condition();
@@ -2297,7 +2537,7 @@ static int check_pending_signals(bool wait) {
         // while suspended because that would surprise the thread that
         // suspended us.
         //
-        ::sem_post(&sig_sem);
+        ::SEM_POST(sig_sem);
 
         thread->java_suspend_self();
       }
@@ -2341,10 +2581,10 @@ void bsd_wrap_code(char* base, size_t size) {
     return;
   }
 
-  char buf[PATH_MAX+1];
+  char buf[PATH_MAX + 1];
   int num = Atomic::add(1, &cnt);
 
-  snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d",
+  snprintf(buf, PATH_MAX + 1, "%s/hs-vm-%d-%d",
            os::get_temp_directory(), os::current_process_id(), num);
   unlink(buf);
 
@@ -2370,9 +2610,14 @@ void bsd_wrap_code(char* base, size_t size) {
 //       problem.
 bool os::commit_memory(char* addr, size_t size, bool exec) {
   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
+#ifdef __OpenBSD__
+  // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
+  return ::mprotect(addr, size, prot) == 0;
+#else
   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
                                    MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
   return res != (uintptr_t) MAP_FAILED;
+#endif
 }
 
 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
@@ -2388,36 +2633,27 @@ void os::free_memory(char *addr, size_t bytes) {
 }
 
 void os::numa_make_global(char *addr, size_t bytes) {
-  Bsd::numa_interleave_memory(addr, bytes);
 }
 
 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
-  Bsd::numa_tonode_memory(addr, bytes, lgrp_hint);
 }
 
 bool os::numa_topology_changed()   { return false; }
 
 size_t os::numa_get_groups_num() {
-  int max_node = Bsd::numa_max_node();
-  return max_node > 0 ? max_node + 1 : 1;
+  return 1;
 }
 
 int os::numa_get_group_id() {
-  int cpu_id = Bsd::sched_getcpu();
-  if (cpu_id != -1) {
-    int lgrp_id = Bsd::get_node_by_cpu(cpu_id);
-    if (lgrp_id != -1) {
-      return lgrp_id;
-    }
-  }
   return 0;
 }
 
 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
-  for (size_t i = 0; i < size; i++) {
-    ids[i] = i;
+  if (size > 0) {
+    ids[0] = 0;
+    return 1;
   }
-  return size;
+  return 0;
 }
 
 bool os::get_page_info(char *start, page_info* info) {
@@ -2428,6 +2664,7 @@ char *os::scan_pages(char *start, char* end, page_info
   return end;
 }
 
+#ifndef _ALLBSD_SOURCE
 extern "C" void numa_warn(int number, char *where, ...) { }
 extern "C" void numa_error(char *where) { }
 
@@ -2529,104 +2766,26 @@ os::Bsd::numa_available_func_t os::Bsd::_numa_availabl
 os::Bsd::numa_tonode_memory_func_t os::Bsd::_numa_tonode_memory;
 os::Bsd::numa_interleave_memory_func_t os::Bsd::_numa_interleave_memory;
 unsigned long* os::Bsd::_numa_all_nodes;
+#endif
 
 bool os::uncommit_memory(char* addr, size_t size) {
+#ifdef __OpenBSD__
+  // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
+  return ::mprotect(addr, size, PROT_NONE) == 0;
+#else
   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
                 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
   return res  != (uintptr_t) MAP_FAILED;
+#endif
 }
 
-// Bsd uses a growable mapping for the stack, and if the mapping for
-// the stack guard pages is not removed when we detach a thread the
-// stack cannot grow beyond the pages where the stack guard was
-// mapped.  If at some point later in the process the stack expands to
-// that point, the Bsd kernel cannot expand the stack any further
-// because the guard pages are in the way, and a segfault occurs.
-//
-// However, it's essential not to split the stack region by unmapping
-// a region (leaving a hole) that's already part of the stack mapping,
-// so if the stack mapping has already grown beyond the guard pages at
-// the time we create them, we have to truncate the stack mapping.
-// So, we need to know the extent of the stack mapping when
-// create_stack_guard_pages() is called.
-
-// Find the bounds of the stack mapping.  Return true for success.
-//
-// We only need this for stacks that are growable: at the time of
-// writing thread stacks don't use growable mappings (i.e. those
-// creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this
-// only applies to the main thread.
-static bool
-get_stack_bounds(uintptr_t *bottom, uintptr_t *top)
-{
-  FILE *f = fopen("/proc/self/maps", "r");
-  if (f == NULL)
-    return false;
-
-  while (!feof(f)) {
-    size_t dummy;
-    char *str = NULL;
-    ssize_t len = getline(&str, &dummy, f);
-    if (len == -1) {
-      fclose(f);
-      return false;
-    }
-
-    if (len > 0 && str[len-1] == '\n') {
-      str[len-1] = 0;
-      len--;
-    }
-
-    static const char *stack_str = "[stack]";
-    if (len > (ssize_t)strlen(stack_str)
-       && (strcmp(str + len - strlen(stack_str), stack_str) == 0)) {
-      if (sscanf(str, "%" SCNxPTR "-%" SCNxPTR, bottom, top) == 2) {
-        uintptr_t sp = (uintptr_t)__builtin_frame_address(0);
-        if (sp >= *bottom && sp <= *top) {
-          free(str);
-          fclose(f);
-          return true;
-        }
-      }
-    }
-    free(str);
-  }
-  fclose(f);
-  return false;
-}
-
-// If the (growable) stack mapping already extends beyond the point
-// where we're going to put our guard pages, truncate the mapping at
-// that point by munmap()ping it.  This ensures that when we later
-// munmap() the guard pages we don't leave a hole in the stack
-// mapping. This only affects the main/initial thread, but guard
-// against future OS changes
 bool os::create_stack_guard_pages(char* addr, size_t size) {
-  uintptr_t stack_extent, stack_base;
-  bool chk_bounds = NOT_DEBUG(os::Bsd::is_initial_thread()) DEBUG_ONLY(true);
-  if (chk_bounds && get_stack_bounds(&stack_extent, &stack_base)) {
-      assert(os::Bsd::is_initial_thread(),
-           "growable stack in non-initial thread");
-    if (stack_extent < (uintptr_t)addr)
-      ::munmap((void*)stack_extent, (uintptr_t)addr - stack_extent);
-  }
-
   return os::commit_memory(addr, size);
 }
 
 // If this is a growable mapping, remove the guard pages entirely by
-// munmap()ping them.  If not, just call uncommit_memory(). This only
-// affects the main/initial thread, but guard against future OS changes
+// munmap()ping them.  If not, just call uncommit_memory().
 bool os::remove_stack_guard_pages(char* addr, size_t size) {
-  uintptr_t stack_extent, stack_base;
-  bool chk_bounds = NOT_DEBUG(os::Bsd::is_initial_thread()) DEBUG_ONLY(true);
-  if (chk_bounds && get_stack_bounds(&stack_extent, &stack_base)) {
-      assert(os::Bsd::is_initial_thread(),
-           "growable stack in non-initial thread");
-
-    return ::munmap(addr, size) == 0;
-  }
-
   return os::uncommit_memory(addr, size);
 }
 
@@ -2731,6 +2890,9 @@ bool os::unguard_memory(char* addr, size_t size) {
 static size_t _large_page_size = 0;
 
 bool os::large_page_init() {
+#ifdef _ALLBSD_SOURCE
+  return false;
+#else
   if (!UseLargePages) return false;
 
   if (LargePageSizeInBytes) {
@@ -2788,6 +2950,7 @@ bool os::large_page_init() {
   // We optimistically assume the support is available. If later it turns out
   // not true, VM will automatically switch to use regular page size.
   return true;
+#endif
 }
 
 #ifndef SHM_HUGETLB
@@ -2964,7 +3127,7 @@ char* os::attempt_reserve_memory_at(size_t bytes, char
 }
 
 size_t os::read(int fd, void *buf, unsigned int nBytes) {
-  return ::read(fd, buf, nBytes);
+  RESTARTABLE_RETURN_INT(::read(fd, buf, nBytes));
 }
 
 // TODO-FIXME: reconcile Solaris' os::sleep with the bsd variation.
@@ -3100,9 +3263,47 @@ void os::loop_breaker(int attempts) {
 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
 // It is only used when ThreadPriorityPolicy=1 and requires root privilege.
 
+#if defined(_ALLBSD_SOURCE) && !defined(__APPLE__)
 int os::java_to_os_priority[MaxPriority + 1] = {
   19,              // 0 Entry should never be used
 
+   0,              // 1 MinPriority
+   3,              // 2
+   6,              // 3
+
+   10,              // 4
+   15,              // 5 NormPriority
+   18,              // 6
+
+   21,              // 7
+   25,              // 8
+   28,              // 9 NearMaxPriority
+
+   31              // 10 MaxPriority
+};
+#elif defined(__APPLE__)
+/* Using Mach high-level priority assignments */
+int os::java_to_os_priority[MaxPriority + 1] = {
+   0,              // 0 Entry should never be used (MINPRI_USER)
+
+  27,              // 1 MinPriority
+  28,              // 2
+  29,              // 3
+
+  30,              // 4
+  31,              // 5 NormPriority (BASEPRI_DEFAULT)
+  32,              // 6
+
+  33,              // 7
+  34,              // 8
+  35,              // 9 NearMaxPriority
+
+  36               // 10 MaxPriority
+};
+#else
+int os::java_to_os_priority[MaxPriority + 1] = {
+  19,              // 0 Entry should never be used
+
    4,              // 1 MinPriority
    3,              // 2
    2,              // 3
@@ -3117,6 +3318,7 @@ int os::java_to_os_priority[MaxPriority + 1] = {
 
   -5               // 10 MaxPriority
 };
+#endif
 
 static int prio_init() {
   if (ThreadPriorityPolicy == 1) {
@@ -3136,8 +3338,28 @@ static int prio_init() {
 OSReturn os::set_native_priority(Thread* thread, int newpri) {
   if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK;
 
+#ifdef __OpenBSD__
+  // OpenBSD pthread_setprio starves low priority threads
+  return OS_OK;
+#elif defined(__FreeBSD__)
+  int ret = pthread_setprio(thread->osthread()->pthread_id(), newpri);
+#elif defined(__APPLE__) || defined(__NetBSD__)
+  struct sched_param sp;
+  int policy;
+  pthread_t self = pthread_self();
+
+  if (pthread_getschedparam(self, &policy, &sp) != 0)
+    return OS_ERR;
+
+  sp.sched_priority = newpri;
+  if (pthread_setschedparam(self, policy, &sp) != 0)
+    return OS_ERR;
+
+  return OS_OK;
+#else
   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
   return (ret == 0) ? OS_OK : OS_ERR;
+#endif
 }
 
 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) {
@@ -3147,7 +3369,17 @@ OSReturn os::get_native_priority(const Thread* const t
   }
 
   errno = 0;
+#if defined(__OpenBSD__) || defined(__FreeBSD__)
+  *priority_ptr = pthread_getprio(thread->osthread()->pthread_id());
+#elif defined(__APPLE__) || defined(__NetBSD__)
+  int policy;
+  struct sched_param sp;
+
+  pthread_getschedparam(pthread_self(), &policy, &sp);
+  *priority_ptr = sp.sched_priority;
+#else
   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
+#endif
   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
 }
 
@@ -3257,7 +3489,7 @@ static int SR_initialize() {
   /* Get signal number to use for suspend/resume */
   if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) {
     int sig = ::strtol(s, 0, 10);
-    if (sig > 0 || sig < _NSIG) {
+    if (sig > 0 || sig < NSIG) {
         SR_signum = sig;
     }
   }
@@ -3601,6 +3833,28 @@ void os::Bsd::install_signal_handlers() {
     set_signal_handler(SIGFPE, true);
     set_signal_handler(SIGXFSZ, true);
 
+#if defined(__APPLE__)
+    // In Mac OS X 10.4, CrashReporter will write a crash log for all 'fatal' signals, including
+    // signals caught and handled by the JVM. To work around this, we reset the mach task
+    // signal handler that's placed on our process by CrashReporter. This disables
+    // CrashReporter-based reporting.
+    //
+    // This work-around is not necessary for 10.5+, as CrashReporter no longer intercedes
+    // on caught fatal signals.
+    //
+    // Additionally, gdb installs both standard BSD signal handlers, and mach exception
+    // handlers. By replacing the existing task exception handler, we disable gdb's mach
+    // exception handling, while leaving the standard BSD signal handlers functional.
+    kern_return_t kr;
+    kr = task_set_exception_ports(mach_task_self(),
+        EXC_MASK_BAD_ACCESS | EXC_MASK_ARITHMETIC,
+        MACH_PORT_NULL,
+        EXCEPTION_STATE_IDENTITY,
+        MACHINE_THREAD_STATE);
+
+    assert(kr == KERN_SUCCESS, "could not set mach task signal handler");
+#endif
+
     if (libjsig_is_loaded) {
       // Tell libjsig jvm finishes setting signal handlers
       (*end_signal_setting)();
@@ -3621,6 +3875,7 @@ void os::Bsd::install_signal_handlers() {
   }
 }
 
+#ifndef _ALLBSD_SOURCE
 // This is the fastest way to get thread cpu time on Bsd.
 // Returns cpu time (user+sys) for any thread, not only for current.
 // POSIX compliant clocks are implemented in the kernels 2.6.16+.
@@ -3635,6 +3890,7 @@ jlong os::Bsd::fast_thread_cpu_time(clockid_t clockid)
 
   return (tp.tv_sec * SEC_IN_NANOSECS) + tp.tv_nsec;
 }
+#endif
 
 /////
 // glibc on Bsd platform uses non-documented flag
@@ -3856,13 +4112,13 @@ void os::init(void) {
 
   _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid();
 
-  clock_tics_per_sec = sysconf(_SC_CLK_TCK);
+  clock_tics_per_sec = CLK_TCK;
 
   init_random(1234567);
 
   ThreadCritical::initialize();
 
-  Bsd::set_page_size(sysconf(_SC_PAGESIZE));
+  Bsd::set_page_size(getpagesize());
   if (Bsd::page_size() == -1) {
     fatal(err_msg("os_bsd.cpp: os::init: sysconf failed (%s)",
                   strerror(errno)));
@@ -3876,7 +4132,16 @@ void os::init(void) {
 
   Bsd::clock_init();
   initial_time_count = os::elapsed_counter();
-  pthread_mutex_init(&dl_mutex, NULL);
+
+#ifdef __APPLE__
+  // XXXDARWIN
+  // Work around the unaligned VM callbacks in hotspot's
+  // sharedRuntime. The callbacks don't use SSE2 instructions, and work on
+  // Linux, Solaris, and FreeBSD. On Mac OS X, dyld (rightly so) enforces
+  // alignment when doing symbol lookup. To work around this, we force early
+  // binding of all symbols now, thus binding when alignment is known-good.
+  _dyld_bind_fully_image_containing_address((const void *) &os::init);
+#endif
 }
 
 // To install functions for atexit system call
@@ -3889,7 +4154,9 @@ extern "C" {
 // this is called _after_ the global arguments have been parsed
 jint os::init_2(void)
 {
+#ifndef _ALLBSD_SOURCE
   Bsd::fast_thread_clock_init();
+#endif
 
   // Allocate a single page and mark it as readable for safepoint polling
   address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
@@ -3947,6 +4214,7 @@ jint os::init_2(void)
   JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes,
         vm_page_size()));
 
+#ifndef _ALLBSD_SOURCE
   Bsd::capture_initial_stack(JavaThread::stack_size_at_create());
 
   Bsd::libpthread_init();
@@ -3969,6 +4237,7 @@ jint os::init_2(void)
       UseNUMA = true;
     }
   }
+#endif
 
   if (MaxFDLimit) {
     // set the number of file descriptors to max. print out error
@@ -3980,6 +4249,14 @@ jint os::init_2(void)
         perror("os::init_2 getrlimit failed");
     } else {
       nbr_files.rlim_cur = nbr_files.rlim_max;
+      
+#ifdef __APPLE__
+      // Darwin returns RLIM_INFINITY for rlim_max, but fails with EINVAL if
+      // you attempt to use RLIM_INFINITY. As per setrlimit(2), OPEN_MAX must
+      // be used instead
+      nbr_files.rlim_cur = MIN(OPEN_MAX, nbr_files.rlim_cur);
+#endif
+
       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
       if (status != 0) {
         if (PrintMiscellaneous && (Verbose || WizardMode))
@@ -3988,8 +4265,10 @@ jint os::init_2(void)
     }
   }
 
+#ifndef _ALLBSD_SOURCE
   // Initialize lock used to serialize thread creation (see os::create_thread)
   Bsd::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false));
+#endif
 
   // Initialize HPI.
   jint hpi_result = hpi::initialize();
@@ -4040,11 +4319,15 @@ void os::make_polling_page_readable(void) {
 };
 
 int os::active_processor_count() {
+#ifdef _ALLBSD_SOURCE
+  return _processor_count;
+#else
   // Bsd doesn't yet have a (official) notion of processor sets,
   // so just return the number of online processors.
   int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
   assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check");
   return online_cpus;
+#endif
 }
 
 bool os::distribute_processes(uint length, uint* distribution) {
@@ -4086,6 +4369,9 @@ ExtendedPC os::get_thread_pc(Thread* thread) {
 
 int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime)
 {
+#ifdef _ALLBSD_SOURCE
+  return pthread_cond_timedwait(_cond, _mutex, _abstime);
+#else
    if (is_NPTL()) {
       return pthread_cond_timedwait(_cond, _mutex, _abstime);
    } else {
@@ -4101,6 +4387,7 @@ int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond
 #endif // IA64
       return status;
    }
+#endif
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -4233,17 +4520,17 @@ int os::create_binary_file(const char* path, bool rewr
   if (!rewrite_existing) {
     oflags |= O_EXCL;
   }
-  return ::open64(path, oflags, S_IREAD | S_IWRITE);
+  return ::open(path, oflags, S_IREAD | S_IWRITE);
 }
 
 // return current position of file pointer
 jlong os::current_file_offset(int fd) {
-  return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
+  return (jlong)::lseek(fd, (off_t)0, SEEK_CUR);
 }
 
 // move file pointer to the specified offset
 jlong os::seek_to_file_offset(int fd, jlong offset) {
-  return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
+  return (jlong)::lseek(fd, (off_t)offset, SEEK_SET);
 }
 
 // Map a block of memory.
@@ -4293,6 +4580,7 @@ bool os::unmap_memory(char* addr, size_t bytes) {
   return munmap(addr, bytes) == 0;
 }
 
+#ifndef _ALLBSD_SOURCE
 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time);
 
 static clockid_t thread_cpu_clockid(Thread* thread) {
@@ -4304,6 +4592,7 @@ static clockid_t thread_cpu_clockid(Thread* thread) {
   assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code");
   return clockid;
 }
+#endif
 
 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
@@ -4313,39 +4602,71 @@ static clockid_t thread_cpu_clockid(Thread* thread) {
 // the fast estimate available on the platform.
 
 jlong os::current_thread_cpu_time() {
+#ifdef __APPLE__
+  return os::thread_cpu_time(Thread::current(), true /* user + sys */);
+#elif !defined(_ALLBSD_SOURCE)
   if (os::Bsd::supports_fast_thread_cpu_time()) {
     return os::Bsd::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
   } else {
     // return user + sys since the cost is the same
     return slow_thread_cpu_time(Thread::current(), true /* user + sys */);
   }
+#endif
 }
 
 jlong os::thread_cpu_time(Thread* thread) {
+#ifndef _ALLBSD_SOURCE
   // consistent with what current_thread_cpu_time() returns
   if (os::Bsd::supports_fast_thread_cpu_time()) {
     return os::Bsd::fast_thread_cpu_time(thread_cpu_clockid(thread));
   } else {
     return slow_thread_cpu_time(thread, true /* user + sys */);
   }
+#endif
 }
 
 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
+#ifdef __APPLE__
+  return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
+#elif !defined(_ALLBSD_SOURCE)
   if (user_sys_cpu_time && os::Bsd::supports_fast_thread_cpu_time()) {
     return os::Bsd::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
   } else {
     return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time);
   }
+#endif
 }
 
 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
+#ifdef __APPLE__
+  struct thread_basic_info tinfo;
+  mach_msg_type_number_t tcount = THREAD_INFO_MAX;
+  kern_return_t kr;
+  mach_port_t mach_thread;
+
+  mach_thread = pthread_mach_thread_np(thread->osthread()->thread_id());
+  kr = thread_info(mach_thread, THREAD_BASIC_INFO, (thread_info_t)&tinfo, &tcount);
+  if (kr != KERN_SUCCESS)
+    return -1;
+
+  if (user_sys_cpu_time) {
+    jlong nanos;
+    nanos = ((jlong) tinfo.system_time.seconds + tinfo.user_time.seconds) * (jlong)1000000000;
+    nanos += ((jlong) tinfo.system_time.microseconds + (jlong) tinfo.user_time.microseconds) * (jlong)1000;
+    return nanos;
+  } else {
+    return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
+  }
+#elif !defined(_ALLBSD_SOURCE)
   if (user_sys_cpu_time && os::Bsd::supports_fast_thread_cpu_time()) {
     return os::Bsd::fast_thread_cpu_time(thread_cpu_clockid(thread));
   } else {
     return slow_thread_cpu_time(thread, user_sys_cpu_time);
   }
+#endif
 }
 
+#ifndef _ALLBSD_SOURCE
 //
 //  -1 on error.
 //
@@ -4435,6 +4756,7 @@ static jlong slow_thread_cpu_time(Thread *thread, bool
     return (jlong)user_time * (1000000000 / clock_tics_per_sec);
   }
 }
+#endif
 
 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
@@ -4451,7 +4773,13 @@ void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr
 }
 
 bool os::is_thread_cpu_time_supported() {
+#ifdef __APPLE__
   return true;
+#elif defined(_ALLBSD_SOURCE)
+  return false;
+#else
+  return true;
+#endif
 }
 
 // System loadavg support.  Returns -1 if load average cannot be obtained.
@@ -4584,7 +4912,7 @@ jdk_pthread_sigmask(int how , const sigset_t* newmask,
 // abstime will be the absolute timeout time
 // TODO: replace compute_abstime() with unpackTime()
 
-static struct timespec* compute_abstime(timespec* abstime, jlong millis) {
+static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) {
   if (millis < 0)  millis = 0;
   struct timeval now;
   int status = gettimeofday(&now, NULL);
@@ -4636,7 +4964,7 @@ void os::PlatformEvent::park() {       // AKA "down()"
         status = pthread_cond_wait(_cond, _mutex);
         // for some reason, under 2.7 lwp_cond_wait() may return ETIME ...
         // Treat this the same as if the wait was interrupted
-        if (status == ETIME) { status = EINTR; }
+        if (status == ETIMEDOUT) { status = EINTR; } 
         assert_status(status == 0 || status == EINTR, status, "cond_wait");
      }
      -- _nParked ;
@@ -4694,10 +5022,10 @@ int os::PlatformEvent::park(jlong millis) {
       pthread_cond_init (_cond, NULL) ;
     }
     assert_status(status == 0 || status == EINTR ||
-                  status == ETIME || status == ETIMEDOUT,
+		  status == ETIMEDOUT, 
                   status, "cond_timedwait");
     if (!FilterSpuriousWakeups) break ;                 // previous semantics
-    if (status == ETIME || status == ETIMEDOUT) break ;
+    if (status == ETIMEDOUT) break ; 
     // We consume and ignore EINTR and spurious wakeups.
   }
   --_nParked ;
@@ -4789,7 +5117,7 @@ void os::PlatformEvent::unpark() {
  * years from "now".
  */
 
-static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) {
+static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) {
   assert (time > 0, "convertTime");
 
   struct timeval now;
@@ -4849,7 +5177,7 @@ void Parker::park(bool isAbsolute, jlong time) {
   }
 
   // Next, demultiplex/decode time arguments
-  timespec absTime;
+  struct timespec absTime;
   if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all
     return;
   }
@@ -4903,7 +5231,7 @@ void Parker::park(bool isAbsolute, jlong time) {
     }
   }
   assert_status(status == 0 || status == EINTR ||
-                status == ETIME || status == ETIMEDOUT,
+                status == ETIMEDOUT, 
                 status, "cond_timedwait");
 
 #ifdef ASSERT
@@ -4946,16 +5274,14 @@ void Parker::unpark() {
 }
 
 
+/* Darwin has no "environ" in a dynamic library. */
+#ifdef __APPLE__
+#include <crt_externs.h>
+#define environ (*_NSGetEnviron())
+#else
 extern char** environ;
-
-#ifndef __NR_fork
-#define __NR_fork IA32_ONLY(2) IA64_ONLY(not defined) AMD64_ONLY(57)
 #endif
 
-#ifndef __NR_execve
-#define __NR_execve IA32_ONLY(11) IA64_ONLY(1033) AMD64_ONLY(59)
-#endif
-
 // Run the specified command in a separate process. Return its exit value,
 // or -1 on failure (e.g. can't fork a new process).
 // Unlike system(), this function can be called from signal handler. It
@@ -4968,8 +5294,7 @@ int os::fork_and_exec(char* cmd) {
   // separate process to execve. Make a direct syscall to fork process.
   // On IA64 there's no fork syscall, we have to use fork() and hope for
   // the best...
-  pid_t pid = NOT_IA64(syscall(__NR_fork);)
-              IA64_ONLY(fork();)
+  pid_t pid = fork();
 
   if (pid < 0) {
     // fork failed
@@ -4985,8 +5310,7 @@ int os::fork_and_exec(char* cmd) {
     // in the new process, so make a system call directly.
     // IA64 should use normal execve() from glibc to match the glibc fork()
     // above.
-    NOT_IA64(syscall(__NR_execve, "/bin/sh", argv, environ);)
-    IA64_ONLY(execve("/bin/sh", (char* const*)argv, environ);)
+    execve("/bin/sh", (char* const*)argv, environ);
 
     // execve failed
     _exit(-1);
