Tue, 26 Aug 2014 13:38:33 -0700
Merge
1 /*
2 * Copyright (c) 1997, 2014, 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 #ifdef ASSERT
36 #include "memory/guardedMemory.hpp"
37 #endif
38 #include "oops/oop.inline.hpp"
39 #include "prims/jvm.h"
40 #include "prims/jvm_misc.hpp"
41 #include "prims/privilegedStack.hpp"
42 #include "runtime/arguments.hpp"
43 #include "runtime/frame.inline.hpp"
44 #include "runtime/interfaceSupport.hpp"
45 #include "runtime/java.hpp"
46 #include "runtime/javaCalls.hpp"
47 #include "runtime/mutexLocker.hpp"
48 #include "runtime/os.hpp"
49 #include "runtime/stubRoutines.hpp"
50 #include "runtime/thread.inline.hpp"
51 #include "services/attachListener.hpp"
52 #include "services/memTracker.hpp"
53 #include "services/threadService.hpp"
54 #include "utilities/defaultStream.hpp"
55 #include "utilities/events.hpp"
56 #ifdef TARGET_OS_FAMILY_linux
57 # include "os_linux.inline.hpp"
58 #endif
59 #ifdef TARGET_OS_FAMILY_solaris
60 # include "os_solaris.inline.hpp"
61 #endif
62 #ifdef TARGET_OS_FAMILY_windows
63 # include "os_windows.inline.hpp"
64 #endif
65 #ifdef TARGET_OS_FAMILY_bsd
66 # include "os_bsd.inline.hpp"
67 #endif
69 # include <signal.h>
71 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
73 OSThread* os::_starting_thread = NULL;
74 address os::_polling_page = NULL;
75 volatile int32_t* os::_mem_serialize_page = NULL;
76 uintptr_t os::_serialize_page_mask = 0;
77 long os::_rand_seed = 1;
78 int os::_processor_count = 0;
79 size_t os::_page_sizes[os::page_sizes_max];
81 #ifndef PRODUCT
82 julong os::num_mallocs = 0; // # of calls to malloc/realloc
83 julong os::alloc_bytes = 0; // # of bytes allocated
84 julong os::num_frees = 0; // # of calls to free
85 julong os::free_bytes = 0; // # of bytes freed
86 #endif
88 static juint cur_malloc_words = 0; // current size for MallocMaxTestWords
90 void os_init_globals() {
91 // Called from init_globals().
92 // See Threads::create_vm() in thread.cpp, and init.cpp.
93 os::init_globals();
94 }
96 // Fill in buffer with current local time as an ISO-8601 string.
97 // E.g., yyyy-mm-ddThh:mm:ss-zzzz.
98 // Returns buffer, or NULL if it failed.
99 // This would mostly be a call to
100 // strftime(...., "%Y-%m-%d" "T" "%H:%M:%S" "%z", ....)
101 // except that on Windows the %z behaves badly, so we do it ourselves.
102 // Also, people wanted milliseconds on there,
103 // and strftime doesn't do milliseconds.
104 char* os::iso8601_time(char* buffer, size_t buffer_length) {
105 // Output will be of the form "YYYY-MM-DDThh:mm:ss.mmm+zzzz\0"
106 // 1 2
107 // 12345678901234567890123456789
108 static const char* iso8601_format =
109 "%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d%02d";
110 static const size_t needed_buffer = 29;
112 // Sanity check the arguments
113 if (buffer == NULL) {
114 assert(false, "NULL buffer");
115 return NULL;
116 }
117 if (buffer_length < needed_buffer) {
118 assert(false, "buffer_length too small");
119 return NULL;
120 }
121 // Get the current time
122 jlong milliseconds_since_19700101 = javaTimeMillis();
123 const int milliseconds_per_microsecond = 1000;
124 const time_t seconds_since_19700101 =
125 milliseconds_since_19700101 / milliseconds_per_microsecond;
126 const int milliseconds_after_second =
127 milliseconds_since_19700101 % milliseconds_per_microsecond;
128 // Convert the time value to a tm and timezone variable
129 struct tm time_struct;
130 if (localtime_pd(&seconds_since_19700101, &time_struct) == NULL) {
131 assert(false, "Failed localtime_pd");
132 return NULL;
133 }
134 #if defined(_ALLBSD_SOURCE)
135 const time_t zone = (time_t) time_struct.tm_gmtoff;
136 #else
137 const time_t zone = timezone;
138 #endif
140 // If daylight savings time is in effect,
141 // we are 1 hour East of our time zone
142 const time_t seconds_per_minute = 60;
143 const time_t minutes_per_hour = 60;
144 const time_t seconds_per_hour = seconds_per_minute * minutes_per_hour;
145 time_t UTC_to_local = zone;
146 if (time_struct.tm_isdst > 0) {
147 UTC_to_local = UTC_to_local - seconds_per_hour;
148 }
149 // Compute the time zone offset.
150 // localtime_pd() sets timezone to the difference (in seconds)
151 // between UTC and and local time.
152 // ISO 8601 says we need the difference between local time and UTC,
153 // we change the sign of the localtime_pd() result.
154 const time_t local_to_UTC = -(UTC_to_local);
155 // Then we have to figure out if if we are ahead (+) or behind (-) UTC.
156 char sign_local_to_UTC = '+';
157 time_t abs_local_to_UTC = local_to_UTC;
158 if (local_to_UTC < 0) {
159 sign_local_to_UTC = '-';
160 abs_local_to_UTC = -(abs_local_to_UTC);
161 }
162 // Convert time zone offset seconds to hours and minutes.
163 const time_t zone_hours = (abs_local_to_UTC / seconds_per_hour);
164 const time_t zone_min =
165 ((abs_local_to_UTC % seconds_per_hour) / seconds_per_minute);
167 // Print an ISO 8601 date and time stamp into the buffer
168 const int year = 1900 + time_struct.tm_year;
169 const int month = 1 + time_struct.tm_mon;
170 const int printed = jio_snprintf(buffer, buffer_length, iso8601_format,
171 year,
172 month,
173 time_struct.tm_mday,
174 time_struct.tm_hour,
175 time_struct.tm_min,
176 time_struct.tm_sec,
177 milliseconds_after_second,
178 sign_local_to_UTC,
179 zone_hours,
180 zone_min);
181 if (printed == 0) {
182 assert(false, "Failed jio_printf");
183 return NULL;
184 }
185 return buffer;
186 }
188 OSReturn os::set_priority(Thread* thread, ThreadPriority p) {
189 #ifdef ASSERT
190 if (!(!thread->is_Java_thread() ||
191 Thread::current() == thread ||
192 Threads_lock->owned_by_self()
193 || thread->is_Compiler_thread()
194 )) {
195 assert(false, "possibility of dangling Thread pointer");
196 }
197 #endif
199 if (p >= MinPriority && p <= MaxPriority) {
200 int priority = java_to_os_priority[p];
201 return set_native_priority(thread, priority);
202 } else {
203 assert(false, "Should not happen");
204 return OS_ERR;
205 }
206 }
208 // The mapping from OS priority back to Java priority may be inexact because
209 // Java priorities can map M:1 with native priorities. If you want the definite
210 // Java priority then use JavaThread::java_priority()
211 OSReturn os::get_priority(const Thread* const thread, ThreadPriority& priority) {
212 int p;
213 int os_prio;
214 OSReturn ret = get_native_priority(thread, &os_prio);
215 if (ret != OS_OK) return ret;
217 if (java_to_os_priority[MaxPriority] > java_to_os_priority[MinPriority]) {
218 for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] > os_prio; p--) ;
219 } else {
220 // niceness values are in reverse order
221 for (p = MaxPriority; p > MinPriority && java_to_os_priority[p] < os_prio; p--) ;
222 }
223 priority = (ThreadPriority)p;
224 return OS_OK;
225 }
228 // --------------------- sun.misc.Signal (optional) ---------------------
231 // SIGBREAK is sent by the keyboard to query the VM state
232 #ifndef SIGBREAK
233 #define SIGBREAK SIGQUIT
234 #endif
236 // sigexitnum_pd is a platform-specific special signal used for terminating the Signal thread.
239 static void signal_thread_entry(JavaThread* thread, TRAPS) {
240 os::set_priority(thread, NearMaxPriority);
241 while (true) {
242 int sig;
243 {
244 // FIXME : Currently we have not decieded what should be the status
245 // for this java thread blocked here. Once we decide about
246 // that we should fix this.
247 sig = os::signal_wait();
248 }
249 if (sig == os::sigexitnum_pd()) {
250 // Terminate the signal thread
251 return;
252 }
254 switch (sig) {
255 case SIGBREAK: {
256 // Check if the signal is a trigger to start the Attach Listener - in that
257 // case don't print stack traces.
258 if (!DisableAttachMechanism && AttachListener::is_init_trigger()) {
259 continue;
260 }
261 // Print stack traces
262 // Any SIGBREAK operations added here should make sure to flush
263 // the output stream (e.g. tty->flush()) after output. See 4803766.
264 // Each module also prints an extra carriage return after its output.
265 VM_PrintThreads op;
266 VMThread::execute(&op);
267 VM_PrintJNI jni_op;
268 VMThread::execute(&jni_op);
269 VM_FindDeadlocks op1(tty);
270 VMThread::execute(&op1);
271 Universe::print_heap_at_SIGBREAK();
272 if (PrintClassHistogram) {
273 VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */);
274 VMThread::execute(&op1);
275 }
276 if (JvmtiExport::should_post_data_dump()) {
277 JvmtiExport::post_data_dump();
278 }
279 break;
280 }
281 default: {
282 // Dispatch the signal to java
283 HandleMark hm(THREAD);
284 Klass* k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_Signal(), THREAD);
285 KlassHandle klass (THREAD, k);
286 if (klass.not_null()) {
287 JavaValue result(T_VOID);
288 JavaCallArguments args;
289 args.push_int(sig);
290 JavaCalls::call_static(
291 &result,
292 klass,
293 vmSymbols::dispatch_name(),
294 vmSymbols::int_void_signature(),
295 &args,
296 THREAD
297 );
298 }
299 if (HAS_PENDING_EXCEPTION) {
300 // tty is initialized early so we don't expect it to be null, but
301 // if it is we can't risk doing an initialization that might
302 // trigger additional out-of-memory conditions
303 if (tty != NULL) {
304 char klass_name[256];
305 char tmp_sig_name[16];
306 const char* sig_name = "UNKNOWN";
307 InstanceKlass::cast(PENDING_EXCEPTION->klass())->
308 name()->as_klass_external_name(klass_name, 256);
309 if (os::exception_name(sig, tmp_sig_name, 16) != NULL)
310 sig_name = tmp_sig_name;
311 warning("Exception %s occurred dispatching signal %s to handler"
312 "- the VM may need to be forcibly terminated",
313 klass_name, sig_name );
314 }
315 CLEAR_PENDING_EXCEPTION;
316 }
317 }
318 }
319 }
320 }
322 void os::init_before_ergo() {
323 // We need to initialize large page support here because ergonomics takes some
324 // decisions depending on large page support and the calculated large page size.
325 large_page_init();
326 }
328 void os::signal_init() {
329 if (!ReduceSignalUsage) {
330 // Setup JavaThread for processing signals
331 EXCEPTION_MARK;
332 Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
333 instanceKlassHandle klass (THREAD, k);
334 instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
336 const char thread_name[] = "Signal Dispatcher";
337 Handle string = java_lang_String::create_from_str(thread_name, CHECK);
339 // Initialize thread_oop to put it into the system threadGroup
340 Handle thread_group (THREAD, Universe::system_thread_group());
341 JavaValue result(T_VOID);
342 JavaCalls::call_special(&result, thread_oop,
343 klass,
344 vmSymbols::object_initializer_name(),
345 vmSymbols::threadgroup_string_void_signature(),
346 thread_group,
347 string,
348 CHECK);
350 KlassHandle group(THREAD, SystemDictionary::ThreadGroup_klass());
351 JavaCalls::call_special(&result,
352 thread_group,
353 group,
354 vmSymbols::add_method_name(),
355 vmSymbols::thread_void_signature(),
356 thread_oop, // ARG 1
357 CHECK);
359 os::signal_init_pd();
361 { MutexLocker mu(Threads_lock);
362 JavaThread* signal_thread = new JavaThread(&signal_thread_entry);
364 // At this point it may be possible that no osthread was created for the
365 // JavaThread due to lack of memory. We would have to throw an exception
366 // in that case. However, since this must work and we do not allow
367 // exceptions anyway, check and abort if this fails.
368 if (signal_thread == NULL || signal_thread->osthread() == NULL) {
369 vm_exit_during_initialization("java.lang.OutOfMemoryError",
370 "unable to create new native thread");
371 }
373 java_lang_Thread::set_thread(thread_oop(), signal_thread);
374 java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
375 java_lang_Thread::set_daemon(thread_oop());
377 signal_thread->set_threadObj(thread_oop());
378 Threads::add(signal_thread);
379 Thread::start(signal_thread);
380 }
381 // Handle ^BREAK
382 os::signal(SIGBREAK, os::user_handler());
383 }
384 }
387 void os::terminate_signal_thread() {
388 if (!ReduceSignalUsage)
389 signal_notify(sigexitnum_pd());
390 }
393 // --------------------- loading libraries ---------------------
395 typedef jint (JNICALL *JNI_OnLoad_t)(JavaVM *, void *);
396 extern struct JavaVM_ main_vm;
398 static void* _native_java_library = NULL;
400 void* os::native_java_library() {
401 if (_native_java_library == NULL) {
402 char buffer[JVM_MAXPATHLEN];
403 char ebuf[1024];
405 // Try to load verify dll first. In 1.3 java dll depends on it and is not
406 // always able to find it when the loading executable is outside the JDK.
407 // In order to keep working with 1.2 we ignore any loading errors.
408 if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
409 "verify")) {
410 dll_load(buffer, ebuf, sizeof(ebuf));
411 }
413 // Load java dll
414 if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
415 "java")) {
416 _native_java_library = dll_load(buffer, ebuf, sizeof(ebuf));
417 }
418 if (_native_java_library == NULL) {
419 vm_exit_during_initialization("Unable to load native library", ebuf);
420 }
422 #if defined(__OpenBSD__)
423 // Work-around OpenBSD's lack of $ORIGIN support by pre-loading libnet.so
424 // ignore errors
425 if (dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
426 "net")) {
427 dll_load(buffer, ebuf, sizeof(ebuf));
428 }
429 #endif
430 }
431 static jboolean onLoaded = JNI_FALSE;
432 if (onLoaded) {
433 // We may have to wait to fire OnLoad until TLS is initialized.
434 if (ThreadLocalStorage::is_initialized()) {
435 // The JNI_OnLoad handling is normally done by method load in
436 // java.lang.ClassLoader$NativeLibrary, but the VM loads the base library
437 // explicitly so we have to check for JNI_OnLoad as well
438 const char *onLoadSymbols[] = JNI_ONLOAD_SYMBOLS;
439 JNI_OnLoad_t JNI_OnLoad = CAST_TO_FN_PTR(
440 JNI_OnLoad_t, dll_lookup(_native_java_library, onLoadSymbols[0]));
441 if (JNI_OnLoad != NULL) {
442 JavaThread* thread = JavaThread::current();
443 ThreadToNativeFromVM ttn(thread);
444 HandleMark hm(thread);
445 jint ver = (*JNI_OnLoad)(&main_vm, NULL);
446 onLoaded = JNI_TRUE;
447 if (!Threads::is_supported_jni_version_including_1_1(ver)) {
448 vm_exit_during_initialization("Unsupported JNI version");
449 }
450 }
451 }
452 }
453 return _native_java_library;
454 }
456 /*
457 * Support for finding Agent_On(Un)Load/Attach<_lib_name> if it exists.
458 * If check_lib == true then we are looking for an
459 * Agent_OnLoad_lib_name or Agent_OnAttach_lib_name function to determine if
460 * this library is statically linked into the image.
461 * If check_lib == false then we will look for the appropriate symbol in the
462 * executable if agent_lib->is_static_lib() == true or in the shared library
463 * referenced by 'handle'.
464 */
465 void* os::find_agent_function(AgentLibrary *agent_lib, bool check_lib,
466 const char *syms[], size_t syms_len) {
467 assert(agent_lib != NULL, "sanity check");
468 const char *lib_name;
469 void *handle = agent_lib->os_lib();
470 void *entryName = NULL;
471 char *agent_function_name;
472 size_t i;
474 // If checking then use the agent name otherwise test is_static_lib() to
475 // see how to process this lookup
476 lib_name = ((check_lib || agent_lib->is_static_lib()) ? agent_lib->name() : NULL);
477 for (i = 0; i < syms_len; i++) {
478 agent_function_name = build_agent_function_name(syms[i], lib_name, agent_lib->is_absolute_path());
479 if (agent_function_name == NULL) {
480 break;
481 }
482 entryName = dll_lookup(handle, agent_function_name);
483 FREE_C_HEAP_ARRAY(char, agent_function_name, mtThread);
484 if (entryName != NULL) {
485 break;
486 }
487 }
488 return entryName;
489 }
491 // See if the passed in agent is statically linked into the VM image.
492 bool os::find_builtin_agent(AgentLibrary *agent_lib, const char *syms[],
493 size_t syms_len) {
494 void *ret;
495 void *proc_handle;
496 void *save_handle;
498 assert(agent_lib != NULL, "sanity check");
499 if (agent_lib->name() == NULL) {
500 return false;
501 }
502 proc_handle = get_default_process_handle();
503 // Check for Agent_OnLoad/Attach_lib_name function
504 save_handle = agent_lib->os_lib();
505 // We want to look in this process' symbol table.
506 agent_lib->set_os_lib(proc_handle);
507 ret = find_agent_function(agent_lib, true, syms, syms_len);
508 if (ret != NULL) {
509 // Found an entry point like Agent_OnLoad_lib_name so we have a static agent
510 agent_lib->set_valid();
511 agent_lib->set_static_lib(true);
512 return true;
513 }
514 agent_lib->set_os_lib(save_handle);
515 return false;
516 }
518 // --------------------- heap allocation utilities ---------------------
520 char *os::strdup(const char *str, MEMFLAGS flags) {
521 size_t size = strlen(str);
522 char *dup_str = (char *)malloc(size + 1, flags);
523 if (dup_str == NULL) return NULL;
524 strcpy(dup_str, str);
525 return dup_str;
526 }
530 #define paranoid 0 /* only set to 1 if you suspect checking code has bug */
532 #ifdef ASSERT
533 static void verify_memory(void* ptr) {
534 GuardedMemory guarded(ptr);
535 if (!guarded.verify_guards()) {
536 tty->print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees);
537 tty->print_cr("## memory stomp:");
538 guarded.print_on(tty);
539 fatal("memory stomping error");
540 }
541 }
542 #endif
544 //
545 // This function supports testing of the malloc out of memory
546 // condition without really running the system out of memory.
547 //
548 static u_char* testMalloc(size_t alloc_size) {
549 assert(MallocMaxTestWords > 0, "sanity check");
551 if ((cur_malloc_words + (alloc_size / BytesPerWord)) > MallocMaxTestWords) {
552 return NULL;
553 }
555 u_char* ptr = (u_char*)::malloc(alloc_size);
557 if (ptr != NULL) {
558 Atomic::add(((jint) (alloc_size / BytesPerWord)),
559 (volatile jint *) &cur_malloc_words);
560 }
561 return ptr;
562 }
564 void* os::malloc(size_t size, MEMFLAGS memflags, address caller) {
565 NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
566 NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
568 #ifdef ASSERT
569 // checking for the WatcherThread and crash_protection first
570 // since os::malloc can be called when the libjvm.{dll,so} is
571 // first loaded and we don't have a thread yet.
572 // try to find the thread after we see that the watcher thread
573 // exists and has crash protection.
574 WatcherThread *wt = WatcherThread::watcher_thread();
575 if (wt != NULL && wt->has_crash_protection()) {
576 Thread* thread = ThreadLocalStorage::get_thread_slow();
577 if (thread == wt) {
578 assert(!wt->has_crash_protection(),
579 "Can't malloc with crash protection from WatcherThread");
580 }
581 }
582 #endif
584 if (size == 0) {
585 // return a valid pointer if size is zero
586 // if NULL is returned the calling functions assume out of memory.
587 size = 1;
588 }
590 #ifndef ASSERT
591 const size_t alloc_size = size;
592 #else
593 const size_t alloc_size = GuardedMemory::get_total_size(size);
594 if (size > alloc_size) { // Check for rollover.
595 return NULL;
596 }
597 #endif
599 NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
601 u_char* ptr;
602 if (MallocMaxTestWords > 0) {
603 ptr = testMalloc(alloc_size);
604 } else {
605 ptr = (u_char*)::malloc(alloc_size);
606 }
608 #ifdef ASSERT
609 if (ptr == NULL) {
610 return NULL;
611 }
612 // Wrap memory with guard
613 GuardedMemory guarded(ptr, size);
614 ptr = guarded.get_user_ptr();
615 #endif
616 if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
617 tty->print_cr("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
618 breakpoint();
619 }
620 debug_only(if (paranoid) verify_memory(ptr));
621 if (PrintMalloc && tty != NULL) {
622 tty->print_cr("os::malloc " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
623 }
625 // we do not track guard memory
626 MemTracker::record_malloc((address)ptr, size, memflags, caller == 0 ? CALLER_PC : caller);
628 return ptr;
629 }
632 void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, address caller) {
633 #ifndef ASSERT
634 NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
635 NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
636 MemTracker::Tracker tkr = MemTracker::get_realloc_tracker();
637 void* ptr = ::realloc(memblock, size);
638 if (ptr != NULL) {
639 tkr.record((address)memblock, (address)ptr, size, memflags,
640 caller == 0 ? CALLER_PC : caller);
641 } else {
642 tkr.discard();
643 }
644 return ptr;
645 #else
646 if (memblock == NULL) {
647 return os::malloc(size, memflags, (caller == 0 ? CALLER_PC : caller));
648 }
649 if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
650 tty->print_cr("os::realloc caught " PTR_FORMAT, memblock);
651 breakpoint();
652 }
653 verify_memory(memblock);
654 NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
655 if (size == 0) {
656 return NULL;
657 }
658 // always move the block
659 void* ptr = os::malloc(size, memflags, caller == 0 ? CALLER_PC : caller);
660 if (PrintMalloc) {
661 tty->print_cr("os::remalloc " SIZE_FORMAT " bytes, " PTR_FORMAT " --> " PTR_FORMAT, size, memblock, ptr);
662 }
663 // Copy to new memory if malloc didn't fail
664 if ( ptr != NULL ) {
665 GuardedMemory guarded(memblock);
666 memcpy(ptr, memblock, MIN2(size, guarded.get_user_size()));
667 if (paranoid) verify_memory(ptr);
668 if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) {
669 tty->print_cr("os::realloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr);
670 breakpoint();
671 }
672 os::free(memblock);
673 }
674 return ptr;
675 #endif
676 }
679 void os::free(void *memblock, MEMFLAGS memflags) {
680 address trackp = (address) memblock;
681 NOT_PRODUCT(inc_stat_counter(&num_frees, 1));
682 #ifdef ASSERT
683 if (memblock == NULL) return;
684 if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) {
685 if (tty != NULL) tty->print_cr("os::free caught " PTR_FORMAT, memblock);
686 breakpoint();
687 }
688 verify_memory(memblock);
689 NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
691 GuardedMemory guarded(memblock);
692 size_t size = guarded.get_user_size();
693 inc_stat_counter(&free_bytes, size);
694 memblock = guarded.release_for_freeing();
695 if (PrintMalloc && tty != NULL) {
696 fprintf(stderr, "os::free " SIZE_FORMAT " bytes --> " PTR_FORMAT "\n", size, (uintptr_t)memblock);
697 }
698 #endif
699 MemTracker::record_free(trackp, memflags);
701 ::free(memblock);
702 }
704 void os::init_random(long initval) {
705 _rand_seed = initval;
706 }
709 long os::random() {
710 /* standard, well-known linear congruential random generator with
711 * next_rand = (16807*seed) mod (2**31-1)
712 * see
713 * (1) "Random Number Generators: Good Ones Are Hard to Find",
714 * S.K. Park and K.W. Miller, Communications of the ACM 31:10 (Oct 1988),
715 * (2) "Two Fast Implementations of the 'Minimal Standard' Random
716 * Number Generator", David G. Carta, Comm. ACM 33, 1 (Jan 1990), pp. 87-88.
717 */
718 const long a = 16807;
719 const unsigned long m = 2147483647;
720 const long q = m / a; assert(q == 127773, "weird math");
721 const long r = m % a; assert(r == 2836, "weird math");
723 // compute az=2^31p+q
724 unsigned long lo = a * (long)(_rand_seed & 0xFFFF);
725 unsigned long hi = a * (long)((unsigned long)_rand_seed >> 16);
726 lo += (hi & 0x7FFF) << 16;
728 // if q overflowed, ignore the overflow and increment q
729 if (lo > m) {
730 lo &= m;
731 ++lo;
732 }
733 lo += hi >> 15;
735 // if (p+q) overflowed, ignore the overflow and increment (p+q)
736 if (lo > m) {
737 lo &= m;
738 ++lo;
739 }
740 return (_rand_seed = lo);
741 }
743 // The INITIALIZED state is distinguished from the SUSPENDED state because the
744 // conditions in which a thread is first started are different from those in which
745 // a suspension is resumed. These differences make it hard for us to apply the
746 // tougher checks when starting threads that we want to do when resuming them.
747 // However, when start_thread is called as a result of Thread.start, on a Java
748 // thread, the operation is synchronized on the Java Thread object. So there
749 // cannot be a race to start the thread and hence for the thread to exit while
750 // we are working on it. Non-Java threads that start Java threads either have
751 // to do so in a context in which races are impossible, or should do appropriate
752 // locking.
754 void os::start_thread(Thread* thread) {
755 // guard suspend/resume
756 MutexLockerEx ml(thread->SR_lock(), Mutex::_no_safepoint_check_flag);
757 OSThread* osthread = thread->osthread();
758 osthread->set_state(RUNNABLE);
759 pd_start_thread(thread);
760 }
762 //---------------------------------------------------------------------------
763 // Helper functions for fatal error handler
765 void os::print_hex_dump(outputStream* st, address start, address end, int unitsize) {
766 assert(unitsize == 1 || unitsize == 2 || unitsize == 4 || unitsize == 8, "just checking");
768 int cols = 0;
769 int cols_per_line = 0;
770 switch (unitsize) {
771 case 1: cols_per_line = 16; break;
772 case 2: cols_per_line = 8; break;
773 case 4: cols_per_line = 4; break;
774 case 8: cols_per_line = 2; break;
775 default: return;
776 }
778 address p = start;
779 st->print(PTR_FORMAT ": ", start);
780 while (p < end) {
781 switch (unitsize) {
782 case 1: st->print("%02x", *(u1*)p); break;
783 case 2: st->print("%04x", *(u2*)p); break;
784 case 4: st->print("%08x", *(u4*)p); break;
785 case 8: st->print("%016" FORMAT64_MODIFIER "x", *(u8*)p); break;
786 }
787 p += unitsize;
788 cols++;
789 if (cols >= cols_per_line && p < end) {
790 cols = 0;
791 st->cr();
792 st->print(PTR_FORMAT ": ", p);
793 } else {
794 st->print(" ");
795 }
796 }
797 st->cr();
798 }
800 void os::print_environment_variables(outputStream* st, const char** env_list,
801 char* buffer, int len) {
802 if (env_list) {
803 st->print_cr("Environment Variables:");
805 for (int i = 0; env_list[i] != NULL; i++) {
806 if (getenv(env_list[i], buffer, len)) {
807 st->print("%s", env_list[i]);
808 st->print("=");
809 st->print_cr("%s", buffer);
810 }
811 }
812 }
813 }
815 void os::print_cpu_info(outputStream* st) {
816 // cpu
817 st->print("CPU:");
818 st->print("total %d", os::processor_count());
819 // It's not safe to query number of active processors after crash
820 // st->print("(active %d)", os::active_processor_count());
821 st->print(" %s", VM_Version::cpu_features());
822 st->cr();
823 pd_print_cpu_info(st);
824 }
826 void os::print_date_and_time(outputStream *st) {
827 const int secs_per_day = 86400;
828 const int secs_per_hour = 3600;
829 const int secs_per_min = 60;
831 time_t tloc;
832 (void)time(&tloc);
833 st->print("time: %s", ctime(&tloc)); // ctime adds newline.
835 double t = os::elapsedTime();
836 // NOTE: It tends to crash after a SEGV if we want to printf("%f",...) in
837 // Linux. Must be a bug in glibc ? Workaround is to round "t" to int
838 // before printf. We lost some precision, but who cares?
839 int eltime = (int)t; // elapsed time in seconds
841 // print elapsed time in a human-readable format:
842 int eldays = eltime / secs_per_day;
843 int day_secs = eldays * secs_per_day;
844 int elhours = (eltime - day_secs) / secs_per_hour;
845 int hour_secs = elhours * secs_per_hour;
846 int elmins = (eltime - day_secs - hour_secs) / secs_per_min;
847 int minute_secs = elmins * secs_per_min;
848 int elsecs = (eltime - day_secs - hour_secs - minute_secs);
849 st->print_cr("elapsed time: %d seconds (%dd %dh %dm %ds)", eltime, eldays, elhours, elmins, elsecs);
850 }
852 // moved from debug.cpp (used to be find()) but still called from there
853 // The verbose parameter is only set by the debug code in one case
854 void os::print_location(outputStream* st, intptr_t x, bool verbose) {
855 address addr = (address)x;
856 CodeBlob* b = CodeCache::find_blob_unsafe(addr);
857 if (b != NULL) {
858 if (b->is_buffer_blob()) {
859 // the interpreter is generated into a buffer blob
860 InterpreterCodelet* i = Interpreter::codelet_containing(addr);
861 if (i != NULL) {
862 st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an Interpreter codelet", addr, (int)(addr - i->code_begin()));
863 i->print_on(st);
864 return;
865 }
866 if (Interpreter::contains(addr)) {
867 st->print_cr(INTPTR_FORMAT " is pointing into interpreter code"
868 " (not bytecode specific)", addr);
869 return;
870 }
871 //
872 if (AdapterHandlerLibrary::contains(b)) {
873 st->print_cr(INTPTR_FORMAT " is at code_begin+%d in an AdapterHandler", addr, (int)(addr - b->code_begin()));
874 AdapterHandlerLibrary::print_handler_on(st, b);
875 }
876 // the stubroutines are generated into a buffer blob
877 StubCodeDesc* d = StubCodeDesc::desc_for(addr);
878 if (d != NULL) {
879 st->print_cr(INTPTR_FORMAT " is at begin+%d in a stub", addr, (int)(addr - d->begin()));
880 d->print_on(st);
881 st->cr();
882 return;
883 }
884 if (StubRoutines::contains(addr)) {
885 st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) "
886 "stub routine", addr);
887 return;
888 }
889 // the InlineCacheBuffer is using stubs generated into a buffer blob
890 if (InlineCacheBuffer::contains(addr)) {
891 st->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr);
892 return;
893 }
894 VtableStub* v = VtableStubs::stub_containing(addr);
895 if (v != NULL) {
896 st->print_cr(INTPTR_FORMAT " is at entry_point+%d in a vtable stub", addr, (int)(addr - v->entry_point()));
897 v->print_on(st);
898 st->cr();
899 return;
900 }
901 }
902 nmethod* nm = b->as_nmethod_or_null();
903 if (nm != NULL) {
904 ResourceMark rm;
905 st->print(INTPTR_FORMAT " is at entry_point+%d in (nmethod*)" INTPTR_FORMAT,
906 addr, (int)(addr - nm->entry_point()), nm);
907 if (verbose) {
908 st->print(" for ");
909 nm->method()->print_value_on(st);
910 }
911 st->cr();
912 nm->print_nmethod(verbose);
913 return;
914 }
915 st->print_cr(INTPTR_FORMAT " is at code_begin+%d in ", addr, (int)(addr - b->code_begin()));
916 b->print_on(st);
917 return;
918 }
920 if (Universe::heap()->is_in(addr)) {
921 HeapWord* p = Universe::heap()->block_start(addr);
922 bool print = false;
923 // If we couldn't find it it just may mean that heap wasn't parseable
924 // See if we were just given an oop directly
925 if (p != NULL && Universe::heap()->block_is_obj(p)) {
926 print = true;
927 } else if (p == NULL && ((oopDesc*)addr)->is_oop()) {
928 p = (HeapWord*) addr;
929 print = true;
930 }
931 if (print) {
932 if (p == (HeapWord*) addr) {
933 st->print_cr(INTPTR_FORMAT " is an oop", addr);
934 } else {
935 st->print_cr(INTPTR_FORMAT " is pointing into object: " INTPTR_FORMAT, addr, p);
936 }
937 oop(p)->print_on(st);
938 return;
939 }
940 } else {
941 if (Universe::heap()->is_in_reserved(addr)) {
942 st->print_cr(INTPTR_FORMAT " is an unallocated location "
943 "in the heap", addr);
944 return;
945 }
946 }
947 if (JNIHandles::is_global_handle((jobject) addr)) {
948 st->print_cr(INTPTR_FORMAT " is a global jni handle", addr);
949 return;
950 }
951 if (JNIHandles::is_weak_global_handle((jobject) addr)) {
952 st->print_cr(INTPTR_FORMAT " is a weak global jni handle", addr);
953 return;
954 }
955 #ifndef PRODUCT
956 // we don't keep the block list in product mode
957 if (JNIHandleBlock::any_contains((jobject) addr)) {
958 st->print_cr(INTPTR_FORMAT " is a local jni handle", addr);
959 return;
960 }
961 #endif
963 for(JavaThread *thread = Threads::first(); thread; thread = thread->next()) {
964 // Check for privilege stack
965 if (thread->privileged_stack_top() != NULL &&
966 thread->privileged_stack_top()->contains(addr)) {
967 st->print_cr(INTPTR_FORMAT " is pointing into the privilege stack "
968 "for thread: " INTPTR_FORMAT, addr, thread);
969 if (verbose) thread->print_on(st);
970 return;
971 }
972 // If the addr is a java thread print information about that.
973 if (addr == (address)thread) {
974 if (verbose) {
975 thread->print_on(st);
976 } else {
977 st->print_cr(INTPTR_FORMAT " is a thread", addr);
978 }
979 return;
980 }
981 // If the addr is in the stack region for this thread then report that
982 // and print thread info
983 if (thread->stack_base() >= addr &&
984 addr > (thread->stack_base() - thread->stack_size())) {
985 st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: "
986 INTPTR_FORMAT, addr, thread);
987 if (verbose) thread->print_on(st);
988 return;
989 }
991 }
993 // Check if in metaspace and print types that have vptrs (only method now)
994 if (Metaspace::contains(addr)) {
995 if (Method::has_method_vptr((const void*)addr)) {
996 ((Method*)addr)->print_value_on(st);
997 st->cr();
998 } else {
999 // Use addr->print() from the debugger instead (not here)
1000 st->print_cr(INTPTR_FORMAT " is pointing into metadata", addr);
1001 }
1002 return;
1003 }
1005 // Try an OS specific find
1006 if (os::find(addr, st)) {
1007 return;
1008 }
1010 st->print_cr(INTPTR_FORMAT " is an unknown value", addr);
1011 }
1013 // Looks like all platforms except IA64 can use the same function to check
1014 // if C stack is walkable beyond current frame. The check for fp() is not
1015 // necessary on Sparc, but it's harmless.
1016 bool os::is_first_C_frame(frame* fr) {
1017 #if (defined(IA64) && !defined(AIX)) && !defined(_WIN32)
1018 // On IA64 we have to check if the callers bsp is still valid
1019 // (i.e. within the register stack bounds).
1020 // Notice: this only works for threads created by the VM and only if
1021 // we walk the current stack!!! If we want to be able to walk
1022 // arbitrary other threads, we'll have to somehow store the thread
1023 // object in the frame.
1024 Thread *thread = Thread::current();
1025 if ((address)fr->fp() <=
1026 thread->register_stack_base() HPUX_ONLY(+ 0x0) LINUX_ONLY(+ 0x50)) {
1027 // This check is a little hacky, because on Linux the first C
1028 // frame's ('start_thread') register stack frame starts at
1029 // "register_stack_base + 0x48" while on HPUX, the first C frame's
1030 // ('__pthread_bound_body') register stack frame seems to really
1031 // start at "register_stack_base".
1032 return true;
1033 } else {
1034 return false;
1035 }
1036 #elif defined(IA64) && defined(_WIN32)
1037 return true;
1038 #else
1039 // Load up sp, fp, sender sp and sender fp, check for reasonable values.
1040 // Check usp first, because if that's bad the other accessors may fault
1041 // on some architectures. Ditto ufp second, etc.
1042 uintptr_t fp_align_mask = (uintptr_t)(sizeof(address)-1);
1043 // sp on amd can be 32 bit aligned.
1044 uintptr_t sp_align_mask = (uintptr_t)(sizeof(int)-1);
1046 uintptr_t usp = (uintptr_t)fr->sp();
1047 if ((usp & sp_align_mask) != 0) return true;
1049 uintptr_t ufp = (uintptr_t)fr->fp();
1050 if ((ufp & fp_align_mask) != 0) return true;
1052 uintptr_t old_sp = (uintptr_t)fr->sender_sp();
1053 if ((old_sp & sp_align_mask) != 0) return true;
1054 if (old_sp == 0 || old_sp == (uintptr_t)-1) return true;
1056 uintptr_t old_fp = (uintptr_t)fr->link();
1057 if ((old_fp & fp_align_mask) != 0) return true;
1058 if (old_fp == 0 || old_fp == (uintptr_t)-1 || old_fp == ufp) return true;
1060 // stack grows downwards; if old_fp is below current fp or if the stack
1061 // frame is too large, either the stack is corrupted or fp is not saved
1062 // on stack (i.e. on x86, ebp may be used as general register). The stack
1063 // is not walkable beyond current frame.
1064 if (old_fp < ufp) return true;
1065 if (old_fp - ufp > 64 * K) return true;
1067 return false;
1068 #endif
1069 }
1071 #ifdef ASSERT
1072 extern "C" void test_random() {
1073 const double m = 2147483647;
1074 double mean = 0.0, variance = 0.0, t;
1075 long reps = 10000;
1076 unsigned long seed = 1;
1078 tty->print_cr("seed %ld for %ld repeats...", seed, reps);
1079 os::init_random(seed);
1080 long num;
1081 for (int k = 0; k < reps; k++) {
1082 num = os::random();
1083 double u = (double)num / m;
1084 assert(u >= 0.0 && u <= 1.0, "bad random number!");
1086 // calculate mean and variance of the random sequence
1087 mean += u;
1088 variance += (u*u);
1089 }
1090 mean /= reps;
1091 variance /= (reps - 1);
1093 assert(num == 1043618065, "bad seed");
1094 tty->print_cr("mean of the 1st 10000 numbers: %f", mean);
1095 tty->print_cr("variance of the 1st 10000 numbers: %f", variance);
1096 const double eps = 0.0001;
1097 t = fabsd(mean - 0.5018);
1098 assert(t < eps, "bad mean");
1099 t = (variance - 0.3355) < 0.0 ? -(variance - 0.3355) : variance - 0.3355;
1100 assert(t < eps, "bad variance");
1101 }
1102 #endif
1105 // Set up the boot classpath.
1107 char* os::format_boot_path(const char* format_string,
1108 const char* home,
1109 int home_len,
1110 char fileSep,
1111 char pathSep) {
1112 assert((fileSep == '/' && pathSep == ':') ||
1113 (fileSep == '\\' && pathSep == ';'), "unexpected seperator chars");
1115 // Scan the format string to determine the length of the actual
1116 // boot classpath, and handle platform dependencies as well.
1117 int formatted_path_len = 0;
1118 const char* p;
1119 for (p = format_string; *p != 0; ++p) {
1120 if (*p == '%') formatted_path_len += home_len - 1;
1121 ++formatted_path_len;
1122 }
1124 char* formatted_path = NEW_C_HEAP_ARRAY(char, formatted_path_len + 1, mtInternal);
1125 if (formatted_path == NULL) {
1126 return NULL;
1127 }
1129 // Create boot classpath from format, substituting separator chars and
1130 // java home directory.
1131 char* q = formatted_path;
1132 for (p = format_string; *p != 0; ++p) {
1133 switch (*p) {
1134 case '%':
1135 strcpy(q, home);
1136 q += home_len;
1137 break;
1138 case '/':
1139 *q++ = fileSep;
1140 break;
1141 case ':':
1142 *q++ = pathSep;
1143 break;
1144 default:
1145 *q++ = *p;
1146 }
1147 }
1148 *q = '\0';
1150 assert((q - formatted_path) == formatted_path_len, "formatted_path size botched");
1151 return formatted_path;
1152 }
1155 bool os::set_boot_path(char fileSep, char pathSep) {
1156 const char* home = Arguments::get_java_home();
1157 int home_len = (int)strlen(home);
1159 static const char* meta_index_dir_format = "%/lib/";
1160 static const char* meta_index_format = "%/lib/meta-index";
1161 char* meta_index = format_boot_path(meta_index_format, home, home_len, fileSep, pathSep);
1162 if (meta_index == NULL) return false;
1163 char* meta_index_dir = format_boot_path(meta_index_dir_format, home, home_len, fileSep, pathSep);
1164 if (meta_index_dir == NULL) return false;
1165 Arguments::set_meta_index_path(meta_index, meta_index_dir);
1167 // Any modification to the JAR-file list, for the boot classpath must be
1168 // aligned with install/install/make/common/Pack.gmk. Note: boot class
1169 // path class JARs, are stripped for StackMapTable to reduce download size.
1170 static const char classpath_format[] =
1171 "%/lib/resources.jar:"
1172 "%/lib/rt.jar:"
1173 "%/lib/sunrsasign.jar:"
1174 "%/lib/jsse.jar:"
1175 "%/lib/jce.jar:"
1176 "%/lib/charsets.jar:"
1177 "%/lib/jfr.jar:"
1178 "%/classes";
1179 char* sysclasspath = format_boot_path(classpath_format, home, home_len, fileSep, pathSep);
1180 if (sysclasspath == NULL) return false;
1181 Arguments::set_sysclasspath(sysclasspath);
1183 return true;
1184 }
1186 /*
1187 * Splits a path, based on its separator, the number of
1188 * elements is returned back in n.
1189 * It is the callers responsibility to:
1190 * a> check the value of n, and n may be 0.
1191 * b> ignore any empty path elements
1192 * c> free up the data.
1193 */
1194 char** os::split_path(const char* path, int* n) {
1195 *n = 0;
1196 if (path == NULL || strlen(path) == 0) {
1197 return NULL;
1198 }
1199 const char psepchar = *os::path_separator();
1200 char* inpath = (char*)NEW_C_HEAP_ARRAY(char, strlen(path) + 1, mtInternal);
1201 if (inpath == NULL) {
1202 return NULL;
1203 }
1204 strcpy(inpath, path);
1205 int count = 1;
1206 char* p = strchr(inpath, psepchar);
1207 // Get a count of elements to allocate memory
1208 while (p != NULL) {
1209 count++;
1210 p++;
1211 p = strchr(p, psepchar);
1212 }
1213 char** opath = (char**) NEW_C_HEAP_ARRAY(char*, count, mtInternal);
1214 if (opath == NULL) {
1215 return NULL;
1216 }
1218 // do the actual splitting
1219 p = inpath;
1220 for (int i = 0 ; i < count ; i++) {
1221 size_t len = strcspn(p, os::path_separator());
1222 if (len > JVM_MAXPATHLEN) {
1223 return NULL;
1224 }
1225 // allocate the string and add terminator storage
1226 char* s = (char*)NEW_C_HEAP_ARRAY(char, len + 1, mtInternal);
1227 if (s == NULL) {
1228 return NULL;
1229 }
1230 strncpy(s, p, len);
1231 s[len] = '\0';
1232 opath[i] = s;
1233 p += len + 1;
1234 }
1235 FREE_C_HEAP_ARRAY(char, inpath, mtInternal);
1236 *n = count;
1237 return opath;
1238 }
1240 void os::set_memory_serialize_page(address page) {
1241 int count = log2_intptr(sizeof(class JavaThread)) - log2_intptr(64);
1242 _mem_serialize_page = (volatile int32_t *)page;
1243 // We initialize the serialization page shift count here
1244 // We assume a cache line size of 64 bytes
1245 assert(SerializePageShiftCount == count,
1246 "thread size changed, fix SerializePageShiftCount constant");
1247 set_serialize_page_mask((uintptr_t)(vm_page_size() - sizeof(int32_t)));
1248 }
1250 static volatile intptr_t SerializePageLock = 0;
1252 // This method is called from signal handler when SIGSEGV occurs while the current
1253 // thread tries to store to the "read-only" memory serialize page during state
1254 // transition.
1255 void os::block_on_serialize_page_trap() {
1256 if (TraceSafepoint) {
1257 tty->print_cr("Block until the serialize page permission restored");
1258 }
1259 // When VMThread is holding the SerializePageLock during modifying the
1260 // access permission of the memory serialize page, the following call
1261 // will block until the permission of that page is restored to rw.
1262 // Generally, it is unsafe to manipulate locks in signal handlers, but in
1263 // this case, it's OK as the signal is synchronous and we know precisely when
1264 // it can occur.
1265 Thread::muxAcquire(&SerializePageLock, "set_memory_serialize_page");
1266 Thread::muxRelease(&SerializePageLock);
1267 }
1269 // Serialize all thread state variables
1270 void os::serialize_thread_states() {
1271 // On some platforms such as Solaris & Linux, the time duration of the page
1272 // permission restoration is observed to be much longer than expected due to
1273 // scheduler starvation problem etc. To avoid the long synchronization
1274 // time and expensive page trap spinning, 'SerializePageLock' is used to block
1275 // the mutator thread if such case is encountered. See bug 6546278 for details.
1276 Thread::muxAcquire(&SerializePageLock, "serialize_thread_states");
1277 os::protect_memory((char *)os::get_memory_serialize_page(),
1278 os::vm_page_size(), MEM_PROT_READ);
1279 os::protect_memory((char *)os::get_memory_serialize_page(),
1280 os::vm_page_size(), MEM_PROT_RW);
1281 Thread::muxRelease(&SerializePageLock);
1282 }
1284 // Returns true if the current stack pointer is above the stack shadow
1285 // pages, false otherwise.
1287 bool os::stack_shadow_pages_available(Thread *thread, methodHandle method) {
1288 assert(StackRedPages > 0 && StackYellowPages > 0,"Sanity check");
1289 address sp = current_stack_pointer();
1290 // Check if we have StackShadowPages above the yellow zone. This parameter
1291 // is dependent on the depth of the maximum VM call stack possible from
1292 // the handler for stack overflow. 'instanceof' in the stack overflow
1293 // handler or a println uses at least 8k stack of VM and native code
1294 // respectively.
1295 const int framesize_in_bytes =
1296 Interpreter::size_top_interpreter_activation(method()) * wordSize;
1297 int reserved_area = ((StackShadowPages + StackRedPages + StackYellowPages)
1298 * vm_page_size()) + framesize_in_bytes;
1299 // The very lower end of the stack
1300 address stack_limit = thread->stack_base() - thread->stack_size();
1301 return (sp > (stack_limit + reserved_area));
1302 }
1304 size_t os::page_size_for_region(size_t region_min_size, size_t region_max_size,
1305 uint min_pages)
1306 {
1307 assert(min_pages > 0, "sanity");
1308 if (UseLargePages) {
1309 const size_t max_page_size = region_max_size / min_pages;
1311 for (unsigned int i = 0; _page_sizes[i] != 0; ++i) {
1312 const size_t sz = _page_sizes[i];
1313 const size_t mask = sz - 1;
1314 if ((region_min_size & mask) == 0 && (region_max_size & mask) == 0) {
1315 // The largest page size with no fragmentation.
1316 return sz;
1317 }
1319 if (sz <= max_page_size) {
1320 // The largest page size that satisfies the min_pages requirement.
1321 return sz;
1322 }
1323 }
1324 }
1326 return vm_page_size();
1327 }
1329 #ifndef PRODUCT
1330 void os::trace_page_sizes(const char* str, const size_t* page_sizes, int count)
1331 {
1332 if (TracePageSizes) {
1333 tty->print("%s: ", str);
1334 for (int i = 0; i < count; ++i) {
1335 tty->print(" " SIZE_FORMAT, page_sizes[i]);
1336 }
1337 tty->cr();
1338 }
1339 }
1341 void os::trace_page_sizes(const char* str, const size_t region_min_size,
1342 const size_t region_max_size, const size_t page_size,
1343 const char* base, const size_t size)
1344 {
1345 if (TracePageSizes) {
1346 tty->print_cr("%s: min=" SIZE_FORMAT " max=" SIZE_FORMAT
1347 " pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT
1348 " size=" SIZE_FORMAT,
1349 str, region_min_size, region_max_size,
1350 page_size, base, size);
1351 }
1352 }
1353 #endif // #ifndef PRODUCT
1355 // This is the working definition of a server class machine:
1356 // >= 2 physical CPU's and >=2GB of memory, with some fuzz
1357 // because the graphics memory (?) sometimes masks physical memory.
1358 // If you want to change the definition of a server class machine
1359 // on some OS or platform, e.g., >=4GB on Windohs platforms,
1360 // then you'll have to parameterize this method based on that state,
1361 // as was done for logical processors here, or replicate and
1362 // specialize this method for each platform. (Or fix os to have
1363 // some inheritance structure and use subclassing. Sigh.)
1364 // If you want some platform to always or never behave as a server
1365 // class machine, change the setting of AlwaysActAsServerClassMachine
1366 // and NeverActAsServerClassMachine in globals*.hpp.
1367 bool os::is_server_class_machine() {
1368 // First check for the early returns
1369 if (NeverActAsServerClassMachine) {
1370 return false;
1371 }
1372 if (AlwaysActAsServerClassMachine) {
1373 return true;
1374 }
1375 // Then actually look at the machine
1376 bool result = false;
1377 const unsigned int server_processors = 2;
1378 const julong server_memory = 2UL * G;
1379 // We seem not to get our full complement of memory.
1380 // We allow some part (1/8?) of the memory to be "missing",
1381 // based on the sizes of DIMMs, and maybe graphics cards.
1382 const julong missing_memory = 256UL * M;
1384 /* Is this a server class machine? */
1385 if ((os::active_processor_count() >= (int)server_processors) &&
1386 (os::physical_memory() >= (server_memory - missing_memory))) {
1387 const unsigned int logical_processors =
1388 VM_Version::logical_processors_per_package();
1389 if (logical_processors > 1) {
1390 const unsigned int physical_packages =
1391 os::active_processor_count() / logical_processors;
1392 if (physical_packages > server_processors) {
1393 result = true;
1394 }
1395 } else {
1396 result = true;
1397 }
1398 }
1399 return result;
1400 }
1402 void os::SuspendedThreadTask::run() {
1403 assert(Threads_lock->owned_by_self() || (_thread == VMThread::vm_thread()), "must have threads lock to call this");
1404 internal_do_task();
1405 _done = true;
1406 }
1408 bool os::create_stack_guard_pages(char* addr, size_t bytes) {
1409 return os::pd_create_stack_guard_pages(addr, bytes);
1410 }
1412 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint) {
1413 char* result = pd_reserve_memory(bytes, addr, alignment_hint);
1414 if (result != NULL) {
1415 MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
1416 }
1418 return result;
1419 }
1421 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint,
1422 MEMFLAGS flags) {
1423 char* result = pd_reserve_memory(bytes, addr, alignment_hint);
1424 if (result != NULL) {
1425 MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
1426 MemTracker::record_virtual_memory_type((address)result, flags);
1427 }
1429 return result;
1430 }
1432 char* os::attempt_reserve_memory_at(size_t bytes, char* addr) {
1433 char* result = pd_attempt_reserve_memory_at(bytes, addr);
1434 if (result != NULL) {
1435 MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
1436 }
1437 return result;
1438 }
1440 void os::split_reserved_memory(char *base, size_t size,
1441 size_t split, bool realloc) {
1442 pd_split_reserved_memory(base, size, split, realloc);
1443 }
1445 bool os::commit_memory(char* addr, size_t bytes, bool executable) {
1446 bool res = pd_commit_memory(addr, bytes, executable);
1447 if (res) {
1448 MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1449 }
1450 return res;
1451 }
1453 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint,
1454 bool executable) {
1455 bool res = os::pd_commit_memory(addr, size, alignment_hint, executable);
1456 if (res) {
1457 MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1458 }
1459 return res;
1460 }
1462 void os::commit_memory_or_exit(char* addr, size_t bytes, bool executable,
1463 const char* mesg) {
1464 pd_commit_memory_or_exit(addr, bytes, executable, mesg);
1465 MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
1466 }
1468 void os::commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint,
1469 bool executable, const char* mesg) {
1470 os::pd_commit_memory_or_exit(addr, size, alignment_hint, executable, mesg);
1471 MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
1472 }
1474 bool os::uncommit_memory(char* addr, size_t bytes) {
1475 MemTracker::Tracker tkr = MemTracker::get_virtual_memory_uncommit_tracker();
1476 bool res = pd_uncommit_memory(addr, bytes);
1477 if (res) {
1478 tkr.record((address)addr, bytes);
1479 } else {
1480 tkr.discard();
1481 }
1482 return res;
1483 }
1485 bool os::release_memory(char* addr, size_t bytes) {
1486 MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
1487 bool res = pd_release_memory(addr, bytes);
1488 if (res) {
1489 tkr.record((address)addr, bytes);
1490 } else {
1491 tkr.discard();
1492 }
1493 return res;
1494 }
1497 char* os::map_memory(int fd, const char* file_name, size_t file_offset,
1498 char *addr, size_t bytes, bool read_only,
1499 bool allow_exec) {
1500 char* result = pd_map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec);
1501 if (result != NULL) {
1502 MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, mtNone, CALLER_PC);
1503 }
1504 return result;
1505 }
1507 char* os::remap_memory(int fd, const char* file_name, size_t file_offset,
1508 char *addr, size_t bytes, bool read_only,
1509 bool allow_exec) {
1510 return pd_remap_memory(fd, file_name, file_offset, addr, bytes,
1511 read_only, allow_exec);
1512 }
1514 bool os::unmap_memory(char *addr, size_t bytes) {
1515 MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
1516 bool result = pd_unmap_memory(addr, bytes);
1517 if (result) {
1518 tkr.record((address)addr, bytes);
1519 } else {
1520 tkr.discard();
1521 }
1522 return result;
1523 }
1525 void os::free_memory(char *addr, size_t bytes, size_t alignment_hint) {
1526 pd_free_memory(addr, bytes, alignment_hint);
1527 }
1529 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
1530 pd_realign_memory(addr, bytes, alignment_hint);
1531 }
1533 #ifndef TARGET_OS_FAMILY_windows
1534 /* try to switch state from state "from" to state "to"
1535 * returns the state set after the method is complete
1536 */
1537 os::SuspendResume::State os::SuspendResume::switch_state(os::SuspendResume::State from,
1538 os::SuspendResume::State to)
1539 {
1540 os::SuspendResume::State result =
1541 (os::SuspendResume::State) Atomic::cmpxchg((jint) to, (jint *) &_state, (jint) from);
1542 if (result == from) {
1543 // success
1544 return to;
1545 }
1546 return result;
1547 }
1548 #endif