1 /* 2 * Copyright (c) 1998, 2020, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "classfile/vmSymbols.hpp" 27 #include "logging/log.hpp" 28 #include "logging/logStream.hpp" 29 #include "jfr/jfrEvents.hpp" 30 #include "memory/allocation.inline.hpp" 31 #include "memory/metaspaceShared.hpp" 32 #include "memory/padded.hpp" 33 #include "memory/resourceArea.hpp" 34 #include "memory/universe.hpp" 35 #include "oops/markWord.hpp" 36 #include "oops/oop.inline.hpp" 37 #include "runtime/atomic.hpp" 38 #include "runtime/biasedLocking.hpp" 39 #include "runtime/handles.inline.hpp" 40 #include "runtime/handshake.hpp" 41 #include "runtime/interfaceSupport.inline.hpp" 42 #include "runtime/mutexLocker.hpp" 43 #include "runtime/objectMonitor.hpp" 44 #include "runtime/objectMonitor.inline.hpp" 45 #include "runtime/osThread.hpp" 46 #include "runtime/safepointMechanism.inline.hpp" 47 #include "runtime/safepointVerifiers.hpp" 48 #include "runtime/sharedRuntime.hpp" 49 #include "runtime/stubRoutines.hpp" 50 #include "runtime/synchronizer.hpp" 51 #include "runtime/thread.inline.hpp" 52 #include "runtime/timer.hpp" 53 #include "runtime/vframe.hpp" 54 #include "runtime/vmThread.hpp" 55 #include "utilities/align.hpp" 56 #include "utilities/dtrace.hpp" 57 #include "utilities/events.hpp" 58 #include "utilities/preserveException.hpp" 59 60 // The "core" versions of monitor enter and exit reside in this file. 61 // The interpreter and compilers contain specialized transliterated 62 // variants of the enter-exit fast-path operations. See i486.ad fast_lock(), 63 // for instance. If you make changes here, make sure to modify the 64 // interpreter, and both C1 and C2 fast-path inline locking code emission. 65 // 66 // ----------------------------------------------------------------------------- 67 68 #ifdef DTRACE_ENABLED 69 70 // Only bother with this argument setup if dtrace is available 71 // TODO-FIXME: probes should not fire when caller is _blocked. assert() accordingly. 72 73 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread) \ 74 char* bytes = NULL; \ 75 int len = 0; \ 76 jlong jtid = SharedRuntime::get_java_tid(thread); \ 77 Symbol* klassname = ((oop)(obj))->klass()->name(); \ 78 if (klassname != NULL) { \ 79 bytes = (char*)klassname->bytes(); \ 80 len = klassname->utf8_length(); \ 81 } 82 83 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis) \ 84 { \ 85 if (DTraceMonitorProbes) { \ 86 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ 87 HOTSPOT_MONITOR_WAIT(jtid, \ 88 (uintptr_t)(monitor), bytes, len, (millis)); \ 89 } \ 90 } 91 92 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY 93 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL 94 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED 95 96 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread) \ 97 { \ 98 if (DTraceMonitorProbes) { \ 99 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ 100 HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */ \ 101 (uintptr_t)(monitor), bytes, len); \ 102 } \ 103 } 104 105 #else // ndef DTRACE_ENABLED 106 107 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon) {;} 108 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon) {;} 109 110 #endif // ndef DTRACE_ENABLED 111 112 // This exists only as a workaround of dtrace bug 6254741 113 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) { 114 DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr); 115 return 0; 116 } 117 118 #define NINFLATIONLOCKS 256 119 static volatile intptr_t gInflationLocks[NINFLATIONLOCKS]; 120 121 // global list of blocks of monitors 122 PaddedObjectMonitor* ObjectSynchronizer::g_block_list = NULL; 123 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false; 124 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0; 125 126 struct ObjectMonitorListGlobals { 127 char _pad_prefix[OM_CACHE_LINE_SIZE]; 128 // These are highly shared list related variables. 129 // To avoid false-sharing they need to be the sole occupants of a cache line. 130 131 // Global ObjectMonitor free list. Newly allocated and deflated 132 // ObjectMonitors are prepended here. 133 ObjectMonitor* _free_list; 134 DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(ObjectMonitor*)); 135 136 // Global ObjectMonitor in-use list. When a JavaThread is exiting, 137 // ObjectMonitors on its per-thread in-use list are prepended here. 138 ObjectMonitor* _in_use_list; 139 DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(ObjectMonitor*)); 140 141 // Global ObjectMonitor wait list. Deflated ObjectMonitors wait on 142 // this list until after a handshake or a safepoint for platforms 143 // that don't support handshakes. After the handshake or safepoint, 144 // the deflated ObjectMonitors are prepended to free_list. 145 ObjectMonitor* _wait_list; 146 DEFINE_PAD_MINUS_SIZE(3, OM_CACHE_LINE_SIZE, sizeof(ObjectMonitor*)); 147 148 int _free_count; // # on free_list 149 DEFINE_PAD_MINUS_SIZE(4, OM_CACHE_LINE_SIZE, sizeof(int)); 150 151 int _in_use_count; // # on in_use_list 152 DEFINE_PAD_MINUS_SIZE(5, OM_CACHE_LINE_SIZE, sizeof(int)); 153 154 int _population; // # Extant -- in circulation 155 DEFINE_PAD_MINUS_SIZE(6, OM_CACHE_LINE_SIZE, sizeof(int)); 156 157 int _wait_count; // # on wait_list 158 DEFINE_PAD_MINUS_SIZE(7, OM_CACHE_LINE_SIZE, sizeof(int)); 159 }; 160 static ObjectMonitorListGlobals om_list_globals; 161 162 #define CHAINMARKER (cast_to_oop<intptr_t>(-1)) 163 164 165 // =====================> Spin-lock functions 166 167 // ObjectMonitors are not lockable outside of this file. We use spin-locks 168 // implemented using a bit in the _next_om field instead of the heavier 169 // weight locking mechanisms for faster list management. 170 171 #define OM_LOCK_BIT 0x1 172 173 // Return true if the ObjectMonitor is locked. 174 // Otherwise returns false. 175 static bool is_locked(ObjectMonitor* om) { 176 return ((intptr_t)om->next_om() & OM_LOCK_BIT) == OM_LOCK_BIT; 177 } 178 179 // Mark an ObjectMonitor* with OM_LOCK_BIT and return it. 180 static ObjectMonitor* mark_om_ptr(ObjectMonitor* om) { 181 return (ObjectMonitor*)((intptr_t)om | OM_LOCK_BIT); 182 } 183 184 // Return the unmarked next field in an ObjectMonitor. Note: the next 185 // field may or may not have been marked with OM_LOCK_BIT originally. 186 static ObjectMonitor* unmarked_next(ObjectMonitor* om) { 187 return (ObjectMonitor*)((intptr_t)om->next_om() & ~OM_LOCK_BIT); 188 } 189 190 // Try to lock an ObjectMonitor. Returns true if locking was successful. 191 // Otherwise returns false. 192 static bool try_om_lock(ObjectMonitor* om) { 193 // Get current next field without any OM_LOCK_BIT value. 194 ObjectMonitor* next = unmarked_next(om); 195 if (om->try_set_next_om(next, mark_om_ptr(next)) != next) { 196 return false; // Cannot lock the ObjectMonitor. 197 } 198 return true; 199 } 200 201 // Lock an ObjectMonitor. 202 static void om_lock(ObjectMonitor* om) { 203 while (true) { 204 if (try_om_lock(om)) { 205 return; 206 } 207 } 208 } 209 210 // Unlock an ObjectMonitor. 211 static void om_unlock(ObjectMonitor* om) { 212 ObjectMonitor* next = om->next_om(); 213 guarantee(((intptr_t)next & OM_LOCK_BIT) == OM_LOCK_BIT, "next=" INTPTR_FORMAT 214 " must have OM_LOCK_BIT=%x set.", p2i(next), OM_LOCK_BIT); 215 216 next = (ObjectMonitor*)((intptr_t)next & ~OM_LOCK_BIT); // Clear OM_LOCK_BIT. 217 om->set_next_om(next); 218 } 219 220 // Get the list head after locking it. Returns the list head or NULL 221 // if the list is empty. 222 static ObjectMonitor* get_list_head_locked(ObjectMonitor** list_p) { 223 while (true) { 224 ObjectMonitor* mid = Atomic::load(list_p); 225 if (mid == NULL) { 226 return NULL; // The list is empty. 227 } 228 if (try_om_lock(mid)) { 229 if (Atomic::load(list_p) != mid) { 230 // The list head changed before we could lock it so we have to retry. 231 om_unlock(mid); 232 continue; 233 } 234 return mid; 235 } 236 } 237 } 238 239 #undef OM_LOCK_BIT 240 241 242 // =====================> List Management functions 243 244 // Prepend a list of ObjectMonitors to the specified *list_p. 'tail' is 245 // the last ObjectMonitor in the list and there are 'count' on the list. 246 // Also updates the specified *count_p. 247 static void prepend_list_to_common(ObjectMonitor* list, ObjectMonitor* tail, 248 int count, ObjectMonitor** list_p, 249 int* count_p) { 250 while (true) { 251 ObjectMonitor* cur = Atomic::load(list_p); 252 // Prepend list to *list_p. 253 if (!try_om_lock(tail)) { 254 // Failed to lock tail due to a list walker so try it all again. 255 continue; 256 } 257 tail->set_next_om(cur); // tail now points to cur (and unlocks tail) 258 if (cur == NULL) { 259 // No potential race with takers or other prependers since 260 // *list_p is empty. 261 if (Atomic::cmpxchg(list_p, cur, list) == cur) { 262 // Successfully switched *list_p to the list value. 263 Atomic::add(count_p, count); 264 break; 265 } 266 // Implied else: try it all again 267 } else { 268 if (!try_om_lock(cur)) { 269 continue; // failed to lock cur so try it all again 270 } 271 // We locked cur so try to switch *list_p to the list value. 272 if (Atomic::cmpxchg(list_p, cur, list) != cur) { 273 // The list head has changed so unlock cur and try again: 274 om_unlock(cur); 275 continue; 276 } 277 Atomic::add(count_p, count); 278 om_unlock(cur); 279 break; 280 } 281 } 282 } 283 284 // Prepend a newly allocated block of ObjectMonitors to g_block_list and 285 // om_list_globals._free_list. Also updates om_list_globals._population 286 // and om_list_globals._free_count. 287 void ObjectSynchronizer::prepend_block_to_lists(PaddedObjectMonitor* new_blk) { 288 // First we handle g_block_list: 289 while (true) { 290 PaddedObjectMonitor* cur = Atomic::load(&g_block_list); 291 // Prepend new_blk to g_block_list. The first ObjectMonitor in 292 // a block is reserved for use as linkage to the next block. 293 new_blk[0].set_next_om(cur); 294 if (Atomic::cmpxchg(&g_block_list, cur, new_blk) == cur) { 295 // Successfully switched g_block_list to the new_blk value. 296 Atomic::add(&om_list_globals._population, _BLOCKSIZE - 1); 297 break; 298 } 299 // Implied else: try it all again 300 } 301 302 // Second we handle om_list_globals._free_list: 303 prepend_list_to_common(new_blk + 1, &new_blk[_BLOCKSIZE - 1], _BLOCKSIZE - 1, 304 &om_list_globals._free_list, &om_list_globals._free_count); 305 } 306 307 // Prepend a list of ObjectMonitors to om_list_globals._free_list. 308 // 'tail' is the last ObjectMonitor in the list and there are 'count' 309 // on the list. Also updates om_list_globals._free_count. 310 static void prepend_list_to_global_free_list(ObjectMonitor* list, 311 ObjectMonitor* tail, int count) { 312 prepend_list_to_common(list, tail, count, &om_list_globals._free_list, 313 &om_list_globals._free_count); 314 } 315 316 // Prepend a list of ObjectMonitors to om_list_globals._wait_list. 317 // 'tail' is the last ObjectMonitor in the list and there are 'count' 318 // on the list. Also updates om_list_globals._wait_count. 319 static void prepend_list_to_global_wait_list(ObjectMonitor* list, 320 ObjectMonitor* tail, int count) { 321 prepend_list_to_common(list, tail, count, &om_list_globals._wait_list, 322 &om_list_globals._wait_count); 323 } 324 325 // Prepend a list of ObjectMonitors to om_list_globals._in_use_list. 326 // 'tail' is the last ObjectMonitor in the list and there are 'count' 327 // on the list. Also updates om_list_globals._in_use_list. 328 static void prepend_list_to_global_in_use_list(ObjectMonitor* list, 329 ObjectMonitor* tail, int count) { 330 prepend_list_to_common(list, tail, count, &om_list_globals._in_use_list, 331 &om_list_globals._in_use_count); 332 } 333 334 // Prepend an ObjectMonitor to the specified list. Also updates 335 // the specified counter. 336 static void prepend_to_common(ObjectMonitor* m, ObjectMonitor** list_p, 337 int* count_p) { 338 while (true) { 339 om_lock(m); // Lock m so we can safely update its next field. 340 ObjectMonitor* cur = NULL; 341 // Lock the list head to guard against races with a list walker 342 // or async deflater thread (which only races in om_in_use_list): 343 if ((cur = get_list_head_locked(list_p)) != NULL) { 344 // List head is now locked so we can safely switch it. 345 m->set_next_om(cur); // m now points to cur (and unlocks m) 346 Atomic::store(list_p, m); // Switch list head to unlocked m. 347 om_unlock(cur); 348 break; 349 } 350 // The list is empty so try to set the list head. 351 assert(cur == NULL, "cur must be NULL: cur=" INTPTR_FORMAT, p2i(cur)); 352 m->set_next_om(cur); // m now points to NULL (and unlocks m) 353 if (Atomic::cmpxchg(list_p, cur, m) == cur) { 354 // List head is now unlocked m. 355 break; 356 } 357 // Implied else: try it all again 358 } 359 Atomic::inc(count_p); 360 } 361 362 // Prepend an ObjectMonitor to a per-thread om_free_list. 363 // Also updates the per-thread om_free_count. 364 static void prepend_to_om_free_list(Thread* self, ObjectMonitor* m) { 365 prepend_to_common(m, &self->om_free_list, &self->om_free_count); 366 } 367 368 // Prepend an ObjectMonitor to a per-thread om_in_use_list. 369 // Also updates the per-thread om_in_use_count. 370 static void prepend_to_om_in_use_list(Thread* self, ObjectMonitor* m) { 371 prepend_to_common(m, &self->om_in_use_list, &self->om_in_use_count); 372 } 373 374 // Take an ObjectMonitor from the start of the specified list. Also 375 // decrements the specified counter. Returns NULL if none are available. 376 static ObjectMonitor* take_from_start_of_common(ObjectMonitor** list_p, 377 int* count_p) { 378 ObjectMonitor* take = NULL; 379 // Lock the list head to guard against races with a list walker 380 // or async deflater thread (which only races in om_list_globals._free_list): 381 if ((take = get_list_head_locked(list_p)) == NULL) { 382 return NULL; // None are available. 383 } 384 ObjectMonitor* next = unmarked_next(take); 385 // Switch locked list head to next (which unlocks the list head, but 386 // leaves take locked): 387 Atomic::store(list_p, next); 388 Atomic::dec(count_p); 389 // Unlock take, but leave the next value for any lagging list 390 // walkers. It will get cleaned up when take is prepended to 391 // the in-use list: 392 om_unlock(take); 393 return take; 394 } 395 396 // Take an ObjectMonitor from the start of the om_list_globals._free_list. 397 // Also updates om_list_globals._free_count. Returns NULL if none are 398 // available. 399 static ObjectMonitor* take_from_start_of_global_free_list() { 400 return take_from_start_of_common(&om_list_globals._free_list, 401 &om_list_globals._free_count); 402 } 403 404 // Take an ObjectMonitor from the start of a per-thread free-list. 405 // Also updates om_free_count. Returns NULL if none are available. 406 static ObjectMonitor* take_from_start_of_om_free_list(Thread* self) { 407 return take_from_start_of_common(&self->om_free_list, &self->om_free_count); 408 } 409 410 411 // =====================> Quick functions 412 413 // The quick_* forms are special fast-path variants used to improve 414 // performance. In the simplest case, a "quick_*" implementation could 415 // simply return false, in which case the caller will perform the necessary 416 // state transitions and call the slow-path form. 417 // The fast-path is designed to handle frequently arising cases in an efficient 418 // manner and is just a degenerate "optimistic" variant of the slow-path. 419 // returns true -- to indicate the call was satisfied. 420 // returns false -- to indicate the call needs the services of the slow-path. 421 // A no-loitering ordinance is in effect for code in the quick_* family 422 // operators: safepoints or indefinite blocking (blocking that might span a 423 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon 424 // entry. 425 // 426 // Consider: An interesting optimization is to have the JIT recognize the 427 // following common idiom: 428 // synchronized (someobj) { .... ; notify(); } 429 // That is, we find a notify() or notifyAll() call that immediately precedes 430 // the monitorexit operation. In that case the JIT could fuse the operations 431 // into a single notifyAndExit() runtime primitive. 432 433 bool ObjectSynchronizer::quick_notify(oopDesc* obj, Thread* self, bool all) { 434 assert(!SafepointSynchronize::is_at_safepoint(), "invariant"); 435 assert(self->is_Java_thread(), "invariant"); 436 assert(((JavaThread *) self)->thread_state() == _thread_in_Java, "invariant"); 437 NoSafepointVerifier nsv; 438 if (obj == NULL) return false; // slow-path for invalid obj 439 const markWord mark = obj->mark(); 440 441 if (mark.has_locker() && self->is_lock_owned((address)mark.locker())) { 442 // Degenerate notify 443 // stack-locked by caller so by definition the implied waitset is empty. 444 return true; 445 } 446 447 if (mark.has_monitor()) { 448 ObjectMonitor* const mon = mark.monitor(); 449 assert(mon->object() == obj, "invariant"); 450 if (mon->owner() != self) return false; // slow-path for IMS exception 451 452 if (mon->first_waiter() != NULL) { 453 // We have one or more waiters. Since this is an inflated monitor 454 // that we own, we can transfer one or more threads from the waitset 455 // to the entrylist here and now, avoiding the slow-path. 456 if (all) { 457 DTRACE_MONITOR_PROBE(notifyAll, mon, obj, self); 458 } else { 459 DTRACE_MONITOR_PROBE(notify, mon, obj, self); 460 } 461 int free_count = 0; 462 do { 463 mon->INotify(self); 464 ++free_count; 465 } while (mon->first_waiter() != NULL && all); 466 OM_PERFDATA_OP(Notifications, inc(free_count)); 467 } 468 return true; 469 } 470 471 // biased locking and any other IMS exception states take the slow-path 472 return false; 473 } 474 475 476 // The LockNode emitted directly at the synchronization site would have 477 // been too big if it were to have included support for the cases of inflated 478 // recursive enter and exit, so they go here instead. 479 // Note that we can't safely call AsyncPrintJavaStack() from within 480 // quick_enter() as our thread state remains _in_Java. 481 482 bool ObjectSynchronizer::quick_enter(oop obj, Thread* self, 483 BasicLock * lock) { 484 assert(!SafepointSynchronize::is_at_safepoint(), "invariant"); 485 assert(self->is_Java_thread(), "invariant"); 486 assert(((JavaThread *) self)->thread_state() == _thread_in_Java, "invariant"); 487 NoSafepointVerifier nsv; 488 if (obj == NULL) return false; // Need to throw NPE 489 490 const markWord mark = obj->mark(); 491 492 if (mark.has_monitor()) { 493 ObjectMonitor* const m = mark.monitor(); 494 // An async deflation can race us before we manage to make the 495 // ObjectMonitor busy by setting the owner below. If we detect 496 // that race we just bail out to the slow-path here. 497 if (m->object() == NULL) { 498 return false; 499 } 500 Thread* const owner = (Thread *) m->_owner; 501 502 // Lock contention and Transactional Lock Elision (TLE) diagnostics 503 // and observability 504 // Case: light contention possibly amenable to TLE 505 // Case: TLE inimical operations such as nested/recursive synchronization 506 507 if (owner == self) { 508 m->_recursions++; 509 return true; 510 } 511 512 // This Java Monitor is inflated so obj's header will never be 513 // displaced to this thread's BasicLock. Make the displaced header 514 // non-NULL so this BasicLock is not seen as recursive nor as 515 // being locked. We do this unconditionally so that this thread's 516 // BasicLock cannot be mis-interpreted by any stack walkers. For 517 // performance reasons, stack walkers generally first check for 518 // Biased Locking in the object's header, the second check is for 519 // stack-locking in the object's header, the third check is for 520 // recursive stack-locking in the displaced header in the BasicLock, 521 // and last are the inflated Java Monitor (ObjectMonitor) checks. 522 lock->set_displaced_header(markWord::unused_mark()); 523 524 if (owner == NULL && m->try_set_owner_from(NULL, self) == NULL) { 525 assert(m->_recursions == 0, "invariant"); 526 return true; 527 } 528 } 529 530 // Note that we could inflate in quick_enter. 531 // This is likely a useful optimization 532 // Critically, in quick_enter() we must not: 533 // -- perform bias revocation, or 534 // -- block indefinitely, or 535 // -- reach a safepoint 536 537 return false; // revert to slow-path 538 } 539 540 // ----------------------------------------------------------------------------- 541 // Monitor Enter/Exit 542 // The interpreter and compiler assembly code tries to lock using the fast path 543 // of this algorithm. Make sure to update that code if the following function is 544 // changed. The implementation is extremely sensitive to race condition. Be careful. 545 546 void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, TRAPS) { 547 if (UseBiasedLocking) { 548 if (!SafepointSynchronize::is_at_safepoint()) { 549 BiasedLocking::revoke(obj, THREAD); 550 } else { 551 BiasedLocking::revoke_at_safepoint(obj); 552 } 553 } 554 555 markWord mark = obj->mark(); 556 assert(!mark.has_bias_pattern(), "should not see bias pattern here"); 557 558 if (mark.is_neutral()) { 559 // Anticipate successful CAS -- the ST of the displaced mark must 560 // be visible <= the ST performed by the CAS. 561 lock->set_displaced_header(mark); 562 if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) { 563 return; 564 } 565 // Fall through to inflate() ... 566 } else if (mark.has_locker() && 567 THREAD->is_lock_owned((address)mark.locker())) { 568 assert(lock != mark.locker(), "must not re-lock the same lock"); 569 assert(lock != (BasicLock*)obj->mark().value(), "don't relock with same BasicLock"); 570 lock->set_displaced_header(markWord::from_pointer(NULL)); 571 return; 572 } 573 574 // The object header will never be displaced to this lock, 575 // so it does not matter what the value is, except that it 576 // must be non-zero to avoid looking like a re-entrant lock, 577 // and must not look locked either. 578 lock->set_displaced_header(markWord::unused_mark()); 579 // An async deflation can race after the inflate() call and before 580 // enter() can make the ObjectMonitor busy. enter() returns false if 581 // we have lost the race to async deflation and we simply try again. 582 while (true) { 583 ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_monitor_enter); 584 if (monitor->enter(THREAD)) { 585 return; 586 } 587 } 588 } 589 590 void ObjectSynchronizer::exit(oop object, BasicLock* lock, TRAPS) { 591 markWord mark = object->mark(); 592 // We cannot check for Biased Locking if we are racing an inflation. 593 assert(mark == markWord::INFLATING() || 594 !mark.has_bias_pattern(), "should not see bias pattern here"); 595 596 markWord dhw = lock->displaced_header(); 597 if (dhw.value() == 0) { 598 // If the displaced header is NULL, then this exit matches up with 599 // a recursive enter. No real work to do here except for diagnostics. 600 #ifndef PRODUCT 601 if (mark != markWord::INFLATING()) { 602 // Only do diagnostics if we are not racing an inflation. Simply 603 // exiting a recursive enter of a Java Monitor that is being 604 // inflated is safe; see the has_monitor() comment below. 605 assert(!mark.is_neutral(), "invariant"); 606 assert(!mark.has_locker() || 607 THREAD->is_lock_owned((address)mark.locker()), "invariant"); 608 if (mark.has_monitor()) { 609 // The BasicLock's displaced_header is marked as a recursive 610 // enter and we have an inflated Java Monitor (ObjectMonitor). 611 // This is a special case where the Java Monitor was inflated 612 // after this thread entered the stack-lock recursively. When a 613 // Java Monitor is inflated, we cannot safely walk the Java 614 // Monitor owner's stack and update the BasicLocks because a 615 // Java Monitor can be asynchronously inflated by a thread that 616 // does not own the Java Monitor. 617 ObjectMonitor* m = mark.monitor(); 618 assert(((oop)(m->object()))->mark() == mark, "invariant"); 619 assert(m->is_entered(THREAD), "invariant"); 620 } 621 } 622 #endif 623 return; 624 } 625 626 if (mark == markWord::from_pointer(lock)) { 627 // If the object is stack-locked by the current thread, try to 628 // swing the displaced header from the BasicLock back to the mark. 629 assert(dhw.is_neutral(), "invariant"); 630 if (object->cas_set_mark(dhw, mark) == mark) { 631 return; 632 } 633 } 634 635 // We have to take the slow-path of possible inflation and then exit. 636 // The ObjectMonitor* can't be async deflated until ownership is 637 // dropped inside exit() and the ObjectMonitor* must be !is_busy(). 638 ObjectMonitor* monitor = inflate(THREAD, object, inflate_cause_vm_internal); 639 monitor->exit(true, THREAD); 640 } 641 642 // ----------------------------------------------------------------------------- 643 // Class Loader support to workaround deadlocks on the class loader lock objects 644 // Also used by GC 645 // complete_exit()/reenter() are used to wait on a nested lock 646 // i.e. to give up an outer lock completely and then re-enter 647 // Used when holding nested locks - lock acquisition order: lock1 then lock2 648 // 1) complete_exit lock1 - saving recursion count 649 // 2) wait on lock2 650 // 3) when notified on lock2, unlock lock2 651 // 4) reenter lock1 with original recursion count 652 // 5) lock lock2 653 // NOTE: must use heavy weight monitor to handle complete_exit/reenter() 654 intx ObjectSynchronizer::complete_exit(Handle obj, TRAPS) { 655 if (UseBiasedLocking) { 656 BiasedLocking::revoke(obj, THREAD); 657 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 658 } 659 660 // The ObjectMonitor* can't be async deflated until ownership is 661 // dropped inside exit() and the ObjectMonitor* must be !is_busy(). 662 ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_vm_internal); 663 intptr_t ret_code = monitor->complete_exit(THREAD); 664 return ret_code; 665 } 666 667 // NOTE: must use heavy weight monitor to handle complete_exit/reenter() 668 void ObjectSynchronizer::reenter(Handle obj, intx recursions, TRAPS) { 669 if (UseBiasedLocking) { 670 BiasedLocking::revoke(obj, THREAD); 671 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 672 } 673 674 // An async deflation can race after the inflate() call and before 675 // reenter() -> enter() can make the ObjectMonitor busy. reenter() -> 676 // enter() returns false if we have lost the race to async deflation 677 // and we simply try again. 678 while (true) { 679 ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_vm_internal); 680 if (monitor->reenter(recursions, THREAD)) { 681 return; 682 } 683 } 684 } 685 686 // ----------------------------------------------------------------------------- 687 // JNI locks on java objects 688 // NOTE: must use heavy weight monitor to handle jni monitor enter 689 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) { 690 // the current locking is from JNI instead of Java code 691 if (UseBiasedLocking) { 692 BiasedLocking::revoke(obj, THREAD); 693 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 694 } 695 THREAD->set_current_pending_monitor_is_from_java(false); 696 // An async deflation can race after the inflate() call and before 697 // enter() can make the ObjectMonitor busy. enter() returns false if 698 // we have lost the race to async deflation and we simply try again. 699 while (true) { 700 ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_jni_enter); 701 if (monitor->enter(THREAD)) { 702 break; 703 } 704 } 705 THREAD->set_current_pending_monitor_is_from_java(true); 706 } 707 708 // NOTE: must use heavy weight monitor to handle jni monitor exit 709 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) { 710 if (UseBiasedLocking) { 711 Handle h_obj(THREAD, obj); 712 BiasedLocking::revoke(h_obj, THREAD); 713 obj = h_obj(); 714 } 715 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 716 717 // The ObjectMonitor* can't be async deflated until ownership is 718 // dropped inside exit() and the ObjectMonitor* must be !is_busy(). 719 ObjectMonitor* monitor = inflate(THREAD, obj, inflate_cause_jni_exit); 720 // If this thread has locked the object, exit the monitor. We 721 // intentionally do not use CHECK here because we must exit the 722 // monitor even if an exception is pending. 723 if (monitor->check_owner(THREAD)) { 724 monitor->exit(true, THREAD); 725 } 726 } 727 728 // ----------------------------------------------------------------------------- 729 // Internal VM locks on java objects 730 // standard constructor, allows locking failures 731 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool do_lock) { 732 _dolock = do_lock; 733 _thread = thread; 734 _thread->check_for_valid_safepoint_state(); 735 _obj = obj; 736 737 if (_dolock) { 738 ObjectSynchronizer::enter(_obj, &_lock, _thread); 739 } 740 } 741 742 ObjectLocker::~ObjectLocker() { 743 if (_dolock) { 744 ObjectSynchronizer::exit(_obj(), &_lock, _thread); 745 } 746 } 747 748 749 // ----------------------------------------------------------------------------- 750 // Wait/Notify/NotifyAll 751 // NOTE: must use heavy weight monitor to handle wait() 752 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) { 753 if (UseBiasedLocking) { 754 BiasedLocking::revoke(obj, THREAD); 755 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 756 } 757 if (millis < 0) { 758 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); 759 } 760 // The ObjectMonitor* can't be async deflated because the _waiters 761 // field is incremented before ownership is dropped and decremented 762 // after ownership is regained. 763 ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_wait); 764 765 DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis); 766 monitor->wait(millis, true, THREAD); 767 768 // This dummy call is in place to get around dtrace bug 6254741. Once 769 // that's fixed we can uncomment the following line, remove the call 770 // and change this function back into a "void" func. 771 // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD); 772 int ret_code = dtrace_waited_probe(monitor, obj, THREAD); 773 return ret_code; 774 } 775 776 void ObjectSynchronizer::wait_uninterruptibly(Handle obj, jlong millis, TRAPS) { 777 if (UseBiasedLocking) { 778 BiasedLocking::revoke(obj, THREAD); 779 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 780 } 781 if (millis < 0) { 782 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); 783 } 784 // The ObjectMonitor* can't be async deflated because the _waiters 785 // field is incremented before ownership is dropped and decremented 786 // after ownership is regained. 787 ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_wait); 788 monitor->wait(millis, false, THREAD); 789 } 790 791 void ObjectSynchronizer::notify(Handle obj, TRAPS) { 792 if (UseBiasedLocking) { 793 BiasedLocking::revoke(obj, THREAD); 794 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 795 } 796 797 markWord mark = obj->mark(); 798 if (mark.has_locker() && THREAD->is_lock_owned((address)mark.locker())) { 799 return; 800 } 801 // The ObjectMonitor* can't be async deflated until ownership is 802 // dropped by the calling thread. 803 ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_notify); 804 monitor->notify(THREAD); 805 } 806 807 // NOTE: see comment of notify() 808 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) { 809 if (UseBiasedLocking) { 810 BiasedLocking::revoke(obj, THREAD); 811 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 812 } 813 814 markWord mark = obj->mark(); 815 if (mark.has_locker() && THREAD->is_lock_owned((address)mark.locker())) { 816 return; 817 } 818 // The ObjectMonitor* can't be async deflated until ownership is 819 // dropped by the calling thread. 820 ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_notify); 821 monitor->notifyAll(THREAD); 822 } 823 824 // ----------------------------------------------------------------------------- 825 // Hash Code handling 826 // 827 // Performance concern: 828 // OrderAccess::storestore() calls release() which at one time stored 0 829 // into the global volatile OrderAccess::dummy variable. This store was 830 // unnecessary for correctness. Many threads storing into a common location 831 // causes considerable cache migration or "sloshing" on large SMP systems. 832 // As such, I avoided using OrderAccess::storestore(). In some cases 833 // OrderAccess::fence() -- which incurs local latency on the executing 834 // processor -- is a better choice as it scales on SMP systems. 835 // 836 // See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for 837 // a discussion of coherency costs. Note that all our current reference 838 // platforms provide strong ST-ST order, so the issue is moot on IA32, 839 // x64, and SPARC. 840 // 841 // As a general policy we use "volatile" to control compiler-based reordering 842 // and explicit fences (barriers) to control for architectural reordering 843 // performed by the CPU(s) or platform. 844 845 struct SharedGlobals { 846 char _pad_prefix[OM_CACHE_LINE_SIZE]; 847 // These are highly shared mostly-read variables. 848 // To avoid false-sharing they need to be the sole occupants of a cache line. 849 volatile int stw_random; 850 volatile int stw_cycle; 851 DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int) * 2); 852 // Hot RW variable -- Sequester to avoid false-sharing 853 volatile int hc_sequence; 854 DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int)); 855 }; 856 857 static SharedGlobals GVars; 858 859 static markWord read_stable_mark(oop obj) { 860 markWord mark = obj->mark(); 861 if (!mark.is_being_inflated()) { 862 return mark; // normal fast-path return 863 } 864 865 int its = 0; 866 for (;;) { 867 markWord mark = obj->mark(); 868 if (!mark.is_being_inflated()) { 869 return mark; // normal fast-path return 870 } 871 872 // The object is being inflated by some other thread. 873 // The caller of read_stable_mark() must wait for inflation to complete. 874 // Avoid live-lock 875 // TODO: consider calling SafepointSynchronize::do_call_back() while 876 // spinning to see if there's a safepoint pending. If so, immediately 877 // yielding or blocking would be appropriate. Avoid spinning while 878 // there is a safepoint pending. 879 // TODO: add inflation contention performance counters. 880 // TODO: restrict the aggregate number of spinners. 881 882 ++its; 883 if (its > 10000 || !os::is_MP()) { 884 if (its & 1) { 885 os::naked_yield(); 886 } else { 887 // Note that the following code attenuates the livelock problem but is not 888 // a complete remedy. A more complete solution would require that the inflating 889 // thread hold the associated inflation lock. The following code simply restricts 890 // the number of spinners to at most one. We'll have N-2 threads blocked 891 // on the inflationlock, 1 thread holding the inflation lock and using 892 // a yield/park strategy, and 1 thread in the midst of inflation. 893 // A more refined approach would be to change the encoding of INFLATING 894 // to allow encapsulation of a native thread pointer. Threads waiting for 895 // inflation to complete would use CAS to push themselves onto a singly linked 896 // list rooted at the markword. Once enqueued, they'd loop, checking a per-thread flag 897 // and calling park(). When inflation was complete the thread that accomplished inflation 898 // would detach the list and set the markword to inflated with a single CAS and 899 // then for each thread on the list, set the flag and unpark() the thread. 900 // This is conceptually similar to muxAcquire-muxRelease, except that muxRelease 901 // wakes at most one thread whereas we need to wake the entire list. 902 int ix = (cast_from_oop<intptr_t>(obj) >> 5) & (NINFLATIONLOCKS-1); 903 int YieldThenBlock = 0; 904 assert(ix >= 0 && ix < NINFLATIONLOCKS, "invariant"); 905 assert((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant"); 906 Thread::muxAcquire(gInflationLocks + ix, "gInflationLock"); 907 while (obj->mark() == markWord::INFLATING()) { 908 // Beware: NakedYield() is advisory and has almost no effect on some platforms 909 // so we periodically call self->_ParkEvent->park(1). 910 // We use a mixed spin/yield/block mechanism. 911 if ((YieldThenBlock++) >= 16) { 912 Thread::current()->_ParkEvent->park(1); 913 } else { 914 os::naked_yield(); 915 } 916 } 917 Thread::muxRelease(gInflationLocks + ix); 918 } 919 } else { 920 SpinPause(); // SMP-polite spinning 921 } 922 } 923 } 924 925 // hashCode() generation : 926 // 927 // Possibilities: 928 // * MD5Digest of {obj,stw_random} 929 // * CRC32 of {obj,stw_random} or any linear-feedback shift register function. 930 // * A DES- or AES-style SBox[] mechanism 931 // * One of the Phi-based schemes, such as: 932 // 2654435761 = 2^32 * Phi (golden ratio) 933 // HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ; 934 // * A variation of Marsaglia's shift-xor RNG scheme. 935 // * (obj ^ stw_random) is appealing, but can result 936 // in undesirable regularity in the hashCode values of adjacent objects 937 // (objects allocated back-to-back, in particular). This could potentially 938 // result in hashtable collisions and reduced hashtable efficiency. 939 // There are simple ways to "diffuse" the middle address bits over the 940 // generated hashCode values: 941 942 static inline intptr_t get_next_hash(Thread* self, oop obj) { 943 intptr_t value = 0; 944 if (hashCode == 0) { 945 // This form uses global Park-Miller RNG. 946 // On MP system we'll have lots of RW access to a global, so the 947 // mechanism induces lots of coherency traffic. 948 value = os::random(); 949 } else if (hashCode == 1) { 950 // This variation has the property of being stable (idempotent) 951 // between STW operations. This can be useful in some of the 1-0 952 // synchronization schemes. 953 intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3; 954 value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random; 955 } else if (hashCode == 2) { 956 value = 1; // for sensitivity testing 957 } else if (hashCode == 3) { 958 value = ++GVars.hc_sequence; 959 } else if (hashCode == 4) { 960 value = cast_from_oop<intptr_t>(obj); 961 } else { 962 // Marsaglia's xor-shift scheme with thread-specific state 963 // This is probably the best overall implementation -- we'll 964 // likely make this the default in future releases. 965 unsigned t = self->_hashStateX; 966 t ^= (t << 11); 967 self->_hashStateX = self->_hashStateY; 968 self->_hashStateY = self->_hashStateZ; 969 self->_hashStateZ = self->_hashStateW; 970 unsigned v = self->_hashStateW; 971 v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)); 972 self->_hashStateW = v; 973 value = v; 974 } 975 976 value &= markWord::hash_mask; 977 if (value == 0) value = 0xBAD; 978 assert(value != markWord::no_hash, "invariant"); 979 return value; 980 } 981 982 intptr_t ObjectSynchronizer::FastHashCode(Thread* self, oop obj) { 983 if (UseBiasedLocking) { 984 // NOTE: many places throughout the JVM do not expect a safepoint 985 // to be taken here. However, we only ever bias Java instances and all 986 // of the call sites of identity_hash that might revoke biases have 987 // been checked to make sure they can handle a safepoint. The 988 // added check of the bias pattern is to avoid useless calls to 989 // thread-local storage. 990 if (obj->mark().has_bias_pattern()) { 991 // Handle for oop obj in case of STW safepoint 992 Handle hobj(self, obj); 993 // Relaxing assertion for bug 6320749. 994 assert(Universe::verify_in_progress() || 995 !SafepointSynchronize::is_at_safepoint(), 996 "biases should not be seen by VM thread here"); 997 BiasedLocking::revoke(hobj, JavaThread::current()); 998 obj = hobj(); 999 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 1000 } 1001 } 1002 1003 // hashCode() is a heap mutator ... 1004 // Relaxing assertion for bug 6320749. 1005 assert(Universe::verify_in_progress() || DumpSharedSpaces || 1006 !SafepointSynchronize::is_at_safepoint(), "invariant"); 1007 assert(Universe::verify_in_progress() || DumpSharedSpaces || 1008 self->is_Java_thread() , "invariant"); 1009 assert(Universe::verify_in_progress() || DumpSharedSpaces || 1010 ((JavaThread *)self)->thread_state() != _thread_blocked, "invariant"); 1011 1012 while (true) { 1013 ObjectMonitor* monitor = NULL; 1014 markWord temp, test; 1015 intptr_t hash; 1016 markWord mark = read_stable_mark(obj); 1017 1018 // object should remain ineligible for biased locking 1019 assert(!mark.has_bias_pattern(), "invariant"); 1020 1021 if (mark.is_neutral()) { // if this is a normal header 1022 hash = mark.hash(); 1023 if (hash != 0) { // if it has a hash, just return it 1024 return hash; 1025 } 1026 hash = get_next_hash(self, obj); // get a new hash 1027 temp = mark.copy_set_hash(hash); // merge the hash into header 1028 // try to install the hash 1029 test = obj->cas_set_mark(temp, mark); 1030 if (test == mark) { // if the hash was installed, return it 1031 return hash; 1032 } 1033 // Failed to install the hash. It could be that another thread 1034 // installed the hash just before our attempt or inflation has 1035 // occurred or... so we fall thru to inflate the monitor for 1036 // stability and then install the hash. 1037 } else if (mark.has_monitor()) { 1038 monitor = mark.monitor(); 1039 temp = monitor->header(); 1040 assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value()); 1041 hash = temp.hash(); 1042 if (hash != 0) { 1043 // It has a hash. 1044 1045 // Separate load of dmw/header above from the loads in 1046 // is_being_async_deflated(). 1047 if (support_IRIW_for_not_multiple_copy_atomic_cpu) { 1048 // A non-multiple copy atomic (nMCA) machine needs a bigger 1049 // hammer to separate the load above and the loads below. 1050 OrderAccess::fence(); 1051 } else { 1052 OrderAccess::loadload(); 1053 } 1054 if (monitor->is_being_async_deflated()) { 1055 // But we can't safely use the hash if we detect that async 1056 // deflation has occurred. So we attempt to restore the 1057 // header/dmw to the object's header so that we only retry 1058 // once if the deflater thread happens to be slow. 1059 monitor->install_displaced_markword_in_object(obj); 1060 continue; 1061 } 1062 return hash; 1063 } 1064 // Fall thru so we only have one place that installs the hash in 1065 // the ObjectMonitor. 1066 } else if (self->is_lock_owned((address)mark.locker())) { 1067 // This is a stack lock owned by the calling thread so fetch the 1068 // displaced markWord from the BasicLock on the stack. 1069 temp = mark.displaced_mark_helper(); 1070 assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value()); 1071 hash = temp.hash(); 1072 if (hash != 0) { // if it has a hash, just return it 1073 return hash; 1074 } 1075 // WARNING: 1076 // The displaced header in the BasicLock on a thread's stack 1077 // is strictly immutable. It CANNOT be changed in ANY cases. 1078 // So we have to inflate the stack lock into an ObjectMonitor 1079 // even if the current thread owns the lock. The BasicLock on 1080 // a thread's stack can be asynchronously read by other threads 1081 // during an inflate() call so any change to that stack memory 1082 // may not propagate to other threads correctly. 1083 } 1084 1085 // Inflate the monitor to set the hash. 1086 1087 // An async deflation can race after the inflate() call and before we 1088 // can update the ObjectMonitor's header with the hash value below. 1089 monitor = inflate(self, obj, inflate_cause_hash_code); 1090 // Load ObjectMonitor's header/dmw field and see if it has a hash. 1091 mark = monitor->header(); 1092 assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value()); 1093 hash = mark.hash(); 1094 if (hash == 0) { // if it does not have a hash 1095 hash = get_next_hash(self, obj); // get a new hash 1096 temp = mark.copy_set_hash(hash); // merge the hash into header 1097 assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value()); 1098 uintptr_t v = Atomic::cmpxchg((volatile uintptr_t*)monitor->header_addr(), mark.value(), temp.value()); 1099 test = markWord(v); 1100 if (test != mark) { 1101 // The attempt to update the ObjectMonitor's header/dmw field 1102 // did not work. This can happen if another thread managed to 1103 // merge in the hash just before our cmpxchg(). 1104 // If we add any new usages of the header/dmw field, this code 1105 // will need to be updated. 1106 hash = test.hash(); 1107 assert(test.is_neutral(), "invariant: header=" INTPTR_FORMAT, test.value()); 1108 assert(hash != 0, "should only have lost the race to a thread that set a non-zero hash"); 1109 } 1110 if (monitor->is_being_async_deflated()) { 1111 // If we detect that async deflation has occurred, then we 1112 // attempt to restore the header/dmw to the object's header 1113 // so that we only retry once if the deflater thread happens 1114 // to be slow. 1115 monitor->install_displaced_markword_in_object(obj); 1116 continue; 1117 } 1118 } 1119 // We finally get the hash. 1120 return hash; 1121 } 1122 } 1123 1124 // Deprecated -- use FastHashCode() instead. 1125 1126 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) { 1127 return FastHashCode(Thread::current(), obj()); 1128 } 1129 1130 1131 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread, 1132 Handle h_obj) { 1133 if (UseBiasedLocking) { 1134 BiasedLocking::revoke(h_obj, thread); 1135 assert(!h_obj->mark().has_bias_pattern(), "biases should be revoked by now"); 1136 } 1137 1138 assert(thread == JavaThread::current(), "Can only be called on current thread"); 1139 oop obj = h_obj(); 1140 1141 markWord mark = read_stable_mark(obj); 1142 1143 // Uncontended case, header points to stack 1144 if (mark.has_locker()) { 1145 return thread->is_lock_owned((address)mark.locker()); 1146 } 1147 // Contended case, header points to ObjectMonitor (tagged pointer) 1148 if (mark.has_monitor()) { 1149 // The first stage of async deflation does not affect any field 1150 // used by this comparison so the ObjectMonitor* is usable here. 1151 ObjectMonitor* monitor = mark.monitor(); 1152 return monitor->is_entered(thread) != 0; 1153 } 1154 // Unlocked case, header in place 1155 assert(mark.is_neutral(), "sanity check"); 1156 return false; 1157 } 1158 1159 // Be aware of this method could revoke bias of the lock object. 1160 // This method queries the ownership of the lock handle specified by 'h_obj'. 1161 // If the current thread owns the lock, it returns owner_self. If no 1162 // thread owns the lock, it returns owner_none. Otherwise, it will return 1163 // owner_other. 1164 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership 1165 (JavaThread *self, Handle h_obj) { 1166 // The caller must beware this method can revoke bias, and 1167 // revocation can result in a safepoint. 1168 assert(!SafepointSynchronize::is_at_safepoint(), "invariant"); 1169 assert(self->thread_state() != _thread_blocked, "invariant"); 1170 1171 // Possible mark states: neutral, biased, stack-locked, inflated 1172 1173 if (UseBiasedLocking && h_obj()->mark().has_bias_pattern()) { 1174 // CASE: biased 1175 BiasedLocking::revoke(h_obj, self); 1176 assert(!h_obj->mark().has_bias_pattern(), 1177 "biases should be revoked by now"); 1178 } 1179 1180 assert(self == JavaThread::current(), "Can only be called on current thread"); 1181 oop obj = h_obj(); 1182 markWord mark = read_stable_mark(obj); 1183 1184 // CASE: stack-locked. Mark points to a BasicLock on the owner's stack. 1185 if (mark.has_locker()) { 1186 return self->is_lock_owned((address)mark.locker()) ? 1187 owner_self : owner_other; 1188 } 1189 1190 // CASE: inflated. Mark (tagged pointer) points to an ObjectMonitor. 1191 if (mark.has_monitor()) { 1192 // The first stage of async deflation does not affect any field 1193 // used by this comparison so the ObjectMonitor* is usable here. 1194 ObjectMonitor* monitor = mark.monitor(); 1195 void* owner = monitor->owner(); 1196 if (owner == NULL) return owner_none; 1197 return (owner == self || 1198 self->is_lock_owned((address)owner)) ? owner_self : owner_other; 1199 } 1200 1201 // CASE: neutral 1202 assert(mark.is_neutral(), "sanity check"); 1203 return owner_none; // it's unlocked 1204 } 1205 1206 // FIXME: jvmti should call this 1207 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) { 1208 if (UseBiasedLocking) { 1209 if (SafepointSynchronize::is_at_safepoint()) { 1210 BiasedLocking::revoke_at_safepoint(h_obj); 1211 } else { 1212 BiasedLocking::revoke(h_obj, JavaThread::current()); 1213 } 1214 assert(!h_obj->mark().has_bias_pattern(), "biases should be revoked by now"); 1215 } 1216 1217 oop obj = h_obj(); 1218 address owner = NULL; 1219 1220 markWord mark = read_stable_mark(obj); 1221 1222 // Uncontended case, header points to stack 1223 if (mark.has_locker()) { 1224 owner = (address) mark.locker(); 1225 } 1226 1227 // Contended case, header points to ObjectMonitor (tagged pointer) 1228 else if (mark.has_monitor()) { 1229 // The first stage of async deflation does not affect any field 1230 // used by this comparison so the ObjectMonitor* is usable here. 1231 ObjectMonitor* monitor = mark.monitor(); 1232 assert(monitor != NULL, "monitor should be non-null"); 1233 owner = (address) monitor->owner(); 1234 } 1235 1236 if (owner != NULL) { 1237 // owning_thread_from_monitor_owner() may also return NULL here 1238 return Threads::owning_thread_from_monitor_owner(t_list, owner); 1239 } 1240 1241 // Unlocked case, header in place 1242 // Cannot have assertion since this object may have been 1243 // locked by another thread when reaching here. 1244 // assert(mark.is_neutral(), "sanity check"); 1245 1246 return NULL; 1247 } 1248 1249 // Visitors ... 1250 1251 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) { 1252 PaddedObjectMonitor* block = Atomic::load(&g_block_list); 1253 while (block != NULL) { 1254 assert(block->object() == CHAINMARKER, "must be a block header"); 1255 for (int i = _BLOCKSIZE - 1; i > 0; i--) { 1256 ObjectMonitor* mid = (ObjectMonitor *)(block + i); 1257 if (mid->object() != NULL) { 1258 // Only process with closure if the object is set. 1259 1260 // monitors_iterate() is only called at a safepoint or when the 1261 // target thread is suspended or when the target thread is 1262 // operating on itself. The current closures in use today are 1263 // only interested in an owned ObjectMonitor and ownership 1264 // cannot be dropped under the calling contexts so the 1265 // ObjectMonitor cannot be async deflated. 1266 closure->do_monitor(mid); 1267 } 1268 } 1269 // unmarked_next() is not needed with g_block_list (no locking 1270 // used with block linkage _next_om fields). 1271 block = (PaddedObjectMonitor*)block->next_om(); 1272 } 1273 } 1274 1275 static bool monitors_used_above_threshold() { 1276 int population = Atomic::load(&om_list_globals._population); 1277 if (population == 0) { 1278 return false; 1279 } 1280 if (MonitorUsedDeflationThreshold > 0) { 1281 int monitors_used = population - Atomic::load(&om_list_globals._free_count) - 1282 Atomic::load(&om_list_globals._wait_count); 1283 int monitor_usage = (monitors_used * 100LL) / population; 1284 return monitor_usage > MonitorUsedDeflationThreshold; 1285 } 1286 return false; 1287 } 1288 1289 bool ObjectSynchronizer::is_async_deflation_needed() { 1290 if (is_async_deflation_requested()) { 1291 // Async deflation request. 1292 return true; 1293 } 1294 if (AsyncDeflationInterval > 0 && 1295 time_since_last_async_deflation_ms() > AsyncDeflationInterval && 1296 monitors_used_above_threshold()) { 1297 // It's been longer than our specified deflate interval and there 1298 // are too many monitors in use. We don't deflate more frequently 1299 // than AsyncDeflationInterval (unless is_async_deflation_requested) 1300 // in order to not swamp the ServiceThread. 1301 return true; 1302 } 1303 return false; 1304 } 1305 1306 bool ObjectSynchronizer::request_deflate_idle_monitors() { 1307 bool is_JavaThread = Thread::current()->is_Java_thread(); 1308 bool ret_code = false; 1309 1310 jlong last_time = last_async_deflation_time_ns(); 1311 set_is_async_deflation_requested(true); 1312 { 1313 MonitorLocker ml(Service_lock, Mutex::_no_safepoint_check_flag); 1314 ml.notify_all(); 1315 } 1316 const int N_CHECKS = 5; 1317 for (int i = 0; i < N_CHECKS; i++) { // sleep for at most 5 seconds 1318 if (last_async_deflation_time_ns() > last_time) { 1319 log_info(monitorinflation)("Async Deflation happened after %d check(s).", i); 1320 ret_code = true; 1321 break; 1322 } 1323 if (is_JavaThread) { 1324 // JavaThread has to honor the blocking protocol. 1325 ThreadBlockInVM tbivm(JavaThread::current()); 1326 os::naked_short_sleep(999); // sleep for almost 1 second 1327 } else { 1328 os::naked_short_sleep(999); // sleep for almost 1 second 1329 } 1330 } 1331 if (!ret_code) { 1332 log_info(monitorinflation)("Async Deflation DID NOT happen after %d checks.", N_CHECKS); 1333 } 1334 1335 return ret_code; 1336 } 1337 1338 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() { 1339 return (os::javaTimeNanos() - last_async_deflation_time_ns()) / (NANOUNITS / MILLIUNITS); 1340 } 1341 1342 void ObjectSynchronizer::oops_do(OopClosure* f) { 1343 // We only scan the global used list here (for moribund threads), and 1344 // the thread-local monitors in Thread::oops_do(). 1345 global_used_oops_do(f); 1346 } 1347 1348 void ObjectSynchronizer::global_used_oops_do(OopClosure* f) { 1349 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1350 list_oops_do(Atomic::load(&om_list_globals._in_use_list), f); 1351 } 1352 1353 void ObjectSynchronizer::thread_local_used_oops_do(Thread* thread, OopClosure* f) { 1354 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1355 list_oops_do(thread->om_in_use_list, f); 1356 } 1357 1358 void ObjectSynchronizer::list_oops_do(ObjectMonitor* list, OopClosure* f) { 1359 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1360 // The oops_do() phase does not overlap with monitor deflation 1361 // so no need to lock ObjectMonitors for the list traversal. 1362 for (ObjectMonitor* mid = list; mid != NULL; mid = unmarked_next(mid)) { 1363 if (mid->object() != NULL) { 1364 f->do_oop((oop*)mid->object_addr()); 1365 } 1366 } 1367 } 1368 1369 1370 // ----------------------------------------------------------------------------- 1371 // ObjectMonitor Lifecycle 1372 // ----------------------- 1373 // Inflation unlinks monitors from om_list_globals._free_list or a per-thread 1374 // free list and associates them with objects. Async deflation disassociates 1375 // idle monitors from objects. Such scavenged monitors are returned to the 1376 // om_list_globals._free_list. 1377 // 1378 // ObjectMonitors reside in type-stable memory (TSM) and are immortal. 1379 // 1380 // Lifecycle: 1381 // -- unassigned and on the om_list_globals._free_list 1382 // -- unassigned and on a per-thread free list 1383 // -- assigned to an object. The object is inflated and the mark refers 1384 // to the ObjectMonitor. 1385 1386 ObjectMonitor* ObjectSynchronizer::om_alloc(Thread* self) { 1387 // A large MAXPRIVATE value reduces both list lock contention 1388 // and list coherency traffic, but also tends to increase the 1389 // number of ObjectMonitors in circulation as well as the 1390 // scavenge costs. As usual, we lean toward time in space-time 1391 // tradeoffs. 1392 const int MAXPRIVATE = 1024; 1393 NoSafepointVerifier nsv; 1394 1395 for (;;) { 1396 ObjectMonitor* m; 1397 1398 // 1: try to allocate from the thread's local om_free_list. 1399 // Threads will attempt to allocate first from their local list, then 1400 // from the global list, and only after those attempts fail will the 1401 // thread attempt to instantiate new monitors. Thread-local free lists 1402 // improve allocation latency, as well as reducing coherency traffic 1403 // on the shared global list. 1404 m = take_from_start_of_om_free_list(self); 1405 if (m != NULL) { 1406 guarantee(m->object() == NULL, "invariant"); 1407 m->set_allocation_state(ObjectMonitor::New); 1408 prepend_to_om_in_use_list(self, m); 1409 return m; 1410 } 1411 1412 // 2: try to allocate from the global om_list_globals._free_list 1413 // If we're using thread-local free lists then try 1414 // to reprovision the caller's free list. 1415 if (Atomic::load(&om_list_globals._free_list) != NULL) { 1416 // Reprovision the thread's om_free_list. 1417 // Use bulk transfers to reduce the allocation rate and heat 1418 // on various locks. 1419 for (int i = self->om_free_provision; --i >= 0;) { 1420 ObjectMonitor* take = take_from_start_of_global_free_list(); 1421 if (take == NULL) { 1422 break; // No more are available. 1423 } 1424 guarantee(take->object() == NULL, "invariant"); 1425 // We allowed 3 field values to linger during async deflation. 1426 // Clear or restore them as appropriate. 1427 take->set_header(markWord::zero()); 1428 // DEFLATER_MARKER is the only non-NULL value we should see here. 1429 take->try_set_owner_from(DEFLATER_MARKER, NULL); 1430 if (take->contentions() < 0) { 1431 // Add back max_jint to restore the contentions field to its 1432 // proper value. 1433 take->add_to_contentions(max_jint); 1434 1435 #ifdef ASSERT 1436 jint l_contentions = take->contentions(); 1437 assert(l_contentions >= 0, "must not be negative: l_contentions=%d, contentions=%d", 1438 l_contentions, take->contentions()); 1439 #endif 1440 } 1441 take->Recycle(); 1442 // Since we're taking from the global free-list, take must be Free. 1443 // om_release() also sets the allocation state to Free because it 1444 // is called from other code paths. 1445 assert(take->is_free(), "invariant"); 1446 om_release(self, take, false); 1447 } 1448 self->om_free_provision += 1 + (self->om_free_provision / 2); 1449 if (self->om_free_provision > MAXPRIVATE) self->om_free_provision = MAXPRIVATE; 1450 continue; 1451 } 1452 1453 // 3: allocate a block of new ObjectMonitors 1454 // Both the local and global free lists are empty -- resort to malloc(). 1455 // In the current implementation ObjectMonitors are TSM - immortal. 1456 // Ideally, we'd write "new ObjectMonitor[_BLOCKSIZE], but we want 1457 // each ObjectMonitor to start at the beginning of a cache line, 1458 // so we use align_up(). 1459 // A better solution would be to use C++ placement-new. 1460 // BEWARE: As it stands currently, we don't run the ctors! 1461 assert(_BLOCKSIZE > 1, "invariant"); 1462 size_t neededsize = sizeof(PaddedObjectMonitor) * _BLOCKSIZE; 1463 PaddedObjectMonitor* temp; 1464 size_t aligned_size = neededsize + (OM_CACHE_LINE_SIZE - 1); 1465 void* real_malloc_addr = NEW_C_HEAP_ARRAY(char, aligned_size, mtInternal); 1466 temp = (PaddedObjectMonitor*)align_up(real_malloc_addr, OM_CACHE_LINE_SIZE); 1467 (void)memset((void *) temp, 0, neededsize); 1468 1469 // Format the block. 1470 // initialize the linked list, each monitor points to its next 1471 // forming the single linked free list, the very first monitor 1472 // will points to next block, which forms the block list. 1473 // The trick of using the 1st element in the block as g_block_list 1474 // linkage should be reconsidered. A better implementation would 1475 // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; } 1476 1477 for (int i = 1; i < _BLOCKSIZE; i++) { 1478 temp[i].set_next_om((ObjectMonitor*)&temp[i + 1]); 1479 assert(temp[i].is_free(), "invariant"); 1480 } 1481 1482 // terminate the last monitor as the end of list 1483 temp[_BLOCKSIZE - 1].set_next_om((ObjectMonitor*)NULL); 1484 1485 // Element [0] is reserved for global list linkage 1486 temp[0].set_object(CHAINMARKER); 1487 1488 // Consider carving out this thread's current request from the 1489 // block in hand. This avoids some lock traffic and redundant 1490 // list activity. 1491 1492 prepend_block_to_lists(temp); 1493 } 1494 } 1495 1496 // Place "m" on the caller's private per-thread om_free_list. 1497 // In practice there's no need to clamp or limit the number of 1498 // monitors on a thread's om_free_list as the only non-allocation time 1499 // we'll call om_release() is to return a monitor to the free list after 1500 // a CAS attempt failed. This doesn't allow unbounded #s of monitors to 1501 // accumulate on a thread's free list. 1502 // 1503 // Key constraint: all ObjectMonitors on a thread's free list and the global 1504 // free list must have their object field set to null. This prevents the 1505 // scavenger -- deflate_monitor_list_using_JT() -- from reclaiming them 1506 // while we are trying to release them. 1507 1508 void ObjectSynchronizer::om_release(Thread* self, ObjectMonitor* m, 1509 bool from_per_thread_alloc) { 1510 guarantee(m->header().value() == 0, "invariant"); 1511 guarantee(m->object() == NULL, "invariant"); 1512 NoSafepointVerifier nsv; 1513 1514 if ((m->is_busy() | m->_recursions) != 0) { 1515 stringStream ss; 1516 fatal("freeing in-use monitor: %s, recursions=" INTX_FORMAT, 1517 m->is_busy_to_string(&ss), m->_recursions); 1518 } 1519 m->set_allocation_state(ObjectMonitor::Free); 1520 // _next_om is used for both per-thread in-use and free lists so 1521 // we have to remove 'm' from the in-use list first (as needed). 1522 if (from_per_thread_alloc) { 1523 // Need to remove 'm' from om_in_use_list. 1524 ObjectMonitor* mid = NULL; 1525 ObjectMonitor* next = NULL; 1526 1527 // This list walk can race with another list walker or with async 1528 // deflation so we have to worry about an ObjectMonitor being 1529 // removed from this list while we are walking it. 1530 1531 // Lock the list head to avoid racing with another list walker 1532 // or with async deflation. 1533 if ((mid = get_list_head_locked(&self->om_in_use_list)) == NULL) { 1534 fatal("thread=" INTPTR_FORMAT " in-use list must not be empty.", p2i(self)); 1535 } 1536 next = unmarked_next(mid); 1537 if (m == mid) { 1538 // First special case: 1539 // 'm' matches mid, is the list head and is locked. Switch the list 1540 // head to next which unlocks the list head, but leaves the extracted 1541 // mid locked: 1542 Atomic::store(&self->om_in_use_list, next); 1543 } else if (m == next) { 1544 // Second special case: 1545 // 'm' matches next after the list head and we already have the list 1546 // head locked so set mid to what we are extracting: 1547 mid = next; 1548 // Lock mid to prevent races with a list walker or an async 1549 // deflater thread that's ahead of us. The locked list head 1550 // prevents races from behind us. 1551 om_lock(mid); 1552 // Update next to what follows mid (if anything): 1553 next = unmarked_next(mid); 1554 // Switch next after the list head to new next which unlocks the 1555 // list head, but leaves the extracted mid locked: 1556 self->om_in_use_list->set_next_om(next); 1557 } else { 1558 // We have to search the list to find 'm'. 1559 guarantee(next != NULL, "thread=" INTPTR_FORMAT ": om_in_use_list=" INTPTR_FORMAT 1560 " is too short.", p2i(self), p2i(self->om_in_use_list)); 1561 // Our starting anchor is next after the list head which is the 1562 // last ObjectMonitor we checked: 1563 ObjectMonitor* anchor = next; 1564 // Lock anchor to prevent races with a list walker or an async 1565 // deflater thread that's ahead of us. The locked list head 1566 // prevents races from behind us. 1567 om_lock(anchor); 1568 om_unlock(mid); // Unlock the list head now that anchor is locked. 1569 while ((mid = unmarked_next(anchor)) != NULL) { 1570 if (m == mid) { 1571 // We found 'm' on the per-thread in-use list so extract it. 1572 // Update next to what follows mid (if anything): 1573 next = unmarked_next(mid); 1574 // Switch next after the anchor to new next which unlocks the 1575 // anchor, but leaves the extracted mid locked: 1576 anchor->set_next_om(next); 1577 break; 1578 } else { 1579 // Lock the next anchor to prevent races with a list walker 1580 // or an async deflater thread that's ahead of us. The locked 1581 // current anchor prevents races from behind us. 1582 om_lock(mid); 1583 // Unlock current anchor now that next anchor is locked: 1584 om_unlock(anchor); 1585 anchor = mid; // Advance to new anchor and try again. 1586 } 1587 } 1588 } 1589 1590 if (mid == NULL) { 1591 // Reached end of the list and didn't find 'm' so: 1592 fatal("thread=" INTPTR_FORMAT " must find m=" INTPTR_FORMAT "on om_in_use_list=" 1593 INTPTR_FORMAT, p2i(self), p2i(m), p2i(self->om_in_use_list)); 1594 } 1595 1596 // At this point mid is disconnected from the in-use list so 1597 // its lock no longer has any effects on the in-use list. 1598 Atomic::dec(&self->om_in_use_count); 1599 // Unlock mid, but leave the next value for any lagging list 1600 // walkers. It will get cleaned up when mid is prepended to 1601 // the thread's free list: 1602 om_unlock(mid); 1603 } 1604 1605 prepend_to_om_free_list(self, m); 1606 guarantee(m->is_free(), "invariant"); 1607 } 1608 1609 // Return ObjectMonitors on a moribund thread's free and in-use 1610 // lists to the appropriate global lists. The ObjectMonitors on the 1611 // per-thread in-use list may still be in use by other threads. 1612 // 1613 // We currently call om_flush() from Threads::remove() before the 1614 // thread has been excised from the thread list and is no longer a 1615 // mutator. In particular, this ensures that the thread's in-use 1616 // monitors are scanned by a GC safepoint, either via Thread::oops_do() 1617 // (before om_flush() is called) or via ObjectSynchronizer::oops_do() 1618 // (after om_flush() is called). 1619 // 1620 // deflate_global_idle_monitors_using_JT() and 1621 // deflate_per_thread_idle_monitors_using_JT() (in another thread) can 1622 // run at the same time as om_flush() so we have to follow a careful 1623 // protocol to prevent list corruption. 1624 1625 void ObjectSynchronizer::om_flush(Thread* self) { 1626 // Process the per-thread in-use list first to be consistent. 1627 int in_use_count = 0; 1628 ObjectMonitor* in_use_list = NULL; 1629 ObjectMonitor* in_use_tail = NULL; 1630 NoSafepointVerifier nsv; 1631 1632 // This function can race with a list walker or with an async 1633 // deflater thread so we lock the list head to prevent confusion. 1634 // An async deflater thread checks to see if the target thread 1635 // is exiting, but if it has made it past that check before we 1636 // started exiting, then it is racing to get to the in-use list. 1637 if ((in_use_list = get_list_head_locked(&self->om_in_use_list)) != NULL) { 1638 // At this point, we have locked the in-use list head so a racing 1639 // thread cannot come in after us. However, a racing thread could 1640 // be ahead of us; we'll detect that and delay to let it finish. 1641 // 1642 // The thread is going away, however the ObjectMonitors on the 1643 // om_in_use_list may still be in-use by other threads. Link 1644 // them to in_use_tail, which will be linked into the global 1645 // in-use list (om_list_globals._in_use_list) below. 1646 // 1647 // Account for the in-use list head before the loop since it is 1648 // already locked (by this thread): 1649 in_use_tail = in_use_list; 1650 in_use_count++; 1651 for (ObjectMonitor* cur_om = unmarked_next(in_use_list); cur_om != NULL;) { 1652 if (is_locked(cur_om)) { 1653 // cur_om is locked so there must be a racing walker or async 1654 // deflater thread ahead of us so we'll give it a chance to finish. 1655 while (is_locked(cur_om)) { 1656 os::naked_short_sleep(1); 1657 } 1658 // Refetch the possibly changed next field and try again. 1659 cur_om = unmarked_next(in_use_tail); 1660 continue; 1661 } 1662 if (cur_om->object() == NULL) { 1663 // cur_om was deflated and the object ref was cleared while it 1664 // was locked. We happened to see it just after it was unlocked 1665 // (and added to the free list). Refetch the possibly changed 1666 // next field and try again. 1667 cur_om = unmarked_next(in_use_tail); 1668 continue; 1669 } 1670 in_use_tail = cur_om; 1671 in_use_count++; 1672 cur_om = unmarked_next(cur_om); 1673 } 1674 guarantee(in_use_tail != NULL, "invariant"); 1675 #ifdef ASSERT 1676 int l_om_in_use_count = Atomic::load(&self->om_in_use_count); 1677 assert(l_om_in_use_count == in_use_count, "in-use counts don't match: " 1678 "l_om_in_use_count=%d, in_use_count=%d", l_om_in_use_count, in_use_count); 1679 #endif 1680 Atomic::store(&self->om_in_use_count, 0); 1681 // Clear the in-use list head (which also unlocks it): 1682 Atomic::store(&self->om_in_use_list, (ObjectMonitor*)NULL); 1683 om_unlock(in_use_list); 1684 } 1685 1686 int free_count = 0; 1687 ObjectMonitor* free_list = NULL; 1688 ObjectMonitor* free_tail = NULL; 1689 // This function can race with a list walker thread so we lock the 1690 // list head to prevent confusion. 1691 if ((free_list = get_list_head_locked(&self->om_free_list)) != NULL) { 1692 // At this point, we have locked the free list head so a racing 1693 // thread cannot come in after us. However, a racing thread could 1694 // be ahead of us; we'll detect that and delay to let it finish. 1695 // 1696 // The thread is going away. Set 'free_tail' to the last per-thread free 1697 // monitor which will be linked to om_list_globals._free_list below. 1698 // 1699 // Account for the free list head before the loop since it is 1700 // already locked (by this thread): 1701 free_tail = free_list; 1702 free_count++; 1703 for (ObjectMonitor* s = unmarked_next(free_list); s != NULL; s = unmarked_next(s)) { 1704 if (is_locked(s)) { 1705 // s is locked so there must be a racing walker thread ahead 1706 // of us so we'll give it a chance to finish. 1707 while (is_locked(s)) { 1708 os::naked_short_sleep(1); 1709 } 1710 } 1711 free_tail = s; 1712 free_count++; 1713 guarantee(s->object() == NULL, "invariant"); 1714 if (s->is_busy()) { 1715 stringStream ss; 1716 fatal("must be !is_busy: %s", s->is_busy_to_string(&ss)); 1717 } 1718 } 1719 guarantee(free_tail != NULL, "invariant"); 1720 #ifdef ASSERT 1721 int l_om_free_count = Atomic::load(&self->om_free_count); 1722 assert(l_om_free_count == free_count, "free counts don't match: " 1723 "l_om_free_count=%d, free_count=%d", l_om_free_count, free_count); 1724 #endif 1725 Atomic::store(&self->om_free_count, 0); 1726 Atomic::store(&self->om_free_list, (ObjectMonitor*)NULL); 1727 om_unlock(free_list); 1728 } 1729 1730 if (free_tail != NULL) { 1731 prepend_list_to_global_free_list(free_list, free_tail, free_count); 1732 } 1733 1734 if (in_use_tail != NULL) { 1735 prepend_list_to_global_in_use_list(in_use_list, in_use_tail, in_use_count); 1736 } 1737 1738 LogStreamHandle(Debug, monitorinflation) lsh_debug; 1739 LogStreamHandle(Info, monitorinflation) lsh_info; 1740 LogStream* ls = NULL; 1741 if (log_is_enabled(Debug, monitorinflation)) { 1742 ls = &lsh_debug; 1743 } else if ((free_count != 0 || in_use_count != 0) && 1744 log_is_enabled(Info, monitorinflation)) { 1745 ls = &lsh_info; 1746 } 1747 if (ls != NULL) { 1748 ls->print_cr("om_flush: jt=" INTPTR_FORMAT ", free_count=%d" 1749 ", in_use_count=%d" ", om_free_provision=%d", 1750 p2i(self), free_count, in_use_count, self->om_free_provision); 1751 } 1752 } 1753 1754 static void post_monitor_inflate_event(EventJavaMonitorInflate* event, 1755 const oop obj, 1756 ObjectSynchronizer::InflateCause cause) { 1757 assert(event != NULL, "invariant"); 1758 assert(event->should_commit(), "invariant"); 1759 event->set_monitorClass(obj->klass()); 1760 event->set_address((uintptr_t)(void*)obj); 1761 event->set_cause((u1)cause); 1762 event->commit(); 1763 } 1764 1765 // Fast path code shared by multiple functions 1766 void ObjectSynchronizer::inflate_helper(oop obj) { 1767 markWord mark = obj->mark(); 1768 if (mark.has_monitor()) { 1769 ObjectMonitor* monitor = mark.monitor(); 1770 assert(ObjectSynchronizer::verify_objmon_isinpool(monitor), "monitor=" INTPTR_FORMAT " is invalid", p2i(monitor)); 1771 markWord dmw = monitor->header(); 1772 assert(dmw.is_neutral(), "sanity check: header=" INTPTR_FORMAT, dmw.value()); 1773 return; 1774 } 1775 (void)inflate(Thread::current(), obj, inflate_cause_vm_internal); 1776 } 1777 1778 ObjectMonitor* ObjectSynchronizer::inflate(Thread* self, oop object, 1779 const InflateCause cause) { 1780 // Inflate mutates the heap ... 1781 // Relaxing assertion for bug 6320749. 1782 assert(Universe::verify_in_progress() || 1783 !SafepointSynchronize::is_at_safepoint(), "invariant"); 1784 1785 EventJavaMonitorInflate event; 1786 1787 for (;;) { 1788 const markWord mark = object->mark(); 1789 assert(!mark.has_bias_pattern(), "invariant"); 1790 1791 // The mark can be in one of the following states: 1792 // * Inflated - just return 1793 // * Stack-locked - coerce it to inflated 1794 // * INFLATING - busy wait for conversion to complete 1795 // * Neutral - aggressively inflate the object. 1796 // * BIASED - Illegal. We should never see this 1797 1798 // CASE: inflated 1799 if (mark.has_monitor()) { 1800 ObjectMonitor* inf = mark.monitor(); 1801 markWord dmw = inf->header(); 1802 assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value()); 1803 assert(ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid"); 1804 return inf; 1805 } 1806 1807 // CASE: inflation in progress - inflating over a stack-lock. 1808 // Some other thread is converting from stack-locked to inflated. 1809 // Only that thread can complete inflation -- other threads must wait. 1810 // The INFLATING value is transient. 1811 // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish. 1812 // We could always eliminate polling by parking the thread on some auxiliary list. 1813 if (mark == markWord::INFLATING()) { 1814 read_stable_mark(object); 1815 continue; 1816 } 1817 1818 // CASE: stack-locked 1819 // Could be stack-locked either by this thread or by some other thread. 1820 // 1821 // Note that we allocate the objectmonitor speculatively, _before_ attempting 1822 // to install INFLATING into the mark word. We originally installed INFLATING, 1823 // allocated the objectmonitor, and then finally STed the address of the 1824 // objectmonitor into the mark. This was correct, but artificially lengthened 1825 // the interval in which INFLATED appeared in the mark, thus increasing 1826 // the odds of inflation contention. 1827 // 1828 // We now use per-thread private objectmonitor free lists. 1829 // These list are reprovisioned from the global free list outside the 1830 // critical INFLATING...ST interval. A thread can transfer 1831 // multiple objectmonitors en-mass from the global free list to its local free list. 1832 // This reduces coherency traffic and lock contention on the global free list. 1833 // Using such local free lists, it doesn't matter if the om_alloc() call appears 1834 // before or after the CAS(INFLATING) operation. 1835 // See the comments in om_alloc(). 1836 1837 LogStreamHandle(Trace, monitorinflation) lsh; 1838 1839 if (mark.has_locker()) { 1840 ObjectMonitor* m = om_alloc(self); 1841 // Optimistically prepare the objectmonitor - anticipate successful CAS 1842 // We do this before the CAS in order to minimize the length of time 1843 // in which INFLATING appears in the mark. 1844 m->Recycle(); 1845 m->_Responsible = NULL; 1846 m->_SpinDuration = ObjectMonitor::Knob_SpinLimit; // Consider: maintain by type/class 1847 1848 markWord cmp = object->cas_set_mark(markWord::INFLATING(), mark); 1849 if (cmp != mark) { 1850 // om_release() will reset the allocation state from New to Free. 1851 om_release(self, m, true); 1852 continue; // Interference -- just retry 1853 } 1854 1855 // We've successfully installed INFLATING (0) into the mark-word. 1856 // This is the only case where 0 will appear in a mark-word. 1857 // Only the singular thread that successfully swings the mark-word 1858 // to 0 can perform (or more precisely, complete) inflation. 1859 // 1860 // Why do we CAS a 0 into the mark-word instead of just CASing the 1861 // mark-word from the stack-locked value directly to the new inflated state? 1862 // Consider what happens when a thread unlocks a stack-locked object. 1863 // It attempts to use CAS to swing the displaced header value from the 1864 // on-stack BasicLock back into the object header. Recall also that the 1865 // header value (hash code, etc) can reside in (a) the object header, or 1866 // (b) a displaced header associated with the stack-lock, or (c) a displaced 1867 // header in an ObjectMonitor. The inflate() routine must copy the header 1868 // value from the BasicLock on the owner's stack to the ObjectMonitor, all 1869 // the while preserving the hashCode stability invariants. If the owner 1870 // decides to release the lock while the value is 0, the unlock will fail 1871 // and control will eventually pass from slow_exit() to inflate. The owner 1872 // will then spin, waiting for the 0 value to disappear. Put another way, 1873 // the 0 causes the owner to stall if the owner happens to try to 1874 // drop the lock (restoring the header from the BasicLock to the object) 1875 // while inflation is in-progress. This protocol avoids races that might 1876 // would otherwise permit hashCode values to change or "flicker" for an object. 1877 // Critically, while object->mark is 0 mark.displaced_mark_helper() is stable. 1878 // 0 serves as a "BUSY" inflate-in-progress indicator. 1879 1880 1881 // fetch the displaced mark from the owner's stack. 1882 // The owner can't die or unwind past the lock while our INFLATING 1883 // object is in the mark. Furthermore the owner can't complete 1884 // an unlock on the object, either. 1885 markWord dmw = mark.displaced_mark_helper(); 1886 // Catch if the object's header is not neutral (not locked and 1887 // not marked is what we care about here). 1888 assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value()); 1889 1890 // Setup monitor fields to proper values -- prepare the monitor 1891 m->set_header(dmw); 1892 1893 // Optimization: if the mark.locker stack address is associated 1894 // with this thread we could simply set m->_owner = self. 1895 // Note that a thread can inflate an object 1896 // that it has stack-locked -- as might happen in wait() -- directly 1897 // with CAS. That is, we can avoid the xchg-NULL .... ST idiom. 1898 m->set_owner_from(NULL, DEFLATER_MARKER, mark.locker()); 1899 m->set_object(object); 1900 // TODO-FIXME: assert BasicLock->dhw != 0. 1901 1902 // Must preserve store ordering. The monitor state must 1903 // be stable at the time of publishing the monitor address. 1904 guarantee(object->mark() == markWord::INFLATING(), "invariant"); 1905 object->release_set_mark(markWord::encode(m)); 1906 1907 // Once ObjectMonitor is configured and the object is associated 1908 // with the ObjectMonitor, it is safe to allow async deflation: 1909 assert(m->is_new(), "freshly allocated monitor must be new"); 1910 m->set_allocation_state(ObjectMonitor::Old); 1911 1912 // Hopefully the performance counters are allocated on distinct cache lines 1913 // to avoid false sharing on MP systems ... 1914 OM_PERFDATA_OP(Inflations, inc()); 1915 if (log_is_enabled(Trace, monitorinflation)) { 1916 ResourceMark rm(self); 1917 lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark=" 1918 INTPTR_FORMAT ", type='%s'", p2i(object), 1919 object->mark().value(), object->klass()->external_name()); 1920 } 1921 if (event.should_commit()) { 1922 post_monitor_inflate_event(&event, object, cause); 1923 } 1924 return m; 1925 } 1926 1927 // CASE: neutral 1928 // TODO-FIXME: for entry we currently inflate and then try to CAS _owner. 1929 // If we know we're inflating for entry it's better to inflate by swinging a 1930 // pre-locked ObjectMonitor pointer into the object header. A successful 1931 // CAS inflates the object *and* confers ownership to the inflating thread. 1932 // In the current implementation we use a 2-step mechanism where we CAS() 1933 // to inflate and then CAS() again to try to swing _owner from NULL to self. 1934 // An inflateTry() method that we could call from enter() would be useful. 1935 1936 // Catch if the object's header is not neutral (not locked and 1937 // not marked is what we care about here). 1938 assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value()); 1939 ObjectMonitor* m = om_alloc(self); 1940 // prepare m for installation - set monitor to initial state 1941 m->Recycle(); 1942 m->set_header(mark); 1943 // DEFLATER_MARKER is the only non-NULL value we should see here. 1944 m->try_set_owner_from(DEFLATER_MARKER, NULL); 1945 m->set_object(object); 1946 m->_Responsible = NULL; 1947 m->_SpinDuration = ObjectMonitor::Knob_SpinLimit; // consider: keep metastats by type/class 1948 1949 if (object->cas_set_mark(markWord::encode(m), mark) != mark) { 1950 m->set_header(markWord::zero()); 1951 m->set_object(NULL); 1952 m->Recycle(); 1953 // om_release() will reset the allocation state from New to Free. 1954 om_release(self, m, true); 1955 m = NULL; 1956 continue; 1957 // interference - the markword changed - just retry. 1958 // The state-transitions are one-way, so there's no chance of 1959 // live-lock -- "Inflated" is an absorbing state. 1960 } 1961 1962 // Once the ObjectMonitor is configured and object is associated 1963 // with the ObjectMonitor, it is safe to allow async deflation: 1964 assert(m->is_new(), "freshly allocated monitor must be new"); 1965 m->set_allocation_state(ObjectMonitor::Old); 1966 1967 // Hopefully the performance counters are allocated on distinct 1968 // cache lines to avoid false sharing on MP systems ... 1969 OM_PERFDATA_OP(Inflations, inc()); 1970 if (log_is_enabled(Trace, monitorinflation)) { 1971 ResourceMark rm(self); 1972 lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark=" 1973 INTPTR_FORMAT ", type='%s'", p2i(object), 1974 object->mark().value(), object->klass()->external_name()); 1975 } 1976 if (event.should_commit()) { 1977 post_monitor_inflate_event(&event, object, cause); 1978 } 1979 return m; 1980 } 1981 } 1982 1983 1984 // An async deflation request is registered with the ServiceThread 1985 // and it is notified. 1986 void ObjectSynchronizer::do_safepoint_work() { 1987 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1988 1989 log_debug(monitorinflation)("requesting async deflation of idle monitors."); 1990 // Request deflation of idle monitors by the ServiceThread: 1991 set_is_async_deflation_requested(true); 1992 MonitorLocker ml(Service_lock, Mutex::_no_safepoint_check_flag); 1993 ml.notify_all(); 1994 1995 if (log_is_enabled(Debug, monitorinflation)) { 1996 // exit_globals()'s call to audit_and_print_stats() is done 1997 // at the Info level and not at a safepoint. 1998 ObjectSynchronizer::audit_and_print_stats(false /* on_exit */); 1999 } 2000 } 2001 2002 // Deflate the specified ObjectMonitor if not in-use using a JavaThread. 2003 // Returns true if it was deflated and false otherwise. 2004 // 2005 // The async deflation protocol sets owner to DEFLATER_MARKER and 2006 // makes contentions negative as signals to contending threads that 2007 // an async deflation is in progress. There are a number of checks 2008 // as part of the protocol to make sure that the calling thread has 2009 // not lost the race to a contending thread. 2010 // 2011 // The ObjectMonitor has been successfully async deflated when: 2012 // (contentions < 0) 2013 // Contending threads that see that condition know to retry their operation. 2014 // 2015 bool ObjectSynchronizer::deflate_monitor_using_JT(ObjectMonitor* mid, 2016 ObjectMonitor** free_head_p, 2017 ObjectMonitor** free_tail_p) { 2018 assert(Thread::current()->is_Java_thread(), "precondition"); 2019 // A newly allocated ObjectMonitor should not be seen here so we 2020 // avoid an endless inflate/deflate cycle. 2021 assert(mid->is_old(), "must be old: allocation_state=%d", 2022 (int) mid->allocation_state()); 2023 2024 if (mid->is_busy()) { 2025 // Easy checks are first - the ObjectMonitor is busy so no deflation. 2026 return false; 2027 } 2028 2029 // Set a NULL owner to DEFLATER_MARKER to force any contending thread 2030 // through the slow path. This is just the first part of the async 2031 // deflation dance. 2032 if (mid->try_set_owner_from(NULL, DEFLATER_MARKER) != NULL) { 2033 // The owner field is no longer NULL so we lost the race since the 2034 // ObjectMonitor is now busy. 2035 return false; 2036 } 2037 2038 if (mid->contentions() > 0 || mid->_waiters != 0) { 2039 // Another thread has raced to enter the ObjectMonitor after 2040 // mid->is_busy() above or has already entered and waited on 2041 // it which makes it busy so no deflation. Restore owner to 2042 // NULL if it is still DEFLATER_MARKER. 2043 if (mid->try_set_owner_from(DEFLATER_MARKER, NULL) != DEFLATER_MARKER) { 2044 // Deferred decrement for the JT EnterI() that cancelled the async deflation. 2045 mid->add_to_contentions(-1); 2046 } 2047 return false; 2048 } 2049 2050 // Make a zero contentions field negative to force any contending threads 2051 // to retry. This is the second part of the async deflation dance. 2052 if (Atomic::cmpxchg(&mid->_contentions, (jint)0, -max_jint) != 0) { 2053 // Contentions was no longer 0 so we lost the race since the 2054 // ObjectMonitor is now busy. Restore owner to NULL if it is 2055 // still DEFLATER_MARKER: 2056 if (mid->try_set_owner_from(DEFLATER_MARKER, NULL) != DEFLATER_MARKER) { 2057 // Deferred decrement for the JT EnterI() that cancelled the async deflation. 2058 mid->add_to_contentions(-1); 2059 } 2060 return false; 2061 } 2062 2063 // Sanity checks for the races: 2064 guarantee(mid->owner_is_DEFLATER_MARKER(), "must be deflater marker"); 2065 guarantee(mid->contentions() < 0, "must be negative: contentions=%d", 2066 mid->contentions()); 2067 guarantee(mid->_waiters == 0, "must be 0: waiters=%d", mid->_waiters); 2068 guarantee(mid->_cxq == NULL, "must be no contending threads: cxq=" 2069 INTPTR_FORMAT, p2i(mid->_cxq)); 2070 guarantee(mid->_EntryList == NULL, 2071 "must be no entering threads: EntryList=" INTPTR_FORMAT, 2072 p2i(mid->_EntryList)); 2073 2074 const oop obj = (oop) mid->object(); 2075 if (log_is_enabled(Trace, monitorinflation)) { 2076 ResourceMark rm; 2077 log_trace(monitorinflation)("deflate_monitor_using_JT: " 2078 "object=" INTPTR_FORMAT ", mark=" 2079 INTPTR_FORMAT ", type='%s'", 2080 p2i(obj), obj->mark().value(), 2081 obj->klass()->external_name()); 2082 } 2083 2084 // Install the old mark word if nobody else has already done it. 2085 mid->install_displaced_markword_in_object(obj); 2086 mid->clear_common(); 2087 2088 assert(mid->object() == NULL, "must be NULL: object=" INTPTR_FORMAT, 2089 p2i(mid->object())); 2090 assert(mid->is_free(), "must be free: allocation_state=%d", 2091 (int)mid->allocation_state()); 2092 2093 // Move the deflated ObjectMonitor to the working free list 2094 // defined by free_head_p and free_tail_p. 2095 if (*free_head_p == NULL) { 2096 // First one on the list. 2097 *free_head_p = mid; 2098 } 2099 if (*free_tail_p != NULL) { 2100 // We append to the list so the caller can use mid->_next_om 2101 // to fix the linkages in its context. 2102 ObjectMonitor* prevtail = *free_tail_p; 2103 // prevtail should have been cleaned up by the caller: 2104 #ifdef ASSERT 2105 ObjectMonitor* l_next_om = unmarked_next(prevtail); 2106 assert(l_next_om == NULL, "must be NULL: _next_om=" INTPTR_FORMAT, p2i(l_next_om)); 2107 #endif 2108 om_lock(prevtail); 2109 prevtail->set_next_om(mid); // prevtail now points to mid (and is unlocked) 2110 } 2111 *free_tail_p = mid; 2112 2113 // At this point, mid->_next_om still refers to its current 2114 // value and another ObjectMonitor's _next_om field still 2115 // refers to this ObjectMonitor. Those linkages have to be 2116 // cleaned up by the caller who has the complete context. 2117 2118 // We leave owner == DEFLATER_MARKER and contentions < 0 2119 // to force any racing threads to retry. 2120 return true; // Success, ObjectMonitor has been deflated. 2121 } 2122 2123 // Walk a given ObjectMonitor list and deflate idle ObjectMonitors using 2124 // a JavaThread. Returns the number of deflated ObjectMonitors. The given 2125 // list could be a per-thread in-use list or the global in-use list. 2126 // If a safepoint has started, then we save state via saved_mid_in_use_p 2127 // and return to the caller to honor the safepoint. 2128 // 2129 int ObjectSynchronizer::deflate_monitor_list_using_JT(ObjectMonitor** list_p, 2130 int* count_p, 2131 ObjectMonitor** free_head_p, 2132 ObjectMonitor** free_tail_p, 2133 ObjectMonitor** saved_mid_in_use_p) { 2134 JavaThread* self = JavaThread::current(); 2135 2136 ObjectMonitor* cur_mid_in_use = NULL; 2137 ObjectMonitor* mid = NULL; 2138 ObjectMonitor* next = NULL; 2139 ObjectMonitor* next_next = NULL; 2140 int deflated_count = 0; 2141 NoSafepointVerifier nsv; 2142 2143 // We use the more complicated lock-cur_mid_in_use-and-mid-as-we-go 2144 // protocol because om_release() can do list deletions in parallel; 2145 // this also prevents races with a list walker thread. We also 2146 // lock-next-next-as-we-go to prevent an om_flush() that is behind 2147 // this thread from passing us. 2148 if (*saved_mid_in_use_p == NULL) { 2149 // No saved state so start at the beginning. 2150 // Lock the list head so we can possibly deflate it: 2151 if ((mid = get_list_head_locked(list_p)) == NULL) { 2152 return 0; // The list is empty so nothing to deflate. 2153 } 2154 next = unmarked_next(mid); 2155 } else { 2156 // We're restarting after a safepoint so restore the necessary state 2157 // before we resume. 2158 cur_mid_in_use = *saved_mid_in_use_p; 2159 // Lock cur_mid_in_use so we can possibly update its 2160 // next field to extract a deflated ObjectMonitor. 2161 om_lock(cur_mid_in_use); 2162 mid = unmarked_next(cur_mid_in_use); 2163 if (mid == NULL) { 2164 om_unlock(cur_mid_in_use); 2165 *saved_mid_in_use_p = NULL; 2166 return 0; // The remainder is empty so nothing more to deflate. 2167 } 2168 // Lock mid so we can possibly deflate it: 2169 om_lock(mid); 2170 next = unmarked_next(mid); 2171 } 2172 2173 while (true) { 2174 // The current mid is locked at this point. If we have a 2175 // cur_mid_in_use, then it is also locked at this point. 2176 2177 if (next != NULL) { 2178 // We lock next so that an om_flush() thread that is behind us 2179 // cannot pass us when we unlock the current mid. 2180 om_lock(next); 2181 next_next = unmarked_next(next); 2182 } 2183 2184 // Only try to deflate if there is an associated Java object and if 2185 // mid is old (is not newly allocated and is not newly freed). 2186 if (mid->object() != NULL && mid->is_old() && 2187 deflate_monitor_using_JT(mid, free_head_p, free_tail_p)) { 2188 // Deflation succeeded and already updated free_head_p and 2189 // free_tail_p as needed. Finish the move to the local free list 2190 // by unlinking mid from the global or per-thread in-use list. 2191 if (cur_mid_in_use == NULL) { 2192 // mid is the list head and it is locked. Switch the list head 2193 // to next which is also locked (if not NULL) and also leave 2194 // mid locked: 2195 Atomic::store(list_p, next); 2196 } else { 2197 ObjectMonitor* locked_next = mark_om_ptr(next); 2198 // mid and cur_mid_in_use are locked. Switch cur_mid_in_use's 2199 // next field to locked_next and also leave mid locked: 2200 cur_mid_in_use->set_next_om(locked_next); 2201 } 2202 // At this point mid is disconnected from the in-use list so 2203 // its lock longer has any effects on in-use list. 2204 deflated_count++; 2205 Atomic::dec(count_p); 2206 // mid is current tail in the free_head_p list so NULL terminate it 2207 // (which also unlocks it): 2208 mid->set_next_om(NULL); 2209 2210 // All the list management is done so move on to the next one: 2211 mid = next; // mid keeps non-NULL next's locked state 2212 next = next_next; 2213 } else { 2214 // mid is considered in-use if it does not have an associated 2215 // Java object or mid is not old or deflation did not succeed. 2216 // A mid->is_new() node can be seen here when it is freshly 2217 // returned by om_alloc() (and skips the deflation code path). 2218 // A mid->is_old() node can be seen here when deflation failed. 2219 // A mid->is_free() node can be seen here when a fresh node from 2220 // om_alloc() is released by om_release() due to losing the race 2221 // in inflate(). 2222 2223 // All the list management is done so move on to the next one: 2224 if (cur_mid_in_use != NULL) { 2225 om_unlock(cur_mid_in_use); 2226 } 2227 // The next cur_mid_in_use keeps mid's lock state so 2228 // that it is stable for a possible next field change. It 2229 // cannot be modified by om_release() while it is locked. 2230 cur_mid_in_use = mid; 2231 mid = next; // mid keeps non-NULL next's locked state 2232 next = next_next; 2233 2234 if (SafepointMechanism::should_block(self) && 2235 cur_mid_in_use != Atomic::load(list_p) && cur_mid_in_use->is_old()) { 2236 // If a safepoint has started and cur_mid_in_use is not the list 2237 // head and is old, then it is safe to use as saved state. Return 2238 // to the caller before blocking. 2239 *saved_mid_in_use_p = cur_mid_in_use; 2240 om_unlock(cur_mid_in_use); 2241 if (mid != NULL) { 2242 om_unlock(mid); 2243 } 2244 return deflated_count; 2245 } 2246 } 2247 if (mid == NULL) { 2248 if (cur_mid_in_use != NULL) { 2249 om_unlock(cur_mid_in_use); 2250 } 2251 break; // Reached end of the list so nothing more to deflate. 2252 } 2253 2254 // The current mid's next field is locked at this point. If we have 2255 // a cur_mid_in_use, then it is also locked at this point. 2256 } 2257 // We finished the list without a safepoint starting so there's 2258 // no need to save state. 2259 *saved_mid_in_use_p = NULL; 2260 return deflated_count; 2261 } 2262 2263 class HandshakeForDeflation : public HandshakeClosure { 2264 public: 2265 HandshakeForDeflation() : HandshakeClosure("HandshakeForDeflation") {} 2266 2267 void do_thread(Thread* thread) { 2268 log_trace(monitorinflation)("HandshakeForDeflation::do_thread: thread=" 2269 INTPTR_FORMAT, p2i(thread)); 2270 } 2271 }; 2272 2273 void ObjectSynchronizer::deflate_idle_monitors_using_JT() { 2274 // Deflate any global idle monitors. 2275 deflate_global_idle_monitors_using_JT(); 2276 2277 int count = 0; 2278 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 2279 if (Atomic::load(&jt->om_in_use_count) > 0 && !jt->is_exiting()) { 2280 // This JavaThread is using ObjectMonitors so deflate any that 2281 // are idle unless this JavaThread is exiting; do not race with 2282 // ObjectSynchronizer::om_flush(). 2283 deflate_per_thread_idle_monitors_using_JT(jt); 2284 count++; 2285 } 2286 } 2287 if (count > 0) { 2288 log_debug(monitorinflation)("did async deflation of idle monitors for %d thread(s).", count); 2289 } 2290 2291 log_info(monitorinflation)("async global_population=%d, global_in_use_count=%d, " 2292 "global_free_count=%d, global_wait_count=%d", 2293 Atomic::load(&om_list_globals._population), 2294 Atomic::load(&om_list_globals._in_use_count), 2295 Atomic::load(&om_list_globals._free_count), 2296 Atomic::load(&om_list_globals._wait_count)); 2297 2298 // The ServiceThread's async deflation request has been processed. 2299 _last_async_deflation_time_ns = os::javaTimeNanos(); 2300 set_is_async_deflation_requested(false); 2301 2302 if (Atomic::load(&om_list_globals._wait_count) > 0) { 2303 // There are deflated ObjectMonitors waiting for a handshake 2304 // (or a safepoint) for safety. 2305 2306 ObjectMonitor* list = Atomic::load(&om_list_globals._wait_list); 2307 assert(list != NULL, "om_list_globals._wait_list must not be NULL"); 2308 int count = Atomic::load(&om_list_globals._wait_count); 2309 Atomic::store(&om_list_globals._wait_count, 0); 2310 Atomic::store(&om_list_globals._wait_list, (ObjectMonitor*)NULL); 2311 2312 // Find the tail for prepend_list_to_common(). No need to mark 2313 // ObjectMonitors for this list walk since only the deflater 2314 // thread manages the wait list. 2315 #ifdef ASSERT 2316 int l_count = 0; 2317 #endif 2318 ObjectMonitor* tail = NULL; 2319 for (ObjectMonitor* n = list; n != NULL; n = unmarked_next(n)) { 2320 tail = n; 2321 #ifdef ASSERT 2322 l_count++; 2323 #endif 2324 } 2325 assert(count == l_count, "count=%d != l_count=%d", count, l_count); 2326 2327 // Will execute a safepoint if !ThreadLocalHandshakes: 2328 HandshakeForDeflation hfd_hc; 2329 Handshake::execute(&hfd_hc); 2330 2331 prepend_list_to_common(list, tail, count, &om_list_globals._free_list, 2332 &om_list_globals._free_count); 2333 2334 log_info(monitorinflation)("moved %d idle monitors from global waiting list to global free list", count); 2335 } 2336 } 2337 2338 // Deflate global idle ObjectMonitors using a JavaThread. 2339 // 2340 void ObjectSynchronizer::deflate_global_idle_monitors_using_JT() { 2341 assert(Thread::current()->is_Java_thread(), "precondition"); 2342 JavaThread* self = JavaThread::current(); 2343 2344 deflate_common_idle_monitors_using_JT(true /* is_global */, self); 2345 } 2346 2347 // Deflate the specified JavaThread's idle ObjectMonitors using a JavaThread. 2348 // 2349 void ObjectSynchronizer::deflate_per_thread_idle_monitors_using_JT(JavaThread* target) { 2350 assert(Thread::current()->is_Java_thread(), "precondition"); 2351 2352 deflate_common_idle_monitors_using_JT(false /* !is_global */, target); 2353 } 2354 2355 // Deflate global or per-thread idle ObjectMonitors using a JavaThread. 2356 // 2357 void ObjectSynchronizer::deflate_common_idle_monitors_using_JT(bool is_global, JavaThread* target) { 2358 JavaThread* self = JavaThread::current(); 2359 2360 int deflated_count = 0; 2361 ObjectMonitor* free_head_p = NULL; // Local SLL of scavenged ObjectMonitors 2362 ObjectMonitor* free_tail_p = NULL; 2363 ObjectMonitor* saved_mid_in_use_p = NULL; 2364 elapsedTimer timer; 2365 2366 if (log_is_enabled(Info, monitorinflation)) { 2367 timer.start(); 2368 } 2369 2370 if (is_global) { 2371 OM_PERFDATA_OP(MonExtant, set_value(Atomic::load(&om_list_globals._in_use_count))); 2372 } else { 2373 OM_PERFDATA_OP(MonExtant, inc(Atomic::load(&target->om_in_use_count))); 2374 } 2375 2376 do { 2377 int local_deflated_count; 2378 if (is_global) { 2379 local_deflated_count = 2380 deflate_monitor_list_using_JT(&om_list_globals._in_use_list, 2381 &om_list_globals._in_use_count, 2382 &free_head_p, &free_tail_p, 2383 &saved_mid_in_use_p); 2384 } else { 2385 local_deflated_count = 2386 deflate_monitor_list_using_JT(&target->om_in_use_list, 2387 &target->om_in_use_count, &free_head_p, 2388 &free_tail_p, &saved_mid_in_use_p); 2389 } 2390 deflated_count += local_deflated_count; 2391 2392 if (free_head_p != NULL) { 2393 // Move the deflated ObjectMonitors to the global free list. 2394 guarantee(free_tail_p != NULL && local_deflated_count > 0, "free_tail_p=" INTPTR_FORMAT ", local_deflated_count=%d", p2i(free_tail_p), local_deflated_count); 2395 // Note: The target thread can be doing an om_alloc() that 2396 // is trying to prepend an ObjectMonitor on its in-use list 2397 // at the same time that we have deflated the current in-use 2398 // list head and put it on the local free list. prepend_to_common() 2399 // will detect the race and retry which avoids list corruption, 2400 // but the next field in free_tail_p can flicker to marked 2401 // and then unmarked while prepend_to_common() is sorting it 2402 // all out. 2403 #ifdef ASSERT 2404 ObjectMonitor* l_next_om = unmarked_next(free_tail_p); 2405 assert(l_next_om == NULL, "must be NULL: _next_om=" INTPTR_FORMAT, p2i(l_next_om)); 2406 #endif 2407 2408 prepend_list_to_global_wait_list(free_head_p, free_tail_p, local_deflated_count); 2409 2410 OM_PERFDATA_OP(Deflations, inc(local_deflated_count)); 2411 } 2412 2413 if (saved_mid_in_use_p != NULL) { 2414 // deflate_monitor_list_using_JT() detected a safepoint starting. 2415 timer.stop(); 2416 { 2417 if (is_global) { 2418 log_debug(monitorinflation)("pausing deflation of global idle monitors for a safepoint."); 2419 } else { 2420 log_debug(monitorinflation)("jt=" INTPTR_FORMAT ": pausing deflation of per-thread idle monitors for a safepoint.", p2i(target)); 2421 } 2422 assert(SafepointMechanism::should_block(self), "sanity check"); 2423 ThreadBlockInVM blocker(self); 2424 } 2425 // Prepare for another loop after the safepoint. 2426 free_head_p = NULL; 2427 free_tail_p = NULL; 2428 if (log_is_enabled(Info, monitorinflation)) { 2429 timer.start(); 2430 } 2431 } 2432 } while (saved_mid_in_use_p != NULL); 2433 timer.stop(); 2434 2435 LogStreamHandle(Debug, monitorinflation) lsh_debug; 2436 LogStreamHandle(Info, monitorinflation) lsh_info; 2437 LogStream* ls = NULL; 2438 if (log_is_enabled(Debug, monitorinflation)) { 2439 ls = &lsh_debug; 2440 } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) { 2441 ls = &lsh_info; 2442 } 2443 if (ls != NULL) { 2444 if (is_global) { 2445 ls->print_cr("async-deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count); 2446 } else { 2447 ls->print_cr("jt=" INTPTR_FORMAT ": async-deflating per-thread idle monitors, %3.7f secs, %d monitors", p2i(target), timer.seconds(), deflated_count); 2448 } 2449 } 2450 } 2451 2452 // Monitor cleanup on JavaThread::exit 2453 2454 // Iterate through monitor cache and attempt to release thread's monitors 2455 // Gives up on a particular monitor if an exception occurs, but continues 2456 // the overall iteration, swallowing the exception. 2457 class ReleaseJavaMonitorsClosure: public MonitorClosure { 2458 private: 2459 TRAPS; 2460 2461 public: 2462 ReleaseJavaMonitorsClosure(Thread* thread) : THREAD(thread) {} 2463 void do_monitor(ObjectMonitor* mid) { 2464 if (mid->owner() == THREAD) { 2465 (void)mid->complete_exit(CHECK); 2466 } 2467 } 2468 }; 2469 2470 // Release all inflated monitors owned by THREAD. Lightweight monitors are 2471 // ignored. This is meant to be called during JNI thread detach which assumes 2472 // all remaining monitors are heavyweight. All exceptions are swallowed. 2473 // Scanning the extant monitor list can be time consuming. 2474 // A simple optimization is to add a per-thread flag that indicates a thread 2475 // called jni_monitorenter() during its lifetime. 2476 // 2477 // Instead of NoSafepointVerifier it might be cheaper to 2478 // use an idiom of the form: 2479 // auto int tmp = SafepointSynchronize::_safepoint_counter ; 2480 // <code that must not run at safepoint> 2481 // guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ; 2482 // Since the tests are extremely cheap we could leave them enabled 2483 // for normal product builds. 2484 2485 void ObjectSynchronizer::release_monitors_owned_by_thread(TRAPS) { 2486 assert(THREAD == JavaThread::current(), "must be current Java thread"); 2487 NoSafepointVerifier nsv; 2488 ReleaseJavaMonitorsClosure rjmc(THREAD); 2489 ObjectSynchronizer::monitors_iterate(&rjmc); 2490 THREAD->clear_pending_exception(); 2491 } 2492 2493 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) { 2494 switch (cause) { 2495 case inflate_cause_vm_internal: return "VM Internal"; 2496 case inflate_cause_monitor_enter: return "Monitor Enter"; 2497 case inflate_cause_wait: return "Monitor Wait"; 2498 case inflate_cause_notify: return "Monitor Notify"; 2499 case inflate_cause_hash_code: return "Monitor Hash Code"; 2500 case inflate_cause_jni_enter: return "JNI Monitor Enter"; 2501 case inflate_cause_jni_exit: return "JNI Monitor Exit"; 2502 default: 2503 ShouldNotReachHere(); 2504 } 2505 return "Unknown"; 2506 } 2507 2508 //------------------------------------------------------------------------------ 2509 // Debugging code 2510 2511 u_char* ObjectSynchronizer::get_gvars_addr() { 2512 return (u_char*)&GVars; 2513 } 2514 2515 u_char* ObjectSynchronizer::get_gvars_hc_sequence_addr() { 2516 return (u_char*)&GVars.hc_sequence; 2517 } 2518 2519 size_t ObjectSynchronizer::get_gvars_size() { 2520 return sizeof(SharedGlobals); 2521 } 2522 2523 u_char* ObjectSynchronizer::get_gvars_stw_random_addr() { 2524 return (u_char*)&GVars.stw_random; 2525 } 2526 2527 // This function can be called at a safepoint or it can be called when 2528 // we are trying to exit the VM. When we are trying to exit the VM, the 2529 // list walker functions can run in parallel with the other list 2530 // operations so spin-locking is used for safety. 2531 // 2532 // Calls to this function can be added in various places as a debugging 2533 // aid; pass 'true' for the 'on_exit' parameter to have in-use monitor 2534 // details logged at the Info level and 'false' for the 'on_exit' 2535 // parameter to have in-use monitor details logged at the Trace level. 2536 // 2537 void ObjectSynchronizer::audit_and_print_stats(bool on_exit) { 2538 assert(on_exit || SafepointSynchronize::is_at_safepoint(), "invariant"); 2539 2540 LogStreamHandle(Debug, monitorinflation) lsh_debug; 2541 LogStreamHandle(Info, monitorinflation) lsh_info; 2542 LogStreamHandle(Trace, monitorinflation) lsh_trace; 2543 LogStream* ls = NULL; 2544 if (log_is_enabled(Trace, monitorinflation)) { 2545 ls = &lsh_trace; 2546 } else if (log_is_enabled(Debug, monitorinflation)) { 2547 ls = &lsh_debug; 2548 } else if (log_is_enabled(Info, monitorinflation)) { 2549 ls = &lsh_info; 2550 } 2551 assert(ls != NULL, "sanity check"); 2552 2553 // Log counts for the global and per-thread monitor lists: 2554 int chk_om_population = log_monitor_list_counts(ls); 2555 int error_cnt = 0; 2556 2557 ls->print_cr("Checking global lists:"); 2558 2559 // Check om_list_globals._population: 2560 if (Atomic::load(&om_list_globals._population) == chk_om_population) { 2561 ls->print_cr("global_population=%d equals chk_om_population=%d", 2562 Atomic::load(&om_list_globals._population), chk_om_population); 2563 } else { 2564 // With fine grained locks on the monitor lists, it is possible for 2565 // log_monitor_list_counts() to return a value that doesn't match 2566 // om_list_globals._population. So far a higher value has been 2567 // seen in testing so something is being double counted by 2568 // log_monitor_list_counts(). 2569 ls->print_cr("WARNING: global_population=%d is not equal to " 2570 "chk_om_population=%d", 2571 Atomic::load(&om_list_globals._population), chk_om_population); 2572 } 2573 2574 // Check om_list_globals._in_use_list and om_list_globals._in_use_count: 2575 chk_global_in_use_list_and_count(ls, &error_cnt); 2576 2577 // Check om_list_globals._free_list and om_list_globals._free_count: 2578 chk_global_free_list_and_count(ls, &error_cnt); 2579 2580 // Check om_list_globals._wait_list and om_list_globals._wait_count: 2581 chk_global_wait_list_and_count(ls, &error_cnt); 2582 2583 ls->print_cr("Checking per-thread lists:"); 2584 2585 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 2586 // Check om_in_use_list and om_in_use_count: 2587 chk_per_thread_in_use_list_and_count(jt, ls, &error_cnt); 2588 2589 // Check om_free_list and om_free_count: 2590 chk_per_thread_free_list_and_count(jt, ls, &error_cnt); 2591 } 2592 2593 if (error_cnt == 0) { 2594 ls->print_cr("No errors found in monitor list checks."); 2595 } else { 2596 log_error(monitorinflation)("found monitor list errors: error_cnt=%d", error_cnt); 2597 } 2598 2599 if ((on_exit && log_is_enabled(Info, monitorinflation)) || 2600 (!on_exit && log_is_enabled(Trace, monitorinflation))) { 2601 // When exiting this log output is at the Info level. When called 2602 // at a safepoint, this log output is at the Trace level since 2603 // there can be a lot of it. 2604 log_in_use_monitor_details(ls); 2605 } 2606 2607 ls->flush(); 2608 2609 guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt); 2610 } 2611 2612 // Check a free monitor entry; log any errors. 2613 void ObjectSynchronizer::chk_free_entry(JavaThread* jt, ObjectMonitor* n, 2614 outputStream * out, int *error_cnt_p) { 2615 stringStream ss; 2616 if (n->is_busy()) { 2617 if (jt != NULL) { 2618 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2619 ": free per-thread monitor must not be busy: %s", p2i(jt), 2620 p2i(n), n->is_busy_to_string(&ss)); 2621 } else { 2622 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor " 2623 "must not be busy: %s", p2i(n), n->is_busy_to_string(&ss)); 2624 } 2625 *error_cnt_p = *error_cnt_p + 1; 2626 } 2627 if (n->header().value() != 0) { 2628 if (jt != NULL) { 2629 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2630 ": free per-thread monitor must have NULL _header " 2631 "field: _header=" INTPTR_FORMAT, p2i(jt), p2i(n), 2632 n->header().value()); 2633 *error_cnt_p = *error_cnt_p + 1; 2634 } 2635 } 2636 if (n->object() != NULL) { 2637 if (jt != NULL) { 2638 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2639 ": free per-thread monitor must have NULL _object " 2640 "field: _object=" INTPTR_FORMAT, p2i(jt), p2i(n), 2641 p2i(n->object())); 2642 } else { 2643 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor " 2644 "must have NULL _object field: _object=" INTPTR_FORMAT, 2645 p2i(n), p2i(n->object())); 2646 } 2647 *error_cnt_p = *error_cnt_p + 1; 2648 } 2649 } 2650 2651 // Lock the next ObjectMonitor for traversal and unlock the current 2652 // ObjectMonitor. Returns the next ObjectMonitor if there is one. 2653 // Otherwise returns NULL (after unlocking the current ObjectMonitor). 2654 // This function is used by the various list walker functions to 2655 // safely walk a list without allowing an ObjectMonitor to be moved 2656 // to another list in the middle of a walk. 2657 static ObjectMonitor* lock_next_for_traversal(ObjectMonitor* cur) { 2658 assert(is_locked(cur), "cur=" INTPTR_FORMAT " must be locked", p2i(cur)); 2659 ObjectMonitor* next = unmarked_next(cur); 2660 if (next == NULL) { // Reached the end of the list. 2661 om_unlock(cur); 2662 return NULL; 2663 } 2664 om_lock(next); // Lock next before unlocking current to keep 2665 om_unlock(cur); // from being by-passed by another thread. 2666 return next; 2667 } 2668 2669 // Check the global free list and count; log the results of the checks. 2670 void ObjectSynchronizer::chk_global_free_list_and_count(outputStream * out, 2671 int *error_cnt_p) { 2672 int chk_om_free_count = 0; 2673 ObjectMonitor* cur = NULL; 2674 if ((cur = get_list_head_locked(&om_list_globals._free_list)) != NULL) { 2675 // Marked the global free list head so process the list. 2676 while (true) { 2677 chk_free_entry(NULL /* jt */, cur, out, error_cnt_p); 2678 chk_om_free_count++; 2679 2680 cur = lock_next_for_traversal(cur); 2681 if (cur == NULL) { 2682 break; 2683 } 2684 } 2685 } 2686 int l_free_count = Atomic::load(&om_list_globals._free_count); 2687 if (l_free_count == chk_om_free_count) { 2688 out->print_cr("global_free_count=%d equals chk_om_free_count=%d", 2689 l_free_count, chk_om_free_count); 2690 } else { 2691 // With fine grained locks on om_list_globals._free_list, it 2692 // is possible for an ObjectMonitor to be prepended to 2693 // om_list_globals._free_list after we started calculating 2694 // chk_om_free_count so om_list_globals._free_count may not 2695 // match anymore. 2696 out->print_cr("WARNING: global_free_count=%d is not equal to " 2697 "chk_om_free_count=%d", l_free_count, chk_om_free_count); 2698 } 2699 } 2700 2701 // Check the global wait list and count; log the results of the checks. 2702 void ObjectSynchronizer::chk_global_wait_list_and_count(outputStream * out, 2703 int *error_cnt_p) { 2704 int chk_om_wait_count = 0; 2705 ObjectMonitor* cur = NULL; 2706 if ((cur = get_list_head_locked(&om_list_globals._wait_list)) != NULL) { 2707 // Marked the global wait list head so process the list. 2708 while (true) { 2709 // Rules for om_list_globals._wait_list are the same as for 2710 // om_list_globals._free_list: 2711 chk_free_entry(NULL /* jt */, cur, out, error_cnt_p); 2712 chk_om_wait_count++; 2713 2714 cur = lock_next_for_traversal(cur); 2715 if (cur == NULL) { 2716 break; 2717 } 2718 } 2719 } 2720 if (Atomic::load(&om_list_globals._wait_count) == chk_om_wait_count) { 2721 out->print_cr("global_wait_count=%d equals chk_om_wait_count=%d", 2722 Atomic::load(&om_list_globals._wait_count), chk_om_wait_count); 2723 } else { 2724 out->print_cr("ERROR: global_wait_count=%d is not equal to " 2725 "chk_om_wait_count=%d", 2726 Atomic::load(&om_list_globals._wait_count), chk_om_wait_count); 2727 *error_cnt_p = *error_cnt_p + 1; 2728 } 2729 } 2730 2731 // Check the global in-use list and count; log the results of the checks. 2732 void ObjectSynchronizer::chk_global_in_use_list_and_count(outputStream * out, 2733 int *error_cnt_p) { 2734 int chk_om_in_use_count = 0; 2735 ObjectMonitor* cur = NULL; 2736 if ((cur = get_list_head_locked(&om_list_globals._in_use_list)) != NULL) { 2737 // Marked the global in-use list head so process the list. 2738 while (true) { 2739 chk_in_use_entry(NULL /* jt */, cur, out, error_cnt_p); 2740 chk_om_in_use_count++; 2741 2742 cur = lock_next_for_traversal(cur); 2743 if (cur == NULL) { 2744 break; 2745 } 2746 } 2747 } 2748 int l_in_use_count = Atomic::load(&om_list_globals._in_use_count); 2749 if (l_in_use_count == chk_om_in_use_count) { 2750 out->print_cr("global_in_use_count=%d equals chk_om_in_use_count=%d", 2751 l_in_use_count, chk_om_in_use_count); 2752 } else { 2753 // With fine grained locks on the monitor lists, it is possible for 2754 // an exiting JavaThread to put its in-use ObjectMonitors on the 2755 // global in-use list after chk_om_in_use_count is calculated above. 2756 out->print_cr("WARNING: global_in_use_count=%d is not equal to chk_om_in_use_count=%d", 2757 l_in_use_count, chk_om_in_use_count); 2758 } 2759 } 2760 2761 // Check an in-use monitor entry; log any errors. 2762 void ObjectSynchronizer::chk_in_use_entry(JavaThread* jt, ObjectMonitor* n, 2763 outputStream * out, int *error_cnt_p) { 2764 if (n->header().value() == 0) { 2765 if (jt != NULL) { 2766 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2767 ": in-use per-thread monitor must have non-NULL _header " 2768 "field.", p2i(jt), p2i(n)); 2769 } else { 2770 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global monitor " 2771 "must have non-NULL _header field.", p2i(n)); 2772 } 2773 *error_cnt_p = *error_cnt_p + 1; 2774 } 2775 if (n->object() == NULL) { 2776 if (jt != NULL) { 2777 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2778 ": in-use per-thread monitor must have non-NULL _object " 2779 "field.", p2i(jt), p2i(n)); 2780 } else { 2781 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global monitor " 2782 "must have non-NULL _object field.", p2i(n)); 2783 } 2784 *error_cnt_p = *error_cnt_p + 1; 2785 } 2786 const oop obj = (oop)n->object(); 2787 const markWord mark = obj->mark(); 2788 if (!mark.has_monitor()) { 2789 if (jt != NULL) { 2790 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2791 ": in-use per-thread monitor's object does not think " 2792 "it has a monitor: obj=" INTPTR_FORMAT ", mark=" 2793 INTPTR_FORMAT, p2i(jt), p2i(n), p2i(obj), mark.value()); 2794 } else { 2795 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global " 2796 "monitor's object does not think it has a monitor: obj=" 2797 INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n), 2798 p2i(obj), mark.value()); 2799 } 2800 *error_cnt_p = *error_cnt_p + 1; 2801 } 2802 ObjectMonitor* const obj_mon = mark.monitor(); 2803 if (n != obj_mon) { 2804 if (jt != NULL) { 2805 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2806 ": in-use per-thread monitor's object does not refer " 2807 "to the same monitor: obj=" INTPTR_FORMAT ", mark=" 2808 INTPTR_FORMAT ", obj_mon=" INTPTR_FORMAT, p2i(jt), 2809 p2i(n), p2i(obj), mark.value(), p2i(obj_mon)); 2810 } else { 2811 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global " 2812 "monitor's object does not refer to the same monitor: obj=" 2813 INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon=" 2814 INTPTR_FORMAT, p2i(n), p2i(obj), mark.value(), p2i(obj_mon)); 2815 } 2816 *error_cnt_p = *error_cnt_p + 1; 2817 } 2818 } 2819 2820 // Check the thread's free list and count; log the results of the checks. 2821 void ObjectSynchronizer::chk_per_thread_free_list_and_count(JavaThread *jt, 2822 outputStream * out, 2823 int *error_cnt_p) { 2824 int chk_om_free_count = 0; 2825 ObjectMonitor* cur = NULL; 2826 if ((cur = get_list_head_locked(&jt->om_free_list)) != NULL) { 2827 // Marked the per-thread free list head so process the list. 2828 while (true) { 2829 chk_free_entry(jt, cur, out, error_cnt_p); 2830 chk_om_free_count++; 2831 2832 cur = lock_next_for_traversal(cur); 2833 if (cur == NULL) { 2834 break; 2835 } 2836 } 2837 } 2838 int l_om_free_count = Atomic::load(&jt->om_free_count); 2839 if (l_om_free_count == chk_om_free_count) { 2840 out->print_cr("jt=" INTPTR_FORMAT ": om_free_count=%d equals " 2841 "chk_om_free_count=%d", p2i(jt), l_om_free_count, chk_om_free_count); 2842 } else { 2843 out->print_cr("ERROR: jt=" INTPTR_FORMAT ": om_free_count=%d is not " 2844 "equal to chk_om_free_count=%d", p2i(jt), l_om_free_count, 2845 chk_om_free_count); 2846 *error_cnt_p = *error_cnt_p + 1; 2847 } 2848 } 2849 2850 // Check the thread's in-use list and count; log the results of the checks. 2851 void ObjectSynchronizer::chk_per_thread_in_use_list_and_count(JavaThread *jt, 2852 outputStream * out, 2853 int *error_cnt_p) { 2854 int chk_om_in_use_count = 0; 2855 ObjectMonitor* cur = NULL; 2856 if ((cur = get_list_head_locked(&jt->om_in_use_list)) != NULL) { 2857 // Marked the per-thread in-use list head so process the list. 2858 while (true) { 2859 chk_in_use_entry(jt, cur, out, error_cnt_p); 2860 chk_om_in_use_count++; 2861 2862 cur = lock_next_for_traversal(cur); 2863 if (cur == NULL) { 2864 break; 2865 } 2866 } 2867 } 2868 int l_om_in_use_count = Atomic::load(&jt->om_in_use_count); 2869 if (l_om_in_use_count == chk_om_in_use_count) { 2870 out->print_cr("jt=" INTPTR_FORMAT ": om_in_use_count=%d equals " 2871 "chk_om_in_use_count=%d", p2i(jt), l_om_in_use_count, 2872 chk_om_in_use_count); 2873 } else { 2874 out->print_cr("ERROR: jt=" INTPTR_FORMAT ": om_in_use_count=%d is not " 2875 "equal to chk_om_in_use_count=%d", p2i(jt), l_om_in_use_count, 2876 chk_om_in_use_count); 2877 *error_cnt_p = *error_cnt_p + 1; 2878 } 2879 } 2880 2881 // Log details about ObjectMonitors on the in-use lists. The 'BHL' 2882 // flags indicate why the entry is in-use, 'object' and 'object type' 2883 // indicate the associated object and its type. 2884 void ObjectSynchronizer::log_in_use_monitor_details(outputStream * out) { 2885 stringStream ss; 2886 if (Atomic::load(&om_list_globals._in_use_count) > 0) { 2887 out->print_cr("In-use global monitor info:"); 2888 out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)"); 2889 out->print_cr("%18s %s %18s %18s", 2890 "monitor", "BHL", "object", "object type"); 2891 out->print_cr("================== === ================== =================="); 2892 ObjectMonitor* cur = NULL; 2893 if ((cur = get_list_head_locked(&om_list_globals._in_use_list)) != NULL) { 2894 // Marked the global in-use list head so process the list. 2895 while (true) { 2896 const oop obj = (oop) cur->object(); 2897 const markWord mark = cur->header(); 2898 ResourceMark rm; 2899 out->print(INTPTR_FORMAT " %d%d%d " INTPTR_FORMAT " %s", p2i(cur), 2900 cur->is_busy() != 0, mark.hash() != 0, cur->owner() != NULL, 2901 p2i(obj), obj->klass()->external_name()); 2902 if (cur->is_busy() != 0) { 2903 out->print(" (%s)", cur->is_busy_to_string(&ss)); 2904 ss.reset(); 2905 } 2906 out->cr(); 2907 2908 cur = lock_next_for_traversal(cur); 2909 if (cur == NULL) { 2910 break; 2911 } 2912 } 2913 } 2914 } 2915 2916 out->print_cr("In-use per-thread monitor info:"); 2917 out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)"); 2918 out->print_cr("%18s %18s %s %18s %18s", 2919 "jt", "monitor", "BHL", "object", "object type"); 2920 out->print_cr("================== ================== === ================== =================="); 2921 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 2922 ObjectMonitor* cur = NULL; 2923 if ((cur = get_list_head_locked(&jt->om_in_use_list)) != NULL) { 2924 // Marked the global in-use list head so process the list. 2925 while (true) { 2926 const oop obj = (oop) cur->object(); 2927 const markWord mark = cur->header(); 2928 ResourceMark rm; 2929 out->print(INTPTR_FORMAT " " INTPTR_FORMAT " %d%d%d " INTPTR_FORMAT 2930 " %s", p2i(jt), p2i(cur), cur->is_busy() != 0, 2931 mark.hash() != 0, cur->owner() != NULL, p2i(obj), 2932 obj->klass()->external_name()); 2933 if (cur->is_busy() != 0) { 2934 out->print(" (%s)", cur->is_busy_to_string(&ss)); 2935 ss.reset(); 2936 } 2937 out->cr(); 2938 2939 cur = lock_next_for_traversal(cur); 2940 if (cur == NULL) { 2941 break; 2942 } 2943 } 2944 } 2945 } 2946 2947 out->flush(); 2948 } 2949 2950 // Log counts for the global and per-thread monitor lists and return 2951 // the population count. 2952 int ObjectSynchronizer::log_monitor_list_counts(outputStream * out) { 2953 int pop_count = 0; 2954 out->print_cr("%18s %10s %10s %10s %10s", 2955 "Global Lists:", "InUse", "Free", "Wait", "Total"); 2956 out->print_cr("================== ========== ========== ========== =========="); 2957 int l_in_use_count = Atomic::load(&om_list_globals._in_use_count); 2958 int l_free_count = Atomic::load(&om_list_globals._free_count); 2959 int l_wait_count = Atomic::load(&om_list_globals._wait_count); 2960 out->print_cr("%18s %10d %10d %10d %10d", "", l_in_use_count, 2961 l_free_count, l_wait_count, 2962 Atomic::load(&om_list_globals._population)); 2963 pop_count += l_in_use_count + l_free_count + l_wait_count; 2964 2965 out->print_cr("%18s %10s %10s %10s", 2966 "Per-Thread Lists:", "InUse", "Free", "Provision"); 2967 out->print_cr("================== ========== ========== =========="); 2968 2969 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 2970 int l_om_in_use_count = Atomic::load(&jt->om_in_use_count); 2971 int l_om_free_count = Atomic::load(&jt->om_free_count); 2972 out->print_cr(INTPTR_FORMAT " %10d %10d %10d", p2i(jt), 2973 l_om_in_use_count, l_om_free_count, jt->om_free_provision); 2974 pop_count += l_om_in_use_count + l_om_free_count; 2975 } 2976 return pop_count; 2977 } 2978 2979 #ifndef PRODUCT 2980 2981 // Check if monitor belongs to the monitor cache 2982 // The list is grow-only so it's *relatively* safe to traverse 2983 // the list of extant blocks without taking a lock. 2984 2985 int ObjectSynchronizer::verify_objmon_isinpool(ObjectMonitor *monitor) { 2986 PaddedObjectMonitor* block = Atomic::load(&g_block_list); 2987 while (block != NULL) { 2988 assert(block->object() == CHAINMARKER, "must be a block header"); 2989 if (monitor > &block[0] && monitor < &block[_BLOCKSIZE]) { 2990 address mon = (address)monitor; 2991 address blk = (address)block; 2992 size_t diff = mon - blk; 2993 assert((diff % sizeof(PaddedObjectMonitor)) == 0, "must be aligned"); 2994 return 1; 2995 } 2996 // unmarked_next() is not needed with g_block_list (no locking 2997 // used with block linkage _next_om fields). 2998 block = (PaddedObjectMonitor*)block->next_om(); 2999 } 3000 return 0; 3001 } 3002 3003 #endif