Path: blob/master/src/hotspot/share/runtime/biasedLocking.cpp
40951 views
/*1* Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/classLoaderDataGraph.hpp"26#include "jfr/jfrEvents.hpp"27#include "jfr/support/jfrThreadId.hpp"28#include "logging/log.hpp"29#include "memory/resourceArea.hpp"30#include "oops/klass.inline.hpp"31#include "oops/markWord.hpp"32#include "oops/oop.inline.hpp"33#include "runtime/atomic.hpp"34#include "runtime/basicLock.hpp"35#include "runtime/biasedLocking.hpp"36#include "runtime/handles.inline.hpp"37#include "runtime/handshake.hpp"38#include "runtime/safepointMechanism.hpp"39#include "runtime/task.hpp"40#include "runtime/threadSMR.hpp"41#include "runtime/vframe.hpp"42#include "runtime/vmThread.hpp"43#include "runtime/vmOperations.hpp"444546static bool _biased_locking_enabled = false;47BiasedLockingCounters BiasedLocking::_counters;4849static GrowableArray<Handle>* _preserved_oop_stack = NULL;50static GrowableArray<markWord>* _preserved_mark_stack = NULL;5152static void enable_biased_locking(InstanceKlass* k) {53k->set_prototype_header(markWord::biased_locking_prototype());54}5556static void enable_biased_locking() {57_biased_locking_enabled = true;58log_info(biasedlocking)("Biased locking enabled");59}6061class VM_EnableBiasedLocking: public VM_Operation {62public:63VM_EnableBiasedLocking() {}64VMOp_Type type() const { return VMOp_EnableBiasedLocking; }6566void doit() {67// Iterate the class loader data dictionaries enabling biased locking for all68// currently loaded classes.69ClassLoaderDataGraph::dictionary_classes_do(enable_biased_locking);70// Indicate that future instances should enable it as well71enable_biased_locking();72}7374bool allow_nested_vm_operations() const { return false; }75};767778// One-shot PeriodicTask subclass for enabling biased locking79class EnableBiasedLockingTask : public PeriodicTask {80public:81EnableBiasedLockingTask(size_t interval_time) : PeriodicTask(interval_time) {}8283virtual void task() {84VM_EnableBiasedLocking op;85VMThread::execute(&op);8687// Reclaim our storage and disenroll ourself88delete this;89}90};919293void BiasedLocking::init() {94// If biased locking is enabled and BiasedLockingStartupDelay is set,95// schedule a task to fire after the specified delay which turns on96// biased locking for all currently loaded classes as well as future97// ones. This could be a workaround for startup time regressions98// due to large number of safepoints being taken during VM startup for99// bias revocation.100if (UseBiasedLocking) {101if (BiasedLockingStartupDelay > 0) {102EnableBiasedLockingTask* task = new EnableBiasedLockingTask(BiasedLockingStartupDelay);103task->enroll();104} else {105enable_biased_locking();106}107}108}109110111bool BiasedLocking::enabled() {112assert(UseBiasedLocking, "precondition");113// We check "BiasedLockingStartupDelay == 0" here to cover the114// possibility of calls to BiasedLocking::enabled() before115// BiasedLocking::init().116return _biased_locking_enabled || BiasedLockingStartupDelay == 0;117}118119120// Returns MonitorInfos for all objects locked on this thread in youngest to oldest order121static GrowableArray<MonitorInfo*>* get_or_compute_monitor_info(JavaThread* thread) {122GrowableArray<MonitorInfo*>* info = thread->cached_monitor_info();123if (info != NULL) {124return info;125}126127info = new GrowableArray<MonitorInfo*>();128129// It's possible for the thread to not have any Java frames on it,130// i.e., if it's the main thread and it's already returned from main()131if (thread->has_last_Java_frame()) {132RegisterMap rm(thread);133for (javaVFrame* vf = thread->last_java_vframe(&rm); vf != NULL; vf = vf->java_sender()) {134GrowableArray<MonitorInfo*> *monitors = vf->monitors();135if (monitors != NULL) {136int len = monitors->length();137// Walk monitors youngest to oldest138for (int i = len - 1; i >= 0; i--) {139MonitorInfo* mon_info = monitors->at(i);140if (mon_info->eliminated()) continue;141oop owner = mon_info->owner();142if (owner != NULL) {143info->append(mon_info);144}145}146}147}148}149150thread->set_cached_monitor_info(info);151return info;152}153154155// After the call, *biased_locker will be set to obj->mark()->biased_locker() if biased_locker != NULL,156// AND it is a living thread. Otherwise it will not be updated, (i.e. the caller is responsible for initialization).157void BiasedLocking::single_revoke_at_safepoint(oop obj, bool is_bulk, JavaThread* requesting_thread, JavaThread** biased_locker) {158assert(SafepointSynchronize::is_at_safepoint(), "must be done at safepoint");159assert(Thread::current()->is_VM_thread(), "must be VMThread");160161markWord mark = obj->mark();162if (!mark.has_bias_pattern()) {163if (log_is_enabled(Info, biasedlocking)) {164ResourceMark rm;165log_info(biasedlocking)(" (Skipping revocation of object " INTPTR_FORMAT166", mark " INTPTR_FORMAT ", type %s"167", requesting thread " INTPTR_FORMAT168" because it's no longer biased)",169p2i((void *)obj), mark.value(),170obj->klass()->external_name(),171(intptr_t) requesting_thread);172}173return;174}175176uint age = mark.age();177markWord unbiased_prototype = markWord::prototype().set_age(age);178179// Log at "info" level if not bulk, else "trace" level180if (!is_bulk) {181ResourceMark rm;182log_info(biasedlocking)("Revoking bias of object " INTPTR_FORMAT ", mark "183INTPTR_FORMAT ", type %s, prototype header " INTPTR_FORMAT184", requesting thread " INTPTR_FORMAT,185p2i((void *)obj),186mark.value(),187obj->klass()->external_name(),188obj->klass()->prototype_header().value(),189(intptr_t) requesting_thread);190} else {191ResourceMark rm;192log_trace(biasedlocking)("Revoking bias of object " INTPTR_FORMAT " , mark "193INTPTR_FORMAT " , type %s , prototype header " INTPTR_FORMAT194" , requesting thread " INTPTR_FORMAT,195p2i((void *)obj),196mark.value(),197obj->klass()->external_name(),198obj->klass()->prototype_header().value(),199(intptr_t) requesting_thread);200}201202JavaThread* biased_thread = mark.biased_locker();203if (biased_thread == NULL) {204// Object is anonymously biased. We can get here if, for205// example, we revoke the bias due to an identity hash code206// being computed for an object.207obj->set_mark(unbiased_prototype);208209// Log at "info" level if not bulk, else "trace" level210if (!is_bulk) {211log_info(biasedlocking)(" Revoked bias of anonymously-biased object");212} else {213log_trace(biasedlocking)(" Revoked bias of anonymously-biased object");214}215return;216}217218// Handle case where the thread toward which the object was biased has exited219bool thread_is_alive = false;220if (requesting_thread == biased_thread) {221thread_is_alive = true;222} else {223ThreadsListHandle tlh;224thread_is_alive = tlh.includes(biased_thread);225}226if (!thread_is_alive) {227obj->set_mark(unbiased_prototype);228// Log at "info" level if not bulk, else "trace" level229if (!is_bulk) {230log_info(biasedlocking)(" Revoked bias of object biased toward dead thread ("231PTR_FORMAT ")", p2i(biased_thread));232} else {233log_trace(biasedlocking)(" Revoked bias of object biased toward dead thread ("234PTR_FORMAT ")", p2i(biased_thread));235}236return;237}238239// Log at "info" level if not bulk, else "trace" level240if (!is_bulk) {241log_info(biasedlocking)(" Revoked bias of object biased toward live thread ("242PTR_FORMAT ")", p2i(biased_thread));243} else {244log_trace(biasedlocking)(" Revoked bias of object biased toward live thread ("245PTR_FORMAT ")", p2i(biased_thread));246}247248// Thread owning bias is alive.249// Check to see whether it currently owns the lock and, if so,250// write down the needed displaced headers to the thread's stack.251// Otherwise, restore the object's header either to the unlocked252// or unbiased state.253GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(biased_thread);254BasicLock* highest_lock = NULL;255for (int i = 0; i < cached_monitor_info->length(); i++) {256MonitorInfo* mon_info = cached_monitor_info->at(i);257if (mon_info->owner() == obj) {258log_trace(biasedlocking)(" mon_info->owner (" PTR_FORMAT ") == obj (" PTR_FORMAT ")",259p2i((void *) mon_info->owner()),260p2i((void *) obj));261// Assume recursive case and fix up highest lock below262markWord mark = markWord::encode((BasicLock*) NULL);263highest_lock = mon_info->lock();264highest_lock->set_displaced_header(mark);265} else {266log_trace(biasedlocking)(" mon_info->owner (" PTR_FORMAT ") != obj (" PTR_FORMAT ")",267p2i((void *) mon_info->owner()),268p2i((void *) obj));269}270}271if (highest_lock != NULL) {272// Fix up highest lock to contain displaced header and point273// object at it274highest_lock->set_displaced_header(unbiased_prototype);275// Reset object header to point to displaced mark.276// Must release store the lock address for platforms without TSO277// ordering (e.g. ppc).278obj->release_set_mark(markWord::encode(highest_lock));279assert(!obj->mark().has_bias_pattern(), "illegal mark state: stack lock used bias bit");280// Log at "info" level if not bulk, else "trace" level281if (!is_bulk) {282log_info(biasedlocking)(" Revoked bias of currently-locked object");283} else {284log_trace(biasedlocking)(" Revoked bias of currently-locked object");285}286} else {287// Log at "info" level if not bulk, else "trace" level288if (!is_bulk) {289log_info(biasedlocking)(" Revoked bias of currently-unlocked object");290} else {291log_trace(biasedlocking)(" Revoked bias of currently-unlocked object");292}293// Store the unlocked value into the object's header.294obj->set_mark(unbiased_prototype);295}296297// If requested, return information on which thread held the bias298if (biased_locker != NULL) {299*biased_locker = biased_thread;300}301}302303304enum HeuristicsResult {305HR_NOT_BIASED = 1,306HR_SINGLE_REVOKE = 2,307HR_BULK_REBIAS = 3,308HR_BULK_REVOKE = 4309};310311312static HeuristicsResult update_heuristics(oop o) {313markWord mark = o->mark();314if (!mark.has_bias_pattern()) {315return HR_NOT_BIASED;316}317318// Heuristics to attempt to throttle the number of revocations.319// Stages:320// 1. Revoke the biases of all objects in the heap of this type,321// but allow rebiasing of those objects if unlocked.322// 2. Revoke the biases of all objects in the heap of this type323// and don't allow rebiasing of these objects. Disable324// allocation of objects of that type with the bias bit set.325Klass* k = o->klass();326jlong cur_time = nanos_to_millis(os::javaTimeNanos());327jlong last_bulk_revocation_time = k->last_biased_lock_bulk_revocation_time();328int revocation_count = k->biased_lock_revocation_count();329if ((revocation_count >= BiasedLockingBulkRebiasThreshold) &&330(revocation_count < BiasedLockingBulkRevokeThreshold) &&331(last_bulk_revocation_time != 0) &&332(cur_time - last_bulk_revocation_time >= BiasedLockingDecayTime)) {333// This is the first revocation we've seen in a while of an334// object of this type since the last time we performed a bulk335// rebiasing operation. The application is allocating objects in336// bulk which are biased toward a thread and then handing them337// off to another thread. We can cope with this allocation338// pattern via the bulk rebiasing mechanism so we reset the339// klass's revocation count rather than allow it to increase340// monotonically. If we see the need to perform another bulk341// rebias operation later, we will, and if subsequently we see342// many more revocation operations in a short period of time we343// will completely disable biasing for this type.344k->set_biased_lock_revocation_count(0);345revocation_count = 0;346}347348// Make revocation count saturate just beyond BiasedLockingBulkRevokeThreshold349if (revocation_count <= BiasedLockingBulkRevokeThreshold) {350revocation_count = k->atomic_incr_biased_lock_revocation_count();351}352353if (revocation_count == BiasedLockingBulkRevokeThreshold) {354return HR_BULK_REVOKE;355}356357if (revocation_count == BiasedLockingBulkRebiasThreshold) {358return HR_BULK_REBIAS;359}360361return HR_SINGLE_REVOKE;362}363364365void BiasedLocking::bulk_revoke_at_safepoint(oop o, bool bulk_rebias, JavaThread* requesting_thread) {366assert(SafepointSynchronize::is_at_safepoint(), "must be done at safepoint");367assert(Thread::current()->is_VM_thread(), "must be VMThread");368369log_info(biasedlocking)("* Beginning bulk revocation (kind == %s) because of object "370INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",371(bulk_rebias ? "rebias" : "revoke"),372p2i((void *) o),373o->mark().value(),374o->klass()->external_name());375376jlong cur_time = nanos_to_millis(os::javaTimeNanos());377o->klass()->set_last_biased_lock_bulk_revocation_time(cur_time);378379Klass* k_o = o->klass();380Klass* klass = k_o;381382{383JavaThreadIteratorWithHandle jtiwh;384385if (bulk_rebias) {386// Use the epoch in the klass of the object to implicitly revoke387// all biases of objects of this data type and force them to be388// reacquired. However, we also need to walk the stacks of all389// threads and update the headers of lightweight locked objects390// with biases to have the current epoch.391392// If the prototype header doesn't have the bias pattern, don't393// try to update the epoch -- assume another VM operation came in394// and reset the header to the unbiased state, which will395// implicitly cause all existing biases to be revoked396if (klass->prototype_header().has_bias_pattern()) {397int prev_epoch = klass->prototype_header().bias_epoch();398klass->set_prototype_header(klass->prototype_header().incr_bias_epoch());399int cur_epoch = klass->prototype_header().bias_epoch();400401// Now walk all threads' stacks and adjust epochs of any biased402// and locked objects of this data type we encounter403for (; JavaThread *thr = jtiwh.next(); ) {404GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(thr);405for (int i = 0; i < cached_monitor_info->length(); i++) {406MonitorInfo* mon_info = cached_monitor_info->at(i);407oop owner = mon_info->owner();408markWord mark = owner->mark();409if ((owner->klass() == k_o) && mark.has_bias_pattern()) {410// We might have encountered this object already in the case of recursive locking411assert(mark.bias_epoch() == prev_epoch || mark.bias_epoch() == cur_epoch, "error in bias epoch adjustment");412owner->set_mark(mark.set_bias_epoch(cur_epoch));413}414}415}416}417418// At this point we're done. All we have to do is potentially419// adjust the header of the given object to revoke its bias.420single_revoke_at_safepoint(o, true, requesting_thread, NULL);421} else {422if (log_is_enabled(Info, biasedlocking)) {423ResourceMark rm;424log_info(biasedlocking)("* Disabling biased locking for type %s", klass->external_name());425}426427// Disable biased locking for this data type. Not only will this428// cause future instances to not be biased, but existing biased429// instances will notice that this implicitly caused their biases430// to be revoked.431klass->set_prototype_header(markWord::prototype());432433// Now walk all threads' stacks and forcibly revoke the biases of434// any locked and biased objects of this data type we encounter.435for (; JavaThread *thr = jtiwh.next(); ) {436GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(thr);437for (int i = 0; i < cached_monitor_info->length(); i++) {438MonitorInfo* mon_info = cached_monitor_info->at(i);439oop owner = mon_info->owner();440markWord mark = owner->mark();441if ((owner->klass() == k_o) && mark.has_bias_pattern()) {442single_revoke_at_safepoint(owner, true, requesting_thread, NULL);443}444}445}446447// Must force the bias of the passed object to be forcibly revoked448// as well to ensure guarantees to callers449single_revoke_at_safepoint(o, true, requesting_thread, NULL);450}451} // ThreadsListHandle is destroyed here.452453log_info(biasedlocking)("* Ending bulk revocation");454455assert(!o->mark().has_bias_pattern(), "bug in bulk bias revocation");456}457458459static void clean_up_cached_monitor_info(JavaThread* thread = NULL) {460if (thread != NULL) {461thread->set_cached_monitor_info(NULL);462} else {463// Walk the thread list clearing out the cached monitors464for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thr = jtiwh.next(); ) {465thr->set_cached_monitor_info(NULL);466}467}468}469470471class VM_BulkRevokeBias : public VM_Operation {472private:473Handle* _obj;474JavaThread* _requesting_thread;475bool _bulk_rebias;476uint64_t _safepoint_id;477478public:479VM_BulkRevokeBias(Handle* obj, JavaThread* requesting_thread,480bool bulk_rebias)481: _obj(obj)482, _requesting_thread(requesting_thread)483, _bulk_rebias(bulk_rebias)484, _safepoint_id(0) {}485486virtual VMOp_Type type() const { return VMOp_BulkRevokeBias; }487488virtual void doit() {489BiasedLocking::bulk_revoke_at_safepoint((*_obj)(), _bulk_rebias, _requesting_thread);490_safepoint_id = SafepointSynchronize::safepoint_id();491clean_up_cached_monitor_info();492}493494bool is_bulk_rebias() const {495return _bulk_rebias;496}497498uint64_t safepoint_id() const {499return _safepoint_id;500}501};502503504class RevokeOneBias : public HandshakeClosure {505protected:506Handle _obj;507JavaThread* _requesting_thread;508JavaThread* _biased_locker;509BiasedLocking::Condition _status_code;510traceid _biased_locker_id;511bool _executed;512513public:514RevokeOneBias(Handle obj, JavaThread* requesting_thread, JavaThread* biased_locker)515: HandshakeClosure("RevokeOneBias")516, _obj(obj)517, _requesting_thread(requesting_thread)518, _biased_locker(biased_locker)519, _status_code(BiasedLocking::NOT_BIASED)520, _biased_locker_id(0)521, _executed(false) {}522523bool executed() { return _executed; }524525void do_thread(Thread* target) {526assert(target == _biased_locker, "Wrong thread");527_executed = true;528529oop o = _obj();530markWord mark = o->mark();531532if (!mark.has_bias_pattern()) {533return;534}535536markWord prototype = o->klass()->prototype_header();537if (!prototype.has_bias_pattern()) {538// This object has a stale bias from before the handshake539// was requested. If we fail this race, the object's bias540// has been revoked by another thread so we simply return.541markWord biased_value = mark;542mark = o->cas_set_mark(markWord::prototype().set_age(mark.age()), mark);543assert(!o->mark().has_bias_pattern(), "even if we raced, should still be revoked");544if (biased_value == mark) {545_status_code = BiasedLocking::BIAS_REVOKED;546}547return;548}549550if (_biased_locker == mark.biased_locker()) {551if (mark.bias_epoch() == prototype.bias_epoch()) {552// Epoch is still valid. This means biaser could be currently553// synchronized on this object. We must walk its stack looking554// for monitor records associated with this object and change555// them to be stack locks if any are found.556ResourceMark rm;557BiasedLocking::walk_stack_and_revoke(o, _biased_locker);558_biased_locker->set_cached_monitor_info(NULL);559assert(!o->mark().has_bias_pattern(), "invariant");560_biased_locker_id = JFR_THREAD_ID(_biased_locker);561_status_code = BiasedLocking::BIAS_REVOKED;562return;563} else {564markWord biased_value = mark;565mark = o->cas_set_mark(markWord::prototype().set_age(mark.age()), mark);566if (mark == biased_value || !mark.has_bias_pattern()) {567assert(!o->mark().has_bias_pattern(), "should be revoked");568_status_code = (biased_value == mark) ? BiasedLocking::BIAS_REVOKED : BiasedLocking::NOT_BIASED;569return;570}571}572}573574_status_code = BiasedLocking::NOT_REVOKED;575}576577BiasedLocking::Condition status_code() const {578return _status_code;579}580581traceid biased_locker() const {582return _biased_locker_id;583}584};585586587static void post_self_revocation_event(EventBiasedLockSelfRevocation* event, Klass* k) {588assert(event != NULL, "invariant");589assert(k != NULL, "invariant");590assert(event->should_commit(), "invariant");591event->set_lockClass(k);592event->commit();593}594595static void post_revocation_event(EventBiasedLockRevocation* event, Klass* k, RevokeOneBias* op) {596assert(event != NULL, "invariant");597assert(k != NULL, "invariant");598assert(op != NULL, "invariant");599assert(event->should_commit(), "invariant");600event->set_lockClass(k);601event->set_safepointId(0);602event->set_previousOwner(op->biased_locker());603event->commit();604}605606static void post_class_revocation_event(EventBiasedLockClassRevocation* event, Klass* k, VM_BulkRevokeBias* op) {607assert(event != NULL, "invariant");608assert(k != NULL, "invariant");609assert(op != NULL, "invariant");610assert(event->should_commit(), "invariant");611event->set_revokedClass(k);612event->set_disableBiasing(!op->is_bulk_rebias());613event->set_safepointId(op->safepoint_id());614event->commit();615}616617618BiasedLocking::Condition BiasedLocking::single_revoke_with_handshake(Handle obj, JavaThread *requester, JavaThread *biaser) {619620EventBiasedLockRevocation event;621if (PrintBiasedLockingStatistics) {622Atomic::inc(handshakes_count_addr());623}624log_info(biasedlocking, handshake)("JavaThread " INTPTR_FORMAT " handshaking JavaThread "625INTPTR_FORMAT " to revoke object " INTPTR_FORMAT, p2i(requester),626p2i(biaser), p2i(obj()));627628RevokeOneBias revoke(obj, requester, biaser);629Handshake::execute(&revoke, biaser);630if (revoke.status_code() == NOT_REVOKED) {631return NOT_REVOKED;632}633if (revoke.executed()) {634log_info(biasedlocking, handshake)("Handshake revocation for object " INTPTR_FORMAT " succeeded. Bias was %srevoked",635p2i(obj()), (revoke.status_code() == BIAS_REVOKED ? "" : "already "));636if (event.should_commit() && revoke.status_code() == BIAS_REVOKED) {637post_revocation_event(&event, obj->klass(), &revoke);638}639assert(!obj->mark().has_bias_pattern(), "invariant");640return revoke.status_code();641} else {642// Thread was not alive.643// Grab Threads_lock before manually trying to revoke bias. This avoids race with a newly644// created JavaThread (that happens to get the same memory address as biaser) synchronizing645// on this object.646{647MutexLocker ml(Threads_lock);648markWord mark = obj->mark();649// Check if somebody else was able to revoke it before biased thread exited.650if (!mark.has_bias_pattern()) {651return NOT_BIASED;652}653ThreadsListHandle tlh;654markWord prototype = obj->klass()->prototype_header();655if (!prototype.has_bias_pattern() || (!tlh.includes(biaser) && biaser == mark.biased_locker() &&656prototype.bias_epoch() == mark.bias_epoch())) {657obj->cas_set_mark(markWord::prototype().set_age(mark.age()), mark);658if (event.should_commit()) {659post_revocation_event(&event, obj->klass(), &revoke);660}661assert(!obj->mark().has_bias_pattern(), "bias should be revoked by now");662return BIAS_REVOKED;663}664}665}666667return NOT_REVOKED;668}669670671// Caller should have instantiated a ResourceMark object before calling this method672void BiasedLocking::walk_stack_and_revoke(oop obj, JavaThread* biased_locker) {673Thread* cur = Thread::current();674assert(!SafepointSynchronize::is_at_safepoint(), "this should always be executed outside safepoints");675assert(biased_locker->is_handshake_safe_for(cur), "wrong thread");676677markWord mark = obj->mark();678assert(mark.biased_locker() == biased_locker &&679obj->klass()->prototype_header().bias_epoch() == mark.bias_epoch(), "invariant");680681log_trace(biasedlocking)("JavaThread(" INTPTR_FORMAT ") revoking object " INTPTR_FORMAT ", mark "682INTPTR_FORMAT ", type %s, prototype header " INTPTR_FORMAT683", biaser " INTPTR_FORMAT " %s",684p2i(cur),685p2i(obj),686mark.value(),687obj->klass()->external_name(),688obj->klass()->prototype_header().value(),689p2i(biased_locker),690cur != biased_locker ? "" : "(walking own stack)");691692markWord unbiased_prototype = markWord::prototype().set_age(obj->mark().age());693694GrowableArray<MonitorInfo*>* cached_monitor_info = get_or_compute_monitor_info(biased_locker);695BasicLock* highest_lock = NULL;696for (int i = 0; i < cached_monitor_info->length(); i++) {697MonitorInfo* mon_info = cached_monitor_info->at(i);698if (mon_info->owner() == obj) {699log_trace(biasedlocking)(" mon_info->owner (" PTR_FORMAT ") == obj (" PTR_FORMAT ")",700p2i(mon_info->owner()),701p2i(obj));702// Assume recursive case and fix up highest lock below703markWord mark = markWord::encode((BasicLock*) NULL);704highest_lock = mon_info->lock();705highest_lock->set_displaced_header(mark);706} else {707log_trace(biasedlocking)(" mon_info->owner (" PTR_FORMAT ") != obj (" PTR_FORMAT ")",708p2i(mon_info->owner()),709p2i(obj));710}711}712if (highest_lock != NULL) {713// Fix up highest lock to contain displaced header and point714// object at it715highest_lock->set_displaced_header(unbiased_prototype);716// Reset object header to point to displaced mark.717// Must release store the lock address for platforms without TSO718// ordering (e.g. ppc).719obj->release_set_mark(markWord::encode(highest_lock));720assert(!obj->mark().has_bias_pattern(), "illegal mark state: stack lock used bias bit");721log_info(biasedlocking)(" Revoked bias of currently-locked object");722} else {723log_info(biasedlocking)(" Revoked bias of currently-unlocked object");724// Store the unlocked value into the object's header.725obj->set_mark(unbiased_prototype);726}727728assert(!obj->mark().has_bias_pattern(), "must not be biased");729}730731void BiasedLocking::revoke_own_lock(JavaThread* current, Handle obj) {732markWord mark = obj->mark();733734if (!mark.has_bias_pattern()) {735return;736}737738Klass *k = obj->klass();739assert(mark.biased_locker() == current &&740k->prototype_header().bias_epoch() == mark.bias_epoch(), "Revoke failed, unhandled biased lock state");741ResourceMark rm(current);742log_info(biasedlocking)("Revoking bias by walking my own stack:");743EventBiasedLockSelfRevocation event;744BiasedLocking::walk_stack_and_revoke(obj(), current);745current->set_cached_monitor_info(NULL);746assert(!obj->mark().has_bias_pattern(), "invariant");747if (event.should_commit()) {748post_self_revocation_event(&event, k);749}750}751752void BiasedLocking::revoke(JavaThread* current, Handle obj) {753assert(!SafepointSynchronize::is_at_safepoint(), "must not be called while at safepoint");754755while (true) {756// We can revoke the biases of anonymously-biased objects757// efficiently enough that we should not cause these revocations to758// update the heuristics because doing so may cause unwanted bulk759// revocations (which are expensive) to occur.760markWord mark = obj->mark();761762if (!mark.has_bias_pattern()) {763return;764}765766if (mark.is_biased_anonymously()) {767// We are probably trying to revoke the bias of this object due to768// an identity hash code computation. Try to revoke the bias769// without a safepoint. This is possible if we can successfully770// compare-and-exchange an unbiased header into the mark word of771// the object, meaning that no other thread has raced to acquire772// the bias of the object.773markWord biased_value = mark;774markWord unbiased_prototype = markWord::prototype().set_age(mark.age());775markWord res_mark = obj->cas_set_mark(unbiased_prototype, mark);776if (res_mark == biased_value) {777return;778}779mark = res_mark; // Refresh mark with the latest value.780} else {781Klass* k = obj->klass();782markWord prototype_header = k->prototype_header();783if (!prototype_header.has_bias_pattern()) {784// This object has a stale bias from before the bulk revocation785// for this data type occurred. It's pointless to update the786// heuristics at this point so simply update the header with a787// CAS. If we fail this race, the object's bias has been revoked788// by another thread so we simply return and let the caller deal789// with it.790obj->cas_set_mark(prototype_header.set_age(mark.age()), mark);791assert(!obj->mark().has_bias_pattern(), "even if we raced, should still be revoked");792return;793} else if (prototype_header.bias_epoch() != mark.bias_epoch()) {794// The epoch of this biasing has expired indicating that the795// object is effectively unbiased. We can revoke the bias of this796// object efficiently enough with a CAS that we shouldn't update the797// heuristics. This is normally done in the assembly code but we798// can reach this point due to various points in the runtime799// needing to revoke biases.800markWord res_mark;801markWord biased_value = mark;802markWord unbiased_prototype = markWord::prototype().set_age(mark.age());803res_mark = obj->cas_set_mark(unbiased_prototype, mark);804if (res_mark == biased_value) {805return;806}807mark = res_mark; // Refresh mark with the latest value.808}809}810811HeuristicsResult heuristics = update_heuristics(obj());812if (heuristics == HR_NOT_BIASED) {813return;814} else if (heuristics == HR_SINGLE_REVOKE) {815JavaThread *blt = mark.biased_locker();816assert(blt != NULL, "invariant");817if (blt == current) {818// A thread is trying to revoke the bias of an object biased819// toward it, again likely due to an identity hash code820// computation. We can again avoid a safepoint/handshake in this case821// since we are only going to walk our own stack. There are no822// races with revocations occurring in other threads because we823// reach no safepoints in the revocation path.824EventBiasedLockSelfRevocation event;825ResourceMark rm(current);826walk_stack_and_revoke(obj(), blt);827blt->set_cached_monitor_info(NULL);828assert(!obj->mark().has_bias_pattern(), "invariant");829if (event.should_commit()) {830post_self_revocation_event(&event, obj->klass());831}832return;833} else {834BiasedLocking::Condition cond = single_revoke_with_handshake(obj, current, blt);835if (cond != NOT_REVOKED) {836return;837}838}839} else {840assert((heuristics == HR_BULK_REVOKE) ||841(heuristics == HR_BULK_REBIAS), "?");842EventBiasedLockClassRevocation event;843VM_BulkRevokeBias bulk_revoke(&obj, current, (heuristics == HR_BULK_REBIAS));844VMThread::execute(&bulk_revoke);845if (event.should_commit()) {846post_class_revocation_event(&event, obj->klass(), &bulk_revoke);847}848return;849}850}851}852853// All objects in objs should be locked by biaser854void BiasedLocking::revoke(GrowableArray<Handle>* objs, JavaThread *biaser) {855bool clean_my_cache = false;856for (int i = 0; i < objs->length(); i++) {857oop obj = (objs->at(i))();858markWord mark = obj->mark();859if (mark.has_bias_pattern()) {860walk_stack_and_revoke(obj, biaser);861clean_my_cache = true;862}863}864if (clean_my_cache) {865clean_up_cached_monitor_info(biaser);866}867}868869870void BiasedLocking::revoke_at_safepoint(Handle h_obj) {871assert(SafepointSynchronize::is_at_safepoint(), "must only be called while at safepoint");872oop obj = h_obj();873HeuristicsResult heuristics = update_heuristics(obj);874if (heuristics == HR_SINGLE_REVOKE) {875JavaThread* biased_locker = NULL;876single_revoke_at_safepoint(obj, false, NULL, &biased_locker);877if (biased_locker) {878clean_up_cached_monitor_info(biased_locker);879}880} else if ((heuristics == HR_BULK_REBIAS) ||881(heuristics == HR_BULK_REVOKE)) {882bulk_revoke_at_safepoint(obj, (heuristics == HR_BULK_REBIAS), NULL);883clean_up_cached_monitor_info();884}885}886887888void BiasedLocking::preserve_marks() {889if (!UseBiasedLocking)890return;891892assert(SafepointSynchronize::is_at_safepoint(), "must only be called while at safepoint");893894assert(_preserved_oop_stack == NULL, "double initialization");895assert(_preserved_mark_stack == NULL, "double initialization");896897// In order to reduce the number of mark words preserved during GC898// due to the presence of biased locking, we reinitialize most mark899// words to the class's prototype during GC -- even those which have900// a currently valid bias owner. One important situation where we901// must not clobber a bias is when a biased object is currently902// locked. To handle this case we iterate over the currently-locked903// monitors in a prepass and, if they are biased, preserve their904// mark words here. This should be a relatively small set of objects905// especially compared to the number of objects in the heap.906_preserved_mark_stack = new (ResourceObj::C_HEAP, mtGC) GrowableArray<markWord>(10, mtGC);907_preserved_oop_stack = new (ResourceObj::C_HEAP, mtGC) GrowableArray<Handle>(10, mtGC);908909Thread* cur = Thread::current();910ResourceMark rm(cur);911912for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) {913if (thread->has_last_Java_frame()) {914RegisterMap rm(thread);915for (javaVFrame* vf = thread->last_java_vframe(&rm); vf != NULL; vf = vf->java_sender()) {916GrowableArray<MonitorInfo*> *monitors = vf->monitors();917if (monitors != NULL) {918int len = monitors->length();919// Walk monitors youngest to oldest920for (int i = len - 1; i >= 0; i--) {921MonitorInfo* mon_info = monitors->at(i);922if (mon_info->owner_is_scalar_replaced()) continue;923oop owner = mon_info->owner();924if (owner != NULL) {925markWord mark = owner->mark();926if (mark.has_bias_pattern()) {927_preserved_oop_stack->push(Handle(cur, owner));928_preserved_mark_stack->push(mark);929}930}931}932}933}934}935}936}937938939void BiasedLocking::restore_marks() {940if (!UseBiasedLocking)941return;942943assert(_preserved_oop_stack != NULL, "double free");944assert(_preserved_mark_stack != NULL, "double free");945946int len = _preserved_oop_stack->length();947for (int i = 0; i < len; i++) {948Handle owner = _preserved_oop_stack->at(i);949markWord mark = _preserved_mark_stack->at(i);950owner->set_mark(mark);951}952953delete _preserved_oop_stack;954_preserved_oop_stack = NULL;955delete _preserved_mark_stack;956_preserved_mark_stack = NULL;957}958959960int* BiasedLocking::total_entry_count_addr() { return _counters.total_entry_count_addr(); }961int* BiasedLocking::biased_lock_entry_count_addr() { return _counters.biased_lock_entry_count_addr(); }962int* BiasedLocking::anonymously_biased_lock_entry_count_addr() { return _counters.anonymously_biased_lock_entry_count_addr(); }963int* BiasedLocking::rebiased_lock_entry_count_addr() { return _counters.rebiased_lock_entry_count_addr(); }964int* BiasedLocking::revoked_lock_entry_count_addr() { return _counters.revoked_lock_entry_count_addr(); }965int* BiasedLocking::handshakes_count_addr() { return _counters.handshakes_count_addr(); }966int* BiasedLocking::fast_path_entry_count_addr() { return _counters.fast_path_entry_count_addr(); }967int* BiasedLocking::slow_path_entry_count_addr() { return _counters.slow_path_entry_count_addr(); }968969970// BiasedLockingCounters971972int BiasedLockingCounters::slow_path_entry_count() const {973if (_slow_path_entry_count != 0) {974return _slow_path_entry_count;975}976int sum = _biased_lock_entry_count + _anonymously_biased_lock_entry_count +977_rebiased_lock_entry_count + _revoked_lock_entry_count +978_fast_path_entry_count;979980return _total_entry_count - sum;981}982983void BiasedLockingCounters::print_on(outputStream* st) const {984tty->print_cr("# total entries: %d", _total_entry_count);985tty->print_cr("# biased lock entries: %d", _biased_lock_entry_count);986tty->print_cr("# anonymously biased lock entries: %d", _anonymously_biased_lock_entry_count);987tty->print_cr("# rebiased lock entries: %d", _rebiased_lock_entry_count);988tty->print_cr("# revoked lock entries: %d", _revoked_lock_entry_count);989tty->print_cr("# handshakes entries: %d", _handshakes_count);990tty->print_cr("# fast path lock entries: %d", _fast_path_entry_count);991tty->print_cr("# slow path lock entries: %d", slow_path_entry_count());992}993994void BiasedLockingCounters::print() const { print_on(tty); }995996997