Path: blob/master/src/hotspot/share/gc/g1/g1CollectionSet.cpp
40961 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}112113void G1CollectionSet::set_recorded_rs_length(size_t rs_length) {114_recorded_rs_length = rs_length;115}116117// Add the heap region at the head of the non-incremental collection set118void G1CollectionSet::add_old_region(HeapRegion* hr) {119assert_at_safepoint_on_vm_thread();120121assert(_inc_build_state == Active,122"Precondition, actively building cset or adding optional later on");123assert(hr->is_old(), "the region should be old");124125assert(!hr->in_collection_set(), "should not already be in the collection set");126_g1h->register_old_region_with_region_attr(hr);127128_collection_set_regions[_collection_set_cur_length++] = hr->hrm_index();129assert(_collection_set_cur_length <= _collection_set_max_length, "Collection set now larger than maximum size.");130131_bytes_used_before += hr->used();132_recorded_rs_length += hr->rem_set()->occupied();133_old_region_length++;134135_g1h->old_set_remove(hr);136}137138void G1CollectionSet::add_optional_region(HeapRegion* hr) {139assert(hr->is_old(), "the region should be old");140assert(!hr->in_collection_set(), "should not already be in the CSet");141142_g1h->register_optional_region_with_region_attr(hr);143144hr->set_index_in_opt_cset(_num_optional_regions++);145}146147void G1CollectionSet::start_incremental_building() {148assert(_collection_set_cur_length == 0, "Collection set must be empty before starting a new collection set.");149assert(_inc_build_state == Inactive, "Precondition");150#ifdef ASSERT151for (size_t i = 0; i < _collection_set_max_length; i++) {152_inc_collection_set_stats[i].reset();153}154#endif155156_inc_bytes_used_before = 0;157158_inc_recorded_rs_length = 0;159_inc_recorded_rs_length_diff = 0;160_inc_predicted_non_copy_time_ms = 0.0;161_inc_predicted_non_copy_time_ms_diff = 0.0;162163update_incremental_marker();164}165166void G1CollectionSet::finalize_incremental_building() {167assert(_inc_build_state == Active, "Precondition");168assert(SafepointSynchronize::is_at_safepoint(), "should be at a safepoint");169170// The two "main" fields, _inc_recorded_rs_length and171// _inc_predicted_non_copy_time_ms, are updated by the thread172// that adds a new region to the CSet. Further updates by the173// concurrent refinement thread that samples the young RSet lengths174// are accumulated in the *_diff fields. Here we add the diffs to175// the "main" fields.176177_inc_recorded_rs_length += _inc_recorded_rs_length_diff;178_inc_predicted_non_copy_time_ms += _inc_predicted_non_copy_time_ms_diff;179180_inc_recorded_rs_length_diff = 0;181_inc_predicted_non_copy_time_ms_diff = 0.0;182}183184void G1CollectionSet::clear() {185assert_at_safepoint_on_vm_thread();186_collection_set_cur_length = 0;187}188189void G1CollectionSet::iterate(HeapRegionClosure* cl) const {190size_t len = _collection_set_cur_length;191OrderAccess::loadload();192193for (uint i = 0; i < len; i++) {194HeapRegion* r = _g1h->region_at(_collection_set_regions[i]);195bool result = cl->do_heap_region(r);196if (result) {197cl->set_incomplete();198return;199}200}201}202203void G1CollectionSet::par_iterate(HeapRegionClosure* cl,204HeapRegionClaimer* hr_claimer,205uint worker_id,206uint total_workers) const {207iterate_part_from(cl, hr_claimer, 0, cur_length(), worker_id, total_workers);208}209210void G1CollectionSet::iterate_optional(HeapRegionClosure* cl) const {211assert_at_safepoint();212213for (uint i = 0; i < _num_optional_regions; i++) {214HeapRegion* r = _candidates->at(i);215bool result = cl->do_heap_region(r);216guarantee(!result, "Must not cancel iteration");217}218}219220void G1CollectionSet::iterate_incremental_part_from(HeapRegionClosure* cl,221HeapRegionClaimer* hr_claimer,222uint worker_id,223uint total_workers) const {224iterate_part_from(cl, hr_claimer, _inc_part_start, increment_length(), worker_id, total_workers);225}226227void G1CollectionSet::iterate_part_from(HeapRegionClosure* cl,228HeapRegionClaimer* hr_claimer,229size_t offset,230size_t length,231uint worker_id,232uint total_workers) const {233assert_at_safepoint();234if (length == 0) {235return;236}237238size_t start_pos = (worker_id * length) / total_workers;239size_t cur_pos = start_pos;240241do {242uint region_idx = _collection_set_regions[cur_pos + offset];243if (hr_claimer == NULL || hr_claimer->claim_region(region_idx)) {244HeapRegion* r = _g1h->region_at(region_idx);245bool result = cl->do_heap_region(r);246guarantee(!result, "Must not cancel iteration");247}248249cur_pos++;250if (cur_pos == length) {251cur_pos = 0;252}253} while (cur_pos != start_pos);254}255256void G1CollectionSet::update_young_region_prediction(HeapRegion* hr,257size_t new_rs_length) {258// Update the CSet information that is dependent on the new RS length259assert(hr->is_young(), "Precondition");260assert(!SafepointSynchronize::is_at_safepoint(), "should not be at a safepoint");261262IncCollectionSetRegionStat* stat = &_inc_collection_set_stats[hr->hrm_index()];263264size_t old_rs_length = stat->_rs_length;265assert(old_rs_length <= new_rs_length,266"Remembered set decreased (changed from " SIZE_FORMAT " to " SIZE_FORMAT " region %u type %s)",267old_rs_length, new_rs_length, hr->hrm_index(), hr->get_short_type_str());268size_t rs_length_diff = new_rs_length - old_rs_length;269stat->_rs_length = new_rs_length;270_inc_recorded_rs_length_diff += rs_length_diff;271272double old_non_copy_time = stat->_non_copy_time_ms;273assert(old_non_copy_time >= 0.0, "Non copy time for region %u not initialized yet, is %.3f", hr->hrm_index(), old_non_copy_time);274double new_non_copy_time = predict_region_non_copy_time_ms(hr);275double non_copy_time_ms_diff = new_non_copy_time - old_non_copy_time;276277stat->_non_copy_time_ms = new_non_copy_time;278_inc_predicted_non_copy_time_ms_diff += non_copy_time_ms_diff;279}280281void G1CollectionSet::add_young_region_common(HeapRegion* hr) {282assert(hr->is_young(), "invariant");283assert(_inc_build_state == Active, "Precondition");284285// This routine is used when:286// * adding survivor regions to the incremental cset at the end of an287// evacuation pause or288// * adding the current allocation region to the incremental cset289// when it is retired.290// Therefore this routine may be called at a safepoint by the291// VM thread, or in-between safepoints by mutator threads (when292// retiring the current allocation region)293// We need to clear and set the cached recorded/cached collection set294// information in the heap region here (before the region gets added295// to the collection set). An individual heap region's cached values296// are calculated, aggregated with the policy collection set info,297// and cached in the heap region here (initially) and (subsequently)298// by the Young List sampling code.299// Ignore calls to this due to retirement during full gc.300301if (!_g1h->collector_state()->in_full_gc()) {302size_t rs_length = hr->rem_set()->occupied();303double non_copy_time = predict_region_non_copy_time_ms(hr);304305// Cache the values we have added to the aggregated information306// in the heap region in case we have to remove this region from307// the incremental collection set, or it is updated by the308// rset sampling code309310IncCollectionSetRegionStat* stat = &_inc_collection_set_stats[hr->hrm_index()];311stat->_rs_length = rs_length;312stat->_non_copy_time_ms = non_copy_time;313314_inc_recorded_rs_length += rs_length;315_inc_predicted_non_copy_time_ms += non_copy_time;316_inc_bytes_used_before += hr->used();317}318319assert(!hr->in_collection_set(), "invariant");320_g1h->register_young_region_with_region_attr(hr);321322// We use UINT_MAX as "invalid" marker in verification.323assert(_collection_set_cur_length < (UINT_MAX - 1),324"Collection set is too large with " SIZE_FORMAT " entries", _collection_set_cur_length);325hr->set_young_index_in_cset((uint)_collection_set_cur_length + 1);326327_collection_set_regions[_collection_set_cur_length] = hr->hrm_index();328// Concurrent readers must observe the store of the value in the array before an329// update to the length field.330OrderAccess::storestore();331_collection_set_cur_length++;332assert(_collection_set_cur_length <= _collection_set_max_length, "Collection set larger than maximum allowed.");333}334335void G1CollectionSet::add_survivor_regions(HeapRegion* hr) {336assert(hr->is_survivor(), "Must only add survivor regions, but is %s", hr->get_type_str());337add_young_region_common(hr);338}339340void G1CollectionSet::add_eden_region(HeapRegion* hr) {341assert(hr->is_eden(), "Must only add eden regions, but is %s", hr->get_type_str());342add_young_region_common(hr);343}344345#ifndef PRODUCT346class G1VerifyYoungAgesClosure : public HeapRegionClosure {347public:348bool _valid;349350G1VerifyYoungAgesClosure() : HeapRegionClosure(), _valid(true) { }351352virtual bool do_heap_region(HeapRegion* r) {353guarantee(r->is_young(), "Region must be young but is %s", r->get_type_str());354355if (!r->has_surv_rate_group()) {356log_error(gc, verify)("## encountered young region without surv_rate_group");357_valid = false;358}359360if (!r->has_valid_age_in_surv_rate()) {361log_error(gc, verify)("## encountered invalid age in young region");362_valid = false;363}364365return false;366}367368bool valid() const { return _valid; }369};370371bool G1CollectionSet::verify_young_ages() {372assert_at_safepoint_on_vm_thread();373374G1VerifyYoungAgesClosure cl;375iterate(&cl);376377if (!cl.valid()) {378LogStreamHandle(Error, gc, verify) log;379print(&log);380}381382return cl.valid();383}384385class G1PrintCollectionSetDetailClosure : public HeapRegionClosure {386outputStream* _st;387public:388G1PrintCollectionSetDetailClosure(outputStream* st) : HeapRegionClosure(), _st(st) { }389390virtual bool do_heap_region(HeapRegion* r) {391assert(r->in_collection_set(), "Region %u should be in collection set", r->hrm_index());392_st->print_cr(" " HR_FORMAT ", P: " PTR_FORMAT "N: " PTR_FORMAT ", age: %4d",393HR_FORMAT_PARAMS(r),394p2i(r->prev_top_at_mark_start()),395p2i(r->next_top_at_mark_start()),396r->has_surv_rate_group() ? r->age_in_surv_rate_group() : -1);397return false;398}399};400401void G1CollectionSet::print(outputStream* st) {402st->print_cr("\nCollection_set:");403404G1PrintCollectionSetDetailClosure cl(st);405iterate(&cl);406}407#endif // !PRODUCT408409double G1CollectionSet::finalize_young_part(double target_pause_time_ms, G1SurvivorRegions* survivors) {410Ticks start_time = Ticks::now();411412finalize_incremental_building();413414guarantee(target_pause_time_ms > 0.0,415"target_pause_time_ms = %1.6lf should be positive", target_pause_time_ms);416417size_t pending_cards = _policy->pending_cards_at_gc_start() + _g1h->hot_card_cache()->num_entries();418419log_trace(gc, ergo, cset)("Start choosing CSet. Pending cards: " SIZE_FORMAT " target pause time: %1.2fms",420pending_cards, target_pause_time_ms);421422// The young list is laid with the survivor regions from the previous423// pause are appended to the RHS of the young list, i.e.424// [Newly Young Regions ++ Survivors from last pause].425426uint eden_region_length = _g1h->eden_regions_count();427uint survivor_region_length = survivors->length();428init_region_lengths(eden_region_length, survivor_region_length);429430verify_young_cset_indices();431432// Clear the fields that point to the survivor list - they are all young now.433survivors->convert_to_eden();434435_bytes_used_before = _inc_bytes_used_before;436437// The number of recorded young regions is the incremental438// collection set's current size439set_recorded_rs_length(_inc_recorded_rs_length);440441double predicted_base_time_ms = _policy->predict_base_elapsed_time_ms(pending_cards);442double predicted_eden_time = _inc_predicted_non_copy_time_ms + _policy->predict_eden_copy_time_ms(eden_region_length);443double remaining_time_ms = MAX2(target_pause_time_ms - (predicted_base_time_ms + predicted_eden_time), 0.0);444445log_trace(gc, ergo, cset)("Added young regions to CSet. Eden: %u regions, Survivors: %u regions, "446"predicted eden time: %1.2fms, predicted base time: %1.2fms, target pause time: %1.2fms, remaining time: %1.2fms",447eden_region_length, survivor_region_length,448predicted_eden_time, predicted_base_time_ms, target_pause_time_ms, remaining_time_ms);449450phase_times()->record_young_cset_choice_time_ms((Ticks::now() - start_time).seconds() * 1000.0);451452return remaining_time_ms;453}454455static int compare_region_idx(const uint a, const uint b) {456if (a > b) {457return 1;458} else if (a == b) {459return 0;460} else {461return -1;462}463}464465void G1CollectionSet::finalize_old_part(double time_remaining_ms) {466double non_young_start_time_sec = os::elapsedTime();467468if (collector_state()->in_mixed_phase()) {469candidates()->verify();470471uint num_initial_old_regions;472uint num_optional_old_regions;473474_policy->calculate_old_collection_set_regions(candidates(),475time_remaining_ms,476num_initial_old_regions,477num_optional_old_regions);478479// Prepare initial old regions.480move_candidates_to_collection_set(num_initial_old_regions);481482// Prepare optional old regions for evacuation.483uint candidate_idx = candidates()->cur_idx();484for (uint i = 0; i < num_optional_old_regions; i++) {485add_optional_region(candidates()->at(candidate_idx + i));486}487488candidates()->verify();489}490491stop_incremental_building();492493double non_young_end_time_sec = os::elapsedTime();494phase_times()->record_non_young_cset_choice_time_ms((non_young_end_time_sec - non_young_start_time_sec) * 1000.0);495496QuickSort::sort(_collection_set_regions, _collection_set_cur_length, compare_region_idx, true);497}498499void G1CollectionSet::move_candidates_to_collection_set(uint num_old_candidate_regions) {500if (num_old_candidate_regions == 0) {501return;502}503uint candidate_idx = candidates()->cur_idx();504for (uint i = 0; i < num_old_candidate_regions; i++) {505HeapRegion* r = candidates()->at(candidate_idx + i);506// This potentially optional candidate region is going to be an actual collection507// set region. Clear cset marker.508_g1h->clear_region_attr(r);509add_old_region(r);510}511candidates()->remove(num_old_candidate_regions);512513candidates()->verify();514}515516void G1CollectionSet::finalize_initial_collection_set(double target_pause_time_ms, G1SurvivorRegions* survivor) {517double time_remaining_ms = finalize_young_part(target_pause_time_ms, survivor);518finalize_old_part(time_remaining_ms);519}520521bool G1CollectionSet::finalize_optional_for_evacuation(double remaining_pause_time) {522update_incremental_marker();523524uint num_selected_regions;525_policy->calculate_optional_collection_set_regions(candidates(),526_num_optional_regions,527remaining_pause_time,528num_selected_regions);529530move_candidates_to_collection_set(num_selected_regions);531532_num_optional_regions -= num_selected_regions;533534stop_incremental_building();535536_g1h->verify_region_attr_remset_update();537538return num_selected_regions > 0;539}540541void G1CollectionSet::abandon_optional_collection_set(G1ParScanThreadStateSet* pss) {542for (uint i = 0; i < _num_optional_regions; i++) {543HeapRegion* r = candidates()->at(candidates()->cur_idx() + i);544pss->record_unused_optional_region(r);545// Clear collection set marker and make sure that the remembered set information546// is correct as we still need it later.547_g1h->clear_region_attr(r);548_g1h->register_region_with_region_attr(r);549r->clear_index_in_opt_cset();550}551free_optional_regions();552553_g1h->verify_region_attr_remset_update();554}555556#ifdef ASSERT557class G1VerifyYoungCSetIndicesClosure : public HeapRegionClosure {558private:559size_t _young_length;560uint* _heap_region_indices;561public:562G1VerifyYoungCSetIndicesClosure(size_t young_length) : HeapRegionClosure(), _young_length(young_length) {563_heap_region_indices = NEW_C_HEAP_ARRAY(uint, young_length + 1, mtGC);564for (size_t i = 0; i < young_length + 1; i++) {565_heap_region_indices[i] = UINT_MAX;566}567}568~G1VerifyYoungCSetIndicesClosure() {569FREE_C_HEAP_ARRAY(int, _heap_region_indices);570}571572virtual bool do_heap_region(HeapRegion* r) {573const uint idx = r->young_index_in_cset();574575assert(idx > 0, "Young index must be set for all regions in the incremental collection set but is not for region %u.", r->hrm_index());576assert(idx <= _young_length, "Young cset index %u too large for region %u", idx, r->hrm_index());577578assert(_heap_region_indices[idx] == UINT_MAX,579"Index %d used by multiple regions, first use by region %u, second by region %u",580idx, _heap_region_indices[idx], r->hrm_index());581582_heap_region_indices[idx] = r->hrm_index();583584return false;585}586};587588void G1CollectionSet::verify_young_cset_indices() const {589assert_at_safepoint_on_vm_thread();590591G1VerifyYoungCSetIndicesClosure cl(_collection_set_cur_length);592iterate(&cl);593}594#endif595596597