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