src/share/vm/runtime/synchronizer.cpp

Fri, 22 Oct 2010 15:59:34 -0400

author
acorn
date
Fri, 22 Oct 2010 15:59:34 -0400
changeset 2233
fa83ab460c54
parent 1995
bfc89697cccb
child 2314
f95d63e2154a
permissions
-rw-r--r--

6988353: refactor contended sync subsystem
Summary: reduce complexity by factoring synchronizer.cpp
Reviewed-by: dholmes, never, coleenp

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

mercurial