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