rev 57156 : imported patch 8234796-v3

   1 /*
   2  * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classLoaderDataGraph.hpp"
  27 #include "jfr/jfrEvents.hpp"
  28 #include "jfr/support/jfrThreadId.hpp"
  29 #include "logging/log.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "oops/klass.inline.hpp"
  32 #include "oops/markWord.hpp"
  33 #include "oops/oop.inline.hpp"
  34 #include "runtime/atomic.hpp"
  35 #include "runtime/basicLock.hpp"
  36 #include "runtime/biasedLocking.hpp"
  37 #include "runtime/handles.inline.hpp"

  38 #include "runtime/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<markWord>* _preserved_mark_stack = NULL;
  50 
  51 static void enable_biased_locking(InstanceKlass* k) {
  52   k->set_prototype_header(markWord::biased_locking_prototype());
  53 }
  54 
  55 static void enable_biased_locking() {
  56   _biased_locking_enabled = true;
  57   log_info(biasedlocking)("Biased locking enabled");
  58 }
  59 
  60 class VM_EnableBiasedLocking: public VM_Operation {
  61  public:
  62   VM_EnableBiasedLocking() {}
  63   VMOp_Type type() const          { return VMOp_EnableBiasedLocking; }
  64 
  65   void doit() {
  66     // Iterate the class loader data dictionaries enabling biased locking for all
  67     // currently loaded classes.
  68     ClassLoaderDataGraph::dictionary_classes_do(enable_biased_locking);
  69     // Indicate that future instances should enable it as well
  70     enable_biased_locking();
  71   }
  72 
  73   bool allow_nested_vm_operations() const        { return false; }
  74 };
  75 
  76 
  77 // One-shot PeriodicTask subclass for enabling biased locking
  78 class EnableBiasedLockingTask : public PeriodicTask {
  79  public:
  80   EnableBiasedLockingTask(size_t interval_time) : PeriodicTask(interval_time) {}
  81 
  82   virtual void task() {
  83     VM_EnableBiasedLocking op;
  84     VMThread::execute(&op);
  85 
  86     // Reclaim our storage and disenroll ourself
  87     delete this;
  88   }
  89 };
  90 
  91 
  92 void BiasedLocking::init() {
  93   // If biased locking is enabled and BiasedLockingStartupDelay is set,
  94   // schedule a task to fire after the specified delay which turns on
  95   // biased locking for all currently loaded classes as well as future
  96   // ones. This could be a workaround for startup time regressions
  97   // due to large number of safepoints being taken during VM startup for
  98   // bias revocation.
  99   if (UseBiasedLocking) {
 100     if (BiasedLockingStartupDelay > 0) {
 101       EnableBiasedLockingTask* task = new EnableBiasedLockingTask(BiasedLockingStartupDelay);
 102       task->enroll();
 103     } else {
 104       enable_biased_locking();
 105     }
 106   }
 107 }
 108 
 109 
 110 bool BiasedLocking::enabled() {
 111   assert(UseBiasedLocking, "precondition");
 112   // We check "BiasedLockingStartupDelay == 0" here to cover the
 113   // possibility of calls to BiasedLocking::enabled() before
 114   // BiasedLocking::init().
 115   return _biased_locking_enabled || BiasedLockingStartupDelay == 0;
 116 }
 117 
 118 
 119 // Returns MonitorInfos for all objects locked on this thread in youngest to oldest order
 120 static GrowableArray<MonitorInfo*>* get_or_compute_monitor_info(JavaThread* thread) {
 121   GrowableArray<MonitorInfo*>* info = thread->cached_monitor_info();
 122   if (info != NULL) {
 123     return info;
 124   }
 125 
 126   info = new GrowableArray<MonitorInfo*>();
 127 
 128   // It's possible for the thread to not have any Java frames on it,
 129   // i.e., if it's the main thread and it's already returned from main()
 130   if (thread->has_last_Java_frame()) {
 131     RegisterMap rm(thread);
 132     for (javaVFrame* vf = thread->last_java_vframe(&rm); vf != NULL; vf = vf->java_sender()) {
 133       GrowableArray<MonitorInfo*> *monitors = vf->monitors();
 134       if (monitors != NULL) {
 135         int len = monitors->length();
 136         // Walk monitors youngest to oldest
 137         for (int i = len - 1; i >= 0; i--) {
 138           MonitorInfo* mon_info = monitors->at(i);
 139           if (mon_info->eliminated()) continue;
 140           oop owner = mon_info->owner();
 141           if (owner != NULL) {
 142             info->append(mon_info);
 143           }
 144         }
 145       }
 146     }
 147   }
 148 
 149   thread->set_cached_monitor_info(info);
 150   return info;
 151 }
 152 
 153 
 154 // After the call, *biased_locker will be set to obj->mark()->biased_locker() if biased_locker != NULL,
 155 // AND it is a living thread. Otherwise it will not be updated, (i.e. the caller is responsible for initialization).
 156 void BiasedLocking::single_revoke_at_safepoint(oop obj, bool is_bulk, JavaThread* requesting_thread, JavaThread** biased_locker) {
 157   assert(SafepointSynchronize::is_at_safepoint(), "must be done at safepoint");
 158   assert(Thread::current()->is_VM_thread(), "must be VMThread");
 159 
 160   markWord mark = obj->mark();
 161   if (!mark.has_bias_pattern()) {
 162     if (log_is_enabled(Info, biasedlocking)) {
 163       ResourceMark rm;
 164       log_info(biasedlocking)("  (Skipping revocation of object " INTPTR_FORMAT
 165                               ", mark " INTPTR_FORMAT ", type %s"
 166                               ", requesting thread " INTPTR_FORMAT
 167                               " because it's no longer biased)",
 168                               p2i((void *)obj), mark.value(),
 169                               obj->klass()->external_name(),
 170                               (intptr_t) requesting_thread);
 171     }
 172     return;
 173   }
 174 
 175   uint age = mark.age();
 176   markWord unbiased_prototype = markWord::prototype().set_age(age);
 177 
 178   // Log at "info" level if not bulk, else "trace" level
 179   if (!is_bulk) {
 180     ResourceMark rm;
 181     log_info(biasedlocking)("Revoking bias of object " INTPTR_FORMAT ", mark "
 182                             INTPTR_FORMAT ", type %s, prototype header " INTPTR_FORMAT
 183                             ", requesting thread " INTPTR_FORMAT,
 184                             p2i((void *)obj),
 185                             mark.value(),
 186                             obj->klass()->external_name(),
 187                             obj->klass()->prototype_header().value(),
 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                              " , requesting thread " INTPTR_FORMAT,
 194                              p2i((void *)obj),
 195                              mark.value(),
 196                              obj->klass()->external_name(),
 197                              obj->klass()->prototype_header().value(),
 198                              (intptr_t) requesting_thread);
 199   }
 200 
 201   JavaThread* biased_thread = mark.biased_locker();
 202   if (biased_thread == NULL) {
 203     // Object is anonymously biased. We can get here if, for
 204     // example, we revoke the bias due to an identity hash code
 205     // being computed for an object.
 206     obj->set_mark(unbiased_prototype);
 207 
 208     // Log at "info" level if not bulk, else "trace" level
 209     if (!is_bulk) {
 210       log_info(biasedlocking)("  Revoked bias of anonymously-biased object");
 211     } else {
 212       log_trace(biasedlocking)("  Revoked bias of anonymously-biased object");
 213     }
 214     return;
 215   }
 216 
 217   // Handle case where the thread toward which the object was biased has exited
 218   bool thread_is_alive = false;
 219   if (requesting_thread == biased_thread) {
 220     thread_is_alive = true;
 221   } else {
 222     ThreadsListHandle tlh;
 223     thread_is_alive = tlh.includes(biased_thread);
 224   }
 225   if (!thread_is_alive) {
 226     obj->set_mark(unbiased_prototype);
 227     // Log at "info" level if not bulk, else "trace" level
 228     if (!is_bulk) {
 229       log_info(biasedlocking)("  Revoked bias of object biased toward dead thread ("
 230                               PTR_FORMAT ")", p2i(biased_thread));
 231     } else {
 232       log_trace(biasedlocking)("  Revoked bias of object biased toward dead thread ("
 233                                PTR_FORMAT ")", p2i(biased_thread));
 234     }
 235     return;
 236   }
 237 
 238   // Log at "info" level if not bulk, else "trace" level
 239   if (!is_bulk) {
 240     log_info(biasedlocking)("  Revoked bias of object biased toward live thread ("
 241                             PTR_FORMAT ")", p2i(biased_thread));
 242   } else {
 243     log_trace(biasedlocking)("  Revoked bias of object biased toward live thread ("
 244                                PTR_FORMAT ")", p2i(biased_thread));
 245   }
 246 
 247   // Thread owning bias is alive.
 248   // Check to see whether it currently owns the lock and, if so,
 249   // write down the needed displaced headers to the thread's stack.
 250   // Otherwise, restore the object's header either to the unlocked
 251   // or unbiased state.
 252   GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(biased_thread);
 253   BasicLock* highest_lock = NULL;
 254   for (int i = 0; i < cached_monitor_info->length(); i++) {
 255     MonitorInfo* mon_info = cached_monitor_info->at(i);
 256     if (mon_info->owner() == obj) {
 257       log_trace(biasedlocking)("   mon_info->owner (" PTR_FORMAT ") == obj (" PTR_FORMAT ")",
 258                                p2i((void *) mon_info->owner()),
 259                                p2i((void *) obj));
 260       // Assume recursive case and fix up highest lock below
 261       markWord mark = markWord::encode((BasicLock*) NULL);
 262       highest_lock = mon_info->lock();
 263       highest_lock->set_displaced_header(mark);
 264     } else {
 265       log_trace(biasedlocking)("   mon_info->owner (" PTR_FORMAT ") != obj (" PTR_FORMAT ")",
 266                                p2i((void *) mon_info->owner()),
 267                                p2i((void *) obj));
 268     }
 269   }
 270   if (highest_lock != NULL) {
 271     // Fix up highest lock to contain displaced header and point
 272     // object at it
 273     highest_lock->set_displaced_header(unbiased_prototype);
 274     // Reset object header to point to displaced mark.
 275     // Must release store the lock address for platforms without TSO
 276     // ordering (e.g. ppc).
 277     obj->release_set_mark(markWord::encode(highest_lock));
 278     assert(!obj->mark().has_bias_pattern(), "illegal mark state: stack lock used bias bit");
 279     // Log at "info" level if not bulk, else "trace" level
 280     if (!is_bulk) {
 281       log_info(biasedlocking)("  Revoked bias of currently-locked object");
 282     } else {
 283       log_trace(biasedlocking)("  Revoked bias of currently-locked object");
 284     }
 285   } else {
 286     // Log at "info" level if not bulk, else "trace" level
 287     if (!is_bulk) {
 288       log_info(biasedlocking)("  Revoked bias of currently-unlocked object");
 289     } else {
 290       log_trace(biasedlocking)("  Revoked bias of currently-unlocked object");
 291     }
 292     // Store the unlocked value into the object's header.
 293     obj->set_mark(unbiased_prototype);
 294   }
 295 
 296   // If requested, return information on which thread held the bias
 297   if (biased_locker != NULL) {
 298     *biased_locker = biased_thread;
 299   }
 300 }
 301 
 302 
 303 enum HeuristicsResult {
 304   HR_NOT_BIASED    = 1,
 305   HR_SINGLE_REVOKE = 2,
 306   HR_BULK_REBIAS   = 3,
 307   HR_BULK_REVOKE   = 4
 308 };
 309 
 310 
 311 static HeuristicsResult update_heuristics(oop o) {
 312   markWord mark = o->mark();
 313   if (!mark.has_bias_pattern()) {
 314     return HR_NOT_BIASED;
 315   }
 316 
 317   // Heuristics to attempt to throttle the number of revocations.
 318   // Stages:
 319   // 1. Revoke the biases of all objects in the heap of this type,
 320   //    but allow rebiasing of those objects if unlocked.
 321   // 2. Revoke the biases of all objects in the heap of this type
 322   //    and don't allow rebiasing of these objects. Disable
 323   //    allocation of objects of that type with the bias bit set.
 324   Klass* k = o->klass();
 325   jlong cur_time = os::javaTimeMillis();
 326   jlong last_bulk_revocation_time = k->last_biased_lock_bulk_revocation_time();
 327   int revocation_count = k->biased_lock_revocation_count();
 328   if ((revocation_count >= BiasedLockingBulkRebiasThreshold) &&
 329       (revocation_count <  BiasedLockingBulkRevokeThreshold) &&
 330       (last_bulk_revocation_time != 0) &&
 331       (cur_time - last_bulk_revocation_time >= BiasedLockingDecayTime)) {
 332     // This is the first revocation we've seen in a while of an
 333     // object of this type since the last time we performed a bulk
 334     // rebiasing operation. The application is allocating objects in
 335     // bulk which are biased toward a thread and then handing them
 336     // off to another thread. We can cope with this allocation
 337     // pattern via the bulk rebiasing mechanism so we reset the
 338     // klass's revocation count rather than allow it to increase
 339     // monotonically. If we see the need to perform another bulk
 340     // rebias operation later, we will, and if subsequently we see
 341     // many more revocation operations in a short period of time we
 342     // will completely disable biasing for this type.
 343     k->set_biased_lock_revocation_count(0);
 344     revocation_count = 0;
 345   }
 346 
 347   // Make revocation count saturate just beyond BiasedLockingBulkRevokeThreshold
 348   if (revocation_count <= BiasedLockingBulkRevokeThreshold) {
 349     revocation_count = k->atomic_incr_biased_lock_revocation_count();
 350   }
 351 
 352   if (revocation_count == BiasedLockingBulkRevokeThreshold) {
 353     return HR_BULK_REVOKE;
 354   }
 355 
 356   if (revocation_count == BiasedLockingBulkRebiasThreshold) {
 357     return HR_BULK_REBIAS;
 358   }
 359 
 360   return HR_SINGLE_REVOKE;
 361 }
 362 
 363 
 364 void BiasedLocking::bulk_revoke_at_safepoint(oop o, bool bulk_rebias, JavaThread* requesting_thread) {
 365   assert(SafepointSynchronize::is_at_safepoint(), "must be done at safepoint");
 366   assert(Thread::current()->is_VM_thread(), "must be VMThread");
 367 
 368   log_info(biasedlocking)("* Beginning bulk revocation (kind == %s) because of object "
 369                           INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
 370                           (bulk_rebias ? "rebias" : "revoke"),
 371                           p2i((void *) o),
 372                           o->mark().value(),
 373                           o->klass()->external_name());
 374 
 375   jlong cur_time = os::javaTimeMillis();
 376   o->klass()->set_last_biased_lock_bulk_revocation_time(cur_time);
 377 
 378   Klass* k_o = o->klass();
 379   Klass* klass = k_o;
 380 
 381   {
 382     JavaThreadIteratorWithHandle jtiwh;
 383 
 384     if (bulk_rebias) {
 385       // Use the epoch in the klass of the object to implicitly revoke
 386       // all biases of objects of this data type and force them to be
 387       // reacquired. However, we also need to walk the stacks of all
 388       // threads and update the headers of lightweight locked objects
 389       // with biases to have the current epoch.
 390 
 391       // If the prototype header doesn't have the bias pattern, don't
 392       // try to update the epoch -- assume another VM operation came in
 393       // and reset the header to the unbiased state, which will
 394       // implicitly cause all existing biases to be revoked
 395       if (klass->prototype_header().has_bias_pattern()) {
 396         int prev_epoch = klass->prototype_header().bias_epoch();
 397         klass->set_prototype_header(klass->prototype_header().incr_bias_epoch());
 398         int cur_epoch = klass->prototype_header().bias_epoch();
 399 
 400         // Now walk all threads' stacks and adjust epochs of any biased
 401         // and locked objects of this data type we encounter
 402         for (; JavaThread *thr = jtiwh.next(); ) {
 403           GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(thr);
 404           for (int i = 0; i < cached_monitor_info->length(); i++) {
 405             MonitorInfo* mon_info = cached_monitor_info->at(i);
 406             oop owner = mon_info->owner();
 407             markWord mark = owner->mark();
 408             if ((owner->klass() == k_o) && mark.has_bias_pattern()) {
 409               // We might have encountered this object already in the case of recursive locking
 410               assert(mark.bias_epoch() == prev_epoch || mark.bias_epoch() == cur_epoch, "error in bias epoch adjustment");
 411               owner->set_mark(mark.set_bias_epoch(cur_epoch));
 412             }
 413           }
 414         }
 415       }
 416 
 417       // At this point we're done. All we have to do is potentially
 418       // adjust the header of the given object to revoke its bias.
 419       single_revoke_at_safepoint(o, true, requesting_thread, NULL);
 420     } else {
 421       if (log_is_enabled(Info, biasedlocking)) {
 422         ResourceMark rm;
 423         log_info(biasedlocking)("* Disabling biased locking for type %s", klass->external_name());
 424       }
 425 
 426       // Disable biased locking for this data type. Not only will this
 427       // cause future instances to not be biased, but existing biased
 428       // instances will notice that this implicitly caused their biases
 429       // to be revoked.
 430       klass->set_prototype_header(markWord::prototype());
 431 
 432       // Now walk all threads' stacks and forcibly revoke the biases of
 433       // any locked and biased objects of this data type we encounter.
 434       for (; JavaThread *thr = jtiwh.next(); ) {
 435         GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(thr);
 436         for (int i = 0; i < cached_monitor_info->length(); i++) {
 437           MonitorInfo* mon_info = cached_monitor_info->at(i);
 438           oop owner = mon_info->owner();
 439           markWord mark = owner->mark();
 440           if ((owner->klass() == k_o) && mark.has_bias_pattern()) {
 441             single_revoke_at_safepoint(owner, true, requesting_thread, NULL);
 442           }
 443         }
 444       }
 445 
 446       // Must force the bias of the passed object to be forcibly revoked
 447       // as well to ensure guarantees to callers
 448       single_revoke_at_safepoint(o, true, requesting_thread, NULL);
 449     }
 450   } // ThreadsListHandle is destroyed here.
 451 
 452   log_info(biasedlocking)("* Ending bulk revocation");
 453 
 454   assert(!o->mark().has_bias_pattern(), "bug in bulk bias revocation");
 455 }
 456 
 457 
 458 static void clean_up_cached_monitor_info(JavaThread* thread = NULL) {
 459   if (thread != NULL) {
 460     thread->set_cached_monitor_info(NULL);
 461   } else {
 462     // Walk the thread list clearing out the cached monitors
 463     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thr = jtiwh.next(); ) {
 464       thr->set_cached_monitor_info(NULL);
 465     }
 466   }
 467 }
 468 
 469 
 470 class VM_BulkRevokeBias : public VM_Operation {
 471 private:
 472   Handle* _obj;
 473   JavaThread* _requesting_thread;
 474   bool _bulk_rebias;
 475   uint64_t _safepoint_id;
 476 
 477 public:
 478   VM_BulkRevokeBias(Handle* obj, JavaThread* requesting_thread,
 479                     bool bulk_rebias)
 480     : _obj(obj)
 481     , _requesting_thread(requesting_thread)
 482     , _bulk_rebias(bulk_rebias)
 483     , _safepoint_id(0) {}
 484 
 485   virtual VMOp_Type type() const { return VMOp_BulkRevokeBias; }
 486 
 487   virtual void doit() {
 488     BiasedLocking::bulk_revoke_at_safepoint((*_obj)(), _bulk_rebias, _requesting_thread);
 489     _safepoint_id = SafepointSynchronize::safepoint_id();
 490     clean_up_cached_monitor_info();
 491   }
 492 
 493   bool is_bulk_rebias() const {
 494     return _bulk_rebias;
 495   }
 496 
 497   uint64_t safepoint_id() const {
 498     return _safepoint_id;
 499   }
 500 };
 501 
 502 
 503 class RevokeOneBias : public ThreadClosure {
 504 protected:
 505   Handle _obj;
 506   JavaThread* _requesting_thread;
 507   JavaThread* _biased_locker;
 508   BiasedLocking::Condition _status_code;
 509   traceid _biased_locker_id;
 510 
 511 public:
 512   RevokeOneBias(Handle obj, JavaThread* requesting_thread, JavaThread* biased_locker)
 513     : _obj(obj)

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