annotate src/share/vm/runtime/synchronizer.cpp @ 2560:9b0ca45cd756

Added tag hs21-b17 for changeset 81d815b05abb
author trims
date Tue, 28 Jun 2011 10:57:38 -0700
parents 3582bf76420e
children
rev   line source
duke@0 1 /*
trims@2273 2 * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
duke@0 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
duke@0 4 *
duke@0 5 * This code is free software; you can redistribute it and/or modify it
duke@0 6 * under the terms of the GNU General Public License version 2 only, as
duke@0 7 * published by the Free Software Foundation.
duke@0 8 *
duke@0 9 * This code is distributed in the hope that it will be useful, but WITHOUT
duke@0 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
duke@0 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
duke@0 12 * version 2 for more details (a copy is included in the LICENSE file that
duke@0 13 * accompanied this code).
duke@0 14 *
duke@0 15 * You should have received a copy of the GNU General Public License version
duke@0 16 * 2 along with this work; if not, write to the Free Software Foundation,
duke@0 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
duke@0 18 *
trims@1472 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
trims@1472 20 * or visit www.oracle.com if you need additional information or have any
trims@1472 21 * questions.
duke@0 22 *
duke@0 23 */
duke@0 24
stefank@1879 25 #include "precompiled.hpp"
stefank@1879 26 #include "classfile/vmSymbols.hpp"
stefank@1879 27 #include "memory/resourceArea.hpp"
stefank@1879 28 #include "oops/markOop.hpp"
stefank@1879 29 #include "oops/oop.inline.hpp"
stefank@1879 30 #include "runtime/biasedLocking.hpp"
stefank@1879 31 #include "runtime/handles.inline.hpp"
stefank@1879 32 #include "runtime/interfaceSupport.hpp"
stefank@1879 33 #include "runtime/mutexLocker.hpp"
stefank@1879 34 #include "runtime/objectMonitor.hpp"
stefank@1879 35 #include "runtime/objectMonitor.inline.hpp"
stefank@1879 36 #include "runtime/osThread.hpp"
stefank@1879 37 #include "runtime/stubRoutines.hpp"
stefank@1879 38 #include "runtime/synchronizer.hpp"
stefank@1879 39 #include "utilities/dtrace.hpp"
stefank@1879 40 #include "utilities/events.hpp"
stefank@1879 41 #include "utilities/preserveException.hpp"
stefank@1879 42 #ifdef TARGET_OS_FAMILY_linux
stefank@1879 43 # include "os_linux.inline.hpp"
stefank@1879 44 # include "thread_linux.inline.hpp"
stefank@1879 45 #endif
stefank@1879 46 #ifdef TARGET_OS_FAMILY_solaris
stefank@1879 47 # include "os_solaris.inline.hpp"
stefank@1879 48 # include "thread_solaris.inline.hpp"
stefank@1879 49 #endif
stefank@1879 50 #ifdef TARGET_OS_FAMILY_windows
stefank@1879 51 # include "os_windows.inline.hpp"
stefank@1879 52 # include "thread_windows.inline.hpp"
stefank@1879 53 #endif
duke@0 54
duke@0 55 #if defined(__GNUC__) && !defined(IA64)
duke@0 56 // Need to inhibit inlining for older versions of GCC to avoid build-time failures
duke@0 57 #define ATTR __attribute__((noinline))
duke@0 58 #else
duke@0 59 #define ATTR
duke@0 60 #endif
duke@0 61
duke@0 62 // The "core" versions of monitor enter and exit reside in this file.
duke@0 63 // The interpreter and compilers contain specialized transliterated
duke@0 64 // variants of the enter-exit fast-path operations. See i486.ad fast_lock(),
duke@0 65 // for instance. If you make changes here, make sure to modify the
duke@0 66 // interpreter, and both C1 and C2 fast-path inline locking code emission.
duke@0 67 //
duke@0 68 //
duke@0 69 // -----------------------------------------------------------------------------
duke@0 70
duke@0 71 #ifdef DTRACE_ENABLED
duke@0 72
duke@0 73 // Only bother with this argument setup if dtrace is available
duke@0 74 // TODO-FIXME: probes should not fire when caller is _blocked. assert() accordingly.
duke@0 75
duke@0 76 HS_DTRACE_PROBE_DECL5(hotspot, monitor__wait,
duke@0 77 jlong, uintptr_t, char*, int, long);
duke@0 78 HS_DTRACE_PROBE_DECL4(hotspot, monitor__waited,
duke@0 79 jlong, uintptr_t, char*, int);
duke@0 80
duke@0 81 #define DTRACE_MONITOR_PROBE_COMMON(klassOop, thread) \
duke@0 82 char* bytes = NULL; \
duke@0 83 int len = 0; \
duke@0 84 jlong jtid = SharedRuntime::get_java_tid(thread); \
coleenp@2062 85 Symbol* klassname = ((oop)(klassOop))->klass()->klass_part()->name(); \
duke@0 86 if (klassname != NULL) { \
duke@0 87 bytes = (char*)klassname->bytes(); \
duke@0 88 len = klassname->utf8_length(); \
duke@0 89 }
duke@0 90
duke@0 91 #define DTRACE_MONITOR_WAIT_PROBE(monitor, klassOop, thread, millis) \
duke@0 92 { \
duke@0 93 if (DTraceMonitorProbes) { \
duke@0 94 DTRACE_MONITOR_PROBE_COMMON(klassOop, thread); \
duke@0 95 HS_DTRACE_PROBE5(hotspot, monitor__wait, jtid, \
duke@0 96 (monitor), bytes, len, (millis)); \
duke@0 97 } \
duke@0 98 }
duke@0 99
duke@0 100 #define DTRACE_MONITOR_PROBE(probe, monitor, klassOop, thread) \
duke@0 101 { \
duke@0 102 if (DTraceMonitorProbes) { \
duke@0 103 DTRACE_MONITOR_PROBE_COMMON(klassOop, thread); \
duke@0 104 HS_DTRACE_PROBE4(hotspot, monitor__##probe, jtid, \
duke@0 105 (uintptr_t)(monitor), bytes, len); \
duke@0 106 } \
duke@0 107 }
duke@0 108
duke@0 109 #else // ndef DTRACE_ENABLED
duke@0 110
duke@0 111 #define DTRACE_MONITOR_WAIT_PROBE(klassOop, thread, millis, mon) {;}
duke@0 112 #define DTRACE_MONITOR_PROBE(probe, klassOop, thread, mon) {;}
duke@0 113
duke@0 114 #endif // ndef DTRACE_ENABLED
duke@0 115
acorn@1798 116 // This exists only as a workaround of dtrace bug 6254741
acorn@1798 117 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) {
acorn@1798 118 DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
acorn@1798 119 return 0;
acorn@1798 120 }
duke@0 121
acorn@1798 122 #define NINFLATIONLOCKS 256
acorn@1798 123 static volatile intptr_t InflationLocks [NINFLATIONLOCKS] ;
acorn@1798 124
acorn@1798 125 ObjectMonitor * ObjectSynchronizer::gBlockList = NULL ;
acorn@1798 126 ObjectMonitor * volatile ObjectSynchronizer::gFreeList = NULL ;
acorn@1798 127 ObjectMonitor * volatile ObjectSynchronizer::gOmInUseList = NULL ;
acorn@1798 128 int ObjectSynchronizer::gOmInUseCount = 0;
acorn@1798 129 static volatile intptr_t ListLock = 0 ; // protects global monitor free-list cache
acorn@1798 130 static volatile int MonitorFreeCount = 0 ; // # on gFreeList
acorn@1798 131 static volatile int MonitorPopulation = 0 ; // # Extant -- in circulation
acorn@1798 132 #define CHAINMARKER ((oop)-1)
acorn@1798 133
acorn@1798 134 // -----------------------------------------------------------------------------
acorn@1798 135 // Fast Monitor Enter/Exit
acorn@1798 136 // This the fast monitor enter. The interpreter and compiler use
acorn@1798 137 // some assembly copies of this code. Make sure update those code
acorn@1798 138 // if the following function is changed. The implementation is
acorn@1798 139 // extremely sensitive to race condition. Be careful.
acorn@1798 140
acorn@1798 141 void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock, bool attempt_rebias, TRAPS) {
acorn@1798 142 if (UseBiasedLocking) {
acorn@1798 143 if (!SafepointSynchronize::is_at_safepoint()) {
acorn@1798 144 BiasedLocking::Condition cond = BiasedLocking::revoke_and_rebias(obj, attempt_rebias, THREAD);
acorn@1798 145 if (cond == BiasedLocking::BIAS_REVOKED_AND_REBIASED) {
acorn@1798 146 return;
acorn@1798 147 }
acorn@1798 148 } else {
acorn@1798 149 assert(!attempt_rebias, "can not rebias toward VM thread");
acorn@1798 150 BiasedLocking::revoke_at_safepoint(obj);
acorn@1798 151 }
acorn@1798 152 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 153 }
acorn@1798 154
acorn@1798 155 slow_enter (obj, lock, THREAD) ;
acorn@1798 156 }
acorn@1798 157
acorn@1798 158 void ObjectSynchronizer::fast_exit(oop object, BasicLock* lock, TRAPS) {
acorn@1798 159 assert(!object->mark()->has_bias_pattern(), "should not see bias pattern here");
acorn@1798 160 // if displaced header is null, the previous enter is recursive enter, no-op
acorn@1798 161 markOop dhw = lock->displaced_header();
acorn@1798 162 markOop mark ;
acorn@1798 163 if (dhw == NULL) {
acorn@1798 164 // Recursive stack-lock.
acorn@1798 165 // Diagnostics -- Could be: stack-locked, inflating, inflated.
acorn@1798 166 mark = object->mark() ;
acorn@1798 167 assert (!mark->is_neutral(), "invariant") ;
acorn@1798 168 if (mark->has_locker() && mark != markOopDesc::INFLATING()) {
acorn@1798 169 assert(THREAD->is_lock_owned((address)mark->locker()), "invariant") ;
acorn@1798 170 }
acorn@1798 171 if (mark->has_monitor()) {
acorn@1798 172 ObjectMonitor * m = mark->monitor() ;
acorn@1798 173 assert(((oop)(m->object()))->mark() == mark, "invariant") ;
acorn@1798 174 assert(m->is_entered(THREAD), "invariant") ;
acorn@1798 175 }
acorn@1798 176 return ;
duke@0 177 }
duke@0 178
acorn@1798 179 mark = object->mark() ;
acorn@1798 180
acorn@1798 181 // If the object is stack-locked by the current thread, try to
acorn@1798 182 // swing the displaced header from the box back to the mark.
acorn@1798 183 if (mark == (markOop) lock) {
acorn@1798 184 assert (dhw->is_neutral(), "invariant") ;
acorn@1798 185 if ((markOop) Atomic::cmpxchg_ptr (dhw, object->mark_addr(), mark) == mark) {
acorn@1798 186 TEVENT (fast_exit: release stacklock) ;
acorn@1798 187 return;
acorn@1798 188 }
duke@0 189 }
duke@0 190
acorn@1798 191 ObjectSynchronizer::inflate(THREAD, object)->exit (THREAD) ;
acorn@1798 192 }
acorn@1798 193
acorn@1798 194 // -----------------------------------------------------------------------------
acorn@1798 195 // Interpreter/Compiler Slow Case
acorn@1798 196 // This routine is used to handle interpreter/compiler slow case
acorn@1798 197 // We don't need to use fast path here, because it must have been
acorn@1798 198 // failed in the interpreter/compiler code.
acorn@1798 199 void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) {
acorn@1798 200 markOop mark = obj->mark();
acorn@1798 201 assert(!mark->has_bias_pattern(), "should not see bias pattern here");
acorn@1798 202
acorn@1798 203 if (mark->is_neutral()) {
acorn@1798 204 // Anticipate successful CAS -- the ST of the displaced mark must
acorn@1798 205 // be visible <= the ST performed by the CAS.
acorn@1798 206 lock->set_displaced_header(mark);
acorn@1798 207 if (mark == (markOop) Atomic::cmpxchg_ptr(lock, obj()->mark_addr(), mark)) {
acorn@1798 208 TEVENT (slow_enter: release stacklock) ;
acorn@1798 209 return ;
acorn@1798 210 }
acorn@1798 211 // Fall through to inflate() ...
acorn@1798 212 } else
acorn@1798 213 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
acorn@1798 214 assert(lock != mark->locker(), "must not re-lock the same lock");
acorn@1798 215 assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock");
acorn@1798 216 lock->set_displaced_header(NULL);
acorn@1798 217 return;
duke@0 218 }
duke@0 219
acorn@1798 220 #if 0
acorn@1798 221 // The following optimization isn't particularly useful.
acorn@1798 222 if (mark->has_monitor() && mark->monitor()->is_entered(THREAD)) {
acorn@1798 223 lock->set_displaced_header (NULL) ;
acorn@1798 224 return ;
acorn@1798 225 }
acorn@1798 226 #endif
duke@0 227
acorn@1798 228 // The object header will never be displaced to this lock,
acorn@1798 229 // so it does not matter what the value is, except that it
acorn@1798 230 // must be non-zero to avoid looking like a re-entrant lock,
acorn@1798 231 // and must not look locked either.
acorn@1798 232 lock->set_displaced_header(markOopDesc::unused_mark());
acorn@1798 233 ObjectSynchronizer::inflate(THREAD, obj())->enter(THREAD);
acorn@1798 234 }
duke@0 235
acorn@1798 236 // This routine is used to handle interpreter/compiler slow case
acorn@1798 237 // We don't need to use fast path here, because it must have
acorn@1798 238 // failed in the interpreter/compiler code. Simply use the heavy
acorn@1798 239 // weight monitor should be ok, unless someone find otherwise.
acorn@1798 240 void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) {
acorn@1798 241 fast_exit (object, lock, THREAD) ;
acorn@1798 242 }
duke@0 243
acorn@1798 244 // -----------------------------------------------------------------------------
acorn@1798 245 // Class Loader support to workaround deadlocks on the class loader lock objects
acorn@1798 246 // Also used by GC
acorn@1798 247 // complete_exit()/reenter() are used to wait on a nested lock
acorn@1798 248 // i.e. to give up an outer lock completely and then re-enter
acorn@1798 249 // Used when holding nested locks - lock acquisition order: lock1 then lock2
acorn@1798 250 // 1) complete_exit lock1 - saving recursion count
acorn@1798 251 // 2) wait on lock2
acorn@1798 252 // 3) when notified on lock2, unlock lock2
acorn@1798 253 // 4) reenter lock1 with original recursion count
acorn@1798 254 // 5) lock lock2
acorn@1798 255 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
acorn@1798 256 intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) {
acorn@1798 257 TEVENT (complete_exit) ;
acorn@1798 258 if (UseBiasedLocking) {
acorn@1798 259 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
acorn@1798 260 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 261 }
duke@0 262
acorn@1798 263 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj());
duke@0 264
acorn@1798 265 return monitor->complete_exit(THREAD);
acorn@1798 266 }
acorn@1798 267
acorn@1798 268 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
acorn@1798 269 void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) {
acorn@1798 270 TEVENT (reenter) ;
acorn@1798 271 if (UseBiasedLocking) {
acorn@1798 272 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
acorn@1798 273 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 274 }
acorn@1798 275
acorn@1798 276 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj());
acorn@1798 277
acorn@1798 278 monitor->reenter(recursion, THREAD);
acorn@1798 279 }
acorn@1798 280 // -----------------------------------------------------------------------------
acorn@1798 281 // JNI locks on java objects
acorn@1798 282 // NOTE: must use heavy weight monitor to handle jni monitor enter
acorn@1798 283 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) { // possible entry from jni enter
acorn@1798 284 // the current locking is from JNI instead of Java code
acorn@1798 285 TEVENT (jni_enter) ;
acorn@1798 286 if (UseBiasedLocking) {
acorn@1798 287 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
acorn@1798 288 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 289 }
acorn@1798 290 THREAD->set_current_pending_monitor_is_from_java(false);
acorn@1798 291 ObjectSynchronizer::inflate(THREAD, obj())->enter(THREAD);
acorn@1798 292 THREAD->set_current_pending_monitor_is_from_java(true);
acorn@1798 293 }
acorn@1798 294
acorn@1798 295 // NOTE: must use heavy weight monitor to handle jni monitor enter
acorn@1798 296 bool ObjectSynchronizer::jni_try_enter(Handle obj, Thread* THREAD) {
acorn@1798 297 if (UseBiasedLocking) {
acorn@1798 298 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
acorn@1798 299 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 300 }
acorn@1798 301
acorn@1798 302 ObjectMonitor* monitor = ObjectSynchronizer::inflate_helper(obj());
acorn@1798 303 return monitor->try_enter(THREAD);
acorn@1798 304 }
acorn@1798 305
acorn@1798 306
acorn@1798 307 // NOTE: must use heavy weight monitor to handle jni monitor exit
acorn@1798 308 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) {
acorn@1798 309 TEVENT (jni_exit) ;
acorn@1798 310 if (UseBiasedLocking) {
acorn@1798 311 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
acorn@1798 312 }
acorn@1798 313 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 314
acorn@1798 315 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj);
acorn@1798 316 // If this thread has locked the object, exit the monitor. Note: can't use
acorn@1798 317 // monitor->check(CHECK); must exit even if an exception is pending.
acorn@1798 318 if (monitor->check(THREAD)) {
acorn@1798 319 monitor->exit(THREAD);
acorn@1798 320 }
acorn@1798 321 }
acorn@1798 322
acorn@1798 323 // -----------------------------------------------------------------------------
acorn@1798 324 // Internal VM locks on java objects
acorn@1798 325 // standard constructor, allows locking failures
acorn@1798 326 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) {
acorn@1798 327 _dolock = doLock;
acorn@1798 328 _thread = thread;
acorn@1798 329 debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);)
acorn@1798 330 _obj = obj;
acorn@1798 331
acorn@1798 332 if (_dolock) {
acorn@1798 333 TEVENT (ObjectLocker) ;
acorn@1798 334
acorn@1798 335 ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread);
acorn@1798 336 }
acorn@1798 337 }
acorn@1798 338
acorn@1798 339 ObjectLocker::~ObjectLocker() {
acorn@1798 340 if (_dolock) {
acorn@1798 341 ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread);
acorn@1798 342 }
acorn@1798 343 }
acorn@1798 344
acorn@1798 345
acorn@1798 346 // -----------------------------------------------------------------------------
acorn@1798 347 // Wait/Notify/NotifyAll
acorn@1798 348 // NOTE: must use heavy weight monitor to handle wait()
acorn@1798 349 void ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
acorn@1798 350 if (UseBiasedLocking) {
acorn@1798 351 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
acorn@1798 352 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 353 }
acorn@1798 354 if (millis < 0) {
acorn@1798 355 TEVENT (wait - throw IAX) ;
acorn@1798 356 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
acorn@1798 357 }
acorn@1798 358 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj());
acorn@1798 359 DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis);
acorn@1798 360 monitor->wait(millis, true, THREAD);
acorn@1798 361
acorn@1798 362 /* This dummy call is in place to get around dtrace bug 6254741. Once
acorn@1798 363 that's fixed we can uncomment the following line and remove the call */
acorn@1798 364 // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
acorn@1798 365 dtrace_waited_probe(monitor, obj, THREAD);
acorn@1798 366 }
acorn@1798 367
acorn@1798 368 void ObjectSynchronizer::waitUninterruptibly (Handle obj, jlong millis, TRAPS) {
acorn@1798 369 if (UseBiasedLocking) {
acorn@1798 370 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
acorn@1798 371 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 372 }
acorn@1798 373 if (millis < 0) {
acorn@1798 374 TEVENT (wait - throw IAX) ;
acorn@1798 375 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
acorn@1798 376 }
acorn@1798 377 ObjectSynchronizer::inflate(THREAD, obj()) -> wait(millis, false, THREAD) ;
acorn@1798 378 }
acorn@1798 379
acorn@1798 380 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
acorn@1798 381 if (UseBiasedLocking) {
acorn@1798 382 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
acorn@1798 383 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 384 }
acorn@1798 385
acorn@1798 386 markOop mark = obj->mark();
acorn@1798 387 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
acorn@1798 388 return;
acorn@1798 389 }
acorn@1798 390 ObjectSynchronizer::inflate(THREAD, obj())->notify(THREAD);
acorn@1798 391 }
acorn@1798 392
acorn@1798 393 // NOTE: see comment of notify()
acorn@1798 394 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
acorn@1798 395 if (UseBiasedLocking) {
acorn@1798 396 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
acorn@1798 397 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 398 }
acorn@1798 399
acorn@1798 400 markOop mark = obj->mark();
acorn@1798 401 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
acorn@1798 402 return;
acorn@1798 403 }
acorn@1798 404 ObjectSynchronizer::inflate(THREAD, obj())->notifyAll(THREAD);
acorn@1798 405 }
acorn@1798 406
acorn@1798 407 // -----------------------------------------------------------------------------
acorn@1798 408 // Hash Code handling
acorn@1798 409 //
duke@0 410 // Performance concern:
duke@0 411 // OrderAccess::storestore() calls release() which STs 0 into the global volatile
duke@0 412 // OrderAccess::Dummy variable. This store is unnecessary for correctness.
duke@0 413 // Many threads STing into a common location causes considerable cache migration
duke@0 414 // or "sloshing" on large SMP system. As such, I avoid using OrderAccess::storestore()
duke@0 415 // until it's repaired. In some cases OrderAccess::fence() -- which incurs local
duke@0 416 // latency on the executing processor -- is a better choice as it scales on SMP
duke@0 417 // systems. See http://blogs.sun.com/dave/entry/biased_locking_in_hotspot for a
duke@0 418 // discussion of coherency costs. Note that all our current reference platforms
duke@0 419 // provide strong ST-ST order, so the issue is moot on IA32, x64, and SPARC.
duke@0 420 //
duke@0 421 // As a general policy we use "volatile" to control compiler-based reordering
duke@0 422 // and explicit fences (barriers) to control for architectural reordering performed
duke@0 423 // by the CPU(s) or platform.
duke@0 424
duke@0 425 static int MBFence (int x) { OrderAccess::fence(); return x; }
duke@0 426
duke@0 427 struct SharedGlobals {
duke@0 428 // These are highly shared mostly-read variables.
duke@0 429 // To avoid false-sharing they need to be the sole occupants of a $ line.
duke@0 430 double padPrefix [8];
duke@0 431 volatile int stwRandom ;
duke@0 432 volatile int stwCycle ;
duke@0 433
duke@0 434 // Hot RW variables -- Sequester to avoid false-sharing
duke@0 435 double padSuffix [16];
duke@0 436 volatile int hcSequence ;
duke@0 437 double padFinal [8] ;
duke@0 438 } ;
duke@0 439
duke@0 440 static SharedGlobals GVars ;
acorn@1507 441 static int MonitorScavengeThreshold = 1000000 ;
acorn@1507 442 static volatile int ForceMonitorScavenge = 0 ; // Scavenge required and pending
duke@0 443
acorn@1798 444 static markOop ReadStableMark (oop obj) {
acorn@1798 445 markOop mark = obj->mark() ;
acorn@1798 446 if (!mark->is_being_inflated()) {
acorn@1798 447 return mark ; // normal fast-path return
acorn@1798 448 }
duke@0 449
acorn@1798 450 int its = 0 ;
acorn@1798 451 for (;;) {
acorn@1798 452 markOop mark = obj->mark() ;
acorn@1798 453 if (!mark->is_being_inflated()) {
acorn@1798 454 return mark ; // normal fast-path return
acorn@1798 455 }
duke@0 456
acorn@1798 457 // The object is being inflated by some other thread.
acorn@1798 458 // The caller of ReadStableMark() must wait for inflation to complete.
acorn@1798 459 // Avoid live-lock
acorn@1798 460 // TODO: consider calling SafepointSynchronize::do_call_back() while
acorn@1798 461 // spinning to see if there's a safepoint pending. If so, immediately
acorn@1798 462 // yielding or blocking would be appropriate. Avoid spinning while
acorn@1798 463 // there is a safepoint pending.
acorn@1798 464 // TODO: add inflation contention performance counters.
acorn@1798 465 // TODO: restrict the aggregate number of spinners.
duke@0 466
acorn@1798 467 ++its ;
acorn@1798 468 if (its > 10000 || !os::is_MP()) {
acorn@1798 469 if (its & 1) {
acorn@1798 470 os::NakedYield() ;
acorn@1798 471 TEVENT (Inflate: INFLATING - yield) ;
acorn@1798 472 } else {
acorn@1798 473 // Note that the following code attenuates the livelock problem but is not
acorn@1798 474 // a complete remedy. A more complete solution would require that the inflating
acorn@1798 475 // thread hold the associated inflation lock. The following code simply restricts
acorn@1798 476 // the number of spinners to at most one. We'll have N-2 threads blocked
acorn@1798 477 // on the inflationlock, 1 thread holding the inflation lock and using
acorn@1798 478 // a yield/park strategy, and 1 thread in the midst of inflation.
acorn@1798 479 // A more refined approach would be to change the encoding of INFLATING
acorn@1798 480 // to allow encapsulation of a native thread pointer. Threads waiting for
acorn@1798 481 // inflation to complete would use CAS to push themselves onto a singly linked
acorn@1798 482 // list rooted at the markword. Once enqueued, they'd loop, checking a per-thread flag
acorn@1798 483 // and calling park(). When inflation was complete the thread that accomplished inflation
acorn@1798 484 // would detach the list and set the markword to inflated with a single CAS and
acorn@1798 485 // then for each thread on the list, set the flag and unpark() the thread.
acorn@1798 486 // This is conceptually similar to muxAcquire-muxRelease, except that muxRelease
acorn@1798 487 // wakes at most one thread whereas we need to wake the entire list.
acorn@1798 488 int ix = (intptr_t(obj) >> 5) & (NINFLATIONLOCKS-1) ;
acorn@1798 489 int YieldThenBlock = 0 ;
acorn@1798 490 assert (ix >= 0 && ix < NINFLATIONLOCKS, "invariant") ;
acorn@1798 491 assert ((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant") ;
acorn@1798 492 Thread::muxAcquire (InflationLocks + ix, "InflationLock") ;
acorn@1798 493 while (obj->mark() == markOopDesc::INFLATING()) {
acorn@1798 494 // Beware: NakedYield() is advisory and has almost no effect on some platforms
acorn@1798 495 // so we periodically call Self->_ParkEvent->park(1).
acorn@1798 496 // We use a mixed spin/yield/block mechanism.
acorn@1798 497 if ((YieldThenBlock++) >= 16) {
acorn@1798 498 Thread::current()->_ParkEvent->park(1) ;
acorn@1798 499 } else {
acorn@1798 500 os::NakedYield() ;
acorn@1798 501 }
acorn@1798 502 }
acorn@1798 503 Thread::muxRelease (InflationLocks + ix ) ;
acorn@1798 504 TEVENT (Inflate: INFLATING - yield/park) ;
acorn@1798 505 }
acorn@1798 506 } else {
acorn@1798 507 SpinPause() ; // SMP-polite spinning
acorn@1798 508 }
acorn@1798 509 }
acorn@1798 510 }
duke@0 511
duke@0 512 // hashCode() generation :
duke@0 513 //
duke@0 514 // Possibilities:
duke@0 515 // * MD5Digest of {obj,stwRandom}
duke@0 516 // * CRC32 of {obj,stwRandom} or any linear-feedback shift register function.
duke@0 517 // * A DES- or AES-style SBox[] mechanism
duke@0 518 // * One of the Phi-based schemes, such as:
duke@0 519 // 2654435761 = 2^32 * Phi (golden ratio)
duke@0 520 // HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ;
duke@0 521 // * A variation of Marsaglia's shift-xor RNG scheme.
duke@0 522 // * (obj ^ stwRandom) is appealing, but can result
duke@0 523 // in undesirable regularity in the hashCode values of adjacent objects
duke@0 524 // (objects allocated back-to-back, in particular). This could potentially
duke@0 525 // result in hashtable collisions and reduced hashtable efficiency.
duke@0 526 // There are simple ways to "diffuse" the middle address bits over the
duke@0 527 // generated hashCode values:
duke@0 528 //
duke@0 529
duke@0 530 static inline intptr_t get_next_hash(Thread * Self, oop obj) {
duke@0 531 intptr_t value = 0 ;
duke@0 532 if (hashCode == 0) {
duke@0 533 // This form uses an unguarded global Park-Miller RNG,
duke@0 534 // so it's possible for two threads to race and generate the same RNG.
duke@0 535 // On MP system we'll have lots of RW access to a global, so the
duke@0 536 // mechanism induces lots of coherency traffic.
duke@0 537 value = os::random() ;
duke@0 538 } else
duke@0 539 if (hashCode == 1) {
duke@0 540 // This variation has the property of being stable (idempotent)
duke@0 541 // between STW operations. This can be useful in some of the 1-0
duke@0 542 // synchronization schemes.
duke@0 543 intptr_t addrBits = intptr_t(obj) >> 3 ;
duke@0 544 value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;
duke@0 545 } else
duke@0 546 if (hashCode == 2) {
duke@0 547 value = 1 ; // for sensitivity testing
duke@0 548 } else
duke@0 549 if (hashCode == 3) {
duke@0 550 value = ++GVars.hcSequence ;
duke@0 551 } else
duke@0 552 if (hashCode == 4) {
duke@0 553 value = intptr_t(obj) ;
duke@0 554 } else {
duke@0 555 // Marsaglia's xor-shift scheme with thread-specific state
duke@0 556 // This is probably the best overall implementation -- we'll
duke@0 557 // likely make this the default in future releases.
duke@0 558 unsigned t = Self->_hashStateX ;
duke@0 559 t ^= (t << 11) ;
duke@0 560 Self->_hashStateX = Self->_hashStateY ;
duke@0 561 Self->_hashStateY = Self->_hashStateZ ;
duke@0 562 Self->_hashStateZ = Self->_hashStateW ;
duke@0 563 unsigned v = Self->_hashStateW ;
duke@0 564 v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ;
duke@0 565 Self->_hashStateW = v ;
duke@0 566 value = v ;
duke@0 567 }
duke@0 568
duke@0 569 value &= markOopDesc::hash_mask;
duke@0 570 if (value == 0) value = 0xBAD ;
duke@0 571 assert (value != markOopDesc::no_hash, "invariant") ;
duke@0 572 TEVENT (hashCode: GENERATE) ;
duke@0 573 return value;
duke@0 574 }
acorn@1798 575 //
acorn@1798 576 intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) {
acorn@1798 577 if (UseBiasedLocking) {
acorn@1798 578 // NOTE: many places throughout the JVM do not expect a safepoint
acorn@1798 579 // to be taken here, in particular most operations on perm gen
acorn@1798 580 // objects. However, we only ever bias Java instances and all of
acorn@1798 581 // the call sites of identity_hash that might revoke biases have
acorn@1798 582 // been checked to make sure they can handle a safepoint. The
acorn@1798 583 // added check of the bias pattern is to avoid useless calls to
acorn@1798 584 // thread-local storage.
acorn@1798 585 if (obj->mark()->has_bias_pattern()) {
acorn@1798 586 // Box and unbox the raw reference just in case we cause a STW safepoint.
acorn@1798 587 Handle hobj (Self, obj) ;
acorn@1798 588 // Relaxing assertion for bug 6320749.
acorn@1798 589 assert (Universe::verify_in_progress() ||
acorn@1798 590 !SafepointSynchronize::is_at_safepoint(),
acorn@1798 591 "biases should not be seen by VM thread here");
acorn@1798 592 BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
acorn@1798 593 obj = hobj() ;
acorn@1798 594 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 595 }
acorn@1798 596 }
duke@0 597
acorn@1798 598 // hashCode() is a heap mutator ...
acorn@1798 599 // Relaxing assertion for bug 6320749.
acorn@1798 600 assert (Universe::verify_in_progress() ||
acorn@1798 601 !SafepointSynchronize::is_at_safepoint(), "invariant") ;
acorn@1798 602 assert (Universe::verify_in_progress() ||
acorn@1798 603 Self->is_Java_thread() , "invariant") ;
acorn@1798 604 assert (Universe::verify_in_progress() ||
acorn@1798 605 ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ;
acorn@1798 606
acorn@1798 607 ObjectMonitor* monitor = NULL;
acorn@1798 608 markOop temp, test;
acorn@1798 609 intptr_t hash;
acorn@1798 610 markOop mark = ReadStableMark (obj);
acorn@1798 611
acorn@1798 612 // object should remain ineligible for biased locking
acorn@1798 613 assert (!mark->has_bias_pattern(), "invariant") ;
acorn@1798 614
acorn@1798 615 if (mark->is_neutral()) {
acorn@1798 616 hash = mark->hash(); // this is a normal header
acorn@1798 617 if (hash) { // if it has hash, just return it
acorn@1798 618 return hash;
acorn@1798 619 }
acorn@1798 620 hash = get_next_hash(Self, obj); // allocate a new hash code
acorn@1798 621 temp = mark->copy_set_hash(hash); // merge the hash code into header
acorn@1798 622 // use (machine word version) atomic operation to install the hash
acorn@1798 623 test = (markOop) Atomic::cmpxchg_ptr(temp, obj->mark_addr(), mark);
acorn@1798 624 if (test == mark) {
acorn@1798 625 return hash;
acorn@1798 626 }
acorn@1798 627 // If atomic operation failed, we must inflate the header
acorn@1798 628 // into heavy weight monitor. We could add more code here
acorn@1798 629 // for fast path, but it does not worth the complexity.
acorn@1798 630 } else if (mark->has_monitor()) {
acorn@1798 631 monitor = mark->monitor();
acorn@1798 632 temp = monitor->header();
acorn@1798 633 assert (temp->is_neutral(), "invariant") ;
acorn@1798 634 hash = temp->hash();
acorn@1798 635 if (hash) {
acorn@1798 636 return hash;
acorn@1798 637 }
acorn@1798 638 // Skip to the following code to reduce code size
acorn@1798 639 } else if (Self->is_lock_owned((address)mark->locker())) {
acorn@1798 640 temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
acorn@1798 641 assert (temp->is_neutral(), "invariant") ;
acorn@1798 642 hash = temp->hash(); // by current thread, check if the displaced
acorn@1798 643 if (hash) { // header contains hash code
acorn@1798 644 return hash;
acorn@1798 645 }
acorn@1798 646 // WARNING:
acorn@1798 647 // The displaced header is strictly immutable.
acorn@1798 648 // It can NOT be changed in ANY cases. So we have
acorn@1798 649 // to inflate the header into heavyweight monitor
acorn@1798 650 // even the current thread owns the lock. The reason
acorn@1798 651 // is the BasicLock (stack slot) will be asynchronously
acorn@1798 652 // read by other threads during the inflate() function.
acorn@1798 653 // Any change to stack may not propagate to other threads
acorn@1798 654 // correctly.
acorn@1798 655 }
acorn@1798 656
acorn@1798 657 // Inflate the monitor to set hash code
acorn@1798 658 monitor = ObjectSynchronizer::inflate(Self, obj);
acorn@1798 659 // Load displaced header and check it has hash code
acorn@1798 660 mark = monitor->header();
acorn@1798 661 assert (mark->is_neutral(), "invariant") ;
acorn@1798 662 hash = mark->hash();
acorn@1798 663 if (hash == 0) {
acorn@1798 664 hash = get_next_hash(Self, obj);
acorn@1798 665 temp = mark->copy_set_hash(hash); // merge hash code into header
acorn@1798 666 assert (temp->is_neutral(), "invariant") ;
acorn@1798 667 test = (markOop) Atomic::cmpxchg_ptr(temp, monitor, mark);
acorn@1798 668 if (test != mark) {
acorn@1798 669 // The only update to the header in the monitor (outside GC)
acorn@1798 670 // is install the hash code. If someone add new usage of
acorn@1798 671 // displaced header, please update this code
acorn@1798 672 hash = test->hash();
acorn@1798 673 assert (test->is_neutral(), "invariant") ;
acorn@1798 674 assert (hash != 0, "Trivial unexpected object/monitor header usage.");
acorn@1798 675 }
acorn@1798 676 }
acorn@1798 677 // We finally get the hash
acorn@1798 678 return hash;
duke@0 679 }
duke@0 680
acorn@1798 681 // Deprecated -- use FastHashCode() instead.
duke@0 682
acorn@1798 683 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) {
acorn@1798 684 return FastHashCode (Thread::current(), obj()) ;
duke@0 685 }
duke@0 686
duke@0 687
acorn@1798 688 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread,
acorn@1798 689 Handle h_obj) {
acorn@1798 690 if (UseBiasedLocking) {
acorn@1798 691 BiasedLocking::revoke_and_rebias(h_obj, false, thread);
acorn@1798 692 assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 693 }
duke@0 694
acorn@1798 695 assert(thread == JavaThread::current(), "Can only be called on current thread");
acorn@1798 696 oop obj = h_obj();
duke@0 697
acorn@1798 698 markOop mark = ReadStableMark (obj) ;
acorn@1798 699
acorn@1798 700 // Uncontended case, header points to stack
acorn@1798 701 if (mark->has_locker()) {
acorn@1798 702 return thread->is_lock_owned((address)mark->locker());
acorn@1798 703 }
acorn@1798 704 // Contended case, header points to ObjectMonitor (tagged pointer)
acorn@1798 705 if (mark->has_monitor()) {
acorn@1798 706 ObjectMonitor* monitor = mark->monitor();
acorn@1798 707 return monitor->is_entered(thread) != 0 ;
acorn@1798 708 }
acorn@1798 709 // Unlocked case, header in place
acorn@1798 710 assert(mark->is_neutral(), "sanity check");
acorn@1798 711 return false;
acorn@1798 712 }
acorn@1798 713
acorn@1798 714 // Be aware of this method could revoke bias of the lock object.
acorn@1798 715 // This method querys the ownership of the lock handle specified by 'h_obj'.
acorn@1798 716 // If the current thread owns the lock, it returns owner_self. If no
acorn@1798 717 // thread owns the lock, it returns owner_none. Otherwise, it will return
acorn@1798 718 // ower_other.
acorn@1798 719 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership
acorn@1798 720 (JavaThread *self, Handle h_obj) {
acorn@1798 721 // The caller must beware this method can revoke bias, and
acorn@1798 722 // revocation can result in a safepoint.
acorn@1798 723 assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ;
acorn@1798 724 assert (self->thread_state() != _thread_blocked , "invariant") ;
acorn@1798 725
acorn@1798 726 // Possible mark states: neutral, biased, stack-locked, inflated
acorn@1798 727
acorn@1798 728 if (UseBiasedLocking && h_obj()->mark()->has_bias_pattern()) {
acorn@1798 729 // CASE: biased
acorn@1798 730 BiasedLocking::revoke_and_rebias(h_obj, false, self);
acorn@1798 731 assert(!h_obj->mark()->has_bias_pattern(),
acorn@1798 732 "biases should be revoked by now");
acorn@1798 733 }
acorn@1798 734
acorn@1798 735 assert(self == JavaThread::current(), "Can only be called on current thread");
acorn@1798 736 oop obj = h_obj();
acorn@1798 737 markOop mark = ReadStableMark (obj) ;
acorn@1798 738
acorn@1798 739 // CASE: stack-locked. Mark points to a BasicLock on the owner's stack.
acorn@1798 740 if (mark->has_locker()) {
acorn@1798 741 return self->is_lock_owned((address)mark->locker()) ?
acorn@1798 742 owner_self : owner_other;
acorn@1798 743 }
acorn@1798 744
acorn@1798 745 // CASE: inflated. Mark (tagged pointer) points to an objectMonitor.
acorn@1798 746 // The Object:ObjectMonitor relationship is stable as long as we're
acorn@1798 747 // not at a safepoint.
acorn@1798 748 if (mark->has_monitor()) {
acorn@1798 749 void * owner = mark->monitor()->_owner ;
acorn@1798 750 if (owner == NULL) return owner_none ;
acorn@1798 751 return (owner == self ||
acorn@1798 752 self->is_lock_owned((address)owner)) ? owner_self : owner_other;
acorn@1798 753 }
acorn@1798 754
acorn@1798 755 // CASE: neutral
acorn@1798 756 assert(mark->is_neutral(), "sanity check");
acorn@1798 757 return owner_none ; // it's unlocked
acorn@1798 758 }
acorn@1798 759
acorn@1798 760 // FIXME: jvmti should call this
acorn@1798 761 JavaThread* ObjectSynchronizer::get_lock_owner(Handle h_obj, bool doLock) {
acorn@1798 762 if (UseBiasedLocking) {
acorn@1798 763 if (SafepointSynchronize::is_at_safepoint()) {
acorn@1798 764 BiasedLocking::revoke_at_safepoint(h_obj);
acorn@1798 765 } else {
acorn@1798 766 BiasedLocking::revoke_and_rebias(h_obj, false, JavaThread::current());
acorn@1798 767 }
acorn@1798 768 assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
acorn@1798 769 }
acorn@1798 770
acorn@1798 771 oop obj = h_obj();
acorn@1798 772 address owner = NULL;
acorn@1798 773
acorn@1798 774 markOop mark = ReadStableMark (obj) ;
acorn@1798 775
acorn@1798 776 // Uncontended case, header points to stack
acorn@1798 777 if (mark->has_locker()) {
acorn@1798 778 owner = (address) mark->locker();
acorn@1798 779 }
acorn@1798 780
acorn@1798 781 // Contended case, header points to ObjectMonitor (tagged pointer)
acorn@1798 782 if (mark->has_monitor()) {
acorn@1798 783 ObjectMonitor* monitor = mark->monitor();
acorn@1798 784 assert(monitor != NULL, "monitor should be non-null");
acorn@1798 785 owner = (address) monitor->owner();
acorn@1798 786 }
acorn@1798 787
acorn@1798 788 if (owner != NULL) {
acorn@1798 789 return Threads::owning_thread_from_monitor_owner(owner, doLock);
acorn@1798 790 }
acorn@1798 791
acorn@1798 792 // Unlocked case, header in place
acorn@1798 793 // Cannot have assertion since this object may have been
acorn@1798 794 // locked by another thread when reaching here.
acorn@1798 795 // assert(mark->is_neutral(), "sanity check");
acorn@1798 796
acorn@1798 797 return NULL;
acorn@1798 798 }
acorn@1798 799 // Visitors ...
acorn@1798 800
acorn@1798 801 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) {
acorn@1798 802 ObjectMonitor* block = gBlockList;
acorn@1798 803 ObjectMonitor* mid;
acorn@1798 804 while (block) {
acorn@1798 805 assert(block->object() == CHAINMARKER, "must be a block header");
acorn@1798 806 for (int i = _BLOCKSIZE - 1; i > 0; i--) {
acorn@1798 807 mid = block + i;
acorn@1798 808 oop object = (oop) mid->object();
acorn@1798 809 if (object != NULL) {
acorn@1798 810 closure->do_monitor(mid);
acorn@1798 811 }
acorn@1798 812 }
acorn@1798 813 block = (ObjectMonitor*) block->FreeNext;
duke@0 814 }
duke@0 815 }
duke@0 816
acorn@1798 817 // Get the next block in the block list.
acorn@1798 818 static inline ObjectMonitor* next(ObjectMonitor* block) {
acorn@1798 819 assert(block->object() == CHAINMARKER, "must be a block header");
acorn@1798 820 block = block->FreeNext ;
acorn@1798 821 assert(block == NULL || block->object() == CHAINMARKER, "must be a block header");
acorn@1798 822 return block;
duke@0 823 }
duke@0 824
duke@0 825
acorn@1798 826 void ObjectSynchronizer::oops_do(OopClosure* f) {
acorn@1798 827 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
acorn@1798 828 for (ObjectMonitor* block = gBlockList; block != NULL; block = next(block)) {
acorn@1798 829 assert(block->object() == CHAINMARKER, "must be a block header");
acorn@1798 830 for (int i = 1; i < _BLOCKSIZE; i++) {
acorn@1798 831 ObjectMonitor* mid = &block[i];
acorn@1798 832 if (mid->object() != NULL) {
acorn@1798 833 f->do_oop((oop*)mid->object_addr());
duke@0 834 }
duke@0 835 }
duke@0 836 }
duke@0 837 }
duke@0 838
duke@0 839
acorn@1798 840 // -----------------------------------------------------------------------------
duke@0 841 // ObjectMonitor Lifecycle
duke@0 842 // -----------------------
duke@0 843 // Inflation unlinks monitors from the global gFreeList and
duke@0 844 // associates them with objects. Deflation -- which occurs at
duke@0 845 // STW-time -- disassociates idle monitors from objects. Such
duke@0 846 // scavenged monitors are returned to the gFreeList.
duke@0 847 //
duke@0 848 // The global list is protected by ListLock. All the critical sections
duke@0 849 // are short and operate in constant-time.
duke@0 850 //
duke@0 851 // ObjectMonitors reside in type-stable memory (TSM) and are immortal.
duke@0 852 //
duke@0 853 // Lifecycle:
duke@0 854 // -- unassigned and on the global free list
duke@0 855 // -- unassigned and on a thread's private omFreeList
duke@0 856 // -- assigned to an object. The object is inflated and the mark refers
duke@0 857 // to the objectmonitor.
duke@0 858 //
duke@0 859
duke@0 860
acorn@1507 861 // Constraining monitor pool growth via MonitorBound ...
acorn@1507 862 //
acorn@1507 863 // The monitor pool is grow-only. We scavenge at STW safepoint-time, but the
acorn@1507 864 // the rate of scavenging is driven primarily by GC. As such, we can find
acorn@1507 865 // an inordinate number of monitors in circulation.
acorn@1507 866 // To avoid that scenario we can artificially induce a STW safepoint
acorn@1507 867 // if the pool appears to be growing past some reasonable bound.
acorn@1507 868 // Generally we favor time in space-time tradeoffs, but as there's no
acorn@1507 869 // natural back-pressure on the # of extant monitors we need to impose some
acorn@1507 870 // type of limit. Beware that if MonitorBound is set to too low a value
acorn@1507 871 // we could just loop. In addition, if MonitorBound is set to a low value
acorn@1507 872 // we'll incur more safepoints, which are harmful to performance.
acorn@1507 873 // See also: GuaranteedSafepointInterval
acorn@1507 874 //
acorn@1507 875 // The current implementation uses asynchronous VM operations.
acorn@1507 876 //
acorn@1507 877
acorn@1507 878 static void InduceScavenge (Thread * Self, const char * Whence) {
acorn@1507 879 // Induce STW safepoint to trim monitors
acorn@1507 880 // Ultimately, this results in a call to deflate_idle_monitors() in the near future.
acorn@1507 881 // More precisely, trigger an asynchronous STW safepoint as the number
acorn@1507 882 // of active monitors passes the specified threshold.
acorn@1507 883 // TODO: assert thread state is reasonable
acorn@1507 884
acorn@1507 885 if (ForceMonitorScavenge == 0 && Atomic::xchg (1, &ForceMonitorScavenge) == 0) {
acorn@1798 886 if (ObjectMonitor::Knob_Verbose) {
acorn@1507 887 ::printf ("Monitor scavenge - Induced STW @%s (%d)\n", Whence, ForceMonitorScavenge) ;
acorn@1507 888 ::fflush(stdout) ;
acorn@1507 889 }
acorn@1507 890 // Induce a 'null' safepoint to scavenge monitors
acorn@1507 891 // Must VM_Operation instance be heap allocated as the op will be enqueue and posted
acorn@1507 892 // to the VMthread and have a lifespan longer than that of this activation record.
acorn@1507 893 // The VMThread will delete the op when completed.
acorn@1507 894 VMThread::execute (new VM_ForceAsyncSafepoint()) ;
acorn@1507 895
acorn@1798 896 if (ObjectMonitor::Knob_Verbose) {
acorn@1507 897 ::printf ("Monitor scavenge - STW posted @%s (%d)\n", Whence, ForceMonitorScavenge) ;
acorn@1507 898 ::fflush(stdout) ;
acorn@1507 899 }
acorn@1507 900 }
acorn@1507 901 }
acorn@1560 902 /* Too slow for general assert or debug
acorn@1560 903 void ObjectSynchronizer::verifyInUse (Thread *Self) {
acorn@1560 904 ObjectMonitor* mid;
acorn@1560 905 int inusetally = 0;
acorn@1560 906 for (mid = Self->omInUseList; mid != NULL; mid = mid->FreeNext) {
acorn@1560 907 inusetally ++;
acorn@1560 908 }
acorn@1560 909 assert(inusetally == Self->omInUseCount, "inuse count off");
acorn@1560 910
acorn@1560 911 int freetally = 0;
acorn@1560 912 for (mid = Self->omFreeList; mid != NULL; mid = mid->FreeNext) {
acorn@1560 913 freetally ++;
acorn@1560 914 }
acorn@1560 915 assert(freetally == Self->omFreeCount, "free count off");
acorn@1560 916 }
acorn@1560 917 */
duke@0 918 ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) {
duke@0 919 // A large MAXPRIVATE value reduces both list lock contention
duke@0 920 // and list coherency traffic, but also tends to increase the
duke@0 921 // number of objectMonitors in circulation as well as the STW
duke@0 922 // scavenge costs. As usual, we lean toward time in space-time
duke@0 923 // tradeoffs.
duke@0 924 const int MAXPRIVATE = 1024 ;
duke@0 925 for (;;) {
duke@0 926 ObjectMonitor * m ;
duke@0 927
duke@0 928 // 1: try to allocate from the thread's local omFreeList.
duke@0 929 // Threads will attempt to allocate first from their local list, then
duke@0 930 // from the global list, and only after those attempts fail will the thread
duke@0 931 // attempt to instantiate new monitors. Thread-local free lists take
duke@0 932 // heat off the ListLock and improve allocation latency, as well as reducing
duke@0 933 // coherency traffic on the shared global list.
duke@0 934 m = Self->omFreeList ;
duke@0 935 if (m != NULL) {
duke@0 936 Self->omFreeList = m->FreeNext ;
duke@0 937 Self->omFreeCount -- ;
duke@0 938 // CONSIDER: set m->FreeNext = BAD -- diagnostic hygiene
duke@0 939 guarantee (m->object() == NULL, "invariant") ;
acorn@1507 940 if (MonitorInUseLists) {
acorn@1507 941 m->FreeNext = Self->omInUseList;
acorn@1507 942 Self->omInUseList = m;
acorn@1507 943 Self->omInUseCount ++;
acorn@1560 944 // verifyInUse(Self);
acorn@1560 945 } else {
acorn@1560 946 m->FreeNext = NULL;
acorn@1507 947 }
duke@0 948 return m ;
duke@0 949 }
duke@0 950
duke@0 951 // 2: try to allocate from the global gFreeList
duke@0 952 // CONSIDER: use muxTry() instead of muxAcquire().
duke@0 953 // If the muxTry() fails then drop immediately into case 3.
duke@0 954 // If we're using thread-local free lists then try
duke@0 955 // to reprovision the caller's free list.
duke@0 956 if (gFreeList != NULL) {
duke@0 957 // Reprovision the thread's omFreeList.
duke@0 958 // Use bulk transfers to reduce the allocation rate and heat
duke@0 959 // on various locks.
duke@0 960 Thread::muxAcquire (&ListLock, "omAlloc") ;
duke@0 961 for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL; ) {
acorn@1507 962 MonitorFreeCount --;
duke@0 963 ObjectMonitor * take = gFreeList ;
duke@0 964 gFreeList = take->FreeNext ;
duke@0 965 guarantee (take->object() == NULL, "invariant") ;
duke@0 966 guarantee (!take->is_busy(), "invariant") ;
duke@0 967 take->Recycle() ;
acorn@1560 968 omRelease (Self, take, false) ;
duke@0 969 }
duke@0 970 Thread::muxRelease (&ListLock) ;
duke@0 971 Self->omFreeProvision += 1 + (Self->omFreeProvision/2) ;
duke@0 972 if (Self->omFreeProvision > MAXPRIVATE ) Self->omFreeProvision = MAXPRIVATE ;
duke@0 973 TEVENT (omFirst - reprovision) ;
acorn@1507 974
acorn@1507 975 const int mx = MonitorBound ;
acorn@1507 976 if (mx > 0 && (MonitorPopulation-MonitorFreeCount) > mx) {
acorn@1507 977 // We can't safely induce a STW safepoint from omAlloc() as our thread
acorn@1507 978 // state may not be appropriate for such activities and callers may hold
acorn@1507 979 // naked oops, so instead we defer the action.
acorn@1507 980 InduceScavenge (Self, "omAlloc") ;
acorn@1507 981 }
acorn@1507 982 continue;
duke@0 983 }
duke@0 984
duke@0 985 // 3: allocate a block of new ObjectMonitors
duke@0 986 // Both the local and global free lists are empty -- resort to malloc().
duke@0 987 // In the current implementation objectMonitors are TSM - immortal.
duke@0 988 assert (_BLOCKSIZE > 1, "invariant") ;
duke@0 989 ObjectMonitor * temp = new ObjectMonitor[_BLOCKSIZE];
duke@0 990
duke@0 991 // NOTE: (almost) no way to recover if allocation failed.
duke@0 992 // We might be able to induce a STW safepoint and scavenge enough
duke@0 993 // objectMonitors to permit progress.
duke@0 994 if (temp == NULL) {
duke@0 995 vm_exit_out_of_memory (sizeof (ObjectMonitor[_BLOCKSIZE]), "Allocate ObjectMonitors") ;
duke@0 996 }
duke@0 997
duke@0 998 // Format the block.
duke@0 999 // initialize the linked list, each monitor points to its next
duke@0 1000 // forming the single linked free list, the very first monitor
duke@0 1001 // will points to next block, which forms the block list.
duke@0 1002 // The trick of using the 1st element in the block as gBlockList
duke@0 1003 // linkage should be reconsidered. A better implementation would
duke@0 1004 // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; }
duke@0 1005
duke@0 1006 for (int i = 1; i < _BLOCKSIZE ; i++) {
duke@0 1007 temp[i].FreeNext = &temp[i+1];
duke@0 1008 }
duke@0 1009
duke@0 1010 // terminate the last monitor as the end of list
duke@0 1011 temp[_BLOCKSIZE - 1].FreeNext = NULL ;
duke@0 1012
duke@0 1013 // Element [0] is reserved for global list linkage
duke@0 1014 temp[0].set_object(CHAINMARKER);
duke@0 1015
duke@0 1016 // Consider carving out this thread's current request from the
duke@0 1017 // block in hand. This avoids some lock traffic and redundant
duke@0 1018 // list activity.
duke@0 1019
duke@0 1020 // Acquire the ListLock to manipulate BlockList and FreeList.
duke@0 1021 // An Oyama-Taura-Yonezawa scheme might be more efficient.
duke@0 1022 Thread::muxAcquire (&ListLock, "omAlloc [2]") ;
acorn@1507 1023 MonitorPopulation += _BLOCKSIZE-1;
acorn@1507 1024 MonitorFreeCount += _BLOCKSIZE-1;
duke@0 1025
duke@0 1026 // Add the new block to the list of extant blocks (gBlockList).
duke@0 1027 // The very first objectMonitor in a block is reserved and dedicated.
duke@0 1028 // It serves as blocklist "next" linkage.
duke@0 1029 temp[0].FreeNext = gBlockList;
duke@0 1030 gBlockList = temp;
duke@0 1031
duke@0 1032 // Add the new string of objectMonitors to the global free list
duke@0 1033 temp[_BLOCKSIZE - 1].FreeNext = gFreeList ;
duke@0 1034 gFreeList = temp + 1;
duke@0 1035 Thread::muxRelease (&ListLock) ;
duke@0 1036 TEVENT (Allocate block of monitors) ;
duke@0 1037 }
duke@0 1038 }
duke@0 1039
duke@0 1040 // Place "m" on the caller's private per-thread omFreeList.
duke@0 1041 // In practice there's no need to clamp or limit the number of
duke@0 1042 // monitors on a thread's omFreeList as the only time we'll call
duke@0 1043 // omRelease is to return a monitor to the free list after a CAS
duke@0 1044 // attempt failed. This doesn't allow unbounded #s of monitors to
duke@0 1045 // accumulate on a thread's free list.
duke@0 1046 //
duke@0 1047
acorn@1560 1048 void ObjectSynchronizer::omRelease (Thread * Self, ObjectMonitor * m, bool fromPerThreadAlloc) {
duke@0 1049 guarantee (m->object() == NULL, "invariant") ;
acorn@1560 1050
acorn@1560 1051 // Remove from omInUseList
acorn@1560 1052 if (MonitorInUseLists && fromPerThreadAlloc) {
acorn@1560 1053 ObjectMonitor* curmidinuse = NULL;
acorn@1560 1054 for (ObjectMonitor* mid = Self->omInUseList; mid != NULL; ) {
acorn@1560 1055 if (m == mid) {
acorn@1560 1056 // extract from per-thread in-use-list
acorn@1560 1057 if (mid == Self->omInUseList) {
acorn@1560 1058 Self->omInUseList = mid->FreeNext;
acorn@1560 1059 } else if (curmidinuse != NULL) {
acorn@1560 1060 curmidinuse->FreeNext = mid->FreeNext; // maintain the current thread inuselist
acorn@1560 1061 }
acorn@1560 1062 Self->omInUseCount --;
acorn@1560 1063 // verifyInUse(Self);
acorn@1560 1064 break;
acorn@1560 1065 } else {
acorn@1560 1066 curmidinuse = mid;
acorn@1560 1067 mid = mid->FreeNext;
acorn@1560 1068 }
acorn@1560 1069 }
acorn@1560 1070 }
acorn@1560 1071
acorn@1560 1072 // FreeNext is used for both onInUseList and omFreeList, so clear old before setting new
acorn@1560 1073 m->FreeNext = Self->omFreeList ;
acorn@1560 1074 Self->omFreeList = m ;
acorn@1560 1075 Self->omFreeCount ++ ;
duke@0 1076 }
duke@0 1077
duke@0 1078 // Return the monitors of a moribund thread's local free list to
duke@0 1079 // the global free list. Typically a thread calls omFlush() when
duke@0 1080 // it's dying. We could also consider having the VM thread steal
duke@0 1081 // monitors from threads that have not run java code over a few
duke@0 1082 // consecutive STW safepoints. Relatedly, we might decay
duke@0 1083 // omFreeProvision at STW safepoints.
duke@0 1084 //
acorn@1560 1085 // Also return the monitors of a moribund thread"s omInUseList to
acorn@1560 1086 // a global gOmInUseList under the global list lock so these
acorn@1560 1087 // will continue to be scanned.
acorn@1560 1088 //
duke@0 1089 // We currently call omFlush() from the Thread:: dtor _after the thread
duke@0 1090 // has been excised from the thread list and is no longer a mutator.
duke@0 1091 // That means that omFlush() can run concurrently with a safepoint and
duke@0 1092 // the scavenge operator. Calling omFlush() from JavaThread::exit() might
duke@0 1093 // be a better choice as we could safely reason that that the JVM is
duke@0 1094 // not at a safepoint at the time of the call, and thus there could
duke@0 1095 // be not inopportune interleavings between omFlush() and the scavenge
duke@0 1096 // operator.
duke@0 1097
duke@0 1098 void ObjectSynchronizer::omFlush (Thread * Self) {
duke@0 1099 ObjectMonitor * List = Self->omFreeList ; // Null-terminated SLL
duke@0 1100 Self->omFreeList = NULL ;
duke@0 1101 ObjectMonitor * Tail = NULL ;
acorn@1507 1102 int Tally = 0;
acorn@1560 1103 if (List != NULL) {
acorn@1560 1104 ObjectMonitor * s ;
acorn@1560 1105 for (s = List ; s != NULL ; s = s->FreeNext) {
acorn@1560 1106 Tally ++ ;
acorn@1560 1107 Tail = s ;
acorn@1560 1108 guarantee (s->object() == NULL, "invariant") ;
acorn@1560 1109 guarantee (!s->is_busy(), "invariant") ;
acorn@1560 1110 s->set_owner (NULL) ; // redundant but good hygiene
acorn@1560 1111 TEVENT (omFlush - Move one) ;
acorn@1560 1112 }
acorn@1560 1113 guarantee (Tail != NULL && List != NULL, "invariant") ;
duke@0 1114 }
duke@0 1115
acorn@1560 1116 ObjectMonitor * InUseList = Self->omInUseList;
acorn@1560 1117 ObjectMonitor * InUseTail = NULL ;
acorn@1560 1118 int InUseTally = 0;
acorn@1560 1119 if (InUseList != NULL) {
acorn@1560 1120 Self->omInUseList = NULL;
acorn@1560 1121 ObjectMonitor *curom;
acorn@1560 1122 for (curom = InUseList; curom != NULL; curom = curom->FreeNext) {
acorn@1560 1123 InUseTail = curom;
acorn@1560 1124 InUseTally++;
acorn@1560 1125 }
acorn@1560 1126 // TODO debug
acorn@1560 1127 assert(Self->omInUseCount == InUseTally, "inuse count off");
acorn@1560 1128 Self->omInUseCount = 0;
acorn@1560 1129 guarantee (InUseTail != NULL && InUseList != NULL, "invariant");
acorn@1560 1130 }
acorn@1560 1131
duke@0 1132 Thread::muxAcquire (&ListLock, "omFlush") ;
acorn@1560 1133 if (Tail != NULL) {
acorn@1560 1134 Tail->FreeNext = gFreeList ;
acorn@1560 1135 gFreeList = List ;
acorn@1560 1136 MonitorFreeCount += Tally;
acorn@1560 1137 }
acorn@1560 1138
acorn@1560 1139 if (InUseTail != NULL) {
acorn@1560 1140 InUseTail->FreeNext = gOmInUseList;
acorn@1560 1141 gOmInUseList = InUseList;
acorn@1560 1142 gOmInUseCount += InUseTally;
acorn@1560 1143 }
acorn@1560 1144
duke@0 1145 Thread::muxRelease (&ListLock) ;
duke@0 1146 TEVENT (omFlush) ;
duke@0 1147 }
duke@0 1148
duke@0 1149 // Fast path code shared by multiple functions
duke@0 1150 ObjectMonitor* ObjectSynchronizer::inflate_helper(oop obj) {
duke@0 1151 markOop mark = obj->mark();
duke@0 1152 if (mark->has_monitor()) {
duke@0 1153 assert(ObjectSynchronizer::verify_objmon_isinpool(mark->monitor()), "monitor is invalid");
duke@0 1154 assert(mark->monitor()->header()->is_neutral(), "monitor must record a good object header");
duke@0 1155 return mark->monitor();
duke@0 1156 }
duke@0 1157 return ObjectSynchronizer::inflate(Thread::current(), obj);
duke@0 1158 }
duke@0 1159
acorn@1798 1160
duke@0 1161 // Note that we could encounter some performance loss through false-sharing as
duke@0 1162 // multiple locks occupy the same $ line. Padding might be appropriate.
duke@0 1163
duke@0 1164
duke@0 1165 ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) {
duke@0 1166 // Inflate mutates the heap ...
duke@0 1167 // Relaxing assertion for bug 6320749.
duke@0 1168 assert (Universe::verify_in_progress() ||
duke@0 1169 !SafepointSynchronize::is_at_safepoint(), "invariant") ;
duke@0 1170
duke@0 1171 for (;;) {
duke@0 1172 const markOop mark = object->mark() ;
duke@0 1173 assert (!mark->has_bias_pattern(), "invariant") ;
duke@0 1174
duke@0 1175 // The mark can be in one of the following states:
duke@0 1176 // * Inflated - just return
duke@0 1177 // * Stack-locked - coerce it to inflated
duke@0 1178 // * INFLATING - busy wait for conversion to complete
duke@0 1179 // * Neutral - aggressively inflate the object.
duke@0 1180 // * BIASED - Illegal. We should never see this
duke@0 1181
duke@0 1182 // CASE: inflated
duke@0 1183 if (mark->has_monitor()) {
duke@0 1184 ObjectMonitor * inf = mark->monitor() ;
duke@0 1185 assert (inf->header()->is_neutral(), "invariant");
duke@0 1186 assert (inf->object() == object, "invariant") ;
duke@0 1187 assert (ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
duke@0 1188 return inf ;
duke@0 1189 }
duke@0 1190
duke@0 1191 // CASE: inflation in progress - inflating over a stack-lock.
duke@0 1192 // Some other thread is converting from stack-locked to inflated.
duke@0 1193 // Only that thread can complete inflation -- other threads must wait.
duke@0 1194 // The INFLATING value is transient.
duke@0 1195 // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
duke@0 1196 // We could always eliminate polling by parking the thread on some auxiliary list.
duke@0 1197 if (mark == markOopDesc::INFLATING()) {
duke@0 1198 TEVENT (Inflate: spin while INFLATING) ;
duke@0 1199 ReadStableMark(object) ;
duke@0 1200 continue ;
duke@0 1201 }
duke@0 1202
duke@0 1203 // CASE: stack-locked
duke@0 1204 // Could be stack-locked either by this thread or by some other thread.
duke@0 1205 //
duke@0 1206 // Note that we allocate the objectmonitor speculatively, _before_ attempting
duke@0 1207 // to install INFLATING into the mark word. We originally installed INFLATING,
duke@0 1208 // allocated the objectmonitor, and then finally STed the address of the
duke@0 1209 // objectmonitor into the mark. This was correct, but artificially lengthened
duke@0 1210 // the interval in which INFLATED appeared in the mark, thus increasing
duke@0 1211 // the odds of inflation contention.
duke@0 1212 //
duke@0 1213 // We now use per-thread private objectmonitor free lists.
duke@0 1214 // These list are reprovisioned from the global free list outside the
duke@0 1215 // critical INFLATING...ST interval. A thread can transfer
duke@0 1216 // multiple objectmonitors en-mass from the global free list to its local free list.
duke@0 1217 // This reduces coherency traffic and lock contention on the global free list.
duke@0 1218 // Using such local free lists, it doesn't matter if the omAlloc() call appears
duke@0 1219 // before or after the CAS(INFLATING) operation.
duke@0 1220 // See the comments in omAlloc().
duke@0 1221
duke@0 1222 if (mark->has_locker()) {
duke@0 1223 ObjectMonitor * m = omAlloc (Self) ;
duke@0 1224 // Optimistically prepare the objectmonitor - anticipate successful CAS
duke@0 1225 // We do this before the CAS in order to minimize the length of time
duke@0 1226 // in which INFLATING appears in the mark.
duke@0 1227 m->Recycle();
duke@0 1228 m->_Responsible = NULL ;
duke@0 1229 m->OwnerIsThread = 0 ;
duke@0 1230 m->_recursions = 0 ;
acorn@1798 1231 m->_SpinDuration = ObjectMonitor::Knob_SpinLimit ; // Consider: maintain by type/class
duke@0 1232
duke@0 1233 markOop cmp = (markOop) Atomic::cmpxchg_ptr (markOopDesc::INFLATING(), object->mark_addr(), mark) ;
duke@0 1234 if (cmp != mark) {
acorn@1560 1235 omRelease (Self, m, true) ;
duke@0 1236 continue ; // Interference -- just retry
duke@0 1237 }
duke@0 1238
duke@0 1239 // We've successfully installed INFLATING (0) into the mark-word.
duke@0 1240 // This is the only case where 0 will appear in a mark-work.
duke@0 1241 // Only the singular thread that successfully swings the mark-word
duke@0 1242 // to 0 can perform (or more precisely, complete) inflation.
duke@0 1243 //
duke@0 1244 // Why do we CAS a 0 into the mark-word instead of just CASing the
duke@0 1245 // mark-word from the stack-locked value directly to the new inflated state?
duke@0 1246 // Consider what happens when a thread unlocks a stack-locked object.
duke@0 1247 // It attempts to use CAS to swing the displaced header value from the
duke@0 1248 // on-stack basiclock back into the object header. Recall also that the
duke@0 1249 // header value (hashcode, etc) can reside in (a) the object header, or
duke@0 1250 // (b) a displaced header associated with the stack-lock, or (c) a displaced
duke@0 1251 // header in an objectMonitor. The inflate() routine must copy the header
duke@0 1252 // value from the basiclock on the owner's stack to the objectMonitor, all
duke@0 1253 // the while preserving the hashCode stability invariants. If the owner
duke@0 1254 // decides to release the lock while the value is 0, the unlock will fail
duke@0 1255 // and control will eventually pass from slow_exit() to inflate. The owner
duke@0 1256 // will then spin, waiting for the 0 value to disappear. Put another way,
duke@0 1257 // the 0 causes the owner to stall if the owner happens to try to
duke@0 1258 // drop the lock (restoring the header from the basiclock to the object)
duke@0 1259 // while inflation is in-progress. This protocol avoids races that might
duke@0 1260 // would otherwise permit hashCode values to change or "flicker" for an object.
duke@0 1261 // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable.
duke@0 1262 // 0 serves as a "BUSY" inflate-in-progress indicator.
duke@0 1263
duke@0 1264
duke@0 1265 // fetch the displaced mark from the owner's stack.
duke@0 1266 // The owner can't die or unwind past the lock while our INFLATING
duke@0 1267 // object is in the mark. Furthermore the owner can't complete
duke@0 1268 // an unlock on the object, either.
duke@0 1269 markOop dmw = mark->displaced_mark_helper() ;
duke@0 1270 assert (dmw->is_neutral(), "invariant") ;
duke@0 1271
duke@0 1272 // Setup monitor fields to proper values -- prepare the monitor
duke@0 1273 m->set_header(dmw) ;
duke@0 1274
duke@0 1275 // Optimization: if the mark->locker stack address is associated
duke@0 1276 // with this thread we could simply set m->_owner = Self and
xlu@702 1277 // m->OwnerIsThread = 1. Note that a thread can inflate an object
duke@0 1278 // that it has stack-locked -- as might happen in wait() -- directly
duke@0 1279 // with CAS. That is, we can avoid the xchg-NULL .... ST idiom.
xlu@702 1280 m->set_owner(mark->locker());
duke@0 1281 m->set_object(object);
duke@0 1282 // TODO-FIXME: assert BasicLock->dhw != 0.
duke@0 1283
duke@0 1284 // Must preserve store ordering. The monitor state must
duke@0 1285 // be stable at the time of publishing the monitor address.
duke@0 1286 guarantee (object->mark() == markOopDesc::INFLATING(), "invariant") ;
duke@0 1287 object->release_set_mark(markOopDesc::encode(m));
duke@0 1288
duke@0 1289 // Hopefully the performance counters are allocated on distinct cache lines
duke@0 1290 // to avoid false sharing on MP systems ...
acorn@1798 1291 if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ;
duke@0 1292 TEVENT(Inflate: overwrite stacklock) ;
duke@0 1293 if (TraceMonitorInflation) {
duke@0 1294 if (object->is_instance()) {
duke@0 1295 ResourceMark rm;
duke@0 1296 tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
duke@0 1297 (intptr_t) object, (intptr_t) object->mark(),
duke@0 1298 Klass::cast(object->klass())->external_name());
duke@0 1299 }
duke@0 1300 }
duke@0 1301 return m ;
duke@0 1302 }
duke@0 1303
duke@0 1304 // CASE: neutral
duke@0 1305 // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
duke@0 1306 // If we know we're inflating for entry it's better to inflate by swinging a
duke@0 1307 // pre-locked objectMonitor pointer into the object header. A successful
duke@0 1308 // CAS inflates the object *and* confers ownership to the inflating thread.
duke@0 1309 // In the current implementation we use a 2-step mechanism where we CAS()
duke@0 1310 // to inflate and then CAS() again to try to swing _owner from NULL to Self.
duke@0 1311 // An inflateTry() method that we could call from fast_enter() and slow_enter()
duke@0 1312 // would be useful.
duke@0 1313
duke@0 1314 assert (mark->is_neutral(), "invariant");
duke@0 1315 ObjectMonitor * m = omAlloc (Self) ;
duke@0 1316 // prepare m for installation - set monitor to initial state
duke@0 1317 m->Recycle();
duke@0 1318 m->set_header(mark);
duke@0 1319 m->set_owner(NULL);
duke@0 1320 m->set_object(object);
duke@0 1321 m->OwnerIsThread = 1 ;
duke@0 1322 m->_recursions = 0 ;
duke@0 1323 m->_Responsible = NULL ;
acorn@1798 1324 m->_SpinDuration = ObjectMonitor::Knob_SpinLimit ; // consider: keep metastats by type/class
duke@0 1325
duke@0 1326 if (Atomic::cmpxchg_ptr (markOopDesc::encode(m), object->mark_addr(), mark) != mark) {
duke@0 1327 m->set_object (NULL) ;
duke@0 1328 m->set_owner (NULL) ;
duke@0 1329 m->OwnerIsThread = 0 ;
duke@0 1330 m->Recycle() ;
acorn@1560 1331 omRelease (Self, m, true) ;
duke@0 1332 m = NULL ;
duke@0 1333 continue ;
duke@0 1334 // interference - the markword changed - just retry.
duke@0 1335 // The state-transitions are one-way, so there's no chance of
duke@0 1336 // live-lock -- "Inflated" is an absorbing state.
duke@0 1337 }
duke@0 1338
duke@0 1339 // Hopefully the performance counters are allocated on distinct
duke@0 1340 // cache lines to avoid false sharing on MP systems ...
acorn@1798 1341 if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ;
duke@0 1342 TEVENT(Inflate: overwrite neutral) ;
duke@0 1343 if (TraceMonitorInflation) {
duke@0 1344 if (object->is_instance()) {
duke@0 1345 ResourceMark rm;
duke@0 1346 tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
duke@0 1347 (intptr_t) object, (intptr_t) object->mark(),
duke@0 1348 Klass::cast(object->klass())->external_name());
duke@0 1349 }
duke@0 1350 }
duke@0 1351 return m ;
duke@0 1352 }
duke@0 1353 }
duke@0 1354
acorn@1798 1355 // Note that we could encounter some performance loss through false-sharing as
acorn@1798 1356 // multiple locks occupy the same $ line. Padding might be appropriate.
duke@0 1357
duke@0 1358
duke@0 1359 // Deflate_idle_monitors() is called at all safepoints, immediately
duke@0 1360 // after all mutators are stopped, but before any objects have moved.
duke@0 1361 // It traverses the list of known monitors, deflating where possible.
duke@0 1362 // The scavenged monitor are returned to the monitor free list.
duke@0 1363 //
duke@0 1364 // Beware that we scavenge at *every* stop-the-world point.
duke@0 1365 // Having a large number of monitors in-circulation negatively
duke@0 1366 // impacts the performance of some applications (e.g., PointBase).
duke@0 1367 // Broadly, we want to minimize the # of monitors in circulation.
acorn@1507 1368 //
acorn@1507 1369 // We have added a flag, MonitorInUseLists, which creates a list
acorn@1507 1370 // of active monitors for each thread. deflate_idle_monitors()
acorn@1507 1371 // only scans the per-thread inuse lists. omAlloc() puts all
acorn@1507 1372 // assigned monitors on the per-thread list. deflate_idle_monitors()
acorn@1507 1373 // returns the non-busy monitors to the global free list.
acorn@1560 1374 // When a thread dies, omFlush() adds the list of active monitors for
acorn@1560 1375 // that thread to a global gOmInUseList acquiring the
acorn@1560 1376 // global list lock. deflate_idle_monitors() acquires the global
acorn@1560 1377 // list lock to scan for non-busy monitors to the global free list.
acorn@1507 1378 // An alternative could have used a single global inuse list. The
acorn@1507 1379 // downside would have been the additional cost of acquiring the global list lock
acorn@1507 1380 // for every omAlloc().
duke@0 1381 //
duke@0 1382 // Perversely, the heap size -- and thus the STW safepoint rate --
duke@0 1383 // typically drives the scavenge rate. Large heaps can mean infrequent GC,
duke@0 1384 // which in turn can mean large(r) numbers of objectmonitors in circulation.
duke@0 1385 // This is an unfortunate aspect of this design.
duke@0 1386 //
duke@0 1387
acorn@1798 1388 enum ManifestConstants {
acorn@1798 1389 ClearResponsibleAtSTW = 0,
acorn@1798 1390 MaximumRecheckInterval = 1000
acorn@1798 1391 } ;
acorn@1507 1392
acorn@1507 1393 // Deflate a single monitor if not in use
acorn@1507 1394 // Return true if deflated, false if in use
acorn@1507 1395 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj,
acorn@1507 1396 ObjectMonitor** FreeHeadp, ObjectMonitor** FreeTailp) {
acorn@1507 1397 bool deflated;
acorn@1507 1398 // Normal case ... The monitor is associated with obj.
acorn@1507 1399 guarantee (obj->mark() == markOopDesc::encode(mid), "invariant") ;
acorn@1507 1400 guarantee (mid == obj->mark()->monitor(), "invariant");
acorn@1507 1401 guarantee (mid->header()->is_neutral(), "invariant");
acorn@1507 1402
acorn@1507 1403 if (mid->is_busy()) {
acorn@1507 1404 if (ClearResponsibleAtSTW) mid->_Responsible = NULL ;
acorn@1507 1405 deflated = false;
acorn@1507 1406 } else {
acorn@1507 1407 // Deflate the monitor if it is no longer being used
acorn@1507 1408 // It's idle - scavenge and return to the global free list
acorn@1507 1409 // plain old deflation ...
acorn@1507 1410 TEVENT (deflate_idle_monitors - scavenge1) ;
acorn@1507 1411 if (TraceMonitorInflation) {
acorn@1507 1412 if (obj->is_instance()) {
acorn@1507 1413 ResourceMark rm;
acorn@1507 1414 tty->print_cr("Deflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
acorn@1507 1415 (intptr_t) obj, (intptr_t) obj->mark(), Klass::cast(obj->klass())->external_name());
acorn@1507 1416 }
acorn@1507 1417 }
acorn@1507 1418
acorn@1507 1419 // Restore the header back to obj
acorn@1507 1420 obj->release_set_mark(mid->header());
acorn@1507 1421 mid->clear();
acorn@1507 1422
acorn@1507 1423 assert (mid->object() == NULL, "invariant") ;
acorn@1507 1424
acorn@1507 1425 // Move the object to the working free list defined by FreeHead,FreeTail.
acorn@1507 1426 if (*FreeHeadp == NULL) *FreeHeadp = mid;
acorn@1507 1427 if (*FreeTailp != NULL) {
acorn@1507 1428 ObjectMonitor * prevtail = *FreeTailp;
acorn@1560 1429 assert(prevtail->FreeNext == NULL, "cleaned up deflated?"); // TODO KK
acorn@1507 1430 prevtail->FreeNext = mid;
acorn@1507 1431 }
acorn@1507 1432 *FreeTailp = mid;
acorn@1507 1433 deflated = true;
acorn@1507 1434 }
acorn@1507 1435 return deflated;
acorn@1507 1436 }
acorn@1507 1437
acorn@1560 1438 // Caller acquires ListLock
acorn@1560 1439 int ObjectSynchronizer::walk_monitor_list(ObjectMonitor** listheadp,
acorn@1560 1440 ObjectMonitor** FreeHeadp, ObjectMonitor** FreeTailp) {
acorn@1560 1441 ObjectMonitor* mid;
acorn@1560 1442 ObjectMonitor* next;
acorn@1560 1443 ObjectMonitor* curmidinuse = NULL;
acorn@1560 1444 int deflatedcount = 0;
acorn@1560 1445
acorn@1560 1446 for (mid = *listheadp; mid != NULL; ) {
acorn@1560 1447 oop obj = (oop) mid->object();
acorn@1560 1448 bool deflated = false;
acorn@1560 1449 if (obj != NULL) {
acorn@1560 1450 deflated = deflate_monitor(mid, obj, FreeHeadp, FreeTailp);
acorn@1560 1451 }
acorn@1560 1452 if (deflated) {
acorn@1560 1453 // extract from per-thread in-use-list
acorn@1560 1454 if (mid == *listheadp) {
acorn@1560 1455 *listheadp = mid->FreeNext;
acorn@1560 1456 } else if (curmidinuse != NULL) {
acorn@1560 1457 curmidinuse->FreeNext = mid->FreeNext; // maintain the current thread inuselist
acorn@1560 1458 }
acorn@1560 1459 next = mid->FreeNext;
acorn@1560 1460 mid->FreeNext = NULL; // This mid is current tail in the FreeHead list
acorn@1560 1461 mid = next;
acorn@1560 1462 deflatedcount++;
acorn@1560 1463 } else {
acorn@1560 1464 curmidinuse = mid;
acorn@1560 1465 mid = mid->FreeNext;
acorn@1560 1466 }
acorn@1560 1467 }
acorn@1560 1468 return deflatedcount;
acorn@1560 1469 }
acorn@1560 1470
duke@0 1471 void ObjectSynchronizer::deflate_idle_monitors() {
duke@0 1472 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
duke@0 1473 int nInuse = 0 ; // currently associated with objects
duke@0 1474 int nInCirculation = 0 ; // extant
duke@0 1475 int nScavenged = 0 ; // reclaimed
acorn@1507 1476 bool deflated = false;
duke@0 1477
duke@0 1478 ObjectMonitor * FreeHead = NULL ; // Local SLL of scavenged monitors
duke@0 1479 ObjectMonitor * FreeTail = NULL ;
duke@0 1480
acorn@1507 1481 TEVENT (deflate_idle_monitors) ;
acorn@1507 1482 // Prevent omFlush from changing mids in Thread dtor's during deflation
acorn@1507 1483 // And in case the vm thread is acquiring a lock during a safepoint
acorn@1507 1484 // See e.g. 6320749
acorn@1507 1485 Thread::muxAcquire (&ListLock, "scavenge - return") ;
acorn@1507 1486
acorn@1507 1487 if (MonitorInUseLists) {
acorn@1560 1488 int inUse = 0;
acorn@1507 1489 for (JavaThread* cur = Threads::first(); cur != NULL; cur = cur->next()) {
acorn@1560 1490 nInCirculation+= cur->omInUseCount;
acorn@1560 1491 int deflatedcount = walk_monitor_list(cur->omInUseList_addr(), &FreeHead, &FreeTail);
acorn@1560 1492 cur->omInUseCount-= deflatedcount;
acorn@1560 1493 // verifyInUse(cur);
acorn@1560 1494 nScavenged += deflatedcount;
acorn@1560 1495 nInuse += cur->omInUseCount;
acorn@1507 1496 }
acorn@1560 1497
acorn@1560 1498 // For moribund threads, scan gOmInUseList
acorn@1560 1499 if (gOmInUseList) {
acorn@1560 1500 nInCirculation += gOmInUseCount;
acorn@1560 1501 int deflatedcount = walk_monitor_list((ObjectMonitor **)&gOmInUseList, &FreeHead, &FreeTail);
acorn@1560 1502 gOmInUseCount-= deflatedcount;
acorn@1560 1503 nScavenged += deflatedcount;
acorn@1560 1504 nInuse += gOmInUseCount;
acorn@1560 1505 }
acorn@1560 1506
acorn@1507 1507 } else for (ObjectMonitor* block = gBlockList; block != NULL; block = next(block)) {
duke@0 1508 // Iterate over all extant monitors - Scavenge all idle monitors.
duke@0 1509 assert(block->object() == CHAINMARKER, "must be a block header");
duke@0 1510 nInCirculation += _BLOCKSIZE ;
duke@0 1511 for (int i = 1 ; i < _BLOCKSIZE; i++) {
duke@0 1512 ObjectMonitor* mid = &block[i];
duke@0 1513 oop obj = (oop) mid->object();
duke@0 1514
duke@0 1515 if (obj == NULL) {
duke@0 1516 // The monitor is not associated with an object.
duke@0 1517 // The monitor should either be a thread-specific private
duke@0 1518 // free list or the global free list.
duke@0 1519 // obj == NULL IMPLIES mid->is_busy() == 0
duke@0 1520 guarantee (!mid->is_busy(), "invariant") ;
duke@0 1521 continue ;
duke@0 1522 }
acorn@1507 1523 deflated = deflate_monitor(mid, obj, &FreeHead, &FreeTail);
acorn@1507 1524
acorn@1507 1525 if (deflated) {
acorn@1507 1526 mid->FreeNext = NULL ;
acorn@1507 1527 nScavenged ++ ;
duke@0 1528 } else {
acorn@1507 1529 nInuse ++;
duke@0 1530 }
duke@0 1531 }
duke@0 1532 }
duke@0 1533
acorn@1507 1534 MonitorFreeCount += nScavenged;
acorn@1507 1535
acorn@1507 1536 // Consider: audit gFreeList to ensure that MonitorFreeCount and list agree.
acorn@1507 1537
acorn@1798 1538 if (ObjectMonitor::Knob_Verbose) {
acorn@1507 1539 ::printf ("Deflate: InCirc=%d InUse=%d Scavenged=%d ForceMonitorScavenge=%d : pop=%d free=%d\n",
acorn@1507 1540 nInCirculation, nInuse, nScavenged, ForceMonitorScavenge,
acorn@1507 1541 MonitorPopulation, MonitorFreeCount) ;
acorn@1507 1542 ::fflush(stdout) ;
acorn@1507 1543 }
acorn@1507 1544
acorn@1507 1545 ForceMonitorScavenge = 0; // Reset
acorn@1507 1546
duke@0 1547 // Move the scavenged monitors back to the global free list.
duke@0 1548 if (FreeHead != NULL) {
duke@0 1549 guarantee (FreeTail != NULL && nScavenged > 0, "invariant") ;
duke@0 1550 assert (FreeTail->FreeNext == NULL, "invariant") ;
duke@0 1551 // constant-time list splice - prepend scavenged segment to gFreeList
duke@0 1552 FreeTail->FreeNext = gFreeList ;
duke@0 1553 gFreeList = FreeHead ;
duke@0 1554 }
acorn@1507 1555 Thread::muxRelease (&ListLock) ;
duke@0 1556
acorn@1798 1557 if (ObjectMonitor::_sync_Deflations != NULL) ObjectMonitor::_sync_Deflations->inc(nScavenged) ;
acorn@1798 1558 if (ObjectMonitor::_sync_MonExtant != NULL) ObjectMonitor::_sync_MonExtant ->set_value(nInCirculation);
duke@0 1559
duke@0 1560 // TODO: Add objectMonitor leak detection.
duke@0 1561 // Audit/inventory the objectMonitors -- make sure they're all accounted for.
duke@0 1562 GVars.stwRandom = os::random() ;
duke@0 1563 GVars.stwCycle ++ ;
duke@0 1564 }
duke@0 1565
acorn@1798 1566 // Monitor cleanup on JavaThread::exit
duke@0 1567
acorn@1798 1568 // Iterate through monitor cache and attempt to release thread's monitors
acorn@1798 1569 // Gives up on a particular monitor if an exception occurs, but continues
acorn@1798 1570 // the overall iteration, swallowing the exception.
acorn@1798 1571 class ReleaseJavaMonitorsClosure: public MonitorClosure {
acorn@1798 1572 private:
acorn@1798 1573 TRAPS;
duke@0 1574
acorn@1798 1575 public:
acorn@1798 1576 ReleaseJavaMonitorsClosure(Thread* thread) : THREAD(thread) {}
acorn@1798 1577 void do_monitor(ObjectMonitor* mid) {
acorn@1798 1578 if (mid->owner() == THREAD) {
acorn@1798 1579 (void)mid->complete_exit(CHECK);
duke@0 1580 }
duke@0 1581 }
acorn@1798 1582 };
acorn@1798 1583
acorn@1798 1584 // Release all inflated monitors owned by THREAD. Lightweight monitors are
acorn@1798 1585 // ignored. This is meant to be called during JNI thread detach which assumes
acorn@1798 1586 // all remaining monitors are heavyweight. All exceptions are swallowed.
acorn@1798 1587 // Scanning the extant monitor list can be time consuming.
acorn@1798 1588 // A simple optimization is to add a per-thread flag that indicates a thread
acorn@1798 1589 // called jni_monitorenter() during its lifetime.
acorn@1798 1590 //
acorn@1798 1591 // Instead of No_Savepoint_Verifier it might be cheaper to
acorn@1798 1592 // use an idiom of the form:
acorn@1798 1593 // auto int tmp = SafepointSynchronize::_safepoint_counter ;
acorn@1798 1594 // <code that must not run at safepoint>
acorn@1798 1595 // guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
acorn@1798 1596 // Since the tests are extremely cheap we could leave them enabled
acorn@1798 1597 // for normal product builds.
acorn@1798 1598
acorn@1798 1599 void ObjectSynchronizer::release_monitors_owned_by_thread(TRAPS) {
acorn@1798 1600 assert(THREAD == JavaThread::current(), "must be current Java thread");
acorn@1798 1601 No_Safepoint_Verifier nsv ;
acorn@1798 1602 ReleaseJavaMonitorsClosure rjmc(THREAD);
acorn@1798 1603 Thread::muxAcquire(&ListLock, "release_monitors_owned_by_thread");
acorn@1798 1604 ObjectSynchronizer::monitors_iterate(&rjmc);
acorn@1798 1605 Thread::muxRelease(&ListLock);
acorn@1798 1606 THREAD->clear_pending_exception();
duke@0 1607 }
duke@0 1608
duke@0 1609 //------------------------------------------------------------------------------
duke@0 1610 // Non-product code
duke@0 1611
duke@0 1612 #ifndef PRODUCT
duke@0 1613
duke@0 1614 void ObjectSynchronizer::trace_locking(Handle locking_obj, bool is_compiled,
duke@0 1615 bool is_method, bool is_locking) {
duke@0 1616 // Don't know what to do here
duke@0 1617 }
duke@0 1618
duke@0 1619 // Verify all monitors in the monitor cache, the verification is weak.
duke@0 1620 void ObjectSynchronizer::verify() {
duke@0 1621 ObjectMonitor* block = gBlockList;
duke@0 1622 ObjectMonitor* mid;
duke@0 1623 while (block) {
duke@0 1624 assert(block->object() == CHAINMARKER, "must be a block header");
duke@0 1625 for (int i = 1; i < _BLOCKSIZE; i++) {
duke@0 1626 mid = block + i;
duke@0 1627 oop object = (oop) mid->object();
duke@0 1628 if (object != NULL) {
duke@0 1629 mid->verify();
duke@0 1630 }
duke@0 1631 }
duke@0 1632 block = (ObjectMonitor*) block->FreeNext;
duke@0 1633 }
duke@0 1634 }
duke@0 1635
duke@0 1636 // Check if monitor belongs to the monitor cache
duke@0 1637 // The list is grow-only so it's *relatively* safe to traverse
duke@0 1638 // the list of extant blocks without taking a lock.
duke@0 1639
duke@0 1640 int ObjectSynchronizer::verify_objmon_isinpool(ObjectMonitor *monitor) {
duke@0 1641 ObjectMonitor* block = gBlockList;
duke@0 1642
duke@0 1643 while (block) {
duke@0 1644 assert(block->object() == CHAINMARKER, "must be a block header");
duke@0 1645 if (monitor > &block[0] && monitor < &block[_BLOCKSIZE]) {
duke@0 1646 address mon = (address) monitor;
duke@0 1647 address blk = (address) block;
duke@0 1648 size_t diff = mon - blk;
duke@0 1649 assert((diff % sizeof(ObjectMonitor)) == 0, "check");
duke@0 1650 return 1;
duke@0 1651 }
duke@0 1652 block = (ObjectMonitor*) block->FreeNext;
duke@0 1653 }
duke@0 1654 return 0;
duke@0 1655 }
duke@0 1656
duke@0 1657 #endif