1 /* 2 * Copyright (c) 2024, 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 27 #include "classfile/vmSymbols.hpp" 28 #include "jfrfiles/jfrEventClasses.hpp" 29 #include "logging/log.hpp" 30 #include "memory/allStatic.hpp" 31 #include "memory/resourceArea.hpp" 32 #include "nmt/memTag.hpp" 33 #include "oops/oop.inline.hpp" 34 #include "runtime/atomic.hpp" 35 #include "runtime/basicLock.inline.hpp" 36 #include "runtime/globals_extension.hpp" 37 #include "runtime/interfaceSupport.inline.hpp" 38 #include "runtime/javaThread.inline.hpp" 39 #include "runtime/lightweightSynchronizer.hpp" 40 #include "runtime/lockStack.inline.hpp" 41 #include "runtime/mutexLocker.hpp" 42 #include "runtime/objectMonitor.inline.hpp" 43 #include "runtime/os.hpp" 44 #include "runtime/perfData.inline.hpp" 45 #include "runtime/safepointMechanism.inline.hpp" 46 #include "runtime/safepointVerifiers.hpp" 47 #include "runtime/synchronizer.inline.hpp" 48 #include "runtime/timerTrace.hpp" 49 #include "runtime/trimNativeHeap.hpp" 50 #include "utilities/concurrentHashTable.inline.hpp" 51 #include "utilities/concurrentHashTableTasks.inline.hpp" 52 #include "utilities/globalDefinitions.hpp" 53 54 // ConcurrentHashTable storing links from objects to ObjectMonitors 55 class ObjectMonitorTable : AllStatic { 56 struct Config { 57 using Value = ObjectMonitor*; 58 static uintx get_hash(Value const& value, bool* is_dead) { 59 return (uintx)value->hash(); 60 } 61 static void* allocate_node(void* context, size_t size, Value const& value) { 62 ObjectMonitorTable::inc_items_count(); 63 return AllocateHeap(size, mtObjectMonitor); 64 }; 65 static void free_node(void* context, void* memory, Value const& value) { 66 ObjectMonitorTable::dec_items_count(); 67 FreeHeap(memory); 68 } 69 }; 70 using ConcurrentTable = ConcurrentHashTable<Config, mtObjectMonitor>; 71 72 static ConcurrentTable* _table; 73 static volatile size_t _items_count; 74 static size_t _table_size; 75 static volatile bool _resize; 76 77 class Lookup : public StackObj { 78 oop _obj; 79 80 public: 81 explicit Lookup(oop obj) : _obj(obj) {} 82 83 uintx get_hash() const { 84 uintx hash = _obj->mark().hash(); 85 assert(hash != 0, "should have a hash"); 86 return hash; 87 } 88 89 bool equals(ObjectMonitor** value) { 90 assert(*value != nullptr, "must be"); 91 return (*value)->object_refers_to(_obj); 92 } 93 94 bool is_dead(ObjectMonitor** value) { 95 assert(*value != nullptr, "must be"); 96 return false; 97 } 98 }; 99 100 class LookupMonitor : public StackObj { 101 ObjectMonitor* _monitor; 102 103 public: 104 explicit LookupMonitor(ObjectMonitor* monitor) : _monitor(monitor) {} 105 106 uintx get_hash() const { 107 return _monitor->hash(); 108 } 109 110 bool equals(ObjectMonitor** value) { 111 return (*value) == _monitor; 112 } 113 114 bool is_dead(ObjectMonitor** value) { 115 assert(*value != nullptr, "must be"); 116 return (*value)->object_is_dead(); 117 } 118 }; 119 120 static void inc_items_count() { 121 Atomic::inc(&_items_count); 122 } 123 124 static void dec_items_count() { 125 Atomic::dec(&_items_count); 126 } 127 128 static double get_load_factor() { 129 return (double)_items_count / (double)_table_size; 130 } 131 132 static size_t table_size(Thread* current = Thread::current()) { 133 return ((size_t)1) << _table->get_size_log2(current); 134 } 135 136 static size_t max_log_size() { 137 // TODO[OMTable]: Evaluate the max size. 138 // TODO[OMTable]: Need to fix init order to use Universe::heap()->max_capacity(); 139 // Using MaxHeapSize directly this early may be wrong, and there 140 // are definitely rounding errors (alignment). 141 const size_t max_capacity = MaxHeapSize; 142 const size_t min_object_size = CollectedHeap::min_dummy_object_size() * HeapWordSize; 143 const size_t max_objects = max_capacity / MAX2(MinObjAlignmentInBytes, checked_cast<int>(min_object_size)); 144 const size_t log_max_objects = log2i_graceful(max_objects); 145 146 return MAX2(MIN2<size_t>(SIZE_BIG_LOG2, log_max_objects), min_log_size()); 147 } 148 149 static size_t min_log_size() { 150 // ~= log(AvgMonitorsPerThreadEstimate default) 151 return 10; 152 } 153 154 template<typename V> 155 static size_t clamp_log_size(V log_size) { 156 return MAX2(MIN2(log_size, checked_cast<V>(max_log_size())), checked_cast<V>(min_log_size())); 157 } 158 159 static size_t initial_log_size() { 160 const size_t estimate = log2i(MAX2(os::processor_count(), 1)) + log2i(MAX2(AvgMonitorsPerThreadEstimate, size_t(1))); 161 return clamp_log_size(estimate); 162 } 163 164 static size_t grow_hint () { 165 return ConcurrentTable::DEFAULT_GROW_HINT; 166 } 167 168 public: 169 static void create() { 170 _table = new ConcurrentTable(initial_log_size(), max_log_size(), grow_hint()); 171 _items_count = 0; 172 _table_size = table_size(); 173 _resize = false; 174 } 175 176 static void verify_monitor_get_result(oop obj, ObjectMonitor* monitor) { 177 #ifdef ASSERT 178 if (SafepointSynchronize::is_at_safepoint()) { 179 bool has_monitor = obj->mark().has_monitor(); 180 assert(has_monitor == (monitor != nullptr), 181 "Inconsistency between markWord and ObjectMonitorTable has_monitor: %s monitor: " PTR_FORMAT, 182 BOOL_TO_STR(has_monitor), p2i(monitor)); 183 } 184 #endif 185 } 186 187 static ObjectMonitor* monitor_get(Thread* current, oop obj) { 188 ObjectMonitor* result = nullptr; 189 Lookup lookup_f(obj); 190 auto found_f = [&](ObjectMonitor** found) { 191 assert((*found)->object_peek() == obj, "must be"); 192 result = *found; 193 }; 194 _table->get(current, lookup_f, found_f); 195 verify_monitor_get_result(obj, result); 196 return result; 197 } 198 199 static void try_notify_grow() { 200 if (!_table->is_max_size_reached() && !Atomic::load(&_resize)) { 201 Atomic::store(&_resize, true); 202 if (Service_lock->try_lock()) { 203 Service_lock->notify(); 204 Service_lock->unlock(); 205 } 206 } 207 } 208 209 static bool should_shrink() { 210 // Not implemented; 211 return false; 212 } 213 214 static constexpr double GROW_LOAD_FACTOR = 0.75; 215 216 static bool should_grow() { 217 return get_load_factor() > GROW_LOAD_FACTOR && !_table->is_max_size_reached(); 218 } 219 220 static bool should_resize() { 221 return should_grow() || should_shrink() || Atomic::load(&_resize); 222 } 223 224 template<typename Task, typename... Args> 225 static bool run_task(JavaThread* current, Task& task, const char* task_name, Args&... args) { 226 if (task.prepare(current)) { 227 log_trace(monitortable)("Started to %s", task_name); 228 TraceTime timer(task_name, TRACETIME_LOG(Debug, monitortable, perf)); 229 while (task.do_task(current, args...)) { 230 task.pause(current); 231 { 232 ThreadBlockInVM tbivm(current); 233 } 234 task.cont(current); 235 } 236 task.done(current); 237 return true; 238 } 239 return false; 240 } 241 242 static bool grow(JavaThread* current) { 243 ConcurrentTable::GrowTask grow_task(_table); 244 if (run_task(current, grow_task, "Grow")) { 245 _table_size = table_size(current); 246 log_info(monitortable)("Grown to size: %zu", _table_size); 247 return true; 248 } 249 return false; 250 } 251 252 static bool clean(JavaThread* current) { 253 ConcurrentTable::BulkDeleteTask clean_task(_table); 254 auto is_dead = [&](ObjectMonitor** monitor) { 255 return (*monitor)->object_is_dead(); 256 }; 257 auto do_nothing = [&](ObjectMonitor** monitor) {}; 258 NativeHeapTrimmer::SuspendMark sm("ObjectMonitorTable"); 259 return run_task(current, clean_task, "Clean", is_dead, do_nothing); 260 } 261 262 static bool resize(JavaThread* current) { 263 LogTarget(Info, monitortable) lt; 264 bool success = false; 265 266 if (should_grow()) { 267 lt.print("Start growing with load factor %f", get_load_factor()); 268 success = grow(current); 269 } else { 270 if (!_table->is_max_size_reached() && Atomic::load(&_resize)) { 271 lt.print("WARNING: Getting resize hints with load factor %f", get_load_factor()); 272 } 273 lt.print("Start cleaning with load factor %f", get_load_factor()); 274 success = clean(current); 275 } 276 277 Atomic::store(&_resize, false); 278 279 return success; 280 } 281 282 static ObjectMonitor* monitor_put_get(Thread* current, ObjectMonitor* monitor, oop obj) { 283 // Enter the monitor into the concurrent hashtable. 284 ObjectMonitor* result = monitor; 285 Lookup lookup_f(obj); 286 auto found_f = [&](ObjectMonitor** found) { 287 assert((*found)->object_peek() == obj, "must be"); 288 result = *found; 289 }; 290 bool grow; 291 _table->insert_get(current, lookup_f, monitor, found_f, &grow); 292 verify_monitor_get_result(obj, result); 293 if (grow) { 294 try_notify_grow(); 295 } 296 return result; 297 } 298 299 static bool remove_monitor_entry(Thread* current, ObjectMonitor* monitor) { 300 LookupMonitor lookup_f(monitor); 301 return _table->remove(current, lookup_f); 302 } 303 304 static bool contains_monitor(Thread* current, ObjectMonitor* monitor) { 305 LookupMonitor lookup_f(monitor); 306 bool result = false; 307 auto found_f = [&](ObjectMonitor** found) { 308 result = true; 309 }; 310 _table->get(current, lookup_f, found_f); 311 return result; 312 } 313 314 static void print_on(outputStream* st) { 315 auto printer = [&] (ObjectMonitor** entry) { 316 ObjectMonitor* om = *entry; 317 oop obj = om->object_peek(); 318 st->print("monitor=" PTR_FORMAT ", ", p2i(om)); 319 st->print("object=" PTR_FORMAT, p2i(obj)); 320 assert(obj->mark().hash() == om->hash(), "hash must match"); 321 st->cr(); 322 return true; 323 }; 324 if (SafepointSynchronize::is_at_safepoint()) { 325 _table->do_safepoint_scan(printer); 326 } else { 327 _table->do_scan(Thread::current(), printer); 328 } 329 } 330 }; 331 332 ObjectMonitorTable::ConcurrentTable* ObjectMonitorTable::_table = nullptr; 333 volatile size_t ObjectMonitorTable::_items_count = 0; 334 size_t ObjectMonitorTable::_table_size = 0; 335 volatile bool ObjectMonitorTable::_resize = false; 336 337 ObjectMonitor* LightweightSynchronizer::get_or_insert_monitor_from_table(oop object, JavaThread* current, bool* inserted) { 338 assert(LockingMode == LM_LIGHTWEIGHT, "must be"); 339 340 ObjectMonitor* monitor = get_monitor_from_table(current, object); 341 if (monitor != nullptr) { 342 *inserted = false; 343 return monitor; 344 } 345 346 ObjectMonitor* alloced_monitor = new ObjectMonitor(object); 347 alloced_monitor->set_anonymous_owner(); 348 349 // Try insert monitor 350 monitor = add_monitor(current, alloced_monitor, object); 351 352 *inserted = alloced_monitor == monitor; 353 if (!*inserted) { 354 delete alloced_monitor; 355 } 356 357 return monitor; 358 } 359 360 static void log_inflate(Thread* current, oop object, ObjectSynchronizer::InflateCause cause) { 361 if (log_is_enabled(Trace, monitorinflation)) { 362 ResourceMark rm(current); 363 log_trace(monitorinflation)("inflate: object=" INTPTR_FORMAT ", mark=" 364 INTPTR_FORMAT ", type='%s' cause=%s", p2i(object), 365 object->mark().value(), object->klass()->external_name(), 366 ObjectSynchronizer::inflate_cause_name(cause)); 367 } 368 } 369 370 static void post_monitor_inflate_event(EventJavaMonitorInflate* event, 371 const oop obj, 372 ObjectSynchronizer::InflateCause cause) { 373 assert(event != nullptr, "invariant"); 374 event->set_monitorClass(obj->klass()); 375 event->set_address((uintptr_t)(void*)obj); 376 event->set_cause((u1)cause); 377 event->commit(); 378 } 379 380 ObjectMonitor* LightweightSynchronizer::get_or_insert_monitor(oop object, JavaThread* current, ObjectSynchronizer::InflateCause cause) { 381 assert(UseObjectMonitorTable, "must be"); 382 383 EventJavaMonitorInflate event; 384 385 bool inserted; 386 ObjectMonitor* monitor = get_or_insert_monitor_from_table(object, current, &inserted); 387 388 if (inserted) { 389 // Hopefully the performance counters are allocated on distinct 390 // cache lines to avoid false sharing on MP systems ... 391 OM_PERFDATA_OP(Inflations, inc()); 392 log_inflate(current, object, cause); 393 if (event.should_commit()) { 394 post_monitor_inflate_event(&event, object, cause); 395 } 396 397 // The monitor has an anonymous owner so it is safe from async deflation. 398 ObjectSynchronizer::_in_use_list.add(monitor); 399 } 400 401 return monitor; 402 } 403 404 // Add the hashcode to the monitor to match the object and put it in the hashtable. 405 ObjectMonitor* LightweightSynchronizer::add_monitor(JavaThread* current, ObjectMonitor* monitor, oop obj) { 406 assert(UseObjectMonitorTable, "must be"); 407 assert(obj == monitor->object(), "must be"); 408 409 intptr_t hash = obj->mark().hash(); 410 assert(hash != 0, "must be set when claiming the object monitor"); 411 monitor->set_hash(hash); 412 413 return ObjectMonitorTable::monitor_put_get(current, monitor, obj); 414 } 415 416 bool LightweightSynchronizer::remove_monitor(Thread* current, ObjectMonitor* monitor, oop obj) { 417 assert(UseObjectMonitorTable, "must be"); 418 assert(monitor->object_peek() == obj, "must be, cleared objects are removed by is_dead"); 419 420 return ObjectMonitorTable::remove_monitor_entry(current, monitor); 421 } 422 423 void LightweightSynchronizer::deflate_mark_word(oop obj) { 424 assert(UseObjectMonitorTable, "must be"); 425 426 markWord mark = obj->mark_acquire(); 427 assert(!mark.has_no_hash(), "obj with inflated monitor must have had a hash"); 428 429 while (mark.has_monitor()) { 430 const markWord new_mark = mark.clear_lock_bits().set_unlocked(); 431 mark = obj->cas_set_mark(new_mark, mark); 432 } 433 } 434 435 void LightweightSynchronizer::initialize() { 436 if (!UseObjectMonitorTable) { 437 return; 438 } 439 ObjectMonitorTable::create(); 440 } 441 442 bool LightweightSynchronizer::needs_resize() { 443 if (!UseObjectMonitorTable) { 444 return false; 445 } 446 return ObjectMonitorTable::should_resize(); 447 } 448 449 bool LightweightSynchronizer::resize_table(JavaThread* current) { 450 if (!UseObjectMonitorTable) { 451 return true; 452 } 453 return ObjectMonitorTable::resize(current); 454 } 455 456 class LightweightSynchronizer::LockStackInflateContendedLocks : private OopClosure { 457 private: 458 oop _contended_oops[LockStack::CAPACITY]; 459 int _length; 460 461 void do_oop(oop* o) final { 462 oop obj = *o; 463 if (obj->mark_acquire().has_monitor()) { 464 if (_length > 0 && _contended_oops[_length - 1] == obj) { 465 // Recursive 466 return; 467 } 468 _contended_oops[_length++] = obj; 469 } 470 } 471 472 void do_oop(narrowOop* o) final { 473 ShouldNotReachHere(); 474 } 475 476 public: 477 LockStackInflateContendedLocks() : 478 _contended_oops(), 479 _length(0) {}; 480 481 void inflate(JavaThread* current) { 482 assert(current == JavaThread::current(), "must be"); 483 current->lock_stack().oops_do(this); 484 for (int i = 0; i < _length; i++) { 485 LightweightSynchronizer:: 486 inflate_fast_locked_object(_contended_oops[i], ObjectSynchronizer::inflate_cause_vm_internal, current, current); 487 } 488 } 489 }; 490 491 void LightweightSynchronizer::ensure_lock_stack_space(JavaThread* current) { 492 assert(current == JavaThread::current(), "must be"); 493 LockStack& lock_stack = current->lock_stack(); 494 495 // Make room on lock_stack 496 if (lock_stack.is_full()) { 497 // Inflate contended objects 498 LockStackInflateContendedLocks().inflate(current); 499 if (lock_stack.is_full()) { 500 // Inflate the oldest object 501 inflate_fast_locked_object(lock_stack.bottom(), ObjectSynchronizer::inflate_cause_vm_internal, current, current); 502 } 503 } 504 } 505 506 class LightweightSynchronizer::CacheSetter : StackObj { 507 JavaThread* const _thread; 508 BasicLock* const _lock; 509 ObjectMonitor* _monitor; 510 511 NONCOPYABLE(CacheSetter); 512 513 public: 514 CacheSetter(JavaThread* thread, BasicLock* lock) : 515 _thread(thread), 516 _lock(lock), 517 _monitor(nullptr) {} 518 519 ~CacheSetter() { 520 // Only use the cache if using the table. 521 if (UseObjectMonitorTable) { 522 if (_monitor != nullptr) { 523 _thread->om_set_monitor_cache(_monitor); 524 _lock->set_object_monitor_cache(_monitor); 525 } else { 526 _lock->clear_object_monitor_cache(); 527 } 528 } 529 } 530 531 void set_monitor(ObjectMonitor* monitor) { 532 assert(_monitor == nullptr, "only set once"); 533 _monitor = monitor; 534 } 535 536 }; 537 538 class LightweightSynchronizer::VerifyThreadState { 539 bool _no_safepoint; 540 541 public: 542 VerifyThreadState(JavaThread* locking_thread, JavaThread* current) : _no_safepoint(locking_thread != current) { 543 assert(current == Thread::current(), "must be"); 544 assert(locking_thread == current || locking_thread->is_obj_deopt_suspend(), "locking_thread may not run concurrently"); 545 if (_no_safepoint) { 546 DEBUG_ONLY(JavaThread::current()->inc_no_safepoint_count();) 547 } 548 } 549 ~VerifyThreadState() { 550 if (_no_safepoint){ 551 DEBUG_ONLY(JavaThread::current()->dec_no_safepoint_count();) 552 } 553 } 554 }; 555 556 inline bool LightweightSynchronizer::fast_lock_try_enter(oop obj, LockStack& lock_stack, JavaThread* current) { 557 markWord mark = obj->mark(); 558 while (mark.is_unlocked()) { 559 ensure_lock_stack_space(current); 560 assert(!lock_stack.is_full(), "must have made room on the lock stack"); 561 assert(!lock_stack.contains(obj), "thread must not already hold the lock"); 562 // Try to swing into 'fast-locked' state. 563 markWord locked_mark = mark.set_fast_locked(); 564 markWord old_mark = mark; 565 mark = obj->cas_set_mark(locked_mark, old_mark); 566 if (old_mark == mark) { 567 // Successfully fast-locked, push object to lock-stack and return. 568 lock_stack.push(obj); 569 return true; 570 } 571 } 572 return false; 573 } 574 575 bool LightweightSynchronizer::fast_lock_spin_enter(oop obj, LockStack& lock_stack, JavaThread* current, bool observed_deflation) { 576 assert(UseObjectMonitorTable, "must be"); 577 // Will spin with exponential backoff with an accumulative O(2^spin_limit) spins. 578 const int log_spin_limit = os::is_MP() ? LightweightFastLockingSpins : 1; 579 const int log_min_safepoint_check_interval = 10; 580 581 markWord mark = obj->mark(); 582 const auto should_spin = [&]() { 583 if (!mark.has_monitor()) { 584 // Spin while not inflated. 585 return true; 586 } else if (observed_deflation) { 587 // Spin while monitor is being deflated. 588 ObjectMonitor* monitor = ObjectSynchronizer::read_monitor(current, obj, mark); 589 return monitor == nullptr || monitor->is_being_async_deflated(); 590 } 591 // Else stop spinning. 592 return false; 593 }; 594 // Always attempt to lock once even when safepoint synchronizing. 595 bool should_process = false; 596 for (int i = 0; should_spin() && !should_process && i < log_spin_limit; i++) { 597 // Spin with exponential backoff. 598 const int total_spin_count = 1 << i; 599 const int inner_spin_count = MIN2(1 << log_min_safepoint_check_interval, total_spin_count); 600 const int outer_spin_count = total_spin_count / inner_spin_count; 601 for (int outer = 0; outer < outer_spin_count; outer++) { 602 should_process = SafepointMechanism::should_process(current); 603 if (should_process) { 604 // Stop spinning for safepoint. 605 break; 606 } 607 for (int inner = 1; inner < inner_spin_count; inner++) { 608 SpinPause(); 609 } 610 } 611 612 if (fast_lock_try_enter(obj, lock_stack, current)) return true; 613 } 614 return false; 615 } 616 617 void LightweightSynchronizer::enter_for(Handle obj, BasicLock* lock, JavaThread* locking_thread) { 618 assert(LockingMode == LM_LIGHTWEIGHT, "must be"); 619 JavaThread* current = JavaThread::current(); 620 VerifyThreadState vts(locking_thread, current); 621 622 if (obj->klass()->is_value_based()) { 623 ObjectSynchronizer::handle_sync_on_value_based_class(obj, locking_thread); 624 } 625 626 CacheSetter cache_setter(locking_thread, lock); 627 628 LockStack& lock_stack = locking_thread->lock_stack(); 629 630 ObjectMonitor* monitor = nullptr; 631 if (lock_stack.contains(obj())) { 632 monitor = inflate_fast_locked_object(obj(), ObjectSynchronizer::inflate_cause_monitor_enter, locking_thread, current); 633 bool entered = monitor->enter_for(locking_thread); 634 assert(entered, "recursive ObjectMonitor::enter_for must succeed"); 635 } else { 636 do { 637 // It is assumed that enter_for must enter on an object without contention. 638 monitor = inflate_and_enter(obj(), ObjectSynchronizer::inflate_cause_monitor_enter, locking_thread, current); 639 // But there may still be a race with deflation. 640 } while (monitor == nullptr); 641 } 642 643 assert(monitor != nullptr, "LightweightSynchronizer::enter_for must succeed"); 644 cache_setter.set_monitor(monitor); 645 } 646 647 void LightweightSynchronizer::enter(Handle obj, BasicLock* lock, JavaThread* current) { 648 assert(LockingMode == LM_LIGHTWEIGHT, "must be"); 649 assert(current == JavaThread::current(), "must be"); 650 651 if (obj->klass()->is_value_based()) { 652 ObjectSynchronizer::handle_sync_on_value_based_class(obj, current); 653 } 654 655 CacheSetter cache_setter(current, lock); 656 657 // Used when deflation is observed. Progress here requires progress 658 // from the deflator. After observing that the deflator is not 659 // making progress (after two yields), switch to sleeping. 660 SpinYield spin_yield(0, 2); 661 bool observed_deflation = false; 662 663 LockStack& lock_stack = current->lock_stack(); 664 665 if (!lock_stack.is_full() && lock_stack.try_recursive_enter(obj())) { 666 // Recursively fast locked 667 return; 668 } 669 670 if (lock_stack.contains(obj())) { 671 ObjectMonitor* monitor = inflate_fast_locked_object(obj(), ObjectSynchronizer::inflate_cause_monitor_enter, current, current); 672 bool entered = monitor->enter(current); 673 assert(entered, "recursive ObjectMonitor::enter must succeed"); 674 cache_setter.set_monitor(monitor); 675 return; 676 } 677 678 while (true) { 679 // Fast-locking does not use the 'lock' argument. 680 // Fast-lock spinning to avoid inflating for short critical sections. 681 // The goal is to only inflate when the extra cost of using ObjectMonitors 682 // is worth it. 683 // If deflation has been observed we also spin while deflation is ongoing. 684 if (fast_lock_try_enter(obj(), lock_stack, current)) { 685 return; 686 } else if (UseObjectMonitorTable && fast_lock_spin_enter(obj(), lock_stack, current, observed_deflation)) { 687 return; 688 } 689 690 if (observed_deflation) { 691 spin_yield.wait(); 692 } 693 694 ObjectMonitor* monitor = inflate_and_enter(obj(), ObjectSynchronizer::inflate_cause_monitor_enter, current, current); 695 if (monitor != nullptr) { 696 cache_setter.set_monitor(monitor); 697 return; 698 } 699 700 // If inflate_and_enter returns nullptr it is because a deflated monitor 701 // was encountered. Fallback to fast locking. The deflater is responsible 702 // for clearing out the monitor and transitioning the markWord back to 703 // fast locking. 704 observed_deflation = true; 705 } 706 } 707 708 void LightweightSynchronizer::exit(oop object, JavaThread* current) { 709 assert(LockingMode == LM_LIGHTWEIGHT, "must be"); 710 assert(current == Thread::current(), "must be"); 711 712 markWord mark = object->mark(); 713 assert(!mark.is_unlocked(), "must be"); 714 715 LockStack& lock_stack = current->lock_stack(); 716 if (mark.is_fast_locked()) { 717 if (lock_stack.try_recursive_exit(object)) { 718 // This is a recursive exit which succeeded 719 return; 720 } 721 if (lock_stack.is_recursive(object)) { 722 // Must inflate recursive locks if try_recursive_exit fails 723 // This happens for un-structured unlocks, could potentially 724 // fix try_recursive_exit to handle these. 725 inflate_fast_locked_object(object, ObjectSynchronizer::inflate_cause_vm_internal, current, current); 726 } 727 } 728 729 while (mark.is_fast_locked()) { 730 markWord unlocked_mark = mark.set_unlocked(); 731 markWord old_mark = mark; 732 mark = object->cas_set_mark(unlocked_mark, old_mark); 733 if (old_mark == mark) { 734 // CAS successful, remove from lock_stack 735 size_t recursion = lock_stack.remove(object) - 1; 736 assert(recursion == 0, "Should not have unlocked here"); 737 return; 738 } 739 } 740 741 assert(mark.has_monitor(), "must be"); 742 // The monitor exists 743 ObjectMonitor* monitor = ObjectSynchronizer::read_monitor(current, object, mark); 744 if (monitor->has_anonymous_owner()) { 745 assert(current->lock_stack().contains(object), "current must have object on its lock stack"); 746 monitor->set_owner_from_anonymous(current); 747 monitor->set_recursions(current->lock_stack().remove(object) - 1); 748 } 749 750 monitor->exit(current); 751 } 752 753 // LightweightSynchronizer::inflate_locked_or_imse is used to to get an inflated 754 // ObjectMonitor* with LM_LIGHTWEIGHT. It is used from contexts which require 755 // an inflated ObjectMonitor* for a monitor, and expects to throw a 756 // java.lang.IllegalMonitorStateException if it is not held by the current 757 // thread. Such as notify/wait and jni_exit. LM_LIGHTWEIGHT keeps it invariant 758 // that it only inflates if it is already locked by the current thread or the 759 // current thread is in the process of entering. To maintain this invariant we 760 // need to throw a java.lang.IllegalMonitorStateException before inflating if 761 // the current thread is not the owner. 762 // LightweightSynchronizer::inflate_locked_or_imse facilitates this. 763 ObjectMonitor* LightweightSynchronizer::inflate_locked_or_imse(oop obj, ObjectSynchronizer::InflateCause cause, TRAPS) { 764 assert(LockingMode == LM_LIGHTWEIGHT, "must be"); 765 JavaThread* current = THREAD; 766 767 for (;;) { 768 markWord mark = obj->mark_acquire(); 769 if (mark.is_unlocked()) { 770 // No lock, IMSE. 771 THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(), 772 "current thread is not owner", nullptr); 773 } 774 775 if (mark.is_fast_locked()) { 776 if (!current->lock_stack().contains(obj)) { 777 // Fast locked by other thread, IMSE. 778 THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(), 779 "current thread is not owner", nullptr); 780 } else { 781 // Current thread owns the lock, must inflate 782 return inflate_fast_locked_object(obj, cause, current, current); 783 } 784 } 785 786 assert(mark.has_monitor(), "must be"); 787 ObjectMonitor* monitor = ObjectSynchronizer::read_monitor(current, obj, mark); 788 if (monitor != nullptr) { 789 if (monitor->has_anonymous_owner()) { 790 LockStack& lock_stack = current->lock_stack(); 791 if (lock_stack.contains(obj)) { 792 // Current thread owns the lock but someone else inflated it. 793 // Fix owner and pop lock stack. 794 monitor->set_owner_from_anonymous(current); 795 monitor->set_recursions(lock_stack.remove(obj) - 1); 796 } else { 797 // Fast locked (and inflated) by other thread, or deflation in progress, IMSE. 798 THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(), 799 "current thread is not owner", nullptr); 800 } 801 } 802 return monitor; 803 } 804 } 805 } 806 807 ObjectMonitor* LightweightSynchronizer::inflate_into_object_header(oop object, ObjectSynchronizer::InflateCause cause, JavaThread* locking_thread, Thread* current) { 808 809 // The JavaThread* locking_thread parameter is only used by LM_LIGHTWEIGHT and requires 810 // that the locking_thread == Thread::current() or is suspended throughout the call by 811 // some other mechanism. 812 // Even with LM_LIGHTWEIGHT the thread might be nullptr when called from a non 813 // JavaThread. (As may still be the case from FastHashCode). However it is only 814 // important for the correctness of the LM_LIGHTWEIGHT algorithm that the thread 815 // is set when called from ObjectSynchronizer::enter from the owning thread, 816 // ObjectSynchronizer::enter_for from any thread, or ObjectSynchronizer::exit. 817 EventJavaMonitorInflate event; 818 819 for (;;) { 820 const markWord mark = object->mark_acquire(); 821 822 // The mark can be in one of the following states: 823 // * inflated - Just return if using stack-locking. 824 // If using fast-locking and the ObjectMonitor owner 825 // is anonymous and the locking_thread owns the 826 // object lock, then we make the locking_thread 827 // the ObjectMonitor owner and remove the lock from 828 // the locking_thread's lock stack. 829 // * fast-locked - Coerce it to inflated from fast-locked. 830 // * unlocked - Aggressively inflate the object. 831 832 // CASE: inflated 833 if (mark.has_monitor()) { 834 ObjectMonitor* inf = mark.monitor(); 835 markWord dmw = inf->header(); 836 assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value()); 837 if (inf->has_anonymous_owner() && 838 locking_thread != nullptr && locking_thread->lock_stack().contains(object)) { 839 inf->set_owner_from_anonymous(locking_thread); 840 size_t removed = locking_thread->lock_stack().remove(object); 841 inf->set_recursions(removed - 1); 842 } 843 return inf; 844 } 845 846 // CASE: fast-locked 847 // Could be fast-locked either by the locking_thread or by some other thread. 848 // 849 // Note that we allocate the ObjectMonitor speculatively, _before_ 850 // attempting to set the object's mark to the new ObjectMonitor. If 851 // the locking_thread owns the monitor, then we set the ObjectMonitor's 852 // owner to the locking_thread. Otherwise, we set the ObjectMonitor's owner 853 // to anonymous. If we lose the race to set the object's mark to the 854 // new ObjectMonitor, then we just delete it and loop around again. 855 // 856 if (mark.is_fast_locked()) { 857 ObjectMonitor* monitor = new ObjectMonitor(object); 858 monitor->set_header(mark.set_unlocked()); 859 bool own = locking_thread != nullptr && locking_thread->lock_stack().contains(object); 860 if (own) { 861 // Owned by locking_thread. 862 monitor->set_owner(locking_thread); 863 } else { 864 // Owned by somebody else. 865 monitor->set_anonymous_owner(); 866 } 867 markWord monitor_mark = markWord::encode(monitor); 868 markWord old_mark = object->cas_set_mark(monitor_mark, mark); 869 if (old_mark == mark) { 870 // Success! Return inflated monitor. 871 if (own) { 872 size_t removed = locking_thread->lock_stack().remove(object); 873 monitor->set_recursions(removed - 1); 874 } 875 // Once the ObjectMonitor is configured and object is associated 876 // with the ObjectMonitor, it is safe to allow async deflation: 877 ObjectSynchronizer::_in_use_list.add(monitor); 878 879 // Hopefully the performance counters are allocated on distinct 880 // cache lines to avoid false sharing on MP systems ... 881 OM_PERFDATA_OP(Inflations, inc()); 882 log_inflate(current, object, cause); 883 if (event.should_commit()) { 884 post_monitor_inflate_event(&event, object, cause); 885 } 886 return monitor; 887 } else { 888 delete monitor; 889 continue; // Interference -- just retry 890 } 891 } 892 893 // CASE: unlocked 894 // TODO-FIXME: for entry we currently inflate and then try to CAS _owner. 895 // If we know we're inflating for entry it's better to inflate by swinging a 896 // pre-locked ObjectMonitor pointer into the object header. A successful 897 // CAS inflates the object *and* confers ownership to the inflating thread. 898 // In the current implementation we use a 2-step mechanism where we CAS() 899 // to inflate and then CAS() again to try to swing _owner from null to current. 900 // An inflateTry() method that we could call from enter() would be useful. 901 902 assert(mark.is_unlocked(), "invariant: header=" INTPTR_FORMAT, mark.value()); 903 ObjectMonitor* m = new ObjectMonitor(object); 904 // prepare m for installation - set monitor to initial state 905 m->set_header(mark); 906 907 if (object->cas_set_mark(markWord::encode(m), mark) != mark) { 908 delete m; 909 m = nullptr; 910 continue; 911 // interference - the markword changed - just retry. 912 // The state-transitions are one-way, so there's no chance of 913 // live-lock -- "Inflated" is an absorbing state. 914 } 915 916 // Once the ObjectMonitor is configured and object is associated 917 // with the ObjectMonitor, it is safe to allow async deflation: 918 ObjectSynchronizer::_in_use_list.add(m); 919 920 // Hopefully the performance counters are allocated on distinct 921 // cache lines to avoid false sharing on MP systems ... 922 OM_PERFDATA_OP(Inflations, inc()); 923 log_inflate(current, object, cause); 924 if (event.should_commit()) { 925 post_monitor_inflate_event(&event, object, cause); 926 } 927 return m; 928 } 929 } 930 931 ObjectMonitor* LightweightSynchronizer::inflate_fast_locked_object(oop object, ObjectSynchronizer::InflateCause cause, JavaThread* locking_thread, JavaThread* current) { 932 assert(LockingMode == LM_LIGHTWEIGHT, "only used for lightweight"); 933 VerifyThreadState vts(locking_thread, current); 934 assert(locking_thread->lock_stack().contains(object), "locking_thread must have object on its lock stack"); 935 936 ObjectMonitor* monitor; 937 938 if (!UseObjectMonitorTable) { 939 return inflate_into_object_header(object, cause, locking_thread, current); 940 } 941 942 // Inflating requires a hash code 943 ObjectSynchronizer::FastHashCode(current, object); 944 945 markWord mark = object->mark_acquire(); 946 assert(!mark.is_unlocked(), "Cannot be unlocked"); 947 948 for (;;) { 949 // Fetch the monitor from the table 950 monitor = get_or_insert_monitor(object, current, cause); 951 952 // ObjectMonitors are always inserted as anonymously owned, this thread is 953 // the current holder of the monitor. So unless the entry is stale and 954 // contains a deflating monitor it must be anonymously owned. 955 if (monitor->has_anonymous_owner()) { 956 // The monitor must be anonymously owned if it was added 957 assert(monitor == get_monitor_from_table(current, object), "The monitor must be found"); 958 // New fresh monitor 959 break; 960 } 961 962 // If the monitor was not anonymously owned then we got a deflating monitor 963 // from the table. We need to let the deflator make progress and remove this 964 // entry before we are allowed to add a new one. 965 os::naked_yield(); 966 assert(monitor->is_being_async_deflated(), "Should be the reason"); 967 } 968 969 // Set the mark word; loop to handle concurrent updates to other parts of the mark word 970 while (mark.is_fast_locked()) { 971 mark = object->cas_set_mark(mark.set_has_monitor(), mark); 972 } 973 974 // Indicate that the monitor now has a known owner 975 monitor->set_owner_from_anonymous(locking_thread); 976 977 // Remove the entry from the thread's lock stack 978 monitor->set_recursions(locking_thread->lock_stack().remove(object) - 1); 979 980 if (locking_thread == current) { 981 // Only change the thread local state of the current thread. 982 locking_thread->om_set_monitor_cache(monitor); 983 } 984 985 return monitor; 986 } 987 988 ObjectMonitor* LightweightSynchronizer::inflate_and_enter(oop object, ObjectSynchronizer::InflateCause cause, JavaThread* locking_thread, JavaThread* current) { 989 assert(LockingMode == LM_LIGHTWEIGHT, "only used for lightweight"); 990 VerifyThreadState vts(locking_thread, current); 991 992 // Note: In some paths (deoptimization) the 'current' thread inflates and 993 // enters the lock on behalf of the 'locking_thread' thread. 994 995 ObjectMonitor* monitor = nullptr; 996 997 if (!UseObjectMonitorTable) { 998 // Do the old inflate and enter. 999 monitor = inflate_into_object_header(object, cause, locking_thread, current); 1000 1001 bool entered; 1002 if (locking_thread == current) { 1003 entered = monitor->enter(locking_thread); 1004 } else { 1005 entered = monitor->enter_for(locking_thread); 1006 } 1007 1008 // enter returns false for deflation found. 1009 return entered ? monitor : nullptr; 1010 } 1011 1012 NoSafepointVerifier nsv; 1013 1014 // Lightweight monitors require that hash codes are installed first 1015 ObjectSynchronizer::FastHashCode(locking_thread, object); 1016 1017 // Try to get the monitor from the thread-local cache. 1018 // There's no need to use the cache if we are locking 1019 // on behalf of another thread. 1020 if (current == locking_thread) { 1021 monitor = current->om_get_from_monitor_cache(object); 1022 } 1023 1024 // Get or create the monitor 1025 if (monitor == nullptr) { 1026 monitor = get_or_insert_monitor(object, current, cause); 1027 } 1028 1029 if (monitor->try_enter(locking_thread)) { 1030 return monitor; 1031 } 1032 1033 // Holds is_being_async_deflated() stable throughout this function. 1034 ObjectMonitorContentionMark contention_mark(monitor); 1035 1036 /// First handle the case where the monitor from the table is deflated 1037 if (monitor->is_being_async_deflated()) { 1038 // The MonitorDeflation thread is deflating the monitor. The locking thread 1039 // must spin until further progress has been made. 1040 1041 const markWord mark = object->mark_acquire(); 1042 1043 if (mark.has_monitor()) { 1044 // Waiting on the deflation thread to remove the deflated monitor from the table. 1045 os::naked_yield(); 1046 1047 } else if (mark.is_fast_locked()) { 1048 // Some other thread managed to fast-lock the lock, or this is a 1049 // recursive lock from the same thread; yield for the deflation 1050 // thread to remove the deflated monitor from the table. 1051 os::naked_yield(); 1052 1053 } else { 1054 assert(mark.is_unlocked(), "Implied"); 1055 // Retry immediately 1056 } 1057 1058 // Retry 1059 return nullptr; 1060 } 1061 1062 for (;;) { 1063 const markWord mark = object->mark_acquire(); 1064 // The mark can be in one of the following states: 1065 // * inflated - If the ObjectMonitor owner is anonymous 1066 // and the locking_thread owns the object 1067 // lock, then we make the locking_thread 1068 // the ObjectMonitor owner and remove the 1069 // lock from the locking_thread's lock stack. 1070 // * fast-locked - Coerce it to inflated from fast-locked. 1071 // * neutral - Inflate the object. Successful CAS is locked 1072 1073 // CASE: inflated 1074 if (mark.has_monitor()) { 1075 LockStack& lock_stack = locking_thread->lock_stack(); 1076 if (monitor->has_anonymous_owner() && lock_stack.contains(object)) { 1077 // The lock is fast-locked by the locking thread, 1078 // convert it to a held monitor with a known owner. 1079 monitor->set_owner_from_anonymous(locking_thread); 1080 monitor->set_recursions(lock_stack.remove(object) - 1); 1081 } 1082 1083 break; // Success 1084 } 1085 1086 // CASE: fast-locked 1087 // Could be fast-locked either by locking_thread or by some other thread. 1088 // 1089 if (mark.is_fast_locked()) { 1090 markWord old_mark = object->cas_set_mark(mark.set_has_monitor(), mark); 1091 if (old_mark != mark) { 1092 // CAS failed 1093 continue; 1094 } 1095 1096 // Success! Return inflated monitor. 1097 LockStack& lock_stack = locking_thread->lock_stack(); 1098 if (lock_stack.contains(object)) { 1099 // The lock is fast-locked by the locking thread, 1100 // convert it to a held monitor with a known owner. 1101 monitor->set_owner_from_anonymous(locking_thread); 1102 monitor->set_recursions(lock_stack.remove(object) - 1); 1103 } 1104 1105 break; // Success 1106 } 1107 1108 // CASE: neutral (unlocked) 1109 1110 // Catch if the object's header is not neutral (not locked and 1111 // not marked is what we care about here). 1112 assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value()); 1113 markWord old_mark = object->cas_set_mark(mark.set_has_monitor(), mark); 1114 if (old_mark != mark) { 1115 // CAS failed 1116 continue; 1117 } 1118 1119 // Transitioned from unlocked to monitor means locking_thread owns the lock. 1120 monitor->set_owner_from_anonymous(locking_thread); 1121 1122 return monitor; 1123 } 1124 1125 if (current == locking_thread) { 1126 // One round of spinning 1127 if (monitor->spin_enter(locking_thread)) { 1128 return monitor; 1129 } 1130 1131 // Monitor is contended, take the time before entering to fix the lock stack. 1132 LockStackInflateContendedLocks().inflate(current); 1133 } 1134 1135 // enter can block for safepoints; clear the unhandled object oop 1136 PauseNoSafepointVerifier pnsv(&nsv); 1137 object = nullptr; 1138 1139 if (current == locking_thread) { 1140 monitor->enter_with_contention_mark(locking_thread, contention_mark); 1141 } else { 1142 monitor->enter_for_with_contention_mark(locking_thread, contention_mark); 1143 } 1144 1145 return monitor; 1146 } 1147 1148 void LightweightSynchronizer::deflate_monitor(Thread* current, oop obj, ObjectMonitor* monitor) { 1149 if (obj != nullptr) { 1150 deflate_mark_word(obj); 1151 } 1152 bool removed = remove_monitor(current, monitor, obj); 1153 if (obj != nullptr) { 1154 assert(removed, "Should have removed the entry if obj was alive"); 1155 } 1156 } 1157 1158 ObjectMonitor* LightweightSynchronizer::get_monitor_from_table(Thread* current, oop obj) { 1159 assert(UseObjectMonitorTable, "must be"); 1160 return ObjectMonitorTable::monitor_get(current, obj); 1161 } 1162 1163 bool LightweightSynchronizer::contains_monitor(Thread* current, ObjectMonitor* monitor) { 1164 assert(UseObjectMonitorTable, "must be"); 1165 return ObjectMonitorTable::contains_monitor(current, monitor); 1166 } 1167 1168 bool LightweightSynchronizer::quick_enter(oop obj, BasicLock* lock, JavaThread* current) { 1169 assert(current->thread_state() == _thread_in_Java, "must be"); 1170 assert(obj != nullptr, "must be"); 1171 NoSafepointVerifier nsv; 1172 1173 // If quick_enter succeeds with entering, the cache should be in a valid initialized state. 1174 CacheSetter cache_setter(current, lock); 1175 1176 LockStack& lock_stack = current->lock_stack(); 1177 if (lock_stack.is_full()) { 1178 // Always go into runtime if the lock stack is full. 1179 return false; 1180 } 1181 1182 const markWord mark = obj->mark(); 1183 1184 #ifndef _LP64 1185 // Only for 32bit which has limited support for fast locking outside the runtime. 1186 if (lock_stack.try_recursive_enter(obj)) { 1187 // Recursive lock successful. 1188 return true; 1189 } 1190 1191 if (mark.is_unlocked()) { 1192 markWord locked_mark = mark.set_fast_locked(); 1193 if (obj->cas_set_mark(locked_mark, mark) == mark) { 1194 // Successfully fast-locked, push object to lock-stack and return. 1195 lock_stack.push(obj); 1196 return true; 1197 } 1198 } 1199 #endif 1200 1201 if (mark.has_monitor()) { 1202 ObjectMonitor* const monitor = UseObjectMonitorTable ? current->om_get_from_monitor_cache(obj) : 1203 ObjectSynchronizer::read_monitor(mark); 1204 1205 if (monitor == nullptr) { 1206 // Take the slow-path on a cache miss. 1207 return false; 1208 } 1209 1210 if (monitor->try_enter(current)) { 1211 // ObjectMonitor enter successful. 1212 cache_setter.set_monitor(monitor); 1213 return true; 1214 } 1215 } 1216 1217 // Slow-path. 1218 return false; 1219 }