src/share/vm/runtime/os.cpp

changeset 435
a61af66fc99e
child 490
2a8eb116ebbe
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/share/vm/runtime/os.cpp	Sat Dec 01 00:00:00 2007 +0000
     1.3 @@ -0,0 +1,1108 @@
     1.4 +/*
     1.5 + * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.
    1.11 + *
    1.12 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.13 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.14 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.15 + * version 2 for more details (a copy is included in the LICENSE file that
    1.16 + * accompanied this code).
    1.17 + *
    1.18 + * You should have received a copy of the GNU General Public License version
    1.19 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.20 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.21 + *
    1.22 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    1.23 + * CA 95054 USA or visit www.sun.com if you need additional information or
    1.24 + * have any questions.
    1.25 + *
    1.26 + */
    1.27 +
    1.28 +# include "incls/_precompiled.incl"
    1.29 +# include "incls/_os.cpp.incl"
    1.30 +
    1.31 +# include <signal.h>
    1.32 +
    1.33 +OSThread*         os::_starting_thread    = NULL;
    1.34 +address           os::_polling_page       = NULL;
    1.35 +volatile int32_t* os::_mem_serialize_page = NULL;
    1.36 +uintptr_t         os::_serialize_page_mask = 0;
    1.37 +long              os::_rand_seed          = 1;
    1.38 +int               os::_processor_count    = 0;
    1.39 +volatile jlong    os::_global_time        = 0;
    1.40 +volatile int      os::_global_time_lock   = 0;
    1.41 +bool              os::_use_global_time    = false;
    1.42 +size_t            os::_page_sizes[os::page_sizes_max];
    1.43 +
    1.44 +#ifndef PRODUCT
    1.45 +int os::num_mallocs = 0;            // # of calls to malloc/realloc
    1.46 +size_t os::alloc_bytes = 0;         // # of bytes allocated
    1.47 +int os::num_frees = 0;              // # of calls to free
    1.48 +#endif
    1.49 +
    1.50 +// Atomic read of a jlong is assured by a seqlock; see update_global_time()
    1.51 +jlong os::read_global_time() {
    1.52 +#ifdef _LP64
    1.53 +  return _global_time;
    1.54 +#else
    1.55 +  volatile int lock;
    1.56 +  volatile jlong current_time;
    1.57 +  int ctr = 0;
    1.58 +
    1.59 +  for (;;) {
    1.60 +    lock = _global_time_lock;
    1.61 +
    1.62 +    // spin while locked
    1.63 +    while ((lock & 0x1) != 0) {
    1.64 +      ++ctr;
    1.65 +      if ((ctr & 0xFFF) == 0) {
    1.66 +        // Guarantee writer progress.  Can't use yield; yield is advisory
    1.67 +        // and has almost no effect on some platforms.  Don't need a state
    1.68 +        // transition - the park call will return promptly.
    1.69 +        assert(Thread::current() != NULL, "TLS not initialized");
    1.70 +        assert(Thread::current()->_ParkEvent != NULL, "sync not initialized");
    1.71 +        Thread::current()->_ParkEvent->park(1);
    1.72 +      }
    1.73 +      lock = _global_time_lock;
    1.74 +    }
    1.75 +
    1.76 +    OrderAccess::loadload();
    1.77 +    current_time = _global_time;
    1.78 +    OrderAccess::loadload();
    1.79 +
    1.80 +    // ratify seqlock value
    1.81 +    if (lock == _global_time_lock) {
    1.82 +      return current_time;
    1.83 +    }
    1.84 +  }
    1.85 +#endif
    1.86 +}
    1.87 +
    1.88 +//
    1.89 +// NOTE - Assumes only one writer thread!
    1.90 +//
    1.91 +// We use a seqlock to guarantee that jlong _global_time is updated
    1.92 +// atomically on 32-bit platforms.  A locked value is indicated by
    1.93 +// the lock variable LSB == 1.  Readers will initially read the lock
    1.94 +// value, spinning until the LSB == 0.  They then speculatively read
    1.95 +// the global time value, then re-read the lock value to ensure that
    1.96 +// it hasn't changed.  If the lock value has changed, the entire read
    1.97 +// sequence is retried.
    1.98 +//
    1.99 +// Writers simply set the LSB = 1 (i.e. increment the variable),
   1.100 +// update the global time, then release the lock and bump the version
   1.101 +// number (i.e. increment the variable again.)  In this case we don't
   1.102 +// even need a CAS since we ensure there's only one writer.
   1.103 +//
   1.104 +void os::update_global_time() {
   1.105 +#ifdef _LP64
   1.106 +  _global_time = timeofday();
   1.107 +#else
   1.108 +  assert((_global_time_lock & 0x1) == 0, "multiple writers?");
   1.109 +  jlong current_time = timeofday();
   1.110 +  _global_time_lock++; // lock
   1.111 +  OrderAccess::storestore();
   1.112 +  _global_time = current_time;
   1.113 +  OrderAccess::storestore();
   1.114 +  _global_time_lock++; // unlock
   1.115 +#endif
   1.116 +}
   1.117 +
   1.118 +// Fill in buffer with current local time as an ISO-8601 string.
   1.119 +// E.g., yyyy-mm-ddThh:mm:ss-zzzz.
   1.120 +// Returns buffer, or NULL if it failed.
   1.121 +// This would mostly be a call to
   1.122 +//     strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
   1.123 +// except that on Windows the %z behaves badly, so we do it ourselves.
   1.124 +// Also, people wanted milliseconds on there,
   1.125 +// and strftime doesn't do milliseconds.
   1.126 +char* os::iso8601_time(char* buffer, size_t buffer_length) {
   1.127 +  // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
   1.128 +  //                                      1         2
   1.129 +  //                             12345678901234567890123456789
   1.130 +  static const char* iso8601_format =
   1.131 +    "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d";
   1.132 +  static const size_t needed_buffer = 29;
   1.133 +
   1.134 +  // Sanity check the arguments
   1.135 +  if (buffer == NULL) {
   1.136 +    assert(false, "NULL buffer");
   1.137 +    return NULL;
   1.138 +  }
   1.139 +  if (buffer_length < needed_buffer) {
   1.140 +    assert(false, "buffer_length too small");
   1.141 +    return NULL;
   1.142 +  }
   1.143 +  // Get the current time
   1.144 +  jlong milliseconds_since_19700101 = timeofday();
   1.145 +  const int milliseconds_per_microsecond = 1000;
   1.146 +  const time_t seconds_since_19700101 =
   1.147 +    milliseconds_since_19700101 / milliseconds_per_microsecond;
   1.148 +  const int milliseconds_after_second =
   1.149 +    milliseconds_since_19700101 % milliseconds_per_microsecond;
   1.150 +  // Convert the time value to a tm and timezone variable
   1.151 +  const struct tm *time_struct_temp = localtime(&seconds_since_19700101);
   1.152 +  if (time_struct_temp == NULL) {
   1.153 +    assert(false, "Failed localtime");
   1.154 +    return NULL;
   1.155 +  }
   1.156 +  // Save the results of localtime
   1.157 +  const struct tm time_struct = *time_struct_temp;
   1.158 +  const time_t zone = timezone;
   1.159 +
   1.160 +  // If daylight savings time is in effect,
   1.161 +  // we are 1 hour East of our time zone
   1.162 +  const time_t seconds_per_minute = 60;
   1.163 +  const time_t minutes_per_hour = 60;
   1.164 +  const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
   1.165 +  time_t UTC_to_local = zone;
   1.166 +  if (time_struct.tm_isdst > 0) {
   1.167 +    UTC_to_local = UTC_to_local - seconds_per_hour;
   1.168 +  }
   1.169 +  // Compute the time zone offset.
   1.170 +  //    localtime(3C) sets timezone to the difference (in seconds)
   1.171 +  //    between UTC and and local time.
   1.172 +  //    ISO 8601 says we need the difference between local time and UTC,
   1.173 +  //    we change the sign of the localtime(3C) result.
   1.174 +  const time_t local_to_UTC = -(UTC_to_local);
   1.175 +  // Then we have to figure out if if we are ahead (+) or behind (-) UTC.
   1.176 +  char sign_local_to_UTC = '+';
   1.177 +  time_t abs_local_to_UTC = local_to_UTC;
   1.178 +  if (local_to_UTC < 0) {
   1.179 +    sign_local_to_UTC = '-';
   1.180 +    abs_local_to_UTC = -(abs_local_to_UTC);
   1.181 +  }
   1.182 +  // Convert time zone offset seconds to hours and minutes.
   1.183 +  const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
   1.184 +  const time_t zone_min =
   1.185 +    ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
   1.186 +
   1.187 +  // Print an ISO 8601 date and time stamp into the buffer
   1.188 +  const int year = 1900 + time_struct.tm_year;
   1.189 +  const int month = 1 + time_struct.tm_mon;
   1.190 +  const int printed = jio_snprintf(buffer, buffer_length, iso8601_format,
   1.191 +                                   year,
   1.192 +                                   month,
   1.193 +                                   time_struct.tm_mday,
   1.194 +                                   time_struct.tm_hour,
   1.195 +                                   time_struct.tm_min,
   1.196 +                                   time_struct.tm_sec,
   1.197 +                                   milliseconds_after_second,
   1.198 +                                   sign_local_to_UTC,
   1.199 +                                   zone_hours,
   1.200 +                                   zone_min);
   1.201 +  if (printed == 0) {
   1.202 +    assert(false, "Failed jio_printf");
   1.203 +    return NULL;
   1.204 +  }
   1.205 +  return buffer;
   1.206 +}
   1.207 +
   1.208 +OSReturn os::set_priority(Thread* thread, ThreadPriority p) {
   1.209 +#ifdef ASSERT
   1.210 +  if (!(!thread->is_Java_thread() ||
   1.211 +         Thread::current() == thread  ||
   1.212 +         Threads_lock->owned_by_self()
   1.213 +         || thread->is_Compiler_thread()
   1.214 +        )) {
   1.215 +    assert(false, "possibility of dangling Thread pointer");
   1.216 +  }
   1.217 +#endif
   1.218 +
   1.219 +  if (p >= MinPriority && p <= MaxPriority) {
   1.220 +    int priority = java_to_os_priority[p];
   1.221 +    return set_native_priority(thread, priority);
   1.222 +  } else {
   1.223 +    assert(false, "Should not happen");
   1.224 +    return OS_ERR;
   1.225 +  }
   1.226 +}
   1.227 +
   1.228 +
   1.229 +OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
   1.230 +  int p;
   1.231 +  int os_prio;
   1.232 +  OSReturn ret = get_native_priority(thread, &os_prio);
   1.233 +  if (ret != OS_OK) return ret;
   1.234 +
   1.235 +  for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
   1.236 +  priority = (ThreadPriority)p;
   1.237 +  return OS_OK;
   1.238 +}
   1.239 +
   1.240 +
   1.241 +// --------------------- sun.misc.Signal (optional) ---------------------
   1.242 +
   1.243 +
   1.244 +// SIGBREAK is sent by the keyboard to query the VM state
   1.245 +#ifndef SIGBREAK
   1.246 +#define SIGBREAK SIGQUIT
   1.247 +#endif
   1.248 +
   1.249 +// sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
   1.250 +
   1.251 +
   1.252 +static void signal_thread_entry(JavaThread* thread, TRAPS) {
   1.253 +  os::set_priority(thread, NearMaxPriority);
   1.254 +  while (true) {
   1.255 +    int sig;
   1.256 +    {
   1.257 +      // FIXME : Currently we have not decieded what should be the status
   1.258 +      //         for this java thread blocked here. Once we decide about
   1.259 +      //         that we should fix this.
   1.260 +      sig = os::signal_wait();
   1.261 +    }
   1.262 +    if (sig == os::sigexitnum_pd()) {
   1.263 +       // Terminate the signal thread
   1.264 +       return;
   1.265 +    }
   1.266 +
   1.267 +    switch (sig) {
   1.268 +      case SIGBREAK: {
   1.269 +        // Check if the signal is a trigger to start the Attach Listener - in that
   1.270 +        // case don't print stack traces.
   1.271 +        if (!DisableAttachMechanism && AttachListener::is_init_trigger()) {
   1.272 +          continue;
   1.273 +        }
   1.274 +        // Print stack traces
   1.275 +        // Any SIGBREAK operations added here should make sure to flush
   1.276 +        // the output stream (e.g. tty->flush()) after output.  See 4803766.
   1.277 +        // Each module also prints an extra carriage return after its output.
   1.278 +        VM_PrintThreads op;
   1.279 +        VMThread::execute(&op);
   1.280 +        VM_PrintJNI jni_op;
   1.281 +        VMThread::execute(&jni_op);
   1.282 +        VM_FindDeadlocks op1(tty);
   1.283 +        VMThread::execute(&op1);
   1.284 +        Universe::print_heap_at_SIGBREAK();
   1.285 +        if (PrintClassHistogram) {
   1.286 +          VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */);
   1.287 +          VMThread::execute(&op1);
   1.288 +        }
   1.289 +        if (JvmtiExport::should_post_data_dump()) {
   1.290 +          JvmtiExport::post_data_dump();
   1.291 +        }
   1.292 +        break;
   1.293 +      }
   1.294 +      default: {
   1.295 +        // Dispatch the signal to java
   1.296 +        HandleMark hm(THREAD);
   1.297 +        klassOop k = SystemDictionary::resolve_or_null(vmSymbolHandles::sun_misc_Signal(), THREAD);
   1.298 +        KlassHandle klass (THREAD, k);
   1.299 +        if (klass.not_null()) {
   1.300 +          JavaValue result(T_VOID);
   1.301 +          JavaCallArguments args;
   1.302 +          args.push_int(sig);
   1.303 +          JavaCalls::call_static(
   1.304 +            &result,
   1.305 +            klass,
   1.306 +            vmSymbolHandles::dispatch_name(),
   1.307 +            vmSymbolHandles::int_void_signature(),
   1.308 +            &args,
   1.309 +            THREAD
   1.310 +          );
   1.311 +        }
   1.312 +        if (HAS_PENDING_EXCEPTION) {
   1.313 +          // tty is initialized early so we don't expect it to be null, but
   1.314 +          // if it is we can't risk doing an initialization that might
   1.315 +          // trigger additional out-of-memory conditions
   1.316 +          if (tty != NULL) {
   1.317 +            char klass_name[256];
   1.318 +            char tmp_sig_name[16];
   1.319 +            const char* sig_name = "UNKNOWN";
   1.320 +            instanceKlass::cast(PENDING_EXCEPTION->klass())->
   1.321 +              name()->as_klass_external_name(klass_name, 256);
   1.322 +            if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
   1.323 +              sig_name = tmp_sig_name;
   1.324 +            warning("Exception %s occurred dispatching signal %s to handler"
   1.325 +                    "- the VM may need to be forcibly terminated",
   1.326 +                    klass_name, sig_name );
   1.327 +          }
   1.328 +          CLEAR_PENDING_EXCEPTION;
   1.329 +        }
   1.330 +      }
   1.331 +    }
   1.332 +  }
   1.333 +}
   1.334 +
   1.335 +
   1.336 +void os::signal_init() {
   1.337 +  if (!ReduceSignalUsage) {
   1.338 +    // Setup JavaThread for processing signals
   1.339 +    EXCEPTION_MARK;
   1.340 +    klassOop k = SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_Thread(), true, CHECK);
   1.341 +    instanceKlassHandle klass (THREAD, k);
   1.342 +    instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
   1.343 +
   1.344 +    const char thread_name[] = "Signal Dispatcher";
   1.345 +    Handle string = java_lang_String::create_from_str(thread_name, CHECK);
   1.346 +
   1.347 +    // Initialize thread_oop to put it into the system threadGroup
   1.348 +    Handle thread_group (THREAD, Universe::system_thread_group());
   1.349 +    JavaValue result(T_VOID);
   1.350 +    JavaCalls::call_special(&result, thread_oop,
   1.351 +                           klass,
   1.352 +                           vmSymbolHandles::object_initializer_name(),
   1.353 +                           vmSymbolHandles::threadgroup_string_void_signature(),
   1.354 +                           thread_group,
   1.355 +                           string,
   1.356 +                           CHECK);
   1.357 +
   1.358 +    KlassHandle group(THREAD, SystemDictionary::threadGroup_klass());
   1.359 +    JavaCalls::call_special(&result,
   1.360 +                            thread_group,
   1.361 +                            group,
   1.362 +                            vmSymbolHandles::add_method_name(),
   1.363 +                            vmSymbolHandles::thread_void_signature(),
   1.364 +                            thread_oop,         // ARG 1
   1.365 +                            CHECK);
   1.366 +
   1.367 +    os::signal_init_pd();
   1.368 +
   1.369 +    { MutexLocker mu(Threads_lock);
   1.370 +      JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
   1.371 +
   1.372 +      // At this point it may be possible that no osthread was created for the
   1.373 +      // JavaThread due to lack of memory. We would have to throw an exception
   1.374 +      // in that case. However, since this must work and we do not allow
   1.375 +      // exceptions anyway, check and abort if this fails.
   1.376 +      if (signal_thread == NULL || signal_thread->osthread() == NULL) {
   1.377 +        vm_exit_during_initialization("java.lang.OutOfMemoryError",
   1.378 +                                      "unable to create new native thread");
   1.379 +      }
   1.380 +
   1.381 +      java_lang_Thread::set_thread(thread_oop(), signal_thread);
   1.382 +      java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
   1.383 +      java_lang_Thread::set_daemon(thread_oop());
   1.384 +
   1.385 +      signal_thread->set_threadObj(thread_oop());
   1.386 +      Threads::add(signal_thread);
   1.387 +      Thread::start(signal_thread);
   1.388 +    }
   1.389 +    // Handle ^BREAK
   1.390 +    os::signal(SIGBREAK, os::user_handler());
   1.391 +  }
   1.392 +}
   1.393 +
   1.394 +
   1.395 +void os::terminate_signal_thread() {
   1.396 +  if (!ReduceSignalUsage)
   1.397 +    signal_notify(sigexitnum_pd());
   1.398 +}
   1.399 +
   1.400 +
   1.401 +// --------------------- loading libraries ---------------------
   1.402 +
   1.403 +typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
   1.404 +extern struct JavaVM_ main_vm;
   1.405 +
   1.406 +static void* _native_java_library = NULL;
   1.407 +
   1.408 +void* os::native_java_library() {
   1.409 +  if (_native_java_library == NULL) {
   1.410 +    char buffer[JVM_MAXPATHLEN];
   1.411 +    char ebuf[1024];
   1.412 +
   1.413 +    // Try to load verify dll first. In 1.3 java dll depends on it and is not always
   1.414 +    // able to find it when the loading executable is outside the JDK.
   1.415 +    // In order to keep working with 1.2 we ignore any loading errors.
   1.416 +    hpi::dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "verify");
   1.417 +    hpi::dll_load(buffer, ebuf, sizeof(ebuf));
   1.418 +
   1.419 +    // Load java dll
   1.420 +    hpi::dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "java");
   1.421 +    _native_java_library = hpi::dll_load(buffer, ebuf, sizeof(ebuf));
   1.422 +    if (_native_java_library == NULL) {
   1.423 +      vm_exit_during_initialization("Unable to load native library", ebuf);
   1.424 +    }
   1.425 +    // The JNI_OnLoad handling is normally done by method load in java.lang.ClassLoader$NativeLibrary,
   1.426 +    // but the VM loads the base library explicitly so we have to check for JNI_OnLoad as well
   1.427 +    const char *onLoadSymbols[] = JNI_ONLOAD_SYMBOLS;
   1.428 +    JNI_OnLoad_t JNI_OnLoad = CAST_TO_FN_PTR(JNI_OnLoad_t, hpi::dll_lookup(_native_java_library, onLoadSymbols[0]));
   1.429 +    if (JNI_OnLoad != NULL) {
   1.430 +      JavaThread* thread = JavaThread::current();
   1.431 +      ThreadToNativeFromVM ttn(thread);
   1.432 +      HandleMark hm(thread);
   1.433 +      jint ver = (*JNI_OnLoad)(&main_vm, NULL);
   1.434 +      if (!Threads::is_supported_jni_version_including_1_1(ver)) {
   1.435 +        vm_exit_during_initialization("Unsupported JNI version");
   1.436 +      }
   1.437 +    }
   1.438 +  }
   1.439 +  return _native_java_library;
   1.440 +}
   1.441 +
   1.442 +// --------------------- heap allocation utilities ---------------------
   1.443 +
   1.444 +char *os::strdup(const char *str) {
   1.445 +  size_t size = strlen(str);
   1.446 +  char *dup_str = (char *)malloc(size + 1);
   1.447 +  if (dup_str == NULL) return NULL;
   1.448 +  strcpy(dup_str, str);
   1.449 +  return dup_str;
   1.450 +}
   1.451 +
   1.452 +
   1.453 +
   1.454 +#ifdef ASSERT
   1.455 +#define space_before             (MallocCushion + sizeof(double))
   1.456 +#define space_after              MallocCushion
   1.457 +#define size_addr_from_base(p)   (size_t*)(p + space_before - sizeof(size_t))
   1.458 +#define size_addr_from_obj(p)    ((size_t*)p - 1)
   1.459 +// MallocCushion: size of extra cushion allocated around objects with +UseMallocOnly
   1.460 +// NB: cannot be debug variable, because these aren't set from the command line until
   1.461 +// *after* the first few allocs already happened
   1.462 +#define MallocCushion            16
   1.463 +#else
   1.464 +#define space_before             0
   1.465 +#define space_after              0
   1.466 +#define size_addr_from_base(p)   should not use w/o ASSERT
   1.467 +#define size_addr_from_obj(p)    should not use w/o ASSERT
   1.468 +#define MallocCushion            0
   1.469 +#endif
   1.470 +#define paranoid                 0  /* only set to 1 if you suspect checking code has bug */
   1.471 +
   1.472 +#ifdef ASSERT
   1.473 +inline size_t get_size(void* obj) {
   1.474 +  size_t size = *size_addr_from_obj(obj);
   1.475 +  if (size < 0 )
   1.476 +    fatal2("free: size field of object #%p was overwritten (%lu)", obj, size);
   1.477 +  return size;
   1.478 +}
   1.479 +
   1.480 +u_char* find_cushion_backwards(u_char* start) {
   1.481 +  u_char* p = start;
   1.482 +  while (p[ 0] != badResourceValue || p[-1] != badResourceValue ||
   1.483 +         p[-2] != badResourceValue || p[-3] != badResourceValue) p--;
   1.484 +  // ok, we have four consecutive marker bytes; find start
   1.485 +  u_char* q = p - 4;
   1.486 +  while (*q == badResourceValue) q--;
   1.487 +  return q + 1;
   1.488 +}
   1.489 +
   1.490 +u_char* find_cushion_forwards(u_char* start) {
   1.491 +  u_char* p = start;
   1.492 +  while (p[0] != badResourceValue || p[1] != badResourceValue ||
   1.493 +         p[2] != badResourceValue || p[3] != badResourceValue) p++;
   1.494 +  // ok, we have four consecutive marker bytes; find end of cushion
   1.495 +  u_char* q = p + 4;
   1.496 +  while (*q == badResourceValue) q++;
   1.497 +  return q - MallocCushion;
   1.498 +}
   1.499 +
   1.500 +void print_neighbor_blocks(void* ptr) {
   1.501 +  // find block allocated before ptr (not entirely crash-proof)
   1.502 +  if (MallocCushion < 4) {
   1.503 +    tty->print_cr("### cannot find previous block (MallocCushion < 4)");
   1.504 +    return;
   1.505 +  }
   1.506 +  u_char* start_of_this_block = (u_char*)ptr - space_before;
   1.507 +  u_char* end_of_prev_block_data = start_of_this_block - space_after -1;
   1.508 +  // look for cushion in front of prev. block
   1.509 +  u_char* start_of_prev_block = find_cushion_backwards(end_of_prev_block_data);
   1.510 +  ptrdiff_t size = *size_addr_from_base(start_of_prev_block);
   1.511 +  u_char* obj = start_of_prev_block + space_before;
   1.512 +  if (size <= 0 ) {
   1.513 +    // start is bad; mayhave been confused by OS data inbetween objects
   1.514 +    // search one more backwards
   1.515 +    start_of_prev_block = find_cushion_backwards(start_of_prev_block);
   1.516 +    size = *size_addr_from_base(start_of_prev_block);
   1.517 +    obj = start_of_prev_block + space_before;
   1.518 +  }
   1.519 +
   1.520 +  if (start_of_prev_block + space_before + size + space_after == start_of_this_block) {
   1.521 +    tty->print_cr("### previous object: %p (%ld bytes)", obj, size);
   1.522 +  } else {
   1.523 +    tty->print_cr("### previous object (not sure if correct): %p (%ld bytes)", obj, size);
   1.524 +  }
   1.525 +
   1.526 +  // now find successor block
   1.527 +  u_char* start_of_next_block = (u_char*)ptr + *size_addr_from_obj(ptr) + space_after;
   1.528 +  start_of_next_block = find_cushion_forwards(start_of_next_block);
   1.529 +  u_char* next_obj = start_of_next_block + space_before;
   1.530 +  ptrdiff_t next_size = *size_addr_from_base(start_of_next_block);
   1.531 +  if (start_of_next_block[0] == badResourceValue &&
   1.532 +      start_of_next_block[1] == badResourceValue &&
   1.533 +      start_of_next_block[2] == badResourceValue &&
   1.534 +      start_of_next_block[3] == badResourceValue) {
   1.535 +    tty->print_cr("### next object: %p (%ld bytes)", next_obj, next_size);
   1.536 +  } else {
   1.537 +    tty->print_cr("### next object (not sure if correct): %p (%ld bytes)", next_obj, next_size);
   1.538 +  }
   1.539 +}
   1.540 +
   1.541 +
   1.542 +void report_heap_error(void* memblock, void* bad, const char* where) {
   1.543 +  tty->print_cr("## nof_mallocs = %d, nof_frees = %d", os::num_mallocs, os::num_frees);
   1.544 +  tty->print_cr("## memory stomp: byte at %p %s object %p", bad, where, memblock);
   1.545 +  print_neighbor_blocks(memblock);
   1.546 +  fatal("memory stomping error");
   1.547 +}
   1.548 +
   1.549 +void verify_block(void* memblock) {
   1.550 +  size_t size = get_size(memblock);
   1.551 +  if (MallocCushion) {
   1.552 +    u_char* ptr = (u_char*)memblock - space_before;
   1.553 +    for (int i = 0; i < MallocCushion; i++) {
   1.554 +      if (ptr[i] != badResourceValue) {
   1.555 +        report_heap_error(memblock, ptr+i, "in front of");
   1.556 +      }
   1.557 +    }
   1.558 +    u_char* end = (u_char*)memblock + size + space_after;
   1.559 +    for (int j = -MallocCushion; j < 0; j++) {
   1.560 +      if (end[j] != badResourceValue) {
   1.561 +        report_heap_error(memblock, end+j, "after");
   1.562 +      }
   1.563 +    }
   1.564 +  }
   1.565 +}
   1.566 +#endif
   1.567 +
   1.568 +void* os::malloc(size_t size) {
   1.569 +  NOT_PRODUCT(num_mallocs++);
   1.570 +  NOT_PRODUCT(alloc_bytes += size);
   1.571 +
   1.572 +  if (size == 0) {
   1.573 +    // return a valid pointer if size is zero
   1.574 +    // if NULL is returned the calling functions assume out of memory.
   1.575 +    size = 1;
   1.576 +  }
   1.577 +
   1.578 +  NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   1.579 +  u_char* ptr = (u_char*)::malloc(size + space_before + space_after);
   1.580 +#ifdef ASSERT
   1.581 +  if (ptr == NULL) return NULL;
   1.582 +  if (MallocCushion) {
   1.583 +    for (u_char* p = ptr; p < ptr + MallocCushion; p++) *p = (u_char)badResourceValue;
   1.584 +    u_char* end = ptr + space_before + size;
   1.585 +    for (u_char* pq = ptr+MallocCushion; pq < end; pq++) *pq = (u_char)uninitBlockPad;
   1.586 +    for (u_char* q = end; q < end + MallocCushion; q++) *q = (u_char)badResourceValue;
   1.587 +  }
   1.588 +  // put size just before data
   1.589 +  *size_addr_from_base(ptr) = size;
   1.590 +#endif
   1.591 +  u_char* memblock = ptr + space_before;
   1.592 +  if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   1.593 +    tty->print_cr("os::malloc caught, %lu bytes --> %p", size, memblock);
   1.594 +    breakpoint();
   1.595 +  }
   1.596 +  debug_only(if (paranoid) verify_block(memblock));
   1.597 +  if (PrintMalloc && tty != NULL) tty->print_cr("os::malloc %lu bytes --> %p", size, memblock);
   1.598 +  return memblock;
   1.599 +}
   1.600 +
   1.601 +
   1.602 +void* os::realloc(void *memblock, size_t size) {
   1.603 +  NOT_PRODUCT(num_mallocs++);
   1.604 +  NOT_PRODUCT(alloc_bytes += size);
   1.605 +#ifndef ASSERT
   1.606 +  return ::realloc(memblock, size);
   1.607 +#else
   1.608 +  if (memblock == NULL) {
   1.609 +    return os::malloc(size);
   1.610 +  }
   1.611 +  if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   1.612 +    tty->print_cr("os::realloc caught %p", memblock);
   1.613 +    breakpoint();
   1.614 +  }
   1.615 +  verify_block(memblock);
   1.616 +  NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   1.617 +  if (size == 0) return NULL;
   1.618 +  // always move the block
   1.619 +  void* ptr = malloc(size);
   1.620 +  if (PrintMalloc) tty->print_cr("os::remalloc %lu bytes, %p --> %p", size, memblock, ptr);
   1.621 +  // Copy to new memory if malloc didn't fail
   1.622 +  if ( ptr != NULL ) {
   1.623 +    memcpy(ptr, memblock, MIN2(size, get_size(memblock)));
   1.624 +    if (paranoid) verify_block(ptr);
   1.625 +    if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
   1.626 +      tty->print_cr("os::realloc caught, %lu bytes --> %p", size, ptr);
   1.627 +      breakpoint();
   1.628 +    }
   1.629 +    free(memblock);
   1.630 +  }
   1.631 +  return ptr;
   1.632 +#endif
   1.633 +}
   1.634 +
   1.635 +
   1.636 +void  os::free(void *memblock) {
   1.637 +  NOT_PRODUCT(num_frees++);
   1.638 +#ifdef ASSERT
   1.639 +  if (memblock == NULL) return;
   1.640 +  if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   1.641 +    if (tty != NULL) tty->print_cr("os::free caught %p", memblock);
   1.642 +    breakpoint();
   1.643 +  }
   1.644 +  verify_block(memblock);
   1.645 +  if (PrintMalloc && tty != NULL)
   1.646 +    // tty->print_cr("os::free %p", memblock);
   1.647 +    fprintf(stderr, "os::free %p\n", memblock);
   1.648 +  NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   1.649 +  // Added by detlefs.
   1.650 +  if (MallocCushion) {
   1.651 +    u_char* ptr = (u_char*)memblock - space_before;
   1.652 +    for (u_char* p = ptr; p < ptr + MallocCushion; p++) {
   1.653 +      guarantee(*p == badResourceValue,
   1.654 +                "Thing freed should be malloc result.");
   1.655 +      *p = (u_char)freeBlockPad;
   1.656 +    }
   1.657 +    size_t size = get_size(memblock);
   1.658 +    u_char* end = ptr + space_before + size;
   1.659 +    for (u_char* q = end; q < end + MallocCushion; q++) {
   1.660 +      guarantee(*q == badResourceValue,
   1.661 +                "Thing freed should be malloc result.");
   1.662 +      *q = (u_char)freeBlockPad;
   1.663 +    }
   1.664 +  }
   1.665 +#endif
   1.666 +  ::free((char*)memblock - space_before);
   1.667 +}
   1.668 +
   1.669 +void os::init_random(long initval) {
   1.670 +  _rand_seed = initval;
   1.671 +}
   1.672 +
   1.673 +
   1.674 +long os::random() {
   1.675 +  /* standard, well-known linear congruential random generator with
   1.676 +   * next_rand = (16807*seed) mod (2**31-1)
   1.677 +   * see
   1.678 +   * (1) "Random Number Generators: Good Ones Are Hard to Find",
   1.679 +   *      S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
   1.680 +   * (2) "Two Fast Implementations of the 'Minimal Standard' Random
   1.681 +   *     Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
   1.682 +  */
   1.683 +  const long a = 16807;
   1.684 +  const unsigned long m = 2147483647;
   1.685 +  const long q = m / a;        assert(q == 127773, "weird math");
   1.686 +  const long r = m % a;        assert(r == 2836, "weird math");
   1.687 +
   1.688 +  // compute az=2^31p+q
   1.689 +  unsigned long lo = a * (long)(_rand_seed & 0xFFFF);
   1.690 +  unsigned long hi = a * (long)((unsigned long)_rand_seed >> 16);
   1.691 +  lo += (hi & 0x7FFF) << 16;
   1.692 +
   1.693 +  // if q overflowed, ignore the overflow and increment q
   1.694 +  if (lo > m) {
   1.695 +    lo &= m;
   1.696 +    ++lo;
   1.697 +  }
   1.698 +  lo += hi >> 15;
   1.699 +
   1.700 +  // if (p+q) overflowed, ignore the overflow and increment (p+q)
   1.701 +  if (lo > m) {
   1.702 +    lo &= m;
   1.703 +    ++lo;
   1.704 +  }
   1.705 +  return (_rand_seed = lo);
   1.706 +}
   1.707 +
   1.708 +// The INITIALIZED state is distinguished from the SUSPENDED state because the
   1.709 +// conditions in which a thread is first started are different from those in which
   1.710 +// a suspension is resumed.  These differences make it hard for us to apply the
   1.711 +// tougher checks when starting threads that we want to do when resuming them.
   1.712 +// However, when start_thread is called as a result of Thread.start, on a Java
   1.713 +// thread, the operation is synchronized on the Java Thread object.  So there
   1.714 +// cannot be a race to start the thread and hence for the thread to exit while
   1.715 +// we are working on it.  Non-Java threads that start Java threads either have
   1.716 +// to do so in a context in which races are impossible, or should do appropriate
   1.717 +// locking.
   1.718 +
   1.719 +void os::start_thread(Thread* thread) {
   1.720 +  // guard suspend/resume
   1.721 +  MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
   1.722 +  OSThread* osthread = thread->osthread();
   1.723 +  osthread->set_state(RUNNABLE);
   1.724 +  pd_start_thread(thread);
   1.725 +}
   1.726 +
   1.727 +//---------------------------------------------------------------------------
   1.728 +// Helper functions for fatal error handler
   1.729 +
   1.730 +void os::print_hex_dump(outputStream* st, address start, address end, int unitsize) {
   1.731 +  assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
   1.732 +
   1.733 +  int cols = 0;
   1.734 +  int cols_per_line = 0;
   1.735 +  switch (unitsize) {
   1.736 +    case 1: cols_per_line = 16; break;
   1.737 +    case 2: cols_per_line = 8;  break;
   1.738 +    case 4: cols_per_line = 4;  break;
   1.739 +    case 8: cols_per_line = 2;  break;
   1.740 +    default: return;
   1.741 +  }
   1.742 +
   1.743 +  address p = start;
   1.744 +  st->print(PTR_FORMAT ":   ", start);
   1.745 +  while (p < end) {
   1.746 +    switch (unitsize) {
   1.747 +      case 1: st->print("%02x", *(u1*)p); break;
   1.748 +      case 2: st->print("%04x", *(u2*)p); break;
   1.749 +      case 4: st->print("%08x", *(u4*)p); break;
   1.750 +      case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
   1.751 +    }
   1.752 +    p += unitsize;
   1.753 +    cols++;
   1.754 +    if (cols >= cols_per_line && p < end) {
   1.755 +       cols = 0;
   1.756 +       st->cr();
   1.757 +       st->print(PTR_FORMAT ":   ", p);
   1.758 +    } else {
   1.759 +       st->print(" ");
   1.760 +    }
   1.761 +  }
   1.762 +  st->cr();
   1.763 +}
   1.764 +
   1.765 +void os::print_environment_variables(outputStream* st, const char** env_list,
   1.766 +                                     char* buffer, int len) {
   1.767 +  if (env_list) {
   1.768 +    st->print_cr("Environment Variables:");
   1.769 +
   1.770 +    for (int i = 0; env_list[i] != NULL; i++) {
   1.771 +      if (getenv(env_list[i], buffer, len)) {
   1.772 +        st->print(env_list[i]);
   1.773 +        st->print("=");
   1.774 +        st->print_cr(buffer);
   1.775 +      }
   1.776 +    }
   1.777 +  }
   1.778 +}
   1.779 +
   1.780 +void os::print_cpu_info(outputStream* st) {
   1.781 +  // cpu
   1.782 +  st->print("CPU:");
   1.783 +  st->print("total %d", os::processor_count());
   1.784 +  // It's not safe to query number of active processors after crash
   1.785 +  // st->print("(active %d)", os::active_processor_count());
   1.786 +  st->print(" %s", VM_Version::cpu_features());
   1.787 +  st->cr();
   1.788 +}
   1.789 +
   1.790 +void os::print_date_and_time(outputStream *st) {
   1.791 +  time_t tloc;
   1.792 +  (void)time(&tloc);
   1.793 +  st->print("time: %s", ctime(&tloc));  // ctime adds newline.
   1.794 +
   1.795 +  double t = os::elapsedTime();
   1.796 +  // NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in
   1.797 +  //       Linux. Must be a bug in glibc ? Workaround is to round "t" to int
   1.798 +  //       before printf. We lost some precision, but who cares?
   1.799 +  st->print_cr("elapsed time: %d seconds", (int)t);
   1.800 +}
   1.801 +
   1.802 +
   1.803 +// Looks like all platforms except IA64 can use the same function to check
   1.804 +// if C stack is walkable beyond current frame. The check for fp() is not
   1.805 +// necessary on Sparc, but it's harmless.
   1.806 +bool os::is_first_C_frame(frame* fr) {
   1.807 +#ifdef IA64
   1.808 +  // In order to walk native frames on Itanium, we need to access the unwind
   1.809 +  // table, which is inside ELF. We don't want to parse ELF after fatal error,
   1.810 +  // so return true for IA64. If we need to support C stack walking on IA64,
   1.811 +  // this function needs to be moved to CPU specific files, as fp() on IA64
   1.812 +  // is register stack, which grows towards higher memory address.
   1.813 +  return true;
   1.814 +#endif
   1.815 +
   1.816 +  // Load up sp, fp, sender sp and sender fp, check for reasonable values.
   1.817 +  // Check usp first, because if that's bad the other accessors may fault
   1.818 +  // on some architectures.  Ditto ufp second, etc.
   1.819 +  uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1);
   1.820 +  // sp on amd can be 32 bit aligned.
   1.821 +  uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1);
   1.822 +
   1.823 +  uintptr_t usp    = (uintptr_t)fr->sp();
   1.824 +  if ((usp & sp_align_mask) != 0) return true;
   1.825 +
   1.826 +  uintptr_t ufp    = (uintptr_t)fr->fp();
   1.827 +  if ((ufp & fp_align_mask) != 0) return true;
   1.828 +
   1.829 +  uintptr_t old_sp = (uintptr_t)fr->sender_sp();
   1.830 +  if ((old_sp & sp_align_mask) != 0) return true;
   1.831 +  if (old_sp == 0 || old_sp == (uintptr_t)-1) return true;
   1.832 +
   1.833 +  uintptr_t old_fp = (uintptr_t)fr->link();
   1.834 +  if ((old_fp & fp_align_mask) != 0) return true;
   1.835 +  if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true;
   1.836 +
   1.837 +  // stack grows downwards; if old_fp is below current fp or if the stack
   1.838 +  // frame is too large, either the stack is corrupted or fp is not saved
   1.839 +  // on stack (i.e. on x86, ebp may be used as general register). The stack
   1.840 +  // is not walkable beyond current frame.
   1.841 +  if (old_fp < ufp) return true;
   1.842 +  if (old_fp - ufp > 64 * K) return true;
   1.843 +
   1.844 +  return false;
   1.845 +}
   1.846 +
   1.847 +#ifdef ASSERT
   1.848 +extern "C" void test_random() {
   1.849 +  const double m = 2147483647;
   1.850 +  double mean = 0.0, variance = 0.0, t;
   1.851 +  long reps = 10000;
   1.852 +  unsigned long seed = 1;
   1.853 +
   1.854 +  tty->print_cr("seed %ld for %ld repeats...", seed, reps);
   1.855 +  os::init_random(seed);
   1.856 +  long num;
   1.857 +  for (int k = 0; k < reps; k++) {
   1.858 +    num = os::random();
   1.859 +    double u = (double)num / m;
   1.860 +    assert(u >= 0.0 && u <= 1.0, "bad random number!");
   1.861 +
   1.862 +    // calculate mean and variance of the random sequence
   1.863 +    mean += u;
   1.864 +    variance += (u*u);
   1.865 +  }
   1.866 +  mean /= reps;
   1.867 +  variance /= (reps - 1);
   1.868 +
   1.869 +  assert(num == 1043618065, "bad seed");
   1.870 +  tty->print_cr("mean of the 1st 10000 numbers: %f", mean);
   1.871 +  tty->print_cr("variance of the 1st 10000 numbers: %f", variance);
   1.872 +  const double eps = 0.0001;
   1.873 +  t = fabsd(mean - 0.5018);
   1.874 +  assert(t < eps, "bad mean");
   1.875 +  t = (variance - 0.3355) < 0.0 ? -(variance - 0.3355) : variance - 0.3355;
   1.876 +  assert(t < eps, "bad variance");
   1.877 +}
   1.878 +#endif
   1.879 +
   1.880 +
   1.881 +// Set up the boot classpath.
   1.882 +
   1.883 +char* os::format_boot_path(const char* format_string,
   1.884 +                           const char* home,
   1.885 +                           int home_len,
   1.886 +                           char fileSep,
   1.887 +                           char pathSep) {
   1.888 +    assert((fileSep == '/' && pathSep == ':') ||
   1.889 +           (fileSep == '\\' && pathSep == ';'), "unexpected seperator chars");
   1.890 +
   1.891 +    // Scan the format string to determine the length of the actual
   1.892 +    // boot classpath, and handle platform dependencies as well.
   1.893 +    int formatted_path_len = 0;
   1.894 +    const char* p;
   1.895 +    for (p = format_string; *p != 0; ++p) {
   1.896 +        if (*p == '%') formatted_path_len += home_len - 1;
   1.897 +        ++formatted_path_len;
   1.898 +    }
   1.899 +
   1.900 +    char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1);
   1.901 +    if (formatted_path == NULL) {
   1.902 +        return NULL;
   1.903 +    }
   1.904 +
   1.905 +    // Create boot classpath from format, substituting separator chars and
   1.906 +    // java home directory.
   1.907 +    char* q = formatted_path;
   1.908 +    for (p = format_string; *p != 0; ++p) {
   1.909 +        switch (*p) {
   1.910 +        case '%':
   1.911 +            strcpy(q, home);
   1.912 +            q += home_len;
   1.913 +            break;
   1.914 +        case '/':
   1.915 +            *q++ = fileSep;
   1.916 +            break;
   1.917 +        case ':':
   1.918 +            *q++ = pathSep;
   1.919 +            break;
   1.920 +        default:
   1.921 +            *q++ = *p;
   1.922 +        }
   1.923 +    }
   1.924 +    *q = '\0';
   1.925 +
   1.926 +    assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
   1.927 +    return formatted_path;
   1.928 +}
   1.929 +
   1.930 +
   1.931 +bool os::set_boot_path(char fileSep, char pathSep) {
   1.932 +
   1.933 +    const char* home = Arguments::get_java_home();
   1.934 +    int home_len = (int)strlen(home);
   1.935 +
   1.936 +    static const char* meta_index_dir_format = "%/lib/";
   1.937 +    static const char* meta_index_format = "%/lib/meta-index";
   1.938 +    char* meta_index = format_boot_path(meta_index_format, home, home_len, fileSep, pathSep);
   1.939 +    if (meta_index == NULL) return false;
   1.940 +    char* meta_index_dir = format_boot_path(meta_index_dir_format, home, home_len, fileSep, pathSep);
   1.941 +    if (meta_index_dir == NULL) return false;
   1.942 +    Arguments::set_meta_index_path(meta_index, meta_index_dir);
   1.943 +
   1.944 +    // Any modification to the JAR-file list, for the boot classpath must be
   1.945 +    // aligned with install/install/make/common/Pack.gmk. Note: boot class
   1.946 +    // path class JARs, are stripped for StackMapTable to reduce download size.
   1.947 +    static const char classpath_format[] =
   1.948 +        "%/lib/resources.jar:"
   1.949 +        "%/lib/rt.jar:"
   1.950 +        "%/lib/sunrsasign.jar:"
   1.951 +        "%/lib/jsse.jar:"
   1.952 +        "%/lib/jce.jar:"
   1.953 +        "%/lib/charsets.jar:"
   1.954 +        "%/classes";
   1.955 +    char* sysclasspath = format_boot_path(classpath_format, home, home_len, fileSep, pathSep);
   1.956 +    if (sysclasspath == NULL) return false;
   1.957 +    Arguments::set_sysclasspath(sysclasspath);
   1.958 +
   1.959 +    return true;
   1.960 +}
   1.961 +
   1.962 +
   1.963 +void os::set_memory_serialize_page(address page) {
   1.964 +  int count = log2_intptr(sizeof(class JavaThread)) - log2_intptr(64);
   1.965 +  _mem_serialize_page = (volatile int32_t *)page;
   1.966 +  // We initialize the serialization page shift count here
   1.967 +  // We assume a cache line size of 64 bytes
   1.968 +  assert(SerializePageShiftCount == count,
   1.969 +         "thread size changed, fix SerializePageShiftCount constant");
   1.970 +  set_serialize_page_mask((uintptr_t)(vm_page_size() - sizeof(int32_t)));
   1.971 +}
   1.972 +
   1.973 +// This method is called from signal handler when SIGSEGV occurs while the current
   1.974 +// thread tries to store to the "read-only" memory serialize page during state
   1.975 +// transition.
   1.976 +void os::block_on_serialize_page_trap() {
   1.977 +  if (TraceSafepoint) {
   1.978 +    tty->print_cr("Block until the serialize page permission restored");
   1.979 +  }
   1.980 +  // When VMThread is holding the SerializePage_lock during modifying the
   1.981 +  // access permission of the memory serialize page, the following call
   1.982 +  // will block until the permission of that page is restored to rw.
   1.983 +  // Generally, it is unsafe to manipulate locks in signal handlers, but in
   1.984 +  // this case, it's OK as the signal is synchronous and we know precisely when
   1.985 +  // it can occur. SerializePage_lock is a transiently-held leaf lock, so
   1.986 +  // lock_without_safepoint_check should be safe.
   1.987 +  SerializePage_lock->lock_without_safepoint_check();
   1.988 +  SerializePage_lock->unlock();
   1.989 +}
   1.990 +
   1.991 +// Serialize all thread state variables
   1.992 +void os::serialize_thread_states() {
   1.993 +  // On some platforms such as Solaris & Linux, the time duration of the page
   1.994 +  // permission restoration is observed to be much longer than expected  due to
   1.995 +  // scheduler starvation problem etc. To avoid the long synchronization
   1.996 +  // time and expensive page trap spinning, 'SerializePage_lock' is used to block
   1.997 +  // the mutator thread if such case is encountered. Since this method is always
   1.998 +  // called by VMThread during safepoint, lock_without_safepoint_check is used
   1.999 +  // instead. See bug 6546278.
  1.1000 +  SerializePage_lock->lock_without_safepoint_check();
  1.1001 +  os::protect_memory( (char *)os::get_memory_serialize_page(), os::vm_page_size() );
  1.1002 +  os::unguard_memory( (char *)os::get_memory_serialize_page(), os::vm_page_size() );
  1.1003 +  SerializePage_lock->unlock();
  1.1004 +}
  1.1005 +
  1.1006 +// Returns true if the current stack pointer is above the stack shadow
  1.1007 +// pages, false otherwise.
  1.1008 +
  1.1009 +bool os::stack_shadow_pages_available(Thread *thread, methodHandle method) {
  1.1010 +  assert(StackRedPages > 0 && StackYellowPages > 0,"Sanity check");
  1.1011 +  address sp = current_stack_pointer();
  1.1012 +  // Check if we have StackShadowPages above the yellow zone.  This parameter
  1.1013 +  // is dependant on the depth of the maximum VM call stack possible from
  1.1014 +  // the handler for stack overflow.  'instanceof' in the stack overflow
  1.1015 +  // handler or a println uses at least 8k stack of VM and native code
  1.1016 +  // respectively.
  1.1017 +  const int framesize_in_bytes =
  1.1018 +    Interpreter::size_top_interpreter_activation(method()) * wordSize;
  1.1019 +  int reserved_area = ((StackShadowPages + StackRedPages + StackYellowPages)
  1.1020 +                      * vm_page_size()) + framesize_in_bytes;
  1.1021 +  // The very lower end of the stack
  1.1022 +  address stack_limit = thread->stack_base() - thread->stack_size();
  1.1023 +  return (sp > (stack_limit + reserved_area));
  1.1024 +}
  1.1025 +
  1.1026 +size_t os::page_size_for_region(size_t region_min_size, size_t region_max_size,
  1.1027 +                                uint min_pages)
  1.1028 +{
  1.1029 +  assert(min_pages > 0, "sanity");
  1.1030 +  if (UseLargePages) {
  1.1031 +    const size_t max_page_size = region_max_size / min_pages;
  1.1032 +
  1.1033 +    for (unsigned int i = 0; _page_sizes[i] != 0; ++i) {
  1.1034 +      const size_t sz = _page_sizes[i];
  1.1035 +      const size_t mask = sz - 1;
  1.1036 +      if ((region_min_size & mask) == 0 && (region_max_size & mask) == 0) {
  1.1037 +        // The largest page size with no fragmentation.
  1.1038 +        return sz;
  1.1039 +      }
  1.1040 +
  1.1041 +      if (sz <= max_page_size) {
  1.1042 +        // The largest page size that satisfies the min_pages requirement.
  1.1043 +        return sz;
  1.1044 +      }
  1.1045 +    }
  1.1046 +  }
  1.1047 +
  1.1048 +  return vm_page_size();
  1.1049 +}
  1.1050 +
  1.1051 +#ifndef PRODUCT
  1.1052 +void os::trace_page_sizes(const char* str, const size_t region_min_size,
  1.1053 +                          const size_t region_max_size, const size_t page_size,
  1.1054 +                          const char* base, const size_t size)
  1.1055 +{
  1.1056 +  if (TracePageSizes) {
  1.1057 +    tty->print_cr("%s:  min=" SIZE_FORMAT " max=" SIZE_FORMAT
  1.1058 +                  " pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT
  1.1059 +                  " size=" SIZE_FORMAT,
  1.1060 +                  str, region_min_size, region_max_size,
  1.1061 +                  page_size, base, size);
  1.1062 +  }
  1.1063 +}
  1.1064 +#endif  // #ifndef PRODUCT
  1.1065 +
  1.1066 +// This is the working definition of a server class machine:
  1.1067 +// >= 2 physical CPU's and >=2GB of memory, with some fuzz
  1.1068 +// because the graphics memory (?) sometimes masks physical memory.
  1.1069 +// If you want to change the definition of a server class machine
  1.1070 +// on some OS or platform, e.g., >=4GB on Windohs platforms,
  1.1071 +// then you'll have to parameterize this method based on that state,
  1.1072 +// as was done for logical processors here, or replicate and
  1.1073 +// specialize this method for each platform.  (Or fix os to have
  1.1074 +// some inheritance structure and use subclassing.  Sigh.)
  1.1075 +// If you want some platform to always or never behave as a server
  1.1076 +// class machine, change the setting of AlwaysActAsServerClassMachine
  1.1077 +// and NeverActAsServerClassMachine in globals*.hpp.
  1.1078 +bool os::is_server_class_machine() {
  1.1079 +  // First check for the early returns
  1.1080 +  if (NeverActAsServerClassMachine) {
  1.1081 +    return false;
  1.1082 +  }
  1.1083 +  if (AlwaysActAsServerClassMachine) {
  1.1084 +    return true;
  1.1085 +  }
  1.1086 +  // Then actually look at the machine
  1.1087 +  bool         result            = false;
  1.1088 +  const unsigned int    server_processors = 2;
  1.1089 +  const julong server_memory     = 2UL * G;
  1.1090 +  // We seem not to get our full complement of memory.
  1.1091 +  //     We allow some part (1/8?) of the memory to be "missing",
  1.1092 +  //     based on the sizes of DIMMs, and maybe graphics cards.
  1.1093 +  const julong missing_memory   = 256UL * M;
  1.1094 +
  1.1095 +  /* Is this a server class machine? */
  1.1096 +  if ((os::active_processor_count() >= (int)server_processors) &&
  1.1097 +      (os::physical_memory() >= (server_memory - missing_memory))) {
  1.1098 +    const unsigned int logical_processors =
  1.1099 +      VM_Version::logical_processors_per_package();
  1.1100 +    if (logical_processors > 1) {
  1.1101 +      const unsigned int physical_packages =
  1.1102 +        os::active_processor_count() / logical_processors;
  1.1103 +      if (physical_packages > server_processors) {
  1.1104 +        result = true;
  1.1105 +      }
  1.1106 +    } else {
  1.1107 +      result = true;
  1.1108 +    }
  1.1109 +  }
  1.1110 +  return result;
  1.1111 +}

mercurial