Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp
38920 views
/*1* Copyright (c) 2001, 2020, 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 "gc_implementation/g1/concurrentG1Refine.hpp"26#include "gc_implementation/g1/concurrentMark.hpp"27#include "gc_implementation/g1/concurrentMarkThread.inline.hpp"28#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"29#include "gc_implementation/g1/g1CollectorPolicy.hpp"30#include "gc_implementation/g1/g1ErgoVerbose.hpp"31#include "gc_implementation/g1/g1GCPhaseTimes.hpp"32#include "gc_implementation/g1/g1Log.hpp"33#include "gc_implementation/g1/heapRegionRemSet.hpp"34#include "gc_implementation/shared/gcPolicyCounters.hpp"35#include "runtime/arguments.hpp"36#include "runtime/java.hpp"37#include "runtime/mutexLocker.hpp"38#include "utilities/debug.hpp"3940// Different defaults for different number of GC threads41// They were chosen by running GCOld and SPECjbb on debris with different42// numbers of GC threads and choosing them based on the results4344// all the same45static double rs_length_diff_defaults[] = {460.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.047};4849static double cost_per_card_ms_defaults[] = {500.01, 0.005, 0.005, 0.003, 0.003, 0.002, 0.002, 0.001551};5253// all the same54static double young_cards_per_entry_ratio_defaults[] = {551.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.056};5758static double cost_per_entry_ms_defaults[] = {590.015, 0.01, 0.01, 0.008, 0.008, 0.0055, 0.0055, 0.00560};6162static double cost_per_byte_ms_defaults[] = {630.00006, 0.00003, 0.00003, 0.000015, 0.000015, 0.00001, 0.00001, 0.00000964};6566// these should be pretty consistent67static double constant_other_time_ms_defaults[] = {685.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.069};707172static double young_other_cost_per_region_ms_defaults[] = {730.3, 0.2, 0.2, 0.15, 0.15, 0.12, 0.12, 0.174};7576static double non_young_other_cost_per_region_ms_defaults[] = {771.0, 0.7, 0.7, 0.5, 0.5, 0.42, 0.42, 0.3078};7980G1CollectorPolicy::G1CollectorPolicy() :81_parallel_gc_threads(G1CollectedHeap::use_parallel_gc_threads()82? ParallelGCThreads : 1),8384_recent_gc_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),85_stop_world_start(0.0),8687_concurrent_mark_remark_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),88_concurrent_mark_cleanup_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),8990_alloc_rate_ms_seq(new TruncatedSeq(TruncatedSeqLength)),91_prev_collection_pause_end_ms(0.0),92_rs_length_diff_seq(new TruncatedSeq(TruncatedSeqLength)),93_cost_per_card_ms_seq(new TruncatedSeq(TruncatedSeqLength)),94_young_cards_per_entry_ratio_seq(new TruncatedSeq(TruncatedSeqLength)),95_mixed_cards_per_entry_ratio_seq(new TruncatedSeq(TruncatedSeqLength)),96_cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),97_mixed_cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),98_cost_per_byte_ms_seq(new TruncatedSeq(TruncatedSeqLength)),99_cost_per_byte_ms_during_cm_seq(new TruncatedSeq(TruncatedSeqLength)),100_constant_other_time_ms_seq(new TruncatedSeq(TruncatedSeqLength)),101_young_other_cost_per_region_ms_seq(new TruncatedSeq(TruncatedSeqLength)),102_non_young_other_cost_per_region_ms_seq(103new TruncatedSeq(TruncatedSeqLength)),104105_pending_cards_seq(new TruncatedSeq(TruncatedSeqLength)),106_rs_lengths_seq(new TruncatedSeq(TruncatedSeqLength)),107108_pause_time_target_ms((double) MaxGCPauseMillis),109110_gcs_are_young(true),111112_during_marking(false),113_in_marking_window(false),114_in_marking_window_im(false),115116_recent_prev_end_times_for_all_gcs_sec(117new TruncatedSeq(NumPrevPausesForHeuristics)),118119_recent_avg_pause_time_ratio(0.0),120121_initiate_conc_mark_if_possible(false),122_during_initial_mark_pause(false),123_last_young_gc(false),124_last_gc_was_young(false),125126_eden_used_bytes_before_gc(0),127_survivor_used_bytes_before_gc(0),128_heap_used_bytes_before_gc(0),129_metaspace_used_bytes_before_gc(0),130_eden_capacity_bytes_before_gc(0),131_heap_capacity_bytes_before_gc(0),132133_eden_cset_region_length(0),134_survivor_cset_region_length(0),135_old_cset_region_length(0),136137_collection_set(NULL),138_collection_set_bytes_used_before(0),139140// Incremental CSet attributes141_inc_cset_build_state(Inactive),142_inc_cset_head(NULL),143_inc_cset_tail(NULL),144_inc_cset_bytes_used_before(0),145_inc_cset_max_finger(NULL),146_inc_cset_recorded_rs_lengths(0),147_inc_cset_recorded_rs_lengths_diffs(0),148_inc_cset_predicted_elapsed_time_ms(0.0),149_inc_cset_predicted_elapsed_time_ms_diffs(0.0),150151#ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away152#pragma warning( disable:4355 ) // 'this' : used in base member initializer list153#endif // _MSC_VER154155_short_lived_surv_rate_group(new SurvRateGroup(this, "Short Lived",156G1YoungSurvRateNumRegionsSummary)),157_survivor_surv_rate_group(new SurvRateGroup(this, "Survivor",158G1YoungSurvRateNumRegionsSummary)),159// add here any more surv rate groups160_recorded_survivor_regions(0),161_recorded_survivor_head(NULL),162_recorded_survivor_tail(NULL),163_survivors_age_table(true),164165_gc_overhead_perc(0.0) {166167// Set up the region size and associated fields. Given that the168// policy is created before the heap, we have to set this up here,169// so it's done as soon as possible.170171// It would have been natural to pass initial_heap_byte_size() and172// max_heap_byte_size() to setup_heap_region_size() but those have173// not been set up at this point since they should be aligned with174// the region size. So, there is a circular dependency here. We base175// the region size on the heap size, but the heap size should be176// aligned with the region size. To get around this we use the177// unaligned values for the heap.178HeapRegion::setup_heap_region_size(InitialHeapSize, MaxHeapSize);179HeapRegionRemSet::setup_remset_size();180181G1ErgoVerbose::initialize();182if (PrintAdaptiveSizePolicy) {183// Currently, we only use a single switch for all the heuristics.184G1ErgoVerbose::set_enabled(true);185// Given that we don't currently have a verboseness level186// parameter, we'll hardcode this to high. This can be easily187// changed in the future.188G1ErgoVerbose::set_level(ErgoHigh);189} else {190G1ErgoVerbose::set_enabled(false);191}192193// Verify PLAB sizes194const size_t region_size = HeapRegion::GrainWords;195if (YoungPLABSize > region_size || OldPLABSize > region_size) {196char buffer[128];197jio_snprintf(buffer, sizeof(buffer), "%sPLABSize should be at most " SIZE_FORMAT,198OldPLABSize > region_size ? "Old" : "Young", region_size);199vm_exit_during_initialization(buffer);200}201202_recent_prev_end_times_for_all_gcs_sec->add(os::elapsedTime());203_prev_collection_pause_end_ms = os::elapsedTime() * 1000.0;204205_phase_times = new G1GCPhaseTimes(_parallel_gc_threads);206207int index = MIN2(_parallel_gc_threads - 1, 7);208209_rs_length_diff_seq->add(rs_length_diff_defaults[index]);210_cost_per_card_ms_seq->add(cost_per_card_ms_defaults[index]);211_young_cards_per_entry_ratio_seq->add(212young_cards_per_entry_ratio_defaults[index]);213_cost_per_entry_ms_seq->add(cost_per_entry_ms_defaults[index]);214_cost_per_byte_ms_seq->add(cost_per_byte_ms_defaults[index]);215_constant_other_time_ms_seq->add(constant_other_time_ms_defaults[index]);216_young_other_cost_per_region_ms_seq->add(217young_other_cost_per_region_ms_defaults[index]);218_non_young_other_cost_per_region_ms_seq->add(219non_young_other_cost_per_region_ms_defaults[index]);220221// Below, we might need to calculate the pause time target based on222// the pause interval. When we do so we are going to give G1 maximum223// flexibility and allow it to do pauses when it needs to. So, we'll224// arrange that the pause interval to be pause time target + 1 to225// ensure that a) the pause time target is maximized with respect to226// the pause interval and b) we maintain the invariant that pause227// time target < pause interval. If the user does not want this228// maximum flexibility, they will have to set the pause interval229// explicitly.230231// First make sure that, if either parameter is set, its value is232// reasonable.233if (!FLAG_IS_DEFAULT(MaxGCPauseMillis)) {234if (MaxGCPauseMillis < 1) {235vm_exit_during_initialization("MaxGCPauseMillis should be "236"greater than 0");237}238}239if (!FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {240if (GCPauseIntervalMillis < 1) {241vm_exit_during_initialization("GCPauseIntervalMillis should be "242"greater than 0");243}244}245246// Then, if the pause time target parameter was not set, set it to247// the default value.248if (FLAG_IS_DEFAULT(MaxGCPauseMillis)) {249if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {250// The default pause time target in G1 is 200ms251FLAG_SET_DEFAULT(MaxGCPauseMillis, 200);252} else {253// We do not allow the pause interval to be set without the254// pause time target255vm_exit_during_initialization("GCPauseIntervalMillis cannot be set "256"without setting MaxGCPauseMillis");257}258}259260// Then, if the interval parameter was not set, set it according to261// the pause time target (this will also deal with the case when the262// pause time target is the default value).263if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {264FLAG_SET_DEFAULT(GCPauseIntervalMillis, MaxGCPauseMillis + 1);265}266267// Finally, make sure that the two parameters are consistent.268if (MaxGCPauseMillis >= GCPauseIntervalMillis) {269char buffer[256];270jio_snprintf(buffer, 256,271"MaxGCPauseMillis (%u) should be less than "272"GCPauseIntervalMillis (%u)",273MaxGCPauseMillis, GCPauseIntervalMillis);274vm_exit_during_initialization(buffer);275}276277double max_gc_time = (double) MaxGCPauseMillis / 1000.0;278double time_slice = (double) GCPauseIntervalMillis / 1000.0;279_mmu_tracker = new G1MMUTrackerQueue(time_slice, max_gc_time);280281uintx confidence_perc = G1ConfidencePercent;282// Put an artificial ceiling on this so that it's not set to a silly value.283if (confidence_perc > 100) {284confidence_perc = 100;285warning("G1ConfidencePercent is set to a value that is too large, "286"it's been updated to " UINTX_FORMAT, confidence_perc);287}288_sigma = (double) confidence_perc / 100.0;289290// start conservatively (around 50ms is about right)291_concurrent_mark_remark_times_ms->add(0.05);292_concurrent_mark_cleanup_times_ms->add(0.20);293_tenuring_threshold = MaxTenuringThreshold;294// _max_survivor_regions will be calculated by295// update_young_list_target_length() during initialization.296_max_survivor_regions = 0;297298assert(GCTimeRatio > 0,299"we should have set it to a default value set_g1_gc_flags() "300"if a user set it to 0");301_gc_overhead_perc = 100.0 * (1.0 / (1.0 + GCTimeRatio));302303uintx reserve_perc = G1ReservePercent;304// Put an artificial ceiling on this so that it's not set to a silly value.305if (reserve_perc > 50) {306reserve_perc = 50;307warning("G1ReservePercent is set to a value that is too large, "308"it's been updated to " UINTX_FORMAT, reserve_perc);309}310_reserve_factor = (double) reserve_perc / 100.0;311// This will be set when the heap is expanded312// for the first time during initialization.313_reserve_regions = 0;314315_collectionSetChooser = new CollectionSetChooser();316}317318void G1CollectorPolicy::initialize_alignments() {319_space_alignment = HeapRegion::GrainBytes;320size_t card_table_alignment = GenRemSet::max_alignment_constraint(GenRemSet::CardTable);321size_t page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();322_heap_alignment = MAX3(card_table_alignment, _space_alignment, page_size);323}324325void G1CollectorPolicy::initialize_flags() {326if (G1HeapRegionSize != HeapRegion::GrainBytes) {327FLAG_SET_ERGO(uintx, G1HeapRegionSize, HeapRegion::GrainBytes);328}329330if (SurvivorRatio < 1) {331vm_exit_during_initialization("Invalid survivor ratio specified");332}333CollectorPolicy::initialize_flags();334_young_gen_sizer = new G1YoungGenSizer(); // Must be after call to initialize_flags335}336337void G1CollectorPolicy::post_heap_initialize() {338uintx max_regions = G1CollectedHeap::heap()->max_regions();339size_t max_young_size = (size_t)_young_gen_sizer->max_young_length(max_regions) * HeapRegion::GrainBytes;340if (max_young_size != MaxNewSize) {341FLAG_SET_ERGO(uintx, MaxNewSize, max_young_size);342}343}344345G1YoungGenSizer::G1YoungGenSizer() : _sizer_kind(SizerDefaults), _adaptive_size(true),346_min_desired_young_length(0), _max_desired_young_length(0) {347if (FLAG_IS_CMDLINE(NewRatio)) {348if (FLAG_IS_CMDLINE(NewSize) || FLAG_IS_CMDLINE(MaxNewSize)) {349warning("-XX:NewSize and -XX:MaxNewSize override -XX:NewRatio");350} else {351_sizer_kind = SizerNewRatio;352_adaptive_size = false;353return;354}355}356357if (NewSize > MaxNewSize) {358if (FLAG_IS_CMDLINE(MaxNewSize)) {359warning("NewSize (" SIZE_FORMAT "k) is greater than the MaxNewSize (" SIZE_FORMAT "k). "360"A new max generation size of " SIZE_FORMAT "k will be used.",361NewSize/K, MaxNewSize/K, NewSize/K);362}363MaxNewSize = NewSize;364}365366if (FLAG_IS_CMDLINE(NewSize)) {367_min_desired_young_length = MAX2((uint) (NewSize / HeapRegion::GrainBytes),3681U);369if (FLAG_IS_CMDLINE(MaxNewSize)) {370_max_desired_young_length =371MAX2((uint) (MaxNewSize / HeapRegion::GrainBytes),3721U);373_sizer_kind = SizerMaxAndNewSize;374_adaptive_size = _min_desired_young_length != _max_desired_young_length;375} else {376_sizer_kind = SizerNewSizeOnly;377}378} else if (FLAG_IS_CMDLINE(MaxNewSize)) {379_max_desired_young_length =380MAX2((uint) (MaxNewSize / HeapRegion::GrainBytes),3811U);382_sizer_kind = SizerMaxNewSizeOnly;383}384}385386uint G1YoungGenSizer::calculate_default_min_length(uint new_number_of_heap_regions) {387uint default_value = (new_number_of_heap_regions * G1NewSizePercent) / 100;388return MAX2(1U, default_value);389}390391uint G1YoungGenSizer::calculate_default_max_length(uint new_number_of_heap_regions) {392uint default_value = (new_number_of_heap_regions * G1MaxNewSizePercent) / 100;393return MAX2(1U, default_value);394}395396void G1YoungGenSizer::recalculate_min_max_young_length(uint number_of_heap_regions, uint* min_young_length, uint* max_young_length) {397assert(number_of_heap_regions > 0, "Heap must be initialized");398399switch (_sizer_kind) {400case SizerDefaults:401*min_young_length = calculate_default_min_length(number_of_heap_regions);402*max_young_length = calculate_default_max_length(number_of_heap_regions);403break;404case SizerNewSizeOnly:405*max_young_length = calculate_default_max_length(number_of_heap_regions);406*max_young_length = MAX2(*min_young_length, *max_young_length);407break;408case SizerMaxNewSizeOnly:409*min_young_length = calculate_default_min_length(number_of_heap_regions);410*min_young_length = MIN2(*min_young_length, *max_young_length);411break;412case SizerMaxAndNewSize:413// Do nothing. Values set on the command line, don't update them at runtime.414break;415case SizerNewRatio:416*min_young_length = number_of_heap_regions / (NewRatio + 1);417*max_young_length = *min_young_length;418break;419default:420ShouldNotReachHere();421}422423assert(*min_young_length <= *max_young_length, "Invalid min/max young gen size values");424}425426uint G1YoungGenSizer::max_young_length(uint number_of_heap_regions) {427// We need to pass the desired values because recalculation may not update these428// values in some cases.429uint temp = _min_desired_young_length;430uint result = _max_desired_young_length;431recalculate_min_max_young_length(number_of_heap_regions, &temp, &result);432return result;433}434435void G1YoungGenSizer::heap_size_changed(uint new_number_of_heap_regions) {436recalculate_min_max_young_length(new_number_of_heap_regions, &_min_desired_young_length,437&_max_desired_young_length);438}439440void G1CollectorPolicy::init() {441// Set aside an initial future to_space.442_g1 = G1CollectedHeap::heap();443444assert(Heap_lock->owned_by_self(), "Locking discipline.");445446initialize_gc_policy_counters();447448if (adaptive_young_list_length()) {449_young_list_fixed_length = 0;450} else {451_young_list_fixed_length = _young_gen_sizer->min_desired_young_length();452}453_free_regions_at_end_of_collection = _g1->num_free_regions();454update_young_list_target_length();455456// We may immediately start allocating regions and placing them on the457// collection set list. Initialize the per-collection set info458start_incremental_cset_building();459}460461// Create the jstat counters for the policy.462void G1CollectorPolicy::initialize_gc_policy_counters() {463_gc_policy_counters = new GCPolicyCounters("GarbageFirst", 1, 3);464}465466bool G1CollectorPolicy::predict_will_fit(uint young_length,467double base_time_ms,468uint base_free_regions,469double target_pause_time_ms) {470if (young_length >= base_free_regions) {471// end condition 1: not enough space for the young regions472return false;473}474475double accum_surv_rate = accum_yg_surv_rate_pred((int) young_length - 1);476size_t bytes_to_copy =477(size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);478double copy_time_ms = predict_object_copy_time_ms(bytes_to_copy);479double young_other_time_ms = predict_young_other_time_ms(young_length);480double pause_time_ms = base_time_ms + copy_time_ms + young_other_time_ms;481if (pause_time_ms > target_pause_time_ms) {482// end condition 2: prediction is over the target pause time483return false;484}485486size_t free_bytes =487(base_free_regions - young_length) * HeapRegion::GrainBytes;488if ((2.0 * sigma()) * (double) bytes_to_copy > (double) free_bytes) {489// end condition 3: out-of-space (conservatively!)490return false;491}492493// success!494return true;495}496497void G1CollectorPolicy::record_new_heap_size(uint new_number_of_regions) {498// re-calculate the necessary reserve499double reserve_regions_d = (double) new_number_of_regions * _reserve_factor;500// We use ceiling so that if reserve_regions_d is > 0.0 (but501// smaller than 1.0) we'll get 1.502_reserve_regions = (uint) ceil(reserve_regions_d);503504_young_gen_sizer->heap_size_changed(new_number_of_regions);505}506507uint G1CollectorPolicy::calculate_young_list_desired_min_length(508uint base_min_length) {509uint desired_min_length = 0;510if (adaptive_young_list_length()) {511if (_alloc_rate_ms_seq->num() > 3) {512double now_sec = os::elapsedTime();513double when_ms = _mmu_tracker->when_max_gc_sec(now_sec) * 1000.0;514double alloc_rate_ms = predict_alloc_rate_ms();515desired_min_length = (uint) ceil(alloc_rate_ms * when_ms);516} else {517// otherwise we don't have enough info to make the prediction518}519}520desired_min_length += base_min_length;521// make sure we don't go below any user-defined minimum bound522return MAX2(_young_gen_sizer->min_desired_young_length(), desired_min_length);523}524525uint G1CollectorPolicy::calculate_young_list_desired_max_length() {526// Here, we might want to also take into account any additional527// constraints (i.e., user-defined minimum bound). Currently, we528// effectively don't set this bound.529return _young_gen_sizer->max_desired_young_length();530}531532void G1CollectorPolicy::update_young_list_target_length(size_t rs_lengths) {533if (rs_lengths == (size_t) -1) {534// if it's set to the default value (-1), we should predict it;535// otherwise, use the given value.536rs_lengths = (size_t) get_new_prediction(_rs_lengths_seq);537}538539// Calculate the absolute and desired min bounds.540541// This is how many young regions we already have (currently: the survivors).542uint base_min_length = recorded_survivor_regions();543// This is the absolute minimum young length, which ensures that we544// can allocate one eden region in the worst-case.545uint absolute_min_length = base_min_length + 1;546uint desired_min_length =547calculate_young_list_desired_min_length(base_min_length);548if (desired_min_length < absolute_min_length) {549desired_min_length = absolute_min_length;550}551552// Calculate the absolute and desired max bounds.553554// We will try our best not to "eat" into the reserve.555uint absolute_max_length = 0;556if (_free_regions_at_end_of_collection > _reserve_regions) {557absolute_max_length = _free_regions_at_end_of_collection - _reserve_regions;558}559uint desired_max_length = calculate_young_list_desired_max_length();560if (desired_max_length > absolute_max_length) {561desired_max_length = absolute_max_length;562}563564uint young_list_target_length = 0;565if (adaptive_young_list_length()) {566if (gcs_are_young()) {567young_list_target_length =568calculate_young_list_target_length(rs_lengths,569base_min_length,570desired_min_length,571desired_max_length);572_rs_lengths_prediction = rs_lengths;573} else {574// Don't calculate anything and let the code below bound it to575// the desired_min_length, i.e., do the next GC as soon as576// possible to maximize how many old regions we can add to it.577}578} else {579// The user asked for a fixed young gen so we'll fix the young gen580// whether the next GC is young or mixed.581young_list_target_length = _young_list_fixed_length;582}583584// Make sure we don't go over the desired max length, nor under the585// desired min length. In case they clash, desired_min_length wins586// which is why that test is second.587if (young_list_target_length > desired_max_length) {588young_list_target_length = desired_max_length;589}590if (young_list_target_length < desired_min_length) {591young_list_target_length = desired_min_length;592}593594assert(young_list_target_length > recorded_survivor_regions(),595"we should be able to allocate at least one eden region");596assert(young_list_target_length >= absolute_min_length, "post-condition");597_young_list_target_length = young_list_target_length;598599update_max_gc_locker_expansion();600}601602uint603G1CollectorPolicy::calculate_young_list_target_length(size_t rs_lengths,604uint base_min_length,605uint desired_min_length,606uint desired_max_length) {607assert(adaptive_young_list_length(), "pre-condition");608assert(gcs_are_young(), "only call this for young GCs");609610// In case some edge-condition makes the desired max length too small...611if (desired_max_length <= desired_min_length) {612return desired_min_length;613}614615// We'll adjust min_young_length and max_young_length not to include616// the already allocated young regions (i.e., so they reflect the617// min and max eden regions we'll allocate). The base_min_length618// will be reflected in the predictions by the619// survivor_regions_evac_time prediction.620assert(desired_min_length > base_min_length, "invariant");621uint min_young_length = desired_min_length - base_min_length;622assert(desired_max_length > base_min_length, "invariant");623uint max_young_length = desired_max_length - base_min_length;624625double target_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;626double survivor_regions_evac_time = predict_survivor_regions_evac_time();627size_t pending_cards = (size_t) get_new_prediction(_pending_cards_seq);628size_t adj_rs_lengths = rs_lengths + predict_rs_length_diff();629size_t scanned_cards = predict_young_card_num(adj_rs_lengths);630double base_time_ms =631predict_base_elapsed_time_ms(pending_cards, scanned_cards) +632survivor_regions_evac_time;633uint available_free_regions = _free_regions_at_end_of_collection;634uint base_free_regions = 0;635if (available_free_regions > _reserve_regions) {636base_free_regions = available_free_regions - _reserve_regions;637}638639// Here, we will make sure that the shortest young length that640// makes sense fits within the target pause time.641642if (predict_will_fit(min_young_length, base_time_ms,643base_free_regions, target_pause_time_ms)) {644// The shortest young length will fit into the target pause time;645// we'll now check whether the absolute maximum number of young646// regions will fit in the target pause time. If not, we'll do647// a binary search between min_young_length and max_young_length.648if (predict_will_fit(max_young_length, base_time_ms,649base_free_regions, target_pause_time_ms)) {650// The maximum young length will fit into the target pause time.651// We are done so set min young length to the maximum length (as652// the result is assumed to be returned in min_young_length).653min_young_length = max_young_length;654} else {655// The maximum possible number of young regions will not fit within656// the target pause time so we'll search for the optimal657// length. The loop invariants are:658//659// min_young_length < max_young_length660// min_young_length is known to fit into the target pause time661// max_young_length is known not to fit into the target pause time662//663// Going into the loop we know the above hold as we've just664// checked them. Every time around the loop we check whether665// the middle value between min_young_length and666// max_young_length fits into the target pause time. If it667// does, it becomes the new min. If it doesn't, it becomes668// the new max. This way we maintain the loop invariants.669670assert(min_young_length < max_young_length, "invariant");671uint diff = (max_young_length - min_young_length) / 2;672while (diff > 0) {673uint young_length = min_young_length + diff;674if (predict_will_fit(young_length, base_time_ms,675base_free_regions, target_pause_time_ms)) {676min_young_length = young_length;677} else {678max_young_length = young_length;679}680assert(min_young_length < max_young_length, "invariant");681diff = (max_young_length - min_young_length) / 2;682}683// The results is min_young_length which, according to the684// loop invariants, should fit within the target pause time.685686// These are the post-conditions of the binary search above:687assert(min_young_length < max_young_length,688"otherwise we should have discovered that max_young_length "689"fits into the pause target and not done the binary search");690assert(predict_will_fit(min_young_length, base_time_ms,691base_free_regions, target_pause_time_ms),692"min_young_length, the result of the binary search, should "693"fit into the pause target");694assert(!predict_will_fit(min_young_length + 1, base_time_ms,695base_free_regions, target_pause_time_ms),696"min_young_length, the result of the binary search, should be "697"optimal, so no larger length should fit into the pause target");698}699} else {700// Even the minimum length doesn't fit into the pause time701// target, return it as the result nevertheless.702}703return base_min_length + min_young_length;704}705706double G1CollectorPolicy::predict_survivor_regions_evac_time() {707double survivor_regions_evac_time = 0.0;708for (HeapRegion * r = _recorded_survivor_head;709r != NULL && r != _recorded_survivor_tail->get_next_young_region();710r = r->get_next_young_region()) {711survivor_regions_evac_time += predict_region_elapsed_time_ms(r, gcs_are_young());712}713return survivor_regions_evac_time;714}715716void G1CollectorPolicy::revise_young_list_target_length_if_necessary() {717guarantee( adaptive_young_list_length(), "should not call this otherwise" );718719size_t rs_lengths = _g1->young_list()->sampled_rs_lengths();720if (rs_lengths > _rs_lengths_prediction) {721// add 10% to avoid having to recalculate often722size_t rs_lengths_prediction = rs_lengths * 1100 / 1000;723update_young_list_target_length(rs_lengths_prediction);724}725}726727728729HeapWord* G1CollectorPolicy::mem_allocate_work(size_t size,730bool is_tlab,731bool* gc_overhead_limit_was_exceeded) {732guarantee(false, "Not using this policy feature yet.");733return NULL;734}735736// This method controls how a collector handles one or more737// of its generations being fully allocated.738HeapWord* G1CollectorPolicy::satisfy_failed_allocation(size_t size,739bool is_tlab) {740guarantee(false, "Not using this policy feature yet.");741return NULL;742}743744745#ifndef PRODUCT746bool G1CollectorPolicy::verify_young_ages() {747HeapRegion* head = _g1->young_list()->first_region();748return749verify_young_ages(head, _short_lived_surv_rate_group);750// also call verify_young_ages on any additional surv rate groups751}752753bool754G1CollectorPolicy::verify_young_ages(HeapRegion* head,755SurvRateGroup *surv_rate_group) {756guarantee( surv_rate_group != NULL, "pre-condition" );757758const char* name = surv_rate_group->name();759bool ret = true;760int prev_age = -1;761762for (HeapRegion* curr = head;763curr != NULL;764curr = curr->get_next_young_region()) {765SurvRateGroup* group = curr->surv_rate_group();766if (group == NULL && !curr->is_survivor()) {767gclog_or_tty->print_cr("## %s: encountered NULL surv_rate_group", name);768ret = false;769}770771if (surv_rate_group == group) {772int age = curr->age_in_surv_rate_group();773774if (age < 0) {775gclog_or_tty->print_cr("## %s: encountered negative age", name);776ret = false;777}778779if (age <= prev_age) {780gclog_or_tty->print_cr("## %s: region ages are not strictly increasing "781"(%d, %d)", name, age, prev_age);782ret = false;783}784prev_age = age;785}786}787788return ret;789}790#endif // PRODUCT791792void G1CollectorPolicy::record_full_collection_start() {793_full_collection_start_sec = os::elapsedTime();794record_heap_size_info_at_start(true /* full */);795// Release the future to-space so that it is available for compaction into.796_g1->set_full_collection();797}798799void G1CollectorPolicy::record_full_collection_end() {800// Consider this like a collection pause for the purposes of allocation801// since last pause.802double end_sec = os::elapsedTime();803double full_gc_time_sec = end_sec - _full_collection_start_sec;804double full_gc_time_ms = full_gc_time_sec * 1000.0;805806_trace_gen1_time_data.record_full_collection(full_gc_time_ms);807808update_recent_gc_times(end_sec, full_gc_time_ms);809810_g1->clear_full_collection();811812// "Nuke" the heuristics that control the young/mixed GC813// transitions and make sure we start with young GCs after the Full GC.814set_gcs_are_young(true);815_last_young_gc = false;816clear_initiate_conc_mark_if_possible();817clear_during_initial_mark_pause();818_in_marking_window = false;819_in_marking_window_im = false;820821_short_lived_surv_rate_group->start_adding_regions();822// also call this on any additional surv rate groups823824record_survivor_regions(0, NULL, NULL);825826_free_regions_at_end_of_collection = _g1->num_free_regions();827// Reset survivors SurvRateGroup.828_survivor_surv_rate_group->reset();829update_young_list_target_length();830_collectionSetChooser->clear();831}832833void G1CollectorPolicy::record_stop_world_start() {834_stop_world_start = os::elapsedTime();835}836837void G1CollectorPolicy::record_collection_pause_start(double start_time_sec, GCTracer &tracer) {838// We only need to do this here as the policy will only be applied839// to the GC we're about to start. so, no point is calculating this840// every time we calculate / recalculate the target young length.841update_survivors_policy(tracer);842843assert(_g1->used() == _g1->recalculate_used(),844err_msg("sanity, used: " SIZE_FORMAT " recalculate_used: " SIZE_FORMAT,845_g1->used(), _g1->recalculate_used()));846847double s_w_t_ms = (start_time_sec - _stop_world_start) * 1000.0;848_trace_gen0_time_data.record_start_collection(s_w_t_ms);849_stop_world_start = 0.0;850851record_heap_size_info_at_start(false /* full */);852853phase_times()->record_cur_collection_start_sec(start_time_sec);854_pending_cards = _g1->pending_card_num();855856_collection_set_bytes_used_before = 0;857_bytes_copied_during_gc = 0;858859_last_gc_was_young = false;860861// do that for any other surv rate groups862_short_lived_surv_rate_group->stop_adding_regions();863_survivors_age_table.clear();864865assert( verify_young_ages(), "region age verification" );866}867868void G1CollectorPolicy::record_concurrent_mark_init_end(double869mark_init_elapsed_time_ms) {870_during_marking = true;871assert(!initiate_conc_mark_if_possible(), "we should have cleared it by now");872clear_during_initial_mark_pause();873_cur_mark_stop_world_time_ms = mark_init_elapsed_time_ms;874}875876void G1CollectorPolicy::record_concurrent_mark_remark_start() {877_mark_remark_start_sec = os::elapsedTime();878_during_marking = false;879}880881void G1CollectorPolicy::record_concurrent_mark_remark_end() {882double end_time_sec = os::elapsedTime();883double elapsed_time_ms = (end_time_sec - _mark_remark_start_sec)*1000.0;884_concurrent_mark_remark_times_ms->add(elapsed_time_ms);885_cur_mark_stop_world_time_ms += elapsed_time_ms;886_prev_collection_pause_end_ms += elapsed_time_ms;887888_mmu_tracker->add_pause(_mark_remark_start_sec, end_time_sec, true);889}890891void G1CollectorPolicy::record_concurrent_mark_cleanup_start() {892_mark_cleanup_start_sec = os::elapsedTime();893}894895void G1CollectorPolicy::record_concurrent_mark_cleanup_completed() {896_last_young_gc = true;897_in_marking_window = false;898}899900void G1CollectorPolicy::record_concurrent_pause() {901if (_stop_world_start > 0.0) {902double yield_ms = (os::elapsedTime() - _stop_world_start) * 1000.0;903_trace_gen0_time_data.record_yield_time(yield_ms);904}905}906907bool G1CollectorPolicy::need_to_start_conc_mark(const char* source, size_t alloc_word_size) {908if (_g1->concurrent_mark()->cmThread()->during_cycle()) {909return false;910}911912size_t marking_initiating_used_threshold =913(_g1->capacity() / 100) * InitiatingHeapOccupancyPercent;914size_t cur_used_bytes = _g1->non_young_capacity_bytes();915size_t alloc_byte_size = alloc_word_size * HeapWordSize;916917if ((cur_used_bytes + alloc_byte_size) > marking_initiating_used_threshold) {918if (gcs_are_young() && !_last_young_gc) {919ergo_verbose5(ErgoConcCycles,920"request concurrent cycle initiation",921ergo_format_reason("occupancy higher than threshold")922ergo_format_byte("occupancy")923ergo_format_byte("allocation request")924ergo_format_byte_perc("threshold")925ergo_format_str("source"),926cur_used_bytes,927alloc_byte_size,928marking_initiating_used_threshold,929(double) InitiatingHeapOccupancyPercent,930source);931return true;932} else {933ergo_verbose5(ErgoConcCycles,934"do not request concurrent cycle initiation",935ergo_format_reason("still doing mixed collections")936ergo_format_byte("occupancy")937ergo_format_byte("allocation request")938ergo_format_byte_perc("threshold")939ergo_format_str("source"),940cur_used_bytes,941alloc_byte_size,942marking_initiating_used_threshold,943(double) InitiatingHeapOccupancyPercent,944source);945}946}947948return false;949}950951// Anything below that is considered to be zero952#define MIN_TIMER_GRANULARITY 0.0000001953954void G1CollectorPolicy::record_collection_pause_end(double pause_time_ms, EvacuationInfo& evacuation_info) {955double end_time_sec = os::elapsedTime();956assert(_cur_collection_pause_used_regions_at_start >= cset_region_length(),957"otherwise, the subtraction below does not make sense");958size_t rs_size =959_cur_collection_pause_used_regions_at_start - cset_region_length();960size_t cur_used_bytes = _g1->used();961assert(cur_used_bytes == _g1->recalculate_used(), "It should!");962bool last_pause_included_initial_mark = false;963bool update_stats = !_g1->evacuation_failed();964965#ifndef PRODUCT966if (G1YoungSurvRateVerbose) {967gclog_or_tty->cr();968_short_lived_surv_rate_group->print();969// do that for any other surv rate groups too970}971#endif // PRODUCT972973last_pause_included_initial_mark = during_initial_mark_pause();974if (last_pause_included_initial_mark) {975record_concurrent_mark_init_end(0.0);976} else if (need_to_start_conc_mark("end of GC")) {977// Note: this might have already been set, if during the last978// pause we decided to start a cycle but at the beginning of979// this pause we decided to postpone it. That's OK.980set_initiate_conc_mark_if_possible();981}982983_mmu_tracker->add_pause(end_time_sec - pause_time_ms/1000.0,984end_time_sec, false);985986evacuation_info.set_collectionset_used_before(_collection_set_bytes_used_before);987evacuation_info.set_bytes_copied(_bytes_copied_during_gc);988989if (update_stats) {990_trace_gen0_time_data.record_end_collection(pause_time_ms, phase_times());991// this is where we update the allocation rate of the application992double app_time_ms =993(phase_times()->cur_collection_start_sec() * 1000.0 - _prev_collection_pause_end_ms);994if (app_time_ms < MIN_TIMER_GRANULARITY) {995// This usually happens due to the timer not having the required996// granularity. Some Linuxes are the usual culprits.997// We'll just set it to something (arbitrarily) small.998app_time_ms = 1.0;999}1000// We maintain the invariant that all objects allocated by mutator1001// threads will be allocated out of eden regions. So, we can use1002// the eden region number allocated since the previous GC to1003// calculate the application's allocate rate. The only exception1004// to that is humongous objects that are allocated separately. But1005// given that humongous object allocations do not really affect1006// either the pause's duration nor when the next pause will take1007// place we can safely ignore them here.1008uint regions_allocated = eden_cset_region_length();1009double alloc_rate_ms = (double) regions_allocated / app_time_ms;1010_alloc_rate_ms_seq->add(alloc_rate_ms);10111012double interval_ms =1013(end_time_sec - _recent_prev_end_times_for_all_gcs_sec->oldest()) * 1000.0;1014update_recent_gc_times(end_time_sec, pause_time_ms);1015_recent_avg_pause_time_ratio = _recent_gc_times_ms->sum()/interval_ms;1016if (recent_avg_pause_time_ratio() < 0.0 ||1017(recent_avg_pause_time_ratio() - 1.0 > 0.0)) {1018#ifndef PRODUCT1019// Dump info to allow post-facto debugging1020gclog_or_tty->print_cr("recent_avg_pause_time_ratio() out of bounds");1021gclog_or_tty->print_cr("-------------------------------------------");1022gclog_or_tty->print_cr("Recent GC Times (ms):");1023_recent_gc_times_ms->dump();1024gclog_or_tty->print_cr("(End Time=%3.3f) Recent GC End Times (s):", end_time_sec);1025_recent_prev_end_times_for_all_gcs_sec->dump();1026gclog_or_tty->print_cr("GC = %3.3f, Interval = %3.3f, Ratio = %3.3f",1027_recent_gc_times_ms->sum(), interval_ms, recent_avg_pause_time_ratio());1028// In debug mode, terminate the JVM if the user wants to debug at this point.1029assert(!G1FailOnFPError, "Debugging data for CR 6898948 has been dumped above");1030#endif // !PRODUCT1031// Clip ratio between 0.0 and 1.0, and continue. This will be fixed in1032// CR 6902692 by redoing the manner in which the ratio is incrementally computed.1033if (_recent_avg_pause_time_ratio < 0.0) {1034_recent_avg_pause_time_ratio = 0.0;1035} else {1036assert(_recent_avg_pause_time_ratio - 1.0 > 0.0, "Ctl-point invariant");1037_recent_avg_pause_time_ratio = 1.0;1038}1039}1040}10411042bool new_in_marking_window = _in_marking_window;1043bool new_in_marking_window_im = false;1044if (last_pause_included_initial_mark) {1045new_in_marking_window = true;1046new_in_marking_window_im = true;1047}10481049if (_last_young_gc) {1050// This is supposed to to be the "last young GC" before we start1051// doing mixed GCs. Here we decide whether to start mixed GCs or not.10521053if (!last_pause_included_initial_mark) {1054if (next_gc_should_be_mixed("start mixed GCs",1055"do not start mixed GCs")) {1056set_gcs_are_young(false);1057}1058} else {1059ergo_verbose0(ErgoMixedGCs,1060"do not start mixed GCs",1061ergo_format_reason("concurrent cycle is about to start"));1062}1063_last_young_gc = false;1064}10651066if (!_last_gc_was_young) {1067// This is a mixed GC. Here we decide whether to continue doing1068// mixed GCs or not.10691070if (!next_gc_should_be_mixed("continue mixed GCs",1071"do not continue mixed GCs")) {1072set_gcs_are_young(true);1073}1074}10751076_short_lived_surv_rate_group->start_adding_regions();1077// do that for any other surv rate groupsx10781079if (update_stats) {1080double cost_per_card_ms = 0.0;1081if (_pending_cards > 0) {1082cost_per_card_ms = phase_times()->average_time_ms(G1GCPhaseTimes::UpdateRS) / (double) _pending_cards;1083_cost_per_card_ms_seq->add(cost_per_card_ms);1084}10851086size_t cards_scanned = _g1->cards_scanned();10871088double cost_per_entry_ms = 0.0;1089if (cards_scanned > 10) {1090cost_per_entry_ms = phase_times()->average_time_ms(G1GCPhaseTimes::ScanRS) / (double) cards_scanned;1091if (_last_gc_was_young) {1092_cost_per_entry_ms_seq->add(cost_per_entry_ms);1093} else {1094_mixed_cost_per_entry_ms_seq->add(cost_per_entry_ms);1095}1096}10971098if (_max_rs_lengths > 0) {1099double cards_per_entry_ratio =1100(double) cards_scanned / (double) _max_rs_lengths;1101if (_last_gc_was_young) {1102_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);1103} else {1104_mixed_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);1105}1106}11071108// This is defensive. For a while _max_rs_lengths could get1109// smaller than _recorded_rs_lengths which was causing1110// rs_length_diff to get very large and mess up the RSet length1111// predictions. The reason was unsafe concurrent updates to the1112// _inc_cset_recorded_rs_lengths field which the code below guards1113// against (see CR 7118202). This bug has now been fixed (see CR1114// 7119027). However, I'm still worried that1115// _inc_cset_recorded_rs_lengths might still end up somewhat1116// inaccurate. The concurrent refinement thread calculates an1117// RSet's length concurrently with other CR threads updating it1118// which might cause it to calculate the length incorrectly (if,1119// say, it's in mid-coarsening). So I'll leave in the defensive1120// conditional below just in case.1121size_t rs_length_diff = 0;1122if (_max_rs_lengths > _recorded_rs_lengths) {1123rs_length_diff = _max_rs_lengths - _recorded_rs_lengths;1124}1125_rs_length_diff_seq->add((double) rs_length_diff);11261127size_t freed_bytes = _heap_used_bytes_before_gc - cur_used_bytes;11281129if (_collection_set_bytes_used_before > freed_bytes) {1130size_t copied_bytes = _collection_set_bytes_used_before - freed_bytes;1131double average_copy_time = phase_times()->average_time_ms(G1GCPhaseTimes::ObjCopy);1132double cost_per_byte_ms = average_copy_time / (double) copied_bytes;1133if (_in_marking_window) {1134_cost_per_byte_ms_during_cm_seq->add(cost_per_byte_ms);1135} else {1136_cost_per_byte_ms_seq->add(cost_per_byte_ms);1137}1138}11391140double all_other_time_ms = pause_time_ms -1141(phase_times()->average_time_ms(G1GCPhaseTimes::UpdateRS) + phase_times()->average_time_ms(G1GCPhaseTimes::ScanRS) +1142phase_times()->average_time_ms(G1GCPhaseTimes::ObjCopy) + phase_times()->average_time_ms(G1GCPhaseTimes::Termination));11431144double young_other_time_ms = 0.0;1145if (young_cset_region_length() > 0) {1146young_other_time_ms =1147phase_times()->young_cset_choice_time_ms() +1148phase_times()->young_free_cset_time_ms();1149_young_other_cost_per_region_ms_seq->add(young_other_time_ms /1150(double) young_cset_region_length());1151}1152double non_young_other_time_ms = 0.0;1153if (old_cset_region_length() > 0) {1154non_young_other_time_ms =1155phase_times()->non_young_cset_choice_time_ms() +1156phase_times()->non_young_free_cset_time_ms();11571158_non_young_other_cost_per_region_ms_seq->add(non_young_other_time_ms /1159(double) old_cset_region_length());1160}11611162double constant_other_time_ms = all_other_time_ms -1163(young_other_time_ms + non_young_other_time_ms);1164_constant_other_time_ms_seq->add(constant_other_time_ms);11651166double survival_ratio = 0.0;1167if (_collection_set_bytes_used_before > 0) {1168survival_ratio = (double) _bytes_copied_during_gc /1169(double) _collection_set_bytes_used_before;1170}11711172_pending_cards_seq->add((double) _pending_cards);1173_rs_lengths_seq->add((double) _max_rs_lengths);1174}11751176_in_marking_window = new_in_marking_window;1177_in_marking_window_im = new_in_marking_window_im;1178_free_regions_at_end_of_collection = _g1->num_free_regions();1179update_young_list_target_length();11801181// Note that _mmu_tracker->max_gc_time() returns the time in seconds.1182double update_rs_time_goal_ms = _mmu_tracker->max_gc_time() * MILLIUNITS * G1RSetUpdatingPauseTimePercent / 100.0;1183adjust_concurrent_refinement(phase_times()->average_time_ms(G1GCPhaseTimes::UpdateRS),1184phase_times()->sum_thread_work_items(G1GCPhaseTimes::UpdateRS), update_rs_time_goal_ms);11851186_collectionSetChooser->verify();1187}11881189#define EXT_SIZE_FORMAT "%.1f%s"1190#define EXT_SIZE_PARAMS(bytes) \1191byte_size_in_proper_unit((double)(bytes)), \1192proper_unit_for_byte_size((bytes))11931194void G1CollectorPolicy::record_heap_size_info_at_start(bool full) {1195YoungList* young_list = _g1->young_list();1196_eden_used_bytes_before_gc = young_list->eden_used_bytes();1197_survivor_used_bytes_before_gc = young_list->survivor_used_bytes();1198_heap_capacity_bytes_before_gc = _g1->capacity();1199_heap_used_bytes_before_gc = _g1->used();1200_cur_collection_pause_used_regions_at_start = _g1->num_used_regions();12011202_eden_capacity_bytes_before_gc =1203(_young_list_target_length * HeapRegion::GrainBytes) - _survivor_used_bytes_before_gc;12041205if (full) {1206_metaspace_used_bytes_before_gc = MetaspaceAux::used_bytes();1207}1208}12091210void G1CollectorPolicy::print_heap_transition() {1211_g1->print_size_transition(gclog_or_tty,1212_heap_used_bytes_before_gc,1213_g1->used(),1214_g1->capacity());1215}12161217void G1CollectorPolicy::print_detailed_heap_transition(bool full) {1218YoungList* young_list = _g1->young_list();12191220size_t eden_used_bytes_after_gc = young_list->eden_used_bytes();1221size_t survivor_used_bytes_after_gc = young_list->survivor_used_bytes();1222size_t heap_used_bytes_after_gc = _g1->used();12231224size_t heap_capacity_bytes_after_gc = _g1->capacity();1225size_t eden_capacity_bytes_after_gc =1226(_young_list_target_length * HeapRegion::GrainBytes) - survivor_used_bytes_after_gc;12271228gclog_or_tty->print(1229" [Eden: " EXT_SIZE_FORMAT "(" EXT_SIZE_FORMAT ")->" EXT_SIZE_FORMAT "(" EXT_SIZE_FORMAT ") "1230"Survivors: " EXT_SIZE_FORMAT "->" EXT_SIZE_FORMAT " "1231"Heap: " EXT_SIZE_FORMAT "(" EXT_SIZE_FORMAT ")->"1232EXT_SIZE_FORMAT "(" EXT_SIZE_FORMAT ")]",1233EXT_SIZE_PARAMS(_eden_used_bytes_before_gc),1234EXT_SIZE_PARAMS(_eden_capacity_bytes_before_gc),1235EXT_SIZE_PARAMS(eden_used_bytes_after_gc),1236EXT_SIZE_PARAMS(eden_capacity_bytes_after_gc),1237EXT_SIZE_PARAMS(_survivor_used_bytes_before_gc),1238EXT_SIZE_PARAMS(survivor_used_bytes_after_gc),1239EXT_SIZE_PARAMS(_heap_used_bytes_before_gc),1240EXT_SIZE_PARAMS(_heap_capacity_bytes_before_gc),1241EXT_SIZE_PARAMS(heap_used_bytes_after_gc),1242EXT_SIZE_PARAMS(heap_capacity_bytes_after_gc));12431244if (full) {1245MetaspaceAux::print_metaspace_change(_metaspace_used_bytes_before_gc);1246}12471248gclog_or_tty->cr();1249}12501251void G1CollectorPolicy::adjust_concurrent_refinement(double update_rs_time,1252double update_rs_processed_buffers,1253double goal_ms) {1254DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();1255ConcurrentG1Refine *cg1r = G1CollectedHeap::heap()->concurrent_g1_refine();12561257if (G1UseAdaptiveConcRefinement) {1258const int k_gy = 3, k_gr = 6;1259const double inc_k = 1.1, dec_k = 0.9;12601261int g = cg1r->green_zone();1262if (update_rs_time > goal_ms) {1263g = (int)(g * dec_k); // Can become 0, that's OK. That would mean a mutator-only processing.1264} else {1265if (update_rs_time < goal_ms && update_rs_processed_buffers > g) {1266g = (int)MAX2(g * inc_k, g + 1.0);1267}1268}1269// Change the refinement threads params1270cg1r->set_green_zone(g);1271cg1r->set_yellow_zone(g * k_gy);1272cg1r->set_red_zone(g * k_gr);1273cg1r->reinitialize_threads();12741275int processing_threshold_delta = MAX2((int)(cg1r->green_zone() * sigma()), 1);1276int processing_threshold = MIN2(cg1r->green_zone() + processing_threshold_delta,1277cg1r->yellow_zone());1278// Change the barrier params1279dcqs.set_process_completed_threshold(processing_threshold);1280dcqs.set_max_completed_queue(cg1r->red_zone());1281}12821283int curr_queue_size = dcqs.completed_buffers_num();1284if (curr_queue_size >= cg1r->yellow_zone()) {1285dcqs.set_completed_queue_padding(curr_queue_size);1286} else {1287dcqs.set_completed_queue_padding(0);1288}1289dcqs.notify_if_necessary();1290}12911292double1293G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards,1294size_t scanned_cards) {1295return1296predict_rs_update_time_ms(pending_cards) +1297predict_rs_scan_time_ms(scanned_cards) +1298predict_constant_other_time_ms();1299}13001301double1302G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards) {1303size_t rs_length = predict_rs_length_diff();1304size_t card_num;1305if (gcs_are_young()) {1306card_num = predict_young_card_num(rs_length);1307} else {1308card_num = predict_non_young_card_num(rs_length);1309}1310return predict_base_elapsed_time_ms(pending_cards, card_num);1311}13121313size_t G1CollectorPolicy::predict_bytes_to_copy(HeapRegion* hr) {1314size_t bytes_to_copy;1315if (hr->is_marked())1316bytes_to_copy = hr->max_live_bytes();1317else {1318assert(hr->is_young() && hr->age_in_surv_rate_group() != -1, "invariant");1319int age = hr->age_in_surv_rate_group();1320double yg_surv_rate = predict_yg_surv_rate(age, hr->surv_rate_group());1321bytes_to_copy = (size_t) ((double) hr->used() * yg_surv_rate);1322}1323return bytes_to_copy;1324}13251326double1327G1CollectorPolicy::predict_region_elapsed_time_ms(HeapRegion* hr,1328bool for_young_gc) {1329size_t rs_length = hr->rem_set()->occupied();1330size_t card_num;13311332// Predicting the number of cards is based on which type of GC1333// we're predicting for.1334if (for_young_gc) {1335card_num = predict_young_card_num(rs_length);1336} else {1337card_num = predict_non_young_card_num(rs_length);1338}1339size_t bytes_to_copy = predict_bytes_to_copy(hr);13401341double region_elapsed_time_ms =1342predict_rs_scan_time_ms(card_num) +1343predict_object_copy_time_ms(bytes_to_copy);13441345// The prediction of the "other" time for this region is based1346// upon the region type and NOT the GC type.1347if (hr->is_young()) {1348region_elapsed_time_ms += predict_young_other_time_ms(1);1349} else {1350region_elapsed_time_ms += predict_non_young_other_time_ms(1);1351}1352return region_elapsed_time_ms;1353}13541355void1356G1CollectorPolicy::init_cset_region_lengths(uint eden_cset_region_length,1357uint survivor_cset_region_length) {1358_eden_cset_region_length = eden_cset_region_length;1359_survivor_cset_region_length = survivor_cset_region_length;1360_old_cset_region_length = 0;1361}13621363void G1CollectorPolicy::set_recorded_rs_lengths(size_t rs_lengths) {1364_recorded_rs_lengths = rs_lengths;1365}13661367void G1CollectorPolicy::update_recent_gc_times(double end_time_sec,1368double elapsed_ms) {1369_recent_gc_times_ms->add(elapsed_ms);1370_recent_prev_end_times_for_all_gcs_sec->add(end_time_sec);1371_prev_collection_pause_end_ms = end_time_sec * 1000.0;1372}13731374size_t G1CollectorPolicy::expansion_amount() {1375double recent_gc_overhead = recent_avg_pause_time_ratio() * 100.0;1376double threshold = _gc_overhead_perc;1377if (recent_gc_overhead > threshold) {1378// We will double the existing space, or take1379// G1ExpandByPercentOfAvailable % of the available expansion1380// space, whichever is smaller, bounded below by a minimum1381// expansion (unless that's all that's left.)1382const size_t min_expand_bytes = 1*M;1383size_t reserved_bytes = _g1->max_capacity();1384size_t committed_bytes = _g1->capacity();1385size_t uncommitted_bytes = reserved_bytes - committed_bytes;1386size_t expand_bytes;1387size_t expand_bytes_via_pct =1388uncommitted_bytes * G1ExpandByPercentOfAvailable / 100;1389expand_bytes = MIN2(expand_bytes_via_pct, committed_bytes);1390expand_bytes = MAX2(expand_bytes, min_expand_bytes);1391expand_bytes = MIN2(expand_bytes, uncommitted_bytes);13921393ergo_verbose5(ErgoHeapSizing,1394"attempt heap expansion",1395ergo_format_reason("recent GC overhead higher than "1396"threshold after GC")1397ergo_format_perc("recent GC overhead")1398ergo_format_perc("threshold")1399ergo_format_byte("uncommitted")1400ergo_format_byte_perc("calculated expansion amount"),1401recent_gc_overhead, threshold,1402uncommitted_bytes,1403expand_bytes_via_pct, (double) G1ExpandByPercentOfAvailable);14041405return expand_bytes;1406} else {1407return 0;1408}1409}14101411void G1CollectorPolicy::print_tracing_info() const {1412_trace_gen0_time_data.print();1413_trace_gen1_time_data.print();1414}14151416void G1CollectorPolicy::print_yg_surv_rate_info() const {1417#ifndef PRODUCT1418_short_lived_surv_rate_group->print_surv_rate_summary();1419// add this call for any other surv rate groups1420#endif // PRODUCT1421}14221423bool G1CollectorPolicy::is_young_list_full() {1424uint young_list_length = _g1->young_list()->length();1425uint young_list_target_length = _young_list_target_length;1426return young_list_length >= young_list_target_length;1427}14281429bool G1CollectorPolicy::can_expand_young_list() {1430uint young_list_length = _g1->young_list()->length();1431uint young_list_max_length = _young_list_max_length;1432return young_list_length < young_list_max_length;1433}14341435void G1CollectorPolicy::update_max_gc_locker_expansion() {1436uint expansion_region_num = 0;1437if (GCLockerEdenExpansionPercent > 0) {1438double perc = (double) GCLockerEdenExpansionPercent / 100.0;1439double expansion_region_num_d = perc * (double) _young_list_target_length;1440// We use ceiling so that if expansion_region_num_d is > 0.0 (but1441// less than 1.0) we'll get 1.1442expansion_region_num = (uint) ceil(expansion_region_num_d);1443} else {1444assert(expansion_region_num == 0, "sanity");1445}1446_young_list_max_length = _young_list_target_length + expansion_region_num;1447assert(_young_list_target_length <= _young_list_max_length, "post-condition");1448}14491450// Calculates survivor space parameters.1451void G1CollectorPolicy::update_survivors_policy(GCTracer &tracer) {1452double max_survivor_regions_d =1453(double) _young_list_target_length / (double) SurvivorRatio;1454// We use ceiling so that if max_survivor_regions_d is > 0.0 (but1455// smaller than 1.0) we'll get 1.1456_max_survivor_regions = (uint) ceil(max_survivor_regions_d);14571458_tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(1459HeapRegion::GrainWords * _max_survivor_regions, tracer);1460}14611462bool G1CollectorPolicy::force_initial_mark_if_outside_cycle(1463GCCause::Cause gc_cause) {1464bool during_cycle = _g1->concurrent_mark()->cmThread()->during_cycle();1465if (!during_cycle) {1466ergo_verbose1(ErgoConcCycles,1467"request concurrent cycle initiation",1468ergo_format_reason("requested by GC cause")1469ergo_format_str("GC cause"),1470GCCause::to_string(gc_cause));1471set_initiate_conc_mark_if_possible();1472return true;1473} else {1474ergo_verbose1(ErgoConcCycles,1475"do not request concurrent cycle initiation",1476ergo_format_reason("concurrent cycle already in progress")1477ergo_format_str("GC cause"),1478GCCause::to_string(gc_cause));1479return false;1480}1481}14821483void1484G1CollectorPolicy::decide_on_conc_mark_initiation() {1485// We are about to decide on whether this pause will be an1486// initial-mark pause.14871488// First, during_initial_mark_pause() should not be already set. We1489// will set it here if we have to. However, it should be cleared by1490// the end of the pause (it's only set for the duration of an1491// initial-mark pause).1492assert(!during_initial_mark_pause(), "pre-condition");14931494if (initiate_conc_mark_if_possible()) {1495// We had noticed on a previous pause that the heap occupancy has1496// gone over the initiating threshold and we should start a1497// concurrent marking cycle. So we might initiate one.14981499bool during_cycle = _g1->concurrent_mark()->cmThread()->during_cycle();1500if (!during_cycle) {1501// The concurrent marking thread is not "during a cycle", i.e.,1502// it has completed the last one. So we can go ahead and1503// initiate a new cycle.15041505set_during_initial_mark_pause();1506// We do not allow mixed GCs during marking.1507if (!gcs_are_young()) {1508set_gcs_are_young(true);1509ergo_verbose0(ErgoMixedGCs,1510"end mixed GCs",1511ergo_format_reason("concurrent cycle is about to start"));1512}15131514// And we can now clear initiate_conc_mark_if_possible() as1515// we've already acted on it.1516clear_initiate_conc_mark_if_possible();15171518ergo_verbose0(ErgoConcCycles,1519"initiate concurrent cycle",1520ergo_format_reason("concurrent cycle initiation requested"));1521} else {1522// The concurrent marking thread is still finishing up the1523// previous cycle. If we start one right now the two cycles1524// overlap. In particular, the concurrent marking thread might1525// be in the process of clearing the next marking bitmap (which1526// we will use for the next cycle if we start one). Starting a1527// cycle now will be bad given that parts of the marking1528// information might get cleared by the marking thread. And we1529// cannot wait for the marking thread to finish the cycle as it1530// periodically yields while clearing the next marking bitmap1531// and, if it's in a yield point, it's waiting for us to1532// finish. So, at this point we will not start a cycle and we'll1533// let the concurrent marking thread complete the last one.1534ergo_verbose0(ErgoConcCycles,1535"do not initiate concurrent cycle",1536ergo_format_reason("concurrent cycle already in progress"));1537}1538}1539}15401541class KnownGarbageClosure: public HeapRegionClosure {1542G1CollectedHeap* _g1h;1543CollectionSetChooser* _hrSorted;15441545public:1546KnownGarbageClosure(CollectionSetChooser* hrSorted) :1547_g1h(G1CollectedHeap::heap()), _hrSorted(hrSorted) { }15481549bool doHeapRegion(HeapRegion* r) {1550// We only include humongous regions in collection1551// sets when concurrent mark shows that their contained object is1552// unreachable.15531554// Do we have any marking information for this region?1555if (r->is_marked()) {1556// We will skip any region that's currently used as an old GC1557// alloc region (we should not consider those for collection1558// before we fill them up).1559if (_hrSorted->should_add(r) && !_g1h->is_old_gc_alloc_region(r)) {1560_hrSorted->add_region(r);1561}1562}1563return false;1564}1565};15661567class ParKnownGarbageHRClosure: public HeapRegionClosure {1568G1CollectedHeap* _g1h;1569CSetChooserParUpdater _cset_updater;15701571public:1572ParKnownGarbageHRClosure(CollectionSetChooser* hrSorted,1573uint chunk_size) :1574_g1h(G1CollectedHeap::heap()),1575_cset_updater(hrSorted, true /* parallel */, chunk_size) { }15761577bool doHeapRegion(HeapRegion* r) {1578// Do we have any marking information for this region?1579if (r->is_marked()) {1580// We will skip any region that's currently used as an old GC1581// alloc region (we should not consider those for collection1582// before we fill them up).1583if (_cset_updater.should_add(r) && !_g1h->is_old_gc_alloc_region(r)) {1584_cset_updater.add_region(r);1585}1586}1587return false;1588}1589};15901591class ParKnownGarbageTask: public AbstractGangTask {1592CollectionSetChooser* _hrSorted;1593uint _chunk_size;1594G1CollectedHeap* _g1;1595public:1596ParKnownGarbageTask(CollectionSetChooser* hrSorted, uint chunk_size) :1597AbstractGangTask("ParKnownGarbageTask"),1598_hrSorted(hrSorted), _chunk_size(chunk_size),1599_g1(G1CollectedHeap::heap()) { }16001601void work(uint worker_id) {1602ParKnownGarbageHRClosure parKnownGarbageCl(_hrSorted, _chunk_size);16031604// Back to zero for the claim value.1605_g1->heap_region_par_iterate_chunked(&parKnownGarbageCl, worker_id,1606_g1->workers()->active_workers(),1607HeapRegion::InitialClaimValue);1608}1609};16101611void1612G1CollectorPolicy::record_concurrent_mark_cleanup_end(int no_of_gc_threads) {1613_collectionSetChooser->clear();16141615uint region_num = _g1->num_regions();1616if (G1CollectedHeap::use_parallel_gc_threads()) {1617const uint OverpartitionFactor = 4;1618uint WorkUnit;1619// The use of MinChunkSize = 8 in the original code1620// causes some assertion failures when the total number of1621// region is less than 8. The code here tries to fix that.1622// Should the original code also be fixed?1623if (no_of_gc_threads > 0) {1624const uint MinWorkUnit = MAX2(region_num / no_of_gc_threads, 1U);1625WorkUnit = MAX2(region_num / (no_of_gc_threads * OverpartitionFactor),1626MinWorkUnit);1627} else {1628assert(no_of_gc_threads > 0,1629"The active gc workers should be greater than 0");1630// In a product build do something reasonable to avoid a crash.1631const uint MinWorkUnit = MAX2(region_num / (uint) ParallelGCThreads, 1U);1632WorkUnit =1633MAX2(region_num / (uint) (ParallelGCThreads * OverpartitionFactor),1634MinWorkUnit);1635}1636_collectionSetChooser->prepare_for_par_region_addition(_g1->num_regions(),1637WorkUnit);1638ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser,1639(int) WorkUnit);1640_g1->workers()->run_task(&parKnownGarbageTask);16411642assert(_g1->check_heap_region_claim_values(HeapRegion::InitialClaimValue),1643"sanity check");1644} else {1645KnownGarbageClosure knownGarbagecl(_collectionSetChooser);1646_g1->heap_region_iterate(&knownGarbagecl);1647}16481649_collectionSetChooser->sort_regions();16501651double end_sec = os::elapsedTime();1652double elapsed_time_ms = (end_sec - _mark_cleanup_start_sec) * 1000.0;1653_concurrent_mark_cleanup_times_ms->add(elapsed_time_ms);1654_cur_mark_stop_world_time_ms += elapsed_time_ms;1655_prev_collection_pause_end_ms += elapsed_time_ms;1656_mmu_tracker->add_pause(_mark_cleanup_start_sec, end_sec, true);1657}16581659// Add the heap region at the head of the non-incremental collection set1660void G1CollectorPolicy::add_old_region_to_cset(HeapRegion* hr) {1661assert(_inc_cset_build_state == Active, "Precondition");1662assert(hr->is_old(), "the region should be old");16631664assert(!hr->in_collection_set(), "should not already be in the CSet");1665hr->set_in_collection_set(true);1666hr->set_next_in_collection_set(_collection_set);1667_collection_set = hr;1668_collection_set_bytes_used_before += hr->used();1669_g1->register_old_region_with_in_cset_fast_test(hr);1670size_t rs_length = hr->rem_set()->occupied();1671_recorded_rs_lengths += rs_length;1672_old_cset_region_length += 1;1673}16741675// Initialize the per-collection-set information1676void G1CollectorPolicy::start_incremental_cset_building() {1677assert(_inc_cset_build_state == Inactive, "Precondition");16781679_inc_cset_head = NULL;1680_inc_cset_tail = NULL;1681_inc_cset_bytes_used_before = 0;16821683_inc_cset_max_finger = 0;1684_inc_cset_recorded_rs_lengths = 0;1685_inc_cset_recorded_rs_lengths_diffs = 0;1686_inc_cset_predicted_elapsed_time_ms = 0.0;1687_inc_cset_predicted_elapsed_time_ms_diffs = 0.0;1688_inc_cset_build_state = Active;1689}16901691void G1CollectorPolicy::finalize_incremental_cset_building() {1692assert(_inc_cset_build_state == Active, "Precondition");1693assert(SafepointSynchronize::is_at_safepoint(), "should be at a safepoint");16941695// The two "main" fields, _inc_cset_recorded_rs_lengths and1696// _inc_cset_predicted_elapsed_time_ms, are updated by the thread1697// that adds a new region to the CSet. Further updates by the1698// concurrent refinement thread that samples the young RSet lengths1699// are accumulated in the *_diffs fields. Here we add the diffs to1700// the "main" fields.17011702if (_inc_cset_recorded_rs_lengths_diffs >= 0) {1703_inc_cset_recorded_rs_lengths += _inc_cset_recorded_rs_lengths_diffs;1704} else {1705// This is defensive. The diff should in theory be always positive1706// as RSets can only grow between GCs. However, given that we1707// sample their size concurrently with other threads updating them1708// it's possible that we might get the wrong size back, which1709// could make the calculations somewhat inaccurate.1710size_t diffs = (size_t) (-_inc_cset_recorded_rs_lengths_diffs);1711if (_inc_cset_recorded_rs_lengths >= diffs) {1712_inc_cset_recorded_rs_lengths -= diffs;1713} else {1714_inc_cset_recorded_rs_lengths = 0;1715}1716}1717_inc_cset_predicted_elapsed_time_ms +=1718_inc_cset_predicted_elapsed_time_ms_diffs;17191720_inc_cset_recorded_rs_lengths_diffs = 0;1721_inc_cset_predicted_elapsed_time_ms_diffs = 0.0;1722}17231724void G1CollectorPolicy::add_to_incremental_cset_info(HeapRegion* hr, size_t rs_length) {1725// This routine is used when:1726// * adding survivor regions to the incremental cset at the end of an1727// evacuation pause,1728// * adding the current allocation region to the incremental cset1729// when it is retired, and1730// * updating existing policy information for a region in the1731// incremental cset via young list RSet sampling.1732// Therefore this routine may be called at a safepoint by the1733// VM thread, or in-between safepoints by mutator threads (when1734// retiring the current allocation region) or a concurrent1735// refine thread (RSet sampling).17361737double region_elapsed_time_ms = predict_region_elapsed_time_ms(hr, gcs_are_young());1738size_t used_bytes = hr->used();1739_inc_cset_recorded_rs_lengths += rs_length;1740_inc_cset_predicted_elapsed_time_ms += region_elapsed_time_ms;1741_inc_cset_bytes_used_before += used_bytes;17421743// Cache the values we have added to the aggregated informtion1744// in the heap region in case we have to remove this region from1745// the incremental collection set, or it is updated by the1746// rset sampling code1747hr->set_recorded_rs_length(rs_length);1748hr->set_predicted_elapsed_time_ms(region_elapsed_time_ms);1749}17501751void G1CollectorPolicy::update_incremental_cset_info(HeapRegion* hr,1752size_t new_rs_length) {1753// Update the CSet information that is dependent on the new RS length1754assert(hr->is_young(), "Precondition");1755assert(!SafepointSynchronize::is_at_safepoint(),1756"should not be at a safepoint");17571758// We could have updated _inc_cset_recorded_rs_lengths and1759// _inc_cset_predicted_elapsed_time_ms directly but we'd need to do1760// that atomically, as this code is executed by a concurrent1761// refinement thread, potentially concurrently with a mutator thread1762// allocating a new region and also updating the same fields. To1763// avoid the atomic operations we accumulate these updates on two1764// separate fields (*_diffs) and we'll just add them to the "main"1765// fields at the start of a GC.17661767ssize_t old_rs_length = (ssize_t) hr->recorded_rs_length();1768ssize_t rs_lengths_diff = (ssize_t) new_rs_length - old_rs_length;1769_inc_cset_recorded_rs_lengths_diffs += rs_lengths_diff;17701771double old_elapsed_time_ms = hr->predicted_elapsed_time_ms();1772double new_region_elapsed_time_ms = predict_region_elapsed_time_ms(hr, gcs_are_young());1773double elapsed_ms_diff = new_region_elapsed_time_ms - old_elapsed_time_ms;1774_inc_cset_predicted_elapsed_time_ms_diffs += elapsed_ms_diff;17751776hr->set_recorded_rs_length(new_rs_length);1777hr->set_predicted_elapsed_time_ms(new_region_elapsed_time_ms);1778}17791780void G1CollectorPolicy::add_region_to_incremental_cset_common(HeapRegion* hr) {1781assert(hr->is_young(), "invariant");1782assert(hr->young_index_in_cset() > -1, "should have already been set");1783assert(_inc_cset_build_state == Active, "Precondition");17841785// We need to clear and set the cached recorded/cached collection set1786// information in the heap region here (before the region gets added1787// to the collection set). An individual heap region's cached values1788// are calculated, aggregated with the policy collection set info,1789// and cached in the heap region here (initially) and (subsequently)1790// by the Young List sampling code.17911792size_t rs_length = hr->rem_set()->occupied();1793add_to_incremental_cset_info(hr, rs_length);17941795HeapWord* hr_end = hr->end();1796_inc_cset_max_finger = MAX2(_inc_cset_max_finger, hr_end);17971798assert(!hr->in_collection_set(), "invariant");1799hr->set_in_collection_set(true);1800assert( hr->next_in_collection_set() == NULL, "invariant");18011802_g1->register_young_region_with_in_cset_fast_test(hr);1803}18041805// Add the region at the RHS of the incremental cset1806void G1CollectorPolicy::add_region_to_incremental_cset_rhs(HeapRegion* hr) {1807// We should only ever be appending survivors at the end of a pause1808assert(hr->is_survivor(), "Logic");18091810// Do the 'common' stuff1811add_region_to_incremental_cset_common(hr);18121813// Now add the region at the right hand side1814if (_inc_cset_tail == NULL) {1815assert(_inc_cset_head == NULL, "invariant");1816_inc_cset_head = hr;1817} else {1818_inc_cset_tail->set_next_in_collection_set(hr);1819}1820_inc_cset_tail = hr;1821}18221823// Add the region to the LHS of the incremental cset1824void G1CollectorPolicy::add_region_to_incremental_cset_lhs(HeapRegion* hr) {1825// Survivors should be added to the RHS at the end of a pause1826assert(hr->is_eden(), "Logic");18271828// Do the 'common' stuff1829add_region_to_incremental_cset_common(hr);18301831// Add the region at the left hand side1832hr->set_next_in_collection_set(_inc_cset_head);1833if (_inc_cset_head == NULL) {1834assert(_inc_cset_tail == NULL, "Invariant");1835_inc_cset_tail = hr;1836}1837_inc_cset_head = hr;1838}18391840#ifndef PRODUCT1841void G1CollectorPolicy::print_collection_set(HeapRegion* list_head, outputStream* st) {1842assert(list_head == inc_cset_head() || list_head == collection_set(), "must be");18431844st->print_cr("\nCollection_set:");1845HeapRegion* csr = list_head;1846while (csr != NULL) {1847HeapRegion* next = csr->next_in_collection_set();1848assert(csr->in_collection_set(), "bad CS");1849st->print_cr(" " HR_FORMAT ", P: " PTR_FORMAT "N: " PTR_FORMAT ", age: %4d",1850HR_FORMAT_PARAMS(csr),1851p2i(csr->prev_top_at_mark_start()), p2i(csr->next_top_at_mark_start()),1852csr->age_in_surv_rate_group_cond());1853csr = next;1854}1855}1856#endif // !PRODUCT18571858double G1CollectorPolicy::reclaimable_bytes_perc(size_t reclaimable_bytes) {1859// Returns the given amount of reclaimable bytes (that represents1860// the amount of reclaimable space still to be collected) as a1861// percentage of the current heap capacity.1862size_t capacity_bytes = _g1->capacity();1863return (double) reclaimable_bytes * 100.0 / (double) capacity_bytes;1864}18651866bool G1CollectorPolicy::next_gc_should_be_mixed(const char* true_action_str,1867const char* false_action_str) {1868CollectionSetChooser* cset_chooser = _collectionSetChooser;1869if (cset_chooser->is_empty()) {1870ergo_verbose0(ErgoMixedGCs,1871false_action_str,1872ergo_format_reason("candidate old regions not available"));1873return false;1874}18751876// Is the amount of uncollected reclaimable space above G1HeapWastePercent?1877size_t reclaimable_bytes = cset_chooser->remaining_reclaimable_bytes();1878double reclaimable_perc = reclaimable_bytes_perc(reclaimable_bytes);1879double threshold = (double) G1HeapWastePercent;1880if (reclaimable_perc <= threshold) {1881ergo_verbose4(ErgoMixedGCs,1882false_action_str,1883ergo_format_reason("reclaimable percentage not over threshold")1884ergo_format_region("candidate old regions")1885ergo_format_byte_perc("reclaimable")1886ergo_format_perc("threshold"),1887cset_chooser->remaining_regions(),1888reclaimable_bytes,1889reclaimable_perc, threshold);1890return false;1891}18921893ergo_verbose4(ErgoMixedGCs,1894true_action_str,1895ergo_format_reason("candidate old regions available")1896ergo_format_region("candidate old regions")1897ergo_format_byte_perc("reclaimable")1898ergo_format_perc("threshold"),1899cset_chooser->remaining_regions(),1900reclaimable_bytes,1901reclaimable_perc, threshold);1902return true;1903}19041905uint G1CollectorPolicy::calc_min_old_cset_length() {1906// The min old CSet region bound is based on the maximum desired1907// number of mixed GCs after a cycle. I.e., even if some old regions1908// look expensive, we should add them to the CSet anyway to make1909// sure we go through the available old regions in no more than the1910// maximum desired number of mixed GCs.1911//1912// The calculation is based on the number of marked regions we added1913// to the CSet chooser in the first place, not how many remain, so1914// that the result is the same during all mixed GCs that follow a cycle.19151916const size_t region_num = (size_t) _collectionSetChooser->length();1917const size_t gc_num = (size_t) MAX2(G1MixedGCCountTarget, (uintx) 1);1918size_t result = region_num / gc_num;1919// emulate ceiling1920if (result * gc_num < region_num) {1921result += 1;1922}1923return (uint) result;1924}19251926uint G1CollectorPolicy::calc_max_old_cset_length() {1927// The max old CSet region bound is based on the threshold expressed1928// as a percentage of the heap size. I.e., it should bound the1929// number of old regions added to the CSet irrespective of how many1930// of them are available.19311932G1CollectedHeap* g1h = G1CollectedHeap::heap();1933const size_t region_num = g1h->num_regions();1934const size_t perc = (size_t) G1OldCSetRegionThresholdPercent;1935size_t result = region_num * perc / 100;1936// emulate ceiling1937if (100 * result < region_num * perc) {1938result += 1;1939}1940return (uint) result;1941}194219431944void G1CollectorPolicy::finalize_cset(double target_pause_time_ms, EvacuationInfo& evacuation_info) {1945double young_start_time_sec = os::elapsedTime();19461947YoungList* young_list = _g1->young_list();1948finalize_incremental_cset_building();19491950guarantee(target_pause_time_ms > 0.0,1951err_msg("target_pause_time_ms = %1.6lf should be positive",1952target_pause_time_ms));1953guarantee(_collection_set == NULL, "Precondition");19541955double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);1956double predicted_pause_time_ms = base_time_ms;1957double time_remaining_ms = MAX2(target_pause_time_ms - base_time_ms, 0.0);19581959ergo_verbose4(ErgoCSetConstruction | ErgoHigh,1960"start choosing CSet",1961ergo_format_size("_pending_cards")1962ergo_format_ms("predicted base time")1963ergo_format_ms("remaining time")1964ergo_format_ms("target pause time"),1965_pending_cards, base_time_ms, time_remaining_ms, target_pause_time_ms);19661967_last_gc_was_young = gcs_are_young() ? true : false;19681969if (_last_gc_was_young) {1970_trace_gen0_time_data.increment_young_collection_count();1971} else {1972_trace_gen0_time_data.increment_mixed_collection_count();1973}19741975// The young list is laid with the survivor regions from the previous1976// pause are appended to the RHS of the young list, i.e.1977// [Newly Young Regions ++ Survivors from last pause].19781979uint survivor_region_length = young_list->survivor_length();1980uint eden_region_length = young_list->length() - survivor_region_length;1981init_cset_region_lengths(eden_region_length, survivor_region_length);19821983HeapRegion* hr = young_list->first_survivor_region();1984while (hr != NULL) {1985assert(hr->is_survivor(), "badly formed young list");1986// There is a convention that all the young regions in the CSet1987// are tagged as "eden", so we do this for the survivors here. We1988// use the special set_eden_pre_gc() as it doesn't check that the1989// region is free (which is not the case here).1990hr->set_eden_pre_gc();1991hr = hr->get_next_young_region();1992}19931994// Clear the fields that point to the survivor list - they are all young now.1995young_list->clear_survivors();19961997_collection_set = _inc_cset_head;1998_collection_set_bytes_used_before = _inc_cset_bytes_used_before;1999time_remaining_ms = MAX2(time_remaining_ms - _inc_cset_predicted_elapsed_time_ms, 0.0);2000predicted_pause_time_ms += _inc_cset_predicted_elapsed_time_ms;20012002ergo_verbose3(ErgoCSetConstruction | ErgoHigh,2003"add young regions to CSet",2004ergo_format_region("eden")2005ergo_format_region("survivors")2006ergo_format_ms("predicted young region time"),2007eden_region_length, survivor_region_length,2008_inc_cset_predicted_elapsed_time_ms);20092010// The number of recorded young regions is the incremental2011// collection set's current size2012set_recorded_rs_lengths(_inc_cset_recorded_rs_lengths);20132014double young_end_time_sec = os::elapsedTime();2015phase_times()->record_young_cset_choice_time_ms((young_end_time_sec - young_start_time_sec) * 1000.0);20162017// Set the start of the non-young choice time.2018double non_young_start_time_sec = young_end_time_sec;20192020if (!gcs_are_young()) {2021CollectionSetChooser* cset_chooser = _collectionSetChooser;2022cset_chooser->verify();2023const uint min_old_cset_length = calc_min_old_cset_length();2024const uint max_old_cset_length = calc_max_old_cset_length();20252026uint expensive_region_num = 0;2027bool check_time_remaining = adaptive_young_list_length();20282029HeapRegion* hr = cset_chooser->peek();2030while (hr != NULL) {2031if (old_cset_region_length() >= max_old_cset_length) {2032// Added maximum number of old regions to the CSet.2033ergo_verbose2(ErgoCSetConstruction,2034"finish adding old regions to CSet",2035ergo_format_reason("old CSet region num reached max")2036ergo_format_region("old")2037ergo_format_region("max"),2038old_cset_region_length(), max_old_cset_length);2039break;2040}204120422043// Stop adding regions if the remaining reclaimable space is2044// not above G1HeapWastePercent.2045size_t reclaimable_bytes = cset_chooser->remaining_reclaimable_bytes();2046double reclaimable_perc = reclaimable_bytes_perc(reclaimable_bytes);2047double threshold = (double) G1HeapWastePercent;2048if (reclaimable_perc <= threshold) {2049// We've added enough old regions that the amount of uncollected2050// reclaimable space is at or below the waste threshold. Stop2051// adding old regions to the CSet.2052ergo_verbose5(ErgoCSetConstruction,2053"finish adding old regions to CSet",2054ergo_format_reason("reclaimable percentage not over threshold")2055ergo_format_region("old")2056ergo_format_region("max")2057ergo_format_byte_perc("reclaimable")2058ergo_format_perc("threshold"),2059old_cset_region_length(),2060max_old_cset_length,2061reclaimable_bytes,2062reclaimable_perc, threshold);2063break;2064}20652066double predicted_time_ms = predict_region_elapsed_time_ms(hr, gcs_are_young());2067if (check_time_remaining) {2068if (predicted_time_ms > time_remaining_ms) {2069// Too expensive for the current CSet.20702071if (old_cset_region_length() >= min_old_cset_length) {2072// We have added the minimum number of old regions to the CSet,2073// we are done with this CSet.2074ergo_verbose4(ErgoCSetConstruction,2075"finish adding old regions to CSet",2076ergo_format_reason("predicted time is too high")2077ergo_format_ms("predicted time")2078ergo_format_ms("remaining time")2079ergo_format_region("old")2080ergo_format_region("min"),2081predicted_time_ms, time_remaining_ms,2082old_cset_region_length(), min_old_cset_length);2083break;2084}20852086// We'll add it anyway given that we haven't reached the2087// minimum number of old regions.2088expensive_region_num += 1;2089}2090} else {2091if (old_cset_region_length() >= min_old_cset_length) {2092// In the non-auto-tuning case, we'll finish adding regions2093// to the CSet if we reach the minimum.2094ergo_verbose2(ErgoCSetConstruction,2095"finish adding old regions to CSet",2096ergo_format_reason("old CSet region num reached min")2097ergo_format_region("old")2098ergo_format_region("min"),2099old_cset_region_length(), min_old_cset_length);2100break;2101}2102}21032104// We will add this region to the CSet.2105time_remaining_ms = MAX2(time_remaining_ms - predicted_time_ms, 0.0);2106predicted_pause_time_ms += predicted_time_ms;2107cset_chooser->remove_and_move_to_next(hr);2108_g1->old_set_remove(hr);2109add_old_region_to_cset(hr);21102111hr = cset_chooser->peek();2112}2113if (hr == NULL) {2114ergo_verbose0(ErgoCSetConstruction,2115"finish adding old regions to CSet",2116ergo_format_reason("candidate old regions not available"));2117}21182119if (expensive_region_num > 0) {2120// We print the information once here at the end, predicated on2121// whether we added any apparently expensive regions or not, to2122// avoid generating output per region.2123ergo_verbose4(ErgoCSetConstruction,2124"added expensive regions to CSet",2125ergo_format_reason("old CSet region num not reached min")2126ergo_format_region("old")2127ergo_format_region("expensive")2128ergo_format_region("min")2129ergo_format_ms("remaining time"),2130old_cset_region_length(),2131expensive_region_num,2132min_old_cset_length,2133time_remaining_ms);2134}21352136cset_chooser->verify();2137}21382139stop_incremental_cset_building();21402141ergo_verbose5(ErgoCSetConstruction,2142"finish choosing CSet",2143ergo_format_region("eden")2144ergo_format_region("survivors")2145ergo_format_region("old")2146ergo_format_ms("predicted pause time")2147ergo_format_ms("target pause time"),2148eden_region_length, survivor_region_length,2149old_cset_region_length(),2150predicted_pause_time_ms, target_pause_time_ms);21512152double non_young_end_time_sec = os::elapsedTime();2153phase_times()->record_non_young_cset_choice_time_ms((non_young_end_time_sec - non_young_start_time_sec) * 1000.0);2154evacuation_info.set_collectionset_regions(cset_region_length());2155}21562157void TraceGen0TimeData::record_start_collection(double time_to_stop_the_world_ms) {2158if(TraceGen0Time) {2159_all_stop_world_times_ms.add(time_to_stop_the_world_ms);2160}2161}21622163void TraceGen0TimeData::record_yield_time(double yield_time_ms) {2164if(TraceGen0Time) {2165_all_yield_times_ms.add(yield_time_ms);2166}2167}21682169void TraceGen0TimeData::record_end_collection(double pause_time_ms, G1GCPhaseTimes* phase_times) {2170if(TraceGen0Time) {2171_total.add(pause_time_ms);2172_other.add(pause_time_ms - phase_times->accounted_time_ms());2173_root_region_scan_wait.add(phase_times->root_region_scan_wait_time_ms());2174_parallel.add(phase_times->cur_collection_par_time_ms());2175_ext_root_scan.add(phase_times->average_time_ms(G1GCPhaseTimes::ExtRootScan));2176_satb_filtering.add(phase_times->average_time_ms(G1GCPhaseTimes::SATBFiltering));2177_update_rs.add(phase_times->average_time_ms(G1GCPhaseTimes::UpdateRS));2178_scan_rs.add(phase_times->average_time_ms(G1GCPhaseTimes::ScanRS));2179_obj_copy.add(phase_times->average_time_ms(G1GCPhaseTimes::ObjCopy));2180_termination.add(phase_times->average_time_ms(G1GCPhaseTimes::Termination));21812182double parallel_known_time = phase_times->average_time_ms(G1GCPhaseTimes::ExtRootScan) +2183phase_times->average_time_ms(G1GCPhaseTimes::SATBFiltering) +2184phase_times->average_time_ms(G1GCPhaseTimes::UpdateRS) +2185phase_times->average_time_ms(G1GCPhaseTimes::ScanRS) +2186phase_times->average_time_ms(G1GCPhaseTimes::ObjCopy) +2187phase_times->average_time_ms(G1GCPhaseTimes::Termination);21882189double parallel_other_time = phase_times->cur_collection_par_time_ms() - parallel_known_time;2190_parallel_other.add(parallel_other_time);2191_clear_ct.add(phase_times->cur_clear_ct_time_ms());2192}2193}21942195void TraceGen0TimeData::increment_young_collection_count() {2196if(TraceGen0Time) {2197++_young_pause_num;2198}2199}22002201void TraceGen0TimeData::increment_mixed_collection_count() {2202if(TraceGen0Time) {2203++_mixed_pause_num;2204}2205}22062207void TraceGen0TimeData::print_summary(const char* str,2208const NumberSeq* seq) const {2209double sum = seq->sum();2210gclog_or_tty->print_cr("%-27s = %8.2lf s (avg = %8.2lf ms)",2211str, sum / 1000.0, seq->avg());2212}22132214void TraceGen0TimeData::print_summary_sd(const char* str,2215const NumberSeq* seq) const {2216print_summary(str, seq);2217gclog_or_tty->print_cr("%45s = %5d, std dev = %8.2lf ms, max = %8.2lf ms)",2218"(num", seq->num(), seq->sd(), seq->maximum());2219}22202221void TraceGen0TimeData::print() const {2222if (!TraceGen0Time) {2223return;2224}22252226gclog_or_tty->print_cr("ALL PAUSES");2227print_summary_sd(" Total", &_total);2228gclog_or_tty->cr();2229gclog_or_tty->cr();2230gclog_or_tty->print_cr(" Young GC Pauses: %8d", _young_pause_num);2231gclog_or_tty->print_cr(" Mixed GC Pauses: %8d", _mixed_pause_num);2232gclog_or_tty->cr();22332234gclog_or_tty->print_cr("EVACUATION PAUSES");22352236if (_young_pause_num == 0 && _mixed_pause_num == 0) {2237gclog_or_tty->print_cr("none");2238} else {2239print_summary_sd(" Evacuation Pauses", &_total);2240print_summary(" Root Region Scan Wait", &_root_region_scan_wait);2241print_summary(" Parallel Time", &_parallel);2242print_summary(" Ext Root Scanning", &_ext_root_scan);2243print_summary(" SATB Filtering", &_satb_filtering);2244print_summary(" Update RS", &_update_rs);2245print_summary(" Scan RS", &_scan_rs);2246print_summary(" Object Copy", &_obj_copy);2247print_summary(" Termination", &_termination);2248print_summary(" Parallel Other", &_parallel_other);2249print_summary(" Clear CT", &_clear_ct);2250print_summary(" Other", &_other);2251}2252gclog_or_tty->cr();22532254gclog_or_tty->print_cr("MISC");2255print_summary_sd(" Stop World", &_all_stop_world_times_ms);2256print_summary_sd(" Yields", &_all_yield_times_ms);2257}22582259void TraceGen1TimeData::record_full_collection(double full_gc_time_ms) {2260if (TraceGen1Time) {2261_all_full_gc_times.add(full_gc_time_ms);2262}2263}22642265void TraceGen1TimeData::print() const {2266if (!TraceGen1Time) {2267return;2268}22692270if (_all_full_gc_times.num() > 0) {2271gclog_or_tty->print("\n%4d full_gcs: total time = %8.2f s",2272_all_full_gc_times.num(),2273_all_full_gc_times.sum() / 1000.0);2274gclog_or_tty->print_cr(" (avg = %8.2fms).", _all_full_gc_times.avg());2275gclog_or_tty->print_cr(" [std. dev = %8.2f ms, max = %8.2f ms]",2276_all_full_gc_times.sd(),2277_all_full_gc_times.maximum());2278}2279}228022812282