/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/symbolTable.hpp"
#include "gc_implementation/g1/concurrentMark.inline.hpp"
#include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
#include "gc_implementation/g1/g1CollectorPolicy.hpp"
#include "gc_implementation/g1/g1ErgoVerbose.hpp"
#include "gc_implementation/g1/g1Log.hpp"
#include "gc_implementation/g1/g1OopClosures.inline.hpp"
#include "gc_implementation/g1/g1RemSet.hpp"
#include "gc_implementation/g1/heapRegion.inline.hpp"
#include "gc_implementation/g1/heapRegionRemSet.hpp"
#include "gc_implementation/g1/heapRegionSeq.inline.hpp"
#include "gc_implementation/shared/vmGCOperations.hpp"
#include "gc_implementation/shared/gcTimer.hpp"
#include "gc_implementation/shared/gcTrace.hpp"
#include "gc_implementation/shared/gcTraceTime.hpp"
#include "memory/genOopClosures.inline.hpp"
#include "memory/referencePolicy.hpp"
#include "memory/resourceArea.hpp"
#include "oops/oop.inline.hpp"
#include "runtime/handles.inline.hpp"
#include "services/memTracker.hpp"
// Concurrent marking bit map wrapper
// For now we'll just commit all of the bit map up fromt.
// Later on we'll try to be more parsimonious with swap.
"couldn't reseve backing store for concurrent marking bit map");
"didn't reserve backing store for all of concurrent marking bit map?");
_bmWordSize, "inconsistency in bit map sizing");
}
// First we must round addr *up* to a possible object boundary.
HeapWordSize << _shifter);
}
"get_next_one postcondition");
return nextAddr;
}
}
"get_next_one postcondition");
return nextAddr;
}
}
#ifndef PRODUCT
// assert(_bm.map() == _virtual_space.low(), "map inconsistency");
"size inconsistency");
}
#endif
return;
}
"markRange memory region end is not card aligned");
// convert address range into offset range
}
// convert address range into offset range
}
clearRange(mr);
}
return mr;
}
#ifdef ASSERT
, _drain_in_progress(false)
, _drain_in_progress_yields(false)
#endif
{}
vm_exit_during_initialization("Failed to allocate CM region mark stack");
}
_index = 0;
_saved_index = -1;
NOT_PRODUCT(_max_depth = 0);
}
CMMarkStack::~CMMarkStack() {
}
}
while (true) {
if (isFull()) {
_overflow = true;
return;
}
// Otherwise...
// Note that we don't maintain this atomically. We could, but it
// doesn't seem necessary.
return;
}
// Otherwise, we need to try again.
}
}
while (true) {
if (isFull()) {
_overflow = true;
return;
}
// Otherwise...
if (next_index > _capacity) {
_overflow = true;
return;
}
for (int i = 0; i < n; i++) {
}
return;
}
// Otherwise, we need to try again.
}
}
if (next_index > _capacity) {
_overflow = true;
return;
}
// Otherwise.
_index = next_index;
for (int i = 0; i < n; i++) {
}
}
if (index == 0) {
*n = 0;
return false;
} else {
for (int j = 0; j < k; j++) {
}
*n = k;
return true;
}
}
template<class OopClosureClass>
"Drain recursion must be yield-safe.");
bool res = true;
debug_only(_drain_in_progress = true);
while (!isEmpty()) {
"only grey objects on this stack");
res = false;
break;
}
}
debug_only(_drain_in_progress = false);
return res;
}
"note_start_of_gc()/end_of_gc() bracketed incorrectly");
}
// This is intentionally a guarantee, instead of an assert. If we
// accidentally add something to the mark stack during GC, it
// will be a correctness issue so it's better if we crash. we'll
// only check this once per GC anyway, so it won't be a performance
// issue in any way.
_saved_index = -1;
}
for (int i = 0; i < _index; i += 1) {
}
}
}
}
// Currently, only survivors can be root regions.
_should_abort = false;
}
if (_should_abort) {
// If someone has set the should_abort flag, we return NULL to
// force the caller to bail out of their loop.
return NULL;
}
// Currently, only survivors can be root regions.
// Read it again in case it changed while we were waiting for the lock.
// We just claimed the last survivor so store NULL to indicate
// that we're done.
} else {
}
} else {
// Someone else claimed the last survivor while we were trying
// to take the lock so nothing else to do.
}
}
return res;
}
// Currently, only survivors can be root regions.
if (!_should_abort) {
}
{
_scan_in_progress = false;
}
}
if (!scan_in_progress()) return false;
{
while (scan_in_progress()) {
}
}
return true;
}
#ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
#endif // _MSC_VER
}
_sleep_factor(0.0),
_marking_task_overhead(1.0),
_cleanup_sleep_factor(0.0),
_cleanup_task_overhead(1.0),
_cleanup_list("Cleanup List"),
false /* in_resource_area*/),
_markStack(this),
// _finger set in set_non_marking_state
// _active_tasks set in set_non_marking_state
// _tasks set inside the constructor
_has_overflown(false),
_concurrent(false),
_has_aborted(false),
_restart_for_overflow(false),
_concurrent_marking_in_progress(false),
// _verbose_level set below
_init_times(),
_total_counting_time(0.0),
_total_rs_scrub_time(0.0),
if (verbose_level < no_verbose) {
}
if (verbose_level > high_verbose) {
}
if (verbose_low()) {
}
// Create & start a ConcurrentMark thread.
_cmThread = new ConcurrentMarkThread(this);
// so that the assertion in MarkingTaskQueue::task_queue doesn't fail
for (int i = 0; i < (int) _max_task_num; ++i) {
task_queue->initialize();
&_count_card_bitmaps[i],
_accum_task_vtime[i] = 0.0;
}
// Calculate the card number for the bottom of the heap. Used
// in biasing indexes into the accounting card bitmaps.
// Clear all the liveness counting data
if (ConcGCThreads > ParallelGCThreads) {
vm_exit_during_initialization("Can't have more ConcGCThreads "
"than ParallelGCThreads.");
}
if (ParallelGCThreads == 0) {
// if we are not running with any parallel GC threads we will not
// spawn any marking threads either
_sleep_factor = 0.0;
_marking_task_overhead = 1.0;
} else {
// Note: ConcGCThreads has precedence over G1MarkingOverheadPercent
// if both are set
_sleep_factor = 0.0;
_marking_task_overhead = 1.0;
} else if (G1MarkingOverheadPercent > 0) {
// We will calculate the number of parallel marking threads based
// on a target overhead with respect to the soft real-time goal
double overall_cm_overhead =
(double) MaxGCPauseMillis * marking_overhead /
(double) GCPauseIntervalMillis;
double marking_task_overhead =
(double) os::processor_count();
double sleep_factor =
} else {
// Calculate the number of parallel marking threads by scaling
// the number of parallel GC threads.
_sleep_factor = 0.0;
_marking_task_overhead = 1.0;
}
if (parallel_marking_threads() > 1) {
_cleanup_task_overhead = 1.0;
} else {
}
#if 0
#endif
_max_parallel_marking_threads, false, true);
if (_parallel_workers == NULL) {
vm_exit_during_initialization("Failed necessary allocation.");
} else {
}
}
// so that the call below can read a sensible value
}
// If concurrent marking is not in progress, then we do not need to
// update _heap_end.
if (!concurrent_marking_in_progress() && !force) return;
// The heap has been expanded.
}
// Notice that the heap can also shrink. However, this only happens
// during a Full GC (at least currently) and the entire marking
// phase will bail out and the task will not be restarted. So, let's
// do nothing.
}
// Starting values for these two. This should be called in a STW
// phase. CM will be notified of any future g1_committed expansions
// will be at the end of evacuation pauses, when tasks are
// inactive.
// Separated the asserts so that we know which one fires.
// Reset all the marking data structures and any necessary flags
if (verbose_low()) {
}
// We do reset all of them, since different phases will use
// different number of active threads. So, it's easiest to have all
// of them ready.
for (int i = 0; i < (int) _max_task_num; ++i) {
}
// we need this to make sure that the flag is on during the evac
// pause with initial mark piggy-backed
}
if (clear_overflow) {
} else {
}
for (uint i = 0; i < _max_task_num; ++i) {
}
}
// Need to update the three data structures below according to the
// number of active threads for this phase.
}
// We propagate this to all tasks, not just the active ones.
for (int i = 0; i < (int) _max_task_num; ++i)
if (concurrent) {
} else {
// We currently assume that the concurrent flag has been set to
// false before we start remark. At this point we should also be
// in a STW phase.
update_g1_committed(true);
}
}
// We set the global marking state to some default values when we're
// not doing marking.
_active_tasks = 0;
}
ConcurrentMark::~ConcurrentMark() {
// The ConcurrentMark instance is never freed.
}
// Make sure that the concurrent mark thread looks to still be in
// the current cycle.
// We are finishing up the current cycle by clearing the next
// marking bitmap and getting it ready for the next cycle. During
// this time no other cycle can start. So, let's make sure that this
// is the case.
// clear the mark bitmap (no grey objects to start with).
// We need to do this in chunks and offer to yield in between
// each chunk.
}
// Repeat the asserts from above. We'll do them as asserts here to
// minimize their overhead on the product. However, we'll have
// them as guarantees at the beginning / end of the bitmap
// clearing to get some checking in the product.
}
// Clear the liveness counting data
// Repeat the asserts from above.
}
public:
if (!r->continuesHumongous()) {
r->note_start_of_marking();
}
return false;
}
};
_has_aborted = false;
#ifndef PRODUCT
print_reachable("at-cycle-start",
VerifyOption_G1UsePrevMarking, true /* all */);
}
#endif
// Initialise marking structures. This has to be done in a STW phase.
reset();
// For each region note start of marking.
}
// If we force an overflow during remark, the remark operation will
// actually abort and we'll restart concurrent marking. If we always
// force an oveflow during remark we'll never actually complete the
// marking phase. So, we initilize this here, at the start of the
// cycle, so that at the remaining overflow number will decrease at
// every remark and we'll eventually not need to cause one.
force_overflow_stw()->init();
// Start Concurrent Marking weak-reference discovery.
// enable ("weak") refs discovery
// This is the start of the marking cycle, we're expected all
// threads to have SATB queues with active set to false.
false /* expected_active */);
// update_g1_committed() will be called at the end of an evac pause
// when marking is on. So, it's also called at the end of the
// initial-mark pause to update the heap end, if the heap expands
// during it. No need to call it here.
}
/*
* Notice that in the next two methods, we actually leave the STS
* during the barrier sync and join it immediately afterwards. If we
* do not do this, the following deadlock can occur: one thread could
* be in the barrier sync code, waiting for the other thread to also
* sync up, whereas another one could be trying to yield, while also
* waiting for the other threads to sync up too.
*
* Note, however, that this code is also used during remark and in
* this case we should not attempt to leave / enter the STS, otherwise
* we'll either hit an asseert (debug / fastdebug) or deadlock
* (product). So we should only leave / enter the STS if we are
* operating concurrently.
*
* Because the thread that does the sync barrier has left the STS, it
* is possible to be suspended for a Full GC or an evacuation pause
* could occur. This is actually safe, since the entering the sync
* barrier is one of the last things do_marking_step() does, and it
* doesn't manipulate any data structures afterwards.
*/
if (verbose_low()) {
}
if (concurrent()) {
}
if (concurrent()) {
}
// at this point everyone should have synced up and not be doing any
// more work
if (verbose_low()) {
}
// If we're executing the concurrent phase of marking, reset the marking
// state; otherwise the marking state is reset after reference processing,
// during the remark pause.
// If we reset here as a result of an overflow during the remark we will
// see assertion failures from any subsequent set_concurrency_and_phase()
// calls.
if (concurrent()) {
// let the task 0 do this
if (task_num == 0) {
// task 0 is responsible for clearing the global data structures
// We should be here because of an overflow. During STW we should
// not clear the overflow flag since we rely on it being true when
// we exit this method to abort the pause and restart concurent
// marking.
reset_marking_state(true /* clear_overflow */);
force_overflow()->update();
}
}
}
// after this, each task should reset its own data structures then
// then go into the second barrier
}
if (verbose_low()) {
}
if (concurrent()) {
}
if (concurrent()) {
}
// at this point everything should be re-initialized and ready to go
if (verbose_low()) {
}
}
#ifndef PRODUCT
_force = false;
update();
}
if (_num_remaining > 0) {
_num_remaining -= 1;
_force = true;
} else {
_force = false;
}
}
if (_force) {
_force = false;
return true;
} else {
return false;
}
}
#endif // !PRODUCT
private:
public:
"this should only be done by a conc GC thread");
if (!_cm->has_aborted()) {
do {
true /* do_termination */,
false /* is_serial*/);
}
#if 0
"overhead %1.4lf",
#endif
}
}
~CMConcurrentMarkingTask() { }
};
// Calculates the number of active workers for a concurrent
// phase.
if (G1CollectedHeap::use_parallel_gc_threads()) {
if (!UseDynamicNumberOfGCThreads ||
(!FLAG_IS_DEFAULT(ConcGCThreads) &&
} else {
1, /* Minimum workers */
// Don't scale down "n_conc_workers" by scale_parallel_threads() because
// that scaling has already gone into "_max_parallel_marking_threads".
}
return n_conc_workers;
}
// If we are not running with any parallel GC threads we will not
// have spawned any marking threads either. Hence the number of
// concurrent workers should be 0.
return 0;
}
// Currently, only survivors can be root regions.
}
}
private:
public:
"this should only be done by a conc GC thread");
}
}
};
// scan_in_progress() will have been set to true only if there was
// at least one root region to scan. So, if it's false, we
// should not attempt to do any further work.
if (root_regions()->scan_in_progress()) {
"Maximum number of marking threads exceeded");
CMRootRegionScanTask task(this);
if (use_parallel_marking_threads()) {
} else {
}
// It's possible that has_aborted() is true here without actually
// aborting the survivor scan earlier. This is OK as it's
// mainly used for sanity checking.
root_regions()->scan_finished();
}
}
// we might be tempted to assert that:
// assert(asynch == !SafepointSynchronize::is_at_safepoint(),
// "inconsistent argument?");
// However that wouldn't be right, because it's possible that
// a safepoint is indeed in progress as a younger generation
// stop-the-world GC happens even as we mark in this generation.
_restart_for_overflow = false;
force_overflow_conc()->init();
// _g1h has _n_par_threads
"Maximum number of marking threads exceeded");
// Parallel task terminator is set in "set_concurrency_and_phase()"
if (use_parallel_marking_threads()) {
// Don't set _n_par_threads because it affects MT in proceess_strong_roots()
// and the decisions on that MT processing is made elsewhere.
} else {
markingTask.work(0);
}
print_stats();
}
// world is stopped at this checkpoint
"world should be stopped");
// If a full collection has happened, we shouldn't do this.
if (has_aborted()) {
return;
}
if (VerifyDuringGC) {
/* option */ VerifyOption_G1UsePrevMarking);
}
if (has_overflown()) {
// Oops. We overflowed. Restart concurrent marking.
_restart_for_overflow = true;
if (G1TraceMarkStackOverflow) {
}
// Verify the heap w.r.t. the previous marking bitmap.
if (VerifyDuringGC) {
/* option */ VerifyOption_G1UsePrevMarking);
}
// Clear the marking state because we will be restarting
// marking due to overflowing the global mark stack.
} else {
// Aggregate the per-task counting data that we have accumulated
// while marking.
// We're done with marking.
// This is the end of the marking cycle, we're expected all
// threads to have SATB queues with active set to true.
true /* expected_active */);
if (VerifyDuringGC) {
/* option */ VerifyOption_G1UseNextMarking);
}
// Completely reset the marking state since marking completed
}
#endif
// Statistics
}
// Base class of the closures that finalize and verify the
// liveness counting data.
protected:
// Takes a region that's not empty (i.e., it has at least one
// live object in it and sets its corresponding bit on the region
// bitmap to 1. If the region is "starts humongous" it will also set
// to 1 the bits on the region bitmap that correspond to its
// associated "continues humongous" regions.
if (!hr->startsHumongous()) {
// Normal (non-humongous) case: just set the bit.
} else {
// Starts humongous case: calculate how many regions are part of
// this humongous region and then set the bit range.
}
}
public:
};
// Closure that calculates the # live objects per region. Used
// for verification purposes during the cleanup pause.
public:
if (hr->continuesHumongous()) {
// We will ignore these here and process them when their
// associated "starts humongous" region is processed (see
// set_bit_for_heap_region()). Note that we cannot rely on their
// associated "starts humongous" region to have their bit set to
// 1 since, due to the region chunking in the parallel region
// iteration, a "continues humongous" region might be visited
// before its associated "starts humongous".
return false;
}
err_msg("Preconditions not met - "
// Find the first marked object at or after "start".
// Note: if we're looking at the last region in heap - obj_end
// could be actually just beyond the end of the heap; end_idx
// will then correspond to a (non-existent) card that is also
// just beyond the heap.
// end of object is not card aligned - increment to cover
// all the cards spanned by the object
end_idx += 1;
}
// Set the bits in the card BM for the cards spanned by this object.
// Add the size of this object to the number of marked bytes.
// Find the next marked object after this one.
}
// Mark the allocated-since-marking portion...
// Note: if we're looking at the last region in heap - top
// could be actually just beyond the end of the heap; end_idx
// will then correspond to a (non-existent) card that is also
// just beyond the heap.
// end of object is not card aligned - increment to cover
// all the cards spanned by the object
end_idx += 1;
}
// This definitely means the region has live objects.
}
// Update the live region bitmap.
if (marked_bytes > 0) {
}
// Set the marked bytes for the current region so that
// it can be queried by a calling verificiation routine
return false;
}
};
// Heap region closure used for verifying the counting data
// that was accumulated concurrently and aggregated during
// the remark pause. This closure is applied to the heap
// regions during the STW cleanup pause.
int _failures;
public:
bool verbose) :
_failures(0) { }
if (hr->continuesHumongous()) {
// We will ignore these here and process them when their
// associated "starts humongous" region is processed (see
// set_bit_for_heap_region()). Note that we cannot rely on their
// associated "starts humongous" region to have their bit set to
// 1 since, due to the region chunking in the parallel region
// iteration, a "continues humongous" region might be visited
// before its associated "starts humongous".
return false;
}
int failures = 0;
// Call the CalcLiveObjectsClosure to walk the marking bitmap for
// this region and set the corresponding bits in the expected region
// and card bitmaps.
// Verify the marked bytes for this region.
// We're not OK if expected marked bytes > actual marked bytes. It means
// we have missed accounting some objects during the actual marking.
if (exp_marked_bytes > act_marked_bytes) {
if (_verbose) {
}
failures += 1;
}
// Verify the bit, for this region, in the actual and expected
// (which was just calculated) region bit maps.
// We're not OK if the bit in the calculated expected region
// bitmap is set and the bit in the actual region bitmap is not.
if (_verbose) {
"expected: %s, actual: %s",
}
failures += 1;
}
// Verify that the card bit maps for the cards spanned by the current
// region match. We have an error if we have a set bit in the expected
// bit map and the corresponding bit in the actual bitmap is not set.
if (_verbose) {
"expected: %s, actual: %s",
}
failures += 1;
}
}
}
// We could stop iteration over the heap when we
// find the first violating region by returning true.
return false;
}
};
protected:
int _failures;
bool _verbose;
public:
: AbstractGangTask("G1 verify final counting"),
_n_workers(0) {
// Use the value already set as the number of active threads
// in the call to run_task().
if (G1CollectedHeap::use_parallel_gc_threads()) {
"Should have been previously set");
} else {
_n_workers = 1;
}
}
_verbose);
if (G1CollectedHeap::use_parallel_gc_threads()) {
} else {
}
}
};
// Closure that finalizes the liveness counting data.
// Used during the cleanup pause.
// Sets the bits corresponding to the interval [NTAMS, top]
// (which contains the implicitly live objects) in the
// card liveness bitmap. Also sets the bit for each region,
// containing live data, in the region liveness bitmap.
public:
if (hr->continuesHumongous()) {
// We will ignore these here and process them when their
// associated "starts humongous" region is processed (see
// set_bit_for_heap_region()). Note that we cannot rely on their
// associated "starts humongous" region to have their bit set to
// 1 since, due to the region chunking in the parallel region
// iteration, a "continues humongous" region might be visited
// before its associated "starts humongous".
return false;
}
// Mark the allocated-since-marking portion...
// This definitely means the region has live objects.
// Now set the bits in the card bitmap for [ntams, top)
// Note: if we're looking at the last region in heap - top
// could be actually just beyond the end of the heap; end_idx
// will then correspond to a (non-existent) card that is also
// just beyond the heap.
// end of object is not card aligned - increment to cover
// all the cards spanned by the object
end_idx += 1;
}
}
// Set the bit for the region if it contains live data
if (hr->next_marked_bytes() > 0) {
}
return false;
}
};
protected:
public:
: AbstractGangTask("G1 final counting"),
_n_workers(0) {
// Use the value already set as the number of active threads
// in the call to run_task().
if (G1CollectedHeap::use_parallel_gc_threads()) {
"Should have been previously set");
} else {
_n_workers = 1;
}
}
if (G1CollectedHeap::use_parallel_gc_threads()) {
} else {
}
}
};
class G1ParNoteEndTask;
int _worker_num;
double _claimed_region_time;
double _max_region_time;
public:
int worker_num,
_max_live_bytes(0), _regions_claimed(0),
_freed_bytes(0),
if (hr->continuesHumongous()) {
return false;
}
// We use a claim value of zero here because all regions
// were claimed with value 1 in the FinalCount task.
true /* par */);
if (region_time > _max_region_time) {
}
return false;
}
};
friend class G1NoteEndOfConcMarkClosure;
protected:
public:
if (G1CollectedHeap::use_parallel_gc_threads()) {
} else {
}
// Now update the lists
NULL /* free_list */,
true /* par */);
{
// If we iterate over the global cleanup list at the end of
// cleanup to do this printing we will not guarantee to only
// generate output for the newly-reclaimed regions (the list
// might not be empty at the beginning of cleanup; we might
// still be working on its previous contents). So we do the
// printing here, before we append the new regions to the global
// cleanup list.
if (hr_printer->is_active()) {
while (iter.more_available()) {
}
}
}
}
};
protected:
public:
if (G1CollectedHeap::use_parallel_gc_threads()) {
} else {
}
}
};
// world is stopped at this checkpoint
"world should be stopped");
// If a full collection has happened, we shouldn't do this.
if (has_aborted()) {
return;
}
if (VerifyDuringGC) {
/* option */ VerifyOption_G1UsePrevMarking);
}
// Do counting once more with the world stopped for good measure.
if (G1CollectedHeap::use_parallel_gc_threads()) {
"sanity check");
g1h->set_par_threads();
"Should not have been reset");
// Done with the parallel phase so reset to 0.
g1h->set_par_threads(0);
"sanity check");
} else {
n_workers = 1;
}
if (VerifyDuringGC) {
// Verify that the counting data accumulated during marking matches
// that calculated by walking the marking bitmap.
// Bitmaps to hold expected values
&_card_bm,
if (G1CollectedHeap::use_parallel_gc_threads()) {
// Done with the parallel phase so reset to 0.
g1h->set_par_threads(0);
"sanity check");
} else {
}
}
if (G1PrintRegionLivenessInfo) {
}
// Install newly created mark bitMap as "prev".
// Note end of marking in all heap regions.
if (G1CollectedHeap::use_parallel_gc_threads()) {
g1h->set_par_threads(0);
"sanity check");
} else {
}
if (!cleanup_list_is_empty()) {
// The cleanup list is not empty, so we'll have to process it
// concurrently. Notify anyone else that might be wanting free
// regions that there will be more free regions coming soon.
}
// call below, since it affects the metric by which we sort the heap
// regions.
if (G1ScrubRemSets) {
if (G1CollectedHeap::use_parallel_gc_threads()) {
g1h->set_par_threads(0);
"sanity check");
} else {
}
}
// this will also free any regions totally full of garbage objects,
// and sort the regions.
// Statistics.
}
// Clean up will have freed any regions completely full of garbage.
// Update the soft reference policy with the new heap occupancy.
// We need to make this be a "collection" so any collection pause that
// races with it goes around and waits for completeCleanup to finish.
// We reclaimed old regions so we should calculate the sizes to make
if (VerifyDuringGC) {
/* option */ VerifyOption_G1UsePrevMarking);
}
}
if (has_aborted()) return;
if (G1ConcRegionFreeingVerbose) {
"cleanup list has %u entries",
_cleanup_list.length());
}
// Noone else should be accessing the _cleanup_list at this point,
// so it's not necessary to take any locks
while (!_cleanup_list.is_empty()) {
// Instead of adding one region at a time to the secondary_free_list,
// we accumulate them in the local list and move them a few at a
// time. This also cuts down on the number of notify_all() calls
// we do during this process. We'll also append the local list when
// _cleanup_list is empty (which means we just removed the last
// region from the _cleanup_list).
_cleanup_list.is_empty()) {
if (G1ConcRegionFreeingVerbose) {
"appending %u entries to the secondary_free_list, "
"cleanup list still has %u entries",
_cleanup_list.length());
}
{
}
if (G1StressConcRegionFreeing) {
for (uintx i = 0; i < G1StressConcRegionFreeingDelayMillis; ++i) {
}
}
}
}
}
// Supporting Object and Oop closures for reference discovery
// and processing in during marking
}
// 'Keep Alive' oop closure used by both serial parallel reference processing.
// Uses the CMTask associated with a worker thread (for serial reference
// processing the CMTask for worker 0 is used) to preserve (mark) and
// trace referent objects.
//
// Using the CMTask and embedded local queues avoids having the worker
// threads operating on the global mark stack. This reduces the risk
// of overflowing the stack - which we would rather avoid at this late
// state. Also using the tasks' local queues removes the potential
// of the workers interfering with each other that could occur if
// operating on the global stack.
int _ref_counter_limit;
int _ref_counter;
bool _is_serial;
public:
}
template <class T> void do_oop_work(T* p) {
if (!_cm->has_overflown()) {
if (_cm->verbose_high()) {
}
_ref_counter--;
if (_ref_counter == 0) {
// We have dealt with _ref_counter_limit references, pushing them
// and objects reachable from them on to the local stack (and
// possibly the global stack). Call CMTask::do_marking_step() to
// process these entries.
//
// We call CMTask::do_marking_step() in a loop, which we'll exit if
// there's nothing more to do (i.e. we're done with the entries that
// were pushed as a result of the CMTask::deal_with_reference() calls
// above) or we overflow.
//
// Note: CMTask::do_marking_step() can set the CMTask::has_aborted()
// flag while there may still be some work to do. (See the comment at
// the beginning of CMTask::do_marking_step() for those conditions -
// one of which is reaching the specified time target.) It is only
// when CMTask::do_marking_step() returns without setting the
// has_aborted() flag that the marking step has completed.
do {
false /* do_termination */,
}
} else {
if (_cm->verbose_high()) {
}
}
}
};
// 'Drain' oop closure used by both serial and parallel reference processing.
// Uses the CMTask associated with a given worker thread (for serial
// reference processing the CMtask for worker 0 is used). Calls the
// do_marking_step routine, with an unbelievably large timeout value,
// to drain the marking data structures of the remaining entries
// added by the 'keep alive' oop closure above.
bool _is_serial;
public:
}
void do_void() {
do {
if (_cm->verbose_high()) {
}
// We call CMTask::do_marking_step() to completely drain the local
// and global marking stacks of entries pushed by the 'keep alive'
// oop closure (an instance of G1CMKeepAliveAndDrainClosure above).
//
// CMTask::do_marking_step() is called in a loop, which we'll exit
// if there's nothing more to do (i.e. we'completely drained the
// entries that were pushed as a a result of applying the 'keep alive'
// closure to the entries on the discovered ref lists) or we overflow
// the global marking stack.
//
// Note: CMTask::do_marking_step() can set the CMTask::has_aborted()
// flag while there may still be some work to do. (See the comment at
// the beginning of CMTask::do_marking_step() for those conditions -
// one of which is reaching the specified time target.) It is only
// when CMTask::do_marking_step() returns without setting the
// has_aborted() flag that the marking step has completed.
true /* do_termination */,
}
};
// Implementation of AbstractRefProcTaskExecutor for parallel
// reference processing at the end of G1 concurrent marking
private:
int _active_workers;
public:
int n_workers) :
// Executes the given task using concurrent marking worker threads.
};
public:
ConcurrentMark* cm) :
AbstractGangTask("Process reference objects in parallel"),
}
}
};
// We need to reset the concurrency level before each
// proxy task execution, so that the termination protocol
// and overflow handling in CMTask::do_marking_step() knows
// how many workers to wait for.
_g1h->set_par_threads(0);
}
public:
AbstractGangTask("Enqueue reference objects in parallel"),
}
};
// Not strictly necessary but...
//
// We need to reset the concurrency level before each
// proxy task execution, so that the termination protocol
// and overflow handling in CMTask::do_marking_step() knows
// how many workers to wait for.
_g1h->set_par_threads(0);
}
if (has_overflown()) {
// Skip processing the discovered references if we have
// overflown the global marking stack. Reference objects
// only get discovered once so it is OK to not
// de-populate the discovered reference lists. We could have,
// but the only benefit would be that, when marking restarts,
// less reference objects are discovered.
return;
}
// Is alive closure.
// Inner scope to exclude the cleaning of the string and symbol
// tables from the displayed time.
{
}
// See the comment in G1CollectedHeap::ref_processing_init()
// about how reference processing currently works in G1.
// Set the soft reference policy
// Instances of the 'Keep Alive' and 'Complete GC' closures used
// in serial reference processing. Note these closures are also
// used for serially processing (by the the current thread) the
// JNI references during parallel reference processing.
//
// These closures do not need to synchronize with the worker
// threads involved in parallel reference processing as these
// instances are executed serially by the current thread (e.g.
// reference processing is not multi-threaded and is thus
// performed by the current thread instead of a gang worker).
//
// The gang tasks involved in parallel reference procssing create
// their own instances of these closures, which do their own
// synchronization among themselves.
// We need at least one active thread. If reference processing
// is not multi-threaded we use the current (VMThread) thread,
// otherwise we use the work gang from the G1CollectedHeap and
// we utilize all the worker threads we can.
// Parallel processing task executor.
// Set the concurrency level. The phase was already set prior to
// executing the remark task.
// Set the degree of MT processing here. If the discovery was done MT,
// the number of threads involved during discovery could differ from
// the number of active workers. This is OK as long as the discovered
// Reference lists are balanced (see balance_all_queues() and balance_queues()).
// Process the weak references.
g1h->gc_timer_cm());
// The do_oop work routines of the keep_alive and drain_marking_stack
// oop closures will set the has_overflown flag if we overflow the
// global marking stack.
"mark stack should be empty (unless it overflowed)");
if (_markStack.overflow()) {
// This should have been done already when we tried to push an
// entry on to the global mark stack. But let's do it again.
}
}
// Now clean up stale oops in StringTable
// Clean up unreferenced symbols in symbol table.
SymbolTable::unlink();
}
}
private:
bool _is_serial;
public:
// Since all available tasks are actually started, we should
// only proceed if we're supposed to be actived.
do {
true /* do_termination */,
// If we overflow, then we do not want to restart. We instead
// want to abort remark and do concurrent marking again.
task->record_end_time();
}
}
}
};
g1h->ensure_parsability(false);
if (G1CollectedHeap::use_parallel_gc_threads()) {
// this is remark, so we'll use up all active threads
if (active_workers == 0) {
}
// Leave _parallel_marking_threads at it's
// value originally calculated in the ConcurrentMark
// constructor and pass values of the active workers
// through the gang in the task.
// We will start all available threads, even if we decide that the
// active_workers will be fewer. The extra ones will just bail out
// immediately.
g1h->set_par_threads(0);
} else {
// Note - if there's no work gang then the VMThread will be
// the thread to execute the remark - serially. We have
// to pass true for the is_serial parameter so that
// CMTask::do_marking_step() doesn't enter the sync
// barriers in the event of an overflow. Doing so will
// cause an assert that the current thread is not a
// concurrent GC thread.
remarkTask.work(0);
}
guarantee(has_overflown() ||
satb_mq_set.completed_buffers_num() == 0,
err_msg("Invariant: has_overflown = %s, num buffers = %d",
print_stats();
"Different number of objs processed and enqueued.");
}
#endif
}
#ifndef PRODUCT
private:
bool _all;
public:
bool all) :
template <class T> void do_oop_work(T* p) {
str = "";
str = " O";
} else {
if (over_tams) {
str = " >";
if (marked) {
str2 = " AND MARKED";
}
} else if (marked) {
str = " M";
} else {
str = " NOT";
}
}
}
};
private:
bool _all;
public:
bool all,
HeapRegion* hr) :
if (print_it) {
o->oop_iterate(&oopCl);
}
}
};
private:
bool _all;
public:
"TAMS: "PTR_FORMAT, b, e, t, p);
}
return false;
}
bool all) :
};
bool all) {
gclog_or_tty->cr();
if (G1PrintReachableBaseFile == NULL) {
return;
}
(JVM_MAXPATHLEN - 1)) {
return;
}
return;
}
gclog_or_tty->flush();
}
#endif // PRODUCT
// Note we are overriding the read-only view of the prev map here, via
// the cast.
}
}
}
// "checkpoint" the finger
// _heap_end will not change underneath our feet; it only changes at
// yield points.
// Note on how this code handles humongous regions. In the
// normal case the finger will reach the start of a "starts
// humongous" (SH) region. Its end will either be the end of the
// last "continues humongous" (CH) region in the sequence, or the
// standard end of the SH region (if the SH is the only region in
// the sequence). That way claim_region() will skip over the CH
// regions. However, there is a subtle race between a CM thread
// executing this method and a mutator thread doing a humongous
// object allocation. The two are not mutually exclusive as the CM
// thread does not need to hold the Heap_lock when it gets
// here. So there is a chance that claim_region() will come across
// a free region that's in the progress of becoming a SH or a CH
// region. In the former case, it will either
// a) Miss the update to the region's end, in which case it will
// visit every subsequent CH region, will find their bitmaps
// empty, and do nothing, or
// b) Will observe the update of the region's end (in which case
// it will skip the subsequent CH regions).
// If it comes across a region that suddenly becomes CH, the
// scenario will be similar to b). So, the race between
// claim_region() and a humongous object allocation might force us
// to do a bit of unnecessary work (due to some unnecessary bitmap
// iterations) but it should not introduce and correctness issues.
if (verbose_low()) {
"limit = "PTR_FORMAT,
}
// Is the gap between reading the finger and doing the CAS too long?
// we succeeded
// notice that _finger == end cannot be guaranteed here since,
// someone else might have moved the finger even further
if (verbose_low()) {
}
if (verbose_low()) {
}
return curr_region;
} else {
"the region limit should be at bottom");
if (verbose_low()) {
}
// we return NULL and the caller should try calling
// claim_region() again.
return NULL;
}
} else {
if (verbose_low()) {
"our finger = "PTR_FORMAT,
}
// read it again
}
}
return NULL;
}
#ifndef PRODUCT
enum VerifyNoCSetOopsPhase {
};
private:
int _info;
const char* phase_str() {
switch (_phase) {
case VerifyNoCSetOopsStack: return "Stack";
case VerifyNoCSetOopsQueues: return "Queue";
case VerifyNoCSetOopsSATBCompleted: return "Completed SATB Buffers";
case VerifyNoCSetOopsSATBThread: return "Thread SATB Buffers";
default: ShouldNotReachHere();
}
return NULL;
}
}
public:
}
}
// We should not come across narrow oops while scanning marking
// stacks and SATB buffers.
}
}
};
bool verify_enqueued_buffers,
bool verify_thread_buffers,
bool verify_fingers) {
return;
}
if (verify_stacks) {
// Verify entries on the global mark stack
// Verify entries on the task queues
for (int i = 0; i < (int) _max_task_num; i += 1) {
}
}
// Verify entries on the enqueued SATB buffers
if (verify_enqueued_buffers) {
}
// Verify entries on the per-thread SATB buffers
if (verify_thread_buffers) {
}
if (verify_fingers) {
// Verify the global finger
// The global finger always points to a heap region boundary. We
// use heap_region_containing_raw() to get the containing region
// given that the global finger could be pointing to a free region
// which subsequently becomes continues humongous. If that
// happens, heap_region_containing() will return the bottom of the
// corresponding starts humongous region and the check below will
// not hold any more.
}
// Verify the task fingers
for (int i = 0; i < (int) parallel_marking_threads(); i += 1) {
// See above note on the global finger verification.
!task_hr->in_collection_set(),
}
}
}
}
#endif // PRODUCT
// Aggregate the counting data that was constructed concurrently
// with marking.
public:
if (hr->continuesHumongous()) {
// We will ignore these here and process them when their
// associated "starts humongous" region is processed.
// Note that we cannot rely on their associated
// "starts humongous" region to have their bit set to 1
// since, due to the region chunking in the parallel region
// iteration, a "continues humongous" region might be visited
// before its associated "starts humongous".
return false;
}
err_msg("Preconditions not met - "
// NTAMS of this region has not been set so nothing to do.
return false;
}
// 'start' should be in the heap.
// 'end' *may* be just beyone the end of the heap (if hr is the last region)
// If ntams is not card aligned then we bump card bitmap index
// for limit so that we get the all the cards spanned by
// the object ending at ntams.
// Note: if this is the last region in the heap then ntams
// could be actually just beyond the end of the the heap;
// limit_idx will then correspond to a (non-existent) card
// that is also outside the heap.
limit_idx += 1;
}
// Aggregate the "stripe" in the count data associated with hr.
// Fetch the marked_bytes in this region for task i and
// add it to the running total for this region.
// Now union the bitmaps[0,max_task_num)[start_idx..limit_idx)
// into the global card bitmap.
// BitMap::get_next_one_offset() can handle the case when
// its left_offset parameter is greater than its right_offset
// parameter. It does, however, have an early exit if
// left_offset == right_offset. So let's limit the value
// passed in for left offset here.
}
}
// Update the marked bytes for this region.
// Next heap region
return false;
}
};
protected:
int _active_workers;
public:
int n_workers) :
AbstractGangTask("Count Aggregation"),
_active_workers(n_workers) { }
if (G1CollectedHeap::use_parallel_gc_threads()) {
} else {
}
}
};
1);
if (G1CollectedHeap::use_parallel_gc_threads()) {
"sanity check");
_g1h->set_par_threads(0);
"sanity check");
} else {
g1_par_agg_task.work(0);
}
}
// Clear the per-worker arrays used to store the per-region counting data
// Clear the global card bitmap - it will be filled during
// liveness count aggregation (during remark) and the
// final counting task.
// Clear the global region bitmap - it will be filled as part
// of the final counting task.
_region_bm.clear();
task_card_bm->clear();
}
}
if (verbose_stats()) {
for (size_t i = 0; i < _active_tasks; ++i) {
_tasks[i]->print_stats();
}
}
}
// abandon current marking iteration due to a Full GC
// Clear all marks to force marking thread to do nothing
// Clear the liveness counting data
// Empty mark stack
for (int i = 0; i < (int)_max_task_num; ++i) {
_tasks[i]->clear_region_fields();
}
_has_aborted = true;
// This can be called either during or outside marking, we'll read
// the expected_active value from the SATB queue set.
false, /* new active value */
}
}
}
{
}
(double)_cleanup_times.num()
: 0.0));
if (G1ScrubRemSets) {
(double)_cleanup_times.num()
: 0.0));
}
"(%8.2f s marking).",
cmThread()->vtime_accum(),
cmThread()->vtime_mark_accum());
}
if (use_parallel_marking_threads()) {
}
}
// We take a break if someone is trying to stop the world.
if (should_yield()) {
if (worker_id == 0) {
}
return true;
} else {
return false;
}
}
return cmThread()->should_yield();
}
}
void* last) {
return containing_card_is_marked(start) &&
}
#ifndef PRODUCT
// for debugging purposes
for (int i = 0; i < (int) _max_task_num; ++i) {
}
}
#endif
if (_cm->verbose_high()) {
}
statsOnly( ++_objs_scanned );
check_limits();
}
// Closure for iteration over bitmaps
private:
// the bitmap that is being iterated over
public:
// We move that task's local finger along.
// we only partially drain the local queue and global stack
_task->drain_local_queue(true);
_task->drain_global_stack(true);
// if the has_aborted flag has been raised, we need to bail out of
// the iteration
return !_task->has_aborted();
}
};
// Closure for iterating over objects, currently only used for
// processing SATB buffers.
private:
public:
}
};
}
}
// Separated the asserts so that we know which one fires.
"claim_region() should have filtered out continues humongous regions");
"claim_region() should have filtered out continues humongous regions");
if (_cm->verbose_low()) {
}
_curr_region = hr;
}
if (_cm->verbose_low()) {
}
// The region was collected underneath our feet.
// We set the finger to bottom to ensure that the bitmap
// iteration that will follow this will not do anything.
// (this is not a condition that holds when we set the region up,
// as the region is not supposed to be empty in the first place)
} else if (limit >= _region_limit) {
} else {
// This can happen under some pretty unusual circumstances. An
// evacuation pause empties the region underneath our feet (NTAMS
// at bottom). We then do some allocation in the region (NTAMS
// stays at bottom), followed by the region being used as a GC
// alloc region (NTAMS will move to top() and the objects
// originally below it will be grayed). All objects now marked in
// the region are explicitly grayed, if below the global finger,
// and we do not need in fact to scan anything else. So, we simply
// set _finger to be limit to ensure that the bitmap iteration
// doesn't do anything.
}
}
void CMTask::giveup_current_region() {
}
}
// Values for these three fields that indicate that we're not
// holding on to a region.
_curr_region = NULL;
}
if (cm_oop_closure == NULL) {
} else {
}
}
if (_cm->verbose_low()) {
}
_calls = 0;
_elapsed_time_ms = 0.0;
_termination_time_ms = 0.0;
_termination_start_time_ms = 0.0;
#if _MARKING_STATS_
_local_pushes = 0;
_local_pops = 0;
_local_max_size = 0;
_objs_scanned = 0;
_global_pushes = 0;
_global_pops = 0;
_global_max_size = 0;
_global_transfers_to = 0;
_regions_claimed = 0;
_steal_attempts = 0;
_steals = 0;
_aborted = 0;
_aborted_overflow = 0;
_aborted_cm_aborted = 0;
_aborted_yield = 0;
_aborted_timed_out = 0;
_aborted_satb = 0;
_aborted_termination = 0;
#endif // _MARKING_STATS_
}
// This is called when we are in the termination protocol. We should
// quit if, for some reason, this task wants to abort or the global
// stack is not empty (this means that we can get work from it).
}
"shouldn't have been called otherwise");
}
if (has_aborted()) return;
// First, we need to recalculate the words scanned and refs reached
// limits for the next clock call.
// During the regular clock call we do the following
// (1) If an overflow has been flagged, then we abort.
if (_cm->has_overflown()) {
return;
}
// If we are not concurrent (i.e. we're doing remark) we don't need
// to check anything else. The other steps are only needed during
// the concurrent marking phase.
if (!concurrent()) return;
// (2) If marking has been aborted for Full GC, then we also abort.
if (_cm->has_aborted()) {
statsOnly( ++_aborted_cm_aborted );
return;
}
// (3) If marking stats are enabled, then we update the step history.
#if _MARKING_STATS_
if (_words_scanned >= _words_scanned_limit) {
}
if (_refs_reached >= _refs_reached_limit) {
}
if (_cm->verbose_medium()) {
"scanned = %d%s, refs reached = %d%s",
}
#endif // _MARKING_STATS_
// (4) We check whether we should yield. If we have to, then we abort.
if (_cm->should_yield()) {
// We should yield. To do this we abort the task. The caller is
// responsible for yielding.
statsOnly( ++_aborted_yield );
return;
}
// (5) We check whether we've reached our time quota. If we have,
// then we abort.
if (elapsed_time_ms > _time_target_ms) {
_has_timed_out = true;
statsOnly( ++_aborted_timed_out );
return;
}
// (6) Finally, we check whether there are enough completed STAB
// buffers available for processing. If there are, we abort.
if (_cm->verbose_low()) {
_task_id);
}
// we do need to process SATB buffers, we'll abort and restart
// the marking task to do so
statsOnly( ++_aborted_satb );
return;
}
}
}
// This is called when we believe that we're going to do an infrequent
// operation which will increase the per byte scanned cost (i.e. move
// scanning limit so that the clock is called earlier.
if (_cm->verbose_medium()) {
}
}
// local array where we'll store the entries that will be popped
// from the local queue
int n = 0;
++n;
}
if (n > 0) {
// we popped at least one entry from the local queue
if (_cm->verbose_low()) {
_task_id);
}
} else {
// the transfer was successful
if (_cm->verbose_medium()) {
_task_id, n);
}
if (tmp_size > _global_max_size) {
}
_global_pushes += n );
}
}
// this operation was quite expensive, so decrease the limits
}
// local array where we'll store the entries that will be popped
// from the global stack.
int n;
"we should not pop more than the given limit");
if (n > 0) {
// yes, we did actually pop at least one entry
if (_cm->verbose_medium()) {
_task_id, n);
}
for (int i = 0; i < n; ++i) {
// We only call this when the local queue is empty or under a
// given target limit. So, we do not expect this push to fail.
}
if (tmp_size > _local_max_size) {
}
_local_pushes += n );
}
// this operation was quite expensive, so decrease the limits
}
if (has_aborted()) return;
// Decide what the target size is, depending whether we're going to
// drain it partially (so that other tasks can steal if they run out
// of things to do) or totally (at the very end).
if (partially) {
} else {
target_size = 0;
}
if (_cm->verbose_high()) {
}
while (ret) {
statsOnly( ++_local_pops );
if (_cm->verbose_high()) {
(void*) obj);
}
ret = false;
} else {
}
}
if (_cm->verbose_high()) {
}
}
}
if (has_aborted()) return;
// We have a policy to drain the local queue before we attempt to
// drain the global stack.
// Decide what the target size is, depending whether we're going to
// drain it partially (so that other tasks can steal if they run out
// of things to do) or totally (at the very end). Notice that,
// because we move entries from the global stack in chunks or
// because another task might be doing the same, we might in fact
// drop below the target. But, this is not a problem.
if (partially) {
} else {
target_size = 0;
}
if (_cm->verbose_low()) {
}
}
if (_cm->verbose_low()) {
}
}
}
// SATB Queue has several assumptions on whether to call the par or
// non-par versions of the methods. this is why some of the code is
// replicated. We should really get rid of the single-threaded version
// of the code to simplify things.
if (has_aborted()) return;
// We set this so that the regular clock knows that we're in the
// middle of draining buffers and doesn't set the abort flag when it
// notices that SATB buffers are available for draining. It'd be
// very counter productive if it did that. :-)
_draining_satb_buffers = true;
CMObjectClosure oc(this);
if (G1CollectedHeap::use_parallel_gc_threads()) {
} else {
}
// This keeps claiming and applying the closure to completed buffers
// until we run out of buffers or we need to abort.
if (G1CollectedHeap::use_parallel_gc_threads()) {
while (!has_aborted() &&
if (_cm->verbose_medium()) {
}
}
} else {
while (!has_aborted() &&
if (_cm->verbose_medium()) {
}
}
}
if (!concurrent() && !has_aborted()) {
// We should only do this during remark.
if (G1CollectedHeap::use_parallel_gc_threads()) {
} else {
}
}
_draining_satb_buffers = false;
assert(has_aborted() ||
concurrent() ||
if (G1CollectedHeap::use_parallel_gc_threads()) {
} else {
}
// again, this was a potentially expensive operation, decrease the
// limits to get the regular clock call early
}
_step_times_ms.sd());
#if _MARKING_STATS_
#endif // _MARKING_STATS_
}
/*****************************************************************************
The do_marking_step(time_target_ms, ...) method is the building
block of the parallel marking framework. It can be called in parallel
with other invocations of do_marking_step() on different tasks
(but only one per task, obviously) and concurrently with the
mutator threads, or during remark, hence it eliminates the need
for two versions of the code. When called during remark, it will
pick up from where the task left off during the concurrent marking
phase. Interestingly, tasks are also claimable during evacuation
pauses too, since do_marking_step() ensures that it aborts before
it needs to yield.
The data structures that it uses to do marking work are the
following:
(1) Marking Bitmap. If there are gray objects that appear only
on the bitmap (this happens either when dealing with an overflow
or when the initial marking phase has simply marked the roots
and didn't push them on the stack), then tasks claim heap
regions whose bitmap they then scan to find gray objects. A
global finger indicates where the end of the last claimed region
is. A local finger indicates how far into the region a task has
scanned. The two fingers are used to determine how to gray an
object (i.e. whether simply marking it is OK, as it will be
visited by a task in the future, or whether it needs to be also
pushed on a stack).
(2) Local Queue. The local queue of the task which is accessed
reasonably efficiently by the task. Other tasks can steal from
it when they run out of work. Throughout the marking phase, a
task attempts to keep its local queue short but not totally
empty, so that entries are available for stealing by other
tasks. Only when there is no more work, a task will totally
drain its local queue.
(3) Global Mark Stack. This handles local queue overflow. During
marking only sets of entries are moved between it and the local
queues, as access to it requires a mutex and more fine-grain
interaction with it which might cause contention. If it
overflows, then the marking phase should restart and iterate
over the bitmap to identify gray objects. Throughout the marking
phase, tasks attempt to keep the global mark stack at a small
length but not totally empty, so that entries are available for
popping by other tasks. Only when there is no more work, tasks
will totally drain the global mark stack.
(4) SATB Buffer Queue. This is where completed SATB buffers are
made available. Buffers are regularly removed from this queue
and scanned for roots, so that the queue doesn't get too
long. During remark, all completed buffers are processed, as
well as the filled in parts of any uncompleted buffers.
The do_marking_step() method tries to abort when the time target
has been reached. There are a few other cases when the
do_marking_step() method also aborts:
(1) When the marking phase has been aborted (after a Full GC).
(2) When a global overflow (on the global stack) has been
triggered. Before the task aborts, it will actually sync up with
the other tasks to ensure that all the marking data structures
(local queues, stacks, fingers etc.) are re-initialized so that
when do_marking_step() completes, the marking phase can
immediately restart.
(3) When enough completed SATB buffers are available. The
do_marking_step() method only tries to drain SATB buffers right
at the beginning. So, if enough buffers are available, the
marking step aborts and the SATB buffers are processed at
the beginning of the next invocation.
(4) To yield. when we have to yield then we abort and yield
right at the end of do_marking_step(). This saves us from a lot
of hassle as, by yielding we might allow a Full GC. If this
happens then objects will be compacted underneath our feet, the
heap might shrink, etc. We save checking for this by just
aborting and doing the yield right at the end.
From the above it follows that the do_marking_step() method should
be called in a loop (or, otherwise, regularly) until it completes.
If a marking step completes without its has_aborted() flag being
true, it means it has completed the current marking phase (and
also all other marking tasks have done so and have all synced up).
A method called regular_clock_call() is invoked "regularly" (in
sub ms intervals) throughout marking. It is this clock method that
checks all the abort conditions which were mentioned above and
decides when the task should abort. A work-based scheme is used to
trigger this clock method: when the number of object words the
marking phase has scanned or the number of references the marking
phase has visited reach a given limit. Additional invocations to
the method clock have been planted in a few other strategic places
too. The initial reason for the clock method was to avoid calling
vtime too regularly, as it is quite expensive. So, once it was in
place, it was natural to piggy-back all the other conditions on it
too and not constantly check them throughout the code.
If do_termination is true then do_marking_step will enter its
termination protocol.
The value of is_serial must be true when do_marking_step is being
called serially (i.e. by the VMThread) and do_marking_step should
skip any synchronization in the termination and overflow code.
Examples include the serial remark code and the serial reference
processing closures.
The value of is_serial must be false when do_marking_step is
being called by any of the worker threads in a work gang.
Examples include the concurrent marking code (CMMarkingTask),
the MT remark code, and the MT reference processing closures.
*****************************************************************************/
bool do_termination,
bool is_serial) {
"only one thread should claim this task at any one time");
// OK, this doesn't safeguard again all possible scenarios, as it is
// possible for two threads to set the _claimed flag at the same
// time. But it is only for debugging purposes anyway and it will
// catch most problems.
_claimed = true;
// If do_stealing is true then do_marking_step will attempt to
// steal work from the other CMTasks. It only makes sense to
// enable stealing when the termination protocol is enabled
// and do_marking_step() is not being called serially.
double diff_prediction_ms =
// set up the variables that are used in the work-based scheme to
// call the regular clock method
_words_scanned = 0;
_refs_reached = 0;
// clear all flags
_has_timed_out = false;
_draining_satb_buffers = false;
++_calls;
if (_cm->verbose_low()) {
"target = %1.2lfms >>>>>>>>>>",
}
// Set up the bitmap and oop closures. Anything that uses them is
// eventually called from this method, so it is OK to allocate these
// statically.
if (_cm->has_overflown()) {
// This can happen if the mark stack overflows during a GC pause
// and this task, after a yield point, restarts. We have to abort
// as we need to get into the overflow protocol which happens
// right at the end of this task.
}
// First drain any available SATB buffers. After this, we will not
// look at SATB buffers before the next invocation of this method.
// If enough completed SATB buffers are queued up, the regular clock
// will abort this task so that it restarts.
// ...then partially drain the local queue and the global stack
drain_local_queue(true);
drain_global_stack(true);
do {
// This means that we're already holding on to a region.
"should not be NULL either");
// We might have restarted this task after an evacuation pause
// which might have evacuated the region we're holding on to
// underneath our feet. Let's read its limit again to make sure
// that we do not iterate over a region of the heap that
// contains garbage (update_region_limit() will also move
// _finger to the start of the region if it is found empty).
// We will start from _finger not from the start of the region,
// as we might be restarting this task after aborting half-way
// through scanning this region. In this case, _finger points to
// the address where we last found a marked object. If this is a
// fresh region, _finger points to start().
if (_cm->verbose_low()) {
"of region "PTR_FORMAT,
}
// Let's iterate over the bitmap of the part of the
// region that is left.
// We successfully completed iterating over the region. Now,
// let's give up the region.
} else {
// The only way to abort the bitmap iteration is to return
// false from the do_bit() method. However, inside the
// do_bit() method we move the _finger to point to the
// object currently being looked at. So, if we bail out, we
// have definitely set _finger to something non-null.
// Region iteration was actually aborted. So now _finger
// points to the address of the object we last scanned. If we
// leave it there, when we restart this task, we will rescan
// the object. It is easy to avoid this. We move the finger by
// enough to point to the next possible object header (the
// bitmap knows by how much we need to move it as it knows its
// granularity).
// Check if bitmap iteration was aborted while scanning the last object
if (new_finger >= _region_limit) {
} else {
}
}
}
// At this point we have either completed iterating over the
// region we were holding on to, or we have aborted.
// We then partially drain the local queue and the global stack.
// (Do we really need this?)
drain_local_queue(true);
drain_global_stack(true);
// Read the note on the claim_region() method on why it might
// return NULL with potentially more regions available for
// claiming and why we have to check out_of_regions() to determine
// whether we're done or not.
// We are going to try to claim a new region. We should have
// given up on the previous one.
// Separated the asserts so that we know which one fires.
if (_cm->verbose_low()) {
}
if (claimed_region != NULL) {
// Yes, we managed to claim one
statsOnly( ++_regions_claimed );
if (_cm->verbose_low()) {
"region "PTR_FORMAT,
}
}
// It is important to call the regular clock here. It might take
// a while to claim a region if, for example, we hit a large
// block of empty regions. So we need to call the regular clock
// method once round the loop to make sure it's called
// frequently enough.
}
"at this point we should be out of regions");
}
if (!has_aborted()) {
// We cannot check whether the global stack is empty, since other
// tasks might be pushing objects to it concurrently.
"at this point we should be out of regions");
if (_cm->verbose_low()) {
}
// Try to reduce the number of available SATB buffers so that
// remark has less work to do.
}
// Since we've done everything else, we can now totally drain the
// local queue and global stack.
drain_local_queue(false);
drain_global_stack(false);
// Attempt at work stealing from other task's queues.
if (do_stealing && !has_aborted()) {
// We have not aborted. This means that we have finished all that
// we could. Let's try to do some stealing...
// We cannot check whether the global stack is empty, since other
// tasks might be pushing objects to it concurrently.
"only way to reach here");
if (_cm->verbose_low()) {
}
while (!has_aborted()) {
statsOnly( ++_steal_attempts );
if (_cm->verbose_medium()) {
}
"any stolen object should be marked");
// And since we're towards the end, let's totally drain the
// local queue and global stack.
drain_local_queue(false);
drain_global_stack(false);
} else {
break;
}
}
}
// If we are about to wrap up and go into termination, check if we
// should raise the overflow flag.
if (do_termination && !has_aborted()) {
_cm->set_has_overflown();
}
}
// We still haven't aborted. Now, let's try to get into the
// termination protocol.
if (do_termination && !has_aborted()) {
// We cannot check whether the global stack is empty, since other
// tasks might be concurrently pushing objects on it.
// Separated the asserts so that we know which one fires.
if (_cm->verbose_low()) {
}
// The CMTask class also extends the TerminatorTerminator class,
// hence its should_exit_termination() method will also decide
// whether to exit the termination protocol or not.
if (finished) {
// We're all done.
if (_task_id == 0) {
// let's allow task 0 to do this
if (concurrent()) {
// we need to set this to false before the next
// safepoint. This way we ensure that the marking phase
// doesn't observe any more heap expansions.
}
}
// We can now guarantee that the global stack is empty, since
// all other tasks have finished. We separated the guarantees so
// that, if a condition is false, we can immediately find out
// which one.
if (_cm->verbose_low()) {
}
} else {
// Apparently there's more work to do. Let's abort this task. It
// will restart it and we can hopefully find more things to do.
if (_cm->verbose_low()) {
_task_id);
}
}
}
// Mainly for debugging purposes to make sure that a pointer to the
// closure which was statically allocated in this frame doesn't
// escape it by accident.
// Update the step history.
if (has_aborted()) {
// The task was aborted for some reason.
if (_has_timed_out) {
// Keep statistics of how well we did with respect to hitting
// our target only if we actually timed out (if we aborted for
// other reasons, then the results might get skewed).
}
if (_cm->has_overflown()) {
// This is the interesting one. We aborted because a global
// overflow was raised. This means we have to restart the
// marking phase and start iterating over regions. However, in
// order to do this we have to make sure that all tasks stop
// what they are doing and re-initialise in a safe manner. We
// will achieve this with the use of two barrier sync points.
if (_cm->verbose_low()) {
}
if (!is_serial) {
// We only need to enter the sync barrier if being called
// from a parallel context
// When we exit this sync barrier we know that all tasks have
// stopped doing marking work. So, it's now safe to
// re-initialise our data structures. At the end of this method,
// task 0 will clear the global data structures.
}
statsOnly( ++_aborted_overflow );
// We clear the local state of this task...
if (!is_serial) {
// ...and enter the second barrier.
}
// At this point, if we're during the concurrent phase of
// marking, everything has been re-initialized and we're
// ready to restart.
}
if (_cm->verbose_low()) {
"elapsed = %1.2lfms <<<<<<<<<<",
if (_cm->has_aborted()) {
_task_id);
}
}
} else {
if (_cm->verbose_low()) {
"elapsed = %1.2lfms <<<<<<<<<<",
}
}
_claimed = false;
}
_claimed(false),
_clock_due_to_marking = 0 );
}
// These are formatting macros that are used below to ensure
// consistent formatting. The *_H_* versions are used to format the
// header for a particular value and they should be kept consistent
// with the corresponding macro. Also note that most of the macros add
// the necessary white space (as a prefix) which makes them a bit
// easier to compose.
// All the output lines are prefixed with this string to be able to
// identify them easily in a large log file.
#ifdef _LP64
#else // _LP64
#endif // _LP64
// For per-region info
// For summary info
_hum_used_bytes(0), _hum_capacity_bytes(0),
_hum_prev_live_bytes(0), _hum_next_live_bytes(0) {
// Print the header of the output.
G1PPRL_SUM_ADDR_FORMAT("committed")
G1PPRL_SUM_ADDR_FORMAT("reserved")
G1PPRL_SUM_BYTE_FORMAT("region-size"),
"type", "address-range",
"used", "prev-live", "next-live", "gc-eff");
"", "",
}
// It takes as a parameter a reference to one of the _hum_* fields, it
// deduces the corresponding value for a region in a humongous region
// series (either the region size, or what's left if the _hum_* field
// is < the region size), and updates the _hum_* field accordingly.
// The > 0 check is to deal with the prev and next live bytes which
// could be 0.
if (*hum_bytes > 0) {
}
return bytes;
}
// It deduces the values for a region in a humongous region series
// from the _hum_* fields and updates those accordingly. It assumes
// that that _hum_* fields have already been set up from the "starts
// humongous" region and we visit the regions in address order.
}
if (r->used() == 0) {
type = "FREE";
} else if (r->is_survivor()) {
type = "SURV";
} else if (r->is_young()) {
type = "EDEN";
} else if (r->startsHumongous()) {
type = "HUMS";
_hum_prev_live_bytes == 0 && _hum_next_live_bytes == 0,
"they should have been zeroed after the last time we used them");
// Set up the _hum_* fields.
} else if (r->continuesHumongous()) {
type = "HUMC";
} else {
type = "OLD";
}
// Print a line for this particular region.
return false;
}
// Print the footer of the output.
" SUMMARY"
G1PPRL_SUM_MB_FORMAT("capacity")
G1PPRL_SUM_MB_PERC_FORMAT("used")
G1PPRL_SUM_MB_PERC_FORMAT("prev-live")
G1PPRL_SUM_MB_PERC_FORMAT("next-live"),
}