src/share/vm/runtime/biasedLocking.cpp

Thu, 10 Apr 2008 15:49:16 -0400

author
sbohne
date
Thu, 10 Apr 2008 15:49:16 -0400
changeset 528
c6ff24ceec1c
parent 519
6e085831cad7
child 631
d1605aabd0a1
permissions
-rw-r--r--

6686407: Fix for 6666698 broke -XX:BiasedLockingStartupDelay=0
Summary: Stack allocated VM_EnableBiasedLocking op must be marked as such
Reviewed-by: xlu, acorn, never, dholmes

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

mercurial