Path: blob/master/src/hotspot/share/gc/g1/g1CollectedHeap.cpp
40957 views
/*1* Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/classLoaderDataGraph.hpp"26#include "classfile/metadataOnStackMark.hpp"27#include "classfile/stringTable.hpp"28#include "code/codeCache.hpp"29#include "code/icBuffer.hpp"30#include "compiler/oopMap.hpp"31#include "gc/g1/g1Allocator.inline.hpp"32#include "gc/g1/g1Arguments.hpp"33#include "gc/g1/g1BarrierSet.hpp"34#include "gc/g1/g1CollectedHeap.inline.hpp"35#include "gc/g1/g1CollectionSet.hpp"36#include "gc/g1/g1CollectorState.hpp"37#include "gc/g1/g1ConcurrentRefine.hpp"38#include "gc/g1/g1ConcurrentRefineThread.hpp"39#include "gc/g1/g1ConcurrentMarkThread.inline.hpp"40#include "gc/g1/g1DirtyCardQueue.hpp"41#include "gc/g1/g1EvacStats.inline.hpp"42#include "gc/g1/g1FullCollector.hpp"43#include "gc/g1/g1GCParPhaseTimesTracker.hpp"44#include "gc/g1/g1GCPhaseTimes.hpp"45#include "gc/g1/g1GCPauseType.hpp"46#include "gc/g1/g1HeapSizingPolicy.hpp"47#include "gc/g1/g1HeapTransition.hpp"48#include "gc/g1/g1HeapVerifier.hpp"49#include "gc/g1/g1HotCardCache.hpp"50#include "gc/g1/g1InitLogger.hpp"51#include "gc/g1/g1MemoryPool.hpp"52#include "gc/g1/g1OopClosures.inline.hpp"53#include "gc/g1/g1ParallelCleaning.hpp"54#include "gc/g1/g1ParScanThreadState.inline.hpp"55#include "gc/g1/g1PeriodicGCTask.hpp"56#include "gc/g1/g1Policy.hpp"57#include "gc/g1/g1RedirtyCardsQueue.hpp"58#include "gc/g1/g1RegionToSpaceMapper.hpp"59#include "gc/g1/g1RemSet.hpp"60#include "gc/g1/g1RootClosures.hpp"61#include "gc/g1/g1RootProcessor.hpp"62#include "gc/g1/g1SATBMarkQueueSet.hpp"63#include "gc/g1/g1ThreadLocalData.hpp"64#include "gc/g1/g1Trace.hpp"65#include "gc/g1/g1ServiceThread.hpp"66#include "gc/g1/g1UncommitRegionTask.hpp"67#include "gc/g1/g1VMOperations.hpp"68#include "gc/g1/g1YoungGCPostEvacuateTasks.hpp"69#include "gc/g1/heapRegion.inline.hpp"70#include "gc/g1/heapRegionRemSet.hpp"71#include "gc/g1/heapRegionSet.inline.hpp"72#include "gc/shared/concurrentGCBreakpoints.hpp"73#include "gc/shared/gcBehaviours.hpp"74#include "gc/shared/gcHeapSummary.hpp"75#include "gc/shared/gcId.hpp"76#include "gc/shared/gcLocker.hpp"77#include "gc/shared/gcTimer.hpp"78#include "gc/shared/gcTraceTime.inline.hpp"79#include "gc/shared/generationSpec.hpp"80#include "gc/shared/isGCActiveMark.hpp"81#include "gc/shared/locationPrinter.inline.hpp"82#include "gc/shared/oopStorageParState.hpp"83#include "gc/shared/preservedMarks.inline.hpp"84#include "gc/shared/suspendibleThreadSet.hpp"85#include "gc/shared/referenceProcessor.inline.hpp"86#include "gc/shared/taskTerminator.hpp"87#include "gc/shared/taskqueue.inline.hpp"88#include "gc/shared/tlab_globals.hpp"89#include "gc/shared/weakProcessor.inline.hpp"90#include "gc/shared/workerPolicy.hpp"91#include "logging/log.hpp"92#include "memory/allocation.hpp"93#include "memory/iterator.hpp"94#include "memory/heapInspection.hpp"95#include "memory/metaspaceUtils.hpp"96#include "memory/resourceArea.hpp"97#include "memory/universe.hpp"98#include "oops/access.inline.hpp"99#include "oops/compressedOops.inline.hpp"100#include "oops/oop.inline.hpp"101#include "runtime/atomic.hpp"102#include "runtime/handles.inline.hpp"103#include "runtime/init.hpp"104#include "runtime/java.hpp"105#include "runtime/orderAccess.hpp"106#include "runtime/threadSMR.hpp"107#include "runtime/vmThread.hpp"108#include "utilities/align.hpp"109#include "utilities/autoRestore.hpp"110#include "utilities/bitMap.inline.hpp"111#include "utilities/globalDefinitions.hpp"112#include "utilities/stack.inline.hpp"113114size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;115116// INVARIANTS/NOTES117//118// All allocation activity covered by the G1CollectedHeap interface is119// serialized by acquiring the HeapLock. This happens in mem_allocate120// and allocate_new_tlab, which are the "entry" points to the121// allocation code from the rest of the JVM. (Note that this does not122// apply to TLAB allocation, which is not part of this interface: it123// is done by clients of this interface.)124125void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) {126HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions);127}128129void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) {130// The from card cache is not the memory that is actually committed. So we cannot131// take advantage of the zero_filled parameter.132reset_from_card_cache(start_idx, num_regions);133}134135Tickspan G1CollectedHeap::run_task_timed(AbstractGangTask* task) {136Ticks start = Ticks::now();137workers()->run_task(task);138return Ticks::now() - start;139}140141void G1CollectedHeap::run_batch_task(G1BatchedGangTask* cl) {142uint num_workers = MAX2(1u, MIN2(cl->num_workers_estimate(), workers()->active_workers()));143cl->set_max_workers(num_workers);144workers()->run_task(cl, num_workers);145}146147HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index,148MemRegion mr) {149return new HeapRegion(hrs_index, bot(), mr);150}151152// Private methods.153154HeapRegion* G1CollectedHeap::new_region(size_t word_size,155HeapRegionType type,156bool do_expand,157uint node_index) {158assert(!is_humongous(word_size) || word_size <= HeapRegion::GrainWords,159"the only time we use this to allocate a humongous region is "160"when we are allocating a single humongous region");161162HeapRegion* res = _hrm.allocate_free_region(type, node_index);163164if (res == NULL && do_expand && _expand_heap_after_alloc_failure) {165// Currently, only attempts to allocate GC alloc regions set166// do_expand to true. So, we should only reach here during a167// safepoint. If this assumption changes we might have to168// reconsider the use of _expand_heap_after_alloc_failure.169assert(SafepointSynchronize::is_at_safepoint(), "invariant");170171log_debug(gc, ergo, heap)("Attempt heap expansion (region allocation request failed). Allocation request: " SIZE_FORMAT "B",172word_size * HeapWordSize);173174assert(word_size * HeapWordSize < HeapRegion::GrainBytes,175"This kind of expansion should never be more than one region. Size: " SIZE_FORMAT,176word_size * HeapWordSize);177if (expand_single_region(node_index)) {178// Given that expand_single_region() succeeded in expanding the heap, and we179// always expand the heap by an amount aligned to the heap180// region size, the free list should in theory not be empty.181// In either case allocate_free_region() will check for NULL.182res = _hrm.allocate_free_region(type, node_index);183} else {184_expand_heap_after_alloc_failure = false;185}186}187return res;188}189190HeapWord*191G1CollectedHeap::humongous_obj_allocate_initialize_regions(HeapRegion* first_hr,192uint num_regions,193size_t word_size) {194assert(first_hr != NULL, "pre-condition");195assert(is_humongous(word_size), "word_size should be humongous");196assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");197198// Index of last region in the series.199uint first = first_hr->hrm_index();200uint last = first + num_regions - 1;201202// We need to initialize the region(s) we just discovered. This is203// a bit tricky given that it can happen concurrently with204// refinement threads refining cards on these regions and205// potentially wanting to refine the BOT as they are scanning206// those cards (this can happen shortly after a cleanup; see CR207// 6991377). So we have to set up the region(s) carefully and in208// a specific order.209210// The word size sum of all the regions we will allocate.211size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;212assert(word_size <= word_size_sum, "sanity");213214// The passed in hr will be the "starts humongous" region. The header215// of the new object will be placed at the bottom of this region.216HeapWord* new_obj = first_hr->bottom();217// This will be the new top of the new object.218HeapWord* obj_top = new_obj + word_size;219220// First, we need to zero the header of the space that we will be221// allocating. When we update top further down, some refinement222// threads might try to scan the region. By zeroing the header we223// ensure that any thread that will try to scan the region will224// come across the zero klass word and bail out.225//226// NOTE: It would not have been correct to have used227// CollectedHeap::fill_with_object() and make the space look like228// an int array. The thread that is doing the allocation will229// later update the object header to a potentially different array230// type and, for a very short period of time, the klass and length231// fields will be inconsistent. This could cause a refinement232// thread to calculate the object size incorrectly.233Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);234235// Next, pad out the unused tail of the last region with filler236// objects, for improved usage accounting.237// How many words we use for filler objects.238size_t word_fill_size = word_size_sum - word_size;239240// How many words memory we "waste" which cannot hold a filler object.241size_t words_not_fillable = 0;242243if (word_fill_size >= min_fill_size()) {244fill_with_objects(obj_top, word_fill_size);245} else if (word_fill_size > 0) {246// We have space to fill, but we cannot fit an object there.247words_not_fillable = word_fill_size;248word_fill_size = 0;249}250251// We will set up the first region as "starts humongous". This252// will also update the BOT covering all the regions to reflect253// that there is a single object that starts at the bottom of the254// first region.255first_hr->set_starts_humongous(obj_top, word_fill_size);256_policy->remset_tracker()->update_at_allocate(first_hr);257// Then, if there are any, we will set up the "continues258// humongous" regions.259HeapRegion* hr = NULL;260for (uint i = first + 1; i <= last; ++i) {261hr = region_at(i);262hr->set_continues_humongous(first_hr);263_policy->remset_tracker()->update_at_allocate(hr);264}265266// Up to this point no concurrent thread would have been able to267// do any scanning on any region in this series. All the top268// fields still point to bottom, so the intersection between269// [bottom,top] and [card_start,card_end] will be empty. Before we270// update the top fields, we'll do a storestore to make sure that271// no thread sees the update to top before the zeroing of the272// object header and the BOT initialization.273OrderAccess::storestore();274275// Now, we will update the top fields of the "continues humongous"276// regions except the last one.277for (uint i = first; i < last; ++i) {278hr = region_at(i);279hr->set_top(hr->end());280}281282hr = region_at(last);283// If we cannot fit a filler object, we must set top to the end284// of the humongous object, otherwise we cannot iterate the heap285// and the BOT will not be complete.286hr->set_top(hr->end() - words_not_fillable);287288assert(hr->bottom() < obj_top && obj_top <= hr->end(),289"obj_top should be in last region");290291_verifier->check_bitmaps("Humongous Region Allocation", first_hr);292293assert(words_not_fillable == 0 ||294first_hr->bottom() + word_size_sum - words_not_fillable == hr->top(),295"Miscalculation in humongous allocation");296297increase_used((word_size_sum - words_not_fillable) * HeapWordSize);298299for (uint i = first; i <= last; ++i) {300hr = region_at(i);301_humongous_set.add(hr);302_hr_printer.alloc(hr);303}304305return new_obj;306}307308size_t G1CollectedHeap::humongous_obj_size_in_regions(size_t word_size) {309assert(is_humongous(word_size), "Object of size " SIZE_FORMAT " must be humongous here", word_size);310return align_up(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords;311}312313// If could fit into free regions w/o expansion, try.314// Otherwise, if can expand, do so.315// Otherwise, if using ex regions might help, try with ex given back.316HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {317assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);318319_verifier->verify_region_sets_optional();320321uint obj_regions = (uint) humongous_obj_size_in_regions(word_size);322323// Policy: First try to allocate a humongous object in the free list.324HeapRegion* humongous_start = _hrm.allocate_humongous(obj_regions);325if (humongous_start == NULL) {326// Policy: We could not find enough regions for the humongous object in the327// free list. Look through the heap to find a mix of free and uncommitted regions.328// If so, expand the heap and allocate the humongous object.329humongous_start = _hrm.expand_and_allocate_humongous(obj_regions);330if (humongous_start != NULL) {331// We managed to find a region by expanding the heap.332log_debug(gc, ergo, heap)("Heap expansion (humongous allocation request). Allocation request: " SIZE_FORMAT "B",333word_size * HeapWordSize);334policy()->record_new_heap_size(num_regions());335} else {336// Policy: Potentially trigger a defragmentation GC.337}338}339340HeapWord* result = NULL;341if (humongous_start != NULL) {342result = humongous_obj_allocate_initialize_regions(humongous_start, obj_regions, word_size);343assert(result != NULL, "it should always return a valid result");344345// A successful humongous object allocation changes the used space346// information of the old generation so we need to recalculate the347// sizes and update the jstat counters here.348g1mm()->update_sizes();349}350351_verifier->verify_region_sets_optional();352353return result;354}355356HeapWord* G1CollectedHeap::allocate_new_tlab(size_t min_size,357size_t requested_size,358size_t* actual_size) {359assert_heap_not_locked_and_not_at_safepoint();360assert(!is_humongous(requested_size), "we do not allow humongous TLABs");361362return attempt_allocation(min_size, requested_size, actual_size);363}364365HeapWord*366G1CollectedHeap::mem_allocate(size_t word_size,367bool* gc_overhead_limit_was_exceeded) {368assert_heap_not_locked_and_not_at_safepoint();369370if (is_humongous(word_size)) {371return attempt_allocation_humongous(word_size);372}373size_t dummy = 0;374return attempt_allocation(word_size, word_size, &dummy);375}376377HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size) {378ResourceMark rm; // For retrieving the thread names in log messages.379380// Make sure you read the note in attempt_allocation_humongous().381382assert_heap_not_locked_and_not_at_safepoint();383assert(!is_humongous(word_size), "attempt_allocation_slow() should not "384"be called for humongous allocation requests");385386// We should only get here after the first-level allocation attempt387// (attempt_allocation()) failed to allocate.388389// We will loop until a) we manage to successfully perform the390// allocation or b) we successfully schedule a collection which391// fails to perform the allocation. b) is the only case when we'll392// return NULL.393HeapWord* result = NULL;394for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {395bool should_try_gc;396uint gc_count_before;397398{399MutexLocker x(Heap_lock);400result = _allocator->attempt_allocation_locked(word_size);401if (result != NULL) {402return result;403}404405// If the GCLocker is active and we are bound for a GC, try expanding young gen.406// This is different to when only GCLocker::needs_gc() is set: try to avoid407// waiting because the GCLocker is active to not wait too long.408if (GCLocker::is_active_and_needs_gc() && policy()->can_expand_young_list()) {409// No need for an ergo message here, can_expand_young_list() does this when410// it returns true.411result = _allocator->attempt_allocation_force(word_size);412if (result != NULL) {413return result;414}415}416// Only try a GC if the GCLocker does not signal the need for a GC. Wait until417// the GCLocker initiated GC has been performed and then retry. This includes418// the case when the GC Locker is not active but has not been performed.419should_try_gc = !GCLocker::needs_gc();420// Read the GC count while still holding the Heap_lock.421gc_count_before = total_collections();422}423424if (should_try_gc) {425bool succeeded;426result = do_collection_pause(word_size, gc_count_before, &succeeded,427GCCause::_g1_inc_collection_pause);428if (result != NULL) {429assert(succeeded, "only way to get back a non-NULL result");430log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,431Thread::current()->name(), p2i(result));432return result;433}434435if (succeeded) {436// We successfully scheduled a collection which failed to allocate. No437// point in trying to allocate further. We'll just return NULL.438log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "439SIZE_FORMAT " words", Thread::current()->name(), word_size);440return NULL;441}442log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT " words",443Thread::current()->name(), word_size);444} else {445// Failed to schedule a collection.446if (gclocker_retry_count > GCLockerRetryAllocationCount) {447log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "448SIZE_FORMAT " words", Thread::current()->name(), word_size);449return NULL;450}451log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());452// The GCLocker is either active or the GCLocker initiated453// GC has not yet been performed. Stall until it is and454// then retry the allocation.455GCLocker::stall_until_clear();456gclocker_retry_count += 1;457}458459// We can reach here if we were unsuccessful in scheduling a460// collection (because another thread beat us to it) or if we were461// stalled due to the GC locker. In either can we should retry the462// allocation attempt in case another thread successfully463// performed a collection and reclaimed enough space. We do the464// first attempt (without holding the Heap_lock) here and the465// follow-on attempt will be at the start of the next loop466// iteration (after taking the Heap_lock).467size_t dummy = 0;468result = _allocator->attempt_allocation(word_size, word_size, &dummy);469if (result != NULL) {470return result;471}472473// Give a warning if we seem to be looping forever.474if ((QueuedAllocationWarningCount > 0) &&475(try_count % QueuedAllocationWarningCount == 0)) {476log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",477Thread::current()->name(), try_count, word_size);478}479}480481ShouldNotReachHere();482return NULL;483}484485void G1CollectedHeap::begin_archive_alloc_range(bool open) {486assert_at_safepoint_on_vm_thread();487if (_archive_allocator == NULL) {488_archive_allocator = G1ArchiveAllocator::create_allocator(this, open);489}490}491492bool G1CollectedHeap::is_archive_alloc_too_large(size_t word_size) {493// Allocations in archive regions cannot be of a size that would be considered494// humongous even for a minimum-sized region, because G1 region sizes/boundaries495// may be different at archive-restore time.496return word_size >= humongous_threshold_for(HeapRegion::min_region_size_in_words());497}498499HeapWord* G1CollectedHeap::archive_mem_allocate(size_t word_size) {500assert_at_safepoint_on_vm_thread();501assert(_archive_allocator != NULL, "_archive_allocator not initialized");502if (is_archive_alloc_too_large(word_size)) {503return NULL;504}505return _archive_allocator->archive_mem_allocate(word_size);506}507508void G1CollectedHeap::end_archive_alloc_range(GrowableArray<MemRegion>* ranges,509size_t end_alignment_in_bytes) {510assert_at_safepoint_on_vm_thread();511assert(_archive_allocator != NULL, "_archive_allocator not initialized");512513// Call complete_archive to do the real work, filling in the MemRegion514// array with the archive regions.515_archive_allocator->complete_archive(ranges, end_alignment_in_bytes);516delete _archive_allocator;517_archive_allocator = NULL;518}519520bool G1CollectedHeap::check_archive_addresses(MemRegion* ranges, size_t count) {521assert(ranges != NULL, "MemRegion array NULL");522assert(count != 0, "No MemRegions provided");523MemRegion reserved = _hrm.reserved();524for (size_t i = 0; i < count; i++) {525if (!reserved.contains(ranges[i].start()) || !reserved.contains(ranges[i].last())) {526return false;527}528}529return true;530}531532bool G1CollectedHeap::alloc_archive_regions(MemRegion* ranges,533size_t count,534bool open) {535assert(!is_init_completed(), "Expect to be called at JVM init time");536assert(ranges != NULL, "MemRegion array NULL");537assert(count != 0, "No MemRegions provided");538MutexLocker x(Heap_lock);539540MemRegion reserved = _hrm.reserved();541HeapWord* prev_last_addr = NULL;542HeapRegion* prev_last_region = NULL;543544// Temporarily disable pretouching of heap pages. This interface is used545// when mmap'ing archived heap data in, so pre-touching is wasted.546FlagSetting fs(AlwaysPreTouch, false);547548// For each specified MemRegion range, allocate the corresponding G1549// regions and mark them as archive regions. We expect the ranges550// in ascending starting address order, without overlap.551for (size_t i = 0; i < count; i++) {552MemRegion curr_range = ranges[i];553HeapWord* start_address = curr_range.start();554size_t word_size = curr_range.word_size();555HeapWord* last_address = curr_range.last();556size_t commits = 0;557558guarantee(reserved.contains(start_address) && reserved.contains(last_address),559"MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",560p2i(start_address), p2i(last_address));561guarantee(start_address > prev_last_addr,562"Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,563p2i(start_address), p2i(prev_last_addr));564prev_last_addr = last_address;565566// Check for ranges that start in the same G1 region in which the previous567// range ended, and adjust the start address so we don't try to allocate568// the same region again. If the current range is entirely within that569// region, skip it, just adjusting the recorded top.570HeapRegion* start_region = _hrm.addr_to_region(start_address);571if ((prev_last_region != NULL) && (start_region == prev_last_region)) {572start_address = start_region->end();573if (start_address > last_address) {574increase_used(word_size * HeapWordSize);575start_region->set_top(last_address + 1);576continue;577}578start_region->set_top(start_address);579curr_range = MemRegion(start_address, last_address + 1);580start_region = _hrm.addr_to_region(start_address);581}582583// Perform the actual region allocation, exiting if it fails.584// Then note how much new space we have allocated.585if (!_hrm.allocate_containing_regions(curr_range, &commits, workers())) {586return false;587}588increase_used(word_size * HeapWordSize);589if (commits != 0) {590log_debug(gc, ergo, heap)("Attempt heap expansion (allocate archive regions). Total size: " SIZE_FORMAT "B",591HeapRegion::GrainWords * HeapWordSize * commits);592593}594595// Mark each G1 region touched by the range as archive, add it to596// the old set, and set top.597HeapRegion* curr_region = _hrm.addr_to_region(start_address);598HeapRegion* last_region = _hrm.addr_to_region(last_address);599prev_last_region = last_region;600601while (curr_region != NULL) {602assert(curr_region->is_empty() && !curr_region->is_pinned(),603"Region already in use (index %u)", curr_region->hrm_index());604if (open) {605curr_region->set_open_archive();606} else {607curr_region->set_closed_archive();608}609_hr_printer.alloc(curr_region);610_archive_set.add(curr_region);611HeapWord* top;612HeapRegion* next_region;613if (curr_region != last_region) {614top = curr_region->end();615next_region = _hrm.next_region_in_heap(curr_region);616} else {617top = last_address + 1;618next_region = NULL;619}620curr_region->set_top(top);621curr_region = next_region;622}623}624return true;625}626627void G1CollectedHeap::fill_archive_regions(MemRegion* ranges, size_t count) {628assert(!is_init_completed(), "Expect to be called at JVM init time");629assert(ranges != NULL, "MemRegion array NULL");630assert(count != 0, "No MemRegions provided");631MemRegion reserved = _hrm.reserved();632HeapWord *prev_last_addr = NULL;633HeapRegion* prev_last_region = NULL;634635// For each MemRegion, create filler objects, if needed, in the G1 regions636// that contain the address range. The address range actually within the637// MemRegion will not be modified. That is assumed to have been initialized638// elsewhere, probably via an mmap of archived heap data.639MutexLocker x(Heap_lock);640for (size_t i = 0; i < count; i++) {641HeapWord* start_address = ranges[i].start();642HeapWord* last_address = ranges[i].last();643644assert(reserved.contains(start_address) && reserved.contains(last_address),645"MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",646p2i(start_address), p2i(last_address));647assert(start_address > prev_last_addr,648"Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,649p2i(start_address), p2i(prev_last_addr));650651HeapRegion* start_region = _hrm.addr_to_region(start_address);652HeapRegion* last_region = _hrm.addr_to_region(last_address);653HeapWord* bottom_address = start_region->bottom();654655// Check for a range beginning in the same region in which the656// previous one ended.657if (start_region == prev_last_region) {658bottom_address = prev_last_addr + 1;659}660661// Verify that the regions were all marked as archive regions by662// alloc_archive_regions.663HeapRegion* curr_region = start_region;664while (curr_region != NULL) {665guarantee(curr_region->is_archive(),666"Expected archive region at index %u", curr_region->hrm_index());667if (curr_region != last_region) {668curr_region = _hrm.next_region_in_heap(curr_region);669} else {670curr_region = NULL;671}672}673674prev_last_addr = last_address;675prev_last_region = last_region;676677// Fill the memory below the allocated range with dummy object(s),678// if the region bottom does not match the range start, or if the previous679// range ended within the same G1 region, and there is a gap.680assert(start_address >= bottom_address, "bottom address should not be greater than start address");681if (start_address > bottom_address) {682size_t fill_size = pointer_delta(start_address, bottom_address);683G1CollectedHeap::fill_with_objects(bottom_address, fill_size);684increase_used(fill_size * HeapWordSize);685}686}687}688689inline HeapWord* G1CollectedHeap::attempt_allocation(size_t min_word_size,690size_t desired_word_size,691size_t* actual_word_size) {692assert_heap_not_locked_and_not_at_safepoint();693assert(!is_humongous(desired_word_size), "attempt_allocation() should not "694"be called for humongous allocation requests");695696HeapWord* result = _allocator->attempt_allocation(min_word_size, desired_word_size, actual_word_size);697698if (result == NULL) {699*actual_word_size = desired_word_size;700result = attempt_allocation_slow(desired_word_size);701}702703assert_heap_not_locked();704if (result != NULL) {705assert(*actual_word_size != 0, "Actual size must have been set here");706dirty_young_block(result, *actual_word_size);707} else {708*actual_word_size = 0;709}710711return result;712}713714void G1CollectedHeap::populate_archive_regions_bot_part(MemRegion* ranges, size_t count) {715assert(!is_init_completed(), "Expect to be called at JVM init time");716assert(ranges != NULL, "MemRegion array NULL");717assert(count != 0, "No MemRegions provided");718719HeapWord* st = ranges[0].start();720HeapWord* last = ranges[count-1].last();721HeapRegion* hr_st = _hrm.addr_to_region(st);722HeapRegion* hr_last = _hrm.addr_to_region(last);723724HeapRegion* hr_curr = hr_st;725while (hr_curr != NULL) {726hr_curr->update_bot();727if (hr_curr != hr_last) {728hr_curr = _hrm.next_region_in_heap(hr_curr);729} else {730hr_curr = NULL;731}732}733}734735void G1CollectedHeap::dealloc_archive_regions(MemRegion* ranges, size_t count) {736assert(!is_init_completed(), "Expect to be called at JVM init time");737assert(ranges != NULL, "MemRegion array NULL");738assert(count != 0, "No MemRegions provided");739MemRegion reserved = _hrm.reserved();740HeapWord* prev_last_addr = NULL;741HeapRegion* prev_last_region = NULL;742size_t size_used = 0;743uint shrink_count = 0;744745// For each Memregion, free the G1 regions that constitute it, and746// notify mark-sweep that the range is no longer to be considered 'archive.'747MutexLocker x(Heap_lock);748for (size_t i = 0; i < count; i++) {749HeapWord* start_address = ranges[i].start();750HeapWord* last_address = ranges[i].last();751752assert(reserved.contains(start_address) && reserved.contains(last_address),753"MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",754p2i(start_address), p2i(last_address));755assert(start_address > prev_last_addr,756"Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,757p2i(start_address), p2i(prev_last_addr));758size_used += ranges[i].byte_size();759prev_last_addr = last_address;760761HeapRegion* start_region = _hrm.addr_to_region(start_address);762HeapRegion* last_region = _hrm.addr_to_region(last_address);763764// Check for ranges that start in the same G1 region in which the previous765// range ended, and adjust the start address so we don't try to free766// the same region again. If the current range is entirely within that767// region, skip it.768if (start_region == prev_last_region) {769start_address = start_region->end();770if (start_address > last_address) {771continue;772}773start_region = _hrm.addr_to_region(start_address);774}775prev_last_region = last_region;776777// After verifying that each region was marked as an archive region by778// alloc_archive_regions, set it free and empty and uncommit it.779HeapRegion* curr_region = start_region;780while (curr_region != NULL) {781guarantee(curr_region->is_archive(),782"Expected archive region at index %u", curr_region->hrm_index());783uint curr_index = curr_region->hrm_index();784_archive_set.remove(curr_region);785curr_region->set_free();786curr_region->set_top(curr_region->bottom());787if (curr_region != last_region) {788curr_region = _hrm.next_region_in_heap(curr_region);789} else {790curr_region = NULL;791}792793_hrm.shrink_at(curr_index, 1);794shrink_count++;795}796}797798if (shrink_count != 0) {799log_debug(gc, ergo, heap)("Attempt heap shrinking (archive regions). Total size: " SIZE_FORMAT "B",800HeapRegion::GrainWords * HeapWordSize * shrink_count);801// Explicit uncommit.802uncommit_regions(shrink_count);803}804decrease_used(size_used);805}806807HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) {808ResourceMark rm; // For retrieving the thread names in log messages.809810// The structure of this method has a lot of similarities to811// attempt_allocation_slow(). The reason these two were not merged812// into a single one is that such a method would require several "if813// allocation is not humongous do this, otherwise do that"814// conditional paths which would obscure its flow. In fact, an early815// version of this code did use a unified method which was harder to816// follow and, as a result, it had subtle bugs that were hard to817// track down. So keeping these two methods separate allows each to818// be more readable. It will be good to keep these two in sync as819// much as possible.820821assert_heap_not_locked_and_not_at_safepoint();822assert(is_humongous(word_size), "attempt_allocation_humongous() "823"should only be called for humongous allocations");824825// Humongous objects can exhaust the heap quickly, so we should check if we826// need to start a marking cycle at each humongous object allocation. We do827// the check before we do the actual allocation. The reason for doing it828// before the allocation is that we avoid having to keep track of the newly829// allocated memory while we do a GC.830if (policy()->need_to_start_conc_mark("concurrent humongous allocation",831word_size)) {832collect(GCCause::_g1_humongous_allocation);833}834835// We will loop until a) we manage to successfully perform the836// allocation or b) we successfully schedule a collection which837// fails to perform the allocation. b) is the only case when we'll838// return NULL.839HeapWord* result = NULL;840for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {841bool should_try_gc;842uint gc_count_before;843844845{846MutexLocker x(Heap_lock);847848// Given that humongous objects are not allocated in young849// regions, we'll first try to do the allocation without doing a850// collection hoping that there's enough space in the heap.851result = humongous_obj_allocate(word_size);852if (result != NULL) {853size_t size_in_regions = humongous_obj_size_in_regions(word_size);854policy()->old_gen_alloc_tracker()->855add_allocated_humongous_bytes_since_last_gc(size_in_regions * HeapRegion::GrainBytes);856return result;857}858859// Only try a GC if the GCLocker does not signal the need for a GC. Wait until860// the GCLocker initiated GC has been performed and then retry. This includes861// the case when the GC Locker is not active but has not been performed.862should_try_gc = !GCLocker::needs_gc();863// Read the GC count while still holding the Heap_lock.864gc_count_before = total_collections();865}866867if (should_try_gc) {868bool succeeded;869result = do_collection_pause(word_size, gc_count_before, &succeeded,870GCCause::_g1_humongous_allocation);871if (result != NULL) {872assert(succeeded, "only way to get back a non-NULL result");873log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,874Thread::current()->name(), p2i(result));875size_t size_in_regions = humongous_obj_size_in_regions(word_size);876policy()->old_gen_alloc_tracker()->877record_collection_pause_humongous_allocation(size_in_regions * HeapRegion::GrainBytes);878return result;879}880881if (succeeded) {882// We successfully scheduled a collection which failed to allocate. No883// point in trying to allocate further. We'll just return NULL.884log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "885SIZE_FORMAT " words", Thread::current()->name(), word_size);886return NULL;887}888log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT "",889Thread::current()->name(), word_size);890} else {891// Failed to schedule a collection.892if (gclocker_retry_count > GCLockerRetryAllocationCount) {893log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "894SIZE_FORMAT " words", Thread::current()->name(), word_size);895return NULL;896}897log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());898// The GCLocker is either active or the GCLocker initiated899// GC has not yet been performed. Stall until it is and900// then retry the allocation.901GCLocker::stall_until_clear();902gclocker_retry_count += 1;903}904905906// We can reach here if we were unsuccessful in scheduling a907// collection (because another thread beat us to it) or if we were908// stalled due to the GC locker. In either can we should retry the909// allocation attempt in case another thread successfully910// performed a collection and reclaimed enough space.911// Humongous object allocation always needs a lock, so we wait for the retry912// in the next iteration of the loop, unlike for the regular iteration case.913// Give a warning if we seem to be looping forever.914915if ((QueuedAllocationWarningCount > 0) &&916(try_count % QueuedAllocationWarningCount == 0)) {917log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",918Thread::current()->name(), try_count, word_size);919}920}921922ShouldNotReachHere();923return NULL;924}925926HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,927bool expect_null_mutator_alloc_region) {928assert_at_safepoint_on_vm_thread();929assert(!_allocator->has_mutator_alloc_region() || !expect_null_mutator_alloc_region,930"the current alloc region was unexpectedly found to be non-NULL");931932if (!is_humongous(word_size)) {933return _allocator->attempt_allocation_locked(word_size);934} else {935HeapWord* result = humongous_obj_allocate(word_size);936if (result != NULL && policy()->need_to_start_conc_mark("STW humongous allocation")) {937collector_state()->set_initiate_conc_mark_if_possible(true);938}939return result;940}941942ShouldNotReachHere();943}944945class PostCompactionPrinterClosure: public HeapRegionClosure {946private:947G1HRPrinter* _hr_printer;948public:949bool do_heap_region(HeapRegion* hr) {950assert(!hr->is_young(), "not expecting to find young regions");951_hr_printer->post_compaction(hr);952return false;953}954955PostCompactionPrinterClosure(G1HRPrinter* hr_printer)956: _hr_printer(hr_printer) { }957};958959void G1CollectedHeap::print_hrm_post_compaction() {960if (_hr_printer.is_active()) {961PostCompactionPrinterClosure cl(hr_printer());962heap_region_iterate(&cl);963}964}965966void G1CollectedHeap::abort_concurrent_cycle() {967// If we start the compaction before the CM threads finish968// scanning the root regions we might trip them over as we'll969// be moving objects / updating references. So let's wait until970// they are done. By telling them to abort, they should complete971// early.972_cm->root_regions()->abort();973_cm->root_regions()->wait_until_scan_finished();974975// Disable discovery and empty the discovered lists976// for the CM ref processor.977_ref_processor_cm->disable_discovery();978_ref_processor_cm->abandon_partial_discovery();979_ref_processor_cm->verify_no_references_recorded();980981// Abandon current iterations of concurrent marking and concurrent982// refinement, if any are in progress.983concurrent_mark()->concurrent_cycle_abort();984}985986void G1CollectedHeap::prepare_heap_for_full_collection() {987// Make sure we'll choose a new allocation region afterwards.988_allocator->release_mutator_alloc_regions();989_allocator->abandon_gc_alloc_regions();990991// We may have added regions to the current incremental collection992// set between the last GC or pause and now. We need to clear the993// incremental collection set and then start rebuilding it afresh994// after this full GC.995abandon_collection_set(collection_set());996997_hrm.remove_all_free_regions();998}9991000void G1CollectedHeap::verify_before_full_collection(bool explicit_gc) {1001assert(!GCCause::is_user_requested_gc(gc_cause()) || explicit_gc, "invariant");1002assert_used_and_recalculate_used_equal(this);1003_verifier->verify_region_sets_optional();1004_verifier->verify_before_gc(G1HeapVerifier::G1VerifyFull);1005_verifier->check_bitmaps("Full GC Start");1006}10071008void G1CollectedHeap::prepare_heap_for_mutators() {1009// Delete metaspaces for unloaded class loaders and clean up loader_data graph1010ClassLoaderDataGraph::purge(/*at_safepoint*/true);1011DEBUG_ONLY(MetaspaceUtils::verify();)10121013// Prepare heap for normal collections.1014assert(num_free_regions() == 0, "we should not have added any free regions");1015rebuild_region_sets(false /* free_list_only */);1016abort_refinement();1017resize_heap_if_necessary();1018uncommit_regions_if_necessary();10191020// Rebuild the strong code root lists for each region1021rebuild_strong_code_roots();10221023// Purge code root memory1024purge_code_root_memory();10251026// Start a new incremental collection set for the next pause1027start_new_collection_set();10281029_allocator->init_mutator_alloc_regions();10301031// Post collection state updates.1032MetaspaceGC::compute_new_size();1033}10341035void G1CollectedHeap::abort_refinement() {1036if (_hot_card_cache->use_cache()) {1037_hot_card_cache->reset_hot_cache();1038}10391040// Discard all remembered set updates and reset refinement statistics.1041G1BarrierSet::dirty_card_queue_set().abandon_logs();1042assert(G1BarrierSet::dirty_card_queue_set().num_cards() == 0,1043"DCQS should be empty");1044concurrent_refine()->get_and_reset_refinement_stats();1045}10461047void G1CollectedHeap::verify_after_full_collection() {1048_hrm.verify_optional();1049_verifier->verify_region_sets_optional();1050_verifier->verify_after_gc(G1HeapVerifier::G1VerifyFull);10511052// This call implicitly verifies that the next bitmap is clear after Full GC.1053_verifier->check_bitmaps("Full GC End");10541055// At this point there should be no regions in the1056// entire heap tagged as young.1057assert(check_young_list_empty(), "young list should be empty at this point");10581059// Note: since we've just done a full GC, concurrent1060// marking is no longer active. Therefore we need not1061// re-enable reference discovery for the CM ref processor.1062// That will be done at the start of the next marking cycle.1063// We also know that the STW processor should no longer1064// discover any new references.1065assert(!_ref_processor_stw->discovery_enabled(), "Postcondition");1066assert(!_ref_processor_cm->discovery_enabled(), "Postcondition");1067_ref_processor_stw->verify_no_references_recorded();1068_ref_processor_cm->verify_no_references_recorded();1069}10701071void G1CollectedHeap::print_heap_after_full_collection(G1HeapTransition* heap_transition) {1072// Post collection logging.1073// We should do this after we potentially resize the heap so1074// that all the COMMIT / UNCOMMIT events are generated before1075// the compaction events.1076print_hrm_post_compaction();1077heap_transition->print();1078print_heap_after_gc();1079print_heap_regions();1080}10811082bool G1CollectedHeap::do_full_collection(bool explicit_gc,1083bool clear_all_soft_refs,1084bool do_maximum_compaction) {1085assert_at_safepoint_on_vm_thread();10861087if (GCLocker::check_active_before_gc()) {1088// Full GC was not completed.1089return false;1090}10911092const bool do_clear_all_soft_refs = clear_all_soft_refs ||1093soft_ref_policy()->should_clear_all_soft_refs();10941095G1FullCollector collector(this, explicit_gc, do_clear_all_soft_refs, do_maximum_compaction);1096GCTraceTime(Info, gc) tm("Pause Full", NULL, gc_cause(), true);10971098collector.prepare_collection();1099collector.collect();1100collector.complete_collection();11011102// Full collection was successfully completed.1103return true;1104}11051106void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {1107// Currently, there is no facility in the do_full_collection(bool) API to notify1108// the caller that the collection did not succeed (e.g., because it was locked1109// out by the GC locker). So, right now, we'll ignore the return value.1110// When clear_all_soft_refs is set we want to do a maximum compaction1111// not leaving any dead wood.1112bool do_maximum_compaction = clear_all_soft_refs;1113bool dummy = do_full_collection(true, /* explicit_gc */1114clear_all_soft_refs,1115do_maximum_compaction);1116}11171118void G1CollectedHeap::resize_heap_if_necessary() {1119assert_at_safepoint_on_vm_thread();11201121bool should_expand;1122size_t resize_amount = _heap_sizing_policy->full_collection_resize_amount(should_expand);11231124if (resize_amount == 0) {1125return;1126} else if (should_expand) {1127expand(resize_amount, _workers);1128} else {1129shrink(resize_amount);1130}1131}11321133HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size,1134bool do_gc,1135bool clear_all_soft_refs,1136bool expect_null_mutator_alloc_region,1137bool* gc_succeeded) {1138*gc_succeeded = true;1139// Let's attempt the allocation first.1140HeapWord* result =1141attempt_allocation_at_safepoint(word_size,1142expect_null_mutator_alloc_region);1143if (result != NULL) {1144return result;1145}11461147// In a G1 heap, we're supposed to keep allocation from failing by1148// incremental pauses. Therefore, at least for now, we'll favor1149// expansion over collection. (This might change in the future if we can1150// do something smarter than full collection to satisfy a failed alloc.)1151result = expand_and_allocate(word_size);1152if (result != NULL) {1153return result;1154}11551156if (do_gc) {1157// When clear_all_soft_refs is set we want to do a maximum compaction1158// not leaving any dead wood.1159bool do_maximum_compaction = clear_all_soft_refs;1160// Expansion didn't work, we'll try to do a Full GC.1161*gc_succeeded = do_full_collection(false, /* explicit_gc */1162clear_all_soft_refs,1163do_maximum_compaction);1164}11651166return NULL;1167}11681169HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size,1170bool* succeeded) {1171assert_at_safepoint_on_vm_thread();11721173// Attempts to allocate followed by Full GC.1174HeapWord* result =1175satisfy_failed_allocation_helper(word_size,1176true, /* do_gc */1177false, /* clear_all_soft_refs */1178false, /* expect_null_mutator_alloc_region */1179succeeded);11801181if (result != NULL || !*succeeded) {1182return result;1183}11841185// Attempts to allocate followed by Full GC that will collect all soft references.1186result = satisfy_failed_allocation_helper(word_size,1187true, /* do_gc */1188true, /* clear_all_soft_refs */1189true, /* expect_null_mutator_alloc_region */1190succeeded);11911192if (result != NULL || !*succeeded) {1193return result;1194}11951196// Attempts to allocate, no GC1197result = satisfy_failed_allocation_helper(word_size,1198false, /* do_gc */1199false, /* clear_all_soft_refs */1200true, /* expect_null_mutator_alloc_region */1201succeeded);12021203if (result != NULL) {1204return result;1205}12061207assert(!soft_ref_policy()->should_clear_all_soft_refs(),1208"Flag should have been handled and cleared prior to this point");12091210// What else? We might try synchronous finalization later. If the total1211// space available is large enough for the allocation, then a more1212// complete compaction phase than we've tried so far might be1213// appropriate.1214return NULL;1215}12161217// Attempting to expand the heap sufficiently1218// to support an allocation of the given "word_size". If1219// successful, perform the allocation and return the address of the1220// allocated block, or else "NULL".12211222HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {1223assert_at_safepoint_on_vm_thread();12241225_verifier->verify_region_sets_optional();12261227size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);1228log_debug(gc, ergo, heap)("Attempt heap expansion (allocation request failed). Allocation request: " SIZE_FORMAT "B",1229word_size * HeapWordSize);123012311232if (expand(expand_bytes, _workers)) {1233_hrm.verify_optional();1234_verifier->verify_region_sets_optional();1235return attempt_allocation_at_safepoint(word_size,1236false /* expect_null_mutator_alloc_region */);1237}1238return NULL;1239}12401241bool G1CollectedHeap::expand(size_t expand_bytes, WorkGang* pretouch_workers, double* expand_time_ms) {1242size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);1243aligned_expand_bytes = align_up(aligned_expand_bytes,1244HeapRegion::GrainBytes);12451246log_debug(gc, ergo, heap)("Expand the heap. requested expansion amount: " SIZE_FORMAT "B expansion amount: " SIZE_FORMAT "B",1247expand_bytes, aligned_expand_bytes);12481249if (is_maximal_no_gc()) {1250log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");1251return false;1252}12531254double expand_heap_start_time_sec = os::elapsedTime();1255uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes);1256assert(regions_to_expand > 0, "Must expand by at least one region");12571258uint expanded_by = _hrm.expand_by(regions_to_expand, pretouch_workers);1259if (expand_time_ms != NULL) {1260*expand_time_ms = (os::elapsedTime() - expand_heap_start_time_sec) * MILLIUNITS;1261}12621263if (expanded_by > 0) {1264size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes;1265assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");1266policy()->record_new_heap_size(num_regions());1267} else {1268log_debug(gc, ergo, heap)("Did not expand the heap (heap expansion operation failed)");12691270// The expansion of the virtual storage space was unsuccessful.1271// Let's see if it was because we ran out of swap.1272if (G1ExitOnExpansionFailure &&1273_hrm.available() >= regions_to_expand) {1274// We had head room...1275vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");1276}1277}1278return regions_to_expand > 0;1279}12801281bool G1CollectedHeap::expand_single_region(uint node_index) {1282uint expanded_by = _hrm.expand_on_preferred_node(node_index);12831284if (expanded_by == 0) {1285assert(is_maximal_no_gc(), "Should be no regions left, available: %u", _hrm.available());1286log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");1287return false;1288}12891290policy()->record_new_heap_size(num_regions());1291return true;1292}12931294void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {1295size_t aligned_shrink_bytes =1296ReservedSpace::page_align_size_down(shrink_bytes);1297aligned_shrink_bytes = align_down(aligned_shrink_bytes,1298HeapRegion::GrainBytes);1299uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);13001301uint num_regions_removed = _hrm.shrink_by(num_regions_to_remove);1302size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;13031304log_debug(gc, ergo, heap)("Shrink the heap. requested shrinking amount: " SIZE_FORMAT "B aligned shrinking amount: " SIZE_FORMAT "B attempted shrinking amount: " SIZE_FORMAT "B",1305shrink_bytes, aligned_shrink_bytes, shrunk_bytes);1306if (num_regions_removed > 0) {1307log_debug(gc, heap)("Uncommittable regions after shrink: %u", num_regions_removed);1308policy()->record_new_heap_size(num_regions());1309} else {1310log_debug(gc, ergo, heap)("Did not expand the heap (heap shrinking operation failed)");1311}1312}13131314void G1CollectedHeap::shrink(size_t shrink_bytes) {1315_verifier->verify_region_sets_optional();13161317// We should only reach here at the end of a Full GC or during Remark which1318// means we should not not be holding to any GC alloc regions. The method1319// below will make sure of that and do any remaining clean up.1320_allocator->abandon_gc_alloc_regions();13211322// Instead of tearing down / rebuilding the free lists here, we1323// could instead use the remove_all_pending() method on free_list to1324// remove only the ones that we need to remove.1325_hrm.remove_all_free_regions();1326shrink_helper(shrink_bytes);1327rebuild_region_sets(true /* free_list_only */);13281329_hrm.verify_optional();1330_verifier->verify_region_sets_optional();1331}13321333class OldRegionSetChecker : public HeapRegionSetChecker {1334public:1335void check_mt_safety() {1336// Master Old Set MT safety protocol:1337// (a) If we're at a safepoint, operations on the master old set1338// should be invoked:1339// - by the VM thread (which will serialize them), or1340// - by the GC workers while holding the FreeList_lock, if we're1341// at a safepoint for an evacuation pause (this lock is taken1342// anyway when an GC alloc region is retired so that a new one1343// is allocated from the free list), or1344// - by the GC workers while holding the OldSets_lock, if we're at a1345// safepoint for a cleanup pause.1346// (b) If we're not at a safepoint, operations on the master old set1347// should be invoked while holding the Heap_lock.13481349if (SafepointSynchronize::is_at_safepoint()) {1350guarantee(Thread::current()->is_VM_thread() ||1351FreeList_lock->owned_by_self() || OldSets_lock->owned_by_self(),1352"master old set MT safety protocol at a safepoint");1353} else {1354guarantee(Heap_lock->owned_by_self(), "master old set MT safety protocol outside a safepoint");1355}1356}1357bool is_correct_type(HeapRegion* hr) { return hr->is_old(); }1358const char* get_description() { return "Old Regions"; }1359};13601361class ArchiveRegionSetChecker : public HeapRegionSetChecker {1362public:1363void check_mt_safety() {1364guarantee(!Universe::is_fully_initialized() || SafepointSynchronize::is_at_safepoint(),1365"May only change archive regions during initialization or safepoint.");1366}1367bool is_correct_type(HeapRegion* hr) { return hr->is_archive(); }1368const char* get_description() { return "Archive Regions"; }1369};13701371class HumongousRegionSetChecker : public HeapRegionSetChecker {1372public:1373void check_mt_safety() {1374// Humongous Set MT safety protocol:1375// (a) If we're at a safepoint, operations on the master humongous1376// set should be invoked by either the VM thread (which will1377// serialize them) or by the GC workers while holding the1378// OldSets_lock.1379// (b) If we're not at a safepoint, operations on the master1380// humongous set should be invoked while holding the Heap_lock.13811382if (SafepointSynchronize::is_at_safepoint()) {1383guarantee(Thread::current()->is_VM_thread() ||1384OldSets_lock->owned_by_self(),1385"master humongous set MT safety protocol at a safepoint");1386} else {1387guarantee(Heap_lock->owned_by_self(),1388"master humongous set MT safety protocol outside a safepoint");1389}1390}1391bool is_correct_type(HeapRegion* hr) { return hr->is_humongous(); }1392const char* get_description() { return "Humongous Regions"; }1393};13941395G1CollectedHeap::G1CollectedHeap() :1396CollectedHeap(),1397_service_thread(NULL),1398_periodic_gc_task(NULL),1399_workers(NULL),1400_card_table(NULL),1401_collection_pause_end(Ticks::now()),1402_soft_ref_policy(),1403_old_set("Old Region Set", new OldRegionSetChecker()),1404_archive_set("Archive Region Set", new ArchiveRegionSetChecker()),1405_humongous_set("Humongous Region Set", new HumongousRegionSetChecker()),1406_bot(NULL),1407_listener(),1408_numa(G1NUMA::create()),1409_hrm(),1410_allocator(NULL),1411_verifier(NULL),1412_summary_bytes_used(0),1413_bytes_used_during_gc(0),1414_archive_allocator(NULL),1415_survivor_evac_stats("Young", YoungPLABSize, PLABWeight),1416_old_evac_stats("Old", OldPLABSize, PLABWeight),1417_expand_heap_after_alloc_failure(true),1418_g1mm(NULL),1419_humongous_reclaim_candidates(),1420_num_humongous_objects(0),1421_num_humongous_reclaim_candidates(0),1422_hr_printer(),1423_collector_state(),1424_old_marking_cycles_started(0),1425_old_marking_cycles_completed(0),1426_eden(),1427_survivor(),1428_gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),1429_gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),1430_policy(new G1Policy(_gc_timer_stw)),1431_heap_sizing_policy(NULL),1432_collection_set(this, _policy),1433_hot_card_cache(NULL),1434_rem_set(NULL),1435_cm(NULL),1436_cm_thread(NULL),1437_cr(NULL),1438_task_queues(NULL),1439_num_regions_failed_evacuation(0),1440_evacuation_failed_info_array(NULL),1441_preserved_marks_set(true /* in_c_heap */),1442#ifndef PRODUCT1443_evacuation_failure_alot_for_current_gc(false),1444_evacuation_failure_alot_gc_number(0),1445_evacuation_failure_alot_count(0),1446#endif1447_ref_processor_stw(NULL),1448_is_alive_closure_stw(this),1449_is_subject_to_discovery_stw(this),1450_ref_processor_cm(NULL),1451_is_alive_closure_cm(this),1452_is_subject_to_discovery_cm(this),1453_region_attr() {14541455_verifier = new G1HeapVerifier(this);14561457_allocator = new G1Allocator(this);14581459_heap_sizing_policy = G1HeapSizingPolicy::create(this, _policy->analytics());14601461_humongous_object_threshold_in_words = humongous_threshold_for(HeapRegion::GrainWords);14621463// Override the default _filler_array_max_size so that no humongous filler1464// objects are created.1465_filler_array_max_size = _humongous_object_threshold_in_words;14661467uint n_queues = ParallelGCThreads;1468_task_queues = new G1ScannerTasksQueueSet(n_queues);14691470_evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);14711472for (uint i = 0; i < n_queues; i++) {1473G1ScannerTasksQueue* q = new G1ScannerTasksQueue();1474q->initialize();1475_task_queues->register_queue(i, q);1476::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();1477}14781479// Initialize the G1EvacuationFailureALot counters and flags.1480NOT_PRODUCT(reset_evacuation_should_fail();)1481_gc_tracer_stw->initialize();14821483guarantee(_task_queues != NULL, "task_queues allocation failure.");1484}14851486G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description,1487size_t size,1488size_t translation_factor) {1489size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1);1490// Allocate a new reserved space, preferring to use large pages.1491ReservedSpace rs(size, preferred_page_size);1492size_t page_size = rs.page_size();1493G1RegionToSpaceMapper* result =1494G1RegionToSpaceMapper::create_mapper(rs,1495size,1496page_size,1497HeapRegion::GrainBytes,1498translation_factor,1499mtGC);15001501os::trace_page_sizes_for_requested_size(description,1502size,1503page_size,1504preferred_page_size,1505rs.base(),1506rs.size());15071508return result;1509}15101511jint G1CollectedHeap::initialize_concurrent_refinement() {1512jint ecode = JNI_OK;1513_cr = G1ConcurrentRefine::create(&ecode);1514return ecode;1515}15161517jint G1CollectedHeap::initialize_service_thread() {1518_service_thread = new G1ServiceThread();1519if (_service_thread->osthread() == NULL) {1520vm_shutdown_during_initialization("Could not create G1ServiceThread");1521return JNI_ENOMEM;1522}1523return JNI_OK;1524}15251526jint G1CollectedHeap::initialize() {15271528// Necessary to satisfy locking discipline assertions.15291530MutexLocker x(Heap_lock);15311532// While there are no constraints in the GC code that HeapWordSize1533// be any particular value, there are multiple other areas in the1534// system which believe this to be true (e.g. oop->object_size in some1535// cases incorrectly returns the size in wordSize units rather than1536// HeapWordSize).1537guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");15381539size_t init_byte_size = InitialHeapSize;1540size_t reserved_byte_size = G1Arguments::heap_reserved_size_bytes();15411542// Ensure that the sizes are properly aligned.1543Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");1544Universe::check_alignment(reserved_byte_size, HeapRegion::GrainBytes, "g1 heap");1545Universe::check_alignment(reserved_byte_size, HeapAlignment, "g1 heap");15461547// Reserve the maximum.15481549// When compressed oops are enabled, the preferred heap base1550// is calculated by subtracting the requested size from the1551// 32Gb boundary and using the result as the base address for1552// heap reservation. If the requested size is not aligned to1553// HeapRegion::GrainBytes (i.e. the alignment that is passed1554// into the ReservedHeapSpace constructor) then the actual1555// base of the reserved heap may end up differing from the1556// address that was requested (i.e. the preferred heap base).1557// If this happens then we could end up using a non-optimal1558// compressed oops mode.15591560ReservedHeapSpace heap_rs = Universe::reserve_heap(reserved_byte_size,1561HeapAlignment);15621563initialize_reserved_region(heap_rs);15641565// Create the barrier set for the entire reserved region.1566G1CardTable* ct = new G1CardTable(heap_rs.region());1567ct->initialize();1568G1BarrierSet* bs = new G1BarrierSet(ct);1569bs->initialize();1570assert(bs->is_a(BarrierSet::G1BarrierSet), "sanity");1571BarrierSet::set_barrier_set(bs);1572_card_table = ct;15731574{1575G1SATBMarkQueueSet& satbqs = bs->satb_mark_queue_set();1576satbqs.set_process_completed_buffers_threshold(G1SATBProcessCompletedThreshold);1577satbqs.set_buffer_enqueue_threshold_percentage(G1SATBBufferEnqueueingThresholdPercent);1578}15791580// Create the hot card cache.1581_hot_card_cache = new G1HotCardCache(this);15821583// Create space mappers.1584size_t page_size = heap_rs.page_size();1585G1RegionToSpaceMapper* heap_storage =1586G1RegionToSpaceMapper::create_mapper(heap_rs,1587heap_rs.size(),1588page_size,1589HeapRegion::GrainBytes,15901,1591mtJavaHeap);1592if(heap_storage == NULL) {1593vm_shutdown_during_initialization("Could not initialize G1 heap");1594return JNI_ERR;1595}15961597os::trace_page_sizes("Heap",1598MinHeapSize,1599reserved_byte_size,1600page_size,1601heap_rs.base(),1602heap_rs.size());1603heap_storage->set_mapping_changed_listener(&_listener);16041605// Create storage for the BOT, card table, card counts table (hot card cache) and the bitmaps.1606G1RegionToSpaceMapper* bot_storage =1607create_aux_memory_mapper("Block Offset Table",1608G1BlockOffsetTable::compute_size(heap_rs.size() / HeapWordSize),1609G1BlockOffsetTable::heap_map_factor());16101611G1RegionToSpaceMapper* cardtable_storage =1612create_aux_memory_mapper("Card Table",1613G1CardTable::compute_size(heap_rs.size() / HeapWordSize),1614G1CardTable::heap_map_factor());16151616G1RegionToSpaceMapper* card_counts_storage =1617create_aux_memory_mapper("Card Counts Table",1618G1CardCounts::compute_size(heap_rs.size() / HeapWordSize),1619G1CardCounts::heap_map_factor());16201621size_t bitmap_size = G1CMBitMap::compute_size(heap_rs.size());1622G1RegionToSpaceMapper* prev_bitmap_storage =1623create_aux_memory_mapper("Prev Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());1624G1RegionToSpaceMapper* next_bitmap_storage =1625create_aux_memory_mapper("Next Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());16261627_hrm.initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage);1628_card_table->initialize(cardtable_storage);16291630// Do later initialization work for concurrent refinement.1631_hot_card_cache->initialize(card_counts_storage);16321633// 6843694 - ensure that the maximum region index can fit1634// in the remembered set structures.1635const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;1636guarantee((max_reserved_regions() - 1) <= max_region_idx, "too many regions");16371638// The G1FromCardCache reserves card with value 0 as "invalid", so the heap must not1639// start within the first card.1640guarantee(heap_rs.base() >= (char*)G1CardTable::card_size, "Java heap must not start within the first card.");1641G1FromCardCache::initialize(max_reserved_regions());1642// Also create a G1 rem set.1643_rem_set = new G1RemSet(this, _card_table, _hot_card_cache);1644_rem_set->initialize(max_reserved_regions());16451646size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;1647guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");1648guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,1649"too many cards per region");16501651FreeRegionList::set_unrealistically_long_length(max_regions() + 1);16521653_bot = new G1BlockOffsetTable(reserved(), bot_storage);16541655{1656size_t granularity = HeapRegion::GrainBytes;16571658_region_attr.initialize(reserved(), granularity);1659_humongous_reclaim_candidates.initialize(reserved(), granularity);1660}16611662_workers = new WorkGang("GC Thread", ParallelGCThreads,1663true /* are_GC_task_threads */,1664false /* are_ConcurrentGC_threads */);1665if (_workers == NULL) {1666return JNI_ENOMEM;1667}1668_workers->initialize_workers();16691670_numa->set_region_info(HeapRegion::GrainBytes, page_size);16711672// Create the G1ConcurrentMark data structure and thread.1673// (Must do this late, so that "max_[reserved_]regions" is defined.)1674_cm = new G1ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage);1675_cm_thread = _cm->cm_thread();16761677// Now expand into the initial heap size.1678if (!expand(init_byte_size, _workers)) {1679vm_shutdown_during_initialization("Failed to allocate initial heap.");1680return JNI_ENOMEM;1681}16821683// Perform any initialization actions delegated to the policy.1684policy()->init(this, &_collection_set);16851686jint ecode = initialize_concurrent_refinement();1687if (ecode != JNI_OK) {1688return ecode;1689}16901691ecode = initialize_service_thread();1692if (ecode != JNI_OK) {1693return ecode;1694}16951696// Initialize and schedule sampling task on service thread.1697_rem_set->initialize_sampling_task(service_thread());16981699// Create and schedule the periodic gc task on the service thread.1700_periodic_gc_task = new G1PeriodicGCTask("Periodic GC Task");1701_service_thread->register_task(_periodic_gc_task);17021703{1704G1DirtyCardQueueSet& dcqs = G1BarrierSet::dirty_card_queue_set();1705dcqs.set_process_cards_threshold(concurrent_refine()->yellow_zone());1706dcqs.set_max_cards(concurrent_refine()->red_zone());1707}17081709// Here we allocate the dummy HeapRegion that is required by the1710// G1AllocRegion class.1711HeapRegion* dummy_region = _hrm.get_dummy_region();17121713// We'll re-use the same region whether the alloc region will1714// require BOT updates or not and, if it doesn't, then a non-young1715// region will complain that it cannot support allocations without1716// BOT updates. So we'll tag the dummy region as eden to avoid that.1717dummy_region->set_eden();1718// Make sure it's full.1719dummy_region->set_top(dummy_region->end());1720G1AllocRegion::setup(this, dummy_region);17211722_allocator->init_mutator_alloc_regions();17231724// Do create of the monitoring and management support so that1725// values in the heap have been properly initialized.1726_g1mm = new G1MonitoringSupport(this);17271728_preserved_marks_set.init(ParallelGCThreads);17291730_collection_set.initialize(max_reserved_regions());17311732G1InitLogger::print();17331734return JNI_OK;1735}17361737void G1CollectedHeap::stop() {1738// Stop all concurrent threads. We do this to make sure these threads1739// do not continue to execute and access resources (e.g. logging)1740// that are destroyed during shutdown.1741_cr->stop();1742_service_thread->stop();1743_cm_thread->stop();1744}17451746void G1CollectedHeap::safepoint_synchronize_begin() {1747SuspendibleThreadSet::synchronize();1748}17491750void G1CollectedHeap::safepoint_synchronize_end() {1751SuspendibleThreadSet::desynchronize();1752}17531754void G1CollectedHeap::post_initialize() {1755CollectedHeap::post_initialize();1756ref_processing_init();1757}17581759void G1CollectedHeap::ref_processing_init() {1760// Reference processing in G1 currently works as follows:1761//1762// * There are two reference processor instances. One is1763// used to record and process discovered references1764// during concurrent marking; the other is used to1765// record and process references during STW pauses1766// (both full and incremental).1767// * Both ref processors need to 'span' the entire heap as1768// the regions in the collection set may be dotted around.1769//1770// * For the concurrent marking ref processor:1771// * Reference discovery is enabled at concurrent start.1772// * Reference discovery is disabled and the discovered1773// references processed etc during remarking.1774// * Reference discovery is MT (see below).1775// * Reference discovery requires a barrier (see below).1776// * Reference processing may or may not be MT1777// (depending on the value of ParallelRefProcEnabled1778// and ParallelGCThreads).1779// * A full GC disables reference discovery by the CM1780// ref processor and abandons any entries on it's1781// discovered lists.1782//1783// * For the STW processor:1784// * Non MT discovery is enabled at the start of a full GC.1785// * Processing and enqueueing during a full GC is non-MT.1786// * During a full GC, references are processed after marking.1787//1788// * Discovery (may or may not be MT) is enabled at the start1789// of an incremental evacuation pause.1790// * References are processed near the end of a STW evacuation pause.1791// * For both types of GC:1792// * Discovery is atomic - i.e. not concurrent.1793// * Reference discovery will not need a barrier.17941795// Concurrent Mark ref processor1796_ref_processor_cm =1797new ReferenceProcessor(&_is_subject_to_discovery_cm,1798ParallelGCThreads, // degree of mt processing1799(ParallelGCThreads > 1) || (ConcGCThreads > 1), // mt discovery1800MAX2(ParallelGCThreads, ConcGCThreads), // degree of mt discovery1801false, // Reference discovery is not atomic1802&_is_alive_closure_cm, // is alive closure1803true); // allow changes to number of processing threads18041805// STW ref processor1806_ref_processor_stw =1807new ReferenceProcessor(&_is_subject_to_discovery_stw,1808ParallelGCThreads, // degree of mt processing1809(ParallelGCThreads > 1), // mt discovery1810ParallelGCThreads, // degree of mt discovery1811true, // Reference discovery is atomic1812&_is_alive_closure_stw, // is alive closure1813true); // allow changes to number of processing threads1814}18151816SoftRefPolicy* G1CollectedHeap::soft_ref_policy() {1817return &_soft_ref_policy;1818}18191820size_t G1CollectedHeap::capacity() const {1821return _hrm.length() * HeapRegion::GrainBytes;1822}18231824size_t G1CollectedHeap::unused_committed_regions_in_bytes() const {1825return _hrm.total_free_bytes();1826}18271828void G1CollectedHeap::iterate_hcc_closure(G1CardTableEntryClosure* cl, uint worker_id) {1829_hot_card_cache->drain(cl, worker_id);1830}18311832// Computes the sum of the storage used by the various regions.1833size_t G1CollectedHeap::used() const {1834size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions();1835if (_archive_allocator != NULL) {1836result += _archive_allocator->used();1837}1838return result;1839}18401841size_t G1CollectedHeap::used_unlocked() const {1842return _summary_bytes_used;1843}18441845class SumUsedClosure: public HeapRegionClosure {1846size_t _used;1847public:1848SumUsedClosure() : _used(0) {}1849bool do_heap_region(HeapRegion* r) {1850_used += r->used();1851return false;1852}1853size_t result() { return _used; }1854};18551856size_t G1CollectedHeap::recalculate_used() const {1857SumUsedClosure blk;1858heap_region_iterate(&blk);1859return blk.result();1860}18611862bool G1CollectedHeap::is_user_requested_concurrent_full_gc(GCCause::Cause cause) {1863switch (cause) {1864case GCCause::_java_lang_system_gc: return ExplicitGCInvokesConcurrent;1865case GCCause::_dcmd_gc_run: return ExplicitGCInvokesConcurrent;1866case GCCause::_wb_conc_mark: return true;1867default : return false;1868}1869}18701871bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {1872switch (cause) {1873case GCCause::_g1_humongous_allocation: return true;1874case GCCause::_g1_periodic_collection: return G1PeriodicGCInvokesConcurrent;1875case GCCause::_wb_breakpoint: return true;1876default: return is_user_requested_concurrent_full_gc(cause);1877}1878}18791880bool G1CollectedHeap::should_upgrade_to_full_gc(GCCause::Cause cause) {1881if (should_do_concurrent_full_gc(_gc_cause)) {1882return false;1883} else if (has_regions_left_for_allocation()) {1884return false;1885} else {1886return true;1887}1888}18891890#ifndef PRODUCT1891void G1CollectedHeap::allocate_dummy_regions() {1892// Let's fill up most of the region1893size_t word_size = HeapRegion::GrainWords - 1024;1894// And as a result the region we'll allocate will be humongous.1895guarantee(is_humongous(word_size), "sanity");18961897// _filler_array_max_size is set to humongous object threshold1898// but temporarily change it to use CollectedHeap::fill_with_object().1899AutoModifyRestore<size_t> temporarily(_filler_array_max_size, word_size);19001901for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {1902// Let's use the existing mechanism for the allocation1903HeapWord* dummy_obj = humongous_obj_allocate(word_size);1904if (dummy_obj != NULL) {1905MemRegion mr(dummy_obj, word_size);1906CollectedHeap::fill_with_object(mr);1907} else {1908// If we can't allocate once, we probably cannot allocate1909// again. Let's get out of the loop.1910break;1911}1912}1913}1914#endif // !PRODUCT19151916void G1CollectedHeap::increment_old_marking_cycles_started() {1917assert(_old_marking_cycles_started == _old_marking_cycles_completed ||1918_old_marking_cycles_started == _old_marking_cycles_completed + 1,1919"Wrong marking cycle count (started: %d, completed: %d)",1920_old_marking_cycles_started, _old_marking_cycles_completed);19211922_old_marking_cycles_started++;1923}19241925void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent,1926bool whole_heap_examined) {1927MonitorLocker ml(G1OldGCCount_lock, Mutex::_no_safepoint_check_flag);19281929// We assume that if concurrent == true, then the caller is a1930// concurrent thread that was joined the Suspendible Thread1931// Set. If there's ever a cheap way to check this, we should add an1932// assert here.19331934// Given that this method is called at the end of a Full GC or of a1935// concurrent cycle, and those can be nested (i.e., a Full GC can1936// interrupt a concurrent cycle), the number of full collections1937// completed should be either one (in the case where there was no1938// nesting) or two (when a Full GC interrupted a concurrent cycle)1939// behind the number of full collections started.19401941// This is the case for the inner caller, i.e. a Full GC.1942assert(concurrent ||1943(_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||1944(_old_marking_cycles_started == _old_marking_cycles_completed + 2),1945"for inner caller (Full GC): _old_marking_cycles_started = %u "1946"is inconsistent with _old_marking_cycles_completed = %u",1947_old_marking_cycles_started, _old_marking_cycles_completed);19481949// This is the case for the outer caller, i.e. the concurrent cycle.1950assert(!concurrent ||1951(_old_marking_cycles_started == _old_marking_cycles_completed + 1),1952"for outer caller (concurrent cycle): "1953"_old_marking_cycles_started = %u "1954"is inconsistent with _old_marking_cycles_completed = %u",1955_old_marking_cycles_started, _old_marking_cycles_completed);19561957_old_marking_cycles_completed += 1;1958if (whole_heap_examined) {1959// Signal that we have completed a visit to all live objects.1960record_whole_heap_examined_timestamp();1961}19621963// We need to clear the "in_progress" flag in the CM thread before1964// we wake up any waiters (especially when ExplicitInvokesConcurrent1965// is set) so that if a waiter requests another System.gc() it doesn't1966// incorrectly see that a marking cycle is still in progress.1967if (concurrent) {1968_cm_thread->set_idle();1969}19701971// Notify threads waiting in System.gc() (with ExplicitGCInvokesConcurrent)1972// for a full GC to finish that their wait is over.1973ml.notify_all();1974}19751976void G1CollectedHeap::collect(GCCause::Cause cause) {1977try_collect(cause);1978}19791980// Return true if (x < y) with allowance for wraparound.1981static bool gc_counter_less_than(uint x, uint y) {1982return (x - y) > (UINT_MAX/2);1983}19841985// LOG_COLLECT_CONCURRENTLY(cause, msg, args...)1986// Macro so msg printing is format-checked.1987#define LOG_COLLECT_CONCURRENTLY(cause, ...) \1988do { \1989LogTarget(Trace, gc) LOG_COLLECT_CONCURRENTLY_lt; \1990if (LOG_COLLECT_CONCURRENTLY_lt.is_enabled()) { \1991ResourceMark rm; /* For thread name. */ \1992LogStream LOG_COLLECT_CONCURRENTLY_s(&LOG_COLLECT_CONCURRENTLY_lt); \1993LOG_COLLECT_CONCURRENTLY_s.print("%s: Try Collect Concurrently (%s): ", \1994Thread::current()->name(), \1995GCCause::to_string(cause)); \1996LOG_COLLECT_CONCURRENTLY_s.print(__VA_ARGS__); \1997} \1998} while (0)19992000#define LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, result) \2001LOG_COLLECT_CONCURRENTLY(cause, "complete %s", BOOL_TO_STR(result))20022003bool G1CollectedHeap::try_collect_concurrently(GCCause::Cause cause,2004uint gc_counter,2005uint old_marking_started_before) {2006assert_heap_not_locked();2007assert(should_do_concurrent_full_gc(cause),2008"Non-concurrent cause %s", GCCause::to_string(cause));20092010for (uint i = 1; true; ++i) {2011// Try to schedule concurrent start evacuation pause that will2012// start a concurrent cycle.2013LOG_COLLECT_CONCURRENTLY(cause, "attempt %u", i);2014VM_G1TryInitiateConcMark op(gc_counter,2015cause,2016policy()->max_pause_time_ms());2017VMThread::execute(&op);20182019// Request is trivially finished.2020if (cause == GCCause::_g1_periodic_collection) {2021LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, op.gc_succeeded());2022return op.gc_succeeded();2023}20242025// If VMOp skipped initiating concurrent marking cycle because2026// we're terminating, then we're done.2027if (op.terminating()) {2028LOG_COLLECT_CONCURRENTLY(cause, "skipped: terminating");2029return false;2030}20312032// Lock to get consistent set of values.2033uint old_marking_started_after;2034uint old_marking_completed_after;2035{2036MutexLocker ml(Heap_lock);2037// Update gc_counter for retrying VMOp if needed. Captured here to be2038// consistent with the values we use below for termination tests. If2039// a retry is needed after a possible wait, and another collection2040// occurs in the meantime, it will cause our retry to be skipped and2041// we'll recheck for termination with updated conditions from that2042// more recent collection. That's what we want, rather than having2043// our retry possibly perform an unnecessary collection.2044gc_counter = total_collections();2045old_marking_started_after = _old_marking_cycles_started;2046old_marking_completed_after = _old_marking_cycles_completed;2047}20482049if (cause == GCCause::_wb_breakpoint) {2050if (op.gc_succeeded()) {2051LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);2052return true;2053}2054// When _wb_breakpoint there can't be another cycle or deferred.2055assert(!op.cycle_already_in_progress(), "invariant");2056assert(!op.whitebox_attached(), "invariant");2057// Concurrent cycle attempt might have been cancelled by some other2058// collection, so retry. Unlike other cases below, we want to retry2059// even if cancelled by a STW full collection, because we really want2060// to start a concurrent cycle.2061if (old_marking_started_before != old_marking_started_after) {2062LOG_COLLECT_CONCURRENTLY(cause, "ignoring STW full GC");2063old_marking_started_before = old_marking_started_after;2064}2065} else if (!GCCause::is_user_requested_gc(cause)) {2066// For an "automatic" (not user-requested) collection, we just need to2067// ensure that progress is made.2068//2069// Request is finished if any of2070// (1) the VMOp successfully performed a GC,2071// (2) a concurrent cycle was already in progress,2072// (3) whitebox is controlling concurrent cycles,2073// (4) a new cycle was started (by this thread or some other), or2074// (5) a Full GC was performed.2075// Cases (4) and (5) are detected together by a change to2076// _old_marking_cycles_started.2077//2078// Note that (1) does not imply (4). If we're still in the mixed2079// phase of an earlier concurrent collection, the request to make the2080// collection a concurrent start won't be honored. If we don't check for2081// both conditions we'll spin doing back-to-back collections.2082if (op.gc_succeeded() ||2083op.cycle_already_in_progress() ||2084op.whitebox_attached() ||2085(old_marking_started_before != old_marking_started_after)) {2086LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);2087return true;2088}2089} else { // User-requested GC.2090// For a user-requested collection, we want to ensure that a complete2091// full collection has been performed before returning, but without2092// waiting for more than needed.20932094// For user-requested GCs (unlike non-UR), a successful VMOp implies a2095// new cycle was started. That's good, because it's not clear what we2096// should do otherwise. Trying again just does back to back GCs.2097// Can't wait for someone else to start a cycle. And returning fails2098// to meet the goal of ensuring a full collection was performed.2099assert(!op.gc_succeeded() ||2100(old_marking_started_before != old_marking_started_after),2101"invariant: succeeded %s, started before %u, started after %u",2102BOOL_TO_STR(op.gc_succeeded()),2103old_marking_started_before, old_marking_started_after);21042105// Request is finished if a full collection (concurrent or stw)2106// was started after this request and has completed, e.g.2107// started_before < completed_after.2108if (gc_counter_less_than(old_marking_started_before,2109old_marking_completed_after)) {2110LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);2111return true;2112}21132114if (old_marking_started_after != old_marking_completed_after) {2115// If there is an in-progress cycle (possibly started by us), then2116// wait for that cycle to complete, e.g.2117// while completed_now < started_after.2118LOG_COLLECT_CONCURRENTLY(cause, "wait");2119MonitorLocker ml(G1OldGCCount_lock);2120while (gc_counter_less_than(_old_marking_cycles_completed,2121old_marking_started_after)) {2122ml.wait();2123}2124// Request is finished if the collection we just waited for was2125// started after this request.2126if (old_marking_started_before != old_marking_started_after) {2127LOG_COLLECT_CONCURRENTLY(cause, "complete after wait");2128return true;2129}2130}21312132// If VMOp was successful then it started a new cycle that the above2133// wait &etc should have recognized as finishing this request. This2134// differs from a non-user-request, where gc_succeeded does not imply2135// a new cycle was started.2136assert(!op.gc_succeeded(), "invariant");21372138if (op.cycle_already_in_progress()) {2139// If VMOp failed because a cycle was already in progress, it2140// is now complete. But it didn't finish this user-requested2141// GC, so try again.2142LOG_COLLECT_CONCURRENTLY(cause, "retry after in-progress");2143continue;2144} else if (op.whitebox_attached()) {2145// If WhiteBox wants control, wait for notification of a state2146// change in the controller, then try again. Don't wait for2147// release of control, since collections may complete while in2148// control. Note: This won't recognize a STW full collection2149// while waiting; we can't wait on multiple monitors.2150LOG_COLLECT_CONCURRENTLY(cause, "whitebox control stall");2151MonitorLocker ml(ConcurrentGCBreakpoints::monitor());2152if (ConcurrentGCBreakpoints::is_controlled()) {2153ml.wait();2154}2155continue;2156}2157}21582159// Collection failed and should be retried.2160assert(op.transient_failure(), "invariant");21612162if (GCLocker::is_active_and_needs_gc()) {2163// If GCLocker is active, wait until clear before retrying.2164LOG_COLLECT_CONCURRENTLY(cause, "gc-locker stall");2165GCLocker::stall_until_clear();2166}21672168LOG_COLLECT_CONCURRENTLY(cause, "retry");2169}2170}21712172bool G1CollectedHeap::try_collect(GCCause::Cause cause) {2173assert_heap_not_locked();21742175// Lock to get consistent set of values.2176uint gc_count_before;2177uint full_gc_count_before;2178uint old_marking_started_before;2179{2180MutexLocker ml(Heap_lock);2181gc_count_before = total_collections();2182full_gc_count_before = total_full_collections();2183old_marking_started_before = _old_marking_cycles_started;2184}21852186if (should_do_concurrent_full_gc(cause)) {2187return try_collect_concurrently(cause,2188gc_count_before,2189old_marking_started_before);2190} else if (GCLocker::should_discard(cause, gc_count_before)) {2191// Indicate failure to be consistent with VMOp failure due to2192// another collection slipping in after our gc_count but before2193// our request is processed.2194return false;2195} else if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc2196DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {21972198// Schedule a standard evacuation pause. We're setting word_size2199// to 0 which means that we are not requesting a post-GC allocation.2200VM_G1CollectForAllocation op(0, /* word_size */2201gc_count_before,2202cause,2203policy()->max_pause_time_ms());2204VMThread::execute(&op);2205return op.gc_succeeded();2206} else {2207// Schedule a Full GC.2208VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause);2209VMThread::execute(&op);2210return op.gc_succeeded();2211}2212}22132214bool G1CollectedHeap::is_in(const void* p) const {2215return is_in_reserved(p) && _hrm.is_available(addr_to_region((HeapWord*)p));2216}22172218// Iteration functions.22192220// Iterates an ObjectClosure over all objects within a HeapRegion.22212222class IterateObjectClosureRegionClosure: public HeapRegionClosure {2223ObjectClosure* _cl;2224public:2225IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}2226bool do_heap_region(HeapRegion* r) {2227if (!r->is_continues_humongous()) {2228r->object_iterate(_cl);2229}2230return false;2231}2232};22332234void G1CollectedHeap::object_iterate(ObjectClosure* cl) {2235IterateObjectClosureRegionClosure blk(cl);2236heap_region_iterate(&blk);2237}22382239class G1ParallelObjectIterator : public ParallelObjectIterator {2240private:2241G1CollectedHeap* _heap;2242HeapRegionClaimer _claimer;22432244public:2245G1ParallelObjectIterator(uint thread_num) :2246_heap(G1CollectedHeap::heap()),2247_claimer(thread_num == 0 ? G1CollectedHeap::heap()->workers()->active_workers() : thread_num) {}22482249virtual void object_iterate(ObjectClosure* cl, uint worker_id) {2250_heap->object_iterate_parallel(cl, worker_id, &_claimer);2251}2252};22532254ParallelObjectIterator* G1CollectedHeap::parallel_object_iterator(uint thread_num) {2255return new G1ParallelObjectIterator(thread_num);2256}22572258void G1CollectedHeap::object_iterate_parallel(ObjectClosure* cl, uint worker_id, HeapRegionClaimer* claimer) {2259IterateObjectClosureRegionClosure blk(cl);2260heap_region_par_iterate_from_worker_offset(&blk, claimer, worker_id);2261}22622263void G1CollectedHeap::keep_alive(oop obj) {2264G1BarrierSet::enqueue(obj);2265}22662267void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {2268_hrm.iterate(cl);2269}22702271void G1CollectedHeap::heap_region_par_iterate_from_worker_offset(HeapRegionClosure* cl,2272HeapRegionClaimer *hrclaimer,2273uint worker_id) const {2274_hrm.par_iterate(cl, hrclaimer, hrclaimer->offset_for_worker(worker_id));2275}22762277void G1CollectedHeap::heap_region_par_iterate_from_start(HeapRegionClosure* cl,2278HeapRegionClaimer *hrclaimer) const {2279_hrm.par_iterate(cl, hrclaimer, 0);2280}22812282void G1CollectedHeap::collection_set_iterate_all(HeapRegionClosure* cl) {2283_collection_set.iterate(cl);2284}22852286void G1CollectedHeap::collection_set_par_iterate_all(HeapRegionClosure* cl, HeapRegionClaimer* hr_claimer, uint worker_id) {2287_collection_set.par_iterate(cl, hr_claimer, worker_id, workers()->active_workers());2288}22892290void G1CollectedHeap::collection_set_iterate_increment_from(HeapRegionClosure *cl, HeapRegionClaimer* hr_claimer, uint worker_id) {2291_collection_set.iterate_incremental_part_from(cl, hr_claimer, worker_id, workers()->active_workers());2292}22932294HeapWord* G1CollectedHeap::block_start(const void* addr) const {2295HeapRegion* hr = heap_region_containing(addr);2296return hr->block_start(addr);2297}22982299bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {2300HeapRegion* hr = heap_region_containing(addr);2301return hr->block_is_obj(addr);2302}23032304size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {2305return (_policy->young_list_target_length() - _survivor.length()) * HeapRegion::GrainBytes;2306}23072308size_t G1CollectedHeap::tlab_used(Thread* ignored) const {2309return _eden.length() * HeapRegion::GrainBytes;2310}23112312// For G1 TLABs should not contain humongous objects, so the maximum TLAB size2313// must be equal to the humongous object limit.2314size_t G1CollectedHeap::max_tlab_size() const {2315return align_down(_humongous_object_threshold_in_words, MinObjAlignment);2316}23172318size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {2319return _allocator->unsafe_max_tlab_alloc();2320}23212322size_t G1CollectedHeap::max_capacity() const {2323return max_regions() * HeapRegion::GrainBytes;2324}23252326void G1CollectedHeap::prepare_for_verify() {2327_verifier->prepare_for_verify();2328}23292330void G1CollectedHeap::verify(VerifyOption vo) {2331_verifier->verify(vo);2332}23332334bool G1CollectedHeap::supports_concurrent_gc_breakpoints() const {2335return true;2336}23372338bool G1CollectedHeap::is_archived_object(oop object) const {2339return object != NULL && heap_region_containing(object)->is_archive();2340}23412342class PrintRegionClosure: public HeapRegionClosure {2343outputStream* _st;2344public:2345PrintRegionClosure(outputStream* st) : _st(st) {}2346bool do_heap_region(HeapRegion* r) {2347r->print_on(_st);2348return false;2349}2350};23512352bool G1CollectedHeap::is_obj_dead_cond(const oop obj,2353const HeapRegion* hr,2354const VerifyOption vo) const {2355switch (vo) {2356case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);2357case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);2358case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj, hr);2359default: ShouldNotReachHere();2360}2361return false; // keep some compilers happy2362}23632364bool G1CollectedHeap::is_obj_dead_cond(const oop obj,2365const VerifyOption vo) const {2366switch (vo) {2367case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);2368case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);2369case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj);2370default: ShouldNotReachHere();2371}2372return false; // keep some compilers happy2373}23742375void G1CollectedHeap::print_heap_regions() const {2376LogTarget(Trace, gc, heap, region) lt;2377if (lt.is_enabled()) {2378LogStream ls(lt);2379print_regions_on(&ls);2380}2381}23822383void G1CollectedHeap::print_on(outputStream* st) const {2384size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();2385st->print(" %-20s", "garbage-first heap");2386st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",2387capacity()/K, heap_used/K);2388st->print(" [" PTR_FORMAT ", " PTR_FORMAT ")",2389p2i(_hrm.reserved().start()),2390p2i(_hrm.reserved().end()));2391st->cr();2392st->print(" region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);2393uint young_regions = young_regions_count();2394st->print("%u young (" SIZE_FORMAT "K), ", young_regions,2395(size_t) young_regions * HeapRegion::GrainBytes / K);2396uint survivor_regions = survivor_regions_count();2397st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,2398(size_t) survivor_regions * HeapRegion::GrainBytes / K);2399st->cr();2400if (_numa->is_enabled()) {2401uint num_nodes = _numa->num_active_nodes();2402st->print(" remaining free region(s) on each NUMA node: ");2403const int* node_ids = _numa->node_ids();2404for (uint node_index = 0; node_index < num_nodes; node_index++) {2405uint num_free_regions = _hrm.num_free_regions(node_index);2406st->print("%d=%u ", node_ids[node_index], num_free_regions);2407}2408st->cr();2409}2410MetaspaceUtils::print_on(st);2411}24122413void G1CollectedHeap::print_regions_on(outputStream* st) const {2414st->print_cr("Heap Regions: E=young(eden), S=young(survivor), O=old, "2415"HS=humongous(starts), HC=humongous(continues), "2416"CS=collection set, F=free, "2417"OA=open archive, CA=closed archive, "2418"TAMS=top-at-mark-start (previous, next)");2419PrintRegionClosure blk(st);2420heap_region_iterate(&blk);2421}24222423void G1CollectedHeap::print_extended_on(outputStream* st) const {2424print_on(st);24252426// Print the per-region information.2427st->cr();2428print_regions_on(st);2429}24302431void G1CollectedHeap::print_on_error(outputStream* st) const {2432this->CollectedHeap::print_on_error(st);24332434if (_cm != NULL) {2435st->cr();2436_cm->print_on_error(st);2437}2438}24392440void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {2441workers()->threads_do(tc);2442tc->do_thread(_cm_thread);2443_cm->threads_do(tc);2444_cr->threads_do(tc);2445tc->do_thread(_service_thread);2446}24472448void G1CollectedHeap::print_tracing_info() const {2449rem_set()->print_summary_info();2450concurrent_mark()->print_summary_info();2451}24522453#ifndef PRODUCT2454// Helpful for debugging RSet issues.24552456class PrintRSetsClosure : public HeapRegionClosure {2457private:2458const char* _msg;2459size_t _occupied_sum;24602461public:2462bool do_heap_region(HeapRegion* r) {2463HeapRegionRemSet* hrrs = r->rem_set();2464size_t occupied = hrrs->occupied();2465_occupied_sum += occupied;24662467tty->print_cr("Printing RSet for region " HR_FORMAT, HR_FORMAT_PARAMS(r));2468if (occupied == 0) {2469tty->print_cr(" RSet is empty");2470} else {2471hrrs->print();2472}2473tty->print_cr("----------");2474return false;2475}24762477PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {2478tty->cr();2479tty->print_cr("========================================");2480tty->print_cr("%s", msg);2481tty->cr();2482}24832484~PrintRSetsClosure() {2485tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum);2486tty->print_cr("========================================");2487tty->cr();2488}2489};24902491void G1CollectedHeap::print_cset_rsets() {2492PrintRSetsClosure cl("Printing CSet RSets");2493collection_set_iterate_all(&cl);2494}24952496void G1CollectedHeap::print_all_rsets() {2497PrintRSetsClosure cl("Printing All RSets");;2498heap_region_iterate(&cl);2499}2500#endif // PRODUCT25012502bool G1CollectedHeap::print_location(outputStream* st, void* addr) const {2503return BlockLocationPrinter<G1CollectedHeap>::print_location(st, addr);2504}25052506G1HeapSummary G1CollectedHeap::create_g1_heap_summary() {25072508size_t eden_used_bytes = _eden.used_bytes();2509size_t survivor_used_bytes = _survivor.used_bytes();2510size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();25112512size_t eden_capacity_bytes =2513(policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes;25142515VirtualSpaceSummary heap_summary = create_heap_space_summary();2516return G1HeapSummary(heap_summary, heap_used, eden_used_bytes,2517eden_capacity_bytes, survivor_used_bytes, num_regions());2518}25192520G1EvacSummary G1CollectedHeap::create_g1_evac_summary(G1EvacStats* stats) {2521return G1EvacSummary(stats->allocated(), stats->wasted(), stats->undo_wasted(),2522stats->unused(), stats->used(), stats->region_end_waste(),2523stats->regions_filled(), stats->direct_allocated(),2524stats->failure_used(), stats->failure_waste());2525}25262527void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {2528const G1HeapSummary& heap_summary = create_g1_heap_summary();2529gc_tracer->report_gc_heap_summary(when, heap_summary);25302531const MetaspaceSummary& metaspace_summary = create_metaspace_summary();2532gc_tracer->report_metaspace_summary(when, metaspace_summary);2533}25342535void G1CollectedHeap::gc_prologue(bool full) {2536assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");25372538// This summary needs to be printed before incrementing total collections.2539rem_set()->print_periodic_summary_info("Before GC RS summary", total_collections());25402541// Update common counters.2542increment_total_collections(full /* full gc */);2543if (full || collector_state()->in_concurrent_start_gc()) {2544increment_old_marking_cycles_started();2545}25462547// Fill TLAB's and such2548{2549Ticks start = Ticks::now();2550ensure_parsability(true);2551Tickspan dt = Ticks::now() - start;2552phase_times()->record_prepare_tlab_time_ms(dt.seconds() * MILLIUNITS);2553}25542555if (!full) {2556// Flush dirty card queues to qset, so later phases don't need to account2557// for partially filled per-thread queues and such. Not needed for full2558// collections, which ignore those logs.2559Ticks start = Ticks::now();2560G1BarrierSet::dirty_card_queue_set().concatenate_logs();2561Tickspan dt = Ticks::now() - start;2562phase_times()->record_concatenate_dirty_card_logs_time_ms(dt.seconds() * MILLIUNITS);2563}2564}25652566void G1CollectedHeap::gc_epilogue(bool full) {2567// Update common counters.2568if (full) {2569// Update the number of full collections that have been completed.2570increment_old_marking_cycles_completed(false /* concurrent */, true /* liveness_completed */);2571}25722573// We are at the end of the GC. Total collections has already been increased.2574rem_set()->print_periodic_summary_info("After GC RS summary", total_collections() - 1);25752576#if COMPILER2_OR_JVMCI2577assert(DerivedPointerTable::is_empty(), "derived pointer present");2578#endif25792580double start = os::elapsedTime();2581resize_all_tlabs();2582phase_times()->record_resize_tlab_time_ms((os::elapsedTime() - start) * 1000.0);25832584MemoryService::track_memory_usage();2585// We have just completed a GC. Update the soft reference2586// policy with the new heap occupancy2587Universe::heap()->update_capacity_and_used_at_gc();25882589// Print NUMA statistics.2590_numa->print_statistics();25912592_collection_pause_end = Ticks::now();2593}25942595uint G1CollectedHeap::uncommit_regions(uint region_limit) {2596return _hrm.uncommit_inactive_regions(region_limit);2597}25982599bool G1CollectedHeap::has_uncommittable_regions() {2600return _hrm.has_inactive_regions();2601}26022603void G1CollectedHeap::uncommit_regions_if_necessary() {2604if (has_uncommittable_regions()) {2605G1UncommitRegionTask::enqueue();2606}2607}26082609void G1CollectedHeap::verify_numa_regions(const char* desc) {2610LogTarget(Trace, gc, heap, verify) lt;26112612if (lt.is_enabled()) {2613LogStream ls(lt);2614// Iterate all heap regions to print matching between preferred numa id and actual numa id.2615G1NodeIndexCheckClosure cl(desc, _numa, &ls);2616heap_region_iterate(&cl);2617}2618}26192620HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,2621uint gc_count_before,2622bool* succeeded,2623GCCause::Cause gc_cause) {2624assert_heap_not_locked_and_not_at_safepoint();2625VM_G1CollectForAllocation op(word_size,2626gc_count_before,2627gc_cause,2628policy()->max_pause_time_ms());2629VMThread::execute(&op);26302631HeapWord* result = op.result();2632bool ret_succeeded = op.prologue_succeeded() && op.gc_succeeded();2633assert(result == NULL || ret_succeeded,2634"the result should be NULL if the VM did not succeed");2635*succeeded = ret_succeeded;26362637assert_heap_not_locked();2638return result;2639}26402641void G1CollectedHeap::start_concurrent_cycle(bool concurrent_operation_is_full_mark) {2642assert(!_cm_thread->in_progress(), "Can not start concurrent operation while in progress");26432644MutexLocker x(CGC_lock, Mutex::_no_safepoint_check_flag);2645if (concurrent_operation_is_full_mark) {2646_cm->post_concurrent_mark_start();2647_cm_thread->start_full_mark();2648} else {2649_cm->post_concurrent_undo_start();2650_cm_thread->start_undo_mark();2651}2652CGC_lock->notify();2653}26542655bool G1CollectedHeap::is_potential_eager_reclaim_candidate(HeapRegion* r) const {2656// We don't nominate objects with many remembered set entries, on2657// the assumption that such objects are likely still live.2658HeapRegionRemSet* rem_set = r->rem_set();26592660return G1EagerReclaimHumongousObjectsWithStaleRefs ?2661rem_set->occupancy_less_or_equal_than(G1EagerReclaimRemSetThreshold) :2662G1EagerReclaimHumongousObjects && rem_set->is_empty();2663}26642665#ifndef PRODUCT2666void G1CollectedHeap::verify_region_attr_remset_update() {2667class VerifyRegionAttrRemSet : public HeapRegionClosure {2668public:2669virtual bool do_heap_region(HeapRegion* r) {2670G1CollectedHeap* g1h = G1CollectedHeap::heap();2671bool const needs_remset_update = g1h->region_attr(r->bottom()).needs_remset_update();2672assert(r->rem_set()->is_tracked() == needs_remset_update,2673"Region %u remset tracking status (%s) different to region attribute (%s)",2674r->hrm_index(), BOOL_TO_STR(r->rem_set()->is_tracked()), BOOL_TO_STR(needs_remset_update));2675return false;2676}2677} cl;2678heap_region_iterate(&cl);2679}2680#endif26812682class VerifyRegionRemSetClosure : public HeapRegionClosure {2683public:2684bool do_heap_region(HeapRegion* hr) {2685if (!hr->is_archive() && !hr->is_continues_humongous()) {2686hr->verify_rem_set();2687}2688return false;2689}2690};26912692uint G1CollectedHeap::num_task_queues() const {2693return _task_queues->size();2694}26952696#if TASKQUEUE_STATS2697void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {2698st->print_raw_cr("GC Task Stats");2699st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();2700st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();2701}27022703void G1CollectedHeap::print_taskqueue_stats() const {2704if (!log_is_enabled(Trace, gc, task, stats)) {2705return;2706}2707Log(gc, task, stats) log;2708ResourceMark rm;2709LogStream ls(log.trace());2710outputStream* st = &ls;27112712print_taskqueue_stats_hdr(st);27132714TaskQueueStats totals;2715const uint n = num_task_queues();2716for (uint i = 0; i < n; ++i) {2717st->print("%3u ", i); task_queue(i)->stats.print(st); st->cr();2718totals += task_queue(i)->stats;2719}2720st->print_raw("tot "); totals.print(st); st->cr();27212722DEBUG_ONLY(totals.verify());2723}27242725void G1CollectedHeap::reset_taskqueue_stats() {2726const uint n = num_task_queues();2727for (uint i = 0; i < n; ++i) {2728task_queue(i)->stats.reset();2729}2730}2731#endif // TASKQUEUE_STATS27322733void G1CollectedHeap::wait_for_root_region_scanning() {2734double scan_wait_start = os::elapsedTime();2735// We have to wait until the CM threads finish scanning the2736// root regions as it's the only way to ensure that all the2737// objects on them have been correctly scanned before we start2738// moving them during the GC.2739bool waited = _cm->root_regions()->wait_until_scan_finished();2740double wait_time_ms = 0.0;2741if (waited) {2742double scan_wait_end = os::elapsedTime();2743wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;2744}2745phase_times()->record_root_region_scan_wait_time(wait_time_ms);2746}27472748class G1PrintCollectionSetClosure : public HeapRegionClosure {2749private:2750G1HRPrinter* _hr_printer;2751public:2752G1PrintCollectionSetClosure(G1HRPrinter* hr_printer) : HeapRegionClosure(), _hr_printer(hr_printer) { }27532754virtual bool do_heap_region(HeapRegion* r) {2755_hr_printer->cset(r);2756return false;2757}2758};27592760void G1CollectedHeap::start_new_collection_set() {2761double start = os::elapsedTime();27622763collection_set()->start_incremental_building();27642765clear_region_attr();27662767guarantee(_eden.length() == 0, "eden should have been cleared");2768policy()->transfer_survivors_to_cset(survivor());27692770// We redo the verification but now wrt to the new CSet which2771// has just got initialized after the previous CSet was freed.2772_cm->verify_no_collection_set_oops();27732774phase_times()->record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0);2775}27762777void G1CollectedHeap::calculate_collection_set(G1EvacuationInfo& evacuation_info, double target_pause_time_ms) {27782779_collection_set.finalize_initial_collection_set(target_pause_time_ms, &_survivor);2780evacuation_info.set_collectionset_regions(collection_set()->region_length() +2781collection_set()->optional_region_length());27822783_cm->verify_no_collection_set_oops();27842785if (_hr_printer.is_active()) {2786G1PrintCollectionSetClosure cl(&_hr_printer);2787_collection_set.iterate(&cl);2788_collection_set.iterate_optional(&cl);2789}2790}27912792G1HeapVerifier::G1VerifyType G1CollectedHeap::young_collection_verify_type() const {2793if (collector_state()->in_concurrent_start_gc()) {2794return G1HeapVerifier::G1VerifyConcurrentStart;2795} else if (collector_state()->in_young_only_phase()) {2796return G1HeapVerifier::G1VerifyYoungNormal;2797} else {2798return G1HeapVerifier::G1VerifyMixed;2799}2800}28012802void G1CollectedHeap::verify_before_young_collection(G1HeapVerifier::G1VerifyType type) {2803if (VerifyRememberedSets) {2804log_info(gc, verify)("[Verifying RemSets before GC]");2805VerifyRegionRemSetClosure v_cl;2806heap_region_iterate(&v_cl);2807}2808_verifier->verify_before_gc(type);2809_verifier->check_bitmaps("GC Start");2810verify_numa_regions("GC Start");2811}28122813void G1CollectedHeap::verify_after_young_collection(G1HeapVerifier::G1VerifyType type) {2814if (VerifyRememberedSets) {2815log_info(gc, verify)("[Verifying RemSets after GC]");2816VerifyRegionRemSetClosure v_cl;2817heap_region_iterate(&v_cl);2818}2819_verifier->verify_after_gc(type);2820_verifier->check_bitmaps("GC End");2821verify_numa_regions("GC End");2822}28232824void G1CollectedHeap::expand_heap_after_young_collection(){2825size_t expand_bytes = _heap_sizing_policy->young_collection_expansion_amount();2826if (expand_bytes > 0) {2827// No need for an ergo logging here,2828// expansion_amount() does this when it returns a value > 0.2829double expand_ms = 0.0;2830if (!expand(expand_bytes, _workers, &expand_ms)) {2831// We failed to expand the heap. Cannot do anything about it.2832}2833phase_times()->record_expand_heap_time(expand_ms);2834}2835}28362837void G1CollectedHeap::set_young_gc_name(char* young_gc_name) {2838G1GCPauseType pause_type =2839// The strings for all Concurrent Start pauses are the same, so the parameter2840// does not matter here.2841collector_state()->young_gc_pause_type(false /* concurrent_operation_is_full_mark */);2842snprintf(young_gc_name,2843MaxYoungGCNameLength,2844"Pause Young (%s)",2845G1GCPauseTypeHelper::to_string(pause_type));2846}28472848bool G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {2849assert_at_safepoint_on_vm_thread();2850guarantee(!is_gc_active(), "collection is not reentrant");28512852if (GCLocker::check_active_before_gc()) {2853return false;2854}28552856do_collection_pause_at_safepoint_helper(target_pause_time_ms);2857if (should_upgrade_to_full_gc(gc_cause())) {2858log_info(gc, ergo)("Attempting maximally compacting collection");2859bool result = do_full_collection(false /* explicit gc */,2860true /* clear_all_soft_refs */,2861false /* do_maximum_compaction */);2862// do_full_collection only fails if blocked by GC locker, but2863// we've already checked for that above.2864assert(result, "invariant");2865}2866return true;2867}28682869void G1CollectedHeap::gc_tracer_report_gc_start() {2870_gc_timer_stw->register_gc_start();2871_gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());2872}28732874void G1CollectedHeap::gc_tracer_report_gc_end(bool concurrent_operation_is_full_mark,2875G1EvacuationInfo& evacuation_info) {2876_gc_tracer_stw->report_evacuation_info(&evacuation_info);2877_gc_tracer_stw->report_tenuring_threshold(_policy->tenuring_threshold());28782879_gc_timer_stw->register_gc_end();2880_gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(),2881_gc_timer_stw->time_partitions());2882}28832884void G1CollectedHeap::do_collection_pause_at_safepoint_helper(double target_pause_time_ms) {2885GCIdMark gc_id_mark;28862887SvcGCMarker sgcm(SvcGCMarker::MINOR);2888ResourceMark rm;28892890policy()->note_gc_start();28912892gc_tracer_report_gc_start();28932894wait_for_root_region_scanning();28952896print_heap_before_gc();2897print_heap_regions();2898trace_heap_before_gc(_gc_tracer_stw);28992900_verifier->verify_region_sets_optional();2901_verifier->verify_dirty_young_regions();29022903// We should not be doing concurrent start unless the concurrent mark thread is running2904if (!_cm_thread->should_terminate()) {2905// This call will decide whether this pause is a concurrent start2906// pause. If it is, in_concurrent_start_gc() will return true2907// for the duration of this pause.2908policy()->decide_on_conc_mark_initiation();2909}29102911// We do not allow concurrent start to be piggy-backed on a mixed GC.2912assert(!collector_state()->in_concurrent_start_gc() ||2913collector_state()->in_young_only_phase(), "sanity");2914// We also do not allow mixed GCs during marking.2915assert(!collector_state()->mark_or_rebuild_in_progress() || collector_state()->in_young_only_phase(), "sanity");29162917// Record whether this pause may need to trigger a concurrent operation. Later,2918// when we signal the G1ConcurrentMarkThread, the collector state has already2919// been reset for the next pause.2920bool should_start_concurrent_mark_operation = collector_state()->in_concurrent_start_gc();2921bool concurrent_operation_is_full_mark = false;29222923// Inner scope for scope based logging, timers, and stats collection2924{2925G1EvacuationInfo evacuation_info;29262927GCTraceCPUTime tcpu;29282929char young_gc_name[MaxYoungGCNameLength];2930set_young_gc_name(young_gc_name);29312932GCTraceTime(Info, gc) tm(young_gc_name, NULL, gc_cause(), true);29332934uint active_workers = WorkerPolicy::calc_active_workers(workers()->total_workers(),2935workers()->active_workers(),2936Threads::number_of_non_daemon_threads());2937active_workers = workers()->update_active_workers(active_workers);2938log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->total_workers());29392940G1MonitoringScope ms(g1mm(),2941false /* full_gc */,2942collector_state()->in_mixed_phase() /* all_memory_pools_affected */);29432944G1HeapTransition heap_transition(this);29452946{2947IsGCActiveMark x;29482949gc_prologue(false);29502951G1HeapVerifier::G1VerifyType verify_type = young_collection_verify_type();2952verify_before_young_collection(verify_type);29532954{2955// The elapsed time induced by the start time below deliberately elides2956// the possible verification above.2957double sample_start_time_sec = os::elapsedTime();29582959// Please see comment in g1CollectedHeap.hpp and2960// G1CollectedHeap::ref_processing_init() to see how2961// reference processing currently works in G1.2962_ref_processor_stw->enable_discovery();29632964// We want to temporarily turn off discovery by the2965// CM ref processor, if necessary, and turn it back on2966// on again later if we do. Using a scoped2967// NoRefDiscovery object will do this.2968NoRefDiscovery no_cm_discovery(_ref_processor_cm);29692970policy()->record_collection_pause_start(sample_start_time_sec);29712972// Forget the current allocation region (we might even choose it to be part2973// of the collection set!).2974_allocator->release_mutator_alloc_regions();29752976calculate_collection_set(evacuation_info, target_pause_time_ms);29772978G1RedirtyCardsQueueSet rdcqs(G1BarrierSet::dirty_card_queue_set().allocator());2979G1ParScanThreadStateSet per_thread_states(this,2980&rdcqs,2981workers()->active_workers(),2982collection_set()->young_region_length(),2983collection_set()->optional_region_length());2984pre_evacuate_collection_set(evacuation_info, &per_thread_states);29852986bool may_do_optional_evacuation = _collection_set.optional_region_length() != 0;2987// Actually do the work...2988evacuate_initial_collection_set(&per_thread_states, may_do_optional_evacuation);29892990if (may_do_optional_evacuation) {2991evacuate_optional_collection_set(&per_thread_states);2992}2993post_evacuate_collection_set(evacuation_info, &rdcqs, &per_thread_states);29942995start_new_collection_set();29962997_survivor_evac_stats.adjust_desired_plab_sz();2998_old_evac_stats.adjust_desired_plab_sz();29993000allocate_dummy_regions();30013002_allocator->init_mutator_alloc_regions();30033004expand_heap_after_young_collection();30053006// Refine the type of a concurrent mark operation now that we did the3007// evacuation, eventually aborting it.3008concurrent_operation_is_full_mark = policy()->concurrent_operation_is_full_mark("Revise IHOP");30093010// Need to report the collection pause now since record_collection_pause_end()3011// modifies it to the next state.3012_gc_tracer_stw->report_young_gc_pause(collector_state()->young_gc_pause_type(concurrent_operation_is_full_mark));30133014double sample_end_time_sec = os::elapsedTime();3015double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;3016policy()->record_collection_pause_end(pause_time_ms, concurrent_operation_is_full_mark);3017}30183019verify_after_young_collection(verify_type);30203021gc_epilogue(false);3022}30233024// Print the remainder of the GC log output.3025if (evacuation_failed()) {3026log_info(gc)("To-space exhausted");3027}30283029policy()->print_phases();3030heap_transition.print();30313032_hrm.verify_optional();3033_verifier->verify_region_sets_optional();30343035TASKQUEUE_STATS_ONLY(print_taskqueue_stats());3036TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());30373038print_heap_after_gc();3039print_heap_regions();3040trace_heap_after_gc(_gc_tracer_stw);30413042// We must call G1MonitoringSupport::update_sizes() in the same scoping level3043// as an active TraceMemoryManagerStats object (i.e. before the destructor for the3044// TraceMemoryManagerStats is called) so that the G1 memory pools are updated3045// before any GC notifications are raised.3046g1mm()->update_sizes();30473048gc_tracer_report_gc_end(concurrent_operation_is_full_mark, evacuation_info);3049}3050// It should now be safe to tell the concurrent mark thread to start3051// without its logging output interfering with the logging output3052// that came from the pause.30533054if (should_start_concurrent_mark_operation) {3055// CAUTION: after the start_concurrent_cycle() call below, the concurrent marking3056// thread(s) could be running concurrently with us. Make sure that anything3057// after this point does not assume that we are the only GC thread running.3058// Note: of course, the actual marking work will not start until the safepoint3059// itself is released in SuspendibleThreadSet::desynchronize().3060start_concurrent_cycle(concurrent_operation_is_full_mark);3061ConcurrentGCBreakpoints::notify_idle_to_active();3062}3063}30643065void G1CollectedHeap::preserve_mark_during_evac_failure(uint worker_id, oop obj, markWord m) {3066_evacuation_failed_info_array[worker_id].register_copy_failure(obj->size());3067_preserved_marks_set.get(worker_id)->push_if_necessary(obj, m);3068}30693070bool G1ParEvacuateFollowersClosure::offer_termination() {3071EventGCPhaseParallel event;3072G1ParScanThreadState* const pss = par_scan_state();3073start_term_time();3074const bool res = (terminator() == nullptr) ? true : terminator()->offer_termination();3075end_term_time();3076event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(G1GCPhaseTimes::Termination));3077return res;3078}30793080void G1ParEvacuateFollowersClosure::do_void() {3081EventGCPhaseParallel event;3082G1ParScanThreadState* const pss = par_scan_state();3083pss->trim_queue();3084event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));3085do {3086EventGCPhaseParallel event;3087pss->steal_and_trim_queue(queues());3088event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));3089} while (!offer_termination());3090}30913092void G1CollectedHeap::complete_cleaning(BoolObjectClosure* is_alive,3093bool class_unloading_occurred) {3094uint num_workers = workers()->active_workers();3095G1ParallelCleaningTask unlink_task(is_alive, num_workers, class_unloading_occurred);3096workers()->run_task(&unlink_task);3097}30983099// Weak Reference Processing support31003101bool G1STWIsAliveClosure::do_object_b(oop p) {3102// An object is reachable if it is outside the collection set,3103// or is inside and copied.3104return !_g1h->is_in_cset(p) || p->is_forwarded();3105}31063107bool G1STWSubjectToDiscoveryClosure::do_object_b(oop obj) {3108assert(obj != NULL, "must not be NULL");3109assert(_g1h->is_in_reserved(obj), "Trying to discover obj " PTR_FORMAT " not in heap", p2i(obj));3110// The areas the CM and STW ref processor manage must be disjoint. The is_in_cset() below3111// may falsely indicate that this is not the case here: however the collection set only3112// contains old regions when concurrent mark is not running.3113return _g1h->is_in_cset(obj) || _g1h->heap_region_containing(obj)->is_survivor();3114}31153116// Non Copying Keep Alive closure3117class G1KeepAliveClosure: public OopClosure {3118G1CollectedHeap*_g1h;3119public:3120G1KeepAliveClosure(G1CollectedHeap* g1h) :_g1h(g1h) {}3121void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }3122void do_oop(oop* p) {3123oop obj = *p;3124assert(obj != NULL, "the caller should have filtered out NULL values");31253126const G1HeapRegionAttr region_attr =_g1h->region_attr(obj);3127if (!region_attr.is_in_cset_or_humongous()) {3128return;3129}3130if (region_attr.is_in_cset()) {3131assert( obj->is_forwarded(), "invariant" );3132*p = obj->forwardee();3133} else {3134assert(!obj->is_forwarded(), "invariant" );3135assert(region_attr.is_humongous(),3136"Only allowed G1HeapRegionAttr state is IsHumongous, but is %d", region_attr.type());3137_g1h->set_humongous_is_live(obj);3138}3139}3140};31413142// Copying Keep Alive closure - can be called from both3143// serial and parallel code as long as different worker3144// threads utilize different G1ParScanThreadState instances3145// and different queues.31463147class G1CopyingKeepAliveClosure: public OopClosure {3148G1CollectedHeap* _g1h;3149G1ParScanThreadState* _par_scan_state;31503151public:3152G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,3153G1ParScanThreadState* pss):3154_g1h(g1h),3155_par_scan_state(pss)3156{}31573158virtual void do_oop(narrowOop* p) { do_oop_work(p); }3159virtual void do_oop( oop* p) { do_oop_work(p); }31603161template <class T> void do_oop_work(T* p) {3162oop obj = RawAccess<>::oop_load(p);31633164if (_g1h->is_in_cset_or_humongous(obj)) {3165// If the referent object has been forwarded (either copied3166// to a new location or to itself in the event of an3167// evacuation failure) then we need to update the reference3168// field and, if both reference and referent are in the G13169// heap, update the RSet for the referent.3170//3171// If the referent has not been forwarded then we have to keep3172// it alive by policy. Therefore we have copy the referent.3173//3174// When the queue is drained (after each phase of reference processing)3175// the object and it's followers will be copied, the reference field set3176// to point to the new location, and the RSet updated.3177_par_scan_state->push_on_queue(ScannerTask(p));3178}3179}3180};31813182// Serial drain queue closure. Called as the 'complete_gc'3183// closure for each discovered list in some of the3184// reference processing phases.31853186class G1STWDrainQueueClosure: public VoidClosure {3187protected:3188G1CollectedHeap* _g1h;3189G1ParScanThreadState* _par_scan_state;31903191G1ParScanThreadState* par_scan_state() { return _par_scan_state; }31923193public:3194G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :3195_g1h(g1h),3196_par_scan_state(pss)3197{ }31983199void do_void() {3200G1ParScanThreadState* const pss = par_scan_state();3201pss->trim_queue();3202}3203};32043205class G1STWRefProcProxyTask : public RefProcProxyTask {3206G1CollectedHeap& _g1h;3207G1ParScanThreadStateSet& _pss;3208TaskTerminator _terminator;3209G1ScannerTasksQueueSet& _task_queues;32103211public:3212G1STWRefProcProxyTask(uint max_workers, G1CollectedHeap& g1h, G1ParScanThreadStateSet& pss, G1ScannerTasksQueueSet& task_queues)3213: RefProcProxyTask("G1STWRefProcProxyTask", max_workers),3214_g1h(g1h),3215_pss(pss),3216_terminator(max_workers, &task_queues),3217_task_queues(task_queues) {}32183219void work(uint worker_id) override {3220assert(worker_id < _max_workers, "sanity");3221uint index = (_tm == RefProcThreadModel::Single) ? 0 : worker_id;3222_pss.state_for_worker(index)->set_ref_discoverer(nullptr);3223G1STWIsAliveClosure is_alive(&_g1h);3224G1CopyingKeepAliveClosure keep_alive(&_g1h, _pss.state_for_worker(index));3225G1ParEvacuateFollowersClosure complete_gc(&_g1h, _pss.state_for_worker(index), &_task_queues, _tm == RefProcThreadModel::Single ? nullptr : &_terminator, G1GCPhaseTimes::ObjCopy);3226_rp_task->rp_work(worker_id, &is_alive, &keep_alive, &complete_gc);3227}32283229void prepare_run_task_hook() override {3230_terminator.reset_for_reuse(_queue_count);3231}3232};32333234// End of weak reference support closures32353236void G1CollectedHeap::process_discovered_references(G1ParScanThreadStateSet* per_thread_states) {3237double ref_proc_start = os::elapsedTime();32383239ReferenceProcessor* rp = _ref_processor_stw;3240assert(rp->discovery_enabled(), "should have been enabled");32413242// Use only a single queue for this PSS.3243G1ParScanThreadState* pss = per_thread_states->state_for_worker(0);3244pss->set_ref_discoverer(NULL);3245assert(pss->queue_is_empty(), "pre-condition");32463247// Setup the soft refs policy...3248rp->setup_policy(false);32493250ReferenceProcessorPhaseTimes& pt = *phase_times()->ref_phase_times();32513252ReferenceProcessorStats stats;3253uint no_of_gc_workers = workers()->active_workers();32543255// Parallel reference processing3256assert(no_of_gc_workers <= rp->max_num_queues(),3257"Mismatch between the number of GC workers %u and the maximum number of Reference process queues %u",3258no_of_gc_workers, rp->max_num_queues());32593260rp->set_active_mt_degree(no_of_gc_workers);3261G1STWRefProcProxyTask task(rp->max_num_queues(), *this, *per_thread_states, *_task_queues);3262stats = rp->process_discovered_references(task, pt);32633264_gc_tracer_stw->report_gc_reference_stats(stats);32653266// We have completed copying any necessary live referent objects.3267assert(pss->queue_is_empty(), "both queue and overflow should be empty");32683269make_pending_list_reachable();32703271assert(!rp->discovery_enabled(), "Postcondition");3272rp->verify_no_references_recorded();32733274double ref_proc_time = os::elapsedTime() - ref_proc_start;3275phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);3276}32773278void G1CollectedHeap::make_pending_list_reachable() {3279if (collector_state()->in_concurrent_start_gc()) {3280oop pll_head = Universe::reference_pending_list();3281if (pll_head != NULL) {3282// Any valid worker id is fine here as we are in the VM thread and single-threaded.3283_cm->mark_in_next_bitmap(0 /* worker_id */, pll_head);3284}3285}3286}32873288static bool do_humongous_object_logging() {3289return log_is_enabled(Debug, gc, humongous);3290}32913292bool G1CollectedHeap::should_do_eager_reclaim() const {3293// As eager reclaim logging also gives information about humongous objects in3294// the heap in general, always do the eager reclaim pass even without known3295// candidates.3296return (G1EagerReclaimHumongousObjects &&3297(has_humongous_reclaim_candidates() || do_humongous_object_logging()));3298}32993300class G1PrepareEvacuationTask : public AbstractGangTask {3301class G1PrepareRegionsClosure : public HeapRegionClosure {3302G1CollectedHeap* _g1h;3303G1PrepareEvacuationTask* _parent_task;3304uint _worker_humongous_total;3305uint _worker_humongous_candidates;33063307bool humongous_region_is_candidate(HeapRegion* region) const {3308assert(region->is_starts_humongous(), "Must start a humongous object");33093310oop obj = cast_to_oop(region->bottom());33113312// Dead objects cannot be eager reclaim candidates. Due to class3313// unloading it is unsafe to query their classes so we return early.3314if (_g1h->is_obj_dead(obj, region)) {3315return false;3316}33173318// If we do not have a complete remembered set for the region, then we can3319// not be sure that we have all references to it.3320if (!region->rem_set()->is_complete()) {3321return false;3322}3323// Candidate selection must satisfy the following constraints3324// while concurrent marking is in progress:3325//3326// * In order to maintain SATB invariants, an object must not be3327// reclaimed if it was allocated before the start of marking and3328// has not had its references scanned. Such an object must have3329// its references (including type metadata) scanned to ensure no3330// live objects are missed by the marking process. Objects3331// allocated after the start of concurrent marking don't need to3332// be scanned.3333//3334// * An object must not be reclaimed if it is on the concurrent3335// mark stack. Objects allocated after the start of concurrent3336// marking are never pushed on the mark stack.3337//3338// Nominating only objects allocated after the start of concurrent3339// marking is sufficient to meet both constraints. This may miss3340// some objects that satisfy the constraints, but the marking data3341// structures don't support efficiently performing the needed3342// additional tests or scrubbing of the mark stack.3343//3344// However, we presently only nominate is_typeArray() objects.3345// A humongous object containing references induces remembered3346// set entries on other regions. In order to reclaim such an3347// object, those remembered sets would need to be cleaned up.3348//3349// We also treat is_typeArray() objects specially, allowing them3350// to be reclaimed even if allocated before the start of3351// concurrent mark. For this we rely on mark stack insertion to3352// exclude is_typeArray() objects, preventing reclaiming an object3353// that is in the mark stack. We also rely on the metadata for3354// such objects to be built-in and so ensured to be kept live.3355// Frequent allocation and drop of large binary blobs is an3356// important use case for eager reclaim, and this special handling3357// may reduce needed headroom.33583359return obj->is_typeArray() &&3360_g1h->is_potential_eager_reclaim_candidate(region);3361}33623363public:3364G1PrepareRegionsClosure(G1CollectedHeap* g1h, G1PrepareEvacuationTask* parent_task) :3365_g1h(g1h),3366_parent_task(parent_task),3367_worker_humongous_total(0),3368_worker_humongous_candidates(0) { }33693370~G1PrepareRegionsClosure() {3371_parent_task->add_humongous_candidates(_worker_humongous_candidates);3372_parent_task->add_humongous_total(_worker_humongous_total);3373}33743375virtual bool do_heap_region(HeapRegion* hr) {3376// First prepare the region for scanning3377_g1h->rem_set()->prepare_region_for_scan(hr);33783379// Now check if region is a humongous candidate3380if (!hr->is_starts_humongous()) {3381_g1h->register_region_with_region_attr(hr);3382return false;3383}33843385uint index = hr->hrm_index();3386if (humongous_region_is_candidate(hr)) {3387_g1h->set_humongous_reclaim_candidate(index, true);3388_g1h->register_humongous_region_with_region_attr(index);3389_worker_humongous_candidates++;3390// We will later handle the remembered sets of these regions.3391} else {3392_g1h->set_humongous_reclaim_candidate(index, false);3393_g1h->register_region_with_region_attr(hr);3394}3395_worker_humongous_total++;33963397return false;3398}3399};34003401G1CollectedHeap* _g1h;3402HeapRegionClaimer _claimer;3403volatile uint _humongous_total;3404volatile uint _humongous_candidates;3405public:3406G1PrepareEvacuationTask(G1CollectedHeap* g1h) :3407AbstractGangTask("Prepare Evacuation"),3408_g1h(g1h),3409_claimer(_g1h->workers()->active_workers()),3410_humongous_total(0),3411_humongous_candidates(0) { }34123413void work(uint worker_id) {3414G1PrepareRegionsClosure cl(_g1h, this);3415_g1h->heap_region_par_iterate_from_worker_offset(&cl, &_claimer, worker_id);3416}34173418void add_humongous_candidates(uint candidates) {3419Atomic::add(&_humongous_candidates, candidates);3420}34213422void add_humongous_total(uint total) {3423Atomic::add(&_humongous_total, total);3424}34253426uint humongous_candidates() {3427return _humongous_candidates;3428}34293430uint humongous_total() {3431return _humongous_total;3432}3433};34343435void G1CollectedHeap::pre_evacuate_collection_set(G1EvacuationInfo& evacuation_info, G1ParScanThreadStateSet* per_thread_states) {3436_bytes_used_during_gc = 0;34373438_expand_heap_after_alloc_failure = true;3439Atomic::store(&_num_regions_failed_evacuation, 0u);34403441// Disable the hot card cache.3442_hot_card_cache->reset_hot_cache_claimed_index();3443_hot_card_cache->set_use_cache(false);34443445// Initialize the GC alloc regions.3446_allocator->init_gc_alloc_regions(evacuation_info);34473448{3449Ticks start = Ticks::now();3450rem_set()->prepare_for_scan_heap_roots();3451phase_times()->record_prepare_heap_roots_time_ms((Ticks::now() - start).seconds() * 1000.0);3452}34533454{3455G1PrepareEvacuationTask g1_prep_task(this);3456Tickspan task_time = run_task_timed(&g1_prep_task);34573458phase_times()->record_register_regions(task_time.seconds() * 1000.0);3459_num_humongous_objects = g1_prep_task.humongous_total();3460_num_humongous_reclaim_candidates = g1_prep_task.humongous_candidates();3461}34623463assert(_verifier->check_region_attr_table(), "Inconsistency in the region attributes table.");3464_preserved_marks_set.assert_empty();34653466#if COMPILER2_OR_JVMCI3467DerivedPointerTable::clear();3468#endif34693470// Concurrent start needs claim bits to keep track of the marked-through CLDs.3471if (collector_state()->in_concurrent_start_gc()) {3472concurrent_mark()->pre_concurrent_start(gc_cause());34733474double start_clear_claimed_marks = os::elapsedTime();34753476ClassLoaderDataGraph::clear_claimed_marks();34773478double recorded_clear_claimed_marks_time_ms = (os::elapsedTime() - start_clear_claimed_marks) * 1000.0;3479phase_times()->record_clear_claimed_marks_time_ms(recorded_clear_claimed_marks_time_ms);3480}34813482// Should G1EvacuationFailureALot be in effect for this GC?3483NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)3484}34853486class G1EvacuateRegionsBaseTask : public AbstractGangTask {3487protected:3488G1CollectedHeap* _g1h;3489G1ParScanThreadStateSet* _per_thread_states;3490G1ScannerTasksQueueSet* _task_queues;3491TaskTerminator _terminator;3492uint _num_workers;34933494void evacuate_live_objects(G1ParScanThreadState* pss,3495uint worker_id,3496G1GCPhaseTimes::GCParPhases objcopy_phase,3497G1GCPhaseTimes::GCParPhases termination_phase) {3498G1GCPhaseTimes* p = _g1h->phase_times();34993500Ticks start = Ticks::now();3501G1ParEvacuateFollowersClosure cl(_g1h, pss, _task_queues, &_terminator, objcopy_phase);3502cl.do_void();35033504assert(pss->queue_is_empty(), "should be empty");35053506Tickspan evac_time = (Ticks::now() - start);3507p->record_or_add_time_secs(objcopy_phase, worker_id, evac_time.seconds() - cl.term_time());35083509if (termination_phase == G1GCPhaseTimes::Termination) {3510p->record_time_secs(termination_phase, worker_id, cl.term_time());3511p->record_thread_work_item(termination_phase, worker_id, cl.term_attempts());3512} else {3513p->record_or_add_time_secs(termination_phase, worker_id, cl.term_time());3514p->record_or_add_thread_work_item(termination_phase, worker_id, cl.term_attempts());3515}3516assert(pss->trim_ticks().value() == 0,3517"Unexpected partial trimming during evacuation value " JLONG_FORMAT,3518pss->trim_ticks().value());3519}35203521virtual void start_work(uint worker_id) { }35223523virtual void end_work(uint worker_id) { }35243525virtual void scan_roots(G1ParScanThreadState* pss, uint worker_id) = 0;35263527virtual void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) = 0;35283529public:3530G1EvacuateRegionsBaseTask(const char* name,3531G1ParScanThreadStateSet* per_thread_states,3532G1ScannerTasksQueueSet* task_queues,3533uint num_workers) :3534AbstractGangTask(name),3535_g1h(G1CollectedHeap::heap()),3536_per_thread_states(per_thread_states),3537_task_queues(task_queues),3538_terminator(num_workers, _task_queues),3539_num_workers(num_workers)3540{ }35413542void work(uint worker_id) {3543start_work(worker_id);35443545{3546ResourceMark rm;35473548G1ParScanThreadState* pss = _per_thread_states->state_for_worker(worker_id);3549pss->set_ref_discoverer(_g1h->ref_processor_stw());35503551scan_roots(pss, worker_id);3552evacuate_live_objects(pss, worker_id);3553}35543555end_work(worker_id);3556}3557};35583559class G1EvacuateRegionsTask : public G1EvacuateRegionsBaseTask {3560G1RootProcessor* _root_processor;3561bool _has_optional_evacuation_work;35623563void scan_roots(G1ParScanThreadState* pss, uint worker_id) {3564_root_processor->evacuate_roots(pss, worker_id);3565_g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::ObjCopy, _has_optional_evacuation_work);3566_g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::CodeRoots, G1GCPhaseTimes::ObjCopy);3567}35683569void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {3570G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::ObjCopy, G1GCPhaseTimes::Termination);3571}35723573void start_work(uint worker_id) {3574_g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, Ticks::now().seconds());3575}35763577void end_work(uint worker_id) {3578_g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, Ticks::now().seconds());3579}35803581public:3582G1EvacuateRegionsTask(G1CollectedHeap* g1h,3583G1ParScanThreadStateSet* per_thread_states,3584G1ScannerTasksQueueSet* task_queues,3585G1RootProcessor* root_processor,3586uint num_workers,3587bool has_optional_evacuation_work) :3588G1EvacuateRegionsBaseTask("G1 Evacuate Regions", per_thread_states, task_queues, num_workers),3589_root_processor(root_processor),3590_has_optional_evacuation_work(has_optional_evacuation_work)3591{ }3592};35933594void G1CollectedHeap::evacuate_initial_collection_set(G1ParScanThreadStateSet* per_thread_states,3595bool has_optional_evacuation_work) {3596G1GCPhaseTimes* p = phase_times();35973598{3599Ticks start = Ticks::now();3600rem_set()->merge_heap_roots(true /* initial_evacuation */);3601p->record_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);3602}36033604Tickspan task_time;3605const uint num_workers = workers()->active_workers();36063607Ticks start_processing = Ticks::now();3608{3609G1RootProcessor root_processor(this, num_workers);3610G1EvacuateRegionsTask g1_par_task(this,3611per_thread_states,3612_task_queues,3613&root_processor,3614num_workers,3615has_optional_evacuation_work);3616task_time = run_task_timed(&g1_par_task);3617// Closing the inner scope will execute the destructor for the G1RootProcessor object.3618// To extract its code root fixup time we measure total time of this scope and3619// subtract from the time the WorkGang task took.3620}3621Tickspan total_processing = Ticks::now() - start_processing;36223623p->record_initial_evac_time(task_time.seconds() * 1000.0);3624p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);36253626rem_set()->complete_evac_phase(has_optional_evacuation_work);3627}36283629class G1EvacuateOptionalRegionsTask : public G1EvacuateRegionsBaseTask {36303631void scan_roots(G1ParScanThreadState* pss, uint worker_id) {3632_g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptObjCopy, true /* remember_already_scanned_cards */);3633_g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptCodeRoots, G1GCPhaseTimes::OptObjCopy);3634}36353636void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {3637G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::OptObjCopy, G1GCPhaseTimes::OptTermination);3638}36393640public:3641G1EvacuateOptionalRegionsTask(G1ParScanThreadStateSet* per_thread_states,3642G1ScannerTasksQueueSet* queues,3643uint num_workers) :3644G1EvacuateRegionsBaseTask("G1 Evacuate Optional Regions", per_thread_states, queues, num_workers) {3645}3646};36473648void G1CollectedHeap::evacuate_next_optional_regions(G1ParScanThreadStateSet* per_thread_states) {3649class G1MarkScope : public MarkScope { };36503651Tickspan task_time;36523653Ticks start_processing = Ticks::now();3654{3655G1MarkScope code_mark_scope;3656G1EvacuateOptionalRegionsTask task(per_thread_states, _task_queues, workers()->active_workers());3657task_time = run_task_timed(&task);3658// See comment in evacuate_collection_set() for the reason of the scope.3659}3660Tickspan total_processing = Ticks::now() - start_processing;36613662G1GCPhaseTimes* p = phase_times();3663p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);3664}36653666void G1CollectedHeap::evacuate_optional_collection_set(G1ParScanThreadStateSet* per_thread_states) {3667const double gc_start_time_ms = phase_times()->cur_collection_start_sec() * 1000.0;36683669while (!evacuation_failed() && _collection_set.optional_region_length() > 0) {36703671double time_used_ms = os::elapsedTime() * 1000.0 - gc_start_time_ms;3672double time_left_ms = MaxGCPauseMillis - time_used_ms;36733674if (time_left_ms < 0 ||3675!_collection_set.finalize_optional_for_evacuation(time_left_ms * policy()->optional_evacuation_fraction())) {3676log_trace(gc, ergo, cset)("Skipping evacuation of %u optional regions, no more regions can be evacuated in %.3fms",3677_collection_set.optional_region_length(), time_left_ms);3678break;3679}36803681{3682Ticks start = Ticks::now();3683rem_set()->merge_heap_roots(false /* initial_evacuation */);3684phase_times()->record_or_add_optional_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);3685}36863687{3688Ticks start = Ticks::now();3689evacuate_next_optional_regions(per_thread_states);3690phase_times()->record_or_add_optional_evac_time((Ticks::now() - start).seconds() * 1000.0);3691}36923693rem_set()->complete_evac_phase(true /* has_more_than_one_evacuation_phase */);3694}36953696_collection_set.abandon_optional_collection_set(per_thread_states);3697}36983699void G1CollectedHeap::post_evacuate_collection_set(G1EvacuationInfo& evacuation_info,3700G1RedirtyCardsQueueSet* rdcqs,3701G1ParScanThreadStateSet* per_thread_states) {3702G1GCPhaseTimes* p = phase_times();37033704// Process any discovered reference objects - we have3705// to do this _before_ we retire the GC alloc regions3706// as we may have to copy some 'reachable' referent3707// objects (and their reachable sub-graphs) that were3708// not copied during the pause.3709process_discovered_references(per_thread_states);37103711G1STWIsAliveClosure is_alive(this);3712G1KeepAliveClosure keep_alive(this);37133714WeakProcessor::weak_oops_do(workers(), &is_alive, &keep_alive, p->weak_phase_times());37153716_allocator->release_gc_alloc_regions(evacuation_info);37173718post_evacuate_cleanup_1(per_thread_states, rdcqs);37193720post_evacuate_cleanup_2(&_preserved_marks_set, rdcqs, &evacuation_info, per_thread_states->surviving_young_words());37213722assert_used_and_recalculate_used_equal(this);37233724rebuild_free_region_list();37253726record_obj_copy_mem_stats();37273728evacuation_info.set_collectionset_used_before(collection_set()->bytes_used_before());3729evacuation_info.set_bytes_used(_bytes_used_during_gc);37303731policy()->print_age_table();3732}37333734void G1CollectedHeap::record_obj_copy_mem_stats() {3735policy()->old_gen_alloc_tracker()->3736add_allocated_bytes_since_last_gc(_old_evac_stats.allocated() * HeapWordSize);37373738_gc_tracer_stw->report_evacuation_statistics(create_g1_evac_summary(&_survivor_evac_stats),3739create_g1_evac_summary(&_old_evac_stats));3740}37413742void G1CollectedHeap::free_region(HeapRegion* hr, FreeRegionList* free_list) {3743assert(!hr->is_free(), "the region should not be free");3744assert(!hr->is_empty(), "the region should not be empty");3745assert(_hrm.is_available(hr->hrm_index()), "region should be committed");37463747if (G1VerifyBitmaps) {3748MemRegion mr(hr->bottom(), hr->end());3749concurrent_mark()->clear_range_in_prev_bitmap(mr);3750}37513752// Clear the card counts for this region.3753// Note: we only need to do this if the region is not young3754// (since we don't refine cards in young regions).3755if (!hr->is_young()) {3756_hot_card_cache->reset_card_counts(hr);3757}37583759// Reset region metadata to allow reuse.3760hr->hr_clear(true /* clear_space */);3761_policy->remset_tracker()->update_at_free(hr);37623763if (free_list != NULL) {3764free_list->add_ordered(hr);3765}3766}37673768void G1CollectedHeap::free_humongous_region(HeapRegion* hr,3769FreeRegionList* free_list) {3770assert(hr->is_humongous(), "this is only for humongous regions");3771hr->clear_humongous();3772free_region(hr, free_list);3773}37743775void G1CollectedHeap::remove_from_old_gen_sets(const uint old_regions_removed,3776const uint archive_regions_removed,3777const uint humongous_regions_removed) {3778if (old_regions_removed > 0 || archive_regions_removed > 0 || humongous_regions_removed > 0) {3779MutexLocker x(OldSets_lock, Mutex::_no_safepoint_check_flag);3780_old_set.bulk_remove(old_regions_removed);3781_archive_set.bulk_remove(archive_regions_removed);3782_humongous_set.bulk_remove(humongous_regions_removed);3783}37843785}37863787void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {3788assert(list != NULL, "list can't be null");3789if (!list->is_empty()) {3790MutexLocker x(FreeList_lock, Mutex::_no_safepoint_check_flag);3791_hrm.insert_list_into_free_list(list);3792}3793}37943795void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {3796decrease_used(bytes);3797}37983799void G1CollectedHeap::post_evacuate_cleanup_1(G1ParScanThreadStateSet* per_thread_states,3800G1RedirtyCardsQueueSet* rdcqs) {3801Ticks start = Ticks::now();3802{3803G1PostEvacuateCollectionSetCleanupTask1 cl(per_thread_states, rdcqs);3804run_batch_task(&cl);3805}3806phase_times()->record_post_evacuate_cleanup_task_1_time((Ticks::now() - start).seconds() * 1000.0);3807}38083809void G1CollectedHeap::post_evacuate_cleanup_2(PreservedMarksSet* preserved_marks,3810G1RedirtyCardsQueueSet* rdcqs,3811G1EvacuationInfo* evacuation_info,3812const size_t* surviving_young_words) {3813Ticks start = Ticks::now();3814{3815G1PostEvacuateCollectionSetCleanupTask2 cl(preserved_marks, rdcqs, evacuation_info, surviving_young_words);3816run_batch_task(&cl);3817}3818phase_times()->record_post_evacuate_cleanup_task_2_time((Ticks::now() - start).seconds() * 1000.0);3819}38203821void G1CollectedHeap::clear_eden() {3822_eden.clear();3823}38243825void G1CollectedHeap::clear_collection_set() {3826collection_set()->clear();3827}38283829void G1CollectedHeap::rebuild_free_region_list() {3830Ticks start = Ticks::now();3831_hrm.rebuild_free_list(workers());3832phase_times()->record_total_rebuild_freelist_time_ms((Ticks::now() - start).seconds() * 1000.0);3833}38343835class G1AbandonCollectionSetClosure : public HeapRegionClosure {3836public:3837virtual bool do_heap_region(HeapRegion* r) {3838assert(r->in_collection_set(), "Region %u must have been in collection set", r->hrm_index());3839G1CollectedHeap::heap()->clear_region_attr(r);3840r->clear_young_index_in_cset();3841return false;3842}3843};38443845void G1CollectedHeap::abandon_collection_set(G1CollectionSet* collection_set) {3846G1AbandonCollectionSetClosure cl;3847collection_set_iterate_all(&cl);38483849collection_set->clear();3850collection_set->stop_incremental_building();3851}38523853bool G1CollectedHeap::is_old_gc_alloc_region(HeapRegion* hr) {3854return _allocator->is_retained_old_region(hr);3855}38563857void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {3858_eden.add(hr);3859_policy->set_region_eden(hr);3860}38613862#ifdef ASSERT38633864class NoYoungRegionsClosure: public HeapRegionClosure {3865private:3866bool _success;3867public:3868NoYoungRegionsClosure() : _success(true) { }3869bool do_heap_region(HeapRegion* r) {3870if (r->is_young()) {3871log_error(gc, verify)("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young",3872p2i(r->bottom()), p2i(r->end()));3873_success = false;3874}3875return false;3876}3877bool success() { return _success; }3878};38793880bool G1CollectedHeap::check_young_list_empty() {3881bool ret = (young_regions_count() == 0);38823883NoYoungRegionsClosure closure;3884heap_region_iterate(&closure);3885ret = ret && closure.success();38863887return ret;3888}38893890#endif // ASSERT38913892// Remove the given HeapRegion from the appropriate region set.3893void G1CollectedHeap::prepare_region_for_full_compaction(HeapRegion* hr) {3894if (hr->is_archive()) {3895_archive_set.remove(hr);3896} else if (hr->is_humongous()) {3897_humongous_set.remove(hr);3898} else if (hr->is_old()) {3899_old_set.remove(hr);3900} else if (hr->is_young()) {3901// Note that emptying the eden and survivor lists is postponed and instead3902// done as the first step when rebuilding the regions sets again. The reason3903// for this is that during a full GC string deduplication needs to know if3904// a collected region was young or old when the full GC was initiated.3905hr->uninstall_surv_rate_group();3906} else {3907// We ignore free regions, we'll empty the free list afterwards.3908assert(hr->is_free(), "it cannot be another type");3909}3910}39113912void G1CollectedHeap::increase_used(size_t bytes) {3913_summary_bytes_used += bytes;3914}39153916void G1CollectedHeap::decrease_used(size_t bytes) {3917assert(_summary_bytes_used >= bytes,3918"invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT,3919_summary_bytes_used, bytes);3920_summary_bytes_used -= bytes;3921}39223923void G1CollectedHeap::set_used(size_t bytes) {3924_summary_bytes_used = bytes;3925}39263927class RebuildRegionSetsClosure : public HeapRegionClosure {3928private:3929bool _free_list_only;39303931HeapRegionSet* _old_set;3932HeapRegionSet* _archive_set;3933HeapRegionSet* _humongous_set;39343935HeapRegionManager* _hrm;39363937size_t _total_used;39383939public:3940RebuildRegionSetsClosure(bool free_list_only,3941HeapRegionSet* old_set,3942HeapRegionSet* archive_set,3943HeapRegionSet* humongous_set,3944HeapRegionManager* hrm) :3945_free_list_only(free_list_only), _old_set(old_set), _archive_set(archive_set),3946_humongous_set(humongous_set), _hrm(hrm), _total_used(0) {3947assert(_hrm->num_free_regions() == 0, "pre-condition");3948if (!free_list_only) {3949assert(_old_set->is_empty(), "pre-condition");3950assert(_archive_set->is_empty(), "pre-condition");3951assert(_humongous_set->is_empty(), "pre-condition");3952}3953}39543955bool do_heap_region(HeapRegion* r) {3956if (r->is_empty()) {3957assert(r->rem_set()->is_empty(), "Empty regions should have empty remembered sets.");3958// Add free regions to the free list3959r->set_free();3960_hrm->insert_into_free_list(r);3961} else if (!_free_list_only) {3962assert(r->rem_set()->is_empty(), "At this point remembered sets must have been cleared.");39633964if (r->is_humongous()) {3965_humongous_set->add(r);3966} else if (r->is_archive()) {3967_archive_set->add(r);3968} else {3969assert(r->is_young() || r->is_free() || r->is_old(), "invariant");3970// We now move all (non-humongous, non-old, non-archive) regions to old gen,3971// and register them as such.3972r->move_to_old();3973_old_set->add(r);3974}3975_total_used += r->used();3976}39773978return false;3979}39803981size_t total_used() {3982return _total_used;3983}3984};39853986void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {3987assert_at_safepoint_on_vm_thread();39883989if (!free_list_only) {3990_eden.clear();3991_survivor.clear();3992}39933994RebuildRegionSetsClosure cl(free_list_only,3995&_old_set, &_archive_set, &_humongous_set,3996&_hrm);3997heap_region_iterate(&cl);39983999if (!free_list_only) {4000set_used(cl.total_used());4001if (_archive_allocator != NULL) {4002_archive_allocator->clear_used();4003}4004}4005assert_used_and_recalculate_used_equal(this);4006}40074008// Methods for the mutator alloc region40094010HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,4011bool force,4012uint node_index) {4013assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);4014bool should_allocate = policy()->should_allocate_mutator_region();4015if (force || should_allocate) {4016HeapRegion* new_alloc_region = new_region(word_size,4017HeapRegionType::Eden,4018false /* do_expand */,4019node_index);4020if (new_alloc_region != NULL) {4021set_region_short_lived_locked(new_alloc_region);4022_hr_printer.alloc(new_alloc_region, !should_allocate);4023_verifier->check_bitmaps("Mutator Region Allocation", new_alloc_region);4024_policy->remset_tracker()->update_at_allocate(new_alloc_region);4025return new_alloc_region;4026}4027}4028return NULL;4029}40304031void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,4032size_t allocated_bytes) {4033assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);4034assert(alloc_region->is_eden(), "all mutator alloc regions should be eden");40354036collection_set()->add_eden_region(alloc_region);4037increase_used(allocated_bytes);4038_eden.add_used_bytes(allocated_bytes);4039_hr_printer.retire(alloc_region);40404041// We update the eden sizes here, when the region is retired,4042// instead of when it's allocated, since this is the point that its4043// used space has been recorded in _summary_bytes_used.4044g1mm()->update_eden_size();4045}40464047// Methods for the GC alloc regions40484049bool G1CollectedHeap::has_more_regions(G1HeapRegionAttr dest) {4050if (dest.is_old()) {4051return true;4052} else {4053return survivor_regions_count() < policy()->max_survivor_regions();4054}4055}40564057HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index) {4058assert(FreeList_lock->owned_by_self(), "pre-condition");40594060if (!has_more_regions(dest)) {4061return NULL;4062}40634064HeapRegionType type;4065if (dest.is_young()) {4066type = HeapRegionType::Survivor;4067} else {4068type = HeapRegionType::Old;4069}40704071HeapRegion* new_alloc_region = new_region(word_size,4072type,4073true /* do_expand */,4074node_index);40754076if (new_alloc_region != NULL) {4077if (type.is_survivor()) {4078new_alloc_region->set_survivor();4079_survivor.add(new_alloc_region);4080_verifier->check_bitmaps("Survivor Region Allocation", new_alloc_region);4081} else {4082new_alloc_region->set_old();4083_verifier->check_bitmaps("Old Region Allocation", new_alloc_region);4084}4085_policy->remset_tracker()->update_at_allocate(new_alloc_region);4086register_region_with_region_attr(new_alloc_region);4087_hr_printer.alloc(new_alloc_region);4088return new_alloc_region;4089}4090return NULL;4091}40924093void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,4094size_t allocated_bytes,4095G1HeapRegionAttr dest) {4096_bytes_used_during_gc += allocated_bytes;4097if (dest.is_old()) {4098old_set_add(alloc_region);4099} else {4100assert(dest.is_young(), "Retiring alloc region should be young (%d)", dest.type());4101_survivor.add_used_bytes(allocated_bytes);4102}41034104bool const during_im = collector_state()->in_concurrent_start_gc();4105if (during_im && allocated_bytes > 0) {4106_cm->root_regions()->add(alloc_region->next_top_at_mark_start(), alloc_region->top());4107}4108_hr_printer.retire(alloc_region);4109}41104111HeapRegion* G1CollectedHeap::alloc_highest_free_region() {4112bool expanded = false;4113uint index = _hrm.find_highest_free(&expanded);41144115if (index != G1_NO_HRM_INDEX) {4116if (expanded) {4117log_debug(gc, ergo, heap)("Attempt heap expansion (requested address range outside heap bounds). region size: " SIZE_FORMAT "B",4118HeapRegion::GrainWords * HeapWordSize);4119}4120return _hrm.allocate_free_regions_starting_at(index, 1);4121}4122return NULL;4123}41244125// Optimized nmethod scanning41264127class RegisterNMethodOopClosure: public OopClosure {4128G1CollectedHeap* _g1h;4129nmethod* _nm;41304131template <class T> void do_oop_work(T* p) {4132T heap_oop = RawAccess<>::oop_load(p);4133if (!CompressedOops::is_null(heap_oop)) {4134oop obj = CompressedOops::decode_not_null(heap_oop);4135HeapRegion* hr = _g1h->heap_region_containing(obj);4136assert(!hr->is_continues_humongous(),4137"trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT4138" starting at " HR_FORMAT,4139p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));41404141// HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries.4142hr->add_strong_code_root_locked(_nm);4143}4144}41454146public:4147RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :4148_g1h(g1h), _nm(nm) {}41494150void do_oop(oop* p) { do_oop_work(p); }4151void do_oop(narrowOop* p) { do_oop_work(p); }4152};41534154class UnregisterNMethodOopClosure: public OopClosure {4155G1CollectedHeap* _g1h;4156nmethod* _nm;41574158template <class T> void do_oop_work(T* p) {4159T heap_oop = RawAccess<>::oop_load(p);4160if (!CompressedOops::is_null(heap_oop)) {4161oop obj = CompressedOops::decode_not_null(heap_oop);4162HeapRegion* hr = _g1h->heap_region_containing(obj);4163assert(!hr->is_continues_humongous(),4164"trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT4165" starting at " HR_FORMAT,4166p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));41674168hr->remove_strong_code_root(_nm);4169}4170}41714172public:4173UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :4174_g1h(g1h), _nm(nm) {}41754176void do_oop(oop* p) { do_oop_work(p); }4177void do_oop(narrowOop* p) { do_oop_work(p); }4178};41794180void G1CollectedHeap::register_nmethod(nmethod* nm) {4181guarantee(nm != NULL, "sanity");4182RegisterNMethodOopClosure reg_cl(this, nm);4183nm->oops_do(®_cl);4184}41854186void G1CollectedHeap::unregister_nmethod(nmethod* nm) {4187guarantee(nm != NULL, "sanity");4188UnregisterNMethodOopClosure reg_cl(this, nm);4189nm->oops_do(®_cl, true);4190}41914192void G1CollectedHeap::update_used_after_gc() {4193if (evacuation_failed()) {4194// Reset the G1EvacuationFailureALot counters and flags4195NOT_PRODUCT(reset_evacuation_should_fail();)41964197set_used(recalculate_used());41984199if (_archive_allocator != NULL) {4200_archive_allocator->clear_used();4201}4202for (uint i = 0; i < ParallelGCThreads; i++) {4203if (_evacuation_failed_info_array[i].has_failed()) {4204_gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);4205}4206}4207} else {4208// The "used" of the the collection set have already been subtracted4209// when they were freed. Add in the bytes used.4210increase_used(_bytes_used_during_gc);4211}4212}42134214void G1CollectedHeap::reset_hot_card_cache() {4215_hot_card_cache->reset_hot_cache();4216_hot_card_cache->set_use_cache(true);4217}42184219void G1CollectedHeap::purge_code_root_memory() {4220G1CodeRootSet::purge();4221}42224223class RebuildStrongCodeRootClosure: public CodeBlobClosure {4224G1CollectedHeap* _g1h;42254226public:4227RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :4228_g1h(g1h) {}42294230void do_code_blob(CodeBlob* cb) {4231nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;4232if (nm == NULL) {4233return;4234}42354236_g1h->register_nmethod(nm);4237}4238};42394240void G1CollectedHeap::rebuild_strong_code_roots() {4241RebuildStrongCodeRootClosure blob_cl(this);4242CodeCache::blobs_do(&blob_cl);4243}42444245void G1CollectedHeap::initialize_serviceability() {4246_g1mm->initialize_serviceability();4247}42484249MemoryUsage G1CollectedHeap::memory_usage() {4250return _g1mm->memory_usage();4251}42524253GrowableArray<GCMemoryManager*> G1CollectedHeap::memory_managers() {4254return _g1mm->memory_managers();4255}42564257GrowableArray<MemoryPool*> G1CollectedHeap::memory_pools() {4258return _g1mm->memory_pools();4259}426042614262