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