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