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