Path: blob/master/src/hotspot/share/gc/g1/g1CollectedHeap.cpp
66644 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;396bool preventive_collection_required = false;397uint gc_count_before;398399{400MutexLocker x(Heap_lock);401402// Now that we have the lock, we first retry the allocation in case another403// thread changed the region while we were waiting to acquire the lock.404size_t actual_size;405result = _allocator->attempt_allocation(word_size, word_size, &actual_size);406if (result != NULL) {407return result;408}409410preventive_collection_required = policy()->preventive_collection_required(1);411if (!preventive_collection_required) {412// We've already attempted a lock-free allocation above, so we don't want to413// do it again. Let's jump straight to replacing the active region.414result = _allocator->attempt_allocation_using_new_region(word_size);415if (result != NULL) {416return result;417}418419// If the GCLocker is active and we are bound for a GC, try expanding young gen.420// This is different to when only GCLocker::needs_gc() is set: try to avoid421// waiting because the GCLocker is active to not wait too long.422if (GCLocker::is_active_and_needs_gc() && policy()->can_expand_young_list()) {423// No need for an ergo message here, can_expand_young_list() does this when424// it returns true.425result = _allocator->attempt_allocation_force(word_size);426if (result != NULL) {427return result;428}429}430}431432// Only try a GC if the GCLocker does not signal the need for a GC. Wait until433// the GCLocker initiated GC has been performed and then retry. This includes434// the case when the GC Locker is not active but has not been performed.435should_try_gc = !GCLocker::needs_gc();436// Read the GC count while still holding the Heap_lock.437gc_count_before = total_collections();438}439440if (should_try_gc) {441GCCause::Cause gc_cause = preventive_collection_required ? GCCause::_g1_preventive_collection442: GCCause::_g1_inc_collection_pause;443bool succeeded;444result = do_collection_pause(word_size, gc_count_before, &succeeded, gc_cause);445if (result != NULL) {446assert(succeeded, "only way to get back a non-NULL result");447log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,448Thread::current()->name(), p2i(result));449return result;450}451452if (succeeded) {453// We successfully scheduled a collection which failed to allocate. No454// point in trying to allocate further. We'll just return NULL.455log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "456SIZE_FORMAT " words", Thread::current()->name(), word_size);457return NULL;458}459log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT " words",460Thread::current()->name(), word_size);461} else {462// Failed to schedule a collection.463if (gclocker_retry_count > GCLockerRetryAllocationCount) {464log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "465SIZE_FORMAT " words", Thread::current()->name(), word_size);466return NULL;467}468log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());469// The GCLocker is either active or the GCLocker initiated470// GC has not yet been performed. Stall until it is and471// then retry the allocation.472GCLocker::stall_until_clear();473gclocker_retry_count += 1;474}475476// We can reach here if we were unsuccessful in scheduling a477// collection (because another thread beat us to it) or if we were478// stalled due to the GC locker. In either can we should retry the479// allocation attempt in case another thread successfully480// performed a collection and reclaimed enough space. We do the481// first attempt (without holding the Heap_lock) here and the482// follow-on attempt will be at the start of the next loop483// iteration (after taking the Heap_lock).484size_t dummy = 0;485result = _allocator->attempt_allocation(word_size, word_size, &dummy);486if (result != NULL) {487return result;488}489490// Give a warning if we seem to be looping forever.491if ((QueuedAllocationWarningCount > 0) &&492(try_count % QueuedAllocationWarningCount == 0)) {493log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",494Thread::current()->name(), try_count, word_size);495}496}497498ShouldNotReachHere();499return NULL;500}501502void G1CollectedHeap::begin_archive_alloc_range(bool open) {503assert_at_safepoint_on_vm_thread();504if (_archive_allocator == NULL) {505_archive_allocator = G1ArchiveAllocator::create_allocator(this, open);506}507}508509bool G1CollectedHeap::is_archive_alloc_too_large(size_t word_size) {510// Allocations in archive regions cannot be of a size that would be considered511// humongous even for a minimum-sized region, because G1 region sizes/boundaries512// may be different at archive-restore time.513return word_size >= humongous_threshold_for(HeapRegion::min_region_size_in_words());514}515516HeapWord* G1CollectedHeap::archive_mem_allocate(size_t word_size) {517assert_at_safepoint_on_vm_thread();518assert(_archive_allocator != NULL, "_archive_allocator not initialized");519if (is_archive_alloc_too_large(word_size)) {520return NULL;521}522return _archive_allocator->archive_mem_allocate(word_size);523}524525void G1CollectedHeap::end_archive_alloc_range(GrowableArray<MemRegion>* ranges,526size_t end_alignment_in_bytes) {527assert_at_safepoint_on_vm_thread();528assert(_archive_allocator != NULL, "_archive_allocator not initialized");529530// Call complete_archive to do the real work, filling in the MemRegion531// array with the archive regions.532_archive_allocator->complete_archive(ranges, end_alignment_in_bytes);533delete _archive_allocator;534_archive_allocator = NULL;535}536537bool G1CollectedHeap::check_archive_addresses(MemRegion* ranges, size_t count) {538assert(ranges != NULL, "MemRegion array NULL");539assert(count != 0, "No MemRegions provided");540MemRegion reserved = _hrm.reserved();541for (size_t i = 0; i < count; i++) {542if (!reserved.contains(ranges[i].start()) || !reserved.contains(ranges[i].last())) {543return false;544}545}546return true;547}548549bool G1CollectedHeap::alloc_archive_regions(MemRegion* ranges,550size_t count,551bool open) {552assert(!is_init_completed(), "Expect to be called at JVM init time");553assert(ranges != NULL, "MemRegion array NULL");554assert(count != 0, "No MemRegions provided");555MutexLocker x(Heap_lock);556557MemRegion reserved = _hrm.reserved();558HeapWord* prev_last_addr = NULL;559HeapRegion* prev_last_region = NULL;560561// Temporarily disable pretouching of heap pages. This interface is used562// when mmap'ing archived heap data in, so pre-touching is wasted.563FlagSetting fs(AlwaysPreTouch, false);564565// For each specified MemRegion range, allocate the corresponding G1566// regions and mark them as archive regions. We expect the ranges567// in ascending starting address order, without overlap.568for (size_t i = 0; i < count; i++) {569MemRegion curr_range = ranges[i];570HeapWord* start_address = curr_range.start();571size_t word_size = curr_range.word_size();572HeapWord* last_address = curr_range.last();573size_t commits = 0;574575guarantee(reserved.contains(start_address) && reserved.contains(last_address),576"MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",577p2i(start_address), p2i(last_address));578guarantee(start_address > prev_last_addr,579"Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,580p2i(start_address), p2i(prev_last_addr));581prev_last_addr = last_address;582583// Check for ranges that start in the same G1 region in which the previous584// range ended, and adjust the start address so we don't try to allocate585// the same region again. If the current range is entirely within that586// region, skip it, just adjusting the recorded top.587HeapRegion* start_region = _hrm.addr_to_region(start_address);588if ((prev_last_region != NULL) && (start_region == prev_last_region)) {589start_address = start_region->end();590if (start_address > last_address) {591increase_used(word_size * HeapWordSize);592start_region->set_top(last_address + 1);593continue;594}595start_region->set_top(start_address);596curr_range = MemRegion(start_address, last_address + 1);597start_region = _hrm.addr_to_region(start_address);598}599600// Perform the actual region allocation, exiting if it fails.601// Then note how much new space we have allocated.602if (!_hrm.allocate_containing_regions(curr_range, &commits, workers())) {603return false;604}605increase_used(word_size * HeapWordSize);606if (commits != 0) {607log_debug(gc, ergo, heap)("Attempt heap expansion (allocate archive regions). Total size: " SIZE_FORMAT "B",608HeapRegion::GrainWords * HeapWordSize * commits);609610}611612// Mark each G1 region touched by the range as archive, add it to613// the old set, and set top.614HeapRegion* curr_region = _hrm.addr_to_region(start_address);615HeapRegion* last_region = _hrm.addr_to_region(last_address);616prev_last_region = last_region;617618while (curr_region != NULL) {619assert(curr_region->is_empty() && !curr_region->is_pinned(),620"Region already in use (index %u)", curr_region->hrm_index());621if (open) {622curr_region->set_open_archive();623} else {624curr_region->set_closed_archive();625}626_hr_printer.alloc(curr_region);627_archive_set.add(curr_region);628HeapWord* top;629HeapRegion* next_region;630if (curr_region != last_region) {631top = curr_region->end();632next_region = _hrm.next_region_in_heap(curr_region);633} else {634top = last_address + 1;635next_region = NULL;636}637curr_region->set_top(top);638curr_region = next_region;639}640}641return true;642}643644void G1CollectedHeap::fill_archive_regions(MemRegion* ranges, size_t count) {645assert(!is_init_completed(), "Expect to be called at JVM init time");646assert(ranges != NULL, "MemRegion array NULL");647assert(count != 0, "No MemRegions provided");648MemRegion reserved = _hrm.reserved();649HeapWord *prev_last_addr = NULL;650HeapRegion* prev_last_region = NULL;651652// For each MemRegion, create filler objects, if needed, in the G1 regions653// that contain the address range. The address range actually within the654// MemRegion will not be modified. That is assumed to have been initialized655// elsewhere, probably via an mmap of archived heap data.656MutexLocker x(Heap_lock);657for (size_t i = 0; i < count; i++) {658HeapWord* start_address = ranges[i].start();659HeapWord* last_address = ranges[i].last();660661assert(reserved.contains(start_address) && reserved.contains(last_address),662"MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",663p2i(start_address), p2i(last_address));664assert(start_address > prev_last_addr,665"Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,666p2i(start_address), p2i(prev_last_addr));667668HeapRegion* start_region = _hrm.addr_to_region(start_address);669HeapRegion* last_region = _hrm.addr_to_region(last_address);670HeapWord* bottom_address = start_region->bottom();671672// Check for a range beginning in the same region in which the673// previous one ended.674if (start_region == prev_last_region) {675bottom_address = prev_last_addr + 1;676}677678// Verify that the regions were all marked as archive regions by679// alloc_archive_regions.680HeapRegion* curr_region = start_region;681while (curr_region != NULL) {682guarantee(curr_region->is_archive(),683"Expected archive region at index %u", curr_region->hrm_index());684if (curr_region != last_region) {685curr_region = _hrm.next_region_in_heap(curr_region);686} else {687curr_region = NULL;688}689}690691prev_last_addr = last_address;692prev_last_region = last_region;693694// Fill the memory below the allocated range with dummy object(s),695// if the region bottom does not match the range start, or if the previous696// range ended within the same G1 region, and there is a gap.697assert(start_address >= bottom_address, "bottom address should not be greater than start address");698if (start_address > bottom_address) {699size_t fill_size = pointer_delta(start_address, bottom_address);700G1CollectedHeap::fill_with_objects(bottom_address, fill_size);701increase_used(fill_size * HeapWordSize);702}703}704}705706inline HeapWord* G1CollectedHeap::attempt_allocation(size_t min_word_size,707size_t desired_word_size,708size_t* actual_word_size) {709assert_heap_not_locked_and_not_at_safepoint();710assert(!is_humongous(desired_word_size), "attempt_allocation() should not "711"be called for humongous allocation requests");712713HeapWord* result = _allocator->attempt_allocation(min_word_size, desired_word_size, actual_word_size);714715if (result == NULL) {716*actual_word_size = desired_word_size;717result = attempt_allocation_slow(desired_word_size);718}719720assert_heap_not_locked();721if (result != NULL) {722assert(*actual_word_size != 0, "Actual size must have been set here");723dirty_young_block(result, *actual_word_size);724} else {725*actual_word_size = 0;726}727728return result;729}730731void G1CollectedHeap::populate_archive_regions_bot_part(MemRegion* ranges, size_t count) {732assert(!is_init_completed(), "Expect to be called at JVM init time");733assert(ranges != NULL, "MemRegion array NULL");734assert(count != 0, "No MemRegions provided");735736HeapWord* st = ranges[0].start();737HeapWord* last = ranges[count-1].last();738HeapRegion* hr_st = _hrm.addr_to_region(st);739HeapRegion* hr_last = _hrm.addr_to_region(last);740741HeapRegion* hr_curr = hr_st;742while (hr_curr != NULL) {743hr_curr->update_bot();744if (hr_curr != hr_last) {745hr_curr = _hrm.next_region_in_heap(hr_curr);746} else {747hr_curr = NULL;748}749}750}751752void G1CollectedHeap::dealloc_archive_regions(MemRegion* ranges, size_t count) {753assert(!is_init_completed(), "Expect to be called at JVM init time");754assert(ranges != NULL, "MemRegion array NULL");755assert(count != 0, "No MemRegions provided");756MemRegion reserved = _hrm.reserved();757HeapWord* prev_last_addr = NULL;758HeapRegion* prev_last_region = NULL;759size_t size_used = 0;760uint shrink_count = 0;761762// For each Memregion, free the G1 regions that constitute it, and763// notify mark-sweep that the range is no longer to be considered 'archive.'764MutexLocker x(Heap_lock);765for (size_t i = 0; i < count; i++) {766HeapWord* start_address = ranges[i].start();767HeapWord* last_address = ranges[i].last();768769assert(reserved.contains(start_address) && reserved.contains(last_address),770"MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",771p2i(start_address), p2i(last_address));772assert(start_address > prev_last_addr,773"Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,774p2i(start_address), p2i(prev_last_addr));775size_used += ranges[i].byte_size();776prev_last_addr = last_address;777778HeapRegion* start_region = _hrm.addr_to_region(start_address);779HeapRegion* last_region = _hrm.addr_to_region(last_address);780781// Check for ranges that start in the same G1 region in which the previous782// range ended, and adjust the start address so we don't try to free783// the same region again. If the current range is entirely within that784// region, skip it.785if (start_region == prev_last_region) {786start_address = start_region->end();787if (start_address > last_address) {788continue;789}790start_region = _hrm.addr_to_region(start_address);791}792prev_last_region = last_region;793794// After verifying that each region was marked as an archive region by795// alloc_archive_regions, set it free and empty and uncommit it.796HeapRegion* curr_region = start_region;797while (curr_region != NULL) {798guarantee(curr_region->is_archive(),799"Expected archive region at index %u", curr_region->hrm_index());800uint curr_index = curr_region->hrm_index();801_archive_set.remove(curr_region);802curr_region->set_free();803curr_region->set_top(curr_region->bottom());804if (curr_region != last_region) {805curr_region = _hrm.next_region_in_heap(curr_region);806} else {807curr_region = NULL;808}809810_hrm.shrink_at(curr_index, 1);811shrink_count++;812}813}814815if (shrink_count != 0) {816log_debug(gc, ergo, heap)("Attempt heap shrinking (archive regions). Total size: " SIZE_FORMAT "B",817HeapRegion::GrainWords * HeapWordSize * shrink_count);818// Explicit uncommit.819uncommit_regions(shrink_count);820}821decrease_used(size_used);822}823824HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) {825ResourceMark rm; // For retrieving the thread names in log messages.826827// The structure of this method has a lot of similarities to828// attempt_allocation_slow(). The reason these two were not merged829// into a single one is that such a method would require several "if830// allocation is not humongous do this, otherwise do that"831// conditional paths which would obscure its flow. In fact, an early832// version of this code did use a unified method which was harder to833// follow and, as a result, it had subtle bugs that were hard to834// track down. So keeping these two methods separate allows each to835// be more readable. It will be good to keep these two in sync as836// much as possible.837838assert_heap_not_locked_and_not_at_safepoint();839assert(is_humongous(word_size), "attempt_allocation_humongous() "840"should only be called for humongous allocations");841842// Humongous objects can exhaust the heap quickly, so we should check if we843// need to start a marking cycle at each humongous object allocation. We do844// the check before we do the actual allocation. The reason for doing it845// before the allocation is that we avoid having to keep track of the newly846// allocated memory while we do a GC.847if (policy()->need_to_start_conc_mark("concurrent humongous allocation",848word_size)) {849collect(GCCause::_g1_humongous_allocation);850}851852// We will loop until a) we manage to successfully perform the853// allocation or b) we successfully schedule a collection which854// fails to perform the allocation. b) is the only case when we'll855// return NULL.856HeapWord* result = NULL;857for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {858bool should_try_gc;859bool preventive_collection_required = false;860uint gc_count_before;861862863{864MutexLocker x(Heap_lock);865866size_t size_in_regions = humongous_obj_size_in_regions(word_size);867preventive_collection_required = policy()->preventive_collection_required((uint)size_in_regions);868if (!preventive_collection_required) {869// Given that humongous objects are not allocated in young870// regions, we'll first try to do the allocation without doing a871// collection hoping that there's enough space in the heap.872result = humongous_obj_allocate(word_size);873if (result != NULL) {874policy()->old_gen_alloc_tracker()->875add_allocated_humongous_bytes_since_last_gc(size_in_regions * HeapRegion::GrainBytes);876return result;877}878}879880// Only try a GC if the GCLocker does not signal the need for a GC. Wait until881// the GCLocker initiated GC has been performed and then retry. This includes882// the case when the GC Locker is not active but has not been performed.883should_try_gc = !GCLocker::needs_gc();884// Read the GC count while still holding the Heap_lock.885gc_count_before = total_collections();886}887888if (should_try_gc) {889GCCause::Cause gc_cause = preventive_collection_required ? GCCause::_g1_preventive_collection890: GCCause::_g1_humongous_allocation;891bool succeeded;892result = do_collection_pause(word_size, gc_count_before, &succeeded, gc_cause);893if (result != NULL) {894assert(succeeded, "only way to get back a non-NULL result");895log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,896Thread::current()->name(), p2i(result));897size_t size_in_regions = humongous_obj_size_in_regions(word_size);898policy()->old_gen_alloc_tracker()->899record_collection_pause_humongous_allocation(size_in_regions * HeapRegion::GrainBytes);900return result;901}902903if (succeeded) {904// We successfully scheduled a collection which failed to allocate. No905// point in trying to allocate further. We'll just return NULL.906log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "907SIZE_FORMAT " words", Thread::current()->name(), word_size);908return NULL;909}910log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT "",911Thread::current()->name(), word_size);912} else {913// Failed to schedule a collection.914if (gclocker_retry_count > GCLockerRetryAllocationCount) {915log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "916SIZE_FORMAT " words", Thread::current()->name(), word_size);917return NULL;918}919log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());920// The GCLocker is either active or the GCLocker initiated921// GC has not yet been performed. Stall until it is and922// then retry the allocation.923GCLocker::stall_until_clear();924gclocker_retry_count += 1;925}926927928// We can reach here if we were unsuccessful in scheduling a929// collection (because another thread beat us to it) or if we were930// stalled due to the GC locker. In either can we should retry the931// allocation attempt in case another thread successfully932// performed a collection and reclaimed enough space.933// Humongous object allocation always needs a lock, so we wait for the retry934// in the next iteration of the loop, unlike for the regular iteration case.935// Give a warning if we seem to be looping forever.936937if ((QueuedAllocationWarningCount > 0) &&938(try_count % QueuedAllocationWarningCount == 0)) {939log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",940Thread::current()->name(), try_count, word_size);941}942}943944ShouldNotReachHere();945return NULL;946}947948HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,949bool expect_null_mutator_alloc_region) {950assert_at_safepoint_on_vm_thread();951assert(!_allocator->has_mutator_alloc_region() || !expect_null_mutator_alloc_region,952"the current alloc region was unexpectedly found to be non-NULL");953954if (!is_humongous(word_size)) {955return _allocator->attempt_allocation_locked(word_size);956} else {957HeapWord* result = humongous_obj_allocate(word_size);958if (result != NULL && policy()->need_to_start_conc_mark("STW humongous allocation")) {959collector_state()->set_initiate_conc_mark_if_possible(true);960}961return result;962}963964ShouldNotReachHere();965}966967class PostCompactionPrinterClosure: public HeapRegionClosure {968private:969G1HRPrinter* _hr_printer;970public:971bool do_heap_region(HeapRegion* hr) {972assert(!hr->is_young(), "not expecting to find young regions");973_hr_printer->post_compaction(hr);974return false;975}976977PostCompactionPrinterClosure(G1HRPrinter* hr_printer)978: _hr_printer(hr_printer) { }979};980981void G1CollectedHeap::print_hrm_post_compaction() {982if (_hr_printer.is_active()) {983PostCompactionPrinterClosure cl(hr_printer());984heap_region_iterate(&cl);985}986}987988void G1CollectedHeap::abort_concurrent_cycle() {989// If we start the compaction before the CM threads finish990// scanning the root regions we might trip them over as we'll991// be moving objects / updating references. So let's wait until992// they are done. By telling them to abort, they should complete993// early.994_cm->root_regions()->abort();995_cm->root_regions()->wait_until_scan_finished();996997// Disable discovery and empty the discovered lists998// for the CM ref processor.999_ref_processor_cm->disable_discovery();1000_ref_processor_cm->abandon_partial_discovery();1001_ref_processor_cm->verify_no_references_recorded();10021003// Abandon current iterations of concurrent marking and concurrent1004// refinement, if any are in progress.1005concurrent_mark()->concurrent_cycle_abort();1006}10071008void G1CollectedHeap::prepare_heap_for_full_collection() {1009// Make sure we'll choose a new allocation region afterwards.1010_allocator->release_mutator_alloc_regions();1011_allocator->abandon_gc_alloc_regions();10121013// We may have added regions to the current incremental collection1014// set between the last GC or pause and now. We need to clear the1015// incremental collection set and then start rebuilding it afresh1016// after this full GC.1017abandon_collection_set(collection_set());10181019_hrm.remove_all_free_regions();1020}10211022void G1CollectedHeap::verify_before_full_collection(bool explicit_gc) {1023assert(!GCCause::is_user_requested_gc(gc_cause()) || explicit_gc, "invariant");1024assert_used_and_recalculate_used_equal(this);1025_verifier->verify_region_sets_optional();1026_verifier->verify_before_gc(G1HeapVerifier::G1VerifyFull);1027_verifier->check_bitmaps("Full GC Start");1028}10291030void G1CollectedHeap::prepare_heap_for_mutators() {1031// Delete metaspaces for unloaded class loaders and clean up loader_data graph1032ClassLoaderDataGraph::purge(/*at_safepoint*/true);1033DEBUG_ONLY(MetaspaceUtils::verify();)10341035// Prepare heap for normal collections.1036assert(num_free_regions() == 0, "we should not have added any free regions");1037rebuild_region_sets(false /* free_list_only */);1038abort_refinement();1039resize_heap_if_necessary();1040uncommit_regions_if_necessary();10411042// Rebuild the strong code root lists for each region1043rebuild_strong_code_roots();10441045// Purge code root memory1046purge_code_root_memory();10471048// Start a new incremental collection set for the next pause1049start_new_collection_set();10501051_allocator->init_mutator_alloc_regions();10521053// Post collection state updates.1054MetaspaceGC::compute_new_size();1055}10561057void G1CollectedHeap::abort_refinement() {1058if (_hot_card_cache->use_cache()) {1059_hot_card_cache->reset_hot_cache();1060}10611062// Discard all remembered set updates and reset refinement statistics.1063G1BarrierSet::dirty_card_queue_set().abandon_logs();1064assert(G1BarrierSet::dirty_card_queue_set().num_cards() == 0,1065"DCQS should be empty");1066concurrent_refine()->get_and_reset_refinement_stats();1067}10681069void G1CollectedHeap::verify_after_full_collection() {1070_hrm.verify_optional();1071_verifier->verify_region_sets_optional();1072_verifier->verify_after_gc(G1HeapVerifier::G1VerifyFull);10731074// This call implicitly verifies that the next bitmap is clear after Full GC.1075_verifier->check_bitmaps("Full GC End");10761077// At this point there should be no regions in the1078// entire heap tagged as young.1079assert(check_young_list_empty(), "young list should be empty at this point");10801081// Note: since we've just done a full GC, concurrent1082// marking is no longer active. Therefore we need not1083// re-enable reference discovery for the CM ref processor.1084// That will be done at the start of the next marking cycle.1085// We also know that the STW processor should no longer1086// discover any new references.1087assert(!_ref_processor_stw->discovery_enabled(), "Postcondition");1088assert(!_ref_processor_cm->discovery_enabled(), "Postcondition");1089_ref_processor_stw->verify_no_references_recorded();1090_ref_processor_cm->verify_no_references_recorded();1091}10921093void G1CollectedHeap::print_heap_after_full_collection(G1HeapTransition* heap_transition) {1094// Post collection logging.1095// We should do this after we potentially resize the heap so1096// that all the COMMIT / UNCOMMIT events are generated before1097// the compaction events.1098print_hrm_post_compaction();1099heap_transition->print();1100print_heap_after_gc();1101print_heap_regions();1102}11031104bool G1CollectedHeap::do_full_collection(bool explicit_gc,1105bool clear_all_soft_refs,1106bool do_maximum_compaction) {1107assert_at_safepoint_on_vm_thread();11081109if (GCLocker::check_active_before_gc()) {1110// Full GC was not completed.1111return false;1112}11131114const bool do_clear_all_soft_refs = clear_all_soft_refs ||1115soft_ref_policy()->should_clear_all_soft_refs();11161117G1FullCollector collector(this, explicit_gc, do_clear_all_soft_refs, do_maximum_compaction);1118GCTraceTime(Info, gc) tm("Pause Full", NULL, gc_cause(), true);11191120collector.prepare_collection();1121collector.collect();1122collector.complete_collection();11231124// Full collection was successfully completed.1125return true;1126}11271128void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {1129// Currently, there is no facility in the do_full_collection(bool) API to notify1130// the caller that the collection did not succeed (e.g., because it was locked1131// out by the GC locker). So, right now, we'll ignore the return value.1132// When clear_all_soft_refs is set we want to do a maximum compaction1133// not leaving any dead wood.1134bool do_maximum_compaction = clear_all_soft_refs;1135bool dummy = do_full_collection(true, /* explicit_gc */1136clear_all_soft_refs,1137do_maximum_compaction);1138}11391140bool G1CollectedHeap::upgrade_to_full_collection() {1141GCCauseSetter compaction(this, GCCause::_g1_compaction_pause);1142log_info(gc, ergo)("Attempting full compaction clearing soft references");1143bool success = do_full_collection(false /* explicit gc */,1144true /* clear_all_soft_refs */,1145false /* do_maximum_compaction */);1146// do_full_collection only fails if blocked by GC locker and that can't1147// be the case here since we only call this when already completed one gc.1148assert(success, "invariant");1149return success;1150}11511152void G1CollectedHeap::resize_heap_if_necessary() {1153assert_at_safepoint_on_vm_thread();11541155bool should_expand;1156size_t resize_amount = _heap_sizing_policy->full_collection_resize_amount(should_expand);11571158if (resize_amount == 0) {1159return;1160} else if (should_expand) {1161expand(resize_amount, _workers);1162} else {1163shrink(resize_amount);1164}1165}11661167HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size,1168bool do_gc,1169bool maximum_compaction,1170bool expect_null_mutator_alloc_region,1171bool* gc_succeeded) {1172*gc_succeeded = true;1173// Let's attempt the allocation first.1174HeapWord* result =1175attempt_allocation_at_safepoint(word_size,1176expect_null_mutator_alloc_region);1177if (result != NULL) {1178return result;1179}11801181// In a G1 heap, we're supposed to keep allocation from failing by1182// incremental pauses. Therefore, at least for now, we'll favor1183// expansion over collection. (This might change in the future if we can1184// do something smarter than full collection to satisfy a failed alloc.)1185result = expand_and_allocate(word_size);1186if (result != NULL) {1187return result;1188}11891190if (do_gc) {1191GCCauseSetter compaction(this, GCCause::_g1_compaction_pause);1192// Expansion didn't work, we'll try to do a Full GC.1193// If maximum_compaction is set we clear all soft references and don't1194// allow any dead wood to be left on the heap.1195if (maximum_compaction) {1196log_info(gc, ergo)("Attempting maximum full compaction clearing soft references");1197} else {1198log_info(gc, ergo)("Attempting full compaction");1199}1200*gc_succeeded = do_full_collection(false, /* explicit_gc */1201maximum_compaction /* clear_all_soft_refs */ ,1202maximum_compaction /* do_maximum_compaction */);1203}12041205return NULL;1206}12071208HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size,1209bool* succeeded) {1210assert_at_safepoint_on_vm_thread();12111212// Attempts to allocate followed by Full GC.1213HeapWord* result =1214satisfy_failed_allocation_helper(word_size,1215true, /* do_gc */1216false, /* maximum_collection */1217false, /* expect_null_mutator_alloc_region */1218succeeded);12191220if (result != NULL || !*succeeded) {1221return result;1222}12231224// Attempts to allocate followed by Full GC that will collect all soft references.1225result = satisfy_failed_allocation_helper(word_size,1226true, /* do_gc */1227true, /* maximum_collection */1228true, /* expect_null_mutator_alloc_region */1229succeeded);12301231if (result != NULL || !*succeeded) {1232return result;1233}12341235// Attempts to allocate, no GC1236result = satisfy_failed_allocation_helper(word_size,1237false, /* do_gc */1238false, /* maximum_collection */1239true, /* expect_null_mutator_alloc_region */1240succeeded);12411242if (result != NULL) {1243return result;1244}12451246assert(!soft_ref_policy()->should_clear_all_soft_refs(),1247"Flag should have been handled and cleared prior to this point");12481249// What else? We might try synchronous finalization later. If the total1250// space available is large enough for the allocation, then a more1251// complete compaction phase than we've tried so far might be1252// appropriate.1253return NULL;1254}12551256// Attempting to expand the heap sufficiently1257// to support an allocation of the given "word_size". If1258// successful, perform the allocation and return the address of the1259// allocated block, or else "NULL".12601261HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {1262assert_at_safepoint_on_vm_thread();12631264_verifier->verify_region_sets_optional();12651266size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);1267log_debug(gc, ergo, heap)("Attempt heap expansion (allocation request failed). Allocation request: " SIZE_FORMAT "B",1268word_size * HeapWordSize);126912701271if (expand(expand_bytes, _workers)) {1272_hrm.verify_optional();1273_verifier->verify_region_sets_optional();1274return attempt_allocation_at_safepoint(word_size,1275false /* expect_null_mutator_alloc_region */);1276}1277return NULL;1278}12791280bool G1CollectedHeap::expand(size_t expand_bytes, WorkGang* pretouch_workers, double* expand_time_ms) {1281size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);1282aligned_expand_bytes = align_up(aligned_expand_bytes,1283HeapRegion::GrainBytes);12841285log_debug(gc, ergo, heap)("Expand the heap. requested expansion amount: " SIZE_FORMAT "B expansion amount: " SIZE_FORMAT "B",1286expand_bytes, aligned_expand_bytes);12871288if (is_maximal_no_gc()) {1289log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");1290return false;1291}12921293double expand_heap_start_time_sec = os::elapsedTime();1294uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes);1295assert(regions_to_expand > 0, "Must expand by at least one region");12961297uint expanded_by = _hrm.expand_by(regions_to_expand, pretouch_workers);1298if (expand_time_ms != NULL) {1299*expand_time_ms = (os::elapsedTime() - expand_heap_start_time_sec) * MILLIUNITS;1300}13011302if (expanded_by > 0) {1303size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes;1304assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");1305policy()->record_new_heap_size(num_regions());1306} else {1307log_debug(gc, ergo, heap)("Did not expand the heap (heap expansion operation failed)");13081309// The expansion of the virtual storage space was unsuccessful.1310// Let's see if it was because we ran out of swap.1311if (G1ExitOnExpansionFailure &&1312_hrm.available() >= regions_to_expand) {1313// We had head room...1314vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");1315}1316}1317return regions_to_expand > 0;1318}13191320bool G1CollectedHeap::expand_single_region(uint node_index) {1321uint expanded_by = _hrm.expand_on_preferred_node(node_index);13221323if (expanded_by == 0) {1324assert(is_maximal_no_gc(), "Should be no regions left, available: %u", _hrm.available());1325log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");1326return false;1327}13281329policy()->record_new_heap_size(num_regions());1330return true;1331}13321333void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {1334size_t aligned_shrink_bytes =1335ReservedSpace::page_align_size_down(shrink_bytes);1336aligned_shrink_bytes = align_down(aligned_shrink_bytes,1337HeapRegion::GrainBytes);1338uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);13391340uint num_regions_removed = _hrm.shrink_by(num_regions_to_remove);1341size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;13421343log_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",1344shrink_bytes, aligned_shrink_bytes, shrunk_bytes);1345if (num_regions_removed > 0) {1346log_debug(gc, heap)("Uncommittable regions after shrink: %u", num_regions_removed);1347policy()->record_new_heap_size(num_regions());1348} else {1349log_debug(gc, ergo, heap)("Did not expand the heap (heap shrinking operation failed)");1350}1351}13521353void G1CollectedHeap::shrink(size_t shrink_bytes) {1354_verifier->verify_region_sets_optional();13551356// We should only reach here at the end of a Full GC or during Remark which1357// means we should not not be holding to any GC alloc regions. The method1358// below will make sure of that and do any remaining clean up.1359_allocator->abandon_gc_alloc_regions();13601361// Instead of tearing down / rebuilding the free lists here, we1362// could instead use the remove_all_pending() method on free_list to1363// remove only the ones that we need to remove.1364_hrm.remove_all_free_regions();1365shrink_helper(shrink_bytes);1366rebuild_region_sets(true /* free_list_only */);13671368_hrm.verify_optional();1369_verifier->verify_region_sets_optional();1370}13711372class OldRegionSetChecker : public HeapRegionSetChecker {1373public:1374void check_mt_safety() {1375// Master Old Set MT safety protocol:1376// (a) If we're at a safepoint, operations on the master old set1377// should be invoked:1378// - by the VM thread (which will serialize them), or1379// - by the GC workers while holding the FreeList_lock, if we're1380// at a safepoint for an evacuation pause (this lock is taken1381// anyway when an GC alloc region is retired so that a new one1382// is allocated from the free list), or1383// - by the GC workers while holding the OldSets_lock, if we're at a1384// safepoint for a cleanup pause.1385// (b) If we're not at a safepoint, operations on the master old set1386// should be invoked while holding the Heap_lock.13871388if (SafepointSynchronize::is_at_safepoint()) {1389guarantee(Thread::current()->is_VM_thread() ||1390FreeList_lock->owned_by_self() || OldSets_lock->owned_by_self(),1391"master old set MT safety protocol at a safepoint");1392} else {1393guarantee(Heap_lock->owned_by_self(), "master old set MT safety protocol outside a safepoint");1394}1395}1396bool is_correct_type(HeapRegion* hr) { return hr->is_old(); }1397const char* get_description() { return "Old Regions"; }1398};13991400class ArchiveRegionSetChecker : public HeapRegionSetChecker {1401public:1402void check_mt_safety() {1403guarantee(!Universe::is_fully_initialized() || SafepointSynchronize::is_at_safepoint(),1404"May only change archive regions during initialization or safepoint.");1405}1406bool is_correct_type(HeapRegion* hr) { return hr->is_archive(); }1407const char* get_description() { return "Archive Regions"; }1408};14091410class HumongousRegionSetChecker : public HeapRegionSetChecker {1411public:1412void check_mt_safety() {1413// Humongous Set MT safety protocol:1414// (a) If we're at a safepoint, operations on the master humongous1415// set should be invoked by either the VM thread (which will1416// serialize them) or by the GC workers while holding the1417// OldSets_lock.1418// (b) If we're not at a safepoint, operations on the master1419// humongous set should be invoked while holding the Heap_lock.14201421if (SafepointSynchronize::is_at_safepoint()) {1422guarantee(Thread::current()->is_VM_thread() ||1423OldSets_lock->owned_by_self(),1424"master humongous set MT safety protocol at a safepoint");1425} else {1426guarantee(Heap_lock->owned_by_self(),1427"master humongous set MT safety protocol outside a safepoint");1428}1429}1430bool is_correct_type(HeapRegion* hr) { return hr->is_humongous(); }1431const char* get_description() { return "Humongous Regions"; }1432};14331434G1CollectedHeap::G1CollectedHeap() :1435CollectedHeap(),1436_service_thread(NULL),1437_periodic_gc_task(NULL),1438_workers(NULL),1439_card_table(NULL),1440_collection_pause_end(Ticks::now()),1441_soft_ref_policy(),1442_old_set("Old Region Set", new OldRegionSetChecker()),1443_archive_set("Archive Region Set", new ArchiveRegionSetChecker()),1444_humongous_set("Humongous Region Set", new HumongousRegionSetChecker()),1445_bot(NULL),1446_listener(),1447_numa(G1NUMA::create()),1448_hrm(),1449_allocator(NULL),1450_verifier(NULL),1451_summary_bytes_used(0),1452_bytes_used_during_gc(0),1453_archive_allocator(NULL),1454_survivor_evac_stats("Young", YoungPLABSize, PLABWeight),1455_old_evac_stats("Old", OldPLABSize, PLABWeight),1456_expand_heap_after_alloc_failure(true),1457_g1mm(NULL),1458_humongous_reclaim_candidates(),1459_num_humongous_objects(0),1460_num_humongous_reclaim_candidates(0),1461_hr_printer(),1462_collector_state(),1463_old_marking_cycles_started(0),1464_old_marking_cycles_completed(0),1465_eden(),1466_survivor(),1467_gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),1468_gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),1469_policy(new G1Policy(_gc_timer_stw)),1470_heap_sizing_policy(NULL),1471_collection_set(this, _policy),1472_hot_card_cache(NULL),1473_rem_set(NULL),1474_cm(NULL),1475_cm_thread(NULL),1476_cr(NULL),1477_task_queues(NULL),1478_num_regions_failed_evacuation(0),1479_regions_failed_evacuation(NULL),1480_evacuation_failed_info_array(NULL),1481_preserved_marks_set(true /* in_c_heap */),1482#ifndef PRODUCT1483_evacuation_failure_alot_for_current_gc(false),1484_evacuation_failure_alot_gc_number(0),1485_evacuation_failure_alot_count(0),1486#endif1487_ref_processor_stw(NULL),1488_is_alive_closure_stw(this),1489_is_subject_to_discovery_stw(this),1490_ref_processor_cm(NULL),1491_is_alive_closure_cm(this),1492_is_subject_to_discovery_cm(this),1493_region_attr() {14941495_verifier = new G1HeapVerifier(this);14961497_allocator = new G1Allocator(this);14981499_heap_sizing_policy = G1HeapSizingPolicy::create(this, _policy->analytics());15001501_humongous_object_threshold_in_words = humongous_threshold_for(HeapRegion::GrainWords);15021503// Override the default _filler_array_max_size so that no humongous filler1504// objects are created.1505_filler_array_max_size = _humongous_object_threshold_in_words;15061507uint n_queues = ParallelGCThreads;1508_task_queues = new G1ScannerTasksQueueSet(n_queues);15091510_evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);15111512for (uint i = 0; i < n_queues; i++) {1513G1ScannerTasksQueue* q = new G1ScannerTasksQueue();1514q->initialize();1515_task_queues->register_queue(i, q);1516::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();1517}15181519// Initialize the G1EvacuationFailureALot counters and flags.1520NOT_PRODUCT(reset_evacuation_should_fail();)1521_gc_tracer_stw->initialize();15221523guarantee(_task_queues != NULL, "task_queues allocation failure.");1524}15251526G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description,1527size_t size,1528size_t translation_factor) {1529size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1);1530// Allocate a new reserved space, preferring to use large pages.1531ReservedSpace rs(size, preferred_page_size);1532size_t page_size = rs.page_size();1533G1RegionToSpaceMapper* result =1534G1RegionToSpaceMapper::create_mapper(rs,1535size,1536page_size,1537HeapRegion::GrainBytes,1538translation_factor,1539mtGC);15401541os::trace_page_sizes_for_requested_size(description,1542size,1543page_size,1544preferred_page_size,1545rs.base(),1546rs.size());15471548return result;1549}15501551jint G1CollectedHeap::initialize_concurrent_refinement() {1552jint ecode = JNI_OK;1553_cr = G1ConcurrentRefine::create(&ecode);1554return ecode;1555}15561557jint G1CollectedHeap::initialize_service_thread() {1558_service_thread = new G1ServiceThread();1559if (_service_thread->osthread() == NULL) {1560vm_shutdown_during_initialization("Could not create G1ServiceThread");1561return JNI_ENOMEM;1562}1563return JNI_OK;1564}15651566jint G1CollectedHeap::initialize() {15671568// Necessary to satisfy locking discipline assertions.15691570MutexLocker x(Heap_lock);15711572// While there are no constraints in the GC code that HeapWordSize1573// be any particular value, there are multiple other areas in the1574// system which believe this to be true (e.g. oop->object_size in some1575// cases incorrectly returns the size in wordSize units rather than1576// HeapWordSize).1577guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");15781579size_t init_byte_size = InitialHeapSize;1580size_t reserved_byte_size = G1Arguments::heap_reserved_size_bytes();15811582// Ensure that the sizes are properly aligned.1583Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");1584Universe::check_alignment(reserved_byte_size, HeapRegion::GrainBytes, "g1 heap");1585Universe::check_alignment(reserved_byte_size, HeapAlignment, "g1 heap");15861587// Reserve the maximum.15881589// When compressed oops are enabled, the preferred heap base1590// is calculated by subtracting the requested size from the1591// 32Gb boundary and using the result as the base address for1592// heap reservation. If the requested size is not aligned to1593// HeapRegion::GrainBytes (i.e. the alignment that is passed1594// into the ReservedHeapSpace constructor) then the actual1595// base of the reserved heap may end up differing from the1596// address that was requested (i.e. the preferred heap base).1597// If this happens then we could end up using a non-optimal1598// compressed oops mode.15991600ReservedHeapSpace heap_rs = Universe::reserve_heap(reserved_byte_size,1601HeapAlignment);16021603initialize_reserved_region(heap_rs);16041605// Create the barrier set for the entire reserved region.1606G1CardTable* ct = new G1CardTable(heap_rs.region());1607ct->initialize();1608G1BarrierSet* bs = new G1BarrierSet(ct);1609bs->initialize();1610assert(bs->is_a(BarrierSet::G1BarrierSet), "sanity");1611BarrierSet::set_barrier_set(bs);1612_card_table = ct;16131614{1615G1SATBMarkQueueSet& satbqs = bs->satb_mark_queue_set();1616satbqs.set_process_completed_buffers_threshold(G1SATBProcessCompletedThreshold);1617satbqs.set_buffer_enqueue_threshold_percentage(G1SATBBufferEnqueueingThresholdPercent);1618}16191620// Create the hot card cache.1621_hot_card_cache = new G1HotCardCache(this);16221623// Create space mappers.1624size_t page_size = heap_rs.page_size();1625G1RegionToSpaceMapper* heap_storage =1626G1RegionToSpaceMapper::create_mapper(heap_rs,1627heap_rs.size(),1628page_size,1629HeapRegion::GrainBytes,16301,1631mtJavaHeap);1632if(heap_storage == NULL) {1633vm_shutdown_during_initialization("Could not initialize G1 heap");1634return JNI_ERR;1635}16361637os::trace_page_sizes("Heap",1638MinHeapSize,1639reserved_byte_size,1640page_size,1641heap_rs.base(),1642heap_rs.size());1643heap_storage->set_mapping_changed_listener(&_listener);16441645// Create storage for the BOT, card table, card counts table (hot card cache) and the bitmaps.1646G1RegionToSpaceMapper* bot_storage =1647create_aux_memory_mapper("Block Offset Table",1648G1BlockOffsetTable::compute_size(heap_rs.size() / HeapWordSize),1649G1BlockOffsetTable::heap_map_factor());16501651G1RegionToSpaceMapper* cardtable_storage =1652create_aux_memory_mapper("Card Table",1653G1CardTable::compute_size(heap_rs.size() / HeapWordSize),1654G1CardTable::heap_map_factor());16551656G1RegionToSpaceMapper* card_counts_storage =1657create_aux_memory_mapper("Card Counts Table",1658G1CardCounts::compute_size(heap_rs.size() / HeapWordSize),1659G1CardCounts::heap_map_factor());16601661size_t bitmap_size = G1CMBitMap::compute_size(heap_rs.size());1662G1RegionToSpaceMapper* prev_bitmap_storage =1663create_aux_memory_mapper("Prev Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());1664G1RegionToSpaceMapper* next_bitmap_storage =1665create_aux_memory_mapper("Next Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());16661667_hrm.initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage);1668_card_table->initialize(cardtable_storage);16691670// Do later initialization work for concurrent refinement.1671_hot_card_cache->initialize(card_counts_storage);16721673// 6843694 - ensure that the maximum region index can fit1674// in the remembered set structures.1675const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;1676guarantee((max_reserved_regions() - 1) <= max_region_idx, "too many regions");16771678// The G1FromCardCache reserves card with value 0 as "invalid", so the heap must not1679// start within the first card.1680guarantee(heap_rs.base() >= (char*)G1CardTable::card_size, "Java heap must not start within the first card.");1681G1FromCardCache::initialize(max_reserved_regions());1682// Also create a G1 rem set.1683_rem_set = new G1RemSet(this, _card_table, _hot_card_cache);1684_rem_set->initialize(max_reserved_regions());16851686size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;1687guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");1688guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,1689"too many cards per region");16901691FreeRegionList::set_unrealistically_long_length(max_regions() + 1);16921693_bot = new G1BlockOffsetTable(reserved(), bot_storage);16941695{1696size_t granularity = HeapRegion::GrainBytes;16971698_region_attr.initialize(reserved(), granularity);1699_humongous_reclaim_candidates.initialize(reserved(), granularity);1700}17011702_workers = new WorkGang("GC Thread", ParallelGCThreads,1703true /* are_GC_task_threads */,1704false /* are_ConcurrentGC_threads */);1705if (_workers == NULL) {1706return JNI_ENOMEM;1707}1708_workers->initialize_workers();17091710_numa->set_region_info(HeapRegion::GrainBytes, page_size);17111712// Create the G1ConcurrentMark data structure and thread.1713// (Must do this late, so that "max_[reserved_]regions" is defined.)1714_cm = new G1ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage);1715_cm_thread = _cm->cm_thread();17161717// Now expand into the initial heap size.1718if (!expand(init_byte_size, _workers)) {1719vm_shutdown_during_initialization("Failed to allocate initial heap.");1720return JNI_ENOMEM;1721}17221723// Perform any initialization actions delegated to the policy.1724policy()->init(this, &_collection_set);17251726jint ecode = initialize_concurrent_refinement();1727if (ecode != JNI_OK) {1728return ecode;1729}17301731ecode = initialize_service_thread();1732if (ecode != JNI_OK) {1733return ecode;1734}17351736// Initialize and schedule sampling task on service thread.1737_rem_set->initialize_sampling_task(service_thread());17381739// Create and schedule the periodic gc task on the service thread.1740_periodic_gc_task = new G1PeriodicGCTask("Periodic GC Task");1741_service_thread->register_task(_periodic_gc_task);17421743{1744G1DirtyCardQueueSet& dcqs = G1BarrierSet::dirty_card_queue_set();1745dcqs.set_process_cards_threshold(concurrent_refine()->yellow_zone());1746dcqs.set_max_cards(concurrent_refine()->red_zone());1747}17481749// Here we allocate the dummy HeapRegion that is required by the1750// G1AllocRegion class.1751HeapRegion* dummy_region = _hrm.get_dummy_region();17521753// We'll re-use the same region whether the alloc region will1754// require BOT updates or not and, if it doesn't, then a non-young1755// region will complain that it cannot support allocations without1756// BOT updates. So we'll tag the dummy region as eden to avoid that.1757dummy_region->set_eden();1758// Make sure it's full.1759dummy_region->set_top(dummy_region->end());1760G1AllocRegion::setup(this, dummy_region);17611762_allocator->init_mutator_alloc_regions();17631764// Do create of the monitoring and management support so that1765// values in the heap have been properly initialized.1766_g1mm = new G1MonitoringSupport(this);17671768_preserved_marks_set.init(ParallelGCThreads);17691770_collection_set.initialize(max_reserved_regions());17711772_regions_failed_evacuation = NEW_C_HEAP_ARRAY(volatile bool, max_regions(), mtGC);17731774G1InitLogger::print();17751776return JNI_OK;1777}17781779void G1CollectedHeap::stop() {1780// Stop all concurrent threads. We do this to make sure these threads1781// do not continue to execute and access resources (e.g. logging)1782// that are destroyed during shutdown.1783_cr->stop();1784_service_thread->stop();1785_cm_thread->stop();1786}17871788void G1CollectedHeap::safepoint_synchronize_begin() {1789SuspendibleThreadSet::synchronize();1790}17911792void G1CollectedHeap::safepoint_synchronize_end() {1793SuspendibleThreadSet::desynchronize();1794}17951796void G1CollectedHeap::post_initialize() {1797CollectedHeap::post_initialize();1798ref_processing_init();1799}18001801void G1CollectedHeap::ref_processing_init() {1802// Reference processing in G1 currently works as follows:1803//1804// * There are two reference processor instances. One is1805// used to record and process discovered references1806// during concurrent marking; the other is used to1807// record and process references during STW pauses1808// (both full and incremental).1809// * Both ref processors need to 'span' the entire heap as1810// the regions in the collection set may be dotted around.1811//1812// * For the concurrent marking ref processor:1813// * Reference discovery is enabled at concurrent start.1814// * Reference discovery is disabled and the discovered1815// references processed etc during remarking.1816// * Reference discovery is MT (see below).1817// * Reference discovery requires a barrier (see below).1818// * Reference processing may or may not be MT1819// (depending on the value of ParallelRefProcEnabled1820// and ParallelGCThreads).1821// * A full GC disables reference discovery by the CM1822// ref processor and abandons any entries on it's1823// discovered lists.1824//1825// * For the STW processor:1826// * Non MT discovery is enabled at the start of a full GC.1827// * Processing and enqueueing during a full GC is non-MT.1828// * During a full GC, references are processed after marking.1829//1830// * Discovery (may or may not be MT) is enabled at the start1831// of an incremental evacuation pause.1832// * References are processed near the end of a STW evacuation pause.1833// * For both types of GC:1834// * Discovery is atomic - i.e. not concurrent.1835// * Reference discovery will not need a barrier.18361837// Concurrent Mark ref processor1838_ref_processor_cm =1839new ReferenceProcessor(&_is_subject_to_discovery_cm,1840ParallelGCThreads, // degree of mt processing1841(ParallelGCThreads > 1) || (ConcGCThreads > 1), // mt discovery1842MAX2(ParallelGCThreads, ConcGCThreads), // degree of mt discovery1843false, // Reference discovery is not atomic1844&_is_alive_closure_cm); // is alive closure18451846// STW ref processor1847_ref_processor_stw =1848new ReferenceProcessor(&_is_subject_to_discovery_stw,1849ParallelGCThreads, // degree of mt processing1850(ParallelGCThreads > 1), // mt discovery1851ParallelGCThreads, // degree of mt discovery1852true, // Reference discovery is atomic1853&_is_alive_closure_stw); // is alive closure1854}18551856SoftRefPolicy* G1CollectedHeap::soft_ref_policy() {1857return &_soft_ref_policy;1858}18591860size_t G1CollectedHeap::capacity() const {1861return _hrm.length() * HeapRegion::GrainBytes;1862}18631864size_t G1CollectedHeap::unused_committed_regions_in_bytes() const {1865return _hrm.total_free_bytes();1866}18671868void G1CollectedHeap::iterate_hcc_closure(G1CardTableEntryClosure* cl, uint worker_id) {1869_hot_card_cache->drain(cl, worker_id);1870}18711872// Computes the sum of the storage used by the various regions.1873size_t G1CollectedHeap::used() const {1874size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions();1875if (_archive_allocator != NULL) {1876result += _archive_allocator->used();1877}1878return result;1879}18801881size_t G1CollectedHeap::used_unlocked() const {1882return _summary_bytes_used;1883}18841885class SumUsedClosure: public HeapRegionClosure {1886size_t _used;1887public:1888SumUsedClosure() : _used(0) {}1889bool do_heap_region(HeapRegion* r) {1890_used += r->used();1891return false;1892}1893size_t result() { return _used; }1894};18951896size_t G1CollectedHeap::recalculate_used() const {1897SumUsedClosure blk;1898heap_region_iterate(&blk);1899return blk.result();1900}19011902bool G1CollectedHeap::is_user_requested_concurrent_full_gc(GCCause::Cause cause) {1903switch (cause) {1904case GCCause::_java_lang_system_gc: return ExplicitGCInvokesConcurrent;1905case GCCause::_dcmd_gc_run: return ExplicitGCInvokesConcurrent;1906case GCCause::_wb_conc_mark: return true;1907default : return false;1908}1909}19101911bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {1912switch (cause) {1913case GCCause::_g1_humongous_allocation: return true;1914case GCCause::_g1_periodic_collection: return G1PeriodicGCInvokesConcurrent;1915case GCCause::_wb_breakpoint: return true;1916default: return is_user_requested_concurrent_full_gc(cause);1917}1918}19191920#ifndef PRODUCT1921void G1CollectedHeap::allocate_dummy_regions() {1922// Let's fill up most of the region1923size_t word_size = HeapRegion::GrainWords - 1024;1924// And as a result the region we'll allocate will be humongous.1925guarantee(is_humongous(word_size), "sanity");19261927// _filler_array_max_size is set to humongous object threshold1928// but temporarily change it to use CollectedHeap::fill_with_object().1929AutoModifyRestore<size_t> temporarily(_filler_array_max_size, word_size);19301931for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {1932// Let's use the existing mechanism for the allocation1933HeapWord* dummy_obj = humongous_obj_allocate(word_size);1934if (dummy_obj != NULL) {1935MemRegion mr(dummy_obj, word_size);1936CollectedHeap::fill_with_object(mr);1937} else {1938// If we can't allocate once, we probably cannot allocate1939// again. Let's get out of the loop.1940break;1941}1942}1943}1944#endif // !PRODUCT19451946void G1CollectedHeap::increment_old_marking_cycles_started() {1947assert(_old_marking_cycles_started == _old_marking_cycles_completed ||1948_old_marking_cycles_started == _old_marking_cycles_completed + 1,1949"Wrong marking cycle count (started: %d, completed: %d)",1950_old_marking_cycles_started, _old_marking_cycles_completed);19511952_old_marking_cycles_started++;1953}19541955void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent,1956bool whole_heap_examined) {1957MonitorLocker ml(G1OldGCCount_lock, Mutex::_no_safepoint_check_flag);19581959// We assume that if concurrent == true, then the caller is a1960// concurrent thread that was joined the Suspendible Thread1961// Set. If there's ever a cheap way to check this, we should add an1962// assert here.19631964// Given that this method is called at the end of a Full GC or of a1965// concurrent cycle, and those can be nested (i.e., a Full GC can1966// interrupt a concurrent cycle), the number of full collections1967// completed should be either one (in the case where there was no1968// nesting) or two (when a Full GC interrupted a concurrent cycle)1969// behind the number of full collections started.19701971// This is the case for the inner caller, i.e. a Full GC.1972assert(concurrent ||1973(_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||1974(_old_marking_cycles_started == _old_marking_cycles_completed + 2),1975"for inner caller (Full GC): _old_marking_cycles_started = %u "1976"is inconsistent with _old_marking_cycles_completed = %u",1977_old_marking_cycles_started, _old_marking_cycles_completed);19781979// This is the case for the outer caller, i.e. the concurrent cycle.1980assert(!concurrent ||1981(_old_marking_cycles_started == _old_marking_cycles_completed + 1),1982"for outer caller (concurrent cycle): "1983"_old_marking_cycles_started = %u "1984"is inconsistent with _old_marking_cycles_completed = %u",1985_old_marking_cycles_started, _old_marking_cycles_completed);19861987_old_marking_cycles_completed += 1;1988if (whole_heap_examined) {1989// Signal that we have completed a visit to all live objects.1990record_whole_heap_examined_timestamp();1991}19921993// We need to clear the "in_progress" flag in the CM thread before1994// we wake up any waiters (especially when ExplicitInvokesConcurrent1995// is set) so that if a waiter requests another System.gc() it doesn't1996// incorrectly see that a marking cycle is still in progress.1997if (concurrent) {1998_cm_thread->set_idle();1999}20002001// Notify threads waiting in System.gc() (with ExplicitGCInvokesConcurrent)2002// for a full GC to finish that their wait is over.2003ml.notify_all();2004}20052006void G1CollectedHeap::collect(GCCause::Cause cause) {2007try_collect(cause);2008}20092010// Return true if (x < y) with allowance for wraparound.2011static bool gc_counter_less_than(uint x, uint y) {2012return (x - y) > (UINT_MAX/2);2013}20142015// LOG_COLLECT_CONCURRENTLY(cause, msg, args...)2016// Macro so msg printing is format-checked.2017#define LOG_COLLECT_CONCURRENTLY(cause, ...) \2018do { \2019LogTarget(Trace, gc) LOG_COLLECT_CONCURRENTLY_lt; \2020if (LOG_COLLECT_CONCURRENTLY_lt.is_enabled()) { \2021ResourceMark rm; /* For thread name. */ \2022LogStream LOG_COLLECT_CONCURRENTLY_s(&LOG_COLLECT_CONCURRENTLY_lt); \2023LOG_COLLECT_CONCURRENTLY_s.print("%s: Try Collect Concurrently (%s): ", \2024Thread::current()->name(), \2025GCCause::to_string(cause)); \2026LOG_COLLECT_CONCURRENTLY_s.print(__VA_ARGS__); \2027} \2028} while (0)20292030#define LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, result) \2031LOG_COLLECT_CONCURRENTLY(cause, "complete %s", BOOL_TO_STR(result))20322033bool G1CollectedHeap::try_collect_concurrently(GCCause::Cause cause,2034uint gc_counter,2035uint old_marking_started_before) {2036assert_heap_not_locked();2037assert(should_do_concurrent_full_gc(cause),2038"Non-concurrent cause %s", GCCause::to_string(cause));20392040for (uint i = 1; true; ++i) {2041// Try to schedule concurrent start evacuation pause that will2042// start a concurrent cycle.2043LOG_COLLECT_CONCURRENTLY(cause, "attempt %u", i);2044VM_G1TryInitiateConcMark op(gc_counter,2045cause,2046policy()->max_pause_time_ms());2047VMThread::execute(&op);20482049// Request is trivially finished.2050if (cause == GCCause::_g1_periodic_collection) {2051LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, op.gc_succeeded());2052return op.gc_succeeded();2053}20542055// If VMOp skipped initiating concurrent marking cycle because2056// we're terminating, then we're done.2057if (op.terminating()) {2058LOG_COLLECT_CONCURRENTLY(cause, "skipped: terminating");2059return false;2060}20612062// Lock to get consistent set of values.2063uint old_marking_started_after;2064uint old_marking_completed_after;2065{2066MutexLocker ml(Heap_lock);2067// Update gc_counter for retrying VMOp if needed. Captured here to be2068// consistent with the values we use below for termination tests. If2069// a retry is needed after a possible wait, and another collection2070// occurs in the meantime, it will cause our retry to be skipped and2071// we'll recheck for termination with updated conditions from that2072// more recent collection. That's what we want, rather than having2073// our retry possibly perform an unnecessary collection.2074gc_counter = total_collections();2075old_marking_started_after = _old_marking_cycles_started;2076old_marking_completed_after = _old_marking_cycles_completed;2077}20782079if (cause == GCCause::_wb_breakpoint) {2080if (op.gc_succeeded()) {2081LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);2082return true;2083}2084// When _wb_breakpoint there can't be another cycle or deferred.2085assert(!op.cycle_already_in_progress(), "invariant");2086assert(!op.whitebox_attached(), "invariant");2087// Concurrent cycle attempt might have been cancelled by some other2088// collection, so retry. Unlike other cases below, we want to retry2089// even if cancelled by a STW full collection, because we really want2090// to start a concurrent cycle.2091if (old_marking_started_before != old_marking_started_after) {2092LOG_COLLECT_CONCURRENTLY(cause, "ignoring STW full GC");2093old_marking_started_before = old_marking_started_after;2094}2095} else if (!GCCause::is_user_requested_gc(cause)) {2096// For an "automatic" (not user-requested) collection, we just need to2097// ensure that progress is made.2098//2099// Request is finished if any of2100// (1) the VMOp successfully performed a GC,2101// (2) a concurrent cycle was already in progress,2102// (3) whitebox is controlling concurrent cycles,2103// (4) a new cycle was started (by this thread or some other), or2104// (5) a Full GC was performed.2105// Cases (4) and (5) are detected together by a change to2106// _old_marking_cycles_started.2107//2108// Note that (1) does not imply (4). If we're still in the mixed2109// phase of an earlier concurrent collection, the request to make the2110// collection a concurrent start won't be honored. If we don't check for2111// both conditions we'll spin doing back-to-back collections.2112if (op.gc_succeeded() ||2113op.cycle_already_in_progress() ||2114op.whitebox_attached() ||2115(old_marking_started_before != old_marking_started_after)) {2116LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);2117return true;2118}2119} else { // User-requested GC.2120// For a user-requested collection, we want to ensure that a complete2121// full collection has been performed before returning, but without2122// waiting for more than needed.21232124// For user-requested GCs (unlike non-UR), a successful VMOp implies a2125// new cycle was started. That's good, because it's not clear what we2126// should do otherwise. Trying again just does back to back GCs.2127// Can't wait for someone else to start a cycle. And returning fails2128// to meet the goal of ensuring a full collection was performed.2129assert(!op.gc_succeeded() ||2130(old_marking_started_before != old_marking_started_after),2131"invariant: succeeded %s, started before %u, started after %u",2132BOOL_TO_STR(op.gc_succeeded()),2133old_marking_started_before, old_marking_started_after);21342135// Request is finished if a full collection (concurrent or stw)2136// was started after this request and has completed, e.g.2137// started_before < completed_after.2138if (gc_counter_less_than(old_marking_started_before,2139old_marking_completed_after)) {2140LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);2141return true;2142}21432144if (old_marking_started_after != old_marking_completed_after) {2145// If there is an in-progress cycle (possibly started by us), then2146// wait for that cycle to complete, e.g.2147// while completed_now < started_after.2148LOG_COLLECT_CONCURRENTLY(cause, "wait");2149MonitorLocker ml(G1OldGCCount_lock);2150while (gc_counter_less_than(_old_marking_cycles_completed,2151old_marking_started_after)) {2152ml.wait();2153}2154// Request is finished if the collection we just waited for was2155// started after this request.2156if (old_marking_started_before != old_marking_started_after) {2157LOG_COLLECT_CONCURRENTLY(cause, "complete after wait");2158return true;2159}2160}21612162// If VMOp was successful then it started a new cycle that the above2163// wait &etc should have recognized as finishing this request. This2164// differs from a non-user-request, where gc_succeeded does not imply2165// a new cycle was started.2166assert(!op.gc_succeeded(), "invariant");21672168if (op.cycle_already_in_progress()) {2169// If VMOp failed because a cycle was already in progress, it2170// is now complete. But it didn't finish this user-requested2171// GC, so try again.2172LOG_COLLECT_CONCURRENTLY(cause, "retry after in-progress");2173continue;2174} else if (op.whitebox_attached()) {2175// If WhiteBox wants control, wait for notification of a state2176// change in the controller, then try again. Don't wait for2177// release of control, since collections may complete while in2178// control. Note: This won't recognize a STW full collection2179// while waiting; we can't wait on multiple monitors.2180LOG_COLLECT_CONCURRENTLY(cause, "whitebox control stall");2181MonitorLocker ml(ConcurrentGCBreakpoints::monitor());2182if (ConcurrentGCBreakpoints::is_controlled()) {2183ml.wait();2184}2185continue;2186}2187}21882189// Collection failed and should be retried.2190assert(op.transient_failure(), "invariant");21912192if (GCLocker::is_active_and_needs_gc()) {2193// If GCLocker is active, wait until clear before retrying.2194LOG_COLLECT_CONCURRENTLY(cause, "gc-locker stall");2195GCLocker::stall_until_clear();2196}21972198LOG_COLLECT_CONCURRENTLY(cause, "retry");2199}2200}22012202bool G1CollectedHeap::try_collect(GCCause::Cause cause) {2203assert_heap_not_locked();22042205// Lock to get consistent set of values.2206uint gc_count_before;2207uint full_gc_count_before;2208uint old_marking_started_before;2209{2210MutexLocker ml(Heap_lock);2211gc_count_before = total_collections();2212full_gc_count_before = total_full_collections();2213old_marking_started_before = _old_marking_cycles_started;2214}22152216if (should_do_concurrent_full_gc(cause)) {2217return try_collect_concurrently(cause,2218gc_count_before,2219old_marking_started_before);2220} else if (GCLocker::should_discard(cause, gc_count_before)) {2221// Indicate failure to be consistent with VMOp failure due to2222// another collection slipping in after our gc_count but before2223// our request is processed.2224return false;2225} else if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc2226DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {22272228// Schedule a standard evacuation pause. We're setting word_size2229// to 0 which means that we are not requesting a post-GC allocation.2230VM_G1CollectForAllocation op(0, /* word_size */2231gc_count_before,2232cause,2233policy()->max_pause_time_ms());2234VMThread::execute(&op);2235return op.gc_succeeded();2236} else {2237// Schedule a Full GC.2238VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause);2239VMThread::execute(&op);2240return op.gc_succeeded();2241}2242}22432244bool G1CollectedHeap::is_in(const void* p) const {2245return is_in_reserved(p) && _hrm.is_available(addr_to_region((HeapWord*)p));2246}22472248// Iteration functions.22492250// Iterates an ObjectClosure over all objects within a HeapRegion.22512252class IterateObjectClosureRegionClosure: public HeapRegionClosure {2253ObjectClosure* _cl;2254public:2255IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}2256bool do_heap_region(HeapRegion* r) {2257if (!r->is_continues_humongous()) {2258r->object_iterate(_cl);2259}2260return false;2261}2262};22632264void G1CollectedHeap::object_iterate(ObjectClosure* cl) {2265IterateObjectClosureRegionClosure blk(cl);2266heap_region_iterate(&blk);2267}22682269class G1ParallelObjectIterator : public ParallelObjectIterator {2270private:2271G1CollectedHeap* _heap;2272HeapRegionClaimer _claimer;22732274public:2275G1ParallelObjectIterator(uint thread_num) :2276_heap(G1CollectedHeap::heap()),2277_claimer(thread_num == 0 ? G1CollectedHeap::heap()->workers()->active_workers() : thread_num) {}22782279virtual void object_iterate(ObjectClosure* cl, uint worker_id) {2280_heap->object_iterate_parallel(cl, worker_id, &_claimer);2281}2282};22832284ParallelObjectIterator* G1CollectedHeap::parallel_object_iterator(uint thread_num) {2285return new G1ParallelObjectIterator(thread_num);2286}22872288void G1CollectedHeap::object_iterate_parallel(ObjectClosure* cl, uint worker_id, HeapRegionClaimer* claimer) {2289IterateObjectClosureRegionClosure blk(cl);2290heap_region_par_iterate_from_worker_offset(&blk, claimer, worker_id);2291}22922293void G1CollectedHeap::keep_alive(oop obj) {2294G1BarrierSet::enqueue(obj);2295}22962297void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {2298_hrm.iterate(cl);2299}23002301void G1CollectedHeap::heap_region_par_iterate_from_worker_offset(HeapRegionClosure* cl,2302HeapRegionClaimer *hrclaimer,2303uint worker_id) const {2304_hrm.par_iterate(cl, hrclaimer, hrclaimer->offset_for_worker(worker_id));2305}23062307void G1CollectedHeap::heap_region_par_iterate_from_start(HeapRegionClosure* cl,2308HeapRegionClaimer *hrclaimer) const {2309_hrm.par_iterate(cl, hrclaimer, 0);2310}23112312void G1CollectedHeap::collection_set_iterate_all(HeapRegionClosure* cl) {2313_collection_set.iterate(cl);2314}23152316void G1CollectedHeap::collection_set_par_iterate_all(HeapRegionClosure* cl, HeapRegionClaimer* hr_claimer, uint worker_id) {2317_collection_set.par_iterate(cl, hr_claimer, worker_id, workers()->active_workers());2318}23192320void G1CollectedHeap::collection_set_iterate_increment_from(HeapRegionClosure *cl, HeapRegionClaimer* hr_claimer, uint worker_id) {2321_collection_set.iterate_incremental_part_from(cl, hr_claimer, worker_id, workers()->active_workers());2322}23232324HeapWord* G1CollectedHeap::block_start(const void* addr) const {2325HeapRegion* hr = heap_region_containing(addr);2326return hr->block_start(addr);2327}23282329bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {2330HeapRegion* hr = heap_region_containing(addr);2331return hr->block_is_obj(addr);2332}23332334size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {2335return (_policy->young_list_target_length() - _survivor.length()) * HeapRegion::GrainBytes;2336}23372338size_t G1CollectedHeap::tlab_used(Thread* ignored) const {2339return _eden.length() * HeapRegion::GrainBytes;2340}23412342// For G1 TLABs should not contain humongous objects, so the maximum TLAB size2343// must be equal to the humongous object limit.2344size_t G1CollectedHeap::max_tlab_size() const {2345return align_down(_humongous_object_threshold_in_words, MinObjAlignment);2346}23472348size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {2349return _allocator->unsafe_max_tlab_alloc();2350}23512352size_t G1CollectedHeap::max_capacity() const {2353return max_regions() * HeapRegion::GrainBytes;2354}23552356void G1CollectedHeap::prepare_for_verify() {2357_verifier->prepare_for_verify();2358}23592360void G1CollectedHeap::verify(VerifyOption vo) {2361_verifier->verify(vo);2362}23632364bool G1CollectedHeap::supports_concurrent_gc_breakpoints() const {2365return true;2366}23672368bool G1CollectedHeap::is_archived_object(oop object) const {2369return object != NULL && heap_region_containing(object)->is_archive();2370}23712372class PrintRegionClosure: public HeapRegionClosure {2373outputStream* _st;2374public:2375PrintRegionClosure(outputStream* st) : _st(st) {}2376bool do_heap_region(HeapRegion* r) {2377r->print_on(_st);2378return false;2379}2380};23812382bool G1CollectedHeap::is_obj_dead_cond(const oop obj,2383const HeapRegion* hr,2384const VerifyOption vo) const {2385switch (vo) {2386case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);2387case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);2388case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj, hr);2389default: ShouldNotReachHere();2390}2391return false; // keep some compilers happy2392}23932394bool G1CollectedHeap::is_obj_dead_cond(const oop obj,2395const VerifyOption vo) const {2396switch (vo) {2397case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);2398case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);2399case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj);2400default: ShouldNotReachHere();2401}2402return false; // keep some compilers happy2403}24042405void G1CollectedHeap::print_heap_regions() const {2406LogTarget(Trace, gc, heap, region) lt;2407if (lt.is_enabled()) {2408LogStream ls(lt);2409print_regions_on(&ls);2410}2411}24122413void G1CollectedHeap::print_on(outputStream* st) const {2414size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();2415st->print(" %-20s", "garbage-first heap");2416st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",2417capacity()/K, heap_used/K);2418st->print(" [" PTR_FORMAT ", " PTR_FORMAT ")",2419p2i(_hrm.reserved().start()),2420p2i(_hrm.reserved().end()));2421st->cr();2422st->print(" region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);2423uint young_regions = young_regions_count();2424st->print("%u young (" SIZE_FORMAT "K), ", young_regions,2425(size_t) young_regions * HeapRegion::GrainBytes / K);2426uint survivor_regions = survivor_regions_count();2427st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,2428(size_t) survivor_regions * HeapRegion::GrainBytes / K);2429st->cr();2430if (_numa->is_enabled()) {2431uint num_nodes = _numa->num_active_nodes();2432st->print(" remaining free region(s) on each NUMA node: ");2433const int* node_ids = _numa->node_ids();2434for (uint node_index = 0; node_index < num_nodes; node_index++) {2435uint num_free_regions = _hrm.num_free_regions(node_index);2436st->print("%d=%u ", node_ids[node_index], num_free_regions);2437}2438st->cr();2439}2440MetaspaceUtils::print_on(st);2441}24422443void G1CollectedHeap::print_regions_on(outputStream* st) const {2444st->print_cr("Heap Regions: E=young(eden), S=young(survivor), O=old, "2445"HS=humongous(starts), HC=humongous(continues), "2446"CS=collection set, F=free, "2447"OA=open archive, CA=closed archive, "2448"TAMS=top-at-mark-start (previous, next)");2449PrintRegionClosure blk(st);2450heap_region_iterate(&blk);2451}24522453void G1CollectedHeap::print_extended_on(outputStream* st) const {2454print_on(st);24552456// Print the per-region information.2457st->cr();2458print_regions_on(st);2459}24602461void G1CollectedHeap::print_on_error(outputStream* st) const {2462this->CollectedHeap::print_on_error(st);24632464if (_cm != NULL) {2465st->cr();2466_cm->print_on_error(st);2467}2468}24692470void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {2471workers()->threads_do(tc);2472tc->do_thread(_cm_thread);2473_cm->threads_do(tc);2474_cr->threads_do(tc);2475tc->do_thread(_service_thread);2476}24772478void G1CollectedHeap::print_tracing_info() const {2479rem_set()->print_summary_info();2480concurrent_mark()->print_summary_info();2481}24822483#ifndef PRODUCT2484// Helpful for debugging RSet issues.24852486class PrintRSetsClosure : public HeapRegionClosure {2487private:2488const char* _msg;2489size_t _occupied_sum;24902491public:2492bool do_heap_region(HeapRegion* r) {2493HeapRegionRemSet* hrrs = r->rem_set();2494size_t occupied = hrrs->occupied();2495_occupied_sum += occupied;24962497tty->print_cr("Printing RSet for region " HR_FORMAT, HR_FORMAT_PARAMS(r));2498if (occupied == 0) {2499tty->print_cr(" RSet is empty");2500} else {2501hrrs->print();2502}2503tty->print_cr("----------");2504return false;2505}25062507PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {2508tty->cr();2509tty->print_cr("========================================");2510tty->print_cr("%s", msg);2511tty->cr();2512}25132514~PrintRSetsClosure() {2515tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum);2516tty->print_cr("========================================");2517tty->cr();2518}2519};25202521void G1CollectedHeap::print_cset_rsets() {2522PrintRSetsClosure cl("Printing CSet RSets");2523collection_set_iterate_all(&cl);2524}25252526void G1CollectedHeap::print_all_rsets() {2527PrintRSetsClosure cl("Printing All RSets");;2528heap_region_iterate(&cl);2529}2530#endif // PRODUCT25312532bool G1CollectedHeap::print_location(outputStream* st, void* addr) const {2533return BlockLocationPrinter<G1CollectedHeap>::print_location(st, addr);2534}25352536G1HeapSummary G1CollectedHeap::create_g1_heap_summary() {25372538size_t eden_used_bytes = _eden.used_bytes();2539size_t survivor_used_bytes = _survivor.used_bytes();2540size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();25412542size_t eden_capacity_bytes =2543(policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes;25442545VirtualSpaceSummary heap_summary = create_heap_space_summary();2546return G1HeapSummary(heap_summary, heap_used, eden_used_bytes,2547eden_capacity_bytes, survivor_used_bytes, num_regions());2548}25492550G1EvacSummary G1CollectedHeap::create_g1_evac_summary(G1EvacStats* stats) {2551return G1EvacSummary(stats->allocated(), stats->wasted(), stats->undo_wasted(),2552stats->unused(), stats->used(), stats->region_end_waste(),2553stats->regions_filled(), stats->direct_allocated(),2554stats->failure_used(), stats->failure_waste());2555}25562557void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {2558const G1HeapSummary& heap_summary = create_g1_heap_summary();2559gc_tracer->report_gc_heap_summary(when, heap_summary);25602561const MetaspaceSummary& metaspace_summary = create_metaspace_summary();2562gc_tracer->report_metaspace_summary(when, metaspace_summary);2563}25642565void G1CollectedHeap::gc_prologue(bool full) {2566assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");25672568// This summary needs to be printed before incrementing total collections.2569rem_set()->print_periodic_summary_info("Before GC RS summary", total_collections());25702571// Update common counters.2572increment_total_collections(full /* full gc */);2573if (full || collector_state()->in_concurrent_start_gc()) {2574increment_old_marking_cycles_started();2575}25762577// Fill TLAB's and such2578{2579Ticks start = Ticks::now();2580ensure_parsability(true);2581Tickspan dt = Ticks::now() - start;2582phase_times()->record_prepare_tlab_time_ms(dt.seconds() * MILLIUNITS);2583}25842585if (!full) {2586// Flush dirty card queues to qset, so later phases don't need to account2587// for partially filled per-thread queues and such. Not needed for full2588// collections, which ignore those logs.2589Ticks start = Ticks::now();2590G1BarrierSet::dirty_card_queue_set().concatenate_logs();2591Tickspan dt = Ticks::now() - start;2592phase_times()->record_concatenate_dirty_card_logs_time_ms(dt.seconds() * MILLIUNITS);2593}2594}25952596void G1CollectedHeap::gc_epilogue(bool full) {2597// Update common counters.2598if (full) {2599// Update the number of full collections that have been completed.2600increment_old_marking_cycles_completed(false /* concurrent */, true /* liveness_completed */);2601}26022603// We are at the end of the GC. Total collections has already been increased.2604rem_set()->print_periodic_summary_info("After GC RS summary", total_collections() - 1);26052606#if COMPILER2_OR_JVMCI2607assert(DerivedPointerTable::is_empty(), "derived pointer present");2608#endif26092610double start = os::elapsedTime();2611resize_all_tlabs();2612phase_times()->record_resize_tlab_time_ms((os::elapsedTime() - start) * 1000.0);26132614MemoryService::track_memory_usage();2615// We have just completed a GC. Update the soft reference2616// policy with the new heap occupancy2617Universe::heap()->update_capacity_and_used_at_gc();26182619// Print NUMA statistics.2620_numa->print_statistics();26212622_collection_pause_end = Ticks::now();2623}26242625uint G1CollectedHeap::uncommit_regions(uint region_limit) {2626return _hrm.uncommit_inactive_regions(region_limit);2627}26282629bool G1CollectedHeap::has_uncommittable_regions() {2630return _hrm.has_inactive_regions();2631}26322633void G1CollectedHeap::uncommit_regions_if_necessary() {2634if (has_uncommittable_regions()) {2635G1UncommitRegionTask::enqueue();2636}2637}26382639void G1CollectedHeap::verify_numa_regions(const char* desc) {2640LogTarget(Trace, gc, heap, verify) lt;26412642if (lt.is_enabled()) {2643LogStream ls(lt);2644// Iterate all heap regions to print matching between preferred numa id and actual numa id.2645G1NodeIndexCheckClosure cl(desc, _numa, &ls);2646heap_region_iterate(&cl);2647}2648}26492650HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,2651uint gc_count_before,2652bool* succeeded,2653GCCause::Cause gc_cause) {2654assert_heap_not_locked_and_not_at_safepoint();2655VM_G1CollectForAllocation op(word_size,2656gc_count_before,2657gc_cause,2658policy()->max_pause_time_ms());2659VMThread::execute(&op);26602661HeapWord* result = op.result();2662bool ret_succeeded = op.prologue_succeeded() && op.gc_succeeded();2663assert(result == NULL || ret_succeeded,2664"the result should be NULL if the VM did not succeed");2665*succeeded = ret_succeeded;26662667assert_heap_not_locked();2668return result;2669}26702671void G1CollectedHeap::start_concurrent_cycle(bool concurrent_operation_is_full_mark) {2672assert(!_cm_thread->in_progress(), "Can not start concurrent operation while in progress");26732674MutexLocker x(CGC_lock, Mutex::_no_safepoint_check_flag);2675if (concurrent_operation_is_full_mark) {2676_cm->post_concurrent_mark_start();2677_cm_thread->start_full_mark();2678} else {2679_cm->post_concurrent_undo_start();2680_cm_thread->start_undo_mark();2681}2682CGC_lock->notify();2683}26842685bool G1CollectedHeap::is_potential_eager_reclaim_candidate(HeapRegion* r) const {2686// We don't nominate objects with many remembered set entries, on2687// the assumption that such objects are likely still live.2688HeapRegionRemSet* rem_set = r->rem_set();26892690return G1EagerReclaimHumongousObjectsWithStaleRefs ?2691rem_set->occupancy_less_or_equal_than(G1EagerReclaimRemSetThreshold) :2692G1EagerReclaimHumongousObjects && rem_set->is_empty();2693}26942695#ifndef PRODUCT2696void G1CollectedHeap::verify_region_attr_remset_update() {2697class VerifyRegionAttrRemSet : public HeapRegionClosure {2698public:2699virtual bool do_heap_region(HeapRegion* r) {2700G1CollectedHeap* g1h = G1CollectedHeap::heap();2701bool const needs_remset_update = g1h->region_attr(r->bottom()).needs_remset_update();2702assert(r->rem_set()->is_tracked() == needs_remset_update,2703"Region %u remset tracking status (%s) different to region attribute (%s)",2704r->hrm_index(), BOOL_TO_STR(r->rem_set()->is_tracked()), BOOL_TO_STR(needs_remset_update));2705return false;2706}2707} cl;2708heap_region_iterate(&cl);2709}2710#endif27112712class VerifyRegionRemSetClosure : public HeapRegionClosure {2713public:2714bool do_heap_region(HeapRegion* hr) {2715if (!hr->is_archive() && !hr->is_continues_humongous()) {2716hr->verify_rem_set();2717}2718return false;2719}2720};27212722uint G1CollectedHeap::num_task_queues() const {2723return _task_queues->size();2724}27252726#if TASKQUEUE_STATS2727void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {2728st->print_raw_cr("GC Task Stats");2729st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();2730st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();2731}27322733void G1CollectedHeap::print_taskqueue_stats() const {2734if (!log_is_enabled(Trace, gc, task, stats)) {2735return;2736}2737Log(gc, task, stats) log;2738ResourceMark rm;2739LogStream ls(log.trace());2740outputStream* st = &ls;27412742print_taskqueue_stats_hdr(st);27432744TaskQueueStats totals;2745const uint n = num_task_queues();2746for (uint i = 0; i < n; ++i) {2747st->print("%3u ", i); task_queue(i)->stats.print(st); st->cr();2748totals += task_queue(i)->stats;2749}2750st->print_raw("tot "); totals.print(st); st->cr();27512752DEBUG_ONLY(totals.verify());2753}27542755void G1CollectedHeap::reset_taskqueue_stats() {2756const uint n = num_task_queues();2757for (uint i = 0; i < n; ++i) {2758task_queue(i)->stats.reset();2759}2760}2761#endif // TASKQUEUE_STATS27622763void G1CollectedHeap::wait_for_root_region_scanning() {2764double scan_wait_start = os::elapsedTime();2765// We have to wait until the CM threads finish scanning the2766// root regions as it's the only way to ensure that all the2767// objects on them have been correctly scanned before we start2768// moving them during the GC.2769bool waited = _cm->root_regions()->wait_until_scan_finished();2770double wait_time_ms = 0.0;2771if (waited) {2772double scan_wait_end = os::elapsedTime();2773wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;2774}2775phase_times()->record_root_region_scan_wait_time(wait_time_ms);2776}27772778class G1PrintCollectionSetClosure : public HeapRegionClosure {2779private:2780G1HRPrinter* _hr_printer;2781public:2782G1PrintCollectionSetClosure(G1HRPrinter* hr_printer) : HeapRegionClosure(), _hr_printer(hr_printer) { }27832784virtual bool do_heap_region(HeapRegion* r) {2785_hr_printer->cset(r);2786return false;2787}2788};27892790void G1CollectedHeap::start_new_collection_set() {2791double start = os::elapsedTime();27922793collection_set()->start_incremental_building();27942795clear_region_attr();27962797guarantee(_eden.length() == 0, "eden should have been cleared");2798policy()->transfer_survivors_to_cset(survivor());27992800// We redo the verification but now wrt to the new CSet which2801// has just got initialized after the previous CSet was freed.2802_cm->verify_no_collection_set_oops();28032804phase_times()->record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0);2805}28062807void G1CollectedHeap::calculate_collection_set(G1EvacuationInfo& evacuation_info, double target_pause_time_ms) {28082809_collection_set.finalize_initial_collection_set(target_pause_time_ms, &_survivor);2810evacuation_info.set_collectionset_regions(collection_set()->region_length() +2811collection_set()->optional_region_length());28122813_cm->verify_no_collection_set_oops();28142815if (_hr_printer.is_active()) {2816G1PrintCollectionSetClosure cl(&_hr_printer);2817_collection_set.iterate(&cl);2818_collection_set.iterate_optional(&cl);2819}2820}28212822G1HeapVerifier::G1VerifyType G1CollectedHeap::young_collection_verify_type() const {2823if (collector_state()->in_concurrent_start_gc()) {2824return G1HeapVerifier::G1VerifyConcurrentStart;2825} else if (collector_state()->in_young_only_phase()) {2826return G1HeapVerifier::G1VerifyYoungNormal;2827} else {2828return G1HeapVerifier::G1VerifyMixed;2829}2830}28312832void G1CollectedHeap::verify_before_young_collection(G1HeapVerifier::G1VerifyType type) {2833if (VerifyRememberedSets) {2834log_info(gc, verify)("[Verifying RemSets before GC]");2835VerifyRegionRemSetClosure v_cl;2836heap_region_iterate(&v_cl);2837}2838_verifier->verify_before_gc(type);2839_verifier->check_bitmaps("GC Start");2840verify_numa_regions("GC Start");2841}28422843void G1CollectedHeap::verify_after_young_collection(G1HeapVerifier::G1VerifyType type) {2844if (VerifyRememberedSets) {2845log_info(gc, verify)("[Verifying RemSets after GC]");2846VerifyRegionRemSetClosure v_cl;2847heap_region_iterate(&v_cl);2848}2849_verifier->verify_after_gc(type);2850_verifier->check_bitmaps("GC End");2851verify_numa_regions("GC End");2852}28532854void G1CollectedHeap::expand_heap_after_young_collection(){2855size_t expand_bytes = _heap_sizing_policy->young_collection_expansion_amount();2856if (expand_bytes > 0) {2857// No need for an ergo logging here,2858// expansion_amount() does this when it returns a value > 0.2859double expand_ms = 0.0;2860if (!expand(expand_bytes, _workers, &expand_ms)) {2861// We failed to expand the heap. Cannot do anything about it.2862}2863phase_times()->record_expand_heap_time(expand_ms);2864}2865}28662867void G1CollectedHeap::set_young_gc_name(char* young_gc_name) {2868G1GCPauseType pause_type =2869// The strings for all Concurrent Start pauses are the same, so the parameter2870// does not matter here.2871collector_state()->young_gc_pause_type(false /* concurrent_operation_is_full_mark */);2872snprintf(young_gc_name,2873MaxYoungGCNameLength,2874"Pause Young (%s)",2875G1GCPauseTypeHelper::to_string(pause_type));2876}28772878bool G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {2879assert_at_safepoint_on_vm_thread();2880guarantee(!is_gc_active(), "collection is not reentrant");28812882if (GCLocker::check_active_before_gc()) {2883return false;2884}28852886do_collection_pause_at_safepoint_helper(target_pause_time_ms);2887return true;2888}28892890void G1CollectedHeap::gc_tracer_report_gc_start() {2891_gc_timer_stw->register_gc_start();2892_gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());2893}28942895void G1CollectedHeap::gc_tracer_report_gc_end(bool concurrent_operation_is_full_mark,2896G1EvacuationInfo& evacuation_info) {2897_gc_tracer_stw->report_evacuation_info(&evacuation_info);2898_gc_tracer_stw->report_tenuring_threshold(_policy->tenuring_threshold());28992900_gc_timer_stw->register_gc_end();2901_gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(),2902_gc_timer_stw->time_partitions());2903}29042905void G1CollectedHeap::do_collection_pause_at_safepoint_helper(double target_pause_time_ms) {2906GCIdMark gc_id_mark;29072908SvcGCMarker sgcm(SvcGCMarker::MINOR);2909ResourceMark rm;29102911policy()->note_gc_start();29122913gc_tracer_report_gc_start();29142915wait_for_root_region_scanning();29162917print_heap_before_gc();2918print_heap_regions();2919trace_heap_before_gc(_gc_tracer_stw);29202921_verifier->verify_region_sets_optional();2922_verifier->verify_dirty_young_regions();29232924// We should not be doing concurrent start unless the concurrent mark thread is running2925if (!_cm_thread->should_terminate()) {2926// This call will decide whether this pause is a concurrent start2927// pause. If it is, in_concurrent_start_gc() will return true2928// for the duration of this pause.2929policy()->decide_on_conc_mark_initiation();2930}29312932// We do not allow concurrent start to be piggy-backed on a mixed GC.2933assert(!collector_state()->in_concurrent_start_gc() ||2934collector_state()->in_young_only_phase(), "sanity");2935// We also do not allow mixed GCs during marking.2936assert(!collector_state()->mark_or_rebuild_in_progress() || collector_state()->in_young_only_phase(), "sanity");29372938// Record whether this pause may need to trigger a concurrent operation. Later,2939// when we signal the G1ConcurrentMarkThread, the collector state has already2940// been reset for the next pause.2941bool should_start_concurrent_mark_operation = collector_state()->in_concurrent_start_gc();2942bool concurrent_operation_is_full_mark = false;29432944// Inner scope for scope based logging, timers, and stats collection2945{2946G1EvacuationInfo evacuation_info;29472948GCTraceCPUTime tcpu;29492950char young_gc_name[MaxYoungGCNameLength];2951set_young_gc_name(young_gc_name);29522953GCTraceTime(Info, gc) tm(young_gc_name, NULL, gc_cause(), true);29542955uint active_workers = WorkerPolicy::calc_active_workers(workers()->total_workers(),2956workers()->active_workers(),2957Threads::number_of_non_daemon_threads());2958active_workers = workers()->update_active_workers(active_workers);2959log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->total_workers());29602961G1MonitoringScope ms(g1mm(),2962false /* full_gc */,2963collector_state()->in_mixed_phase() /* all_memory_pools_affected */);29642965G1HeapTransition heap_transition(this);29662967{2968IsGCActiveMark x;29692970gc_prologue(false);29712972G1HeapVerifier::G1VerifyType verify_type = young_collection_verify_type();2973verify_before_young_collection(verify_type);29742975{2976// The elapsed time induced by the start time below deliberately elides2977// the possible verification above.2978double sample_start_time_sec = os::elapsedTime();29792980// Please see comment in g1CollectedHeap.hpp and2981// G1CollectedHeap::ref_processing_init() to see how2982// reference processing currently works in G1.2983_ref_processor_stw->enable_discovery();29842985// We want to temporarily turn off discovery by the2986// CM ref processor, if necessary, and turn it back on2987// on again later if we do. Using a scoped2988// NoRefDiscovery object will do this.2989NoRefDiscovery no_cm_discovery(_ref_processor_cm);29902991policy()->record_collection_pause_start(sample_start_time_sec);29922993// Forget the current allocation region (we might even choose it to be part2994// of the collection set!).2995_allocator->release_mutator_alloc_regions();29962997calculate_collection_set(evacuation_info, target_pause_time_ms);29982999G1RedirtyCardsQueueSet rdcqs(G1BarrierSet::dirty_card_queue_set().allocator());3000G1ParScanThreadStateSet per_thread_states(this,3001&rdcqs,3002workers()->active_workers(),3003collection_set()->young_region_length(),3004collection_set()->optional_region_length());3005pre_evacuate_collection_set(evacuation_info, &per_thread_states);30063007bool may_do_optional_evacuation = _collection_set.optional_region_length() != 0;3008// Actually do the work...3009evacuate_initial_collection_set(&per_thread_states, may_do_optional_evacuation);30103011if (may_do_optional_evacuation) {3012evacuate_optional_collection_set(&per_thread_states);3013}3014post_evacuate_collection_set(evacuation_info, &rdcqs, &per_thread_states);30153016start_new_collection_set();30173018_survivor_evac_stats.adjust_desired_plab_sz();3019_old_evac_stats.adjust_desired_plab_sz();30203021allocate_dummy_regions();30223023_allocator->init_mutator_alloc_regions();30243025expand_heap_after_young_collection();30263027// Refine the type of a concurrent mark operation now that we did the3028// evacuation, eventually aborting it.3029concurrent_operation_is_full_mark = policy()->concurrent_operation_is_full_mark("Revise IHOP");30303031// Need to report the collection pause now since record_collection_pause_end()3032// modifies it to the next state.3033_gc_tracer_stw->report_young_gc_pause(collector_state()->young_gc_pause_type(concurrent_operation_is_full_mark));30343035double sample_end_time_sec = os::elapsedTime();3036double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;3037policy()->record_collection_pause_end(pause_time_ms, concurrent_operation_is_full_mark);3038}30393040verify_after_young_collection(verify_type);30413042gc_epilogue(false);3043}30443045// Print the remainder of the GC log output.3046if (evacuation_failed()) {3047log_info(gc)("To-space exhausted");3048}30493050policy()->print_phases();3051heap_transition.print();30523053_hrm.verify_optional();3054_verifier->verify_region_sets_optional();30553056TASKQUEUE_STATS_ONLY(print_taskqueue_stats());3057TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());30583059print_heap_after_gc();3060print_heap_regions();3061trace_heap_after_gc(_gc_tracer_stw);30623063// We must call G1MonitoringSupport::update_sizes() in the same scoping level3064// as an active TraceMemoryManagerStats object (i.e. before the destructor for the3065// TraceMemoryManagerStats is called) so that the G1 memory pools are updated3066// before any GC notifications are raised.3067g1mm()->update_sizes();30683069gc_tracer_report_gc_end(concurrent_operation_is_full_mark, evacuation_info);3070}3071// It should now be safe to tell the concurrent mark thread to start3072// without its logging output interfering with the logging output3073// that came from the pause.30743075if (should_start_concurrent_mark_operation) {3076// CAUTION: after the start_concurrent_cycle() call below, the concurrent marking3077// thread(s) could be running concurrently with us. Make sure that anything3078// after this point does not assume that we are the only GC thread running.3079// Note: of course, the actual marking work will not start until the safepoint3080// itself is released in SuspendibleThreadSet::desynchronize().3081start_concurrent_cycle(concurrent_operation_is_full_mark);3082ConcurrentGCBreakpoints::notify_idle_to_active();3083}3084}30853086void G1CollectedHeap::preserve_mark_during_evac_failure(uint worker_id, oop obj, markWord m) {3087_evacuation_failed_info_array[worker_id].register_copy_failure(obj->size());3088_preserved_marks_set.get(worker_id)->push_if_necessary(obj, m);3089}30903091bool G1ParEvacuateFollowersClosure::offer_termination() {3092EventGCPhaseParallel event;3093G1ParScanThreadState* const pss = par_scan_state();3094start_term_time();3095const bool res = (terminator() == nullptr) ? true : terminator()->offer_termination();3096end_term_time();3097event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(G1GCPhaseTimes::Termination));3098return res;3099}31003101void G1ParEvacuateFollowersClosure::do_void() {3102EventGCPhaseParallel event;3103G1ParScanThreadState* const pss = par_scan_state();3104pss->trim_queue();3105event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));3106do {3107EventGCPhaseParallel event;3108pss->steal_and_trim_queue(queues());3109event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));3110} while (!offer_termination());3111}31123113void G1CollectedHeap::complete_cleaning(BoolObjectClosure* is_alive,3114bool class_unloading_occurred) {3115uint num_workers = workers()->active_workers();3116G1ParallelCleaningTask unlink_task(is_alive, num_workers, class_unloading_occurred);3117workers()->run_task(&unlink_task);3118}31193120// Weak Reference Processing support31213122bool G1STWIsAliveClosure::do_object_b(oop p) {3123// An object is reachable if it is outside the collection set,3124// or is inside and copied.3125return !_g1h->is_in_cset(p) || p->is_forwarded();3126}31273128bool G1STWSubjectToDiscoveryClosure::do_object_b(oop obj) {3129assert(obj != NULL, "must not be NULL");3130assert(_g1h->is_in_reserved(obj), "Trying to discover obj " PTR_FORMAT " not in heap", p2i(obj));3131// The areas the CM and STW ref processor manage must be disjoint. The is_in_cset() below3132// may falsely indicate that this is not the case here: however the collection set only3133// contains old regions when concurrent mark is not running.3134return _g1h->is_in_cset(obj) || _g1h->heap_region_containing(obj)->is_survivor();3135}31363137// Non Copying Keep Alive closure3138class G1KeepAliveClosure: public OopClosure {3139G1CollectedHeap*_g1h;3140public:3141G1KeepAliveClosure(G1CollectedHeap* g1h) :_g1h(g1h) {}3142void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }3143void do_oop(oop* p) {3144oop obj = *p;3145assert(obj != NULL, "the caller should have filtered out NULL values");31463147const G1HeapRegionAttr region_attr =_g1h->region_attr(obj);3148if (!region_attr.is_in_cset_or_humongous()) {3149return;3150}3151if (region_attr.is_in_cset()) {3152assert( obj->is_forwarded(), "invariant" );3153*p = obj->forwardee();3154} else {3155assert(!obj->is_forwarded(), "invariant" );3156assert(region_attr.is_humongous(),3157"Only allowed G1HeapRegionAttr state is IsHumongous, but is %d", region_attr.type());3158_g1h->set_humongous_is_live(obj);3159}3160}3161};31623163// Copying Keep Alive closure - can be called from both3164// serial and parallel code as long as different worker3165// threads utilize different G1ParScanThreadState instances3166// and different queues.31673168class G1CopyingKeepAliveClosure: public OopClosure {3169G1CollectedHeap* _g1h;3170G1ParScanThreadState* _par_scan_state;31713172public:3173G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,3174G1ParScanThreadState* pss):3175_g1h(g1h),3176_par_scan_state(pss)3177{}31783179virtual void do_oop(narrowOop* p) { do_oop_work(p); }3180virtual void do_oop( oop* p) { do_oop_work(p); }31813182template <class T> void do_oop_work(T* p) {3183oop obj = RawAccess<>::oop_load(p);31843185if (_g1h->is_in_cset_or_humongous(obj)) {3186// If the referent object has been forwarded (either copied3187// to a new location or to itself in the event of an3188// evacuation failure) then we need to update the reference3189// field and, if both reference and referent are in the G13190// heap, update the RSet for the referent.3191//3192// If the referent has not been forwarded then we have to keep3193// it alive by policy. Therefore we have copy the referent.3194//3195// When the queue is drained (after each phase of reference processing)3196// the object and it's followers will be copied, the reference field set3197// to point to the new location, and the RSet updated.3198_par_scan_state->push_on_queue(ScannerTask(p));3199}3200}3201};32023203// Serial drain queue closure. Called as the 'complete_gc'3204// closure for each discovered list in some of the3205// reference processing phases.32063207class G1STWDrainQueueClosure: public VoidClosure {3208protected:3209G1CollectedHeap* _g1h;3210G1ParScanThreadState* _par_scan_state;32113212G1ParScanThreadState* par_scan_state() { return _par_scan_state; }32133214public:3215G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :3216_g1h(g1h),3217_par_scan_state(pss)3218{ }32193220void do_void() {3221G1ParScanThreadState* const pss = par_scan_state();3222pss->trim_queue();3223}3224};32253226class G1STWRefProcProxyTask : public RefProcProxyTask {3227G1CollectedHeap& _g1h;3228G1ParScanThreadStateSet& _pss;3229TaskTerminator _terminator;3230G1ScannerTasksQueueSet& _task_queues;32313232public:3233G1STWRefProcProxyTask(uint max_workers, G1CollectedHeap& g1h, G1ParScanThreadStateSet& pss, G1ScannerTasksQueueSet& task_queues)3234: RefProcProxyTask("G1STWRefProcProxyTask", max_workers),3235_g1h(g1h),3236_pss(pss),3237_terminator(max_workers, &task_queues),3238_task_queues(task_queues) {}32393240void work(uint worker_id) override {3241assert(worker_id < _max_workers, "sanity");3242uint index = (_tm == RefProcThreadModel::Single) ? 0 : worker_id;3243_pss.state_for_worker(index)->set_ref_discoverer(nullptr);3244G1STWIsAliveClosure is_alive(&_g1h);3245G1CopyingKeepAliveClosure keep_alive(&_g1h, _pss.state_for_worker(index));3246G1ParEvacuateFollowersClosure complete_gc(&_g1h, _pss.state_for_worker(index), &_task_queues, _tm == RefProcThreadModel::Single ? nullptr : &_terminator, G1GCPhaseTimes::ObjCopy);3247_rp_task->rp_work(worker_id, &is_alive, &keep_alive, &complete_gc);3248}32493250void prepare_run_task_hook() override {3251_terminator.reset_for_reuse(_queue_count);3252}3253};32543255// End of weak reference support closures32563257void G1CollectedHeap::process_discovered_references(G1ParScanThreadStateSet* per_thread_states) {3258double ref_proc_start = os::elapsedTime();32593260ReferenceProcessor* rp = _ref_processor_stw;3261assert(rp->discovery_enabled(), "should have been enabled");32623263// Use only a single queue for this PSS.3264G1ParScanThreadState* pss = per_thread_states->state_for_worker(0);3265pss->set_ref_discoverer(NULL);3266assert(pss->queue_is_empty(), "pre-condition");32673268// Setup the soft refs policy...3269rp->setup_policy(false);32703271ReferenceProcessorPhaseTimes& pt = *phase_times()->ref_phase_times();32723273ReferenceProcessorStats stats;3274uint no_of_gc_workers = workers()->active_workers();32753276// Parallel reference processing3277assert(no_of_gc_workers <= rp->max_num_queues(),3278"Mismatch between the number of GC workers %u and the maximum number of Reference process queues %u",3279no_of_gc_workers, rp->max_num_queues());32803281rp->set_active_mt_degree(no_of_gc_workers);3282G1STWRefProcProxyTask task(rp->max_num_queues(), *this, *per_thread_states, *_task_queues);3283stats = rp->process_discovered_references(task, pt);32843285_gc_tracer_stw->report_gc_reference_stats(stats);32863287// We have completed copying any necessary live referent objects.3288assert(pss->queue_is_empty(), "both queue and overflow should be empty");32893290make_pending_list_reachable();32913292assert(!rp->discovery_enabled(), "Postcondition");3293rp->verify_no_references_recorded();32943295double ref_proc_time = os::elapsedTime() - ref_proc_start;3296phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);3297}32983299void G1CollectedHeap::make_pending_list_reachable() {3300if (collector_state()->in_concurrent_start_gc()) {3301oop pll_head = Universe::reference_pending_list();3302if (pll_head != NULL) {3303// Any valid worker id is fine here as we are in the VM thread and single-threaded.3304_cm->mark_in_next_bitmap(0 /* worker_id */, pll_head);3305}3306}3307}33083309static bool do_humongous_object_logging() {3310return log_is_enabled(Debug, gc, humongous);3311}33123313bool G1CollectedHeap::should_do_eager_reclaim() const {3314// As eager reclaim logging also gives information about humongous objects in3315// the heap in general, always do the eager reclaim pass even without known3316// candidates.3317return (G1EagerReclaimHumongousObjects &&3318(has_humongous_reclaim_candidates() || do_humongous_object_logging()));3319}33203321class G1PrepareEvacuationTask : public AbstractGangTask {3322class G1PrepareRegionsClosure : public HeapRegionClosure {3323G1CollectedHeap* _g1h;3324G1PrepareEvacuationTask* _parent_task;3325uint _worker_humongous_total;3326uint _worker_humongous_candidates;33273328bool humongous_region_is_candidate(HeapRegion* region) const {3329assert(region->is_starts_humongous(), "Must start a humongous object");33303331oop obj = cast_to_oop(region->bottom());33323333// Dead objects cannot be eager reclaim candidates. Due to class3334// unloading it is unsafe to query their classes so we return early.3335if (_g1h->is_obj_dead(obj, region)) {3336return false;3337}33383339// If we do not have a complete remembered set for the region, then we can3340// not be sure that we have all references to it.3341if (!region->rem_set()->is_complete()) {3342return false;3343}3344// Candidate selection must satisfy the following constraints3345// while concurrent marking is in progress:3346//3347// * In order to maintain SATB invariants, an object must not be3348// reclaimed if it was allocated before the start of marking and3349// has not had its references scanned. Such an object must have3350// its references (including type metadata) scanned to ensure no3351// live objects are missed by the marking process. Objects3352// allocated after the start of concurrent marking don't need to3353// be scanned.3354//3355// * An object must not be reclaimed if it is on the concurrent3356// mark stack. Objects allocated after the start of concurrent3357// marking are never pushed on the mark stack.3358//3359// Nominating only objects allocated after the start of concurrent3360// marking is sufficient to meet both constraints. This may miss3361// some objects that satisfy the constraints, but the marking data3362// structures don't support efficiently performing the needed3363// additional tests or scrubbing of the mark stack.3364//3365// However, we presently only nominate is_typeArray() objects.3366// A humongous object containing references induces remembered3367// set entries on other regions. In order to reclaim such an3368// object, those remembered sets would need to be cleaned up.3369//3370// We also treat is_typeArray() objects specially, allowing them3371// to be reclaimed even if allocated before the start of3372// concurrent mark. For this we rely on mark stack insertion to3373// exclude is_typeArray() objects, preventing reclaiming an object3374// that is in the mark stack. We also rely on the metadata for3375// such objects to be built-in and so ensured to be kept live.3376// Frequent allocation and drop of large binary blobs is an3377// important use case for eager reclaim, and this special handling3378// may reduce needed headroom.33793380return obj->is_typeArray() &&3381_g1h->is_potential_eager_reclaim_candidate(region);3382}33833384public:3385G1PrepareRegionsClosure(G1CollectedHeap* g1h, G1PrepareEvacuationTask* parent_task) :3386_g1h(g1h),3387_parent_task(parent_task),3388_worker_humongous_total(0),3389_worker_humongous_candidates(0) { }33903391~G1PrepareRegionsClosure() {3392_parent_task->add_humongous_candidates(_worker_humongous_candidates);3393_parent_task->add_humongous_total(_worker_humongous_total);3394}33953396virtual bool do_heap_region(HeapRegion* hr) {3397// First prepare the region for scanning3398_g1h->rem_set()->prepare_region_for_scan(hr);33993400// Now check if region is a humongous candidate3401if (!hr->is_starts_humongous()) {3402_g1h->register_region_with_region_attr(hr);3403return false;3404}34053406uint index = hr->hrm_index();3407if (humongous_region_is_candidate(hr)) {3408_g1h->set_humongous_reclaim_candidate(index, true);3409_g1h->register_humongous_region_with_region_attr(index);3410_worker_humongous_candidates++;3411// We will later handle the remembered sets of these regions.3412} else {3413_g1h->set_humongous_reclaim_candidate(index, false);3414_g1h->register_region_with_region_attr(hr);3415}3416log_debug(gc, humongous)("Humongous region %u (object size " SIZE_FORMAT " @ " PTR_FORMAT ") remset " SIZE_FORMAT " code roots " SIZE_FORMAT " marked %d reclaim candidate %d type array %d",3417index,3418(size_t)cast_to_oop(hr->bottom())->size() * HeapWordSize,3419p2i(hr->bottom()),3420hr->rem_set()->occupied(),3421hr->rem_set()->strong_code_roots_list_length(),3422_g1h->concurrent_mark()->next_mark_bitmap()->is_marked(hr->bottom()),3423_g1h->is_humongous_reclaim_candidate(index),3424cast_to_oop(hr->bottom())->is_typeArray()3425);3426_worker_humongous_total++;34273428return false;3429}3430};34313432G1CollectedHeap* _g1h;3433HeapRegionClaimer _claimer;3434volatile uint _humongous_total;3435volatile uint _humongous_candidates;3436public:3437G1PrepareEvacuationTask(G1CollectedHeap* g1h) :3438AbstractGangTask("Prepare Evacuation"),3439_g1h(g1h),3440_claimer(_g1h->workers()->active_workers()),3441_humongous_total(0),3442_humongous_candidates(0) { }34433444void work(uint worker_id) {3445G1PrepareRegionsClosure cl(_g1h, this);3446_g1h->heap_region_par_iterate_from_worker_offset(&cl, &_claimer, worker_id);3447}34483449void add_humongous_candidates(uint candidates) {3450Atomic::add(&_humongous_candidates, candidates);3451}34523453void add_humongous_total(uint total) {3454Atomic::add(&_humongous_total, total);3455}34563457uint humongous_candidates() {3458return _humongous_candidates;3459}34603461uint humongous_total() {3462return _humongous_total;3463}3464};34653466void G1CollectedHeap::pre_evacuate_collection_set(G1EvacuationInfo& evacuation_info, G1ParScanThreadStateSet* per_thread_states) {3467_bytes_used_during_gc = 0;34683469_expand_heap_after_alloc_failure = true;3470Atomic::store(&_num_regions_failed_evacuation, 0u);34713472memset((void*)_regions_failed_evacuation, false, sizeof(bool) * max_regions());34733474// Disable the hot card cache.3475_hot_card_cache->reset_hot_cache_claimed_index();3476_hot_card_cache->set_use_cache(false);34773478// Initialize the GC alloc regions.3479_allocator->init_gc_alloc_regions(evacuation_info);34803481{3482Ticks start = Ticks::now();3483rem_set()->prepare_for_scan_heap_roots();3484phase_times()->record_prepare_heap_roots_time_ms((Ticks::now() - start).seconds() * 1000.0);3485}34863487{3488G1PrepareEvacuationTask g1_prep_task(this);3489Tickspan task_time = run_task_timed(&g1_prep_task);34903491phase_times()->record_register_regions(task_time.seconds() * 1000.0);3492_num_humongous_objects = g1_prep_task.humongous_total();3493_num_humongous_reclaim_candidates = g1_prep_task.humongous_candidates();3494}34953496assert(_verifier->check_region_attr_table(), "Inconsistency in the region attributes table.");3497_preserved_marks_set.assert_empty();34983499#if COMPILER2_OR_JVMCI3500DerivedPointerTable::clear();3501#endif35023503// Concurrent start needs claim bits to keep track of the marked-through CLDs.3504if (collector_state()->in_concurrent_start_gc()) {3505concurrent_mark()->pre_concurrent_start(gc_cause());35063507double start_clear_claimed_marks = os::elapsedTime();35083509ClassLoaderDataGraph::clear_claimed_marks();35103511double recorded_clear_claimed_marks_time_ms = (os::elapsedTime() - start_clear_claimed_marks) * 1000.0;3512phase_times()->record_clear_claimed_marks_time_ms(recorded_clear_claimed_marks_time_ms);3513}35143515// Should G1EvacuationFailureALot be in effect for this GC?3516NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)3517}35183519class G1EvacuateRegionsBaseTask : public AbstractGangTask {3520protected:3521G1CollectedHeap* _g1h;3522G1ParScanThreadStateSet* _per_thread_states;3523G1ScannerTasksQueueSet* _task_queues;3524TaskTerminator _terminator;3525uint _num_workers;35263527void evacuate_live_objects(G1ParScanThreadState* pss,3528uint worker_id,3529G1GCPhaseTimes::GCParPhases objcopy_phase,3530G1GCPhaseTimes::GCParPhases termination_phase) {3531G1GCPhaseTimes* p = _g1h->phase_times();35323533Ticks start = Ticks::now();3534G1ParEvacuateFollowersClosure cl(_g1h, pss, _task_queues, &_terminator, objcopy_phase);3535cl.do_void();35363537assert(pss->queue_is_empty(), "should be empty");35383539Tickspan evac_time = (Ticks::now() - start);3540p->record_or_add_time_secs(objcopy_phase, worker_id, evac_time.seconds() - cl.term_time());35413542if (termination_phase == G1GCPhaseTimes::Termination) {3543p->record_time_secs(termination_phase, worker_id, cl.term_time());3544p->record_thread_work_item(termination_phase, worker_id, cl.term_attempts());3545} else {3546p->record_or_add_time_secs(termination_phase, worker_id, cl.term_time());3547p->record_or_add_thread_work_item(termination_phase, worker_id, cl.term_attempts());3548}3549assert(pss->trim_ticks().value() == 0,3550"Unexpected partial trimming during evacuation value " JLONG_FORMAT,3551pss->trim_ticks().value());3552}35533554virtual void start_work(uint worker_id) { }35553556virtual void end_work(uint worker_id) { }35573558virtual void scan_roots(G1ParScanThreadState* pss, uint worker_id) = 0;35593560virtual void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) = 0;35613562public:3563G1EvacuateRegionsBaseTask(const char* name,3564G1ParScanThreadStateSet* per_thread_states,3565G1ScannerTasksQueueSet* task_queues,3566uint num_workers) :3567AbstractGangTask(name),3568_g1h(G1CollectedHeap::heap()),3569_per_thread_states(per_thread_states),3570_task_queues(task_queues),3571_terminator(num_workers, _task_queues),3572_num_workers(num_workers)3573{ }35743575void work(uint worker_id) {3576start_work(worker_id);35773578{3579ResourceMark rm;35803581G1ParScanThreadState* pss = _per_thread_states->state_for_worker(worker_id);3582pss->set_ref_discoverer(_g1h->ref_processor_stw());35833584scan_roots(pss, worker_id);3585evacuate_live_objects(pss, worker_id);3586}35873588end_work(worker_id);3589}3590};35913592class G1EvacuateRegionsTask : public G1EvacuateRegionsBaseTask {3593G1RootProcessor* _root_processor;3594bool _has_optional_evacuation_work;35953596void scan_roots(G1ParScanThreadState* pss, uint worker_id) {3597_root_processor->evacuate_roots(pss, worker_id);3598_g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::ObjCopy, _has_optional_evacuation_work);3599_g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::CodeRoots, G1GCPhaseTimes::ObjCopy);3600}36013602void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {3603G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::ObjCopy, G1GCPhaseTimes::Termination);3604}36053606void start_work(uint worker_id) {3607_g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, Ticks::now().seconds());3608}36093610void end_work(uint worker_id) {3611_g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, Ticks::now().seconds());3612}36133614public:3615G1EvacuateRegionsTask(G1CollectedHeap* g1h,3616G1ParScanThreadStateSet* per_thread_states,3617G1ScannerTasksQueueSet* task_queues,3618G1RootProcessor* root_processor,3619uint num_workers,3620bool has_optional_evacuation_work) :3621G1EvacuateRegionsBaseTask("G1 Evacuate Regions", per_thread_states, task_queues, num_workers),3622_root_processor(root_processor),3623_has_optional_evacuation_work(has_optional_evacuation_work)3624{ }3625};36263627void G1CollectedHeap::evacuate_initial_collection_set(G1ParScanThreadStateSet* per_thread_states,3628bool has_optional_evacuation_work) {3629G1GCPhaseTimes* p = phase_times();36303631{3632Ticks start = Ticks::now();3633rem_set()->merge_heap_roots(true /* initial_evacuation */);3634p->record_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);3635}36363637Tickspan task_time;3638const uint num_workers = workers()->active_workers();36393640Ticks start_processing = Ticks::now();3641{3642G1RootProcessor root_processor(this, num_workers);3643G1EvacuateRegionsTask g1_par_task(this,3644per_thread_states,3645_task_queues,3646&root_processor,3647num_workers,3648has_optional_evacuation_work);3649task_time = run_task_timed(&g1_par_task);3650// Closing the inner scope will execute the destructor for the G1RootProcessor object.3651// To extract its code root fixup time we measure total time of this scope and3652// subtract from the time the WorkGang task took.3653}3654Tickspan total_processing = Ticks::now() - start_processing;36553656p->record_initial_evac_time(task_time.seconds() * 1000.0);3657p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);36583659rem_set()->complete_evac_phase(has_optional_evacuation_work);3660}36613662class G1EvacuateOptionalRegionsTask : public G1EvacuateRegionsBaseTask {36633664void scan_roots(G1ParScanThreadState* pss, uint worker_id) {3665_g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptObjCopy, true /* remember_already_scanned_cards */);3666_g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptCodeRoots, G1GCPhaseTimes::OptObjCopy);3667}36683669void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {3670G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::OptObjCopy, G1GCPhaseTimes::OptTermination);3671}36723673public:3674G1EvacuateOptionalRegionsTask(G1ParScanThreadStateSet* per_thread_states,3675G1ScannerTasksQueueSet* queues,3676uint num_workers) :3677G1EvacuateRegionsBaseTask("G1 Evacuate Optional Regions", per_thread_states, queues, num_workers) {3678}3679};36803681void G1CollectedHeap::evacuate_next_optional_regions(G1ParScanThreadStateSet* per_thread_states) {3682class G1MarkScope : public MarkScope { };36833684Tickspan task_time;36853686Ticks start_processing = Ticks::now();3687{3688G1MarkScope code_mark_scope;3689G1EvacuateOptionalRegionsTask task(per_thread_states, _task_queues, workers()->active_workers());3690task_time = run_task_timed(&task);3691// See comment in evacuate_collection_set() for the reason of the scope.3692}3693Tickspan total_processing = Ticks::now() - start_processing;36943695G1GCPhaseTimes* p = phase_times();3696p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);3697}36983699void G1CollectedHeap::evacuate_optional_collection_set(G1ParScanThreadStateSet* per_thread_states) {3700const double gc_start_time_ms = phase_times()->cur_collection_start_sec() * 1000.0;37013702while (!evacuation_failed() && _collection_set.optional_region_length() > 0) {37033704double time_used_ms = os::elapsedTime() * 1000.0 - gc_start_time_ms;3705double time_left_ms = MaxGCPauseMillis - time_used_ms;37063707if (time_left_ms < 0 ||3708!_collection_set.finalize_optional_for_evacuation(time_left_ms * policy()->optional_evacuation_fraction())) {3709log_trace(gc, ergo, cset)("Skipping evacuation of %u optional regions, no more regions can be evacuated in %.3fms",3710_collection_set.optional_region_length(), time_left_ms);3711break;3712}37133714{3715Ticks start = Ticks::now();3716rem_set()->merge_heap_roots(false /* initial_evacuation */);3717phase_times()->record_or_add_optional_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);3718}37193720{3721Ticks start = Ticks::now();3722evacuate_next_optional_regions(per_thread_states);3723phase_times()->record_or_add_optional_evac_time((Ticks::now() - start).seconds() * 1000.0);3724}37253726rem_set()->complete_evac_phase(true /* has_more_than_one_evacuation_phase */);3727}37283729_collection_set.abandon_optional_collection_set(per_thread_states);3730}37313732void G1CollectedHeap::post_evacuate_collection_set(G1EvacuationInfo& evacuation_info,3733G1RedirtyCardsQueueSet* rdcqs,3734G1ParScanThreadStateSet* per_thread_states) {3735G1GCPhaseTimes* p = phase_times();37363737// Process any discovered reference objects - we have3738// to do this _before_ we retire the GC alloc regions3739// as we may have to copy some 'reachable' referent3740// objects (and their reachable sub-graphs) that were3741// not copied during the pause.3742process_discovered_references(per_thread_states);37433744G1STWIsAliveClosure is_alive(this);3745G1KeepAliveClosure keep_alive(this);37463747WeakProcessor::weak_oops_do(workers(), &is_alive, &keep_alive, p->weak_phase_times());37483749_allocator->release_gc_alloc_regions(evacuation_info);37503751post_evacuate_cleanup_1(per_thread_states, rdcqs);37523753post_evacuate_cleanup_2(&_preserved_marks_set, rdcqs, &evacuation_info, per_thread_states->surviving_young_words());37543755assert_used_and_recalculate_used_equal(this);37563757rebuild_free_region_list();37583759record_obj_copy_mem_stats();37603761evacuation_info.set_collectionset_used_before(collection_set()->bytes_used_before());3762evacuation_info.set_bytes_used(_bytes_used_during_gc);37633764policy()->print_age_table();3765}37663767void G1CollectedHeap::record_obj_copy_mem_stats() {3768policy()->old_gen_alloc_tracker()->3769add_allocated_bytes_since_last_gc(_old_evac_stats.allocated() * HeapWordSize);37703771_gc_tracer_stw->report_evacuation_statistics(create_g1_evac_summary(&_survivor_evac_stats),3772create_g1_evac_summary(&_old_evac_stats));3773}37743775void G1CollectedHeap::free_region(HeapRegion* hr, FreeRegionList* free_list) {3776assert(!hr->is_free(), "the region should not be free");3777assert(!hr->is_empty(), "the region should not be empty");3778assert(_hrm.is_available(hr->hrm_index()), "region should be committed");37793780if (G1VerifyBitmaps) {3781MemRegion mr(hr->bottom(), hr->end());3782concurrent_mark()->clear_range_in_prev_bitmap(mr);3783}37843785// Clear the card counts for this region.3786// Note: we only need to do this if the region is not young3787// (since we don't refine cards in young regions).3788if (!hr->is_young()) {3789_hot_card_cache->reset_card_counts(hr);3790}37913792// Reset region metadata to allow reuse.3793hr->hr_clear(true /* clear_space */);3794_policy->remset_tracker()->update_at_free(hr);37953796if (free_list != NULL) {3797free_list->add_ordered(hr);3798}3799}38003801void G1CollectedHeap::free_humongous_region(HeapRegion* hr,3802FreeRegionList* free_list) {3803assert(hr->is_humongous(), "this is only for humongous regions");3804hr->clear_humongous();3805free_region(hr, free_list);3806}38073808void G1CollectedHeap::remove_from_old_gen_sets(const uint old_regions_removed,3809const uint archive_regions_removed,3810const uint humongous_regions_removed) {3811if (old_regions_removed > 0 || archive_regions_removed > 0 || humongous_regions_removed > 0) {3812MutexLocker x(OldSets_lock, Mutex::_no_safepoint_check_flag);3813_old_set.bulk_remove(old_regions_removed);3814_archive_set.bulk_remove(archive_regions_removed);3815_humongous_set.bulk_remove(humongous_regions_removed);3816}38173818}38193820void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {3821assert(list != NULL, "list can't be null");3822if (!list->is_empty()) {3823MutexLocker x(FreeList_lock, Mutex::_no_safepoint_check_flag);3824_hrm.insert_list_into_free_list(list);3825}3826}38273828void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {3829decrease_used(bytes);3830}38313832void G1CollectedHeap::post_evacuate_cleanup_1(G1ParScanThreadStateSet* per_thread_states,3833G1RedirtyCardsQueueSet* rdcqs) {3834Ticks start = Ticks::now();3835{3836G1PostEvacuateCollectionSetCleanupTask1 cl(per_thread_states, rdcqs);3837run_batch_task(&cl);3838}3839phase_times()->record_post_evacuate_cleanup_task_1_time((Ticks::now() - start).seconds() * 1000.0);3840}38413842void G1CollectedHeap::post_evacuate_cleanup_2(PreservedMarksSet* preserved_marks,3843G1RedirtyCardsQueueSet* rdcqs,3844G1EvacuationInfo* evacuation_info,3845const size_t* surviving_young_words) {3846Ticks start = Ticks::now();3847{3848G1PostEvacuateCollectionSetCleanupTask2 cl(preserved_marks, rdcqs, evacuation_info, surviving_young_words);3849run_batch_task(&cl);3850}3851phase_times()->record_post_evacuate_cleanup_task_2_time((Ticks::now() - start).seconds() * 1000.0);3852}38533854void G1CollectedHeap::clear_eden() {3855_eden.clear();3856}38573858void G1CollectedHeap::clear_collection_set() {3859collection_set()->clear();3860}38613862void G1CollectedHeap::rebuild_free_region_list() {3863Ticks start = Ticks::now();3864_hrm.rebuild_free_list(workers());3865phase_times()->record_total_rebuild_freelist_time_ms((Ticks::now() - start).seconds() * 1000.0);3866}38673868class G1AbandonCollectionSetClosure : public HeapRegionClosure {3869public:3870virtual bool do_heap_region(HeapRegion* r) {3871assert(r->in_collection_set(), "Region %u must have been in collection set", r->hrm_index());3872G1CollectedHeap::heap()->clear_region_attr(r);3873r->clear_young_index_in_cset();3874return false;3875}3876};38773878void G1CollectedHeap::abandon_collection_set(G1CollectionSet* collection_set) {3879G1AbandonCollectionSetClosure cl;3880collection_set_iterate_all(&cl);38813882collection_set->clear();3883collection_set->stop_incremental_building();3884}38853886bool G1CollectedHeap::is_old_gc_alloc_region(HeapRegion* hr) {3887return _allocator->is_retained_old_region(hr);3888}38893890void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {3891_eden.add(hr);3892_policy->set_region_eden(hr);3893}38943895#ifdef ASSERT38963897class NoYoungRegionsClosure: public HeapRegionClosure {3898private:3899bool _success;3900public:3901NoYoungRegionsClosure() : _success(true) { }3902bool do_heap_region(HeapRegion* r) {3903if (r->is_young()) {3904log_error(gc, verify)("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young",3905p2i(r->bottom()), p2i(r->end()));3906_success = false;3907}3908return false;3909}3910bool success() { return _success; }3911};39123913bool G1CollectedHeap::check_young_list_empty() {3914bool ret = (young_regions_count() == 0);39153916NoYoungRegionsClosure closure;3917heap_region_iterate(&closure);3918ret = ret && closure.success();39193920return ret;3921}39223923#endif // ASSERT39243925// Remove the given HeapRegion from the appropriate region set.3926void G1CollectedHeap::prepare_region_for_full_compaction(HeapRegion* hr) {3927if (hr->is_archive()) {3928_archive_set.remove(hr);3929} else if (hr->is_humongous()) {3930_humongous_set.remove(hr);3931} else if (hr->is_old()) {3932_old_set.remove(hr);3933} else if (hr->is_young()) {3934// Note that emptying the eden and survivor lists is postponed and instead3935// done as the first step when rebuilding the regions sets again. The reason3936// for this is that during a full GC string deduplication needs to know if3937// a collected region was young or old when the full GC was initiated.3938hr->uninstall_surv_rate_group();3939} else {3940// We ignore free regions, we'll empty the free list afterwards.3941assert(hr->is_free(), "it cannot be another type");3942}3943}39443945void G1CollectedHeap::increase_used(size_t bytes) {3946_summary_bytes_used += bytes;3947}39483949void G1CollectedHeap::decrease_used(size_t bytes) {3950assert(_summary_bytes_used >= bytes,3951"invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT,3952_summary_bytes_used, bytes);3953_summary_bytes_used -= bytes;3954}39553956void G1CollectedHeap::set_used(size_t bytes) {3957_summary_bytes_used = bytes;3958}39593960class RebuildRegionSetsClosure : public HeapRegionClosure {3961private:3962bool _free_list_only;39633964HeapRegionSet* _old_set;3965HeapRegionSet* _archive_set;3966HeapRegionSet* _humongous_set;39673968HeapRegionManager* _hrm;39693970size_t _total_used;39713972public:3973RebuildRegionSetsClosure(bool free_list_only,3974HeapRegionSet* old_set,3975HeapRegionSet* archive_set,3976HeapRegionSet* humongous_set,3977HeapRegionManager* hrm) :3978_free_list_only(free_list_only), _old_set(old_set), _archive_set(archive_set),3979_humongous_set(humongous_set), _hrm(hrm), _total_used(0) {3980assert(_hrm->num_free_regions() == 0, "pre-condition");3981if (!free_list_only) {3982assert(_old_set->is_empty(), "pre-condition");3983assert(_archive_set->is_empty(), "pre-condition");3984assert(_humongous_set->is_empty(), "pre-condition");3985}3986}39873988bool do_heap_region(HeapRegion* r) {3989if (r->is_empty()) {3990assert(r->rem_set()->is_empty(), "Empty regions should have empty remembered sets.");3991// Add free regions to the free list3992r->set_free();3993_hrm->insert_into_free_list(r);3994} else if (!_free_list_only) {3995assert(r->rem_set()->is_empty(), "At this point remembered sets must have been cleared.");39963997if (r->is_humongous()) {3998_humongous_set->add(r);3999} else if (r->is_archive()) {4000_archive_set->add(r);4001} else {4002assert(r->is_young() || r->is_free() || r->is_old(), "invariant");4003// We now move all (non-humongous, non-old, non-archive) regions to old gen,4004// and register them as such.4005r->move_to_old();4006_old_set->add(r);4007}4008_total_used += r->used();4009}40104011return false;4012}40134014size_t total_used() {4015return _total_used;4016}4017};40184019void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {4020assert_at_safepoint_on_vm_thread();40214022if (!free_list_only) {4023_eden.clear();4024_survivor.clear();4025}40264027RebuildRegionSetsClosure cl(free_list_only,4028&_old_set, &_archive_set, &_humongous_set,4029&_hrm);4030heap_region_iterate(&cl);40314032if (!free_list_only) {4033set_used(cl.total_used());4034if (_archive_allocator != NULL) {4035_archive_allocator->clear_used();4036}4037}4038assert_used_and_recalculate_used_equal(this);4039}40404041// Methods for the mutator alloc region40424043HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,4044bool force,4045uint node_index) {4046assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);4047bool should_allocate = policy()->should_allocate_mutator_region();4048if (force || should_allocate) {4049HeapRegion* new_alloc_region = new_region(word_size,4050HeapRegionType::Eden,4051false /* do_expand */,4052node_index);4053if (new_alloc_region != NULL) {4054set_region_short_lived_locked(new_alloc_region);4055_hr_printer.alloc(new_alloc_region, !should_allocate);4056_verifier->check_bitmaps("Mutator Region Allocation", new_alloc_region);4057_policy->remset_tracker()->update_at_allocate(new_alloc_region);4058return new_alloc_region;4059}4060}4061return NULL;4062}40634064void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,4065size_t allocated_bytes) {4066assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);4067assert(alloc_region->is_eden(), "all mutator alloc regions should be eden");40684069collection_set()->add_eden_region(alloc_region);4070increase_used(allocated_bytes);4071_eden.add_used_bytes(allocated_bytes);4072_hr_printer.retire(alloc_region);40734074// We update the eden sizes here, when the region is retired,4075// instead of when it's allocated, since this is the point that its4076// used space has been recorded in _summary_bytes_used.4077g1mm()->update_eden_size();4078}40794080// Methods for the GC alloc regions40814082bool G1CollectedHeap::has_more_regions(G1HeapRegionAttr dest) {4083if (dest.is_old()) {4084return true;4085} else {4086return survivor_regions_count() < policy()->max_survivor_regions();4087}4088}40894090HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index) {4091assert(FreeList_lock->owned_by_self(), "pre-condition");40924093if (!has_more_regions(dest)) {4094return NULL;4095}40964097HeapRegionType type;4098if (dest.is_young()) {4099type = HeapRegionType::Survivor;4100} else {4101type = HeapRegionType::Old;4102}41034104HeapRegion* new_alloc_region = new_region(word_size,4105type,4106true /* do_expand */,4107node_index);41084109if (new_alloc_region != NULL) {4110if (type.is_survivor()) {4111new_alloc_region->set_survivor();4112_survivor.add(new_alloc_region);4113_verifier->check_bitmaps("Survivor Region Allocation", new_alloc_region);4114} else {4115new_alloc_region->set_old();4116_verifier->check_bitmaps("Old Region Allocation", new_alloc_region);4117}4118_policy->remset_tracker()->update_at_allocate(new_alloc_region);4119register_region_with_region_attr(new_alloc_region);4120_hr_printer.alloc(new_alloc_region);4121return new_alloc_region;4122}4123return NULL;4124}41254126void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,4127size_t allocated_bytes,4128G1HeapRegionAttr dest) {4129_bytes_used_during_gc += allocated_bytes;4130if (dest.is_old()) {4131old_set_add(alloc_region);4132} else {4133assert(dest.is_young(), "Retiring alloc region should be young (%d)", dest.type());4134_survivor.add_used_bytes(allocated_bytes);4135}41364137bool const during_im = collector_state()->in_concurrent_start_gc();4138if (during_im && allocated_bytes > 0) {4139_cm->root_regions()->add(alloc_region->next_top_at_mark_start(), alloc_region->top());4140}4141_hr_printer.retire(alloc_region);4142}41434144HeapRegion* G1CollectedHeap::alloc_highest_free_region() {4145bool expanded = false;4146uint index = _hrm.find_highest_free(&expanded);41474148if (index != G1_NO_HRM_INDEX) {4149if (expanded) {4150log_debug(gc, ergo, heap)("Attempt heap expansion (requested address range outside heap bounds). region size: " SIZE_FORMAT "B",4151HeapRegion::GrainWords * HeapWordSize);4152}4153return _hrm.allocate_free_regions_starting_at(index, 1);4154}4155return NULL;4156}41574158// Optimized nmethod scanning41594160class RegisterNMethodOopClosure: public OopClosure {4161G1CollectedHeap* _g1h;4162nmethod* _nm;41634164template <class T> void do_oop_work(T* p) {4165T heap_oop = RawAccess<>::oop_load(p);4166if (!CompressedOops::is_null(heap_oop)) {4167oop obj = CompressedOops::decode_not_null(heap_oop);4168HeapRegion* hr = _g1h->heap_region_containing(obj);4169assert(!hr->is_continues_humongous(),4170"trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT4171" starting at " HR_FORMAT,4172p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));41734174// HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries.4175hr->add_strong_code_root_locked(_nm);4176}4177}41784179public:4180RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :4181_g1h(g1h), _nm(nm) {}41824183void do_oop(oop* p) { do_oop_work(p); }4184void do_oop(narrowOop* p) { do_oop_work(p); }4185};41864187class UnregisterNMethodOopClosure: public OopClosure {4188G1CollectedHeap* _g1h;4189nmethod* _nm;41904191template <class T> void do_oop_work(T* p) {4192T heap_oop = RawAccess<>::oop_load(p);4193if (!CompressedOops::is_null(heap_oop)) {4194oop obj = CompressedOops::decode_not_null(heap_oop);4195HeapRegion* hr = _g1h->heap_region_containing(obj);4196assert(!hr->is_continues_humongous(),4197"trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT4198" starting at " HR_FORMAT,4199p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));42004201hr->remove_strong_code_root(_nm);4202}4203}42044205public:4206UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :4207_g1h(g1h), _nm(nm) {}42084209void do_oop(oop* p) { do_oop_work(p); }4210void do_oop(narrowOop* p) { do_oop_work(p); }4211};42124213void G1CollectedHeap::register_nmethod(nmethod* nm) {4214guarantee(nm != NULL, "sanity");4215RegisterNMethodOopClosure reg_cl(this, nm);4216nm->oops_do(®_cl);4217}42184219void G1CollectedHeap::unregister_nmethod(nmethod* nm) {4220guarantee(nm != NULL, "sanity");4221UnregisterNMethodOopClosure reg_cl(this, nm);4222nm->oops_do(®_cl, true);4223}42244225void G1CollectedHeap::update_used_after_gc() {4226if (evacuation_failed()) {4227// Reset the G1EvacuationFailureALot counters and flags4228NOT_PRODUCT(reset_evacuation_should_fail();)42294230set_used(recalculate_used());42314232if (_archive_allocator != NULL) {4233_archive_allocator->clear_used();4234}4235for (uint i = 0; i < ParallelGCThreads; i++) {4236if (_evacuation_failed_info_array[i].has_failed()) {4237_gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);4238}4239}4240} else {4241// The "used" of the the collection set have already been subtracted4242// when they were freed. Add in the bytes used.4243increase_used(_bytes_used_during_gc);4244}4245}42464247void G1CollectedHeap::reset_hot_card_cache() {4248_hot_card_cache->reset_hot_cache();4249_hot_card_cache->set_use_cache(true);4250}42514252void G1CollectedHeap::purge_code_root_memory() {4253G1CodeRootSet::purge();4254}42554256class RebuildStrongCodeRootClosure: public CodeBlobClosure {4257G1CollectedHeap* _g1h;42584259public:4260RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :4261_g1h(g1h) {}42624263void do_code_blob(CodeBlob* cb) {4264nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;4265if (nm == NULL) {4266return;4267}42684269_g1h->register_nmethod(nm);4270}4271};42724273void G1CollectedHeap::rebuild_strong_code_roots() {4274RebuildStrongCodeRootClosure blob_cl(this);4275CodeCache::blobs_do(&blob_cl);4276}42774278void G1CollectedHeap::initialize_serviceability() {4279_g1mm->initialize_serviceability();4280}42814282MemoryUsage G1CollectedHeap::memory_usage() {4283return _g1mm->memory_usage();4284}42854286GrowableArray<GCMemoryManager*> G1CollectedHeap::memory_managers() {4287return _g1mm->memory_managers();4288}42894290GrowableArray<MemoryPool*> G1CollectedHeap::memory_pools() {4291return _g1mm->memory_pools();4292}429342944295