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