Path: blob/master/src/hotspot/share/gc/g1/g1CollectionSet.cpp
66644 views
/*1* Copyright (c) 2016, 2019, 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/g1/g1CollectedHeap.inline.hpp"26#include "gc/g1/g1CollectionSet.hpp"27#include "gc/g1/g1CollectionSetCandidates.hpp"28#include "gc/g1/g1CollectorState.hpp"29#include "gc/g1/g1HotCardCache.hpp"30#include "gc/g1/g1ParScanThreadState.hpp"31#include "gc/g1/g1Policy.hpp"32#include "gc/g1/heapRegion.inline.hpp"33#include "gc/g1/heapRegionRemSet.hpp"34#include "gc/g1/heapRegionSet.hpp"35#include "logging/logStream.hpp"36#include "runtime/orderAccess.hpp"37#include "utilities/debug.hpp"38#include "utilities/globalDefinitions.hpp"39#include "utilities/quickSort.hpp"4041G1CollectorState* G1CollectionSet::collector_state() const {42return _g1h->collector_state();43}4445G1GCPhaseTimes* G1CollectionSet::phase_times() {46return _policy->phase_times();47}4849double G1CollectionSet::predict_region_non_copy_time_ms(HeapRegion* hr) const {50return _policy->predict_region_non_copy_time_ms(hr, collector_state()->in_young_only_phase());51}5253G1CollectionSet::G1CollectionSet(G1CollectedHeap* g1h, G1Policy* policy) :54_g1h(g1h),55_policy(policy),56_candidates(NULL),57_eden_region_length(0),58_survivor_region_length(0),59_old_region_length(0),60_collection_set_regions(NULL),61_collection_set_cur_length(0),62_collection_set_max_length(0),63_num_optional_regions(0),64_bytes_used_before(0),65_recorded_rs_length(0),66_inc_build_state(Inactive),67_inc_part_start(0),68_inc_collection_set_stats(NULL),69_inc_bytes_used_before(0),70_inc_recorded_rs_length(0),71_inc_recorded_rs_length_diff(0),72_inc_predicted_non_copy_time_ms(0.0),73_inc_predicted_non_copy_time_ms_diff(0.0) {74}7576G1CollectionSet::~G1CollectionSet() {77FREE_C_HEAP_ARRAY(uint, _collection_set_regions);78FREE_C_HEAP_ARRAY(IncCollectionSetRegionStat, _inc_collection_set_stats);79free_optional_regions();80clear_candidates();81}8283void G1CollectionSet::init_region_lengths(uint eden_cset_region_length,84uint survivor_cset_region_length) {85assert_at_safepoint_on_vm_thread();8687_eden_region_length = eden_cset_region_length;88_survivor_region_length = survivor_cset_region_length;8990assert((size_t) young_region_length() == _collection_set_cur_length,91"Young region length %u should match collection set length " SIZE_FORMAT, young_region_length(), _collection_set_cur_length);9293_old_region_length = 0;94free_optional_regions();95}9697void G1CollectionSet::initialize(uint max_region_length) {98guarantee(_collection_set_regions == NULL, "Must only initialize once.");99_collection_set_max_length = max_region_length;100_collection_set_regions = NEW_C_HEAP_ARRAY(uint, max_region_length, mtGC);101_inc_collection_set_stats = NEW_C_HEAP_ARRAY(IncCollectionSetRegionStat, max_region_length, mtGC);102}103104void G1CollectionSet::free_optional_regions() {105_num_optional_regions = 0;106}107108void G1CollectionSet::clear_candidates() {109delete _candidates;110_candidates = NULL;111}112113bool G1CollectionSet::has_candidates() {114return _candidates != NULL && !_candidates->is_empty();115}116117void G1CollectionSet::set_recorded_rs_length(size_t rs_length) {118_recorded_rs_length = rs_length;119}120121// Add the heap region at the head of the non-incremental collection set122void G1CollectionSet::add_old_region(HeapRegion* hr) {123assert_at_safepoint_on_vm_thread();124125assert(_inc_build_state == Active,126"Precondition, actively building cset or adding optional later on");127assert(hr->is_old(), "the region should be old");128129assert(!hr->in_collection_set(), "should not already be in the collection set");130_g1h->register_old_region_with_region_attr(hr);131132_collection_set_regions[_collection_set_cur_length++] = hr->hrm_index();133assert(_collection_set_cur_length <= _collection_set_max_length, "Collection set now larger than maximum size.");134135_bytes_used_before += hr->used();136_recorded_rs_length += hr->rem_set()->occupied();137_old_region_length++;138139_g1h->old_set_remove(hr);140}141142void G1CollectionSet::add_optional_region(HeapRegion* hr) {143assert(hr->is_old(), "the region should be old");144assert(!hr->in_collection_set(), "should not already be in the CSet");145146_g1h->register_optional_region_with_region_attr(hr);147148hr->set_index_in_opt_cset(_num_optional_regions++);149}150151void G1CollectionSet::start_incremental_building() {152assert(_collection_set_cur_length == 0, "Collection set must be empty before starting a new collection set.");153assert(_inc_build_state == Inactive, "Precondition");154#ifdef ASSERT155for (size_t i = 0; i < _collection_set_max_length; i++) {156_inc_collection_set_stats[i].reset();157}158#endif159160_inc_bytes_used_before = 0;161162_inc_recorded_rs_length = 0;163_inc_recorded_rs_length_diff = 0;164_inc_predicted_non_copy_time_ms = 0.0;165_inc_predicted_non_copy_time_ms_diff = 0.0;166167update_incremental_marker();168}169170void G1CollectionSet::finalize_incremental_building() {171assert(_inc_build_state == Active, "Precondition");172assert(SafepointSynchronize::is_at_safepoint(), "should be at a safepoint");173174// The two "main" fields, _inc_recorded_rs_length and175// _inc_predicted_non_copy_time_ms, are updated by the thread176// that adds a new region to the CSet. Further updates by the177// concurrent refinement thread that samples the young RSet lengths178// are accumulated in the *_diff fields. Here we add the diffs to179// the "main" fields.180181_inc_recorded_rs_length += _inc_recorded_rs_length_diff;182_inc_predicted_non_copy_time_ms += _inc_predicted_non_copy_time_ms_diff;183184_inc_recorded_rs_length_diff = 0;185_inc_predicted_non_copy_time_ms_diff = 0.0;186}187188void G1CollectionSet::clear() {189assert_at_safepoint_on_vm_thread();190_collection_set_cur_length = 0;191}192193void G1CollectionSet::iterate(HeapRegionClosure* cl) const {194size_t len = _collection_set_cur_length;195OrderAccess::loadload();196197for (uint i = 0; i < len; i++) {198HeapRegion* r = _g1h->region_at(_collection_set_regions[i]);199bool result = cl->do_heap_region(r);200if (result) {201cl->set_incomplete();202return;203}204}205}206207void G1CollectionSet::par_iterate(HeapRegionClosure* cl,208HeapRegionClaimer* hr_claimer,209uint worker_id,210uint total_workers) const {211iterate_part_from(cl, hr_claimer, 0, cur_length(), worker_id, total_workers);212}213214void G1CollectionSet::iterate_optional(HeapRegionClosure* cl) const {215assert_at_safepoint();216217for (uint i = 0; i < _num_optional_regions; i++) {218HeapRegion* r = _candidates->at(i);219bool result = cl->do_heap_region(r);220guarantee(!result, "Must not cancel iteration");221}222}223224void G1CollectionSet::iterate_incremental_part_from(HeapRegionClosure* cl,225HeapRegionClaimer* hr_claimer,226uint worker_id,227uint total_workers) const {228iterate_part_from(cl, hr_claimer, _inc_part_start, increment_length(), worker_id, total_workers);229}230231void G1CollectionSet::iterate_part_from(HeapRegionClosure* cl,232HeapRegionClaimer* hr_claimer,233size_t offset,234size_t length,235uint worker_id,236uint total_workers) const {237assert_at_safepoint();238if (length == 0) {239return;240}241242size_t start_pos = (worker_id * length) / total_workers;243size_t cur_pos = start_pos;244245do {246uint region_idx = _collection_set_regions[cur_pos + offset];247if (hr_claimer == NULL || hr_claimer->claim_region(region_idx)) {248HeapRegion* r = _g1h->region_at(region_idx);249bool result = cl->do_heap_region(r);250guarantee(!result, "Must not cancel iteration");251}252253cur_pos++;254if (cur_pos == length) {255cur_pos = 0;256}257} while (cur_pos != start_pos);258}259260void G1CollectionSet::update_young_region_prediction(HeapRegion* hr,261size_t new_rs_length) {262// Update the CSet information that is dependent on the new RS length263assert(hr->is_young(), "Precondition");264assert(!SafepointSynchronize::is_at_safepoint(), "should not be at a safepoint");265266IncCollectionSetRegionStat* stat = &_inc_collection_set_stats[hr->hrm_index()];267268size_t old_rs_length = stat->_rs_length;269assert(old_rs_length <= new_rs_length,270"Remembered set decreased (changed from " SIZE_FORMAT " to " SIZE_FORMAT " region %u type %s)",271old_rs_length, new_rs_length, hr->hrm_index(), hr->get_short_type_str());272size_t rs_length_diff = new_rs_length - old_rs_length;273stat->_rs_length = new_rs_length;274_inc_recorded_rs_length_diff += rs_length_diff;275276double old_non_copy_time = stat->_non_copy_time_ms;277assert(old_non_copy_time >= 0.0, "Non copy time for region %u not initialized yet, is %.3f", hr->hrm_index(), old_non_copy_time);278double new_non_copy_time = predict_region_non_copy_time_ms(hr);279double non_copy_time_ms_diff = new_non_copy_time - old_non_copy_time;280281stat->_non_copy_time_ms = new_non_copy_time;282_inc_predicted_non_copy_time_ms_diff += non_copy_time_ms_diff;283}284285void G1CollectionSet::add_young_region_common(HeapRegion* hr) {286assert(hr->is_young(), "invariant");287assert(_inc_build_state == Active, "Precondition");288289// This routine is used when:290// * adding survivor regions to the incremental cset at the end of an291// evacuation pause or292// * adding the current allocation region to the incremental cset293// when it is retired.294// Therefore this routine may be called at a safepoint by the295// VM thread, or in-between safepoints by mutator threads (when296// retiring the current allocation region)297// We need to clear and set the cached recorded/cached collection set298// information in the heap region here (before the region gets added299// to the collection set). An individual heap region's cached values300// are calculated, aggregated with the policy collection set info,301// and cached in the heap region here (initially) and (subsequently)302// by the Young List sampling code.303// Ignore calls to this due to retirement during full gc.304305if (!_g1h->collector_state()->in_full_gc()) {306size_t rs_length = hr->rem_set()->occupied();307double non_copy_time = predict_region_non_copy_time_ms(hr);308309// Cache the values we have added to the aggregated information310// in the heap region in case we have to remove this region from311// the incremental collection set, or it is updated by the312// rset sampling code313314IncCollectionSetRegionStat* stat = &_inc_collection_set_stats[hr->hrm_index()];315stat->_rs_length = rs_length;316stat->_non_copy_time_ms = non_copy_time;317318_inc_recorded_rs_length += rs_length;319_inc_predicted_non_copy_time_ms += non_copy_time;320_inc_bytes_used_before += hr->used();321}322323assert(!hr->in_collection_set(), "invariant");324_g1h->register_young_region_with_region_attr(hr);325326// We use UINT_MAX as "invalid" marker in verification.327assert(_collection_set_cur_length < (UINT_MAX - 1),328"Collection set is too large with " SIZE_FORMAT " entries", _collection_set_cur_length);329hr->set_young_index_in_cset((uint)_collection_set_cur_length + 1);330331_collection_set_regions[_collection_set_cur_length] = hr->hrm_index();332// Concurrent readers must observe the store of the value in the array before an333// update to the length field.334OrderAccess::storestore();335_collection_set_cur_length++;336assert(_collection_set_cur_length <= _collection_set_max_length, "Collection set larger than maximum allowed.");337}338339void G1CollectionSet::add_survivor_regions(HeapRegion* hr) {340assert(hr->is_survivor(), "Must only add survivor regions, but is %s", hr->get_type_str());341add_young_region_common(hr);342}343344void G1CollectionSet::add_eden_region(HeapRegion* hr) {345assert(hr->is_eden(), "Must only add eden regions, but is %s", hr->get_type_str());346add_young_region_common(hr);347}348349#ifndef PRODUCT350class G1VerifyYoungAgesClosure : public HeapRegionClosure {351public:352bool _valid;353354G1VerifyYoungAgesClosure() : HeapRegionClosure(), _valid(true) { }355356virtual bool do_heap_region(HeapRegion* r) {357guarantee(r->is_young(), "Region must be young but is %s", r->get_type_str());358359if (!r->has_surv_rate_group()) {360log_error(gc, verify)("## encountered young region without surv_rate_group");361_valid = false;362}363364if (!r->has_valid_age_in_surv_rate()) {365log_error(gc, verify)("## encountered invalid age in young region");366_valid = false;367}368369return false;370}371372bool valid() const { return _valid; }373};374375bool G1CollectionSet::verify_young_ages() {376assert_at_safepoint_on_vm_thread();377378G1VerifyYoungAgesClosure cl;379iterate(&cl);380381if (!cl.valid()) {382LogStreamHandle(Error, gc, verify) log;383print(&log);384}385386return cl.valid();387}388389class G1PrintCollectionSetDetailClosure : public HeapRegionClosure {390outputStream* _st;391public:392G1PrintCollectionSetDetailClosure(outputStream* st) : HeapRegionClosure(), _st(st) { }393394virtual bool do_heap_region(HeapRegion* r) {395assert(r->in_collection_set(), "Region %u should be in collection set", r->hrm_index());396_st->print_cr(" " HR_FORMAT ", P: " PTR_FORMAT "N: " PTR_FORMAT ", age: %4d",397HR_FORMAT_PARAMS(r),398p2i(r->prev_top_at_mark_start()),399p2i(r->next_top_at_mark_start()),400r->has_surv_rate_group() ? r->age_in_surv_rate_group() : -1);401return false;402}403};404405void G1CollectionSet::print(outputStream* st) {406st->print_cr("\nCollection_set:");407408G1PrintCollectionSetDetailClosure cl(st);409iterate(&cl);410}411#endif // !PRODUCT412413double G1CollectionSet::finalize_young_part(double target_pause_time_ms, G1SurvivorRegions* survivors) {414Ticks start_time = Ticks::now();415416finalize_incremental_building();417418guarantee(target_pause_time_ms > 0.0,419"target_pause_time_ms = %1.6lf should be positive", target_pause_time_ms);420421size_t pending_cards = _policy->pending_cards_at_gc_start() + _g1h->hot_card_cache()->num_entries();422423log_trace(gc, ergo, cset)("Start choosing CSet. Pending cards: " SIZE_FORMAT " target pause time: %1.2fms",424pending_cards, target_pause_time_ms);425426// The young list is laid with the survivor regions from the previous427// pause are appended to the RHS of the young list, i.e.428// [Newly Young Regions ++ Survivors from last pause].429430uint eden_region_length = _g1h->eden_regions_count();431uint survivor_region_length = survivors->length();432init_region_lengths(eden_region_length, survivor_region_length);433434verify_young_cset_indices();435436// Clear the fields that point to the survivor list - they are all young now.437survivors->convert_to_eden();438439_bytes_used_before = _inc_bytes_used_before;440441// The number of recorded young regions is the incremental442// collection set's current size443set_recorded_rs_length(_inc_recorded_rs_length);444445double predicted_base_time_ms = _policy->predict_base_elapsed_time_ms(pending_cards);446double predicted_eden_time = _inc_predicted_non_copy_time_ms + _policy->predict_eden_copy_time_ms(eden_region_length);447double remaining_time_ms = MAX2(target_pause_time_ms - (predicted_base_time_ms + predicted_eden_time), 0.0);448449log_trace(gc, ergo, cset)("Added young regions to CSet. Eden: %u regions, Survivors: %u regions, "450"predicted eden time: %1.2fms, predicted base time: %1.2fms, target pause time: %1.2fms, remaining time: %1.2fms",451eden_region_length, survivor_region_length,452predicted_eden_time, predicted_base_time_ms, target_pause_time_ms, remaining_time_ms);453454phase_times()->record_young_cset_choice_time_ms((Ticks::now() - start_time).seconds() * 1000.0);455456return remaining_time_ms;457}458459static int compare_region_idx(const uint a, const uint b) {460if (a > b) {461return 1;462} else if (a == b) {463return 0;464} else {465return -1;466}467}468469void G1CollectionSet::finalize_old_part(double time_remaining_ms) {470double non_young_start_time_sec = os::elapsedTime();471472if (collector_state()->in_mixed_phase()) {473candidates()->verify();474475uint num_initial_old_regions;476uint num_optional_old_regions;477478_policy->calculate_old_collection_set_regions(candidates(),479time_remaining_ms,480num_initial_old_regions,481num_optional_old_regions);482483// Prepare initial old regions.484move_candidates_to_collection_set(num_initial_old_regions);485486// Prepare optional old regions for evacuation.487uint candidate_idx = candidates()->cur_idx();488for (uint i = 0; i < num_optional_old_regions; i++) {489add_optional_region(candidates()->at(candidate_idx + i));490}491492candidates()->verify();493}494495stop_incremental_building();496497double non_young_end_time_sec = os::elapsedTime();498phase_times()->record_non_young_cset_choice_time_ms((non_young_end_time_sec - non_young_start_time_sec) * 1000.0);499500QuickSort::sort(_collection_set_regions, _collection_set_cur_length, compare_region_idx, true);501}502503void G1CollectionSet::move_candidates_to_collection_set(uint num_old_candidate_regions) {504if (num_old_candidate_regions == 0) {505return;506}507uint candidate_idx = candidates()->cur_idx();508for (uint i = 0; i < num_old_candidate_regions; i++) {509HeapRegion* r = candidates()->at(candidate_idx + i);510// This potentially optional candidate region is going to be an actual collection511// set region. Clear cset marker.512_g1h->clear_region_attr(r);513add_old_region(r);514}515candidates()->remove(num_old_candidate_regions);516517candidates()->verify();518}519520void G1CollectionSet::finalize_initial_collection_set(double target_pause_time_ms, G1SurvivorRegions* survivor) {521double time_remaining_ms = finalize_young_part(target_pause_time_ms, survivor);522finalize_old_part(time_remaining_ms);523}524525bool G1CollectionSet::finalize_optional_for_evacuation(double remaining_pause_time) {526update_incremental_marker();527528uint num_selected_regions;529_policy->calculate_optional_collection_set_regions(candidates(),530_num_optional_regions,531remaining_pause_time,532num_selected_regions);533534move_candidates_to_collection_set(num_selected_regions);535536_num_optional_regions -= num_selected_regions;537538stop_incremental_building();539540_g1h->verify_region_attr_remset_update();541542return num_selected_regions > 0;543}544545void G1CollectionSet::abandon_optional_collection_set(G1ParScanThreadStateSet* pss) {546for (uint i = 0; i < _num_optional_regions; i++) {547HeapRegion* r = candidates()->at(candidates()->cur_idx() + i);548pss->record_unused_optional_region(r);549// Clear collection set marker and make sure that the remembered set information550// is correct as we still need it later.551_g1h->clear_region_attr(r);552_g1h->register_region_with_region_attr(r);553r->clear_index_in_opt_cset();554}555free_optional_regions();556557_g1h->verify_region_attr_remset_update();558}559560#ifdef ASSERT561class G1VerifyYoungCSetIndicesClosure : public HeapRegionClosure {562private:563size_t _young_length;564uint* _heap_region_indices;565public:566G1VerifyYoungCSetIndicesClosure(size_t young_length) : HeapRegionClosure(), _young_length(young_length) {567_heap_region_indices = NEW_C_HEAP_ARRAY(uint, young_length + 1, mtGC);568for (size_t i = 0; i < young_length + 1; i++) {569_heap_region_indices[i] = UINT_MAX;570}571}572~G1VerifyYoungCSetIndicesClosure() {573FREE_C_HEAP_ARRAY(int, _heap_region_indices);574}575576virtual bool do_heap_region(HeapRegion* r) {577const uint idx = r->young_index_in_cset();578579assert(idx > 0, "Young index must be set for all regions in the incremental collection set but is not for region %u.", r->hrm_index());580assert(idx <= _young_length, "Young cset index %u too large for region %u", idx, r->hrm_index());581582assert(_heap_region_indices[idx] == UINT_MAX,583"Index %d used by multiple regions, first use by region %u, second by region %u",584idx, _heap_region_indices[idx], r->hrm_index());585586_heap_region_indices[idx] = r->hrm_index();587588return false;589}590};591592void G1CollectionSet::verify_young_cset_indices() const {593assert_at_safepoint_on_vm_thread();594595G1VerifyYoungCSetIndicesClosure cl(_collection_set_cur_length);596iterate(&cl);597}598#endif599600601