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