src/share/vm/runtime/os.cpp

Thu, 27 Jan 2011 16:11:27 -0800

author
coleenp
date
Thu, 27 Jan 2011 16:11:27 -0800
changeset 2497
3582bf76420e
parent 2322
828eafbd85cc
child 2557
f7de3327c683
permissions
-rw-r--r--

6990754: Use native memory and reference counting to implement SymbolTable
Summary: move symbols from permgen into C heap and reference count them
Reviewed-by: never, acorn, jmasa, stefank

     1 /*
     2  * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 #include "precompiled.hpp"
    26 #include "classfile/classLoader.hpp"
    27 #include "classfile/javaClasses.hpp"
    28 #include "classfile/systemDictionary.hpp"
    29 #include "classfile/vmSymbols.hpp"
    30 #include "code/icBuffer.hpp"
    31 #include "code/vtableStubs.hpp"
    32 #include "gc_implementation/shared/vmGCOperations.hpp"
    33 #include "interpreter/interpreter.hpp"
    34 #include "memory/allocation.inline.hpp"
    35 #include "oops/oop.inline.hpp"
    36 #include "prims/jvm.h"
    37 #include "prims/jvm_misc.hpp"
    38 #include "prims/privilegedStack.hpp"
    39 #include "runtime/arguments.hpp"
    40 #include "runtime/frame.inline.hpp"
    41 #include "runtime/interfaceSupport.hpp"
    42 #include "runtime/java.hpp"
    43 #include "runtime/javaCalls.hpp"
    44 #include "runtime/mutexLocker.hpp"
    45 #include "runtime/os.hpp"
    46 #include "runtime/stubRoutines.hpp"
    47 #include "services/attachListener.hpp"
    48 #include "services/threadService.hpp"
    49 #include "utilities/defaultStream.hpp"
    50 #include "utilities/events.hpp"
    51 #ifdef TARGET_OS_FAMILY_linux
    52 # include "os_linux.inline.hpp"
    53 # include "thread_linux.inline.hpp"
    54 #endif
    55 #ifdef TARGET_OS_FAMILY_solaris
    56 # include "os_solaris.inline.hpp"
    57 # include "thread_solaris.inline.hpp"
    58 #endif
    59 #ifdef TARGET_OS_FAMILY_windows
    60 # include "os_windows.inline.hpp"
    61 # include "thread_windows.inline.hpp"
    62 #endif
    64 # include <signal.h>
    66 OSThread*         os::_starting_thread    = NULL;
    67 address           os::_polling_page       = NULL;
    68 volatile int32_t* os::_mem_serialize_page = NULL;
    69 uintptr_t         os::_serialize_page_mask = 0;
    70 long              os::_rand_seed          = 1;
    71 int               os::_processor_count    = 0;
    72 size_t            os::_page_sizes[os::page_sizes_max];
    74 #ifndef PRODUCT
    75 int os::num_mallocs = 0;            // # of calls to malloc/realloc
    76 size_t os::alloc_bytes = 0;         // # of bytes allocated
    77 int os::num_frees = 0;              // # of calls to free
    78 #endif
    80 // Fill in buffer with current local time as an ISO-8601 string.
    81 // E.g., yyyy-mm-ddThh:mm:ss-zzzz.
    82 // Returns buffer, or NULL if it failed.
    83 // This would mostly be a call to
    84 //     strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
    85 // except that on Windows the %z behaves badly, so we do it ourselves.
    86 // Also, people wanted milliseconds on there,
    87 // and strftime doesn't do milliseconds.
    88 char* os::iso8601_time(char* buffer, size_t buffer_length) {
    89   // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
    90   //                                      1         2
    91   //                             12345678901234567890123456789
    92   static const char* iso8601_format =
    93     "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d";
    94   static const size_t needed_buffer = 29;
    96   // Sanity check the arguments
    97   if (buffer == NULL) {
    98     assert(false, "NULL buffer");
    99     return NULL;
   100   }
   101   if (buffer_length < needed_buffer) {
   102     assert(false, "buffer_length too small");
   103     return NULL;
   104   }
   105   // Get the current time
   106   jlong milliseconds_since_19700101 = javaTimeMillis();
   107   const int milliseconds_per_microsecond = 1000;
   108   const time_t seconds_since_19700101 =
   109     milliseconds_since_19700101 / milliseconds_per_microsecond;
   110   const int milliseconds_after_second =
   111     milliseconds_since_19700101 % milliseconds_per_microsecond;
   112   // Convert the time value to a tm and timezone variable
   113   struct tm time_struct;
   114   if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
   115     assert(false, "Failed localtime_pd");
   116     return NULL;
   117   }
   118   const time_t zone = timezone;
   120   // If daylight savings time is in effect,
   121   // we are 1 hour East of our time zone
   122   const time_t seconds_per_minute = 60;
   123   const time_t minutes_per_hour = 60;
   124   const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
   125   time_t UTC_to_local = zone;
   126   if (time_struct.tm_isdst > 0) {
   127     UTC_to_local = UTC_to_local - seconds_per_hour;
   128   }
   129   // Compute the time zone offset.
   130   //    localtime_pd() sets timezone to the difference (in seconds)
   131   //    between UTC and and local time.
   132   //    ISO 8601 says we need the difference between local time and UTC,
   133   //    we change the sign of the localtime_pd() result.
   134   const time_t local_to_UTC = -(UTC_to_local);
   135   // Then we have to figure out if if we are ahead (+) or behind (-) UTC.
   136   char sign_local_to_UTC = '+';
   137   time_t abs_local_to_UTC = local_to_UTC;
   138   if (local_to_UTC < 0) {
   139     sign_local_to_UTC = '-';
   140     abs_local_to_UTC = -(abs_local_to_UTC);
   141   }
   142   // Convert time zone offset seconds to hours and minutes.
   143   const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
   144   const time_t zone_min =
   145     ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
   147   // Print an ISO 8601 date and time stamp into the buffer
   148   const int year = 1900 + time_struct.tm_year;
   149   const int month = 1 + time_struct.tm_mon;
   150   const int printed = jio_snprintf(buffer, buffer_length, iso8601_format,
   151                                    year,
   152                                    month,
   153                                    time_struct.tm_mday,
   154                                    time_struct.tm_hour,
   155                                    time_struct.tm_min,
   156                                    time_struct.tm_sec,
   157                                    milliseconds_after_second,
   158                                    sign_local_to_UTC,
   159                                    zone_hours,
   160                                    zone_min);
   161   if (printed == 0) {
   162     assert(false, "Failed jio_printf");
   163     return NULL;
   164   }
   165   return buffer;
   166 }
   168 OSReturn os::set_priority(Thread* thread, ThreadPriority p) {
   169 #ifdef ASSERT
   170   if (!(!thread->is_Java_thread() ||
   171          Thread::current() == thread  ||
   172          Threads_lock->owned_by_self()
   173          || thread->is_Compiler_thread()
   174         )) {
   175     assert(false, "possibility of dangling Thread pointer");
   176   }
   177 #endif
   179   if (p >= MinPriority && p <= MaxPriority) {
   180     int priority = java_to_os_priority[p];
   181     return set_native_priority(thread, priority);
   182   } else {
   183     assert(false, "Should not happen");
   184     return OS_ERR;
   185   }
   186 }
   189 OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
   190   int p;
   191   int os_prio;
   192   OSReturn ret = get_native_priority(thread, &os_prio);
   193   if (ret != OS_OK) return ret;
   195   for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
   196   priority = (ThreadPriority)p;
   197   return OS_OK;
   198 }
   201 // --------------------- sun.misc.Signal (optional) ---------------------
   204 // SIGBREAK is sent by the keyboard to query the VM state
   205 #ifndef SIGBREAK
   206 #define SIGBREAK SIGQUIT
   207 #endif
   209 // sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
   212 static void signal_thread_entry(JavaThread* thread, TRAPS) {
   213   os::set_priority(thread, NearMaxPriority);
   214   while (true) {
   215     int sig;
   216     {
   217       // FIXME : Currently we have not decieded what should be the status
   218       //         for this java thread blocked here. Once we decide about
   219       //         that we should fix this.
   220       sig = os::signal_wait();
   221     }
   222     if (sig == os::sigexitnum_pd()) {
   223        // Terminate the signal thread
   224        return;
   225     }
   227     switch (sig) {
   228       case SIGBREAK: {
   229         // Check if the signal is a trigger to start the Attach Listener - in that
   230         // case don't print stack traces.
   231         if (!DisableAttachMechanism && AttachListener::is_init_trigger()) {
   232           continue;
   233         }
   234         // Print stack traces
   235         // Any SIGBREAK operations added here should make sure to flush
   236         // the output stream (e.g. tty->flush()) after output.  See 4803766.
   237         // Each module also prints an extra carriage return after its output.
   238         VM_PrintThreads op;
   239         VMThread::execute(&op);
   240         VM_PrintJNI jni_op;
   241         VMThread::execute(&jni_op);
   242         VM_FindDeadlocks op1(tty);
   243         VMThread::execute(&op1);
   244         Universe::print_heap_at_SIGBREAK();
   245         if (PrintClassHistogram) {
   246           VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */,
   247                                    true /* need_prologue */);
   248           VMThread::execute(&op1);
   249         }
   250         if (JvmtiExport::should_post_data_dump()) {
   251           JvmtiExport::post_data_dump();
   252         }
   253         break;
   254       }
   255       default: {
   256         // Dispatch the signal to java
   257         HandleMark hm(THREAD);
   258         klassOop k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_Signal(), THREAD);
   259         KlassHandle klass (THREAD, k);
   260         if (klass.not_null()) {
   261           JavaValue result(T_VOID);
   262           JavaCallArguments args;
   263           args.push_int(sig);
   264           JavaCalls::call_static(
   265             &result,
   266             klass,
   267             vmSymbols::dispatch_name(),
   268             vmSymbols::int_void_signature(),
   269             &args,
   270             THREAD
   271           );
   272         }
   273         if (HAS_PENDING_EXCEPTION) {
   274           // tty is initialized early so we don't expect it to be null, but
   275           // if it is we can't risk doing an initialization that might
   276           // trigger additional out-of-memory conditions
   277           if (tty != NULL) {
   278             char klass_name[256];
   279             char tmp_sig_name[16];
   280             const char* sig_name = "UNKNOWN";
   281             instanceKlass::cast(PENDING_EXCEPTION->klass())->
   282               name()->as_klass_external_name(klass_name, 256);
   283             if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
   284               sig_name = tmp_sig_name;
   285             warning("Exception %s occurred dispatching signal %s to handler"
   286                     "- the VM may need to be forcibly terminated",
   287                     klass_name, sig_name );
   288           }
   289           CLEAR_PENDING_EXCEPTION;
   290         }
   291       }
   292     }
   293   }
   294 }
   297 void os::signal_init() {
   298   if (!ReduceSignalUsage) {
   299     // Setup JavaThread for processing signals
   300     EXCEPTION_MARK;
   301     klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
   302     instanceKlassHandle klass (THREAD, k);
   303     instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
   305     const char thread_name[] = "Signal Dispatcher";
   306     Handle string = java_lang_String::create_from_str(thread_name, CHECK);
   308     // Initialize thread_oop to put it into the system threadGroup
   309     Handle thread_group (THREAD, Universe::system_thread_group());
   310     JavaValue result(T_VOID);
   311     JavaCalls::call_special(&result, thread_oop,
   312                            klass,
   313                            vmSymbols::object_initializer_name(),
   314                            vmSymbols::threadgroup_string_void_signature(),
   315                            thread_group,
   316                            string,
   317                            CHECK);
   319     KlassHandle group(THREAD, SystemDictionary::ThreadGroup_klass());
   320     JavaCalls::call_special(&result,
   321                             thread_group,
   322                             group,
   323                             vmSymbols::add_method_name(),
   324                             vmSymbols::thread_void_signature(),
   325                             thread_oop,         // ARG 1
   326                             CHECK);
   328     os::signal_init_pd();
   330     { MutexLocker mu(Threads_lock);
   331       JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
   333       // At this point it may be possible that no osthread was created for the
   334       // JavaThread due to lack of memory. We would have to throw an exception
   335       // in that case. However, since this must work and we do not allow
   336       // exceptions anyway, check and abort if this fails.
   337       if (signal_thread == NULL || signal_thread->osthread() == NULL) {
   338         vm_exit_during_initialization("java.lang.OutOfMemoryError",
   339                                       "unable to create new native thread");
   340       }
   342       java_lang_Thread::set_thread(thread_oop(), signal_thread);
   343       java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
   344       java_lang_Thread::set_daemon(thread_oop());
   346       signal_thread->set_threadObj(thread_oop());
   347       Threads::add(signal_thread);
   348       Thread::start(signal_thread);
   349     }
   350     // Handle ^BREAK
   351     os::signal(SIGBREAK, os::user_handler());
   352   }
   353 }
   356 void os::terminate_signal_thread() {
   357   if (!ReduceSignalUsage)
   358     signal_notify(sigexitnum_pd());
   359 }
   362 // --------------------- loading libraries ---------------------
   364 typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
   365 extern struct JavaVM_ main_vm;
   367 static void* _native_java_library = NULL;
   369 void* os::native_java_library() {
   370   if (_native_java_library == NULL) {
   371     char buffer[JVM_MAXPATHLEN];
   372     char ebuf[1024];
   374     // Try to load verify dll first. In 1.3 java dll depends on it and is not
   375     // always able to find it when the loading executable is outside the JDK.
   376     // In order to keep working with 1.2 we ignore any loading errors.
   377     dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "verify");
   378     dll_load(buffer, ebuf, sizeof(ebuf));
   380     // Load java dll
   381     dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), "java");
   382     _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
   383     if (_native_java_library == NULL) {
   384       vm_exit_during_initialization("Unable to load native library", ebuf);
   385     }
   386   }
   387   static jboolean onLoaded = JNI_FALSE;
   388   if (onLoaded) {
   389     // We may have to wait to fire OnLoad until TLS is initialized.
   390     if (ThreadLocalStorage::is_initialized()) {
   391       // The JNI_OnLoad handling is normally done by method load in
   392       // java.lang.ClassLoader$NativeLibrary, but the VM loads the base library
   393       // explicitly so we have to check for JNI_OnLoad as well
   394       const char *onLoadSymbols[] = JNI_ONLOAD_SYMBOLS;
   395       JNI_OnLoad_t JNI_OnLoad = CAST_TO_FN_PTR(
   396           JNI_OnLoad_t, dll_lookup(_native_java_library, onLoadSymbols[0]));
   397       if (JNI_OnLoad != NULL) {
   398         JavaThread* thread = JavaThread::current();
   399         ThreadToNativeFromVM ttn(thread);
   400         HandleMark hm(thread);
   401         jint ver = (*JNI_OnLoad)(&main_vm, NULL);
   402         onLoaded = JNI_TRUE;
   403         if (!Threads::is_supported_jni_version_including_1_1(ver)) {
   404           vm_exit_during_initialization("Unsupported JNI version");
   405         }
   406       }
   407     }
   408   }
   409   return _native_java_library;
   410 }
   412 // --------------------- heap allocation utilities ---------------------
   414 char *os::strdup(const char *str) {
   415   size_t size = strlen(str);
   416   char *dup_str = (char *)malloc(size + 1);
   417   if (dup_str == NULL) return NULL;
   418   strcpy(dup_str, str);
   419   return dup_str;
   420 }
   424 #ifdef ASSERT
   425 #define space_before             (MallocCushion + sizeof(double))
   426 #define space_after              MallocCushion
   427 #define size_addr_from_base(p)   (size_t*)(p + space_before - sizeof(size_t))
   428 #define size_addr_from_obj(p)    ((size_t*)p - 1)
   429 // MallocCushion: size of extra cushion allocated around objects with +UseMallocOnly
   430 // NB: cannot be debug variable, because these aren't set from the command line until
   431 // *after* the first few allocs already happened
   432 #define MallocCushion            16
   433 #else
   434 #define space_before             0
   435 #define space_after              0
   436 #define size_addr_from_base(p)   should not use w/o ASSERT
   437 #define size_addr_from_obj(p)    should not use w/o ASSERT
   438 #define MallocCushion            0
   439 #endif
   440 #define paranoid                 0  /* only set to 1 if you suspect checking code has bug */
   442 #ifdef ASSERT
   443 inline size_t get_size(void* obj) {
   444   size_t size = *size_addr_from_obj(obj);
   445   if (size < 0) {
   446     fatal(err_msg("free: size field of object #" PTR_FORMAT " was overwritten ("
   447                   SIZE_FORMAT ")", obj, size));
   448   }
   449   return size;
   450 }
   452 u_char* find_cushion_backwards(u_char* start) {
   453   u_char* p = start;
   454   while (p[ 0] != badResourceValue || p[-1] != badResourceValue ||
   455          p[-2] != badResourceValue || p[-3] != badResourceValue) p--;
   456   // ok, we have four consecutive marker bytes; find start
   457   u_char* q = p - 4;
   458   while (*q == badResourceValue) q--;
   459   return q + 1;
   460 }
   462 u_char* find_cushion_forwards(u_char* start) {
   463   u_char* p = start;
   464   while (p[0] != badResourceValue || p[1] != badResourceValue ||
   465          p[2] != badResourceValue || p[3] != badResourceValue) p++;
   466   // ok, we have four consecutive marker bytes; find end of cushion
   467   u_char* q = p + 4;
   468   while (*q == badResourceValue) q++;
   469   return q - MallocCushion;
   470 }
   472 void print_neighbor_blocks(void* ptr) {
   473   // find block allocated before ptr (not entirely crash-proof)
   474   if (MallocCushion < 4) {
   475     tty->print_cr("### cannot find previous block (MallocCushion < 4)");
   476     return;
   477   }
   478   u_char* start_of_this_block = (u_char*)ptr - space_before;
   479   u_char* end_of_prev_block_data = start_of_this_block - space_after -1;
   480   // look for cushion in front of prev. block
   481   u_char* start_of_prev_block = find_cushion_backwards(end_of_prev_block_data);
   482   ptrdiff_t size = *size_addr_from_base(start_of_prev_block);
   483   u_char* obj = start_of_prev_block + space_before;
   484   if (size <= 0 ) {
   485     // start is bad; mayhave been confused by OS data inbetween objects
   486     // search one more backwards
   487     start_of_prev_block = find_cushion_backwards(start_of_prev_block);
   488     size = *size_addr_from_base(start_of_prev_block);
   489     obj = start_of_prev_block + space_before;
   490   }
   492   if (start_of_prev_block + space_before + size + space_after == start_of_this_block) {
   493     tty->print_cr("### previous object: %p (%ld bytes)", obj, size);
   494   } else {
   495     tty->print_cr("### previous object (not sure if correct): %p (%ld bytes)", obj, size);
   496   }
   498   // now find successor block
   499   u_char* start_of_next_block = (u_char*)ptr + *size_addr_from_obj(ptr) + space_after;
   500   start_of_next_block = find_cushion_forwards(start_of_next_block);
   501   u_char* next_obj = start_of_next_block + space_before;
   502   ptrdiff_t next_size = *size_addr_from_base(start_of_next_block);
   503   if (start_of_next_block[0] == badResourceValue &&
   504       start_of_next_block[1] == badResourceValue &&
   505       start_of_next_block[2] == badResourceValue &&
   506       start_of_next_block[3] == badResourceValue) {
   507     tty->print_cr("### next object: %p (%ld bytes)", next_obj, next_size);
   508   } else {
   509     tty->print_cr("### next object (not sure if correct): %p (%ld bytes)", next_obj, next_size);
   510   }
   511 }
   514 void report_heap_error(void* memblock, void* bad, const char* where) {
   515   tty->print_cr("## nof_mallocs = %d, nof_frees = %d", os::num_mallocs, os::num_frees);
   516   tty->print_cr("## memory stomp: byte at %p %s object %p", bad, where, memblock);
   517   print_neighbor_blocks(memblock);
   518   fatal("memory stomping error");
   519 }
   521 void verify_block(void* memblock) {
   522   size_t size = get_size(memblock);
   523   if (MallocCushion) {
   524     u_char* ptr = (u_char*)memblock - space_before;
   525     for (int i = 0; i < MallocCushion; i++) {
   526       if (ptr[i] != badResourceValue) {
   527         report_heap_error(memblock, ptr+i, "in front of");
   528       }
   529     }
   530     u_char* end = (u_char*)memblock + size + space_after;
   531     for (int j = -MallocCushion; j < 0; j++) {
   532       if (end[j] != badResourceValue) {
   533         report_heap_error(memblock, end+j, "after");
   534       }
   535     }
   536   }
   537 }
   538 #endif
   540 void* os::malloc(size_t size) {
   541   NOT_PRODUCT(num_mallocs++);
   542   NOT_PRODUCT(alloc_bytes += size);
   544   if (size == 0) {
   545     // return a valid pointer if size is zero
   546     // if NULL is returned the calling functions assume out of memory.
   547     size = 1;
   548   }
   550   NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   551   u_char* ptr = (u_char*)::malloc(size + space_before + space_after);
   552 #ifdef ASSERT
   553   if (ptr == NULL) return NULL;
   554   if (MallocCushion) {
   555     for (u_char* p = ptr; p < ptr + MallocCushion; p++) *p = (u_char)badResourceValue;
   556     u_char* end = ptr + space_before + size;
   557     for (u_char* pq = ptr+MallocCushion; pq < end; pq++) *pq = (u_char)uninitBlockPad;
   558     for (u_char* q = end; q < end + MallocCushion; q++) *q = (u_char)badResourceValue;
   559   }
   560   // put size just before data
   561   *size_addr_from_base(ptr) = size;
   562 #endif
   563   u_char* memblock = ptr + space_before;
   564   if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   565     tty->print_cr("os::malloc caught, %lu bytes --> %p", size, memblock);
   566     breakpoint();
   567   }
   568   debug_only(if (paranoid) verify_block(memblock));
   569   if (PrintMalloc && tty != NULL) tty->print_cr("os::malloc %lu bytes --> %p", size, memblock);
   570   return memblock;
   571 }
   574 void* os::realloc(void *memblock, size_t size) {
   575   NOT_PRODUCT(num_mallocs++);
   576   NOT_PRODUCT(alloc_bytes += size);
   577 #ifndef ASSERT
   578   return ::realloc(memblock, size);
   579 #else
   580   if (memblock == NULL) {
   581     return os::malloc(size);
   582   }
   583   if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   584     tty->print_cr("os::realloc caught %p", memblock);
   585     breakpoint();
   586   }
   587   verify_block(memblock);
   588   NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   589   if (size == 0) return NULL;
   590   // always move the block
   591   void* ptr = malloc(size);
   592   if (PrintMalloc) tty->print_cr("os::remalloc %lu bytes, %p --> %p", size, memblock, ptr);
   593   // Copy to new memory if malloc didn't fail
   594   if ( ptr != NULL ) {
   595     memcpy(ptr, memblock, MIN2(size, get_size(memblock)));
   596     if (paranoid) verify_block(ptr);
   597     if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
   598       tty->print_cr("os::realloc caught, %lu bytes --> %p", size, ptr);
   599       breakpoint();
   600     }
   601     free(memblock);
   602   }
   603   return ptr;
   604 #endif
   605 }
   608 void  os::free(void *memblock) {
   609   NOT_PRODUCT(num_frees++);
   610 #ifdef ASSERT
   611   if (memblock == NULL) return;
   612   if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
   613     if (tty != NULL) tty->print_cr("os::free caught %p", memblock);
   614     breakpoint();
   615   }
   616   verify_block(memblock);
   617   if (PrintMalloc && tty != NULL)
   618     // tty->print_cr("os::free %p", memblock);
   619     fprintf(stderr, "os::free %p\n", memblock);
   620   NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
   621   // Added by detlefs.
   622   if (MallocCushion) {
   623     u_char* ptr = (u_char*)memblock - space_before;
   624     for (u_char* p = ptr; p < ptr + MallocCushion; p++) {
   625       guarantee(*p == badResourceValue,
   626                 "Thing freed should be malloc result.");
   627       *p = (u_char)freeBlockPad;
   628     }
   629     size_t size = get_size(memblock);
   630     u_char* end = ptr + space_before + size;
   631     for (u_char* q = end; q < end + MallocCushion; q++) {
   632       guarantee(*q == badResourceValue,
   633                 "Thing freed should be malloc result.");
   634       *q = (u_char)freeBlockPad;
   635     }
   636   }
   637 #endif
   638   ::free((char*)memblock - space_before);
   639 }
   641 void os::init_random(long initval) {
   642   _rand_seed = initval;
   643 }
   646 long os::random() {
   647   /* standard, well-known linear congruential random generator with
   648    * next_rand = (16807*seed) mod (2**31-1)
   649    * see
   650    * (1) "Random Number Generators: Good Ones Are Hard to Find",
   651    *      S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
   652    * (2) "Two Fast Implementations of the 'Minimal Standard' Random
   653    *     Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
   654   */
   655   const long a = 16807;
   656   const unsigned long m = 2147483647;
   657   const long q = m / a;        assert(q == 127773, "weird math");
   658   const long r = m % a;        assert(r == 2836, "weird math");
   660   // compute az=2^31p+q
   661   unsigned long lo = a * (long)(_rand_seed & 0xFFFF);
   662   unsigned long hi = a * (long)((unsigned long)_rand_seed >> 16);
   663   lo += (hi & 0x7FFF) << 16;
   665   // if q overflowed, ignore the overflow and increment q
   666   if (lo > m) {
   667     lo &= m;
   668     ++lo;
   669   }
   670   lo += hi >> 15;
   672   // if (p+q) overflowed, ignore the overflow and increment (p+q)
   673   if (lo > m) {
   674     lo &= m;
   675     ++lo;
   676   }
   677   return (_rand_seed = lo);
   678 }
   680 // The INITIALIZED state is distinguished from the SUSPENDED state because the
   681 // conditions in which a thread is first started are different from those in which
   682 // a suspension is resumed.  These differences make it hard for us to apply the
   683 // tougher checks when starting threads that we want to do when resuming them.
   684 // However, when start_thread is called as a result of Thread.start, on a Java
   685 // thread, the operation is synchronized on the Java Thread object.  So there
   686 // cannot be a race to start the thread and hence for the thread to exit while
   687 // we are working on it.  Non-Java threads that start Java threads either have
   688 // to do so in a context in which races are impossible, or should do appropriate
   689 // locking.
   691 void os::start_thread(Thread* thread) {
   692   // guard suspend/resume
   693   MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
   694   OSThread* osthread = thread->osthread();
   695   osthread->set_state(RUNNABLE);
   696   pd_start_thread(thread);
   697 }
   699 //---------------------------------------------------------------------------
   700 // Helper functions for fatal error handler
   702 void os::print_hex_dump(outputStream* st, address start, address end, int unitsize) {
   703   assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
   705   int cols = 0;
   706   int cols_per_line = 0;
   707   switch (unitsize) {
   708     case 1: cols_per_line = 16; break;
   709     case 2: cols_per_line = 8;  break;
   710     case 4: cols_per_line = 4;  break;
   711     case 8: cols_per_line = 2;  break;
   712     default: return;
   713   }
   715   address p = start;
   716   st->print(PTR_FORMAT ":   ", start);
   717   while (p < end) {
   718     switch (unitsize) {
   719       case 1: st->print("%02x", *(u1*)p); break;
   720       case 2: st->print("%04x", *(u2*)p); break;
   721       case 4: st->print("%08x", *(u4*)p); break;
   722       case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
   723     }
   724     p += unitsize;
   725     cols++;
   726     if (cols >= cols_per_line && p < end) {
   727        cols = 0;
   728        st->cr();
   729        st->print(PTR_FORMAT ":   ", p);
   730     } else {
   731        st->print(" ");
   732     }
   733   }
   734   st->cr();
   735 }
   737 void os::print_environment_variables(outputStream* st, const char** env_list,
   738                                      char* buffer, int len) {
   739   if (env_list) {
   740     st->print_cr("Environment Variables:");
   742     for (int i = 0; env_list[i] != NULL; i++) {
   743       if (getenv(env_list[i], buffer, len)) {
   744         st->print(env_list[i]);
   745         st->print("=");
   746         st->print_cr(buffer);
   747       }
   748     }
   749   }
   750 }
   752 void os::print_cpu_info(outputStream* st) {
   753   // cpu
   754   st->print("CPU:");
   755   st->print("total %d", os::processor_count());
   756   // It's not safe to query number of active processors after crash
   757   // st->print("(active %d)", os::active_processor_count());
   758   st->print(" %s", VM_Version::cpu_features());
   759   st->cr();
   760 }
   762 void os::print_date_and_time(outputStream *st) {
   763   time_t tloc;
   764   (void)time(&tloc);
   765   st->print("time: %s", ctime(&tloc));  // ctime adds newline.
   767   double t = os::elapsedTime();
   768   // NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in
   769   //       Linux. Must be a bug in glibc ? Workaround is to round "t" to int
   770   //       before printf. We lost some precision, but who cares?
   771   st->print_cr("elapsed time: %d seconds", (int)t);
   772 }
   774 // moved from debug.cpp (used to be find()) but still called from there
   775 // The verbose parameter is only set by the debug code in one case
   776 void os::print_location(outputStream* st, intptr_t x, bool verbose) {
   777   address addr = (address)x;
   778   CodeBlob* b = CodeCache::find_blob_unsafe(addr);
   779   if (b != NULL) {
   780     if (b->is_buffer_blob()) {
   781       // the interpreter is generated into a buffer blob
   782       InterpreterCodelet* i = Interpreter::codelet_containing(addr);
   783       if (i != NULL) {
   784         st->print_cr(INTPTR_FORMAT " is an Interpreter codelet", addr);
   785         i->print_on(st);
   786         return;
   787       }
   788       if (Interpreter::contains(addr)) {
   789         st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
   790                      " (not bytecode specific)", addr);
   791         return;
   792       }
   793       //
   794       if (AdapterHandlerLibrary::contains(b)) {
   795         st->print_cr(INTPTR_FORMAT " is an AdapterHandler", addr);
   796         AdapterHandlerLibrary::print_handler_on(st, b);
   797       }
   798       // the stubroutines are generated into a buffer blob
   799       StubCodeDesc* d = StubCodeDesc::desc_for(addr);
   800       if (d != NULL) {
   801         d->print_on(st);
   802         if (verbose) st->cr();
   803         return;
   804       }
   805       if (StubRoutines::contains(addr)) {
   806         st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) "
   807                      "stub routine", addr);
   808         return;
   809       }
   810       // the InlineCacheBuffer is using stubs generated into a buffer blob
   811       if (InlineCacheBuffer::contains(addr)) {
   812         st->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr);
   813         return;
   814       }
   815       VtableStub* v = VtableStubs::stub_containing(addr);
   816       if (v != NULL) {
   817         v->print_on(st);
   818         return;
   819       }
   820     }
   821     if (verbose && b->is_nmethod()) {
   822       ResourceMark rm;
   823       st->print("%#p: Compiled ", addr);
   824       ((nmethod*)b)->method()->print_value_on(st);
   825       st->print("  = (CodeBlob*)" INTPTR_FORMAT, b);
   826       st->cr();
   827       return;
   828     }
   829     st->print(INTPTR_FORMAT " ", b);
   830     if ( b->is_nmethod()) {
   831       if (b->is_zombie()) {
   832         st->print_cr("is zombie nmethod");
   833       } else if (b->is_not_entrant()) {
   834         st->print_cr("is non-entrant nmethod");
   835       }
   836     }
   837     b->print_on(st);
   838     return;
   839   }
   841   if (Universe::heap()->is_in(addr)) {
   842     HeapWord* p = Universe::heap()->block_start(addr);
   843     bool print = false;
   844     // If we couldn't find it it just may mean that heap wasn't parseable
   845     // See if we were just given an oop directly
   846     if (p != NULL && Universe::heap()->block_is_obj(p)) {
   847       print = true;
   848     } else if (p == NULL && ((oopDesc*)addr)->is_oop()) {
   849       p = (HeapWord*) addr;
   850       print = true;
   851     }
   852     if (print) {
   853       st->print_cr(INTPTR_FORMAT " is an oop", addr);
   854       oop(p)->print_on(st);
   855       if (p != (HeapWord*)x && oop(p)->is_constMethod() &&
   856           constMethodOop(p)->contains(addr)) {
   857         Thread *thread = Thread::current();
   858         HandleMark hm(thread);
   859         methodHandle mh (thread, constMethodOop(p)->method());
   860         if (!mh->is_native()) {
   861           st->print_cr("bci_from(%p) = %d; print_codes():",
   862                         addr, mh->bci_from(address(x)));
   863           mh->print_codes_on(st);
   864         }
   865       }
   866       return;
   867     }
   868   } else {
   869     if (Universe::heap()->is_in_reserved(addr)) {
   870       st->print_cr(INTPTR_FORMAT " is an unallocated location "
   871                    "in the heap", addr);
   872       return;
   873     }
   874   }
   875   if (JNIHandles::is_global_handle((jobject) addr)) {
   876     st->print_cr(INTPTR_FORMAT " is a global jni handle", addr);
   877     return;
   878   }
   879   if (JNIHandles::is_weak_global_handle((jobject) addr)) {
   880     st->print_cr(INTPTR_FORMAT " is a weak global jni handle", addr);
   881     return;
   882   }
   883 #ifndef PRODUCT
   884   // we don't keep the block list in product mode
   885   if (JNIHandleBlock::any_contains((jobject) addr)) {
   886     st->print_cr(INTPTR_FORMAT " is a local jni handle", addr);
   887     return;
   888   }
   889 #endif
   891   for(JavaThread *thread = Threads::first(); thread; thread = thread->next()) {
   892     // Check for privilege stack
   893     if (thread->privileged_stack_top() != NULL &&
   894         thread->privileged_stack_top()->contains(addr)) {
   895       st->print_cr(INTPTR_FORMAT " is pointing into the privilege stack "
   896                    "for thread: " INTPTR_FORMAT, addr, thread);
   897       if (verbose) thread->print_on(st);
   898       return;
   899     }
   900     // If the addr is a java thread print information about that.
   901     if (addr == (address)thread) {
   902       if (verbose) {
   903         thread->print_on(st);
   904       } else {
   905         st->print_cr(INTPTR_FORMAT " is a thread", addr);
   906       }
   907       return;
   908     }
   909     // If the addr is in the stack region for this thread then report that
   910     // and print thread info
   911     if (thread->stack_base() >= addr &&
   912         addr > (thread->stack_base() - thread->stack_size())) {
   913       st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
   914                    INTPTR_FORMAT, addr, thread);
   915       if (verbose) thread->print_on(st);
   916       return;
   917     }
   919   }
   920   // Try an OS specific find
   921   if (os::find(addr, st)) {
   922     return;
   923   }
   925   st->print_cr(INTPTR_FORMAT " is an unknown value", addr);
   926 }
   928 // Looks like all platforms except IA64 can use the same function to check
   929 // if C stack is walkable beyond current frame. The check for fp() is not
   930 // necessary on Sparc, but it's harmless.
   931 bool os::is_first_C_frame(frame* fr) {
   932 #ifdef IA64
   933   // In order to walk native frames on Itanium, we need to access the unwind
   934   // table, which is inside ELF. We don't want to parse ELF after fatal error,
   935   // so return true for IA64. If we need to support C stack walking on IA64,
   936   // this function needs to be moved to CPU specific files, as fp() on IA64
   937   // is register stack, which grows towards higher memory address.
   938   return true;
   939 #endif
   941   // Load up sp, fp, sender sp and sender fp, check for reasonable values.
   942   // Check usp first, because if that's bad the other accessors may fault
   943   // on some architectures.  Ditto ufp second, etc.
   944   uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1);
   945   // sp on amd can be 32 bit aligned.
   946   uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1);
   948   uintptr_t usp    = (uintptr_t)fr->sp();
   949   if ((usp & sp_align_mask) != 0) return true;
   951   uintptr_t ufp    = (uintptr_t)fr->fp();
   952   if ((ufp & fp_align_mask) != 0) return true;
   954   uintptr_t old_sp = (uintptr_t)fr->sender_sp();
   955   if ((old_sp & sp_align_mask) != 0) return true;
   956   if (old_sp == 0 || old_sp == (uintptr_t)-1) return true;
   958   uintptr_t old_fp = (uintptr_t)fr->link();
   959   if ((old_fp & fp_align_mask) != 0) return true;
   960   if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true;
   962   // stack grows downwards; if old_fp is below current fp or if the stack
   963   // frame is too large, either the stack is corrupted or fp is not saved
   964   // on stack (i.e. on x86, ebp may be used as general register). The stack
   965   // is not walkable beyond current frame.
   966   if (old_fp < ufp) return true;
   967   if (old_fp - ufp > 64 * K) return true;
   969   return false;
   970 }
   972 #ifdef ASSERT
   973 extern "C" void test_random() {
   974   const double m = 2147483647;
   975   double mean = 0.0, variance = 0.0, t;
   976   long reps = 10000;
   977   unsigned long seed = 1;
   979   tty->print_cr("seed %ld for %ld repeats...", seed, reps);
   980   os::init_random(seed);
   981   long num;
   982   for (int k = 0; k < reps; k++) {
   983     num = os::random();
   984     double u = (double)num / m;
   985     assert(u >= 0.0 && u <= 1.0, "bad random number!");
   987     // calculate mean and variance of the random sequence
   988     mean += u;
   989     variance += (u*u);
   990   }
   991   mean /= reps;
   992   variance /= (reps - 1);
   994   assert(num == 1043618065, "bad seed");
   995   tty->print_cr("mean of the 1st 10000 numbers: %f", mean);
   996   tty->print_cr("variance of the 1st 10000 numbers: %f", variance);
   997   const double eps = 0.0001;
   998   t = fabsd(mean - 0.5018);
   999   assert(t < eps, "bad mean");
  1000   t = (variance - 0.3355) < 0.0 ? -(variance - 0.3355) : variance - 0.3355;
  1001   assert(t < eps, "bad variance");
  1003 #endif
  1006 // Set up the boot classpath.
  1008 char* os::format_boot_path(const char* format_string,
  1009                            const char* home,
  1010                            int home_len,
  1011                            char fileSep,
  1012                            char pathSep) {
  1013     assert((fileSep == '/' && pathSep == ':') ||
  1014            (fileSep == '\\' && pathSep == ';'), "unexpected seperator chars");
  1016     // Scan the format string to determine the length of the actual
  1017     // boot classpath, and handle platform dependencies as well.
  1018     int formatted_path_len = 0;
  1019     const char* p;
  1020     for (p = format_string; *p != 0; ++p) {
  1021         if (*p == '%') formatted_path_len += home_len - 1;
  1022         ++formatted_path_len;
  1025     char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1);
  1026     if (formatted_path == NULL) {
  1027         return NULL;
  1030     // Create boot classpath from format, substituting separator chars and
  1031     // java home directory.
  1032     char* q = formatted_path;
  1033     for (p = format_string; *p != 0; ++p) {
  1034         switch (*p) {
  1035         case '%':
  1036             strcpy(q, home);
  1037             q += home_len;
  1038             break;
  1039         case '/':
  1040             *q++ = fileSep;
  1041             break;
  1042         case ':':
  1043             *q++ = pathSep;
  1044             break;
  1045         default:
  1046             *q++ = *p;
  1049     *q = '\0';
  1051     assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
  1052     return formatted_path;
  1056 bool os::set_boot_path(char fileSep, char pathSep) {
  1057     const char* home = Arguments::get_java_home();
  1058     int home_len = (int)strlen(home);
  1060     static const char* meta_index_dir_format = "%/lib/";
  1061     static const char* meta_index_format = "%/lib/meta-index";
  1062     char* meta_index = format_boot_path(meta_index_format, home, home_len, fileSep, pathSep);
  1063     if (meta_index == NULL) return false;
  1064     char* meta_index_dir = format_boot_path(meta_index_dir_format, home, home_len, fileSep, pathSep);
  1065     if (meta_index_dir == NULL) return false;
  1066     Arguments::set_meta_index_path(meta_index, meta_index_dir);
  1068     // Any modification to the JAR-file list, for the boot classpath must be
  1069     // aligned with install/install/make/common/Pack.gmk. Note: boot class
  1070     // path class JARs, are stripped for StackMapTable to reduce download size.
  1071     static const char classpath_format[] =
  1072         "%/lib/resources.jar:"
  1073         "%/lib/rt.jar:"
  1074         "%/lib/sunrsasign.jar:"
  1075         "%/lib/jsse.jar:"
  1076         "%/lib/jce.jar:"
  1077         "%/lib/charsets.jar:"
  1079         // ## TEMPORARY hack to keep the legacy launcher working when
  1080         // ## only the boot module is installed (cf. j.l.ClassLoader)
  1081         "%/lib/modules/jdk.boot.jar:"
  1083         "%/classes";
  1084     char* sysclasspath = format_boot_path(classpath_format, home, home_len, fileSep, pathSep);
  1085     if (sysclasspath == NULL) return false;
  1086     Arguments::set_sysclasspath(sysclasspath);
  1088     return true;
  1091 /*
  1092  * Splits a path, based on its separator, the number of
  1093  * elements is returned back in n.
  1094  * It is the callers responsibility to:
  1095  *   a> check the value of n, and n may be 0.
  1096  *   b> ignore any empty path elements
  1097  *   c> free up the data.
  1098  */
  1099 char** os::split_path(const char* path, int* n) {
  1100   *n = 0;
  1101   if (path == NULL || strlen(path) == 0) {
  1102     return NULL;
  1104   const char psepchar = *os::path_separator();
  1105   char* inpath = (char*)NEW_C_HEAP_ARRAY(char, strlen(path) + 1);
  1106   if (inpath == NULL) {
  1107     return NULL;
  1109   strncpy(inpath, path, strlen(path));
  1110   int count = 1;
  1111   char* p = strchr(inpath, psepchar);
  1112   // Get a count of elements to allocate memory
  1113   while (p != NULL) {
  1114     count++;
  1115     p++;
  1116     p = strchr(p, psepchar);
  1118   char** opath = (char**) NEW_C_HEAP_ARRAY(char*, count);
  1119   if (opath == NULL) {
  1120     return NULL;
  1123   // do the actual splitting
  1124   p = inpath;
  1125   for (int i = 0 ; i < count ; i++) {
  1126     size_t len = strcspn(p, os::path_separator());
  1127     if (len > JVM_MAXPATHLEN) {
  1128       return NULL;
  1130     // allocate the string and add terminator storage
  1131     char* s  = (char*)NEW_C_HEAP_ARRAY(char, len + 1);
  1132     if (s == NULL) {
  1133       return NULL;
  1135     strncpy(s, p, len);
  1136     s[len] = '\0';
  1137     opath[i] = s;
  1138     p += len + 1;
  1140   FREE_C_HEAP_ARRAY(char, inpath);
  1141   *n = count;
  1142   return opath;
  1145 void os::set_memory_serialize_page(address page) {
  1146   int count = log2_intptr(sizeof(class JavaThread)) - log2_intptr(64);
  1147   _mem_serialize_page = (volatile int32_t *)page;
  1148   // We initialize the serialization page shift count here
  1149   // We assume a cache line size of 64 bytes
  1150   assert(SerializePageShiftCount == count,
  1151          "thread size changed, fix SerializePageShiftCount constant");
  1152   set_serialize_page_mask((uintptr_t)(vm_page_size() - sizeof(int32_t)));
  1155 static volatile intptr_t SerializePageLock = 0;
  1157 // This method is called from signal handler when SIGSEGV occurs while the current
  1158 // thread tries to store to the "read-only" memory serialize page during state
  1159 // transition.
  1160 void os::block_on_serialize_page_trap() {
  1161   if (TraceSafepoint) {
  1162     tty->print_cr("Block until the serialize page permission restored");
  1164   // When VMThread is holding the SerializePageLock during modifying the
  1165   // access permission of the memory serialize page, the following call
  1166   // will block until the permission of that page is restored to rw.
  1167   // Generally, it is unsafe to manipulate locks in signal handlers, but in
  1168   // this case, it's OK as the signal is synchronous and we know precisely when
  1169   // it can occur.
  1170   Thread::muxAcquire(&SerializePageLock, "set_memory_serialize_page");
  1171   Thread::muxRelease(&SerializePageLock);
  1174 // Serialize all thread state variables
  1175 void os::serialize_thread_states() {
  1176   // On some platforms such as Solaris & Linux, the time duration of the page
  1177   // permission restoration is observed to be much longer than expected  due to
  1178   // scheduler starvation problem etc. To avoid the long synchronization
  1179   // time and expensive page trap spinning, 'SerializePageLock' is used to block
  1180   // the mutator thread if such case is encountered. See bug 6546278 for details.
  1181   Thread::muxAcquire(&SerializePageLock, "serialize_thread_states");
  1182   os::protect_memory((char *)os::get_memory_serialize_page(),
  1183                      os::vm_page_size(), MEM_PROT_READ);
  1184   os::protect_memory((char *)os::get_memory_serialize_page(),
  1185                      os::vm_page_size(), MEM_PROT_RW);
  1186   Thread::muxRelease(&SerializePageLock);
  1189 // Returns true if the current stack pointer is above the stack shadow
  1190 // pages, false otherwise.
  1192 bool os::stack_shadow_pages_available(Thread *thread, methodHandle method) {
  1193   assert(StackRedPages > 0 && StackYellowPages > 0,"Sanity check");
  1194   address sp = current_stack_pointer();
  1195   // Check if we have StackShadowPages above the yellow zone.  This parameter
  1196   // is dependent on the depth of the maximum VM call stack possible from
  1197   // the handler for stack overflow.  'instanceof' in the stack overflow
  1198   // handler or a println uses at least 8k stack of VM and native code
  1199   // respectively.
  1200   const int framesize_in_bytes =
  1201     Interpreter::size_top_interpreter_activation(method()) * wordSize;
  1202   int reserved_area = ((StackShadowPages + StackRedPages + StackYellowPages)
  1203                       * vm_page_size()) + framesize_in_bytes;
  1204   // The very lower end of the stack
  1205   address stack_limit = thread->stack_base() - thread->stack_size();
  1206   return (sp > (stack_limit + reserved_area));
  1209 size_t os::page_size_for_region(size_t region_min_size, size_t region_max_size,
  1210                                 uint min_pages)
  1212   assert(min_pages > 0, "sanity");
  1213   if (UseLargePages) {
  1214     const size_t max_page_size = region_max_size / min_pages;
  1216     for (unsigned int i = 0; _page_sizes[i] != 0; ++i) {
  1217       const size_t sz = _page_sizes[i];
  1218       const size_t mask = sz - 1;
  1219       if ((region_min_size & mask) == 0 && (region_max_size & mask) == 0) {
  1220         // The largest page size with no fragmentation.
  1221         return sz;
  1224       if (sz <= max_page_size) {
  1225         // The largest page size that satisfies the min_pages requirement.
  1226         return sz;
  1231   return vm_page_size();
  1234 #ifndef PRODUCT
  1235 void os::trace_page_sizes(const char* str, const size_t region_min_size,
  1236                           const size_t region_max_size, const size_t page_size,
  1237                           const char* base, const size_t size)
  1239   if (TracePageSizes) {
  1240     tty->print_cr("%s:  min=" SIZE_FORMAT " max=" SIZE_FORMAT
  1241                   " pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT
  1242                   " size=" SIZE_FORMAT,
  1243                   str, region_min_size, region_max_size,
  1244                   page_size, base, size);
  1247 #endif  // #ifndef PRODUCT
  1249 // This is the working definition of a server class machine:
  1250 // >= 2 physical CPU's and >=2GB of memory, with some fuzz
  1251 // because the graphics memory (?) sometimes masks physical memory.
  1252 // If you want to change the definition of a server class machine
  1253 // on some OS or platform, e.g., >=4GB on Windohs platforms,
  1254 // then you'll have to parameterize this method based on that state,
  1255 // as was done for logical processors here, or replicate and
  1256 // specialize this method for each platform.  (Or fix os to have
  1257 // some inheritance structure and use subclassing.  Sigh.)
  1258 // If you want some platform to always or never behave as a server
  1259 // class machine, change the setting of AlwaysActAsServerClassMachine
  1260 // and NeverActAsServerClassMachine in globals*.hpp.
  1261 bool os::is_server_class_machine() {
  1262   // First check for the early returns
  1263   if (NeverActAsServerClassMachine) {
  1264     return false;
  1266   if (AlwaysActAsServerClassMachine) {
  1267     return true;
  1269   // Then actually look at the machine
  1270   bool         result            = false;
  1271   const unsigned int    server_processors = 2;
  1272   const julong server_memory     = 2UL * G;
  1273   // We seem not to get our full complement of memory.
  1274   //     We allow some part (1/8?) of the memory to be "missing",
  1275   //     based on the sizes of DIMMs, and maybe graphics cards.
  1276   const julong missing_memory   = 256UL * M;
  1278   /* Is this a server class machine? */
  1279   if ((os::active_processor_count() >= (int)server_processors) &&
  1280       (os::physical_memory() >= (server_memory - missing_memory))) {
  1281     const unsigned int logical_processors =
  1282       VM_Version::logical_processors_per_package();
  1283     if (logical_processors > 1) {
  1284       const unsigned int physical_packages =
  1285         os::active_processor_count() / logical_processors;
  1286       if (physical_packages > server_processors) {
  1287         result = true;
  1289     } else {
  1290       result = true;
  1293   return result;

mercurial