1 /* 2 * Copyright (c) 2005, 2019, 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/classLoaderDataGraph.hpp" 27 #include "jfr/jfrEvents.hpp" 28 #include "jfr/support/jfrThreadId.hpp" 29 #include "logging/log.hpp" 30 #include "memory/resourceArea.hpp" 31 #include "oops/klass.inline.hpp" 32 #include "oops/markWord.hpp" 33 #include "oops/oop.inline.hpp" 34 #include "runtime/atomic.hpp" 35 #include "runtime/basicLock.hpp" 36 #include "runtime/biasedLocking.hpp" 37 #include "runtime/handles.inline.hpp" 38 #include "runtime/mutexLocker.inline.hpp" 39 #include "runtime/task.hpp" 40 #include "runtime/threadSMR.hpp" 41 #include "runtime/vframe.hpp" 42 #include "runtime/vmThread.hpp" 43 #include "runtime/vmOperations.hpp" 44 45 46 static bool _biased_locking_enabled = false; 47 BiasedLockingCounters BiasedLocking::_counters; 48 49 static GrowableArray<Handle>* _preserved_oop_stack = NULL; 50 static GrowableArray<markWord>* _preserved_mark_stack = NULL; 51 52 static void enable_biased_locking(InstanceKlass* k) { 53 k->set_prototype_header(markWord::biased_locking_prototype()); 54 } 55 56 static void enable_biased_locking() { 57 _biased_locking_enabled = true; 58 log_info(biasedlocking)("Biased locking enabled"); 59 } 60 61 class VM_EnableBiasedLocking: public VM_Operation { 62 public: 63 VM_EnableBiasedLocking() {} 64 VMOp_Type type() const { return VMOp_EnableBiasedLocking; } 65 Mode evaluation_mode() const { return _async_safepoint; } 66 bool is_cheap_allocated() const { return true; } 67 68 void doit() { 69 // Iterate the class loader data dictionaries enabling biased locking for all 70 // currently loaded classes. 71 ClassLoaderDataGraph::dictionary_classes_do(enable_biased_locking); 72 // Indicate that future instances should enable it as well 73 enable_biased_locking(); 74 } 75 76 bool allow_nested_vm_operations() const { return false; } 77 }; 78 79 80 // One-shot PeriodicTask subclass for enabling biased locking 81 class EnableBiasedLockingTask : public PeriodicTask { 82 public: 83 EnableBiasedLockingTask(size_t interval_time) : PeriodicTask(interval_time) {} 84 85 virtual void task() { 86 // Use async VM operation to avoid blocking the Watcher thread. 87 // VM Thread will free C heap storage. 88 VM_EnableBiasedLocking *op = new VM_EnableBiasedLocking(); 89 VMThread::execute(op); 90 91 // Reclaim our storage and disenroll ourself 92 delete this; 93 } 94 }; 95 96 97 void BiasedLocking::init() { 98 // If biased locking is enabled and BiasedLockingStartupDelay is set, 99 // schedule a task to fire after the specified delay which turns on 100 // biased locking for all currently loaded classes as well as future 101 // ones. This could be a workaround for startup time regressions 102 // due to large number of safepoints being taken during VM startup for 103 // bias revocation. 104 if (UseBiasedLocking) { 105 if (BiasedLockingStartupDelay > 0) { 106 EnableBiasedLockingTask* task = new EnableBiasedLockingTask(BiasedLockingStartupDelay); 107 task->enroll(); 108 } else { 109 enable_biased_locking(); 110 } 111 } 112 } 113 114 115 bool BiasedLocking::enabled() { 116 assert(UseBiasedLocking, "precondition"); 117 // We check "BiasedLockingStartupDelay == 0" here to cover the 118 // possibility of calls to BiasedLocking::enabled() before 119 // BiasedLocking::init(). 120 return _biased_locking_enabled || BiasedLockingStartupDelay == 0; 121 } 122 123 124 // Returns MonitorInfos for all objects locked on this thread in youngest to oldest order 125 static GrowableArray<MonitorInfo*>* get_or_compute_monitor_info(JavaThread* thread) { 126 GrowableArray<MonitorInfo*>* info = thread->cached_monitor_info(); 127 if (info != NULL) { 128 return info; 129 } 130 131 info = new GrowableArray<MonitorInfo*>(); 132 133 // It's possible for the thread to not have any Java frames on it, 134 // i.e., if it's the main thread and it's already returned from main() 135 if (thread->has_last_Java_frame()) { 136 RegisterMap rm(thread); 137 for (javaVFrame* vf = thread->last_java_vframe(&rm); vf != NULL; vf = vf->java_sender()) { 138 GrowableArray<MonitorInfo*> *monitors = vf->monitors(); 139 if (monitors != NULL) { 140 int len = monitors->length(); 141 // Walk monitors youngest to oldest 142 for (int i = len - 1; i >= 0; i--) { 143 MonitorInfo* mon_info = monitors->at(i); 144 if (mon_info->eliminated()) continue; 145 oop owner = mon_info->owner(); 146 if (owner != NULL) { 147 info->append(mon_info); 148 } 149 } 150 } 151 } 152 } 153 154 thread->set_cached_monitor_info(info); 155 return info; 156 } 157 158 159 // After the call, *biased_locker will be set to obj->mark()->biased_locker() if biased_locker != NULL, 160 // AND it is a living thread. Otherwise it will not be updated, (i.e. the caller is responsible for initialization). 161 void BiasedLocking::single_revoke_at_safepoint(oop obj, bool is_bulk, JavaThread* requesting_thread, JavaThread** biased_locker) { 162 assert(SafepointSynchronize::is_at_safepoint(), "must be done at safepoint"); 163 assert(Thread::current()->is_VM_thread(), "must be VMThread"); 164 165 markWord mark = obj->mark(); 166 if (!mark.has_bias_pattern()) { 167 if (log_is_enabled(Info, biasedlocking)) { 168 ResourceMark rm; 169 log_info(biasedlocking)(" (Skipping revocation of object " INTPTR_FORMAT 170 ", mark " INTPTR_FORMAT ", type %s" 171 ", requesting thread " INTPTR_FORMAT 172 " because it's no longer biased)", 173 p2i((void *)obj), mark.value(), 174 obj->klass()->external_name(), 175 (intptr_t) requesting_thread); 176 } 177 return; 178 } 179 180 uint age = mark.age(); 181 markWord unbiased_prototype = markWord::prototype().set_age(age); 182 183 // Log at "info" level if not bulk, else "trace" level 184 if (!is_bulk) { 185 ResourceMark rm; 186 log_info(biasedlocking)("Revoking bias of object " INTPTR_FORMAT ", mark " 187 INTPTR_FORMAT ", type %s, prototype header " INTPTR_FORMAT 188 ", requesting thread " INTPTR_FORMAT, 189 p2i((void *)obj), 190 mark.value(), 191 obj->klass()->external_name(), 192 obj->klass()->prototype_header().value(), 193 (intptr_t) requesting_thread); 194 } else { 195 ResourceMark rm; 196 log_trace(biasedlocking)("Revoking bias of object " INTPTR_FORMAT " , mark " 197 INTPTR_FORMAT " , type %s , prototype header " INTPTR_FORMAT 198 " , requesting thread " INTPTR_FORMAT, 199 p2i((void *)obj), 200 mark.value(), 201 obj->klass()->external_name(), 202 obj->klass()->prototype_header().value(), 203 (intptr_t) requesting_thread); 204 } 205 206 JavaThread* biased_thread = mark.biased_locker(); 207 if (biased_thread == NULL) { 208 // Object is anonymously biased. We can get here if, for 209 // example, we revoke the bias due to an identity hash code 210 // being computed for an object. 211 obj->set_mark(unbiased_prototype); 212 213 // Log at "info" level if not bulk, else "trace" level 214 if (!is_bulk) { 215 log_info(biasedlocking)(" Revoked bias of anonymously-biased object"); 216 } else { 217 log_trace(biasedlocking)(" Revoked bias of anonymously-biased object"); 218 } 219 return; 220 } 221 222 // Handle case where the thread toward which the object was biased has exited 223 bool thread_is_alive = false; 224 if (requesting_thread == biased_thread) { 225 thread_is_alive = true; 226 } else { 227 ThreadsListHandle tlh; 228 thread_is_alive = tlh.includes(biased_thread); 229 } 230 if (!thread_is_alive) { 231 obj->set_mark(unbiased_prototype); 232 // Log at "info" level if not bulk, else "trace" level 233 if (!is_bulk) { 234 log_info(biasedlocking)(" Revoked bias of object biased toward dead thread (" 235 PTR_FORMAT ")", p2i(biased_thread)); 236 } else { 237 log_trace(biasedlocking)(" Revoked bias of object biased toward dead thread (" 238 PTR_FORMAT ")", p2i(biased_thread)); 239 } 240 return; 241 } 242 243 // Log at "info" level if not bulk, else "trace" level 244 if (!is_bulk) { 245 log_info(biasedlocking)(" Revoked bias of object biased toward live thread (" 246 PTR_FORMAT ")", p2i(biased_thread)); 247 } else { 248 log_trace(biasedlocking)(" Revoked bias of object biased toward live thread (" 249 PTR_FORMAT ")", p2i(biased_thread)); 250 } 251 252 // Thread owning bias is alive. 253 // Check to see whether it currently owns the lock and, if so, 254 // write down the needed displaced headers to the thread's stack. 255 // Otherwise, restore the object's header either to the unlocked 256 // or unbiased state. 257 GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(biased_thread); 258 BasicLock* highest_lock = NULL; 259 for (int i = 0; i < cached_monitor_info->length(); i++) { 260 MonitorInfo* mon_info = cached_monitor_info->at(i); 261 if (mon_info->owner() == obj) { 262 log_trace(biasedlocking)(" mon_info->owner (" PTR_FORMAT ") == obj (" PTR_FORMAT ")", 263 p2i((void *) mon_info->owner()), 264 p2i((void *) obj)); 265 // Assume recursive case and fix up highest lock below 266 markWord mark = markWord::encode((BasicLock*) NULL); 267 highest_lock = mon_info->lock(); 268 highest_lock->set_displaced_header(mark); 269 } else { 270 log_trace(biasedlocking)(" mon_info->owner (" PTR_FORMAT ") != obj (" PTR_FORMAT ")", 271 p2i((void *) mon_info->owner()), 272 p2i((void *) obj)); 273 } 274 } 275 if (highest_lock != NULL) { 276 // Fix up highest lock to contain displaced header and point 277 // object at it 278 highest_lock->set_displaced_header(unbiased_prototype); 279 // Reset object header to point to displaced mark. 280 // Must release store the lock address for platforms without TSO 281 // ordering (e.g. ppc). 282 obj->release_set_mark(markWord::encode(highest_lock)); 283 assert(!obj->mark().has_bias_pattern(), "illegal mark state: stack lock used bias bit"); 284 // Log at "info" level if not bulk, else "trace" level 285 if (!is_bulk) { 286 log_info(biasedlocking)(" Revoked bias of currently-locked object"); 287 } else { 288 log_trace(biasedlocking)(" Revoked bias of currently-locked object"); 289 } 290 } else { 291 // Log at "info" level if not bulk, else "trace" level 292 if (!is_bulk) { 293 log_info(biasedlocking)(" Revoked bias of currently-unlocked object"); 294 } else { 295 log_trace(biasedlocking)(" Revoked bias of currently-unlocked object"); 296 } 297 // Store the unlocked value into the object's header. 298 obj->set_mark(unbiased_prototype); 299 } 300 301 // If requested, return information on which thread held the bias 302 if (biased_locker != NULL) { 303 *biased_locker = biased_thread; 304 } 305 } 306 307 308 enum HeuristicsResult { 309 HR_NOT_BIASED = 1, 310 HR_SINGLE_REVOKE = 2, 311 HR_BULK_REBIAS = 3, 312 HR_BULK_REVOKE = 4 313 }; 314 315 316 static HeuristicsResult update_heuristics(oop o) { 317 markWord mark = o->mark(); 318 if (!mark.has_bias_pattern()) { 319 return HR_NOT_BIASED; 320 } 321 322 // Heuristics to attempt to throttle the number of revocations. 323 // Stages: 324 // 1. Revoke the biases of all objects in the heap of this type, 325 // but allow rebiasing of those objects if unlocked. 326 // 2. Revoke the biases of all objects in the heap of this type 327 // and don't allow rebiasing of these objects. Disable 328 // allocation of objects of that type with the bias bit set. 329 Klass* k = o->klass(); 330 jlong cur_time = os::javaTimeMillis(); 331 jlong last_bulk_revocation_time = k->last_biased_lock_bulk_revocation_time(); 332 int revocation_count = k->biased_lock_revocation_count(); 333 if ((revocation_count >= BiasedLockingBulkRebiasThreshold) && 334 (revocation_count < BiasedLockingBulkRevokeThreshold) && 335 (last_bulk_revocation_time != 0) && 336 (cur_time - last_bulk_revocation_time >= BiasedLockingDecayTime)) { 337 // This is the first revocation we've seen in a while of an 338 // object of this type since the last time we performed a bulk 339 // rebiasing operation. The application is allocating objects in 340 // bulk which are biased toward a thread and then handing them 341 // off to another thread. We can cope with this allocation 342 // pattern via the bulk rebiasing mechanism so we reset the 343 // klass's revocation count rather than allow it to increase 344 // monotonically. If we see the need to perform another bulk 345 // rebias operation later, we will, and if subsequently we see 346 // many more revocation operations in a short period of time we 347 // will completely disable biasing for this type. 348 k->set_biased_lock_revocation_count(0); 349 revocation_count = 0; 350 } 351 352 // Make revocation count saturate just beyond BiasedLockingBulkRevokeThreshold 353 if (revocation_count <= BiasedLockingBulkRevokeThreshold) { 354 revocation_count = k->atomic_incr_biased_lock_revocation_count(); 355 } 356 357 if (revocation_count == BiasedLockingBulkRevokeThreshold) { 358 return HR_BULK_REVOKE; 359 } 360 361 if (revocation_count == BiasedLockingBulkRebiasThreshold) { 362 return HR_BULK_REBIAS; 363 } 364 365 return HR_SINGLE_REVOKE; 366 } 367 368 369 void BiasedLocking::bulk_revoke_at_safepoint(oop o, bool bulk_rebias, JavaThread* requesting_thread) { 370 assert(SafepointSynchronize::is_at_safepoint(), "must be done at safepoint"); 371 assert(Thread::current()->is_VM_thread(), "must be VMThread"); 372 373 log_info(biasedlocking)("* Beginning bulk revocation (kind == %s) because of object " 374 INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s", 375 (bulk_rebias ? "rebias" : "revoke"), 376 p2i((void *) o), 377 o->mark().value(), 378 o->klass()->external_name()); 379 380 jlong cur_time = os::javaTimeMillis(); 381 o->klass()->set_last_biased_lock_bulk_revocation_time(cur_time); 382 383 Klass* k_o = o->klass(); 384 Klass* klass = k_o; 385 386 { 387 JavaThreadIteratorWithHandle jtiwh; 388 389 if (bulk_rebias) { 390 // Use the epoch in the klass of the object to implicitly revoke 391 // all biases of objects of this data type and force them to be 392 // reacquired. However, we also need to walk the stacks of all 393 // threads and update the headers of lightweight locked objects 394 // with biases to have the current epoch. 395 396 // If the prototype header doesn't have the bias pattern, don't 397 // try to update the epoch -- assume another VM operation came in 398 // and reset the header to the unbiased state, which will 399 // implicitly cause all existing biases to be revoked 400 if (klass->prototype_header().has_bias_pattern()) { 401 int prev_epoch = klass->prototype_header().bias_epoch(); 402 klass->set_prototype_header(klass->prototype_header().incr_bias_epoch()); 403 int cur_epoch = klass->prototype_header().bias_epoch(); 404 405 // Now walk all threads' stacks and adjust epochs of any biased 406 // and locked objects of this data type we encounter 407 for (; JavaThread *thr = jtiwh.next(); ) { 408 GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(thr); 409 for (int i = 0; i < cached_monitor_info->length(); i++) { 410 MonitorInfo* mon_info = cached_monitor_info->at(i); 411 oop owner = mon_info->owner(); 412 markWord mark = owner->mark(); 413 if ((owner->klass() == k_o) && mark.has_bias_pattern()) { 414 // We might have encountered this object already in the case of recursive locking 415 assert(mark.bias_epoch() == prev_epoch || mark.bias_epoch() == cur_epoch, "error in bias epoch adjustment"); 416 owner->set_mark(mark.set_bias_epoch(cur_epoch)); 417 } 418 } 419 } 420 } 421 422 // At this point we're done. All we have to do is potentially 423 // adjust the header of the given object to revoke its bias. 424 single_revoke_at_safepoint(o, true, requesting_thread, NULL); 425 } else { 426 if (log_is_enabled(Info, biasedlocking)) { 427 ResourceMark rm; 428 log_info(biasedlocking)("* Disabling biased locking for type %s", klass->external_name()); 429 } 430 431 // Disable biased locking for this data type. Not only will this 432 // cause future instances to not be biased, but existing biased 433 // instances will notice that this implicitly caused their biases 434 // to be revoked. 435 klass->set_prototype_header(markWord::prototype()); 436 437 // Now walk all threads' stacks and forcibly revoke the biases of 438 // any locked and biased objects of this data type we encounter. 439 for (; JavaThread *thr = jtiwh.next(); ) { 440 GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(thr); 441 for (int i = 0; i < cached_monitor_info->length(); i++) { 442 MonitorInfo* mon_info = cached_monitor_info->at(i); 443 oop owner = mon_info->owner(); 444 markWord mark = owner->mark(); 445 if ((owner->klass() == k_o) && mark.has_bias_pattern()) { 446 single_revoke_at_safepoint(owner, true, requesting_thread, NULL); 447 } 448 } 449 } 450 451 // Must force the bias of the passed object to be forcibly revoked 452 // as well to ensure guarantees to callers 453 single_revoke_at_safepoint(o, true, requesting_thread, NULL); 454 } 455 } // ThreadsListHandle is destroyed here. 456 457 log_info(biasedlocking)("* Ending bulk revocation"); 458 459 assert(!o->mark().has_bias_pattern(), "bug in bulk bias revocation"); 460 } 461 462 463 static void clean_up_cached_monitor_info(JavaThread* thread = NULL) { 464 if (thread != NULL) { 465 thread->set_cached_monitor_info(NULL); 466 } else { 467 // Walk the thread list clearing out the cached monitors 468 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thr = jtiwh.next(); ) { 469 thr->set_cached_monitor_info(NULL); 470 } 471 } 472 } 473 474 475 class VM_BulkRevokeBias : public VM_Operation { 476 private: 477 Handle* _obj; 478 JavaThread* _requesting_thread; 479 bool _bulk_rebias; 480 uint64_t _safepoint_id; 481 482 public: 483 VM_BulkRevokeBias(Handle* obj, JavaThread* requesting_thread, 484 bool bulk_rebias) 485 : _obj(obj) 486 , _requesting_thread(requesting_thread) 487 , _bulk_rebias(bulk_rebias) 488 , _safepoint_id(0) {} 489 490 virtual VMOp_Type type() const { return VMOp_BulkRevokeBias; } 491 492 virtual void doit() { 493 BiasedLocking::bulk_revoke_at_safepoint((*_obj)(), _bulk_rebias, _requesting_thread); 494 _safepoint_id = SafepointSynchronize::safepoint_id(); 495 clean_up_cached_monitor_info(); 496 } 497 498 bool is_bulk_rebias() const { 499 return _bulk_rebias; 500 } 501 502 uint64_t safepoint_id() const { 503 return _safepoint_id; 504 } 505 }; 506 507 508 class RevokeOneBias : public ThreadClosure { 509 protected: 510 Handle _obj; 511 JavaThread* _requesting_thread; 512 JavaThread* _biased_locker; 513 BiasedLocking::Condition _status_code; 514 traceid _biased_locker_id; 515 516 public: 517 RevokeOneBias(Handle obj, JavaThread* requesting_thread, JavaThread* biased_locker) 518 : _obj(obj) 519 , _requesting_thread(requesting_thread) 520 , _biased_locker(biased_locker) 521 , _status_code(BiasedLocking::NOT_BIASED) 522 , _biased_locker_id(0) {} 523 524 void do_thread(Thread* target) { 525 assert(target == _biased_locker, "Wrong thread"); 526 527 oop o = _obj(); 528 markWord mark = o->mark(); 529 530 if (!mark.has_bias_pattern()) { 531 return; 532 } 533 534 markWord prototype = o->klass()->prototype_header(); 535 if (!prototype.has_bias_pattern()) { 536 // This object has a stale bias from before the handshake 537 // was requested. If we fail this race, the object's bias 538 // has been revoked by another thread so we simply return. 539 markWord biased_value = mark; 540 mark = o->cas_set_mark(markWord::prototype().set_age(mark.age()), mark); 541 assert(!o->mark().has_bias_pattern(), "even if we raced, should still be revoked"); 542 if (biased_value == mark) { 543 _status_code = BiasedLocking::BIAS_REVOKED; 544 } 545 return; 546 } 547 548 if (_biased_locker == mark.biased_locker()) { 549 if (mark.bias_epoch() == prototype.bias_epoch()) { 550 // Epoch is still valid. This means biaser could be currently 551 // synchronized on this object. We must walk its stack looking 552 // for monitor records associated with this object and change 553 // them to be stack locks if any are found. 554 ResourceMark rm; 555 BiasedLocking::walk_stack_and_revoke(o, _biased_locker); 556 _biased_locker->set_cached_monitor_info(NULL); 557 assert(!o->mark().has_bias_pattern(), "invariant"); 558 _biased_locker_id = JFR_THREAD_ID(_biased_locker); 559 _status_code = BiasedLocking::BIAS_REVOKED; 560 return; 561 } else { 562 markWord biased_value = mark; 563 mark = o->cas_set_mark(markWord::prototype().set_age(mark.age()), mark); 564 if (mark == biased_value || !mark.has_bias_pattern()) { 565 assert(!o->mark().has_bias_pattern(), "should be revoked"); 566 _status_code = (biased_value == mark) ? BiasedLocking::BIAS_REVOKED : BiasedLocking::NOT_BIASED; 567 return; 568 } 569 } 570 } 571 572 _status_code = BiasedLocking::NOT_REVOKED; 573 } 574 575 BiasedLocking::Condition status_code() const { 576 return _status_code; 577 } 578 579 traceid biased_locker() const { 580 return _biased_locker_id; 581 } 582 }; 583 584 585 static void post_self_revocation_event(EventBiasedLockSelfRevocation* event, Klass* k) { 586 assert(event != NULL, "invariant"); 587 assert(k != NULL, "invariant"); 588 assert(event->should_commit(), "invariant"); 589 event->set_lockClass(k); 590 event->commit(); 591 } 592 593 static void post_revocation_event(EventBiasedLockRevocation* event, Klass* k, RevokeOneBias* op) { 594 assert(event != NULL, "invariant"); 595 assert(k != NULL, "invariant"); 596 assert(op != NULL, "invariant"); 597 assert(event->should_commit(), "invariant"); 598 event->set_lockClass(k); 599 event->set_safepointId(0); 600 event->set_previousOwner(op->biased_locker()); 601 event->commit(); 602 } 603 604 static void post_class_revocation_event(EventBiasedLockClassRevocation* event, Klass* k, VM_BulkRevokeBias* op) { 605 assert(event != NULL, "invariant"); 606 assert(k != NULL, "invariant"); 607 assert(op != NULL, "invariant"); 608 assert(event->should_commit(), "invariant"); 609 event->set_revokedClass(k); 610 event->set_disableBiasing(!op->is_bulk_rebias()); 611 event->set_safepointId(op->safepoint_id()); 612 event->commit(); 613 } 614 615 616 BiasedLocking::Condition BiasedLocking::single_revoke_with_handshake(Handle obj, JavaThread *requester, JavaThread *biaser) { 617 618 EventBiasedLockRevocation event; 619 if (PrintBiasedLockingStatistics) { 620 Atomic::inc(handshakes_count_addr()); 621 } 622 log_info(biasedlocking, handshake)("JavaThread " INTPTR_FORMAT " handshaking JavaThread " 623 INTPTR_FORMAT " to revoke object " INTPTR_FORMAT, p2i(requester), 624 p2i(biaser), p2i(obj())); 625 626 RevokeOneBias revoke(obj, requester, biaser); 627 bool executed = Handshake::execute(&revoke, biaser); 628 if (revoke.status_code() == NOT_REVOKED) { 629 return NOT_REVOKED; 630 } 631 if (executed) { 632 log_info(biasedlocking, handshake)("Handshake revocation for object " INTPTR_FORMAT " succeeded. Bias was %srevoked", 633 p2i(obj()), (revoke.status_code() == BIAS_REVOKED ? "" : "already ")); 634 if (event.should_commit() && revoke.status_code() == BIAS_REVOKED) { 635 post_revocation_event(&event, obj->klass(), &revoke); 636 } 637 assert(!obj->mark().has_bias_pattern(), "invariant"); 638 return revoke.status_code(); 639 } else { 640 // Thread was not alive. 641 // Grab Threads_lock before manually trying to revoke bias. This avoids race with a newly 642 // created JavaThread (that happens to get the same memory address as biaser) synchronizing 643 // on this object. 644 { 645 MutexLocker ml(Threads_lock); 646 markWord mark = obj->mark(); 647 // Check if somebody else was able to revoke it before biased thread exited. 648 if (!mark.has_bias_pattern()) { 649 return NOT_BIASED; 650 } 651 ThreadsListHandle tlh; 652 markWord prototype = obj->klass()->prototype_header(); 653 if (!prototype.has_bias_pattern() || (!tlh.includes(biaser) && biaser == mark.biased_locker() && 654 prototype.bias_epoch() == mark.bias_epoch())) { 655 obj->cas_set_mark(markWord::prototype().set_age(mark.age()), mark); 656 if (event.should_commit()) { 657 post_revocation_event(&event, obj->klass(), &revoke); 658 } 659 assert(!obj->mark().has_bias_pattern(), "bias should be revoked by now"); 660 return BIAS_REVOKED; 661 } 662 } 663 } 664 665 return NOT_REVOKED; 666 } 667 668 669 // Caller should have instantiated a ResourceMark object before calling this method 670 void BiasedLocking::walk_stack_and_revoke(oop obj, JavaThread* biased_locker) { 671 assert(!SafepointSynchronize::is_at_safepoint() || !ThreadLocalHandshakes, 672 "if ThreadLocalHandshakes is enabled this should always be executed outside safepoints"); 673 assert(Thread::current() == biased_locker || Thread::current()->is_VM_thread(), "wrong thread"); 674 675 markWord mark = obj->mark(); 676 assert(mark.biased_locker() == biased_locker && 677 obj->klass()->prototype_header().bias_epoch() == mark.bias_epoch(), "invariant"); 678 679 log_trace(biasedlocking)("%s(" INTPTR_FORMAT ") revoking object " INTPTR_FORMAT ", mark " 680 INTPTR_FORMAT ", type %s, prototype header " INTPTR_FORMAT 681 ", biaser " INTPTR_FORMAT " %s", 682 Thread::current()->is_VM_thread() ? "VMThread" : "JavaThread", 683 p2i(Thread::current()), 684 p2i(obj), 685 mark.value(), 686 obj->klass()->external_name(), 687 obj->klass()->prototype_header().value(), 688 p2i(biased_locker), 689 Thread::current()->is_VM_thread() ? "" : "(walking own stack)"); 690 691 markWord unbiased_prototype = markWord::prototype().set_age(obj->mark().age()); 692 693 GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(biased_locker); 694 BasicLock* highest_lock = NULL; 695 for (int i = 0; i < cached_monitor_info->length(); i++) { 696 MonitorInfo* mon_info = cached_monitor_info->at(i); 697 if (mon_info->owner() == obj) { 698 log_trace(biasedlocking)(" mon_info->owner (" PTR_FORMAT ") == obj (" PTR_FORMAT ")", 699 p2i(mon_info->owner()), 700 p2i(obj)); 701 // Assume recursive case and fix up highest lock below 702 markWord mark = markWord::encode((BasicLock*) NULL); 703 highest_lock = mon_info->lock(); 704 highest_lock->set_displaced_header(mark); 705 } else { 706 log_trace(biasedlocking)(" mon_info->owner (" PTR_FORMAT ") != obj (" PTR_FORMAT ")", 707 p2i(mon_info->owner()), 708 p2i(obj)); 709 } 710 } 711 if (highest_lock != NULL) { 712 // Fix up highest lock to contain displaced header and point 713 // object at it 714 highest_lock->set_displaced_header(unbiased_prototype); 715 // Reset object header to point to displaced mark. 716 // Must release store the lock address for platforms without TSO 717 // ordering (e.g. ppc). 718 obj->release_set_mark(markWord::encode(highest_lock)); 719 assert(!obj->mark().has_bias_pattern(), "illegal mark state: stack lock used bias bit"); 720 log_info(biasedlocking)(" Revoked bias of currently-locked object"); 721 } else { 722 log_info(biasedlocking)(" Revoked bias of currently-unlocked object"); 723 // Store the unlocked value into the object's header. 724 obj->set_mark(unbiased_prototype); 725 } 726 727 assert(!obj->mark().has_bias_pattern(), "must not be biased"); 728 } 729 730 void BiasedLocking::revoke_own_lock(Handle obj, TRAPS) { 731 assert(THREAD->is_Java_thread(), "must be called by a JavaThread"); 732 JavaThread* thread = (JavaThread*)THREAD; 733 734 markWord mark = obj->mark(); 735 736 if (!mark.has_bias_pattern()) { 737 return; 738 } 739 740 Klass *k = obj->klass(); 741 assert(mark.biased_locker() == thread && 742 k->prototype_header().bias_epoch() == mark.bias_epoch(), "Revoke failed, unhandled biased lock state"); 743 ResourceMark rm; 744 log_info(biasedlocking)("Revoking bias by walking my own stack:"); 745 EventBiasedLockSelfRevocation event; 746 BiasedLocking::walk_stack_and_revoke(obj(), (JavaThread*) thread); 747 thread->set_cached_monitor_info(NULL); 748 assert(!obj->mark().has_bias_pattern(), "invariant"); 749 if (event.should_commit()) { 750 post_self_revocation_event(&event, k); 751 } 752 } 753 754 void BiasedLocking::revoke(Handle obj, TRAPS) { 755 assert(!SafepointSynchronize::is_at_safepoint(), "must not be called while at safepoint"); 756 757 while (true) { 758 // We can revoke the biases of anonymously-biased objects 759 // efficiently enough that we should not cause these revocations to 760 // update the heuristics because doing so may cause unwanted bulk 761 // revocations (which are expensive) to occur. 762 markWord mark = obj->mark(); 763 764 if (!mark.has_bias_pattern()) { 765 return; 766 } 767 768 if (mark.is_biased_anonymously()) { 769 // We are probably trying to revoke the bias of this object due to 770 // an identity hash code computation. Try to revoke the bias 771 // without a safepoint. This is possible if we can successfully 772 // compare-and-exchange an unbiased header into the mark word of 773 // the object, meaning that no other thread has raced to acquire 774 // the bias of the object. 775 markWord biased_value = mark; 776 markWord unbiased_prototype = markWord::prototype().set_age(mark.age()); 777 markWord res_mark = obj->cas_set_mark(unbiased_prototype, mark); 778 if (res_mark == biased_value) { 779 return; 780 } 781 mark = res_mark; // Refresh mark with the latest value. 782 } else { 783 Klass* k = obj->klass(); 784 markWord prototype_header = k->prototype_header(); 785 if (!prototype_header.has_bias_pattern()) { 786 // This object has a stale bias from before the bulk revocation 787 // for this data type occurred. It's pointless to update the 788 // heuristics at this point so simply update the header with a 789 // CAS. If we fail this race, the object's bias has been revoked 790 // by another thread so we simply return and let the caller deal 791 // with it. 792 obj->cas_set_mark(prototype_header.set_age(mark.age()), mark); 793 assert(!obj->mark().has_bias_pattern(), "even if we raced, should still be revoked"); 794 return; 795 } else if (prototype_header.bias_epoch() != mark.bias_epoch()) { 796 // The epoch of this biasing has expired indicating that the 797 // object is effectively unbiased. We can revoke the bias of this 798 // object efficiently enough with a CAS that we shouldn't update the 799 // heuristics. This is normally done in the assembly code but we 800 // can reach this point due to various points in the runtime 801 // needing to revoke biases. 802 markWord res_mark; 803 markWord biased_value = mark; 804 markWord unbiased_prototype = markWord::prototype().set_age(mark.age()); 805 res_mark = obj->cas_set_mark(unbiased_prototype, mark); 806 if (res_mark == biased_value) { 807 return; 808 } 809 mark = res_mark; // Refresh mark with the latest value. 810 } 811 } 812 813 HeuristicsResult heuristics = update_heuristics(obj()); 814 if (heuristics == HR_NOT_BIASED) { 815 return; 816 } else if (heuristics == HR_SINGLE_REVOKE) { 817 JavaThread *blt = mark.biased_locker(); 818 assert(blt != NULL, "invariant"); 819 if (blt == THREAD) { 820 // A thread is trying to revoke the bias of an object biased 821 // toward it, again likely due to an identity hash code 822 // computation. We can again avoid a safepoint/handshake in this case 823 // since we are only going to walk our own stack. There are no 824 // races with revocations occurring in other threads because we 825 // reach no safepoints in the revocation path. 826 EventBiasedLockSelfRevocation event; 827 ResourceMark rm; 828 walk_stack_and_revoke(obj(), blt); 829 blt->set_cached_monitor_info(NULL); 830 assert(!obj->mark().has_bias_pattern(), "invariant"); 831 if (event.should_commit()) { 832 post_self_revocation_event(&event, obj->klass()); 833 } 834 return; 835 } else { 836 BiasedLocking::Condition cond = single_revoke_with_handshake(obj, (JavaThread*)THREAD, blt); 837 if (cond != NOT_REVOKED) { 838 return; 839 } 840 } 841 } else { 842 assert((heuristics == HR_BULK_REVOKE) || 843 (heuristics == HR_BULK_REBIAS), "?"); 844 EventBiasedLockClassRevocation event; 845 VM_BulkRevokeBias bulk_revoke(&obj, (JavaThread*)THREAD, 846 (heuristics == HR_BULK_REBIAS)); 847 VMThread::execute(&bulk_revoke); 848 if (event.should_commit()) { 849 post_class_revocation_event(&event, obj->klass(), &bulk_revoke); 850 } 851 return; 852 } 853 } 854 } 855 856 // All objects in objs should be locked by biaser 857 void BiasedLocking::revoke(GrowableArray<Handle>* objs, JavaThread *biaser) { 858 bool clean_my_cache = false; 859 for (int i = 0; i < objs->length(); i++) { 860 oop obj = (objs->at(i))(); 861 markWord mark = obj->mark(); 862 if (mark.has_bias_pattern()) { 863 walk_stack_and_revoke(obj, biaser); 864 clean_my_cache = true; 865 } 866 } 867 if (clean_my_cache) { 868 clean_up_cached_monitor_info(biaser); 869 } 870 } 871 872 873 void BiasedLocking::revoke_at_safepoint(Handle h_obj) { 874 assert(SafepointSynchronize::is_at_safepoint(), "must only be called while at safepoint"); 875 oop obj = h_obj(); 876 HeuristicsResult heuristics = update_heuristics(obj); 877 if (heuristics == HR_SINGLE_REVOKE) { 878 JavaThread* biased_locker = NULL; 879 single_revoke_at_safepoint(obj, false, NULL, &biased_locker); 880 if (biased_locker) { 881 clean_up_cached_monitor_info(biased_locker); 882 } 883 } else if ((heuristics == HR_BULK_REBIAS) || 884 (heuristics == HR_BULK_REVOKE)) { 885 bulk_revoke_at_safepoint(obj, (heuristics == HR_BULK_REBIAS), NULL); 886 clean_up_cached_monitor_info(); 887 } 888 } 889 890 891 void BiasedLocking::preserve_marks() { 892 if (!UseBiasedLocking) 893 return; 894 895 assert(SafepointSynchronize::is_at_safepoint(), "must only be called while at safepoint"); 896 897 assert(_preserved_oop_stack == NULL, "double initialization"); 898 assert(_preserved_mark_stack == NULL, "double initialization"); 899 900 // In order to reduce the number of mark words preserved during GC 901 // due to the presence of biased locking, we reinitialize most mark 902 // words to the class's prototype during GC -- even those which have 903 // a currently valid bias owner. One important situation where we 904 // must not clobber a bias is when a biased object is currently 905 // locked. To handle this case we iterate over the currently-locked 906 // monitors in a prepass and, if they are biased, preserve their 907 // mark words here. This should be a relatively small set of objects 908 // especially compared to the number of objects in the heap. 909 _preserved_mark_stack = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<markWord>(10, true); 910 _preserved_oop_stack = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<Handle>(10, true); 911 912 ResourceMark rm; 913 Thread* cur = Thread::current(); 914 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) { 915 if (thread->has_last_Java_frame()) { 916 RegisterMap rm(thread); 917 for (javaVFrame* vf = thread->last_java_vframe(&rm); vf != NULL; vf = vf->java_sender()) { 918 GrowableArray<MonitorInfo*> *monitors = vf->monitors(); 919 if (monitors != NULL) { 920 int len = monitors->length(); 921 // Walk monitors youngest to oldest 922 for (int i = len - 1; i >= 0; i--) { 923 MonitorInfo* mon_info = monitors->at(i); 924 if (mon_info->owner_is_scalar_replaced()) continue; 925 oop owner = mon_info->owner(); 926 if (owner != NULL) { 927 markWord mark = owner->mark(); 928 if (mark.has_bias_pattern()) { 929 _preserved_oop_stack->push(Handle(cur, owner)); 930 _preserved_mark_stack->push(mark); 931 } 932 } 933 } 934 } 935 } 936 } 937 } 938 } 939 940 941 void BiasedLocking::restore_marks() { 942 if (!UseBiasedLocking) 943 return; 944 945 assert(_preserved_oop_stack != NULL, "double free"); 946 assert(_preserved_mark_stack != NULL, "double free"); 947 948 int len = _preserved_oop_stack->length(); 949 for (int i = 0; i < len; i++) { 950 Handle owner = _preserved_oop_stack->at(i); 951 markWord mark = _preserved_mark_stack->at(i); 952 owner->set_mark(mark); 953 } 954 955 delete _preserved_oop_stack; 956 _preserved_oop_stack = NULL; 957 delete _preserved_mark_stack; 958 _preserved_mark_stack = NULL; 959 } 960 961 962 int* BiasedLocking::total_entry_count_addr() { return _counters.total_entry_count_addr(); } 963 int* BiasedLocking::biased_lock_entry_count_addr() { return _counters.biased_lock_entry_count_addr(); } 964 int* BiasedLocking::anonymously_biased_lock_entry_count_addr() { return _counters.anonymously_biased_lock_entry_count_addr(); } 965 int* BiasedLocking::rebiased_lock_entry_count_addr() { return _counters.rebiased_lock_entry_count_addr(); } 966 int* BiasedLocking::revoked_lock_entry_count_addr() { return _counters.revoked_lock_entry_count_addr(); } 967 int* BiasedLocking::handshakes_count_addr() { return _counters.handshakes_count_addr(); } 968 int* BiasedLocking::fast_path_entry_count_addr() { return _counters.fast_path_entry_count_addr(); } 969 int* BiasedLocking::slow_path_entry_count_addr() { return _counters.slow_path_entry_count_addr(); } 970 971 972 // BiasedLockingCounters 973 974 int BiasedLockingCounters::slow_path_entry_count() const { 975 if (_slow_path_entry_count != 0) { 976 return _slow_path_entry_count; 977 } 978 int sum = _biased_lock_entry_count + _anonymously_biased_lock_entry_count + 979 _rebiased_lock_entry_count + _revoked_lock_entry_count + 980 _fast_path_entry_count; 981 982 return _total_entry_count - sum; 983 } 984 985 void BiasedLockingCounters::print_on(outputStream* st) const { 986 tty->print_cr("# total entries: %d", _total_entry_count); 987 tty->print_cr("# biased lock entries: %d", _biased_lock_entry_count); 988 tty->print_cr("# anonymously biased lock entries: %d", _anonymously_biased_lock_entry_count); 989 tty->print_cr("# rebiased lock entries: %d", _rebiased_lock_entry_count); 990 tty->print_cr("# revoked lock entries: %d", _revoked_lock_entry_count); 991 tty->print_cr("# handshakes entries: %d", _handshakes_count); 992 tty->print_cr("# fast path lock entries: %d", _fast_path_entry_count); 993 tty->print_cr("# slow path lock entries: %d", slow_path_entry_count()); 994 } 995 996 void BiasedLockingCounters::print() const { print_on(tty); }