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   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 HandshakeClosure {
 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     : HandshakeClosure("RevokeOneBias")
 519     , _obj(obj)
 520     , _requesting_thread(requesting_thread)
 521     , _biased_locker(biased_locker)
 522     , _status_code(BiasedLocking::NOT_BIASED)
 523     , _biased_locker_id(0) {}
 524 
 525   void do_thread(Thread* target) {
 526     assert(target == _biased_locker, "Wrong thread");
 527 
 528     oop o = _obj();
 529     markWord mark = o->mark();
 530 
 531     if (!mark.has_bias_pattern()) {
 532       return;
 533     }
 534 
 535     markWord prototype = o->klass()->prototype_header();
 536     if (!prototype.has_bias_pattern()) {
 537       // This object has a stale bias from before the handshake
 538       // was requested. If we fail this race, the object's bias
 539       // has been revoked by another thread so we simply return.
 540       markWord biased_value = mark;
 541       mark = o->cas_set_mark(markWord::prototype().set_age(mark.age()), mark);
 542       assert(!o->mark().has_bias_pattern(), "even if we raced, should still be revoked");
 543       if (biased_value == mark) {
 544         _status_code = BiasedLocking::BIAS_REVOKED;
 545       }
 546       return;
 547     }
 548 
 549     if (_biased_locker == mark.biased_locker()) {
 550       if (mark.bias_epoch() == prototype.bias_epoch()) {
 551         // Epoch is still valid. This means biaser could be currently
 552         // synchronized on this object. We must walk its stack looking
 553         // for monitor records associated with this object and change
 554         // them to be stack locks if any are found.
 555         ResourceMark rm;
 556         BiasedLocking::walk_stack_and_revoke(o, _biased_locker);
 557         _biased_locker->set_cached_monitor_info(NULL);
 558         assert(!o->mark().has_bias_pattern(), "invariant");
 559         _biased_locker_id = JFR_THREAD_ID(_biased_locker);
 560         _status_code = BiasedLocking::BIAS_REVOKED;
 561         return;
 562       } else {
 563         markWord biased_value = mark;
 564         mark = o->cas_set_mark(markWord::prototype().set_age(mark.age()), mark);
 565         if (mark == biased_value || !mark.has_bias_pattern()) {
 566           assert(!o->mark().has_bias_pattern(), "should be revoked");
 567           _status_code = (biased_value == mark) ? BiasedLocking::BIAS_REVOKED : BiasedLocking::NOT_BIASED;
 568           return;
 569         }
 570       }
 571     }
 572 
 573     _status_code = BiasedLocking::NOT_REVOKED;
 574   }
 575 
 576   BiasedLocking::Condition status_code() const {
 577     return _status_code;
 578   }
 579 
 580   traceid biased_locker() const {
 581     return _biased_locker_id;
 582   }
 583 };
 584 
 585 
 586 static void post_self_revocation_event(EventBiasedLockSelfRevocation* event, Klass* k) {
 587   assert(event != NULL, "invariant");
 588   assert(k != NULL, "invariant");
 589   assert(event->should_commit(), "invariant");
 590   event->set_lockClass(k);
 591   event->commit();
 592 }
 593 
 594 static void post_revocation_event(EventBiasedLockRevocation* event, Klass* k, RevokeOneBias* op) {
 595   assert(event != NULL, "invariant");
 596   assert(k != NULL, "invariant");
 597   assert(op != NULL, "invariant");
 598   assert(event->should_commit(), "invariant");
 599   event->set_lockClass(k);
 600   event->set_safepointId(0);
 601   event->set_previousOwner(op->biased_locker());
 602   event->commit();
 603 }
 604 
 605 static void post_class_revocation_event(EventBiasedLockClassRevocation* event, Klass* k, VM_BulkRevokeBias* op) {
 606   assert(event != NULL, "invariant");
 607   assert(k != NULL, "invariant");
 608   assert(op != NULL, "invariant");
 609   assert(event->should_commit(), "invariant");
 610   event->set_revokedClass(k);
 611   event->set_disableBiasing(!op->is_bulk_rebias());
 612   event->set_safepointId(op->safepoint_id());
 613   event->commit();
 614 }
 615 
 616 
 617 BiasedLocking::Condition BiasedLocking::single_revoke_with_handshake(Handle obj, JavaThread *requester, JavaThread *biaser) {
 618 
 619   EventBiasedLockRevocation event;
 620   if (PrintBiasedLockingStatistics) {
 621     Atomic::inc(handshakes_count_addr());
 622   }
 623   log_info(biasedlocking, handshake)("JavaThread " INTPTR_FORMAT " handshaking JavaThread "
 624                                      INTPTR_FORMAT " to revoke object " INTPTR_FORMAT, p2i(requester),
 625                                      p2i(biaser), p2i(obj()));
 626 
 627   RevokeOneBias revoke(obj, requester, biaser);
 628   bool executed = Handshake::execute(&revoke, biaser);
 629   if (revoke.status_code() == NOT_REVOKED) {
 630     return NOT_REVOKED;
 631   }
 632   if (executed) {
 633     log_info(biasedlocking, handshake)("Handshake revocation for object " INTPTR_FORMAT " succeeded. Bias was %srevoked",
 634                                        p2i(obj()), (revoke.status_code() == BIAS_REVOKED ? "" : "already "));
 635     if (event.should_commit() && revoke.status_code() == BIAS_REVOKED) {
 636       post_revocation_event(&event, obj->klass(), &revoke);
 637     }
 638     assert(!obj->mark().has_bias_pattern(), "invariant");
 639     return revoke.status_code();
 640   } else {
 641     // Thread was not alive.
 642     // Grab Threads_lock before manually trying to revoke bias. This avoids race with a newly
 643     // created JavaThread (that happens to get the same memory address as biaser) synchronizing
 644     // on this object.
 645     {
 646       MutexLocker ml(Threads_lock);
 647       markWord mark = obj->mark();
 648       // Check if somebody else was able to revoke it before biased thread exited.
 649       if (!mark.has_bias_pattern()) {
 650         return NOT_BIASED;
 651       }
 652       ThreadsListHandle tlh;
 653       markWord prototype = obj->klass()->prototype_header();
 654       if (!prototype.has_bias_pattern() || (!tlh.includes(biaser) && biaser == mark.biased_locker() &&
 655                                             prototype.bias_epoch() == mark.bias_epoch())) {
 656         obj->cas_set_mark(markWord::prototype().set_age(mark.age()), mark);
 657         if (event.should_commit()) {
 658           post_revocation_event(&event, obj->klass(), &revoke);
 659         }
 660         assert(!obj->mark().has_bias_pattern(), "bias should be revoked by now");
 661         return BIAS_REVOKED;
 662       }
 663     }
 664   }
 665 
 666   return NOT_REVOKED;
 667 }
 668 
 669 
 670 // Caller should have instantiated a ResourceMark object before calling this method
 671 void BiasedLocking::walk_stack_and_revoke(oop obj, JavaThread* biased_locker) {
 672   assert(!SafepointSynchronize::is_at_safepoint() || !ThreadLocalHandshakes,
 673          "if ThreadLocalHandshakes is enabled this should always be executed outside safepoints");
 674   assert(Thread::current() == biased_locker || Thread::current()->is_VM_thread(), "wrong thread");
 675 
 676   markWord mark = obj->mark();
 677   assert(mark.biased_locker() == biased_locker &&
 678          obj->klass()->prototype_header().bias_epoch() == mark.bias_epoch(), "invariant");
 679 
 680   log_trace(biasedlocking)("%s(" INTPTR_FORMAT ") revoking object " INTPTR_FORMAT ", mark "
 681                            INTPTR_FORMAT ", type %s, prototype header " INTPTR_FORMAT
 682                            ", biaser " INTPTR_FORMAT " %s",
 683                            Thread::current()->is_VM_thread() ? "VMThread" : "JavaThread",
 684                            p2i(Thread::current()),
 685                            p2i(obj),
 686                            mark.value(),
 687                            obj->klass()->external_name(),
 688                            obj->klass()->prototype_header().value(),
 689                            p2i(biased_locker),
 690                            Thread::current()->is_VM_thread() ? "" : "(walking own stack)");
 691 
 692   markWord unbiased_prototype = markWord::prototype().set_age(obj->mark().age());
 693 
 694   GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(biased_locker);
 695   BasicLock* highest_lock = NULL;
 696   for (int i = 0; i < cached_monitor_info->length(); i++) {
 697     MonitorInfo* mon_info = cached_monitor_info->at(i);
 698     if (mon_info->owner() == obj) {
 699       log_trace(biasedlocking)("   mon_info->owner (" PTR_FORMAT ") == obj (" PTR_FORMAT ")",
 700                                p2i(mon_info->owner()),
 701                                p2i(obj));
 702       // Assume recursive case and fix up highest lock below
 703       markWord mark = markWord::encode((BasicLock*) NULL);
 704       highest_lock = mon_info->lock();
 705       highest_lock->set_displaced_header(mark);
 706     } else {
 707       log_trace(biasedlocking)("   mon_info->owner (" PTR_FORMAT ") != obj (" PTR_FORMAT ")",
 708                                p2i(mon_info->owner()),
 709                                p2i(obj));
 710     }
 711   }
 712   if (highest_lock != NULL) {
 713     // Fix up highest lock to contain displaced header and point
 714     // object at it
 715     highest_lock->set_displaced_header(unbiased_prototype);
 716     // Reset object header to point to displaced mark.
 717     // Must release store the lock address for platforms without TSO
 718     // ordering (e.g. ppc).
 719     obj->release_set_mark(markWord::encode(highest_lock));
 720     assert(!obj->mark().has_bias_pattern(), "illegal mark state: stack lock used bias bit");
 721     log_info(biasedlocking)("  Revoked bias of currently-locked object");
 722   } else {
 723     log_info(biasedlocking)("  Revoked bias of currently-unlocked object");
 724     // Store the unlocked value into the object's header.
 725     obj->set_mark(unbiased_prototype);
 726   }
 727 
 728   assert(!obj->mark().has_bias_pattern(), "must not be biased");
 729 }
 730 
 731 void BiasedLocking::revoke_own_lock(Handle obj, TRAPS) {
 732   assert(THREAD->is_Java_thread(), "must be called by a JavaThread");
 733   JavaThread* thread = (JavaThread*)THREAD;
 734 
 735   markWord mark = obj->mark();
 736 
 737   if (!mark.has_bias_pattern()) {
 738     return;
 739   }
 740 
 741   Klass *k = obj->klass();
 742   assert(mark.biased_locker() == thread &&
 743          k->prototype_header().bias_epoch() == mark.bias_epoch(), "Revoke failed, unhandled biased lock state");
 744   ResourceMark rm;
 745   log_info(biasedlocking)("Revoking bias by walking my own stack:");
 746   EventBiasedLockSelfRevocation event;
 747   BiasedLocking::walk_stack_and_revoke(obj(), (JavaThread*) thread);
 748   thread->set_cached_monitor_info(NULL);
 749   assert(!obj->mark().has_bias_pattern(), "invariant");
 750   if (event.should_commit()) {
 751     post_self_revocation_event(&event, k);
 752   }
 753 }
 754 
 755 void BiasedLocking::revoke(Handle obj, TRAPS) {
 756   assert(!SafepointSynchronize::is_at_safepoint(), "must not be called while at safepoint");
 757 
 758   while (true) {
 759     // We can revoke the biases of anonymously-biased objects
 760     // efficiently enough that we should not cause these revocations to
 761     // update the heuristics because doing so may cause unwanted bulk
 762     // revocations (which are expensive) to occur.
 763     markWord mark = obj->mark();
 764 
 765     if (!mark.has_bias_pattern()) {
 766       return;
 767     }
 768 
 769     if (mark.is_biased_anonymously()) {
 770       // We are probably trying to revoke the bias of this object due to
 771       // an identity hash code computation. Try to revoke the bias
 772       // without a safepoint. This is possible if we can successfully
 773       // compare-and-exchange an unbiased header into the mark word of
 774       // the object, meaning that no other thread has raced to acquire
 775       // the bias of the object.
 776       markWord biased_value       = mark;
 777       markWord unbiased_prototype = markWord::prototype().set_age(mark.age());
 778       markWord res_mark = obj->cas_set_mark(unbiased_prototype, mark);
 779       if (res_mark == biased_value) {
 780         return;
 781       }
 782       mark = res_mark;  // Refresh mark with the latest value.
 783     } else {
 784       Klass* k = obj->klass();
 785       markWord prototype_header = k->prototype_header();
 786       if (!prototype_header.has_bias_pattern()) {
 787         // This object has a stale bias from before the bulk revocation
 788         // for this data type occurred. It's pointless to update the
 789         // heuristics at this point so simply update the header with a
 790         // CAS. If we fail this race, the object's bias has been revoked
 791         // by another thread so we simply return and let the caller deal
 792         // with it.
 793         obj->cas_set_mark(prototype_header.set_age(mark.age()), mark);
 794         assert(!obj->mark().has_bias_pattern(), "even if we raced, should still be revoked");
 795         return;
 796       } else if (prototype_header.bias_epoch() != mark.bias_epoch()) {
 797         // The epoch of this biasing has expired indicating that the
 798         // object is effectively unbiased. We can revoke the bias of this
 799         // object efficiently enough with a CAS that we shouldn't update the
 800         // heuristics. This is normally done in the assembly code but we
 801         // can reach this point due to various points in the runtime
 802         // needing to revoke biases.
 803         markWord res_mark;
 804         markWord biased_value       = mark;
 805         markWord unbiased_prototype = markWord::prototype().set_age(mark.age());
 806         res_mark = obj->cas_set_mark(unbiased_prototype, mark);
 807         if (res_mark == biased_value) {
 808           return;
 809         }
 810         mark = res_mark;  // Refresh mark with the latest value.
 811       }
 812     }
 813 
 814     HeuristicsResult heuristics = update_heuristics(obj());
 815     if (heuristics == HR_NOT_BIASED) {
 816       return;
 817     } else if (heuristics == HR_SINGLE_REVOKE) {
 818       JavaThread *blt = mark.biased_locker();
 819       assert(blt != NULL, "invariant");
 820       if (blt == THREAD) {
 821         // A thread is trying to revoke the bias of an object biased
 822         // toward it, again likely due to an identity hash code
 823         // computation. We can again avoid a safepoint/handshake in this case
 824         // since we are only going to walk our own stack. There are no
 825         // races with revocations occurring in other threads because we
 826         // reach no safepoints in the revocation path.
 827         EventBiasedLockSelfRevocation event;
 828         ResourceMark rm;
 829         walk_stack_and_revoke(obj(), blt);
 830         blt->set_cached_monitor_info(NULL);
 831         assert(!obj->mark().has_bias_pattern(), "invariant");
 832         if (event.should_commit()) {
 833           post_self_revocation_event(&event, obj->klass());
 834         }
 835         return;
 836       } else {
 837         BiasedLocking::Condition cond = single_revoke_with_handshake(obj, (JavaThread*)THREAD, blt);
 838         if (cond != NOT_REVOKED) {
 839           return;
 840         }
 841       }
 842     } else {
 843       assert((heuristics == HR_BULK_REVOKE) ||
 844          (heuristics == HR_BULK_REBIAS), "?");
 845       EventBiasedLockClassRevocation event;
 846       VM_BulkRevokeBias bulk_revoke(&obj, (JavaThread*)THREAD,
 847                                     (heuristics == HR_BULK_REBIAS));
 848       VMThread::execute(&bulk_revoke);
 849       if (event.should_commit()) {
 850         post_class_revocation_event(&event, obj->klass(), &bulk_revoke);
 851       }
 852       return;
 853     }
 854   }
 855 }
 856 
 857 // All objects in objs should be locked by biaser
 858 void BiasedLocking::revoke(GrowableArray<Handle>* objs, JavaThread *biaser) {
 859   bool clean_my_cache = false;
 860   for (int i = 0; i < objs->length(); i++) {
 861     oop obj = (objs->at(i))();
 862     markWord mark = obj->mark();
 863     if (mark.has_bias_pattern()) {
 864       walk_stack_and_revoke(obj, biaser);
 865       clean_my_cache = true;
 866     }
 867   }
 868   if (clean_my_cache) {
 869     clean_up_cached_monitor_info(biaser);
 870   }
 871 }
 872 
 873 
 874 void BiasedLocking::revoke_at_safepoint(Handle h_obj) {
 875   assert(SafepointSynchronize::is_at_safepoint(), "must only be called while at safepoint");
 876   oop obj = h_obj();
 877   HeuristicsResult heuristics = update_heuristics(obj);
 878   if (heuristics == HR_SINGLE_REVOKE) {
 879     JavaThread* biased_locker = NULL;
 880     single_revoke_at_safepoint(obj, false, NULL, &biased_locker);
 881     if (biased_locker) {
 882       clean_up_cached_monitor_info(biased_locker);
 883     }
 884   } else if ((heuristics == HR_BULK_REBIAS) ||
 885              (heuristics == HR_BULK_REVOKE)) {
 886     bulk_revoke_at_safepoint(obj, (heuristics == HR_BULK_REBIAS), NULL);
 887     clean_up_cached_monitor_info();
 888   }
 889 }
 890 
 891 
 892 void BiasedLocking::preserve_marks() {
 893   if (!UseBiasedLocking)
 894     return;
 895 
 896   assert(SafepointSynchronize::is_at_safepoint(), "must only be called while at safepoint");
 897 
 898   assert(_preserved_oop_stack  == NULL, "double initialization");
 899   assert(_preserved_mark_stack == NULL, "double initialization");
 900 
 901   // In order to reduce the number of mark words preserved during GC
 902   // due to the presence of biased locking, we reinitialize most mark
 903   // words to the class's prototype during GC -- even those which have
 904   // a currently valid bias owner. One important situation where we
 905   // must not clobber a bias is when a biased object is currently
 906   // locked. To handle this case we iterate over the currently-locked
 907   // monitors in a prepass and, if they are biased, preserve their
 908   // mark words here. This should be a relatively small set of objects
 909   // especially compared to the number of objects in the heap.
 910   _preserved_mark_stack = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<markWord>(10, true);
 911   _preserved_oop_stack = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<Handle>(10, true);
 912 
 913   ResourceMark rm;
 914   Thread* cur = Thread::current();
 915   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) {
 916     if (thread->has_last_Java_frame()) {
 917       RegisterMap rm(thread);
 918       for (javaVFrame* vf = thread->last_java_vframe(&rm); vf != NULL; vf = vf->java_sender()) {
 919         GrowableArray<MonitorInfo*> *monitors = vf->monitors();
 920         if (monitors != NULL) {
 921           int len = monitors->length();
 922           // Walk monitors youngest to oldest
 923           for (int i = len - 1; i >= 0; i--) {
 924             MonitorInfo* mon_info = monitors->at(i);
 925             if (mon_info->owner_is_scalar_replaced()) continue;
 926             oop owner = mon_info->owner();
 927             if (owner != NULL) {
 928               markWord mark = owner->mark();
 929               if (mark.has_bias_pattern()) {
 930                 _preserved_oop_stack->push(Handle(cur, owner));
 931                 _preserved_mark_stack->push(mark);
 932               }
 933             }
 934           }
 935         }
 936       }
 937     }
 938   }
 939 }
 940 
 941 
 942 void BiasedLocking::restore_marks() {
 943   if (!UseBiasedLocking)
 944     return;
 945 
 946   assert(_preserved_oop_stack  != NULL, "double free");
 947   assert(_preserved_mark_stack != NULL, "double free");
 948 
 949   int len = _preserved_oop_stack->length();
 950   for (int i = 0; i < len; i++) {
 951     Handle owner = _preserved_oop_stack->at(i);
 952     markWord mark = _preserved_mark_stack->at(i);
 953     owner->set_mark(mark);
 954   }
 955 
 956   delete _preserved_oop_stack;
 957   _preserved_oop_stack = NULL;
 958   delete _preserved_mark_stack;
 959   _preserved_mark_stack = NULL;
 960 }
 961 
 962 
 963 int* BiasedLocking::total_entry_count_addr()                   { return _counters.total_entry_count_addr(); }
 964 int* BiasedLocking::biased_lock_entry_count_addr()             { return _counters.biased_lock_entry_count_addr(); }
 965 int* BiasedLocking::anonymously_biased_lock_entry_count_addr() { return _counters.anonymously_biased_lock_entry_count_addr(); }
 966 int* BiasedLocking::rebiased_lock_entry_count_addr()           { return _counters.rebiased_lock_entry_count_addr(); }
 967 int* BiasedLocking::revoked_lock_entry_count_addr()            { return _counters.revoked_lock_entry_count_addr(); }
 968 int* BiasedLocking::handshakes_count_addr()                    { return _counters.handshakes_count_addr(); }
 969 int* BiasedLocking::fast_path_entry_count_addr()               { return _counters.fast_path_entry_count_addr(); }
 970 int* BiasedLocking::slow_path_entry_count_addr()               { return _counters.slow_path_entry_count_addr(); }
 971 
 972 
 973 // BiasedLockingCounters
 974 
 975 int BiasedLockingCounters::slow_path_entry_count() const {
 976   if (_slow_path_entry_count != 0) {
 977     return _slow_path_entry_count;
 978   }
 979   int sum = _biased_lock_entry_count   + _anonymously_biased_lock_entry_count +
 980             _rebiased_lock_entry_count + _revoked_lock_entry_count +
 981             _fast_path_entry_count;
 982 
 983   return _total_entry_count - sum;
 984 }
 985 
 986 void BiasedLockingCounters::print_on(outputStream* st) const {
 987   tty->print_cr("# total entries: %d", _total_entry_count);
 988   tty->print_cr("# biased lock entries: %d", _biased_lock_entry_count);
 989   tty->print_cr("# anonymously biased lock entries: %d", _anonymously_biased_lock_entry_count);
 990   tty->print_cr("# rebiased lock entries: %d", _rebiased_lock_entry_count);
 991   tty->print_cr("# revoked lock entries: %d", _revoked_lock_entry_count);
 992   tty->print_cr("# handshakes entries: %d", _handshakes_count);
 993   tty->print_cr("# fast path lock entries: %d", _fast_path_entry_count);
 994   tty->print_cr("# slow path lock entries: %d", slow_path_entry_count());
 995 }
 996 
 997 void BiasedLockingCounters::print() const { print_on(tty); }