Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
48790 views
/*1* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#if !defined(__clang_major__) && defined(__GNUC__)25#define ATTRIBUTE_PRINTF(x,y) // FIXME, formats are a mess.26#endif2728#include "precompiled.hpp"29#include "classfile/metadataOnStackMark.hpp"30#include "code/codeCache.hpp"31#include "code/icBuffer.hpp"32#include "gc_implementation/g1/bufferingOopClosure.hpp"33#include "gc_implementation/g1/concurrentG1Refine.hpp"34#include "gc_implementation/g1/concurrentG1RefineThread.hpp"35#include "gc_implementation/g1/concurrentMarkThread.inline.hpp"36#include "gc_implementation/g1/g1AllocRegion.inline.hpp"37#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"38#include "gc_implementation/g1/g1CollectorPolicy.hpp"39#include "gc_implementation/g1/g1ErgoVerbose.hpp"40#include "gc_implementation/g1/g1EvacFailure.hpp"41#include "gc_implementation/g1/g1GCPhaseTimes.hpp"42#include "gc_implementation/g1/g1Log.hpp"43#include "gc_implementation/g1/g1MarkSweep.hpp"44#include "gc_implementation/g1/g1OopClosures.inline.hpp"45#include "gc_implementation/g1/g1ParScanThreadState.inline.hpp"46#include "gc_implementation/g1/g1RegionToSpaceMapper.hpp"47#include "gc_implementation/g1/g1RemSet.inline.hpp"48#include "gc_implementation/g1/g1RootProcessor.hpp"49#include "gc_implementation/g1/g1StringDedup.hpp"50#include "gc_implementation/g1/g1YCTypes.hpp"51#include "gc_implementation/g1/heapRegion.inline.hpp"52#include "gc_implementation/g1/heapRegionRemSet.hpp"53#include "gc_implementation/g1/heapRegionSet.inline.hpp"54#include "gc_implementation/g1/vm_operations_g1.hpp"55#include "gc_implementation/shared/gcHeapSummary.hpp"56#include "gc_implementation/shared/gcTimer.hpp"57#include "gc_implementation/shared/gcTrace.hpp"58#include "gc_implementation/shared/gcTraceTime.hpp"59#include "gc_implementation/shared/isGCActiveMark.hpp"60#include "memory/allocation.hpp"61#include "memory/gcLocker.inline.hpp"62#include "memory/generationSpec.hpp"63#include "memory/iterator.hpp"64#include "memory/referenceProcessor.hpp"65#include "oops/oop.inline.hpp"66#include "oops/oop.pcgc.inline.hpp"67#include "runtime/orderAccess.inline.hpp"68#include "runtime/vmThread.hpp"6970size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;7172// turn it on so that the contents of the young list (scan-only /73// to-be-collected) are printed at "strategic" points before / during74// / after the collection --- this is useful for debugging75#define YOUNG_LIST_VERBOSE 076// CURRENT STATUS77// This file is under construction. Search for "FIXME".7879// INVARIANTS/NOTES80//81// All allocation activity covered by the G1CollectedHeap interface is82// serialized by acquiring the HeapLock. This happens in mem_allocate83// and allocate_new_tlab, which are the "entry" points to the84// allocation code from the rest of the JVM. (Note that this does not85// apply to TLAB allocation, which is not part of this interface: it86// is done by clients of this interface.)8788// Local to this file.8990class RefineCardTableEntryClosure: public CardTableEntryClosure {91bool _concurrent;92public:93RefineCardTableEntryClosure() : _concurrent(true) { }9495bool do_card_ptr(jbyte* card_ptr, uint worker_i) {96bool oops_into_cset = G1CollectedHeap::heap()->g1_rem_set()->refine_card(card_ptr, worker_i, false);97// This path is executed by the concurrent refine or mutator threads,98// concurrently, and so we do not care if card_ptr contains references99// that point into the collection set.100assert(!oops_into_cset, "should be");101102if (_concurrent && SuspendibleThreadSet::should_yield()) {103// Caller will actually yield.104return false;105}106// Otherwise, we finished successfully; return true.107return true;108}109110void set_concurrent(bool b) { _concurrent = b; }111};112113114class ClearLoggedCardTableEntryClosure: public CardTableEntryClosure {115size_t _num_processed;116CardTableModRefBS* _ctbs;117int _histo[256];118119public:120ClearLoggedCardTableEntryClosure() :121_num_processed(0), _ctbs(G1CollectedHeap::heap()->g1_barrier_set())122{123for (int i = 0; i < 256; i++) _histo[i] = 0;124}125126bool do_card_ptr(jbyte* card_ptr, uint worker_i) {127unsigned char* ujb = (unsigned char*)card_ptr;128int ind = (int)(*ujb);129_histo[ind]++;130131*card_ptr = (jbyte)CardTableModRefBS::clean_card_val();132_num_processed++;133134return true;135}136137size_t num_processed() { return _num_processed; }138139void print_histo() {140gclog_or_tty->print_cr("Card table value histogram:");141for (int i = 0; i < 256; i++) {142if (_histo[i] != 0) {143gclog_or_tty->print_cr(" %d: %d", i, _histo[i]);144}145}146}147};148149class RedirtyLoggedCardTableEntryClosure : public CardTableEntryClosure {150private:151size_t _num_processed;152153public:154RedirtyLoggedCardTableEntryClosure() : CardTableEntryClosure(), _num_processed(0) { }155156bool do_card_ptr(jbyte* card_ptr, uint worker_i) {157*card_ptr = CardTableModRefBS::dirty_card_val();158_num_processed++;159return true;160}161162size_t num_processed() const { return _num_processed; }163};164165YoungList::YoungList(G1CollectedHeap* g1h) :166_g1h(g1h), _head(NULL), _length(0), _last_sampled_rs_lengths(0),167_survivor_head(NULL), _survivor_tail(NULL), _survivor_length(0) {168guarantee(check_list_empty(false), "just making sure...");169}170171void YoungList::push_region(HeapRegion *hr) {172assert(!hr->is_young(), "should not already be young");173assert(hr->get_next_young_region() == NULL, "cause it should!");174175hr->set_next_young_region(_head);176_head = hr;177178_g1h->g1_policy()->set_region_eden(hr, (int) _length);179++_length;180}181182void YoungList::add_survivor_region(HeapRegion* hr) {183assert(hr->is_survivor(), "should be flagged as survivor region");184assert(hr->get_next_young_region() == NULL, "cause it should!");185186hr->set_next_young_region(_survivor_head);187if (_survivor_head == NULL) {188_survivor_tail = hr;189}190_survivor_head = hr;191++_survivor_length;192}193194void YoungList::empty_list(HeapRegion* list) {195while (list != NULL) {196HeapRegion* next = list->get_next_young_region();197list->set_next_young_region(NULL);198list->uninstall_surv_rate_group();199// This is called before a Full GC and all the non-empty /200// non-humongous regions at the end of the Full GC will end up as201// old anyway.202list->set_old();203list = next;204}205}206207void YoungList::empty_list() {208assert(check_list_well_formed(), "young list should be well formed");209210empty_list(_head);211_head = NULL;212_length = 0;213214empty_list(_survivor_head);215_survivor_head = NULL;216_survivor_tail = NULL;217_survivor_length = 0;218219_last_sampled_rs_lengths = 0;220221assert(check_list_empty(false), "just making sure...");222}223224bool YoungList::check_list_well_formed() {225bool ret = true;226227uint length = 0;228HeapRegion* curr = _head;229HeapRegion* last = NULL;230while (curr != NULL) {231if (!curr->is_young()) {232gclog_or_tty->print_cr("### YOUNG REGION " PTR_FORMAT "-" PTR_FORMAT " "233"incorrectly tagged (y: %d, surv: %d)",234curr->bottom(), curr->end(),235curr->is_young(), curr->is_survivor());236ret = false;237}238++length;239last = curr;240curr = curr->get_next_young_region();241}242ret = ret && (length == _length);243244if (!ret) {245gclog_or_tty->print_cr("### YOUNG LIST seems not well formed!");246gclog_or_tty->print_cr("### list has %u entries, _length is %u",247length, _length);248}249250return ret;251}252253bool YoungList::check_list_empty(bool check_sample) {254bool ret = true;255256if (_length != 0) {257gclog_or_tty->print_cr("### YOUNG LIST should have 0 length, not %u",258_length);259ret = false;260}261if (check_sample && _last_sampled_rs_lengths != 0) {262gclog_or_tty->print_cr("### YOUNG LIST has non-zero last sampled RS lengths");263ret = false;264}265if (_head != NULL) {266gclog_or_tty->print_cr("### YOUNG LIST does not have a NULL head");267ret = false;268}269if (!ret) {270gclog_or_tty->print_cr("### YOUNG LIST does not seem empty");271}272273return ret;274}275276void277YoungList::rs_length_sampling_init() {278_sampled_rs_lengths = 0;279_curr = _head;280}281282bool283YoungList::rs_length_sampling_more() {284return _curr != NULL;285}286287void288YoungList::rs_length_sampling_next() {289assert( _curr != NULL, "invariant" );290size_t rs_length = _curr->rem_set()->occupied();291292_sampled_rs_lengths += rs_length;293294// The current region may not yet have been added to the295// incremental collection set (it gets added when it is296// retired as the current allocation region).297if (_curr->in_collection_set()) {298// Update the collection set policy information for this region299_g1h->g1_policy()->update_incremental_cset_info(_curr, rs_length);300}301302_curr = _curr->get_next_young_region();303if (_curr == NULL) {304_last_sampled_rs_lengths = _sampled_rs_lengths;305// gclog_or_tty->print_cr("last sampled RS lengths = %d", _last_sampled_rs_lengths);306}307}308309void310YoungList::reset_auxilary_lists() {311guarantee( is_empty(), "young list should be empty" );312assert(check_list_well_formed(), "young list should be well formed");313314// Add survivor regions to SurvRateGroup.315_g1h->g1_policy()->note_start_adding_survivor_regions();316_g1h->g1_policy()->finished_recalculating_age_indexes(true /* is_survivors */);317318int young_index_in_cset = 0;319for (HeapRegion* curr = _survivor_head;320curr != NULL;321curr = curr->get_next_young_region()) {322_g1h->g1_policy()->set_region_survivor(curr, young_index_in_cset);323324// The region is a non-empty survivor so let's add it to325// the incremental collection set for the next evacuation326// pause.327_g1h->g1_policy()->add_region_to_incremental_cset_rhs(curr);328young_index_in_cset += 1;329}330assert((uint) young_index_in_cset == _survivor_length, "post-condition");331_g1h->g1_policy()->note_stop_adding_survivor_regions();332333_head = _survivor_head;334_length = _survivor_length;335if (_survivor_head != NULL) {336assert(_survivor_tail != NULL, "cause it shouldn't be");337assert(_survivor_length > 0, "invariant");338_survivor_tail->set_next_young_region(NULL);339}340341// Don't clear the survivor list handles until the start of342// the next evacuation pause - we need it in order to re-tag343// the survivor regions from this evacuation pause as 'young'344// at the start of the next.345346_g1h->g1_policy()->finished_recalculating_age_indexes(false /* is_survivors */);347348assert(check_list_well_formed(), "young list should be well formed");349}350351void YoungList::print() {352HeapRegion* lists[] = {_head, _survivor_head};353const char* names[] = {"YOUNG", "SURVIVOR"};354355for (uint list = 0; list < ARRAY_SIZE(lists); ++list) {356gclog_or_tty->print_cr("%s LIST CONTENTS", names[list]);357HeapRegion *curr = lists[list];358if (curr == NULL)359gclog_or_tty->print_cr(" empty");360while (curr != NULL) {361gclog_or_tty->print_cr(" " HR_FORMAT ", P: " PTR_FORMAT ", N: " PTR_FORMAT ", age: %4d",362HR_FORMAT_PARAMS(curr),363curr->prev_top_at_mark_start(),364curr->next_top_at_mark_start(),365curr->age_in_surv_rate_group_cond());366curr = curr->get_next_young_region();367}368}369370gclog_or_tty->cr();371}372373void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) {374OtherRegionsTable::invalidate(start_idx, num_regions);375}376377void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) {378// The from card cache is not the memory that is actually committed. So we cannot379// take advantage of the zero_filled parameter.380reset_from_card_cache(start_idx, num_regions);381}382383void G1CollectedHeap::push_dirty_cards_region(HeapRegion* hr)384{385// Claim the right to put the region on the dirty cards region list386// by installing a self pointer.387HeapRegion* next = hr->get_next_dirty_cards_region();388if (next == NULL) {389HeapRegion* res = (HeapRegion*)390Atomic::cmpxchg_ptr(hr, hr->next_dirty_cards_region_addr(),391NULL);392if (res == NULL) {393HeapRegion* head;394do {395// Put the region to the dirty cards region list.396head = _dirty_cards_region_list;397next = (HeapRegion*)398Atomic::cmpxchg_ptr(hr, &_dirty_cards_region_list, head);399if (next == head) {400assert(hr->get_next_dirty_cards_region() == hr,401"hr->get_next_dirty_cards_region() != hr");402if (next == NULL) {403// The last region in the list points to itself.404hr->set_next_dirty_cards_region(hr);405} else {406hr->set_next_dirty_cards_region(next);407}408}409} while (next != head);410}411}412}413414HeapRegion* G1CollectedHeap::pop_dirty_cards_region()415{416HeapRegion* head;417HeapRegion* hr;418do {419head = _dirty_cards_region_list;420if (head == NULL) {421return NULL;422}423HeapRegion* new_head = head->get_next_dirty_cards_region();424if (head == new_head) {425// The last region.426new_head = NULL;427}428hr = (HeapRegion*)Atomic::cmpxchg_ptr(new_head, &_dirty_cards_region_list,429head);430} while (hr != head);431assert(hr != NULL, "invariant");432hr->set_next_dirty_cards_region(NULL);433return hr;434}435436#ifdef ASSERT437// A region is added to the collection set as it is retired438// so an address p can point to a region which will be in the439// collection set but has not yet been retired. This method440// therefore is only accurate during a GC pause after all441// regions have been retired. It is used for debugging442// to check if an nmethod has references to objects that can443// be move during a partial collection. Though it can be444// inaccurate, it is sufficient for G1 because the conservative445// implementation of is_scavengable() for G1 will indicate that446// all nmethods must be scanned during a partial collection.447bool G1CollectedHeap::is_in_partial_collection(const void* p) {448if (p == NULL) {449return false;450}451return heap_region_containing(p)->in_collection_set();452}453#endif454455// Returns true if the reference points to an object that456// can move in an incremental collection.457bool G1CollectedHeap::is_scavengable(const void* p) {458HeapRegion* hr = heap_region_containing(p);459return !hr->isHumongous();460}461462void G1CollectedHeap::check_ct_logs_at_safepoint() {463DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();464CardTableModRefBS* ct_bs = g1_barrier_set();465466// Count the dirty cards at the start.467CountNonCleanMemRegionClosure count1(this);468ct_bs->mod_card_iterate(&count1);469int orig_count = count1.n();470471// First clear the logged cards.472ClearLoggedCardTableEntryClosure clear;473dcqs.apply_closure_to_all_completed_buffers(&clear);474dcqs.iterate_closure_all_threads(&clear, false);475clear.print_histo();476477// Now ensure that there's no dirty cards.478CountNonCleanMemRegionClosure count2(this);479ct_bs->mod_card_iterate(&count2);480if (count2.n() != 0) {481gclog_or_tty->print_cr("Card table has %d entries; %d originally",482count2.n(), orig_count);483}484guarantee(count2.n() == 0, "Card table should be clean.");485486RedirtyLoggedCardTableEntryClosure redirty;487dcqs.apply_closure_to_all_completed_buffers(&redirty);488dcqs.iterate_closure_all_threads(&redirty, false);489gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",490clear.num_processed(), orig_count);491guarantee(redirty.num_processed() == clear.num_processed(),492err_msg("Redirtied " SIZE_FORMAT " cards, bug cleared " SIZE_FORMAT,493redirty.num_processed(), clear.num_processed()));494495CountNonCleanMemRegionClosure count3(this);496ct_bs->mod_card_iterate(&count3);497if (count3.n() != orig_count) {498gclog_or_tty->print_cr("Should have restored them all: orig = %d, final = %d.",499orig_count, count3.n());500guarantee(count3.n() >= orig_count, "Should have restored them all.");501}502}503504// Private class members.505506G1CollectedHeap* G1CollectedHeap::_g1h;507508// Private methods.509510HeapRegion*511G1CollectedHeap::new_region_try_secondary_free_list(bool is_old) {512MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);513while (!_secondary_free_list.is_empty() || free_regions_coming()) {514if (!_secondary_free_list.is_empty()) {515if (G1ConcRegionFreeingVerbose) {516gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "517"secondary_free_list has %u entries",518_secondary_free_list.length());519}520// It looks as if there are free regions available on the521// secondary_free_list. Let's move them to the free_list and try522// again to allocate from it.523append_secondary_free_list();524525assert(_hrm.num_free_regions() > 0, "if the secondary_free_list was not "526"empty we should have moved at least one entry to the free_list");527HeapRegion* res = _hrm.allocate_free_region(is_old);528if (G1ConcRegionFreeingVerbose) {529gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "530"allocated " HR_FORMAT " from secondary_free_list",531HR_FORMAT_PARAMS(res));532}533return res;534}535536// Wait here until we get notified either when (a) there are no537// more free regions coming or (b) some regions have been moved on538// the secondary_free_list.539SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);540}541542if (G1ConcRegionFreeingVerbose) {543gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "544"could not allocate from secondary_free_list");545}546return NULL;547}548549HeapRegion* G1CollectedHeap::new_region(size_t word_size, bool is_old, bool do_expand) {550assert(!isHumongous(word_size) || word_size <= HeapRegion::GrainWords,551"the only time we use this to allocate a humongous region is "552"when we are allocating a single humongous region");553554HeapRegion* res;555if (G1StressConcRegionFreeing) {556if (!_secondary_free_list.is_empty()) {557if (G1ConcRegionFreeingVerbose) {558gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "559"forced to look at the secondary_free_list");560}561res = new_region_try_secondary_free_list(is_old);562if (res != NULL) {563return res;564}565}566}567568res = _hrm.allocate_free_region(is_old);569570if (res == NULL) {571if (G1ConcRegionFreeingVerbose) {572gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "573"res == NULL, trying the secondary_free_list");574}575res = new_region_try_secondary_free_list(is_old);576}577if (res == NULL && do_expand && _expand_heap_after_alloc_failure) {578// Currently, only attempts to allocate GC alloc regions set579// do_expand to true. So, we should only reach here during a580// safepoint. If this assumption changes we might have to581// reconsider the use of _expand_heap_after_alloc_failure.582assert(SafepointSynchronize::is_at_safepoint(), "invariant");583584ergo_verbose1(ErgoHeapSizing,585"attempt heap expansion",586ergo_format_reason("region allocation request failed")587ergo_format_byte("allocation request"),588word_size * HeapWordSize);589if (expand(word_size * HeapWordSize)) {590// Given that expand() succeeded in expanding the heap, and we591// always expand the heap by an amount aligned to the heap592// region size, the free list should in theory not be empty.593// In either case allocate_free_region() will check for NULL.594res = _hrm.allocate_free_region(is_old);595} else {596_expand_heap_after_alloc_failure = false;597}598}599return res;600}601602HeapWord*603G1CollectedHeap::humongous_obj_allocate_initialize_regions(uint first,604uint num_regions,605size_t word_size,606AllocationContext_t context) {607assert(first != G1_NO_HRM_INDEX, "pre-condition");608assert(isHumongous(word_size), "word_size should be humongous");609assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");610611// Index of last region in the series + 1.612uint last = first + num_regions;613614// We need to initialize the region(s) we just discovered. This is615// a bit tricky given that it can happen concurrently with616// refinement threads refining cards on these regions and617// potentially wanting to refine the BOT as they are scanning618// those cards (this can happen shortly after a cleanup; see CR619// 6991377). So we have to set up the region(s) carefully and in620// a specific order.621622// The word size sum of all the regions we will allocate.623size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;624assert(word_size <= word_size_sum, "sanity");625626// This will be the "starts humongous" region.627HeapRegion* first_hr = region_at(first);628// The header of the new object will be placed at the bottom of629// the first region.630HeapWord* new_obj = first_hr->bottom();631// This will be the new end of the first region in the series that632// should also match the end of the last region in the series.633HeapWord* new_end = new_obj + word_size_sum;634// This will be the new top of the first region that will reflect635// this allocation.636HeapWord* new_top = new_obj + word_size;637638// First, we need to zero the header of the space that we will be639// allocating. When we update top further down, some refinement640// threads might try to scan the region. By zeroing the header we641// ensure that any thread that will try to scan the region will642// come across the zero klass word and bail out.643//644// NOTE: It would not have been correct to have used645// CollectedHeap::fill_with_object() and make the space look like646// an int array. The thread that is doing the allocation will647// later update the object header to a potentially different array648// type and, for a very short period of time, the klass and length649// fields will be inconsistent. This could cause a refinement650// thread to calculate the object size incorrectly.651Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);652653// We will set up the first region as "starts humongous". This654// will also update the BOT covering all the regions to reflect655// that there is a single object that starts at the bottom of the656// first region.657first_hr->set_startsHumongous(new_top, new_end);658first_hr->set_allocation_context(context);659// Then, if there are any, we will set up the "continues660// humongous" regions.661HeapRegion* hr = NULL;662for (uint i = first + 1; i < last; ++i) {663hr = region_at(i);664hr->set_continuesHumongous(first_hr);665hr->set_allocation_context(context);666}667// If we have "continues humongous" regions (hr != NULL), then the668// end of the last one should match new_end.669assert(hr == NULL || hr->end() == new_end, "sanity");670671// Up to this point no concurrent thread would have been able to672// do any scanning on any region in this series. All the top673// fields still point to bottom, so the intersection between674// [bottom,top] and [card_start,card_end] will be empty. Before we675// update the top fields, we'll do a storestore to make sure that676// no thread sees the update to top before the zeroing of the677// object header and the BOT initialization.678OrderAccess::storestore();679680// Now that the BOT and the object header have been initialized,681// we can update top of the "starts humongous" region.682assert(first_hr->bottom() < new_top && new_top <= first_hr->end(),683"new_top should be in this region");684first_hr->set_top(new_top);685if (_hr_printer.is_active()) {686HeapWord* bottom = first_hr->bottom();687HeapWord* end = first_hr->orig_end();688if ((first + 1) == last) {689// the series has a single humongous region690_hr_printer.alloc(G1HRPrinter::SingleHumongous, first_hr, new_top);691} else {692// the series has more than one humongous regions693_hr_printer.alloc(G1HRPrinter::StartsHumongous, first_hr, end);694}695}696697// Now, we will update the top fields of the "continues humongous"698// regions. The reason we need to do this is that, otherwise,699// these regions would look empty and this will confuse parts of700// G1. For example, the code that looks for a consecutive number701// of empty regions will consider them empty and try to702// re-allocate them. We can extend is_empty() to also include703// !continuesHumongous(), but it is easier to just update the top704// fields here. The way we set top for all regions (i.e., top ==705// end for all regions but the last one, top == new_top for the706// last one) is actually used when we will free up the humongous707// region in free_humongous_region().708hr = NULL;709for (uint i = first + 1; i < last; ++i) {710hr = region_at(i);711if ((i + 1) == last) {712// last continues humongous region713assert(hr->bottom() < new_top && new_top <= hr->end(),714"new_top should fall on this region");715hr->set_top(new_top);716_hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, new_top);717} else {718// not last one719assert(new_top > hr->end(), "new_top should be above this region");720hr->set_top(hr->end());721_hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, hr->end());722}723}724// If we have continues humongous regions (hr != NULL), then the725// end of the last one should match new_end and its top should726// match new_top.727assert(hr == NULL ||728(hr->end() == new_end && hr->top() == new_top), "sanity");729check_bitmaps("Humongous Region Allocation", first_hr);730731assert(first_hr->used() == word_size * HeapWordSize, "invariant");732_allocator->increase_used(first_hr->used());733_humongous_set.add(first_hr);734735return new_obj;736}737738// If could fit into free regions w/o expansion, try.739// Otherwise, if can expand, do so.740// Otherwise, if using ex regions might help, try with ex given back.741HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size, AllocationContext_t context) {742assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);743744verify_region_sets_optional();745746uint first = G1_NO_HRM_INDEX;747uint obj_regions = (uint)(align_size_up_(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords);748749if (obj_regions == 1) {750// Only one region to allocate, try to use a fast path by directly allocating751// from the free lists. Do not try to expand here, we will potentially do that752// later.753HeapRegion* hr = new_region(word_size, true /* is_old */, false /* do_expand */);754if (hr != NULL) {755first = hr->hrm_index();756}757} else {758// We can't allocate humongous regions spanning more than one region while759// cleanupComplete() is running, since some of the regions we find to be760// empty might not yet be added to the free list. It is not straightforward761// to know in which list they are on so that we can remove them. We only762// need to do this if we need to allocate more than one region to satisfy the763// current humongous allocation request. If we are only allocating one region764// we use the one-region region allocation code (see above), that already765// potentially waits for regions from the secondary free list.766wait_while_free_regions_coming();767append_secondary_free_list_if_not_empty_with_lock();768769// Policy: Try only empty regions (i.e. already committed first). Maybe we770// are lucky enough to find some.771first = _hrm.find_contiguous_only_empty(obj_regions);772if (first != G1_NO_HRM_INDEX) {773_hrm.allocate_free_regions_starting_at(first, obj_regions);774}775}776777if (first == G1_NO_HRM_INDEX) {778// Policy: We could not find enough regions for the humongous object in the779// free list. Look through the heap to find a mix of free and uncommitted regions.780// If so, try expansion.781first = _hrm.find_contiguous_empty_or_unavailable(obj_regions);782if (first != G1_NO_HRM_INDEX) {783// We found something. Make sure these regions are committed, i.e. expand784// the heap. Alternatively we could do a defragmentation GC.785ergo_verbose1(ErgoHeapSizing,786"attempt heap expansion",787ergo_format_reason("humongous allocation request failed")788ergo_format_byte("allocation request"),789word_size * HeapWordSize);790791_hrm.expand_at(first, obj_regions);792g1_policy()->record_new_heap_size(num_regions());793794#ifdef ASSERT795for (uint i = first; i < first + obj_regions; ++i) {796HeapRegion* hr = region_at(i);797assert(hr->is_free(), "sanity");798assert(hr->is_empty(), "sanity");799assert(is_on_master_free_list(hr), "sanity");800}801#endif802_hrm.allocate_free_regions_starting_at(first, obj_regions);803} else {804// Policy: Potentially trigger a defragmentation GC.805}806}807808HeapWord* result = NULL;809if (first != G1_NO_HRM_INDEX) {810result = humongous_obj_allocate_initialize_regions(first, obj_regions,811word_size, context);812assert(result != NULL, "it should always return a valid result");813814// A successful humongous object allocation changes the used space815// information of the old generation so we need to recalculate the816// sizes and update the jstat counters here.817g1mm()->update_sizes();818}819820verify_region_sets_optional();821822return result;823}824825HeapWord* G1CollectedHeap::allocate_new_tlab(size_t word_size) {826assert_heap_not_locked_and_not_at_safepoint();827assert(!isHumongous(word_size), "we do not allow humongous TLABs");828829uint dummy_gc_count_before;830uint dummy_gclocker_retry_count = 0;831return attempt_allocation(word_size, &dummy_gc_count_before, &dummy_gclocker_retry_count);832}833834HeapWord*835G1CollectedHeap::mem_allocate(size_t word_size,836bool* gc_overhead_limit_was_exceeded) {837assert_heap_not_locked_and_not_at_safepoint();838839// Loop until the allocation is satisfied, or unsatisfied after GC.840for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {841uint gc_count_before;842843HeapWord* result = NULL;844if (!isHumongous(word_size)) {845result = attempt_allocation(word_size, &gc_count_before, &gclocker_retry_count);846} else {847result = attempt_allocation_humongous(word_size, &gc_count_before, &gclocker_retry_count);848}849if (result != NULL) {850return result;851}852853// Create the garbage collection operation...854VM_G1CollectForAllocation op(gc_count_before, word_size);855op.set_allocation_context(AllocationContext::current());856857// ...and get the VM thread to execute it.858VMThread::execute(&op);859860if (op.prologue_succeeded() && op.pause_succeeded()) {861// If the operation was successful we'll return the result even862// if it is NULL. If the allocation attempt failed immediately863// after a Full GC, it's unlikely we'll be able to allocate now.864HeapWord* result = op.result();865if (result != NULL && !isHumongous(word_size)) {866// Allocations that take place on VM operations do not do any867// card dirtying and we have to do it here. We only have to do868// this for non-humongous allocations, though.869dirty_young_block(result, word_size);870}871return result;872} else {873if (gclocker_retry_count > GCLockerRetryAllocationCount) {874return NULL;875}876assert(op.result() == NULL,877"the result should be NULL if the VM op did not succeed");878}879880// Give a warning if we seem to be looping forever.881if ((QueuedAllocationWarningCount > 0) &&882(try_count % QueuedAllocationWarningCount == 0)) {883warning("G1CollectedHeap::mem_allocate retries %d times", try_count);884}885}886887ShouldNotReachHere();888return NULL;889}890891HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size,892AllocationContext_t context,893uint* gc_count_before_ret,894uint* gclocker_retry_count_ret) {895// Make sure you read the note in attempt_allocation_humongous().896897assert_heap_not_locked_and_not_at_safepoint();898assert(!isHumongous(word_size), "attempt_allocation_slow() should not "899"be called for humongous allocation requests");900901// We should only get here after the first-level allocation attempt902// (attempt_allocation()) failed to allocate.903904// We will loop until a) we manage to successfully perform the905// allocation or b) we successfully schedule a collection which906// fails to perform the allocation. b) is the only case when we'll907// return NULL.908HeapWord* result = NULL;909for (int try_count = 1; /* we'll return */; try_count += 1) {910bool should_try_gc;911uint gc_count_before;912913{914MutexLockerEx x(Heap_lock);915result = _allocator->mutator_alloc_region(context)->attempt_allocation_locked(word_size,916false /* bot_updates */);917if (result != NULL) {918return result;919}920921// If we reach here, attempt_allocation_locked() above failed to922// allocate a new region. So the mutator alloc region should be NULL.923assert(_allocator->mutator_alloc_region(context)->get() == NULL, "only way to get here");924925if (GC_locker::is_active_and_needs_gc()) {926if (g1_policy()->can_expand_young_list()) {927// No need for an ergo verbose message here,928// can_expand_young_list() does this when it returns true.929result = _allocator->mutator_alloc_region(context)->attempt_allocation_force(word_size,930false /* bot_updates */);931if (result != NULL) {932return result;933}934}935should_try_gc = false;936} else {937// The GCLocker may not be active but the GCLocker initiated938// GC may not yet have been performed (GCLocker::needs_gc()939// returns true). In this case we do not try this GC and940// wait until the GCLocker initiated GC is performed, and941// then retry the allocation.942if (GC_locker::needs_gc()) {943should_try_gc = false;944} else {945// Read the GC count while still holding the Heap_lock.946gc_count_before = total_collections();947should_try_gc = true;948}949}950}951952if (should_try_gc) {953bool succeeded;954result = do_collection_pause(word_size, gc_count_before, &succeeded,955GCCause::_g1_inc_collection_pause);956if (result != NULL) {957assert(succeeded, "only way to get back a non-NULL result");958return result;959}960961if (succeeded) {962// If we get here we successfully scheduled a collection which963// failed to allocate. No point in trying to allocate964// further. We'll just return NULL.965MutexLockerEx x(Heap_lock);966*gc_count_before_ret = total_collections();967return NULL;968}969} else {970if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {971MutexLockerEx x(Heap_lock);972*gc_count_before_ret = total_collections();973return NULL;974}975// The GCLocker is either active or the GCLocker initiated976// GC has not yet been performed. Stall until it is and977// then retry the allocation.978GC_locker::stall_until_clear();979(*gclocker_retry_count_ret) += 1;980}981982// We can reach here if we were unsuccessful in scheduling a983// collection (because another thread beat us to it) or if we were984// stalled due to the GC locker. In either can we should retry the985// allocation attempt in case another thread successfully986// performed a collection and reclaimed enough space. We do the987// first attempt (without holding the Heap_lock) here and the988// follow-on attempt will be at the start of the next loop989// iteration (after taking the Heap_lock).990result = _allocator->mutator_alloc_region(context)->attempt_allocation(word_size,991false /* bot_updates */);992if (result != NULL) {993return result;994}995996// Give a warning if we seem to be looping forever.997if ((QueuedAllocationWarningCount > 0) &&998(try_count % QueuedAllocationWarningCount == 0)) {999warning("G1CollectedHeap::attempt_allocation_slow() "1000"retries %d times", try_count);1001}1002}10031004ShouldNotReachHere();1005return NULL;1006}10071008HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size,1009uint* gc_count_before_ret,1010uint* gclocker_retry_count_ret) {1011// The structure of this method has a lot of similarities to1012// attempt_allocation_slow(). The reason these two were not merged1013// into a single one is that such a method would require several "if1014// allocation is not humongous do this, otherwise do that"1015// conditional paths which would obscure its flow. In fact, an early1016// version of this code did use a unified method which was harder to1017// follow and, as a result, it had subtle bugs that were hard to1018// track down. So keeping these two methods separate allows each to1019// be more readable. It will be good to keep these two in sync as1020// much as possible.10211022assert_heap_not_locked_and_not_at_safepoint();1023assert(isHumongous(word_size), "attempt_allocation_humongous() "1024"should only be called for humongous allocations");10251026// Humongous objects can exhaust the heap quickly, so we should check if we1027// need to start a marking cycle at each humongous object allocation. We do1028// the check before we do the actual allocation. The reason for doing it1029// before the allocation is that we avoid having to keep track of the newly1030// allocated memory while we do a GC.1031if (g1_policy()->need_to_start_conc_mark("concurrent humongous allocation",1032word_size)) {1033collect(GCCause::_g1_humongous_allocation);1034}10351036// We will loop until a) we manage to successfully perform the1037// allocation or b) we successfully schedule a collection which1038// fails to perform the allocation. b) is the only case when we'll1039// return NULL.1040HeapWord* result = NULL;1041for (int try_count = 1; /* we'll return */; try_count += 1) {1042bool should_try_gc;1043uint gc_count_before;10441045{1046MutexLockerEx x(Heap_lock);10471048// Given that humongous objects are not allocated in young1049// regions, we'll first try to do the allocation without doing a1050// collection hoping that there's enough space in the heap.1051result = humongous_obj_allocate(word_size, AllocationContext::current());1052if (result != NULL) {1053return result;1054}10551056if (GC_locker::is_active_and_needs_gc()) {1057should_try_gc = false;1058} else {1059// The GCLocker may not be active but the GCLocker initiated1060// GC may not yet have been performed (GCLocker::needs_gc()1061// returns true). In this case we do not try this GC and1062// wait until the GCLocker initiated GC is performed, and1063// then retry the allocation.1064if (GC_locker::needs_gc()) {1065should_try_gc = false;1066} else {1067// Read the GC count while still holding the Heap_lock.1068gc_count_before = total_collections();1069should_try_gc = true;1070}1071}1072}10731074if (should_try_gc) {1075// If we failed to allocate the humongous object, we should try to1076// do a collection pause (if we're allowed) in case it reclaims1077// enough space for the allocation to succeed after the pause.10781079bool succeeded;1080result = do_collection_pause(word_size, gc_count_before, &succeeded,1081GCCause::_g1_humongous_allocation);1082if (result != NULL) {1083assert(succeeded, "only way to get back a non-NULL result");1084return result;1085}10861087if (succeeded) {1088// If we get here we successfully scheduled a collection which1089// failed to allocate. No point in trying to allocate1090// further. We'll just return NULL.1091MutexLockerEx x(Heap_lock);1092*gc_count_before_ret = total_collections();1093return NULL;1094}1095} else {1096if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {1097MutexLockerEx x(Heap_lock);1098*gc_count_before_ret = total_collections();1099return NULL;1100}1101// The GCLocker is either active or the GCLocker initiated1102// GC has not yet been performed. Stall until it is and1103// then retry the allocation.1104GC_locker::stall_until_clear();1105(*gclocker_retry_count_ret) += 1;1106}11071108// We can reach here if we were unsuccessful in scheduling a1109// collection (because another thread beat us to it) or if we were1110// stalled due to the GC locker. In either can we should retry the1111// allocation attempt in case another thread successfully1112// performed a collection and reclaimed enough space. Give a1113// warning if we seem to be looping forever.11141115if ((QueuedAllocationWarningCount > 0) &&1116(try_count % QueuedAllocationWarningCount == 0)) {1117warning("G1CollectedHeap::attempt_allocation_humongous() "1118"retries %d times", try_count);1119}1120}11211122ShouldNotReachHere();1123return NULL;1124}11251126HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,1127AllocationContext_t context,1128bool expect_null_mutator_alloc_region) {1129assert_at_safepoint(true /* should_be_vm_thread */);1130assert(_allocator->mutator_alloc_region(context)->get() == NULL ||1131!expect_null_mutator_alloc_region,1132"the current alloc region was unexpectedly found to be non-NULL");11331134if (!isHumongous(word_size)) {1135return _allocator->mutator_alloc_region(context)->attempt_allocation_locked(word_size,1136false /* bot_updates */);1137} else {1138HeapWord* result = humongous_obj_allocate(word_size, context);1139if (result != NULL && g1_policy()->need_to_start_conc_mark("STW humongous allocation")) {1140g1_policy()->set_initiate_conc_mark_if_possible();1141}1142return result;1143}11441145ShouldNotReachHere();1146}11471148class PostMCRemSetClearClosure: public HeapRegionClosure {1149G1CollectedHeap* _g1h;1150ModRefBarrierSet* _mr_bs;1151public:1152PostMCRemSetClearClosure(G1CollectedHeap* g1h, ModRefBarrierSet* mr_bs) :1153_g1h(g1h), _mr_bs(mr_bs) {}11541155bool doHeapRegion(HeapRegion* r) {1156HeapRegionRemSet* hrrs = r->rem_set();11571158if (r->continuesHumongous()) {1159// We'll assert that the strong code root list and RSet is empty1160assert(hrrs->strong_code_roots_list_length() == 0, "sanity");1161assert(hrrs->occupied() == 0, "RSet should be empty");1162return false;1163}11641165_g1h->reset_gc_time_stamps(r);1166hrrs->clear();1167// You might think here that we could clear just the cards1168// corresponding to the used region. But no: if we leave a dirty card1169// in a region we might allocate into, then it would prevent that card1170// from being enqueued, and cause it to be missed.1171// Re: the performance cost: we shouldn't be doing full GC anyway!1172_mr_bs->clear(MemRegion(r->bottom(), r->end()));11731174return false;1175}1176};11771178void G1CollectedHeap::clear_rsets_post_compaction() {1179PostMCRemSetClearClosure rs_clear(this, g1_barrier_set());1180heap_region_iterate(&rs_clear);1181}11821183class RebuildRSOutOfRegionClosure: public HeapRegionClosure {1184G1CollectedHeap* _g1h;1185UpdateRSOopClosure _cl;1186int _worker_i;1187public:1188RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, int worker_i = 0) :1189_cl(g1->g1_rem_set(), worker_i),1190_worker_i(worker_i),1191_g1h(g1)1192{ }11931194bool doHeapRegion(HeapRegion* r) {1195if (!r->continuesHumongous()) {1196_cl.set_from(r);1197r->oop_iterate(&_cl);1198}1199return false;1200}1201};12021203class ParRebuildRSTask: public AbstractGangTask {1204G1CollectedHeap* _g1;1205public:1206ParRebuildRSTask(G1CollectedHeap* g1)1207: AbstractGangTask("ParRebuildRSTask"),1208_g1(g1)1209{ }12101211void work(uint worker_id) {1212RebuildRSOutOfRegionClosure rebuild_rs(_g1, worker_id);1213_g1->heap_region_par_iterate_chunked(&rebuild_rs, worker_id,1214_g1->workers()->active_workers(),1215HeapRegion::RebuildRSClaimValue);1216}1217};12181219class PostCompactionPrinterClosure: public HeapRegionClosure {1220private:1221G1HRPrinter* _hr_printer;1222public:1223bool doHeapRegion(HeapRegion* hr) {1224assert(!hr->is_young(), "not expecting to find young regions");1225if (hr->is_free()) {1226// We only generate output for non-empty regions.1227} else if (hr->startsHumongous()) {1228if (hr->region_num() == 1) {1229// single humongous region1230_hr_printer->post_compaction(hr, G1HRPrinter::SingleHumongous);1231} else {1232_hr_printer->post_compaction(hr, G1HRPrinter::StartsHumongous);1233}1234} else if (hr->continuesHumongous()) {1235_hr_printer->post_compaction(hr, G1HRPrinter::ContinuesHumongous);1236} else if (hr->is_old()) {1237_hr_printer->post_compaction(hr, G1HRPrinter::Old);1238} else {1239ShouldNotReachHere();1240}1241return false;1242}12431244PostCompactionPrinterClosure(G1HRPrinter* hr_printer)1245: _hr_printer(hr_printer) { }1246};12471248void G1CollectedHeap::print_hrm_post_compaction() {1249PostCompactionPrinterClosure cl(hr_printer());1250heap_region_iterate(&cl);1251}12521253bool G1CollectedHeap::do_collection(bool explicit_gc,1254bool clear_all_soft_refs,1255size_t word_size) {1256assert_at_safepoint(true /* should_be_vm_thread */);12571258if (GC_locker::check_active_before_gc()) {1259return false;1260}12611262STWGCTimer* gc_timer = G1MarkSweep::gc_timer();1263gc_timer->register_gc_start();12641265SerialOldTracer* gc_tracer = G1MarkSweep::gc_tracer();1266gc_tracer->report_gc_start(gc_cause(), gc_timer->gc_start());12671268SvcGCMarker sgcm(SvcGCMarker::FULL);1269ResourceMark rm;12701271print_heap_before_gc();1272trace_heap_before_gc(gc_tracer);12731274size_t metadata_prev_used = MetaspaceAux::used_bytes();12751276verify_region_sets_optional();12771278const bool do_clear_all_soft_refs = clear_all_soft_refs ||1279collector_policy()->should_clear_all_soft_refs();12801281ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());12821283{1284IsGCActiveMark x;12851286// Timing1287assert(gc_cause() != GCCause::_java_lang_system_gc || explicit_gc, "invariant");1288TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);12891290{1291GCTraceTime t(GCCauseString("Full GC", gc_cause()), G1Log::fine(), true, NULL, gc_tracer->gc_id());1292TraceCollectorStats tcs(g1mm()->full_collection_counters());1293TraceMemoryManagerStats tms(true /* fullGC */, gc_cause());12941295double start = os::elapsedTime();1296g1_policy()->record_full_collection_start();12971298// Note: When we have a more flexible GC logging framework that1299// allows us to add optional attributes to a GC log record we1300// could consider timing and reporting how long we wait in the1301// following two methods.1302wait_while_free_regions_coming();1303// If we start the compaction before the CM threads finish1304// scanning the root regions we might trip them over as we'll1305// be moving objects / updating references. So let's wait until1306// they are done. By telling them to abort, they should complete1307// early.1308_cm->root_regions()->abort();1309_cm->root_regions()->wait_until_scan_finished();1310append_secondary_free_list_if_not_empty_with_lock();13111312gc_prologue(true);1313increment_total_collections(true /* full gc */);1314increment_old_marking_cycles_started();13151316assert(used() == recalculate_used(), "Should be equal");13171318verify_before_gc();13191320check_bitmaps("Full GC Start");1321pre_full_gc_dump(gc_timer);13221323COMPILER2_PRESENT(DerivedPointerTable::clear());13241325// Disable discovery and empty the discovered lists1326// for the CM ref processor.1327ref_processor_cm()->disable_discovery();1328ref_processor_cm()->abandon_partial_discovery();1329ref_processor_cm()->verify_no_references_recorded();13301331// Abandon current iterations of concurrent marking and concurrent1332// refinement, if any are in progress. We have to do this before1333// wait_until_scan_finished() below.1334concurrent_mark()->abort();13351336// Make sure we'll choose a new allocation region afterwards.1337_allocator->release_mutator_alloc_region();1338_allocator->abandon_gc_alloc_regions();1339g1_rem_set()->cleanupHRRS();13401341// We should call this after we retire any currently active alloc1342// regions so that all the ALLOC / RETIRE events are generated1343// before the start GC event.1344_hr_printer.start_gc(true /* full */, (size_t) total_collections());13451346// We may have added regions to the current incremental collection1347// set between the last GC or pause and now. We need to clear the1348// incremental collection set and then start rebuilding it afresh1349// after this full GC.1350abandon_collection_set(g1_policy()->inc_cset_head());1351g1_policy()->clear_incremental_cset();1352g1_policy()->stop_incremental_cset_building();13531354tear_down_region_sets(false /* free_list_only */);1355g1_policy()->set_gcs_are_young(true);13561357// See the comments in g1CollectedHeap.hpp and1358// G1CollectedHeap::ref_processing_init() about1359// how reference processing currently works in G1.13601361// Temporarily make discovery by the STW ref processor single threaded (non-MT).1362ReferenceProcessorMTDiscoveryMutator stw_rp_disc_ser(ref_processor_stw(), false);13631364// Temporarily clear the STW ref processor's _is_alive_non_header field.1365ReferenceProcessorIsAliveMutator stw_rp_is_alive_null(ref_processor_stw(), NULL);13661367ref_processor_stw()->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);1368ref_processor_stw()->setup_policy(do_clear_all_soft_refs);13691370// Do collection work1371{1372HandleMark hm; // Discard invalid handles created during gc1373G1MarkSweep::invoke_at_safepoint(ref_processor_stw(), do_clear_all_soft_refs);1374}13751376assert(num_free_regions() == 0, "we should not have added any free regions");1377rebuild_region_sets(false /* free_list_only */);13781379// Enqueue any discovered reference objects that have1380// not been removed from the discovered lists.1381ref_processor_stw()->enqueue_discovered_references();13821383COMPILER2_PRESENT(DerivedPointerTable::update_pointers());13841385MemoryService::track_memory_usage();13861387assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");1388ref_processor_stw()->verify_no_references_recorded();13891390// Delete metaspaces for unloaded class loaders and clean up loader_data graph1391ClassLoaderDataGraph::purge();1392MetaspaceAux::verify_metrics();13931394// Note: since we've just done a full GC, concurrent1395// marking is no longer active. Therefore we need not1396// re-enable reference discovery for the CM ref processor.1397// That will be done at the start of the next marking cycle.1398assert(!ref_processor_cm()->discovery_enabled(), "Postcondition");1399ref_processor_cm()->verify_no_references_recorded();14001401reset_gc_time_stamp();1402// Since everything potentially moved, we will clear all remembered1403// sets, and clear all cards. Later we will rebuild remembered1404// sets. We will also reset the GC time stamps of the regions.1405clear_rsets_post_compaction();1406check_gc_time_stamps();14071408// Resize the heap if necessary.1409resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size);14101411if (_hr_printer.is_active()) {1412// We should do this after we potentially resize the heap so1413// that all the COMMIT / UNCOMMIT events are generated before1414// the end GC event.14151416print_hrm_post_compaction();1417_hr_printer.end_gc(true /* full */, (size_t) total_collections());1418}14191420G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();1421if (hot_card_cache->use_cache()) {1422hot_card_cache->reset_card_counts();1423hot_card_cache->reset_hot_cache();1424}14251426// Rebuild remembered sets of all regions.1427if (G1CollectedHeap::use_parallel_gc_threads()) {1428uint n_workers =1429AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),1430workers()->active_workers(),1431Threads::number_of_non_daemon_threads());1432assert(UseDynamicNumberOfGCThreads ||1433n_workers == workers()->total_workers(),1434"If not dynamic should be using all the workers");1435workers()->set_active_workers(n_workers);1436// Set parallel threads in the heap (_n_par_threads) only1437// before a parallel phase and always reset it to 0 after1438// the phase so that the number of parallel threads does1439// no get carried forward to a serial phase where there1440// may be code that is "possibly_parallel".1441set_par_threads(n_workers);14421443ParRebuildRSTask rebuild_rs_task(this);1444assert(check_heap_region_claim_values(1445HeapRegion::InitialClaimValue), "sanity check");1446assert(UseDynamicNumberOfGCThreads ||1447workers()->active_workers() == workers()->total_workers(),1448"Unless dynamic should use total workers");1449// Use the most recent number of active workers1450assert(workers()->active_workers() > 0,1451"Active workers not properly set");1452set_par_threads(workers()->active_workers());1453workers()->run_task(&rebuild_rs_task);1454set_par_threads(0);1455assert(check_heap_region_claim_values(1456HeapRegion::RebuildRSClaimValue), "sanity check");1457reset_heap_region_claim_values();1458} else {1459RebuildRSOutOfRegionClosure rebuild_rs(this);1460heap_region_iterate(&rebuild_rs);1461}14621463// Rebuild the strong code root lists for each region1464rebuild_strong_code_roots();14651466// Purge code root memory1467purge_code_root_memory();14681469if (true) { // FIXME1470MetaspaceGC::compute_new_size();1471}14721473#ifdef TRACESPINNING1474ParallelTaskTerminator::print_termination_counts();1475#endif14761477// Discard all rset updates1478JavaThread::dirty_card_queue_set().abandon_logs();1479assert(dirty_card_queue_set().completed_buffers_num() == 0, "DCQS should be empty");14801481_young_list->reset_sampled_info();1482// At this point there should be no regions in the1483// entire heap tagged as young.1484assert(check_young_list_empty(true /* check_heap */),1485"young list should be empty at this point");14861487// Update the number of full collections that have been completed.1488increment_old_marking_cycles_completed(false /* concurrent */);14891490_hrm.verify_optional();1491verify_region_sets_optional();14921493verify_after_gc();14941495// Clear the previous marking bitmap, if needed for bitmap verification.1496// Note we cannot do this when we clear the next marking bitmap in1497// ConcurrentMark::abort() above since VerifyDuringGC verifies the1498// objects marked during a full GC against the previous bitmap.1499// But we need to clear it before calling check_bitmaps below since1500// the full GC has compacted objects and updated TAMS but not updated1501// the prev bitmap.1502if (G1VerifyBitmaps) {1503((CMBitMap*) concurrent_mark()->prevMarkBitMap())->clearAll();1504}1505check_bitmaps("Full GC End");15061507// Start a new incremental collection set for the next pause1508assert(g1_policy()->collection_set() == NULL, "must be");1509g1_policy()->start_incremental_cset_building();15101511clear_cset_fast_test();15121513_allocator->init_mutator_alloc_region();15141515double end = os::elapsedTime();1516g1_policy()->record_full_collection_end();15171518if (G1Log::fine()) {1519g1_policy()->print_heap_transition();1520}15211522// We must call G1MonitoringSupport::update_sizes() in the same scoping level1523// as an active TraceMemoryManagerStats object (i.e. before the destructor for the1524// TraceMemoryManagerStats is called) so that the G1 memory pools are updated1525// before any GC notifications are raised.1526g1mm()->update_sizes();15271528gc_epilogue(true);1529}15301531if (G1Log::finer()) {1532g1_policy()->print_detailed_heap_transition(true /* full */);1533}15341535print_heap_after_gc();1536trace_heap_after_gc(gc_tracer);15371538post_full_gc_dump(gc_timer);15391540gc_timer->register_gc_end();1541gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions());1542}15431544return true;1545}15461547void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {1548// do_collection() will return whether it succeeded in performing1549// the GC. Currently, there is no facility on the1550// do_full_collection() API to notify the caller than the collection1551// did not succeed (e.g., because it was locked out by the GC1552// locker). So, right now, we'll ignore the return value.1553bool dummy = do_collection(true, /* explicit_gc */1554clear_all_soft_refs,15550 /* word_size */);1556}15571558// This code is mostly copied from TenuredGeneration.1559void1560G1CollectedHeap::1561resize_if_necessary_after_full_collection(size_t word_size) {1562// Include the current allocation, if any, and bytes that will be1563// pre-allocated to support collections, as "used".1564const size_t used_after_gc = used();1565const size_t capacity_after_gc = capacity();1566const size_t free_after_gc = capacity_after_gc - used_after_gc;15671568// This is enforced in arguments.cpp.1569assert(MinHeapFreeRatio <= MaxHeapFreeRatio,1570"otherwise the code below doesn't make sense");15711572// We don't have floating point command-line arguments1573const double minimum_free_percentage = (double) MinHeapFreeRatio / 100.0;1574const double maximum_used_percentage = 1.0 - minimum_free_percentage;1575const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100.0;1576const double minimum_used_percentage = 1.0 - maximum_free_percentage;15771578const size_t min_heap_size = collector_policy()->min_heap_byte_size();1579const size_t max_heap_size = collector_policy()->max_heap_byte_size();15801581// We have to be careful here as these two calculations can overflow1582// 32-bit size_t's.1583double used_after_gc_d = (double) used_after_gc;1584double minimum_desired_capacity_d = used_after_gc_d / maximum_used_percentage;1585double maximum_desired_capacity_d = used_after_gc_d / minimum_used_percentage;15861587// Let's make sure that they are both under the max heap size, which1588// by default will make them fit into a size_t.1589double desired_capacity_upper_bound = (double) max_heap_size;1590minimum_desired_capacity_d = MIN2(minimum_desired_capacity_d,1591desired_capacity_upper_bound);1592maximum_desired_capacity_d = MIN2(maximum_desired_capacity_d,1593desired_capacity_upper_bound);15941595// We can now safely turn them into size_t's.1596size_t minimum_desired_capacity = (size_t) minimum_desired_capacity_d;1597size_t maximum_desired_capacity = (size_t) maximum_desired_capacity_d;15981599// This assert only makes sense here, before we adjust them1600// with respect to the min and max heap size.1601assert(minimum_desired_capacity <= maximum_desired_capacity,1602err_msg("minimum_desired_capacity = " SIZE_FORMAT ", "1603"maximum_desired_capacity = " SIZE_FORMAT,1604minimum_desired_capacity, maximum_desired_capacity));16051606// Should not be greater than the heap max size. No need to adjust1607// it with respect to the heap min size as it's a lower bound (i.e.,1608// we'll try to make the capacity larger than it, not smaller).1609minimum_desired_capacity = MIN2(minimum_desired_capacity, max_heap_size);1610// Should not be less than the heap min size. No need to adjust it1611// with respect to the heap max size as it's an upper bound (i.e.,1612// we'll try to make the capacity smaller than it, not greater).1613maximum_desired_capacity = MAX2(maximum_desired_capacity, min_heap_size);16141615if (capacity_after_gc < minimum_desired_capacity) {1616// Don't expand unless it's significant1617size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;1618ergo_verbose4(ErgoHeapSizing,1619"attempt heap expansion",1620ergo_format_reason("capacity lower than "1621"min desired capacity after Full GC")1622ergo_format_byte("capacity")1623ergo_format_byte("occupancy")1624ergo_format_byte_perc("min desired capacity"),1625capacity_after_gc, used_after_gc,1626minimum_desired_capacity, (double) MinHeapFreeRatio);1627expand(expand_bytes);16281629// No expansion, now see if we want to shrink1630} else if (capacity_after_gc > maximum_desired_capacity) {1631// Capacity too large, compute shrinking size1632size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;1633ergo_verbose4(ErgoHeapSizing,1634"attempt heap shrinking",1635ergo_format_reason("capacity higher than "1636"max desired capacity after Full GC")1637ergo_format_byte("capacity")1638ergo_format_byte("occupancy")1639ergo_format_byte_perc("max desired capacity"),1640capacity_after_gc, used_after_gc,1641maximum_desired_capacity, (double) MaxHeapFreeRatio);1642shrink(shrink_bytes);1643}1644}164516461647HeapWord*1648G1CollectedHeap::satisfy_failed_allocation(size_t word_size,1649AllocationContext_t context,1650bool* succeeded) {1651assert_at_safepoint(true /* should_be_vm_thread */);16521653*succeeded = true;1654// Let's attempt the allocation first.1655HeapWord* result =1656attempt_allocation_at_safepoint(word_size,1657context,1658false /* expect_null_mutator_alloc_region */);1659if (result != NULL) {1660assert(*succeeded, "sanity");1661return result;1662}16631664// In a G1 heap, we're supposed to keep allocation from failing by1665// incremental pauses. Therefore, at least for now, we'll favor1666// expansion over collection. (This might change in the future if we can1667// do something smarter than full collection to satisfy a failed alloc.)1668result = expand_and_allocate(word_size, context);1669if (result != NULL) {1670assert(*succeeded, "sanity");1671return result;1672}16731674// Expansion didn't work, we'll try to do a Full GC.1675bool gc_succeeded = do_collection(false, /* explicit_gc */1676false, /* clear_all_soft_refs */1677word_size);1678if (!gc_succeeded) {1679*succeeded = false;1680return NULL;1681}16821683// Retry the allocation1684result = attempt_allocation_at_safepoint(word_size,1685context,1686true /* expect_null_mutator_alloc_region */);1687if (result != NULL) {1688assert(*succeeded, "sanity");1689return result;1690}16911692// Then, try a Full GC that will collect all soft references.1693gc_succeeded = do_collection(false, /* explicit_gc */1694true, /* clear_all_soft_refs */1695word_size);1696if (!gc_succeeded) {1697*succeeded = false;1698return NULL;1699}17001701// Retry the allocation once more1702result = attempt_allocation_at_safepoint(word_size,1703context,1704true /* expect_null_mutator_alloc_region */);1705if (result != NULL) {1706assert(*succeeded, "sanity");1707return result;1708}17091710assert(!collector_policy()->should_clear_all_soft_refs(),1711"Flag should have been handled and cleared prior to this point");17121713// What else? We might try synchronous finalization later. If the total1714// space available is large enough for the allocation, then a more1715// complete compaction phase than we've tried so far might be1716// appropriate.1717assert(*succeeded, "sanity");1718return NULL;1719}17201721// Attempting to expand the heap sufficiently1722// to support an allocation of the given "word_size". If1723// successful, perform the allocation and return the address of the1724// allocated block, or else "NULL".17251726HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size, AllocationContext_t context) {1727assert_at_safepoint(true /* should_be_vm_thread */);17281729verify_region_sets_optional();17301731size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);1732ergo_verbose1(ErgoHeapSizing,1733"attempt heap expansion",1734ergo_format_reason("allocation request failed")1735ergo_format_byte("allocation request"),1736word_size * HeapWordSize);1737if (expand(expand_bytes)) {1738_hrm.verify_optional();1739verify_region_sets_optional();1740return attempt_allocation_at_safepoint(word_size,1741context,1742false /* expect_null_mutator_alloc_region */);1743}1744return NULL;1745}17461747bool G1CollectedHeap::expand(size_t expand_bytes) {1748size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);1749aligned_expand_bytes = align_size_up(aligned_expand_bytes,1750HeapRegion::GrainBytes);1751ergo_verbose2(ErgoHeapSizing,1752"expand the heap",1753ergo_format_byte("requested expansion amount")1754ergo_format_byte("attempted expansion amount"),1755expand_bytes, aligned_expand_bytes);17561757if (is_maximal_no_gc()) {1758ergo_verbose0(ErgoHeapSizing,1759"did not expand the heap",1760ergo_format_reason("heap already fully expanded"));1761return false;1762}17631764uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes);1765assert(regions_to_expand > 0, "Must expand by at least one region");17661767uint expanded_by = _hrm.expand_by(regions_to_expand);17681769if (expanded_by > 0) {1770size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes;1771assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");1772g1_policy()->record_new_heap_size(num_regions());1773} else {1774ergo_verbose0(ErgoHeapSizing,1775"did not expand the heap",1776ergo_format_reason("heap expansion operation failed"));1777// The expansion of the virtual storage space was unsuccessful.1778// Let's see if it was because we ran out of swap.1779if (G1ExitOnExpansionFailure &&1780_hrm.available() >= regions_to_expand) {1781// We had head room...1782vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");1783}1784}1785return regions_to_expand > 0;1786}17871788void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {1789size_t aligned_shrink_bytes =1790ReservedSpace::page_align_size_down(shrink_bytes);1791aligned_shrink_bytes = align_size_down(aligned_shrink_bytes,1792HeapRegion::GrainBytes);1793uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);17941795uint num_regions_removed = _hrm.shrink_by(num_regions_to_remove);1796size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;17971798ergo_verbose3(ErgoHeapSizing,1799"shrink the heap",1800ergo_format_byte("requested shrinking amount")1801ergo_format_byte("aligned shrinking amount")1802ergo_format_byte("attempted shrinking amount"),1803shrink_bytes, aligned_shrink_bytes, shrunk_bytes);1804if (num_regions_removed > 0) {1805g1_policy()->record_new_heap_size(num_regions());1806} else {1807ergo_verbose0(ErgoHeapSizing,1808"did not shrink the heap",1809ergo_format_reason("heap shrinking operation failed"));1810}1811}18121813void G1CollectedHeap::shrink(size_t shrink_bytes) {1814verify_region_sets_optional();18151816// We should only reach here at the end of a Full GC which means we1817// should not not be holding to any GC alloc regions. The method1818// below will make sure of that and do any remaining clean up.1819_allocator->abandon_gc_alloc_regions();18201821// Instead of tearing down / rebuilding the free lists here, we1822// could instead use the remove_all_pending() method on free_list to1823// remove only the ones that we need to remove.1824tear_down_region_sets(true /* free_list_only */);1825shrink_helper(shrink_bytes);1826rebuild_region_sets(true /* free_list_only */);18271828_hrm.verify_optional();1829verify_region_sets_optional();1830}18311832// Public methods.18331834#ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away1835#pragma warning( disable:4355 ) // 'this' : used in base member initializer list1836#endif // _MSC_VER183718381839G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :1840SharedHeap(policy_),1841_g1_policy(policy_),1842_dirty_card_queue_set(false),1843_into_cset_dirty_card_queue_set(false),1844_is_alive_closure_cm(this),1845_is_alive_closure_stw(this),1846_ref_processor_cm(NULL),1847_ref_processor_stw(NULL),1848_bot_shared(NULL),1849_evac_failure_scan_stack(NULL),1850_mark_in_progress(false),1851_cg1r(NULL),1852_g1mm(NULL),1853_refine_cte_cl(NULL),1854_full_collection(false),1855_secondary_free_list("Secondary Free List", new SecondaryFreeRegionListMtSafeChecker()),1856_old_set("Old Set", false /* humongous */, new OldRegionSetMtSafeChecker()),1857_humongous_set("Master Humongous Set", true /* humongous */, new HumongousRegionSetMtSafeChecker()),1858_humongous_reclaim_candidates(),1859_has_humongous_reclaim_candidates(false),1860_free_regions_coming(false),1861_young_list(new YoungList(this)),1862_gc_time_stamp(0),1863_survivor_plab_stats(YoungPLABSize, PLABWeight),1864_old_plab_stats(OldPLABSize, PLABWeight),1865_expand_heap_after_alloc_failure(true),1866_surviving_young_words(NULL),1867_old_marking_cycles_started(0),1868_old_marking_cycles_completed(0),1869_concurrent_cycle_started(false),1870_heap_summary_sent(false),1871_in_cset_fast_test(),1872_dirty_cards_region_list(NULL),1873_worker_cset_start_region(NULL),1874_worker_cset_start_region_time_stamp(NULL),1875_gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),1876_gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),1877_gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),1878_gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) G1OldTracer()) {18791880_g1h = this;18811882_allocator = G1Allocator::create_allocator(_g1h);1883_humongous_object_threshold_in_words = HeapRegion::GrainWords / 2;18841885int n_queues = MAX2((int)ParallelGCThreads, 1);1886_task_queues = new RefToScanQueueSet(n_queues);18871888uint n_rem_sets = HeapRegionRemSet::num_par_rem_sets();1889assert(n_rem_sets > 0, "Invariant.");18901891_worker_cset_start_region = NEW_C_HEAP_ARRAY(HeapRegion*, n_queues, mtGC);1892_worker_cset_start_region_time_stamp = NEW_C_HEAP_ARRAY(uint, n_queues, mtGC);1893_evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);18941895for (int i = 0; i < n_queues; i++) {1896RefToScanQueue* q = new RefToScanQueue();1897q->initialize();1898_task_queues->register_queue(i, q);1899::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();1900}1901clear_cset_start_regions();19021903// Initialize the G1EvacuationFailureALot counters and flags.1904NOT_PRODUCT(reset_evacuation_should_fail();)19051906guarantee(_task_queues != NULL, "task_queues allocation failure.");1907}19081909G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description,1910size_t size,1911size_t translation_factor) {1912size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1);1913// Allocate a new reserved space, preferring to use large pages.1914ReservedSpace rs(size, preferred_page_size);1915G1RegionToSpaceMapper* result =1916G1RegionToSpaceMapper::create_mapper(rs,1917size,1918rs.alignment(),1919HeapRegion::GrainBytes,1920translation_factor,1921mtGC);1922if (TracePageSizes) {1923gclog_or_tty->print_cr("G1 '%s': pg_sz=" SIZE_FORMAT " base=" PTR_FORMAT " size=" SIZE_FORMAT " alignment=" SIZE_FORMAT " reqsize=" SIZE_FORMAT,1924description, preferred_page_size, p2i(rs.base()), rs.size(), rs.alignment(), size);1925}1926return result;1927}19281929jint G1CollectedHeap::initialize() {1930CollectedHeap::pre_initialize();1931os::enable_vtime();19321933G1Log::init();19341935// Necessary to satisfy locking discipline assertions.19361937MutexLocker x(Heap_lock);19381939// We have to initialize the printer before committing the heap, as1940// it will be used then.1941_hr_printer.set_active(G1PrintHeapRegions);19421943// While there are no constraints in the GC code that HeapWordSize1944// be any particular value, there are multiple other areas in the1945// system which believe this to be true (e.g. oop->object_size in some1946// cases incorrectly returns the size in wordSize units rather than1947// HeapWordSize).1948guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");19491950size_t init_byte_size = collector_policy()->initial_heap_byte_size();1951size_t max_byte_size = collector_policy()->max_heap_byte_size();1952size_t heap_alignment = collector_policy()->heap_alignment();19531954// Ensure that the sizes are properly aligned.1955Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");1956Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");1957Universe::check_alignment(max_byte_size, heap_alignment, "g1 heap");19581959_refine_cte_cl = new RefineCardTableEntryClosure();19601961_cg1r = new ConcurrentG1Refine(this, _refine_cte_cl);19621963// Reserve the maximum.19641965// When compressed oops are enabled, the preferred heap base1966// is calculated by subtracting the requested size from the1967// 32Gb boundary and using the result as the base address for1968// heap reservation. If the requested size is not aligned to1969// HeapRegion::GrainBytes (i.e. the alignment that is passed1970// into the ReservedHeapSpace constructor) then the actual1971// base of the reserved heap may end up differing from the1972// address that was requested (i.e. the preferred heap base).1973// If this happens then we could end up using a non-optimal1974// compressed oops mode.19751976ReservedSpace heap_rs = Universe::reserve_heap(max_byte_size,1977heap_alignment);19781979// It is important to do this in a way such that concurrent readers can't1980// temporarily think something is in the heap. (I've actually seen this1981// happen in asserts: DLD.)1982_reserved.set_word_size(0);1983_reserved.set_start((HeapWord*)heap_rs.base());1984_reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size()));19851986// Create the gen rem set (and barrier set) for the entire reserved region.1987_rem_set = collector_policy()->create_rem_set(_reserved, 2);1988set_barrier_set(rem_set()->bs());1989if (!barrier_set()->is_a(BarrierSet::G1SATBCTLogging)) {1990vm_exit_during_initialization("G1 requires a G1SATBLoggingCardTableModRefBS");1991return JNI_ENOMEM;1992}19931994// Also create a G1 rem set.1995_g1_rem_set = new G1RemSet(this, g1_barrier_set());19961997// Carve out the G1 part of the heap.19981999ReservedSpace g1_rs = heap_rs.first_part(max_byte_size);2000G1RegionToSpaceMapper* heap_storage =2001G1RegionToSpaceMapper::create_mapper(g1_rs,2002g1_rs.size(),2003UseLargePages ? os::large_page_size() : os::vm_page_size(),2004HeapRegion::GrainBytes,20051,2006mtJavaHeap);2007heap_storage->set_mapping_changed_listener(&_listener);20082009// Create storage for the BOT, card table, card counts table (hot card cache) and the bitmaps.2010G1RegionToSpaceMapper* bot_storage =2011create_aux_memory_mapper("Block offset table",2012G1BlockOffsetSharedArray::compute_size(g1_rs.size() / HeapWordSize),2013G1BlockOffsetSharedArray::N_bytes);20142015ReservedSpace cardtable_rs(G1SATBCardTableLoggingModRefBS::compute_size(g1_rs.size() / HeapWordSize));2016G1RegionToSpaceMapper* cardtable_storage =2017create_aux_memory_mapper("Card table",2018G1SATBCardTableLoggingModRefBS::compute_size(g1_rs.size() / HeapWordSize),2019G1BlockOffsetSharedArray::N_bytes);20202021G1RegionToSpaceMapper* card_counts_storage =2022create_aux_memory_mapper("Card counts table",2023G1BlockOffsetSharedArray::compute_size(g1_rs.size() / HeapWordSize),2024G1BlockOffsetSharedArray::N_bytes);20252026size_t bitmap_size = CMBitMap::compute_size(g1_rs.size());2027G1RegionToSpaceMapper* prev_bitmap_storage =2028create_aux_memory_mapper("Prev Bitmap", bitmap_size, CMBitMap::mark_distance());2029G1RegionToSpaceMapper* next_bitmap_storage =2030create_aux_memory_mapper("Next Bitmap", bitmap_size, CMBitMap::mark_distance());20312032_hrm.initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage);2033g1_barrier_set()->initialize(cardtable_storage);2034// Do later initialization work for concurrent refinement.2035_cg1r->init(card_counts_storage);20362037// 6843694 - ensure that the maximum region index can fit2038// in the remembered set structures.2039const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;2040guarantee((max_regions() - 1) <= max_region_idx, "too many regions");20412042size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;2043guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");2044guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,2045"too many cards per region");20462047FreeRegionList::set_unrealistically_long_length(max_regions() + 1);20482049_bot_shared = new G1BlockOffsetSharedArray(_reserved, bot_storage);20502051_g1h = this;20522053{2054HeapWord* start = _hrm.reserved().start();2055HeapWord* end = _hrm.reserved().end();2056size_t granularity = HeapRegion::GrainBytes;20572058_in_cset_fast_test.initialize(start, end, granularity);2059_humongous_reclaim_candidates.initialize(start, end, granularity);2060}20612062// Create the ConcurrentMark data structure and thread.2063// (Must do this late, so that "max_regions" is defined.)2064_cm = new ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage);2065if (_cm == NULL || !_cm->completed_initialization()) {2066vm_shutdown_during_initialization("Could not create/initialize ConcurrentMark");2067return JNI_ENOMEM;2068}2069_cmThread = _cm->cmThread();20702071// Initialize the from_card cache structure of HeapRegionRemSet.2072HeapRegionRemSet::init_heap(max_regions());20732074// Now expand into the initial heap size.2075if (!expand(init_byte_size)) {2076vm_shutdown_during_initialization("Failed to allocate initial heap.");2077return JNI_ENOMEM;2078}20792080// Perform any initialization actions delegated to the policy.2081g1_policy()->init();20822083JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,2084SATB_Q_FL_lock,2085G1SATBProcessCompletedThreshold,2086Shared_SATB_Q_lock);20872088JavaThread::dirty_card_queue_set().initialize(_refine_cte_cl,2089DirtyCardQ_CBL_mon,2090DirtyCardQ_FL_lock,2091concurrent_g1_refine()->yellow_zone(),2092concurrent_g1_refine()->red_zone(),2093Shared_DirtyCardQ_lock);20942095dirty_card_queue_set().initialize(NULL, // Should never be called by the Java code2096DirtyCardQ_CBL_mon,2097DirtyCardQ_FL_lock,2098-1, // never trigger processing2099-1, // no limit on length2100Shared_DirtyCardQ_lock,2101&JavaThread::dirty_card_queue_set());21022103// Initialize the card queue set used to hold cards containing2104// references into the collection set.2105_into_cset_dirty_card_queue_set.initialize(NULL, // Should never be called by the Java code2106DirtyCardQ_CBL_mon,2107DirtyCardQ_FL_lock,2108-1, // never trigger processing2109-1, // no limit on length2110Shared_DirtyCardQ_lock,2111&JavaThread::dirty_card_queue_set());21122113// In case we're keeping closure specialization stats, initialize those2114// counts and that mechanism.2115SpecializationStats::clear();21162117// Here we allocate the dummy HeapRegion that is required by the2118// G1AllocRegion class.2119HeapRegion* dummy_region = _hrm.get_dummy_region();21202121// We'll re-use the same region whether the alloc region will2122// require BOT updates or not and, if it doesn't, then a non-young2123// region will complain that it cannot support allocations without2124// BOT updates. So we'll tag the dummy region as eden to avoid that.2125dummy_region->set_eden();2126// Make sure it's full.2127dummy_region->set_top(dummy_region->end());2128G1AllocRegion::setup(this, dummy_region);21292130_allocator->init_mutator_alloc_region();21312132// Do create of the monitoring and management support so that2133// values in the heap have been properly initialized.2134_g1mm = new G1MonitoringSupport(this);21352136G1StringDedup::initialize();21372138return JNI_OK;2139}21402141void G1CollectedHeap::stop() {2142// Stop all concurrent threads. We do this to make sure these threads2143// do not continue to execute and access resources (e.g. gclog_or_tty)2144// that are destroyed during shutdown.2145_cg1r->stop();2146_cmThread->stop();2147if (G1StringDedup::is_enabled()) {2148G1StringDedup::stop();2149}2150}21512152size_t G1CollectedHeap::conservative_max_heap_alignment() {2153return HeapRegion::max_region_size();2154}21552156void G1CollectedHeap::ref_processing_init() {2157// Reference processing in G1 currently works as follows:2158//2159// * There are two reference processor instances. One is2160// used to record and process discovered references2161// during concurrent marking; the other is used to2162// record and process references during STW pauses2163// (both full and incremental).2164// * Both ref processors need to 'span' the entire heap as2165// the regions in the collection set may be dotted around.2166//2167// * For the concurrent marking ref processor:2168// * Reference discovery is enabled at initial marking.2169// * Reference discovery is disabled and the discovered2170// references processed etc during remarking.2171// * Reference discovery is MT (see below).2172// * Reference discovery requires a barrier (see below).2173// * Reference processing may or may not be MT2174// (depending on the value of ParallelRefProcEnabled2175// and ParallelGCThreads).2176// * A full GC disables reference discovery by the CM2177// ref processor and abandons any entries on it's2178// discovered lists.2179//2180// * For the STW processor:2181// * Non MT discovery is enabled at the start of a full GC.2182// * Processing and enqueueing during a full GC is non-MT.2183// * During a full GC, references are processed after marking.2184//2185// * Discovery (may or may not be MT) is enabled at the start2186// of an incremental evacuation pause.2187// * References are processed near the end of a STW evacuation pause.2188// * For both types of GC:2189// * Discovery is atomic - i.e. not concurrent.2190// * Reference discovery will not need a barrier.21912192SharedHeap::ref_processing_init();2193MemRegion mr = reserved_region();21942195// Concurrent Mark ref processor2196_ref_processor_cm =2197new ReferenceProcessor(mr, // span2198ParallelRefProcEnabled && (ParallelGCThreads > 1),2199// mt processing2200(int) ParallelGCThreads,2201// degree of mt processing2202(ParallelGCThreads > 1) || (ConcGCThreads > 1),2203// mt discovery2204(int) MAX2(ParallelGCThreads, ConcGCThreads),2205// degree of mt discovery2206false,2207// Reference discovery is not atomic2208&_is_alive_closure_cm);2209// is alive closure2210// (for efficiency/performance)22112212// STW ref processor2213_ref_processor_stw =2214new ReferenceProcessor(mr, // span2215ParallelRefProcEnabled && (ParallelGCThreads > 1),2216// mt processing2217MAX2((int)ParallelGCThreads, 1),2218// degree of mt processing2219(ParallelGCThreads > 1),2220// mt discovery2221MAX2((int)ParallelGCThreads, 1),2222// degree of mt discovery2223true,2224// Reference discovery is atomic2225&_is_alive_closure_stw);2226// is alive closure2227// (for efficiency/performance)2228}22292230size_t G1CollectedHeap::capacity() const {2231return _hrm.length() * HeapRegion::GrainBytes;2232}22332234void G1CollectedHeap::reset_gc_time_stamps(HeapRegion* hr) {2235assert(!hr->continuesHumongous(), "pre-condition");2236hr->reset_gc_time_stamp();2237if (hr->startsHumongous()) {2238uint first_index = hr->hrm_index() + 1;2239uint last_index = hr->last_hc_index();2240for (uint i = first_index; i < last_index; i += 1) {2241HeapRegion* chr = region_at(i);2242assert(chr->continuesHumongous(), "sanity");2243chr->reset_gc_time_stamp();2244}2245}2246}22472248#ifndef PRODUCT2249class CheckGCTimeStampsHRClosure : public HeapRegionClosure {2250private:2251unsigned _gc_time_stamp;2252bool _failures;22532254public:2255CheckGCTimeStampsHRClosure(unsigned gc_time_stamp) :2256_gc_time_stamp(gc_time_stamp), _failures(false) { }22572258virtual bool doHeapRegion(HeapRegion* hr) {2259unsigned region_gc_time_stamp = hr->get_gc_time_stamp();2260if (_gc_time_stamp != region_gc_time_stamp) {2261gclog_or_tty->print_cr("Region " HR_FORMAT " has GC time stamp = %d, "2262"expected %d", HR_FORMAT_PARAMS(hr),2263region_gc_time_stamp, _gc_time_stamp);2264_failures = true;2265}2266return false;2267}22682269bool failures() { return _failures; }2270};22712272void G1CollectedHeap::check_gc_time_stamps() {2273CheckGCTimeStampsHRClosure cl(_gc_time_stamp);2274heap_region_iterate(&cl);2275guarantee(!cl.failures(), "all GC time stamps should have been reset");2276}2277#endif // PRODUCT22782279void G1CollectedHeap::iterate_dirty_card_closure(CardTableEntryClosure* cl,2280DirtyCardQueue* into_cset_dcq,2281bool concurrent,2282uint worker_i) {2283// Clean cards in the hot card cache2284G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();2285hot_card_cache->drain(worker_i, g1_rem_set(), into_cset_dcq);22862287DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();2288size_t n_completed_buffers = 0;2289while (dcqs.apply_closure_to_completed_buffer(cl, worker_i, 0, true)) {2290n_completed_buffers++;2291}2292g1_policy()->phase_times()->record_thread_work_item(G1GCPhaseTimes::UpdateRS, worker_i, n_completed_buffers);2293dcqs.clear_n_completed_buffers();2294assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!");2295}229622972298// Computes the sum of the storage used by the various regions.2299size_t G1CollectedHeap::used() const {2300return _allocator->used();2301}23022303size_t G1CollectedHeap::used_unlocked() const {2304return _allocator->used_unlocked();2305}23062307class SumUsedClosure: public HeapRegionClosure {2308size_t _used;2309public:2310SumUsedClosure() : _used(0) {}2311bool doHeapRegion(HeapRegion* r) {2312if (!r->continuesHumongous()) {2313_used += r->used();2314}2315return false;2316}2317size_t result() { return _used; }2318};23192320size_t G1CollectedHeap::recalculate_used() const {2321double recalculate_used_start = os::elapsedTime();23222323SumUsedClosure blk;2324heap_region_iterate(&blk);23252326g1_policy()->phase_times()->record_evac_fail_recalc_used_time((os::elapsedTime() - recalculate_used_start) * 1000.0);2327return blk.result();2328}23292330bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {2331switch (cause) {2332case GCCause::_gc_locker: return GCLockerInvokesConcurrent;2333case GCCause::_java_lang_system_gc: return ExplicitGCInvokesConcurrent;2334case GCCause::_g1_humongous_allocation: return true;2335case GCCause::_update_allocation_context_stats_inc: return true;2336case GCCause::_wb_conc_mark: return true;2337default: return false;2338}2339}23402341#ifndef PRODUCT2342void G1CollectedHeap::allocate_dummy_regions() {2343// Let's fill up most of the region2344size_t word_size = HeapRegion::GrainWords - 1024;2345// And as a result the region we'll allocate will be humongous.2346guarantee(isHumongous(word_size), "sanity");23472348for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {2349// Let's use the existing mechanism for the allocation2350HeapWord* dummy_obj = humongous_obj_allocate(word_size,2351AllocationContext::system());2352if (dummy_obj != NULL) {2353MemRegion mr(dummy_obj, word_size);2354CollectedHeap::fill_with_object(mr);2355} else {2356// If we can't allocate once, we probably cannot allocate2357// again. Let's get out of the loop.2358break;2359}2360}2361}2362#endif // !PRODUCT23632364void G1CollectedHeap::increment_old_marking_cycles_started() {2365assert(_old_marking_cycles_started == _old_marking_cycles_completed ||2366_old_marking_cycles_started == _old_marking_cycles_completed + 1,2367err_msg("Wrong marking cycle count (started: %d, completed: %d)",2368_old_marking_cycles_started, _old_marking_cycles_completed));23692370_old_marking_cycles_started++;2371}23722373void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent) {2374MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag);23752376// We assume that if concurrent == true, then the caller is a2377// concurrent thread that was joined the Suspendible Thread2378// Set. If there's ever a cheap way to check this, we should add an2379// assert here.23802381// Given that this method is called at the end of a Full GC or of a2382// concurrent cycle, and those can be nested (i.e., a Full GC can2383// interrupt a concurrent cycle), the number of full collections2384// completed should be either one (in the case where there was no2385// nesting) or two (when a Full GC interrupted a concurrent cycle)2386// behind the number of full collections started.23872388// This is the case for the inner caller, i.e. a Full GC.2389assert(concurrent ||2390(_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||2391(_old_marking_cycles_started == _old_marking_cycles_completed + 2),2392err_msg("for inner caller (Full GC): _old_marking_cycles_started = %u "2393"is inconsistent with _old_marking_cycles_completed = %u",2394_old_marking_cycles_started, _old_marking_cycles_completed));23952396// This is the case for the outer caller, i.e. the concurrent cycle.2397assert(!concurrent ||2398(_old_marking_cycles_started == _old_marking_cycles_completed + 1),2399err_msg("for outer caller (concurrent cycle): "2400"_old_marking_cycles_started = %u "2401"is inconsistent with _old_marking_cycles_completed = %u",2402_old_marking_cycles_started, _old_marking_cycles_completed));24032404_old_marking_cycles_completed += 1;24052406// We need to clear the "in_progress" flag in the CM thread before2407// we wake up any waiters (especially when ExplicitInvokesConcurrent2408// is set) so that if a waiter requests another System.gc() it doesn't2409// incorrectly see that a marking cycle is still in progress.2410if (concurrent) {2411_cmThread->set_idle();2412}24132414// This notify_all() will ensure that a thread that called2415// System.gc() with (with ExplicitGCInvokesConcurrent set or not)2416// and it's waiting for a full GC to finish will be woken up. It is2417// waiting in VM_G1IncCollectionPause::doit_epilogue().2418FullGCCount_lock->notify_all();2419}24202421void G1CollectedHeap::register_concurrent_cycle_start(const Ticks& start_time) {2422_concurrent_cycle_started = true;2423_gc_timer_cm->register_gc_start(start_time);24242425_gc_tracer_cm->report_gc_start(gc_cause(), _gc_timer_cm->gc_start());2426trace_heap_before_gc(_gc_tracer_cm);2427}24282429void G1CollectedHeap::register_concurrent_cycle_end() {2430if (_concurrent_cycle_started) {2431if (_cm->has_aborted()) {2432_gc_tracer_cm->report_concurrent_mode_failure();2433}24342435_gc_timer_cm->register_gc_end();2436_gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions());24372438// Clear state variables to prepare for the next concurrent cycle.2439_concurrent_cycle_started = false;2440_heap_summary_sent = false;2441}2442}24432444void G1CollectedHeap::trace_heap_after_concurrent_cycle() {2445if (_concurrent_cycle_started) {2446// This function can be called when:2447// the cleanup pause is run2448// the concurrent cycle is aborted before the cleanup pause.2449// the concurrent cycle is aborted after the cleanup pause,2450// but before the concurrent cycle end has been registered.2451// Make sure that we only send the heap information once.2452if (!_heap_summary_sent) {2453trace_heap_after_gc(_gc_tracer_cm);2454_heap_summary_sent = true;2455}2456}2457}24582459G1YCType G1CollectedHeap::yc_type() {2460bool is_young = g1_policy()->gcs_are_young();2461bool is_initial_mark = g1_policy()->during_initial_mark_pause();2462bool is_during_mark = mark_in_progress();24632464if (is_initial_mark) {2465return InitialMark;2466} else if (is_during_mark) {2467return DuringMark;2468} else if (is_young) {2469return Normal;2470} else {2471return Mixed;2472}2473}24742475void G1CollectedHeap::collect(GCCause::Cause cause) {2476assert_heap_not_locked();24772478uint gc_count_before;2479uint old_marking_count_before;2480uint full_gc_count_before;2481bool retry_gc;24822483do {2484retry_gc = false;24852486{2487MutexLocker ml(Heap_lock);24882489// Read the GC count while holding the Heap_lock2490gc_count_before = total_collections();2491full_gc_count_before = total_full_collections();2492old_marking_count_before = _old_marking_cycles_started;2493}24942495if (should_do_concurrent_full_gc(cause)) {2496// Schedule an initial-mark evacuation pause that will start a2497// concurrent cycle. We're setting word_size to 0 which means that2498// we are not requesting a post-GC allocation.2499VM_G1IncCollectionPause op(gc_count_before,25000, /* word_size */2501true, /* should_initiate_conc_mark */2502g1_policy()->max_pause_time_ms(),2503cause);2504op.set_allocation_context(AllocationContext::current());25052506VMThread::execute(&op);2507if (!op.pause_succeeded()) {2508if (old_marking_count_before == _old_marking_cycles_started) {2509retry_gc = op.should_retry_gc();2510} else {2511// A Full GC happened while we were trying to schedule the2512// initial-mark GC. No point in starting a new cycle given2513// that the whole heap was collected anyway.2514}25152516if (retry_gc) {2517if (GC_locker::is_active_and_needs_gc()) {2518GC_locker::stall_until_clear();2519}2520}2521}2522} else if (GC_locker::should_discard(cause, gc_count_before)) {2523// Return to be consistent with VMOp failure due to another2524// collection slipping in after our gc_count but before our2525// request is processed. _gc_locker collections upgraded by2526// GCLockerInvokesConcurrent are handled above and never discarded.2527return;2528} else {2529if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc2530DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {25312532// Schedule a standard evacuation pause. We're setting word_size2533// to 0 which means that we are not requesting a post-GC allocation.2534VM_G1IncCollectionPause op(gc_count_before,25350, /* word_size */2536false, /* should_initiate_conc_mark */2537g1_policy()->max_pause_time_ms(),2538cause);2539VMThread::execute(&op);2540} else {2541// Schedule a Full GC.2542VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause);2543VMThread::execute(&op);2544}2545}2546} while (retry_gc);2547}25482549bool G1CollectedHeap::is_in(const void* p) const {2550if (_hrm.reserved().contains(p)) {2551// Given that we know that p is in the reserved space,2552// heap_region_containing_raw() should successfully2553// return the containing region.2554HeapRegion* hr = heap_region_containing_raw(p);2555return hr->is_in(p);2556} else {2557return false;2558}2559}25602561#ifdef ASSERT2562bool G1CollectedHeap::is_in_exact(const void* p) const {2563bool contains = reserved_region().contains(p);2564bool available = _hrm.is_available(addr_to_region((HeapWord*)p));2565if (contains && available) {2566return true;2567} else {2568return false;2569}2570}2571#endif25722573// Iteration functions.25742575// Applies an ExtendedOopClosure onto all references of objects within a HeapRegion.25762577class IterateOopClosureRegionClosure: public HeapRegionClosure {2578ExtendedOopClosure* _cl;2579public:2580IterateOopClosureRegionClosure(ExtendedOopClosure* cl) : _cl(cl) {}2581bool doHeapRegion(HeapRegion* r) {2582if (!r->continuesHumongous()) {2583r->oop_iterate(_cl);2584}2585return false;2586}2587};25882589void G1CollectedHeap::oop_iterate(ExtendedOopClosure* cl) {2590IterateOopClosureRegionClosure blk(cl);2591heap_region_iterate(&blk);2592}25932594// Iterates an ObjectClosure over all objects within a HeapRegion.25952596class IterateObjectClosureRegionClosure: public HeapRegionClosure {2597ObjectClosure* _cl;2598public:2599IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}2600bool doHeapRegion(HeapRegion* r) {2601if (! r->continuesHumongous()) {2602r->object_iterate(_cl);2603}2604return false;2605}2606};26072608void G1CollectedHeap::object_iterate(ObjectClosure* cl) {2609IterateObjectClosureRegionClosure blk(cl);2610heap_region_iterate(&blk);2611}26122613// Calls a SpaceClosure on a HeapRegion.26142615class SpaceClosureRegionClosure: public HeapRegionClosure {2616SpaceClosure* _cl;2617public:2618SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {}2619bool doHeapRegion(HeapRegion* r) {2620_cl->do_space(r);2621return false;2622}2623};26242625void G1CollectedHeap::space_iterate(SpaceClosure* cl) {2626SpaceClosureRegionClosure blk(cl);2627heap_region_iterate(&blk);2628}26292630void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {2631_hrm.iterate(cl);2632}26332634void2635G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,2636uint worker_id,2637uint num_workers,2638jint claim_value) const {2639_hrm.par_iterate(cl, worker_id, num_workers, claim_value);2640}26412642class ResetClaimValuesClosure: public HeapRegionClosure {2643public:2644bool doHeapRegion(HeapRegion* r) {2645r->set_claim_value(HeapRegion::InitialClaimValue);2646return false;2647}2648};26492650void G1CollectedHeap::reset_heap_region_claim_values() {2651ResetClaimValuesClosure blk;2652heap_region_iterate(&blk);2653}26542655void G1CollectedHeap::reset_cset_heap_region_claim_values() {2656ResetClaimValuesClosure blk;2657collection_set_iterate(&blk);2658}26592660#ifdef ASSERT2661// This checks whether all regions in the heap have the correct claim2662// value. I also piggy-backed on this a check to ensure that the2663// humongous_start_region() information on "continues humongous"2664// regions is correct.26652666class CheckClaimValuesClosure : public HeapRegionClosure {2667private:2668jint _claim_value;2669uint _failures;2670HeapRegion* _sh_region;26712672public:2673CheckClaimValuesClosure(jint claim_value) :2674_claim_value(claim_value), _failures(0), _sh_region(NULL) { }2675bool doHeapRegion(HeapRegion* r) {2676if (r->claim_value() != _claim_value) {2677gclog_or_tty->print_cr("Region " HR_FORMAT ", "2678"claim value = %d, should be %d",2679HR_FORMAT_PARAMS(r),2680r->claim_value(), _claim_value);2681++_failures;2682}2683if (!r->isHumongous()) {2684_sh_region = NULL;2685} else if (r->startsHumongous()) {2686_sh_region = r;2687} else if (r->continuesHumongous()) {2688if (r->humongous_start_region() != _sh_region) {2689gclog_or_tty->print_cr("Region " HR_FORMAT ", "2690"HS = " PTR_FORMAT ", should be " PTR_FORMAT,2691HR_FORMAT_PARAMS(r),2692r->humongous_start_region(),2693_sh_region);2694++_failures;2695}2696}2697return false;2698}2699uint failures() { return _failures; }2700};27012702bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {2703CheckClaimValuesClosure cl(claim_value);2704heap_region_iterate(&cl);2705return cl.failures() == 0;2706}27072708class CheckClaimValuesInCSetHRClosure: public HeapRegionClosure {2709private:2710jint _claim_value;2711uint _failures;27122713public:2714CheckClaimValuesInCSetHRClosure(jint claim_value) :2715_claim_value(claim_value), _failures(0) { }27162717uint failures() { return _failures; }27182719bool doHeapRegion(HeapRegion* hr) {2720assert(hr->in_collection_set(), "how?");2721assert(!hr->isHumongous(), "H-region in CSet");2722if (hr->claim_value() != _claim_value) {2723gclog_or_tty->print_cr("CSet Region " HR_FORMAT ", "2724"claim value = %d, should be %d",2725HR_FORMAT_PARAMS(hr),2726hr->claim_value(), _claim_value);2727_failures += 1;2728}2729return false;2730}2731};27322733bool G1CollectedHeap::check_cset_heap_region_claim_values(jint claim_value) {2734CheckClaimValuesInCSetHRClosure cl(claim_value);2735collection_set_iterate(&cl);2736return cl.failures() == 0;2737}2738#endif // ASSERT27392740// Clear the cached CSet starting regions and (more importantly)2741// the time stamps. Called when we reset the GC time stamp.2742void G1CollectedHeap::clear_cset_start_regions() {2743assert(_worker_cset_start_region != NULL, "sanity");2744assert(_worker_cset_start_region_time_stamp != NULL, "sanity");27452746int n_queues = MAX2((int)ParallelGCThreads, 1);2747for (int i = 0; i < n_queues; i++) {2748_worker_cset_start_region[i] = NULL;2749_worker_cset_start_region_time_stamp[i] = 0;2750}2751}27522753// Given the id of a worker, obtain or calculate a suitable2754// starting region for iterating over the current collection set.2755HeapRegion* G1CollectedHeap::start_cset_region_for_worker(uint worker_i) {2756assert(get_gc_time_stamp() > 0, "should have been updated by now");27572758HeapRegion* result = NULL;2759unsigned gc_time_stamp = get_gc_time_stamp();27602761if (_worker_cset_start_region_time_stamp[worker_i] == gc_time_stamp) {2762// Cached starting region for current worker was set2763// during the current pause - so it's valid.2764// Note: the cached starting heap region may be NULL2765// (when the collection set is empty).2766result = _worker_cset_start_region[worker_i];2767assert(result == NULL || result->in_collection_set(), "sanity");2768return result;2769}27702771// The cached entry was not valid so let's calculate2772// a suitable starting heap region for this worker.27732774// We want the parallel threads to start their collection2775// set iteration at different collection set regions to2776// avoid contention.2777// If we have:2778// n collection set regions2779// p threads2780// Then thread t will start at region floor ((t * n) / p)27812782result = g1_policy()->collection_set();2783if (G1CollectedHeap::use_parallel_gc_threads()) {2784uint cs_size = g1_policy()->cset_region_length();2785uint active_workers = workers()->active_workers();2786assert(UseDynamicNumberOfGCThreads ||2787active_workers == workers()->total_workers(),2788"Unless dynamic should use total workers");27892790uint end_ind = (cs_size * worker_i) / active_workers;2791uint start_ind = 0;27922793if (worker_i > 0 &&2794_worker_cset_start_region_time_stamp[worker_i - 1] == gc_time_stamp) {2795// Previous workers starting region is valid2796// so let's iterate from there2797start_ind = (cs_size * (worker_i - 1)) / active_workers;2798OrderAccess::loadload();2799result = _worker_cset_start_region[worker_i - 1];2800}28012802for (uint i = start_ind; i < end_ind; i++) {2803result = result->next_in_collection_set();2804}2805}28062807// Note: the calculated starting heap region may be NULL2808// (when the collection set is empty).2809assert(result == NULL || result->in_collection_set(), "sanity");2810assert(_worker_cset_start_region_time_stamp[worker_i] != gc_time_stamp,2811"should be updated only once per pause");2812_worker_cset_start_region[worker_i] = result;2813OrderAccess::storestore();2814_worker_cset_start_region_time_stamp[worker_i] = gc_time_stamp;2815return result;2816}28172818void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {2819HeapRegion* r = g1_policy()->collection_set();2820while (r != NULL) {2821HeapRegion* next = r->next_in_collection_set();2822if (cl->doHeapRegion(r)) {2823cl->incomplete();2824return;2825}2826r = next;2827}2828}28292830void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,2831HeapRegionClosure *cl) {2832if (r == NULL) {2833// The CSet is empty so there's nothing to do.2834return;2835}28362837assert(r->in_collection_set(),2838"Start region must be a member of the collection set.");2839HeapRegion* cur = r;2840while (cur != NULL) {2841HeapRegion* next = cur->next_in_collection_set();2842if (cl->doHeapRegion(cur) && false) {2843cl->incomplete();2844return;2845}2846cur = next;2847}2848cur = g1_policy()->collection_set();2849while (cur != r) {2850HeapRegion* next = cur->next_in_collection_set();2851if (cl->doHeapRegion(cur) && false) {2852cl->incomplete();2853return;2854}2855cur = next;2856}2857}28582859HeapRegion* G1CollectedHeap::next_compaction_region(const HeapRegion* from) const {2860HeapRegion* result = _hrm.next_region_in_heap(from);2861while (result != NULL && result->isHumongous()) {2862result = _hrm.next_region_in_heap(result);2863}2864return result;2865}28662867Space* G1CollectedHeap::space_containing(const void* addr) const {2868return heap_region_containing(addr);2869}28702871HeapWord* G1CollectedHeap::block_start(const void* addr) const {2872Space* sp = space_containing(addr);2873return sp->block_start(addr);2874}28752876size_t G1CollectedHeap::block_size(const HeapWord* addr) const {2877Space* sp = space_containing(addr);2878return sp->block_size(addr);2879}28802881bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {2882Space* sp = space_containing(addr);2883return sp->block_is_obj(addr);2884}28852886bool G1CollectedHeap::supports_tlab_allocation() const {2887return true;2888}28892890size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {2891return (_g1_policy->young_list_target_length() - young_list()->survivor_length()) * HeapRegion::GrainBytes;2892}28932894size_t G1CollectedHeap::tlab_used(Thread* ignored) const {2895return young_list()->eden_used_bytes();2896}28972898// For G1 TLABs should not contain humongous objects, so the maximum TLAB size2899// must be smaller than the humongous object limit.2900size_t G1CollectedHeap::max_tlab_size() const {2901return align_size_down(_humongous_object_threshold_in_words - 1, MinObjAlignment);2902}29032904size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {2905// Return the remaining space in the cur alloc region, but not less than2906// the min TLAB size.29072908// Also, this value can be at most the humongous object threshold,2909// since we can't allow tlabs to grow big enough to accommodate2910// humongous objects.29112912HeapRegion* hr = _allocator->mutator_alloc_region(AllocationContext::current())->get();2913size_t max_tlab = max_tlab_size() * wordSize;2914if (hr == NULL) {2915return max_tlab;2916} else {2917return MIN2(MAX2(hr->free(), (size_t) MinTLABSize), max_tlab);2918}2919}29202921size_t G1CollectedHeap::max_capacity() const {2922return _hrm.reserved().byte_size();2923}29242925jlong G1CollectedHeap::millis_since_last_gc() {2926// assert(false, "NYI");2927return 0;2928}29292930void G1CollectedHeap::prepare_for_verify() {2931if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {2932ensure_parsability(false);2933}2934g1_rem_set()->prepare_for_verify();2935}29362937bool G1CollectedHeap::allocated_since_marking(oop obj, HeapRegion* hr,2938VerifyOption vo) {2939switch (vo) {2940case VerifyOption_G1UsePrevMarking:2941return hr->obj_allocated_since_prev_marking(obj);2942case VerifyOption_G1UseNextMarking:2943return hr->obj_allocated_since_next_marking(obj);2944case VerifyOption_G1UseMarkWord:2945return false;2946default:2947ShouldNotReachHere();2948}2949return false; // keep some compilers happy2950}29512952HeapWord* G1CollectedHeap::top_at_mark_start(HeapRegion* hr, VerifyOption vo) {2953switch (vo) {2954case VerifyOption_G1UsePrevMarking: return hr->prev_top_at_mark_start();2955case VerifyOption_G1UseNextMarking: return hr->next_top_at_mark_start();2956case VerifyOption_G1UseMarkWord: return NULL;2957default: ShouldNotReachHere();2958}2959return NULL; // keep some compilers happy2960}29612962bool G1CollectedHeap::is_marked(oop obj, VerifyOption vo) {2963switch (vo) {2964case VerifyOption_G1UsePrevMarking: return isMarkedPrev(obj);2965case VerifyOption_G1UseNextMarking: return isMarkedNext(obj);2966case VerifyOption_G1UseMarkWord: return obj->is_gc_marked();2967default: ShouldNotReachHere();2968}2969return false; // keep some compilers happy2970}29712972const char* G1CollectedHeap::top_at_mark_start_str(VerifyOption vo) {2973switch (vo) {2974case VerifyOption_G1UsePrevMarking: return "PTAMS";2975case VerifyOption_G1UseNextMarking: return "NTAMS";2976case VerifyOption_G1UseMarkWord: return "NONE";2977default: ShouldNotReachHere();2978}2979return NULL; // keep some compilers happy2980}29812982class VerifyRootsClosure: public OopClosure {2983private:2984G1CollectedHeap* _g1h;2985VerifyOption _vo;2986bool _failures;2987public:2988// _vo == UsePrevMarking -> use "prev" marking information,2989// _vo == UseNextMarking -> use "next" marking information,2990// _vo == UseMarkWord -> use mark word from object header.2991VerifyRootsClosure(VerifyOption vo) :2992_g1h(G1CollectedHeap::heap()),2993_vo(vo),2994_failures(false) { }29952996bool failures() { return _failures; }29972998template <class T> void do_oop_nv(T* p) {2999T heap_oop = oopDesc::load_heap_oop(p);3000if (!oopDesc::is_null(heap_oop)) {3001oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);3002if (_g1h->is_obj_dead_cond(obj, _vo)) {3003gclog_or_tty->print_cr("Root location " PTR_FORMAT " "3004"points to dead obj " PTR_FORMAT, p, (void*) obj);3005if (_vo == VerifyOption_G1UseMarkWord) {3006gclog_or_tty->print_cr(" Mark word: " PTR_FORMAT, (void*)(obj->mark()));3007}3008obj->print_on(gclog_or_tty);3009_failures = true;3010}3011}3012}30133014void do_oop(oop* p) { do_oop_nv(p); }3015void do_oop(narrowOop* p) { do_oop_nv(p); }3016};30173018class G1VerifyCodeRootOopClosure: public OopClosure {3019G1CollectedHeap* _g1h;3020OopClosure* _root_cl;3021nmethod* _nm;3022VerifyOption _vo;3023bool _failures;30243025template <class T> void do_oop_work(T* p) {3026// First verify that this root is live3027_root_cl->do_oop(p);30283029if (!G1VerifyHeapRegionCodeRoots) {3030// We're not verifying the code roots attached to heap region.3031return;3032}30333034// Don't check the code roots during marking verification in a full GC3035if (_vo == VerifyOption_G1UseMarkWord) {3036return;3037}30383039// Now verify that the current nmethod (which contains p) is3040// in the code root list of the heap region containing the3041// object referenced by p.30423043T heap_oop = oopDesc::load_heap_oop(p);3044if (!oopDesc::is_null(heap_oop)) {3045oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);30463047// Now fetch the region containing the object3048HeapRegion* hr = _g1h->heap_region_containing(obj);3049HeapRegionRemSet* hrrs = hr->rem_set();3050// Verify that the strong code root list for this region3051// contains the nmethod3052if (!hrrs->strong_code_roots_list_contains(_nm)) {3053gclog_or_tty->print_cr("Code root location " PTR_FORMAT " "3054"from nmethod " PTR_FORMAT " not in strong "3055"code roots for region [" PTR_FORMAT "," PTR_FORMAT ")",3056p, _nm, hr->bottom(), hr->end());3057_failures = true;3058}3059}3060}30613062public:3063G1VerifyCodeRootOopClosure(G1CollectedHeap* g1h, OopClosure* root_cl, VerifyOption vo):3064_g1h(g1h), _root_cl(root_cl), _vo(vo), _nm(NULL), _failures(false) {}30653066void do_oop(oop* p) { do_oop_work(p); }3067void do_oop(narrowOop* p) { do_oop_work(p); }30683069void set_nmethod(nmethod* nm) { _nm = nm; }3070bool failures() { return _failures; }3071};30723073class G1VerifyCodeRootBlobClosure: public CodeBlobClosure {3074G1VerifyCodeRootOopClosure* _oop_cl;30753076public:3077G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure* oop_cl):3078_oop_cl(oop_cl) {}30793080void do_code_blob(CodeBlob* cb) {3081nmethod* nm = cb->as_nmethod_or_null();3082if (nm != NULL) {3083_oop_cl->set_nmethod(nm);3084nm->oops_do(_oop_cl);3085}3086}3087};30883089class YoungRefCounterClosure : public OopClosure {3090G1CollectedHeap* _g1h;3091int _count;3092public:3093YoungRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {}3094void do_oop(oop* p) { if (_g1h->is_in_young(*p)) { _count++; } }3095void do_oop(narrowOop* p) { ShouldNotReachHere(); }30963097int count() { return _count; }3098void reset_count() { _count = 0; };3099};31003101class VerifyKlassClosure: public KlassClosure {3102YoungRefCounterClosure _young_ref_counter_closure;3103OopClosure *_oop_closure;3104public:3105VerifyKlassClosure(G1CollectedHeap* g1h, OopClosure* cl) : _young_ref_counter_closure(g1h), _oop_closure(cl) {}3106void do_klass(Klass* k) {3107k->oops_do(_oop_closure);31083109_young_ref_counter_closure.reset_count();3110k->oops_do(&_young_ref_counter_closure);3111if (_young_ref_counter_closure.count() > 0) {3112guarantee(k->has_modified_oops(), err_msg("Klass %p, has young refs but is not dirty.", k));3113}3114}3115};31163117class VerifyLivenessOopClosure: public OopClosure {3118G1CollectedHeap* _g1h;3119VerifyOption _vo;3120public:3121VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo):3122_g1h(g1h), _vo(vo)3123{ }3124void do_oop(narrowOop *p) { do_oop_work(p); }3125void do_oop( oop *p) { do_oop_work(p); }31263127template <class T> void do_oop_work(T *p) {3128oop obj = oopDesc::load_decode_heap_oop(p);3129guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo),3130"Dead object referenced by a not dead object");3131}3132};31333134class VerifyObjsInRegionClosure: public ObjectClosure {3135private:3136G1CollectedHeap* _g1h;3137size_t _live_bytes;3138HeapRegion *_hr;3139VerifyOption _vo;3140public:3141// _vo == UsePrevMarking -> use "prev" marking information,3142// _vo == UseNextMarking -> use "next" marking information,3143// _vo == UseMarkWord -> use mark word from object header.3144VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo)3145: _live_bytes(0), _hr(hr), _vo(vo) {3146_g1h = G1CollectedHeap::heap();3147}3148void do_object(oop o) {3149VerifyLivenessOopClosure isLive(_g1h, _vo);3150assert(o != NULL, "Huh?");3151if (!_g1h->is_obj_dead_cond(o, _vo)) {3152// If the object is alive according to the mark word,3153// then verify that the marking information agrees.3154// Note we can't verify the contra-positive of the3155// above: if the object is dead (according to the mark3156// word), it may not be marked, or may have been marked3157// but has since became dead, or may have been allocated3158// since the last marking.3159if (_vo == VerifyOption_G1UseMarkWord) {3160guarantee(!_g1h->is_obj_dead(o), "mark word and concurrent mark mismatch");3161}31623163o->oop_iterate_no_header(&isLive);3164if (!_hr->obj_allocated_since_prev_marking(o)) {3165size_t obj_size = o->size(); // Make sure we don't overflow3166_live_bytes += (obj_size * HeapWordSize);3167}3168}3169}3170size_t live_bytes() { return _live_bytes; }3171};31723173class PrintObjsInRegionClosure : public ObjectClosure {3174HeapRegion *_hr;3175G1CollectedHeap *_g1;3176public:3177PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) {3178_g1 = G1CollectedHeap::heap();3179};31803181void do_object(oop o) {3182if (o != NULL) {3183HeapWord *start = (HeapWord *) o;3184size_t word_sz = o->size();3185gclog_or_tty->print("\nPrinting obj " PTR_FORMAT " of size " SIZE_FORMAT3186" isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",3187(void*) o, word_sz,3188_g1->isMarkedPrev(o),3189_g1->isMarkedNext(o),3190_hr->obj_allocated_since_prev_marking(o));3191HeapWord *end = start + word_sz;3192HeapWord *cur;3193int *val;3194for (cur = start; cur < end; cur++) {3195val = (int *) cur;3196gclog_or_tty->print("\t " PTR_FORMAT ":" PTR_FORMAT "\n", val, *val);3197}3198}3199}3200};32013202class VerifyRegionClosure: public HeapRegionClosure {3203private:3204bool _par;3205VerifyOption _vo;3206bool _failures;3207public:3208// _vo == UsePrevMarking -> use "prev" marking information,3209// _vo == UseNextMarking -> use "next" marking information,3210// _vo == UseMarkWord -> use mark word from object header.3211VerifyRegionClosure(bool par, VerifyOption vo)3212: _par(par),3213_vo(vo),3214_failures(false) {}32153216bool failures() {3217return _failures;3218}32193220bool doHeapRegion(HeapRegion* r) {3221if (!r->continuesHumongous()) {3222bool failures = false;3223r->verify(_vo, &failures);3224if (failures) {3225_failures = true;3226} else {3227VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo);3228r->object_iterate(¬_dead_yet_cl);3229if (_vo != VerifyOption_G1UseNextMarking) {3230if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {3231gclog_or_tty->print_cr("[" PTR_FORMAT "," PTR_FORMAT "] "3232"max_live_bytes " SIZE_FORMAT " "3233"< calculated " SIZE_FORMAT,3234r->bottom(), r->end(),3235r->max_live_bytes(),3236not_dead_yet_cl.live_bytes());3237_failures = true;3238}3239} else {3240// When vo == UseNextMarking we cannot currently do a sanity3241// check on the live bytes as the calculation has not been3242// finalized yet.3243}3244}3245}3246return false; // stop the region iteration if we hit a failure3247}3248};32493250// This is the task used for parallel verification of the heap regions32513252class G1ParVerifyTask: public AbstractGangTask {3253private:3254G1CollectedHeap* _g1h;3255VerifyOption _vo;3256bool _failures;32573258public:3259// _vo == UsePrevMarking -> use "prev" marking information,3260// _vo == UseNextMarking -> use "next" marking information,3261// _vo == UseMarkWord -> use mark word from object header.3262G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :3263AbstractGangTask("Parallel verify task"),3264_g1h(g1h),3265_vo(vo),3266_failures(false) { }32673268bool failures() {3269return _failures;3270}32713272void work(uint worker_id) {3273HandleMark hm;3274VerifyRegionClosure blk(true, _vo);3275_g1h->heap_region_par_iterate_chunked(&blk, worker_id,3276_g1h->workers()->active_workers(),3277HeapRegion::ParVerifyClaimValue);3278if (blk.failures()) {3279_failures = true;3280}3281}3282};32833284void G1CollectedHeap::verify(bool silent, VerifyOption vo) {3285if (SafepointSynchronize::is_at_safepoint()) {3286assert(Thread::current()->is_VM_thread(),3287"Expected to be executed serially by the VM thread at this point");32883289if (!silent) { gclog_or_tty->print("Roots "); }3290VerifyRootsClosure rootsCl(vo);3291VerifyKlassClosure klassCl(this, &rootsCl);3292CLDToKlassAndOopClosure cldCl(&klassCl, &rootsCl, false);32933294// We apply the relevant closures to all the oops in the3295// system dictionary, class loader data graph, the string table3296// and the nmethods in the code cache.3297G1VerifyCodeRootOopClosure codeRootsCl(this, &rootsCl, vo);3298G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl);32993300{3301G1RootProcessor root_processor(this);3302root_processor.process_all_roots(&rootsCl,3303&cldCl,3304&blobsCl);3305}33063307bool failures = rootsCl.failures() || codeRootsCl.failures();33083309if (vo != VerifyOption_G1UseMarkWord) {3310// If we're verifying during a full GC then the region sets3311// will have been torn down at the start of the GC. Therefore3312// verifying the region sets will fail. So we only verify3313// the region sets when not in a full GC.3314if (!silent) { gclog_or_tty->print("HeapRegionSets "); }3315verify_region_sets();3316}33173318if (!silent) { gclog_or_tty->print("HeapRegions "); }3319if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {3320assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),3321"sanity check");33223323G1ParVerifyTask task(this, vo);3324assert(UseDynamicNumberOfGCThreads ||3325workers()->active_workers() == workers()->total_workers(),3326"If not dynamic should be using all the workers");3327int n_workers = workers()->active_workers();3328set_par_threads(n_workers);3329workers()->run_task(&task);3330set_par_threads(0);3331if (task.failures()) {3332failures = true;3333}33343335// Checks that the expected amount of parallel work was done.3336// The implication is that n_workers is > 0.3337assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),3338"sanity check");33393340reset_heap_region_claim_values();33413342assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),3343"sanity check");3344} else {3345VerifyRegionClosure blk(false, vo);3346heap_region_iterate(&blk);3347if (blk.failures()) {3348failures = true;3349}3350}3351if (!silent) gclog_or_tty->print("RemSet ");3352rem_set()->verify();33533354if (G1StringDedup::is_enabled()) {3355if (!silent) gclog_or_tty->print("StrDedup ");3356G1StringDedup::verify();3357}33583359if (failures) {3360gclog_or_tty->print_cr("Heap:");3361// It helps to have the per-region information in the output to3362// help us track down what went wrong. This is why we call3363// print_extended_on() instead of print_on().3364print_extended_on(gclog_or_tty);3365gclog_or_tty->cr();3366#ifndef PRODUCT3367if (VerifyDuringGC && G1VerifyDuringGCPrintReachable) {3368concurrent_mark()->print_reachable("at-verification-failure",3369vo, false /* all */);3370}3371#endif3372gclog_or_tty->flush();3373}3374guarantee(!failures, "there should not have been any failures");3375} else {3376if (!silent) {3377gclog_or_tty->print("(SKIPPING Roots, HeapRegionSets, HeapRegions, RemSet");3378if (G1StringDedup::is_enabled()) {3379gclog_or_tty->print(", StrDedup");3380}3381gclog_or_tty->print(") ");3382}3383}3384}33853386void G1CollectedHeap::verify(bool silent) {3387verify(silent, VerifyOption_G1UsePrevMarking);3388}33893390double G1CollectedHeap::verify(bool guard, const char* msg) {3391double verify_time_ms = 0.0;33923393if (guard && total_collections() >= VerifyGCStartAt) {3394double verify_start = os::elapsedTime();3395HandleMark hm; // Discard invalid handles created during verification3396prepare_for_verify();3397Universe::verify(VerifyOption_G1UsePrevMarking, msg);3398verify_time_ms = (os::elapsedTime() - verify_start) * 1000;3399}34003401return verify_time_ms;3402}34033404void G1CollectedHeap::verify_before_gc() {3405double verify_time_ms = verify(VerifyBeforeGC, " VerifyBeforeGC:");3406g1_policy()->phase_times()->record_verify_before_time_ms(verify_time_ms);3407}34083409void G1CollectedHeap::verify_after_gc() {3410double verify_time_ms = verify(VerifyAfterGC, " VerifyAfterGC:");3411g1_policy()->phase_times()->record_verify_after_time_ms(verify_time_ms);3412}34133414class PrintRegionClosure: public HeapRegionClosure {3415outputStream* _st;3416public:3417PrintRegionClosure(outputStream* st) : _st(st) {}3418bool doHeapRegion(HeapRegion* r) {3419r->print_on(_st);3420return false;3421}3422};34233424bool G1CollectedHeap::is_obj_dead_cond(const oop obj,3425const HeapRegion* hr,3426const VerifyOption vo) const {3427switch (vo) {3428case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);3429case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);3430case VerifyOption_G1UseMarkWord: return !obj->is_gc_marked();3431default: ShouldNotReachHere();3432}3433return false; // keep some compilers happy3434}34353436bool G1CollectedHeap::is_obj_dead_cond(const oop obj,3437const VerifyOption vo) const {3438switch (vo) {3439case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);3440case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);3441case VerifyOption_G1UseMarkWord: return !obj->is_gc_marked();3442default: ShouldNotReachHere();3443}3444return false; // keep some compilers happy3445}34463447void G1CollectedHeap::print_on(outputStream* st) const {3448st->print(" %-20s", "garbage-first heap");3449st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",3450capacity()/K, used_unlocked()/K);3451st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")",3452_hrm.reserved().start(),3453_hrm.reserved().start() + _hrm.length() + HeapRegion::GrainWords,3454_hrm.reserved().end());3455st->cr();3456st->print(" region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);3457uint young_regions = _young_list->length();3458st->print("%u young (" SIZE_FORMAT "K), ", young_regions,3459(size_t) young_regions * HeapRegion::GrainBytes / K);3460uint survivor_regions = g1_policy()->recorded_survivor_regions();3461st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,3462(size_t) survivor_regions * HeapRegion::GrainBytes / K);3463st->cr();3464MetaspaceAux::print_on(st);3465}34663467void G1CollectedHeap::print_extended_on(outputStream* st) const {3468print_on(st);34693470// Print the per-region information.3471st->cr();3472st->print_cr("Heap Regions: (Y=young(eden), SU=young(survivor), "3473"HS=humongous(starts), HC=humongous(continues), "3474"CS=collection set, F=free, TS=gc time stamp, "3475"PTAMS=previous top-at-mark-start, "3476"NTAMS=next top-at-mark-start)");3477PrintRegionClosure blk(st);3478heap_region_iterate(&blk);3479}34803481void G1CollectedHeap::print_on_error(outputStream* st) const {3482this->CollectedHeap::print_on_error(st);34833484if (_cm != NULL) {3485st->cr();3486_cm->print_on_error(st);3487}3488}34893490void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {3491if (G1CollectedHeap::use_parallel_gc_threads()) {3492workers()->print_worker_threads_on(st);3493}3494_cmThread->print_on(st);3495st->cr();3496_cm->print_worker_threads_on(st);3497_cg1r->print_worker_threads_on(st);3498if (G1StringDedup::is_enabled()) {3499G1StringDedup::print_worker_threads_on(st);3500}3501}35023503void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {3504if (G1CollectedHeap::use_parallel_gc_threads()) {3505workers()->threads_do(tc);3506}3507tc->do_thread(_cmThread);3508_cg1r->threads_do(tc);3509if (G1StringDedup::is_enabled()) {3510G1StringDedup::threads_do(tc);3511}3512}35133514void G1CollectedHeap::print_tracing_info() const {3515// We'll overload this to mean "trace GC pause statistics."3516if (TraceGen0Time || TraceGen1Time) {3517// The "G1CollectorPolicy" is keeping track of these stats, so delegate3518// to that.3519g1_policy()->print_tracing_info();3520}3521if (G1SummarizeRSetStats) {3522g1_rem_set()->print_summary_info();3523}3524if (G1SummarizeConcMark) {3525concurrent_mark()->print_summary_info();3526}3527g1_policy()->print_yg_surv_rate_info();3528SpecializationStats::print();3529}35303531#ifndef PRODUCT3532// Helpful for debugging RSet issues.35333534class PrintRSetsClosure : public HeapRegionClosure {3535private:3536const char* _msg;3537size_t _occupied_sum;35383539public:3540bool doHeapRegion(HeapRegion* r) {3541HeapRegionRemSet* hrrs = r->rem_set();3542size_t occupied = hrrs->occupied();3543_occupied_sum += occupied;35443545gclog_or_tty->print_cr("Printing RSet for region " HR_FORMAT,3546HR_FORMAT_PARAMS(r));3547if (occupied == 0) {3548gclog_or_tty->print_cr(" RSet is empty");3549} else {3550hrrs->print();3551}3552gclog_or_tty->print_cr("----------");3553return false;3554}35553556PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {3557gclog_or_tty->cr();3558gclog_or_tty->print_cr("========================================");3559gclog_or_tty->print_cr("%s", msg);3560gclog_or_tty->cr();3561}35623563~PrintRSetsClosure() {3564gclog_or_tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum);3565gclog_or_tty->print_cr("========================================");3566gclog_or_tty->cr();3567}3568};35693570void G1CollectedHeap::print_cset_rsets() {3571PrintRSetsClosure cl("Printing CSet RSets");3572collection_set_iterate(&cl);3573}35743575void G1CollectedHeap::print_all_rsets() {3576PrintRSetsClosure cl("Printing All RSets");;3577heap_region_iterate(&cl);3578}3579#endif // PRODUCT35803581G1HeapSummary G1CollectedHeap::create_g1_heap_summary() {35823583size_t eden_used_bytes = _young_list->eden_used_bytes();3584size_t survivor_used_bytes = _young_list->survivor_used_bytes();3585size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();35863587size_t eden_capacity_bytes =3588(g1_policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes;35893590VirtualSpaceSummary heap_summary = create_heap_space_summary();3591return G1HeapSummary(heap_summary, heap_used, eden_used_bytes,3592eden_capacity_bytes, survivor_used_bytes, num_regions());3593}35943595void G1CollectedHeap::trace_heap(GCWhen::Type when, GCTracer* gc_tracer) {3596const G1HeapSummary& heap_summary = create_g1_heap_summary();3597gc_tracer->report_gc_heap_summary(when, heap_summary);35983599const MetaspaceSummary& metaspace_summary = create_metaspace_summary();3600gc_tracer->report_metaspace_summary(when, metaspace_summary);3601}36023603G1CollectedHeap* G1CollectedHeap::heap() {3604assert(_sh->kind() == CollectedHeap::G1CollectedHeap,3605"not a garbage-first heap");3606return _g1h;3607}36083609void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {3610// always_do_update_barrier = false;3611assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");3612// Fill TLAB's and such3613accumulate_statistics_all_tlabs();3614ensure_parsability(true);36153616if (G1SummarizeRSetStats && (G1SummarizeRSetStatsPeriod > 0) &&3617(total_collections() % G1SummarizeRSetStatsPeriod == 0)) {3618g1_rem_set()->print_periodic_summary_info("Before GC RS summary");3619}3620}36213622void G1CollectedHeap::gc_epilogue(bool full) {36233624if (G1SummarizeRSetStats &&3625(G1SummarizeRSetStatsPeriod > 0) &&3626// we are at the end of the GC. Total collections has already been increased.3627((total_collections() - 1) % G1SummarizeRSetStatsPeriod == 0)) {3628g1_rem_set()->print_periodic_summary_info("After GC RS summary");3629}36303631// FIXME: what is this about?3632// I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"3633// is set.3634COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),3635"derived pointer present"));3636// always_do_update_barrier = true;36373638resize_all_tlabs();3639allocation_context_stats().update(full);36403641// We have just completed a GC. Update the soft reference3642// policy with the new heap occupancy3643Universe::update_heap_info_at_gc();3644}36453646HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,3647uint gc_count_before,3648bool* succeeded,3649GCCause::Cause gc_cause) {3650assert_heap_not_locked_and_not_at_safepoint();3651g1_policy()->record_stop_world_start();3652VM_G1IncCollectionPause op(gc_count_before,3653word_size,3654false, /* should_initiate_conc_mark */3655g1_policy()->max_pause_time_ms(),3656gc_cause);36573658op.set_allocation_context(AllocationContext::current());3659VMThread::execute(&op);36603661HeapWord* result = op.result();3662bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded();3663assert(result == NULL || ret_succeeded,3664"the result should be NULL if the VM did not succeed");3665*succeeded = ret_succeeded;36663667assert_heap_not_locked();3668return result;3669}36703671void3672G1CollectedHeap::doConcurrentMark() {3673MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);3674if (!_cmThread->in_progress()) {3675_cmThread->set_started();3676CGC_lock->notify();3677}3678}36793680size_t G1CollectedHeap::pending_card_num() {3681size_t extra_cards = 0;3682JavaThread *curr = Threads::first();3683while (curr != NULL) {3684DirtyCardQueue& dcq = curr->dirty_card_queue();3685extra_cards += dcq.size();3686curr = curr->next();3687}3688DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();3689size_t buffer_size = dcqs.buffer_size();3690size_t buffer_num = dcqs.completed_buffers_num();36913692// PtrQueueSet::buffer_size() and PtrQueue:size() return sizes3693// in bytes - not the number of 'entries'. We need to convert3694// into a number of cards.3695return (buffer_size * buffer_num + extra_cards) / oopSize;3696}36973698size_t G1CollectedHeap::cards_scanned() {3699return g1_rem_set()->cardsScanned();3700}37013702class RegisterHumongousWithInCSetFastTestClosure : public HeapRegionClosure {3703private:3704size_t _total_humongous;3705size_t _candidate_humongous;37063707DirtyCardQueue _dcq;37083709// We don't nominate objects with many remembered set entries, on3710// the assumption that such objects are likely still live.3711bool is_remset_small(HeapRegion* region) const {3712HeapRegionRemSet* const rset = region->rem_set();3713return G1EagerReclaimHumongousObjectsWithStaleRefs3714? rset->occupancy_less_or_equal_than(G1RSetSparseRegionEntries)3715: rset->is_empty();3716}37173718bool is_typeArray_region(HeapRegion* region) const {3719return oop(region->bottom())->is_typeArray();3720}37213722bool humongous_region_is_candidate(G1CollectedHeap* heap, HeapRegion* region) const {3723assert(region->startsHumongous(), "Must start a humongous object");37243725// Candidate selection must satisfy the following constraints3726// while concurrent marking is in progress:3727//3728// * In order to maintain SATB invariants, an object must not be3729// reclaimed if it was allocated before the start of marking and3730// has not had its references scanned. Such an object must have3731// its references (including type metadata) scanned to ensure no3732// live objects are missed by the marking process. Objects3733// allocated after the start of concurrent marking don't need to3734// be scanned.3735//3736// * An object must not be reclaimed if it is on the concurrent3737// mark stack. Objects allocated after the start of concurrent3738// marking are never pushed on the mark stack.3739//3740// Nominating only objects allocated after the start of concurrent3741// marking is sufficient to meet both constraints. This may miss3742// some objects that satisfy the constraints, but the marking data3743// structures don't support efficiently performing the needed3744// additional tests or scrubbing of the mark stack.3745//3746// However, we presently only nominate is_typeArray() objects.3747// A humongous object containing references induces remembered3748// set entries on other regions. In order to reclaim such an3749// object, those remembered sets would need to be cleaned up.3750//3751// We also treat is_typeArray() objects specially, allowing them3752// to be reclaimed even if allocated before the start of3753// concurrent mark. For this we rely on mark stack insertion to3754// exclude is_typeArray() objects, preventing reclaiming an object3755// that is in the mark stack. We also rely on the metadata for3756// such objects to be built-in and so ensured to be kept live.3757// Frequent allocation and drop of large binary blobs is an3758// important use case for eager reclaim, and this special handling3759// may reduce needed headroom.37603761return is_typeArray_region(region) && is_remset_small(region);3762}37633764public:3765RegisterHumongousWithInCSetFastTestClosure()3766: _total_humongous(0),3767_candidate_humongous(0),3768_dcq(&JavaThread::dirty_card_queue_set()) {3769}37703771virtual bool doHeapRegion(HeapRegion* r) {3772if (!r->startsHumongous()) {3773return false;3774}3775G1CollectedHeap* g1h = G1CollectedHeap::heap();37763777bool is_candidate = humongous_region_is_candidate(g1h, r);3778uint rindex = r->hrm_index();3779g1h->set_humongous_reclaim_candidate(rindex, is_candidate);3780if (is_candidate) {3781_candidate_humongous++;3782g1h->register_humongous_region_with_in_cset_fast_test(rindex);3783// Is_candidate already filters out humongous object with large remembered sets.3784// If we have a humongous object with a few remembered sets, we simply flush these3785// remembered set entries into the DCQS. That will result in automatic3786// re-evaluation of their remembered set entries during the following evacuation3787// phase.3788if (!r->rem_set()->is_empty()) {3789guarantee(r->rem_set()->occupancy_less_or_equal_than(G1RSetSparseRegionEntries),3790"Found a not-small remembered set here. This is inconsistent with previous assumptions.");3791G1SATBCardTableLoggingModRefBS* bs = g1h->g1_barrier_set();3792HeapRegionRemSetIterator hrrs(r->rem_set());3793size_t card_index;3794while (hrrs.has_next(card_index)) {3795jbyte* card_ptr = (jbyte*)bs->byte_for_index(card_index);3796if (*card_ptr != CardTableModRefBS::dirty_card_val()) {3797*card_ptr = CardTableModRefBS::dirty_card_val();3798_dcq.enqueue(card_ptr);3799}3800}3801assert(hrrs.n_yielded() == r->rem_set()->occupied(),3802err_msg("Remembered set hash maps out of sync, cur: " SIZE_FORMAT " entries, next: " SIZE_FORMAT " entries",3803hrrs.n_yielded(), r->rem_set()->occupied()));3804r->rem_set()->clear_locked();3805}3806assert(r->rem_set()->is_empty(), "At this point any humongous candidate remembered set must be empty.");3807}3808_total_humongous++;38093810return false;3811}38123813size_t total_humongous() const { return _total_humongous; }3814size_t candidate_humongous() const { return _candidate_humongous; }38153816void flush_rem_set_entries() { _dcq.flush(); }3817};38183819void G1CollectedHeap::register_humongous_regions_with_in_cset_fast_test() {3820if (!G1EagerReclaimHumongousObjects) {3821g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(0.0, 0, 0);3822return;3823}3824double time = os::elapsed_counter();38253826// Collect reclaim candidate information and register candidates with cset.3827RegisterHumongousWithInCSetFastTestClosure cl;3828heap_region_iterate(&cl);38293830time = ((double)(os::elapsed_counter() - time) / os::elapsed_frequency()) * 1000.0;3831g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(time,3832cl.total_humongous(),3833cl.candidate_humongous());3834_has_humongous_reclaim_candidates = cl.candidate_humongous() > 0;38353836// Finally flush all remembered set entries to re-check into the global DCQS.3837cl.flush_rem_set_entries();3838}38393840void3841G1CollectedHeap::setup_surviving_young_words() {3842assert(_surviving_young_words == NULL, "pre-condition");3843uint array_length = g1_policy()->young_cset_region_length();3844_surviving_young_words = NEW_C_HEAP_ARRAY(size_t, (size_t) array_length, mtGC);3845if (_surviving_young_words == NULL) {3846vm_exit_out_of_memory(sizeof(size_t) * array_length, OOM_MALLOC_ERROR,3847"Not enough space for young surv words summary.");3848}3849memset(_surviving_young_words, 0, (size_t) array_length * sizeof(size_t));3850#ifdef ASSERT3851for (uint i = 0; i < array_length; ++i) {3852assert( _surviving_young_words[i] == 0, "memset above" );3853}3854#endif // !ASSERT3855}38563857void3858G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {3859MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);3860uint array_length = g1_policy()->young_cset_region_length();3861for (uint i = 0; i < array_length; ++i) {3862_surviving_young_words[i] += surv_young_words[i];3863}3864}38653866void3867G1CollectedHeap::cleanup_surviving_young_words() {3868guarantee( _surviving_young_words != NULL, "pre-condition" );3869FREE_C_HEAP_ARRAY(size_t, _surviving_young_words, mtGC);3870_surviving_young_words = NULL;3871}38723873class VerifyRegionRemSetClosure : public HeapRegionClosure {3874public:3875bool doHeapRegion(HeapRegion* hr) {3876if (!hr->continuesHumongous()) {3877hr->verify_rem_set();3878}3879return false;3880}3881};38823883#ifdef ASSERT3884class VerifyCSetClosure: public HeapRegionClosure {3885public:3886bool doHeapRegion(HeapRegion* hr) {3887// Here we check that the CSet region's RSet is ready for parallel3888// iteration. The fields that we'll verify are only manipulated3889// when the region is part of a CSet and is collected. Afterwards,3890// we reset these fields when we clear the region's RSet (when the3891// region is freed) so they are ready when the region is3892// re-allocated. The only exception to this is if there's an3893// evacuation failure and instead of freeing the region we leave3894// it in the heap. In that case, we reset these fields during3895// evacuation failure handling.3896guarantee(hr->rem_set()->verify_ready_for_par_iteration(), "verification");38973898// Here's a good place to add any other checks we'd like to3899// perform on CSet regions.3900return false;3901}3902};3903#endif // ASSERT39043905#if TASKQUEUE_STATS3906void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {3907st->print_raw_cr("GC Task Stats");3908st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();3909st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();3910}39113912void G1CollectedHeap::print_taskqueue_stats(outputStream* const st) const {3913print_taskqueue_stats_hdr(st);39143915TaskQueueStats totals;3916const int n = workers() != NULL ? workers()->total_workers() : 1;3917for (int i = 0; i < n; ++i) {3918st->print("%3d ", i); task_queue(i)->stats.print(st); st->cr();3919totals += task_queue(i)->stats;3920}3921st->print_raw("tot "); totals.print(st); st->cr();39223923DEBUG_ONLY(totals.verify());3924}39253926void G1CollectedHeap::reset_taskqueue_stats() {3927const int n = workers() != NULL ? workers()->total_workers() : 1;3928for (int i = 0; i < n; ++i) {3929task_queue(i)->stats.reset();3930}3931}3932#endif // TASKQUEUE_STATS39333934void G1CollectedHeap::log_gc_header() {3935if (!G1Log::fine()) {3936return;3937}39383939gclog_or_tty->gclog_stamp(_gc_tracer_stw->gc_id());39403941GCCauseString gc_cause_str = GCCauseString("GC pause", gc_cause())3942.append(g1_policy()->gcs_are_young() ? "(young)" : "(mixed)")3943.append(g1_policy()->during_initial_mark_pause() ? " (initial-mark)" : "");39443945gclog_or_tty->print("[%s", (const char*)gc_cause_str);3946}39473948void G1CollectedHeap::log_gc_footer(double pause_time_sec) {3949if (!G1Log::fine()) {3950return;3951}39523953if (G1Log::finer()) {3954if (evacuation_failed()) {3955gclog_or_tty->print(" (to-space exhausted)");3956}3957gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);3958g1_policy()->phase_times()->note_gc_end();3959g1_policy()->phase_times()->print(pause_time_sec);3960g1_policy()->print_detailed_heap_transition();3961} else {3962if (evacuation_failed()) {3963gclog_or_tty->print("--");3964}3965g1_policy()->print_heap_transition();3966gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);3967}3968gclog_or_tty->flush();3969}39703971bool3972G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {3973assert_at_safepoint(true /* should_be_vm_thread */);3974guarantee(!is_gc_active(), "collection is not reentrant");39753976if (GC_locker::check_active_before_gc()) {3977return false;3978}39793980_gc_timer_stw->register_gc_start();39813982_gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());39833984SvcGCMarker sgcm(SvcGCMarker::MINOR);3985ResourceMark rm;39863987print_heap_before_gc();3988trace_heap_before_gc(_gc_tracer_stw);39893990verify_region_sets_optional();3991verify_dirty_young_regions();39923993// This call will decide whether this pause is an initial-mark3994// pause. If it is, during_initial_mark_pause() will return true3995// for the duration of this pause.3996g1_policy()->decide_on_conc_mark_initiation();39973998// We do not allow initial-mark to be piggy-backed on a mixed GC.3999assert(!g1_policy()->during_initial_mark_pause() ||4000g1_policy()->gcs_are_young(), "sanity");40014002// We also do not allow mixed GCs during marking.4003assert(!mark_in_progress() || g1_policy()->gcs_are_young(), "sanity");40044005// Record whether this pause is an initial mark. When the current4006// thread has completed its logging output and it's safe to signal4007// the CM thread, the flag's value in the policy has been reset.4008bool should_start_conc_mark = g1_policy()->during_initial_mark_pause();40094010// Inner scope for scope based logging, timers, and stats collection4011{4012EvacuationInfo evacuation_info;40134014if (g1_policy()->during_initial_mark_pause()) {4015// We are about to start a marking cycle, so we increment the4016// full collection counter.4017increment_old_marking_cycles_started();4018register_concurrent_cycle_start(_gc_timer_stw->gc_start());4019}40204021_gc_tracer_stw->report_yc_type(yc_type());40224023TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);40244025uint active_workers = AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),4026workers()->active_workers(),4027Threads::number_of_non_daemon_threads());4028assert(UseDynamicNumberOfGCThreads ||4029active_workers == workers()->total_workers(),4030"If not dynamic should be using all the workers");4031workers()->set_active_workers(active_workers);403240334034double pause_start_sec = os::elapsedTime();4035g1_policy()->phase_times()->note_gc_start(active_workers, mark_in_progress());4036log_gc_header();40374038TraceCollectorStats tcs(g1mm()->incremental_collection_counters());4039TraceMemoryManagerStats tms(false /* fullGC */, gc_cause(),4040yc_type() == Mixed /* allMemoryPoolsAffected */);40414042// If the secondary_free_list is not empty, append it to the4043// free_list. No need to wait for the cleanup operation to finish;4044// the region allocation code will check the secondary_free_list4045// and wait if necessary. If the G1StressConcRegionFreeing flag is4046// set, skip this step so that the region allocation code has to4047// get entries from the secondary_free_list.4048if (!G1StressConcRegionFreeing) {4049append_secondary_free_list_if_not_empty_with_lock();4050}40514052assert(check_young_list_well_formed(), "young list should be well formed");4053assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),4054"sanity check");40554056// Don't dynamically change the number of GC threads this early. A value of4057// 0 is used to indicate serial work. When parallel work is done,4058// it will be set.40594060{ // Call to jvmpi::post_class_unload_events must occur outside of active GC4061IsGCActiveMark x;40624063gc_prologue(false);4064increment_total_collections(false /* full gc */);4065increment_gc_time_stamp();40664067if (VerifyRememberedSets) {4068if (!VerifySilently) {4069gclog_or_tty->print_cr("[Verifying RemSets before GC]");4070}4071VerifyRegionRemSetClosure v_cl;4072heap_region_iterate(&v_cl);4073}40744075verify_before_gc();4076check_bitmaps("GC Start");40774078COMPILER2_PRESENT(DerivedPointerTable::clear());40794080// Please see comment in g1CollectedHeap.hpp and4081// G1CollectedHeap::ref_processing_init() to see how4082// reference processing currently works in G1.40834084// Enable discovery in the STW reference processor4085ref_processor_stw()->enable_discovery(true /*verify_disabled*/,4086true /*verify_no_refs*/);40874088{4089// We want to temporarily turn off discovery by the4090// CM ref processor, if necessary, and turn it back on4091// on again later if we do. Using a scoped4092// NoRefDiscovery object will do this.4093NoRefDiscovery no_cm_discovery(ref_processor_cm());40944095// Forget the current alloc region (we might even choose it to be part4096// of the collection set!).4097_allocator->release_mutator_alloc_region();40984099// We should call this after we retire the mutator alloc4100// region(s) so that all the ALLOC / RETIRE events are generated4101// before the start GC event.4102_hr_printer.start_gc(false /* full */, (size_t) total_collections());41034104// This timing is only used by the ergonomics to handle our pause target.4105// It is unclear why this should not include the full pause. We will4106// investigate this in CR 7178365.4107//4108// Preserving the old comment here if that helps the investigation:4109//4110// The elapsed time induced by the start time below deliberately elides4111// the possible verification above.4112double sample_start_time_sec = os::elapsedTime();41134114#if YOUNG_LIST_VERBOSE4115gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:");4116_young_list->print();4117g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);4118#endif // YOUNG_LIST_VERBOSE41194120g1_policy()->record_collection_pause_start(sample_start_time_sec, *_gc_tracer_stw);41214122double scan_wait_start = os::elapsedTime();4123// We have to wait until the CM threads finish scanning the4124// root regions as it's the only way to ensure that all the4125// objects on them have been correctly scanned before we start4126// moving them during the GC.4127bool waited = _cm->root_regions()->wait_until_scan_finished();4128double wait_time_ms = 0.0;4129if (waited) {4130double scan_wait_end = os::elapsedTime();4131wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;4132}4133g1_policy()->phase_times()->record_root_region_scan_wait_time(wait_time_ms);41344135#if YOUNG_LIST_VERBOSE4136gclog_or_tty->print_cr("\nAfter recording pause start.\nYoung_list:");4137_young_list->print();4138#endif // YOUNG_LIST_VERBOSE41394140if (g1_policy()->during_initial_mark_pause()) {4141concurrent_mark()->checkpointRootsInitialPre();4142}41434144#if YOUNG_LIST_VERBOSE4145gclog_or_tty->print_cr("\nBefore choosing collection set.\nYoung_list:");4146_young_list->print();4147g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);4148#endif // YOUNG_LIST_VERBOSE41494150g1_policy()->finalize_cset(target_pause_time_ms, evacuation_info);41514152// Make sure the remembered sets are up to date. This needs to be4153// done before register_humongous_regions_with_cset(), because the4154// remembered sets are used there to choose eager reclaim candidates.4155// If the remembered sets are not up to date we might miss some4156// entries that need to be handled.4157g1_rem_set()->cleanupHRRS();41584159register_humongous_regions_with_in_cset_fast_test();41604161assert(check_cset_fast_test(), "Inconsistency in the InCSetState table.");41624163_cm->note_start_of_gc();4164// We call this after finalize_cset() to4165// ensure that the CSet has been finalized.4166_cm->verify_no_cset_oops();41674168if (_hr_printer.is_active()) {4169HeapRegion* hr = g1_policy()->collection_set();4170while (hr != NULL) {4171_hr_printer.cset(hr);4172hr = hr->next_in_collection_set();4173}4174}41754176#ifdef ASSERT4177VerifyCSetClosure cl;4178collection_set_iterate(&cl);4179#endif // ASSERT41804181setup_surviving_young_words();41824183// Initialize the GC alloc regions.4184_allocator->init_gc_alloc_regions(evacuation_info);41854186// Actually do the work...4187evacuate_collection_set(evacuation_info);41884189free_collection_set(g1_policy()->collection_set(), evacuation_info);41904191eagerly_reclaim_humongous_regions();41924193g1_policy()->clear_collection_set();41944195cleanup_surviving_young_words();41964197// Start a new incremental collection set for the next pause.4198g1_policy()->start_incremental_cset_building();41994200clear_cset_fast_test();42014202_young_list->reset_sampled_info();42034204// Don't check the whole heap at this point as the4205// GC alloc regions from this pause have been tagged4206// as survivors and moved on to the survivor list.4207// Survivor regions will fail the !is_young() check.4208assert(check_young_list_empty(false /* check_heap */),4209"young list should be empty");42104211#if YOUNG_LIST_VERBOSE4212gclog_or_tty->print_cr("Before recording survivors.\nYoung List:");4213_young_list->print();4214#endif // YOUNG_LIST_VERBOSE42154216g1_policy()->record_survivor_regions(_young_list->survivor_length(),4217_young_list->first_survivor_region(),4218_young_list->last_survivor_region());42194220_young_list->reset_auxilary_lists();42214222if (evacuation_failed()) {4223_allocator->set_used(recalculate_used());4224uint n_queues = MAX2((int)ParallelGCThreads, 1);4225for (uint i = 0; i < n_queues; i++) {4226if (_evacuation_failed_info_array[i].has_failed()) {4227_gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);4228}4229}4230} else {4231// The "used" of the the collection set have already been subtracted4232// when they were freed. Add in the bytes evacuated.4233_allocator->increase_used(g1_policy()->bytes_copied_during_gc());4234}42354236if (g1_policy()->during_initial_mark_pause()) {4237// We have to do this before we notify the CM threads that4238// they can start working to make sure that all the4239// appropriate initialization is done on the CM object.4240concurrent_mark()->checkpointRootsInitialPost();4241set_marking_started();4242// Note that we don't actually trigger the CM thread at4243// this point. We do that later when we're sure that4244// the current thread has completed its logging output.4245}42464247allocate_dummy_regions();42484249#if YOUNG_LIST_VERBOSE4250gclog_or_tty->print_cr("\nEnd of the pause.\nYoung_list:");4251_young_list->print();4252g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);4253#endif // YOUNG_LIST_VERBOSE42544255_allocator->init_mutator_alloc_region();42564257{4258size_t expand_bytes = g1_policy()->expansion_amount();4259if (expand_bytes > 0) {4260size_t bytes_before = capacity();4261// No need for an ergo verbose message here,4262// expansion_amount() does this when it returns a value > 0.4263if (!expand(expand_bytes)) {4264// We failed to expand the heap. Cannot do anything about it.4265}4266}4267}42684269// We redo the verification but now wrt to the new CSet which4270// has just got initialized after the previous CSet was freed.4271_cm->verify_no_cset_oops();4272_cm->note_end_of_gc();42734274// This timing is only used by the ergonomics to handle our pause target.4275// It is unclear why this should not include the full pause. We will4276// investigate this in CR 7178365.4277double sample_end_time_sec = os::elapsedTime();4278double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;4279g1_policy()->record_collection_pause_end(pause_time_ms, evacuation_info);42804281MemoryService::track_memory_usage();42824283// In prepare_for_verify() below we'll need to scan the deferred4284// update buffers to bring the RSets up-to-date if4285// G1HRRSFlushLogBuffersOnVerify has been set. While scanning4286// the update buffers we'll probably need to scan cards on the4287// regions we just allocated to (i.e., the GC alloc4288// regions). However, during the last GC we called4289// set_saved_mark() on all the GC alloc regions, so card4290// scanning might skip the [saved_mark_word()...top()] area of4291// those regions (i.e., the area we allocated objects into4292// during the last GC). But it shouldn't. Given that4293// saved_mark_word() is conditional on whether the GC time stamp4294// on the region is current or not, by incrementing the GC time4295// stamp here we invalidate all the GC time stamps on all the4296// regions and saved_mark_word() will simply return top() for4297// all the regions. This is a nicer way of ensuring this rather4298// than iterating over the regions and fixing them. In fact, the4299// GC time stamp increment here also ensures that4300// saved_mark_word() will return top() between pauses, i.e.,4301// during concurrent refinement. So we don't need the4302// is_gc_active() check to decided which top to use when4303// scanning cards (see CR 7039627).4304increment_gc_time_stamp();43054306if (VerifyRememberedSets) {4307if (!VerifySilently) {4308gclog_or_tty->print_cr("[Verifying RemSets after GC]");4309}4310VerifyRegionRemSetClosure v_cl;4311heap_region_iterate(&v_cl);4312}43134314verify_after_gc();4315check_bitmaps("GC End");43164317assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");4318ref_processor_stw()->verify_no_references_recorded();43194320// CM reference discovery will be re-enabled if necessary.4321}43224323// We should do this after we potentially expand the heap so4324// that all the COMMIT events are generated before the end GC4325// event, and after we retire the GC alloc regions so that all4326// RETIRE events are generated before the end GC event.4327_hr_printer.end_gc(false /* full */, (size_t) total_collections());43284329#ifdef TRACESPINNING4330ParallelTaskTerminator::print_termination_counts();4331#endif43324333gc_epilogue(false);4334}43354336// Print the remainder of the GC log output.4337log_gc_footer(os::elapsedTime() - pause_start_sec);43384339// It is not yet to safe to tell the concurrent mark to4340// start as we have some optional output below. We don't want the4341// output from the concurrent mark thread interfering with this4342// logging output either.43434344_hrm.verify_optional();4345verify_region_sets_optional();43464347TASKQUEUE_STATS_ONLY(if (ParallelGCVerbose) print_taskqueue_stats());4348TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());43494350print_heap_after_gc();4351trace_heap_after_gc(_gc_tracer_stw);43524353// We must call G1MonitoringSupport::update_sizes() in the same scoping level4354// as an active TraceMemoryManagerStats object (i.e. before the destructor for the4355// TraceMemoryManagerStats is called) so that the G1 memory pools are updated4356// before any GC notifications are raised.4357g1mm()->update_sizes();43584359_gc_tracer_stw->report_evacuation_info(&evacuation_info);4360_gc_tracer_stw->report_tenuring_threshold(_g1_policy->tenuring_threshold());4361_gc_timer_stw->register_gc_end();4362_gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(), _gc_timer_stw->time_partitions());4363}4364// It should now be safe to tell the concurrent mark thread to start4365// without its logging output interfering with the logging output4366// that came from the pause.43674368if (should_start_conc_mark) {4369// CAUTION: after the doConcurrentMark() call below,4370// the concurrent marking thread(s) could be running4371// concurrently with us. Make sure that anything after4372// this point does not assume that we are the only GC thread4373// running. Note: of course, the actual marking work will4374// not start until the safepoint itself is released in4375// SuspendibleThreadSet::desynchronize().4376doConcurrentMark();4377}43784379return true;4380}43814382void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {4383_drain_in_progress = false;4384set_evac_failure_closure(cl);4385_evac_failure_scan_stack = new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(40, true);4386}43874388void G1CollectedHeap::finalize_for_evac_failure() {4389assert(_evac_failure_scan_stack != NULL &&4390_evac_failure_scan_stack->length() == 0,4391"Postcondition");4392assert(!_drain_in_progress, "Postcondition");4393delete _evac_failure_scan_stack;4394_evac_failure_scan_stack = NULL;4395}43964397void G1CollectedHeap::remove_self_forwarding_pointers() {4398assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");43994400double remove_self_forwards_start = os::elapsedTime();44014402G1ParRemoveSelfForwardPtrsTask rsfp_task(this);44034404if (G1CollectedHeap::use_parallel_gc_threads()) {4405set_par_threads();4406workers()->run_task(&rsfp_task);4407set_par_threads(0);4408} else {4409rsfp_task.work(0);4410}44114412assert(check_cset_heap_region_claim_values(HeapRegion::ParEvacFailureClaimValue), "sanity");44134414// Reset the claim values in the regions in the collection set.4415reset_cset_heap_region_claim_values();44164417assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");44184419// Now restore saved marks, if any.4420assert(_objs_with_preserved_marks.size() ==4421_preserved_marks_of_objs.size(), "Both or none.");4422while (!_objs_with_preserved_marks.is_empty()) {4423oop obj = _objs_with_preserved_marks.pop();4424markOop m = _preserved_marks_of_objs.pop();4425obj->set_mark(m);4426}4427_objs_with_preserved_marks.clear(true);4428_preserved_marks_of_objs.clear(true);44294430g1_policy()->phase_times()->record_evac_fail_remove_self_forwards((os::elapsedTime() - remove_self_forwards_start) * 1000.0);4431}44324433void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {4434_evac_failure_scan_stack->push(obj);4435}44364437void G1CollectedHeap::drain_evac_failure_scan_stack() {4438assert(_evac_failure_scan_stack != NULL, "precondition");44394440while (_evac_failure_scan_stack->length() > 0) {4441oop obj = _evac_failure_scan_stack->pop();4442_evac_failure_closure->set_region(heap_region_containing(obj));4443obj->oop_iterate_backwards(_evac_failure_closure);4444}4445}44464447oop4448G1CollectedHeap::handle_evacuation_failure_par(G1ParScanThreadState* _par_scan_state,4449oop old) {4450assert(obj_in_cs(old),4451err_msg("obj: " PTR_FORMAT " should still be in the CSet",4452(HeapWord*) old));4453markOop m = old->mark();4454oop forward_ptr = old->forward_to_atomic(old);4455if (forward_ptr == NULL) {4456// Forward-to-self succeeded.4457assert(_par_scan_state != NULL, "par scan state");4458OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure();4459uint queue_num = _par_scan_state->queue_num();44604461_evacuation_failed = true;4462_evacuation_failed_info_array[queue_num].register_copy_failure(old->size());4463if (_evac_failure_closure != cl) {4464MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag);4465assert(!_drain_in_progress,4466"Should only be true while someone holds the lock.");4467// Set the global evac-failure closure to the current thread's.4468assert(_evac_failure_closure == NULL, "Or locking has failed.");4469set_evac_failure_closure(cl);4470// Now do the common part.4471handle_evacuation_failure_common(old, m);4472// Reset to NULL.4473set_evac_failure_closure(NULL);4474} else {4475// The lock is already held, and this is recursive.4476assert(_drain_in_progress, "This should only be the recursive case.");4477handle_evacuation_failure_common(old, m);4478}4479return old;4480} else {4481// Forward-to-self failed. Either someone else managed to allocate4482// space for this object (old != forward_ptr) or they beat us in4483// self-forwarding it (old == forward_ptr).4484assert(old == forward_ptr || !obj_in_cs(forward_ptr),4485err_msg("obj: " PTR_FORMAT " forwarded to: " PTR_FORMAT " "4486"should not be in the CSet",4487(HeapWord*) old, (HeapWord*) forward_ptr));4488return forward_ptr;4489}4490}44914492void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) {4493preserve_mark_if_necessary(old, m);44944495HeapRegion* r = heap_region_containing(old);4496if (!r->evacuation_failed()) {4497r->set_evacuation_failed(true);4498_hr_printer.evac_failure(r);4499}45004501push_on_evac_failure_scan_stack(old);45024503if (!_drain_in_progress) {4504// prevent recursion in copy_to_survivor_space()4505_drain_in_progress = true;4506drain_evac_failure_scan_stack();4507_drain_in_progress = false;4508}4509}45104511void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) {4512assert(evacuation_failed(), "Oversaving!");4513// We want to call the "for_promotion_failure" version only in the4514// case of a promotion failure.4515if (m->must_be_preserved_for_promotion_failure(obj)) {4516_objs_with_preserved_marks.push(obj);4517_preserved_marks_of_objs.push(m);4518}4519}45204521void G1ParCopyHelper::mark_object(oop obj) {4522assert(!_g1->heap_region_containing(obj)->in_collection_set(), "should not mark objects in the CSet");45234524// We know that the object is not moving so it's safe to read its size.4525_cm->grayRoot(obj, (size_t) obj->size(), _worker_id);4526}45274528void G1ParCopyHelper::mark_forwarded_object(oop from_obj, oop to_obj) {4529assert(from_obj->is_forwarded(), "from obj should be forwarded");4530assert(from_obj->forwardee() == to_obj, "to obj should be the forwardee");4531assert(from_obj != to_obj, "should not be self-forwarded");45324533assert(_g1->heap_region_containing(from_obj)->in_collection_set(), "from obj should be in the CSet");4534assert(!_g1->heap_region_containing(to_obj)->in_collection_set(), "should not mark objects in the CSet");45354536// The object might be in the process of being copied by another4537// worker so we cannot trust that its to-space image is4538// well-formed. So we have to read its size from its from-space4539// image which we know should not be changing.4540_cm->grayRoot(to_obj, (size_t) from_obj->size(), _worker_id);4541}45424543template <class T>4544void G1ParCopyHelper::do_klass_barrier(T* p, oop new_obj) {4545if (_g1->heap_region_containing_raw(new_obj)->is_young()) {4546_scanned_klass->record_modified_oops();4547}4548}45494550template <G1Barrier barrier, G1Mark do_mark_object>4551template <class T>4552void G1ParCopyClosure<barrier, do_mark_object>::do_oop_work(T* p) {4553T heap_oop = oopDesc::load_heap_oop(p);45544555if (oopDesc::is_null(heap_oop)) {4556return;4557}45584559oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);45604561assert(_worker_id == _par_scan_state->queue_num(), "sanity");45624563const InCSetState state = _g1->in_cset_state(obj);4564if (state.is_in_cset()) {4565oop forwardee;4566markOop m = obj->mark();4567if (m->is_marked()) {4568forwardee = (oop) m->decode_pointer();4569} else {4570forwardee = _par_scan_state->copy_to_survivor_space(state, obj, m);4571}4572assert(forwardee != NULL, "forwardee should not be NULL");4573oopDesc::encode_store_heap_oop(p, forwardee);4574if (do_mark_object != G1MarkNone && forwardee != obj) {4575// If the object is self-forwarded we don't need to explicitly4576// mark it, the evacuation failure protocol will do so.4577mark_forwarded_object(obj, forwardee);4578}45794580if (barrier == G1BarrierKlass) {4581do_klass_barrier(p, forwardee);4582}4583} else {4584if (state.is_humongous()) {4585_g1->set_humongous_is_live(obj);4586}4587// The object is not in collection set. If we're a root scanning4588// closure during an initial mark pause then attempt to mark the object.4589if (do_mark_object == G1MarkFromRoot) {4590mark_object(obj);4591}4592}45934594if (barrier == G1BarrierEvac) {4595_par_scan_state->update_rs(_from, p, _worker_id);4596}4597}45984599template void G1ParCopyClosure<G1BarrierEvac, G1MarkNone>::do_oop_work(oop* p);4600template void G1ParCopyClosure<G1BarrierEvac, G1MarkNone>::do_oop_work(narrowOop* p);46014602class G1ParEvacuateFollowersClosure : public VoidClosure {4603protected:4604G1CollectedHeap* _g1h;4605G1ParScanThreadState* _par_scan_state;4606RefToScanQueueSet* _queues;4607ParallelTaskTerminator* _terminator;46084609G1ParScanThreadState* par_scan_state() { return _par_scan_state; }4610RefToScanQueueSet* queues() { return _queues; }4611ParallelTaskTerminator* terminator() { return _terminator; }46124613public:4614G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,4615G1ParScanThreadState* par_scan_state,4616RefToScanQueueSet* queues,4617ParallelTaskTerminator* terminator)4618: _g1h(g1h), _par_scan_state(par_scan_state),4619_queues(queues), _terminator(terminator) {}46204621void do_void();46224623private:4624inline bool offer_termination();4625};46264627bool G1ParEvacuateFollowersClosure::offer_termination() {4628G1ParScanThreadState* const pss = par_scan_state();4629pss->start_term_time();4630const bool res = terminator()->offer_termination();4631pss->end_term_time();4632return res;4633}46344635void G1ParEvacuateFollowersClosure::do_void() {4636G1ParScanThreadState* const pss = par_scan_state();4637pss->trim_queue();4638do {4639pss->steal_and_trim_queue(queues());4640} while (!offer_termination());4641}46424643class G1KlassScanClosure : public KlassClosure {4644G1ParCopyHelper* _closure;4645bool _process_only_dirty;4646int _count;4647public:4648G1KlassScanClosure(G1ParCopyHelper* closure, bool process_only_dirty)4649: _process_only_dirty(process_only_dirty), _closure(closure), _count(0) {}4650void do_klass(Klass* klass) {4651// If the klass has not been dirtied we know that there's4652// no references into the young gen and we can skip it.4653if (!_process_only_dirty || klass->has_modified_oops()) {4654// Clean the klass since we're going to scavenge all the metadata.4655klass->clear_modified_oops();46564657// Tell the closure that this klass is the Klass to scavenge4658// and is the one to dirty if oops are left pointing into the young gen.4659_closure->set_scanned_klass(klass);46604661klass->oops_do(_closure);46624663_closure->set_scanned_klass(NULL);4664}4665_count++;4666}4667};46684669class G1ParTask : public AbstractGangTask {4670protected:4671G1CollectedHeap* _g1h;4672RefToScanQueueSet *_queues;4673G1RootProcessor* _root_processor;4674ParallelTaskTerminator _terminator;4675uint _n_workers;46764677Mutex _stats_lock;4678Mutex* stats_lock() { return &_stats_lock; }46794680public:4681G1ParTask(G1CollectedHeap* g1h, RefToScanQueueSet *task_queues, G1RootProcessor* root_processor)4682: AbstractGangTask("G1 collection"),4683_g1h(g1h),4684_queues(task_queues),4685_root_processor(root_processor),4686_terminator(0, _queues),4687_stats_lock(Mutex::leaf, "parallel G1 stats lock", true)4688{}46894690RefToScanQueueSet* queues() { return _queues; }46914692RefToScanQueue *work_queue(int i) {4693return queues()->queue(i);4694}46954696ParallelTaskTerminator* terminator() { return &_terminator; }46974698virtual void set_for_termination(int active_workers) {4699_root_processor->set_num_workers(active_workers);4700terminator()->reset_for_reuse(active_workers);4701_n_workers = active_workers;4702}47034704// Helps out with CLD processing.4705//4706// During InitialMark we need to:4707// 1) Scavenge all CLDs for the young GC.4708// 2) Mark all objects directly reachable from strong CLDs.4709template <G1Mark do_mark_object>4710class G1CLDClosure : public CLDClosure {4711G1ParCopyClosure<G1BarrierNone, do_mark_object>* _oop_closure;4712G1ParCopyClosure<G1BarrierKlass, do_mark_object> _oop_in_klass_closure;4713G1KlassScanClosure _klass_in_cld_closure;4714bool _claim;47154716public:4717G1CLDClosure(G1ParCopyClosure<G1BarrierNone, do_mark_object>* oop_closure,4718bool only_young, bool claim)4719: _oop_closure(oop_closure),4720_oop_in_klass_closure(oop_closure->g1(),4721oop_closure->pss(),4722oop_closure->rp()),4723_klass_in_cld_closure(&_oop_in_klass_closure, only_young),4724_claim(claim) {47254726}47274728void do_cld(ClassLoaderData* cld) {4729cld->oops_do(_oop_closure, &_klass_in_cld_closure, _claim);4730}4731};47324733void work(uint worker_id) {4734if (worker_id >= _n_workers) return; // no work needed this round47354736_g1h->g1_policy()->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, os::elapsedTime());47374738{4739ResourceMark rm;4740HandleMark hm;47414742ReferenceProcessor* rp = _g1h->ref_processor_stw();47434744G1ParScanThreadState pss(_g1h, worker_id, rp);4745G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, rp);47464747pss.set_evac_failure_closure(&evac_failure_cl);47484749bool only_young = _g1h->g1_policy()->gcs_are_young();47504751// Non-IM young GC.4752G1ParCopyClosure<G1BarrierNone, G1MarkNone> scan_only_root_cl(_g1h, &pss, rp);4753G1CLDClosure<G1MarkNone> scan_only_cld_cl(&scan_only_root_cl,4754only_young, // Only process dirty klasses.4755false); // No need to claim CLDs.4756// IM young GC.4757// Strong roots closures.4758G1ParCopyClosure<G1BarrierNone, G1MarkFromRoot> scan_mark_root_cl(_g1h, &pss, rp);4759G1CLDClosure<G1MarkFromRoot> scan_mark_cld_cl(&scan_mark_root_cl,4760false, // Process all klasses.4761true); // Need to claim CLDs.4762// Weak roots closures.4763G1ParCopyClosure<G1BarrierNone, G1MarkPromotedFromRoot> scan_mark_weak_root_cl(_g1h, &pss, rp);4764G1CLDClosure<G1MarkPromotedFromRoot> scan_mark_weak_cld_cl(&scan_mark_weak_root_cl,4765false, // Process all klasses.4766true); // Need to claim CLDs.47674768OopClosure* strong_root_cl;4769OopClosure* weak_root_cl;4770CLDClosure* strong_cld_cl;4771CLDClosure* weak_cld_cl;47724773bool trace_metadata = false;47744775if (_g1h->g1_policy()->during_initial_mark_pause()) {4776// We also need to mark copied objects.4777strong_root_cl = &scan_mark_root_cl;4778strong_cld_cl = &scan_mark_cld_cl;4779if (ClassUnloadingWithConcurrentMark) {4780weak_root_cl = &scan_mark_weak_root_cl;4781weak_cld_cl = &scan_mark_weak_cld_cl;4782trace_metadata = true;4783} else {4784weak_root_cl = &scan_mark_root_cl;4785weak_cld_cl = &scan_mark_cld_cl;4786}4787} else {4788strong_root_cl = &scan_only_root_cl;4789weak_root_cl = &scan_only_root_cl;4790strong_cld_cl = &scan_only_cld_cl;4791weak_cld_cl = &scan_only_cld_cl;4792}47934794pss.start_strong_roots();47954796_root_processor->evacuate_roots(strong_root_cl,4797weak_root_cl,4798strong_cld_cl,4799weak_cld_cl,4800trace_metadata,4801worker_id);48024803G1ParPushHeapRSClosure push_heap_rs_cl(_g1h, &pss);4804_root_processor->scan_remembered_sets(&push_heap_rs_cl,4805weak_root_cl,4806worker_id);4807pss.end_strong_roots();48084809{4810double start = os::elapsedTime();4811G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);4812evac.do_void();4813double elapsed_sec = os::elapsedTime() - start;4814double term_sec = pss.term_time();4815_g1h->g1_policy()->phase_times()->add_time_secs(G1GCPhaseTimes::ObjCopy, worker_id, elapsed_sec - term_sec);4816_g1h->g1_policy()->phase_times()->record_time_secs(G1GCPhaseTimes::Termination, worker_id, term_sec);4817_g1h->g1_policy()->phase_times()->record_thread_work_item(G1GCPhaseTimes::Termination, worker_id, pss.term_attempts());4818}4819_g1h->g1_policy()->record_thread_age_table(pss.age_table());4820_g1h->update_surviving_young_words(pss.surviving_young_words()+1);48214822if (ParallelGCVerbose) {4823MutexLocker x(stats_lock());4824pss.print_termination_stats(worker_id);4825}48264827assert(pss.queue_is_empty(), "should be empty");48284829// Close the inner scope so that the ResourceMark and HandleMark4830// destructors are executed here and are included as part of the4831// "GC Worker Time".4832}4833_g1h->g1_policy()->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, os::elapsedTime());4834}4835};48364837class G1StringSymbolTableUnlinkTask : public AbstractGangTask {4838private:4839BoolObjectClosure* _is_alive;4840int _initial_string_table_size;4841int _initial_symbol_table_size;48424843bool _process_strings;4844int _strings_processed;4845int _strings_removed;48464847bool _process_symbols;4848int _symbols_processed;4849int _symbols_removed;48504851bool _do_in_parallel;4852public:4853G1StringSymbolTableUnlinkTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols) :4854AbstractGangTask("String/Symbol Unlinking"),4855_is_alive(is_alive),4856_do_in_parallel(G1CollectedHeap::use_parallel_gc_threads()),4857_process_strings(process_strings), _strings_processed(0), _strings_removed(0),4858_process_symbols(process_symbols), _symbols_processed(0), _symbols_removed(0) {48594860_initial_string_table_size = StringTable::the_table()->table_size();4861_initial_symbol_table_size = SymbolTable::the_table()->table_size();4862if (process_strings) {4863StringTable::clear_parallel_claimed_index();4864}4865if (process_symbols) {4866SymbolTable::clear_parallel_claimed_index();4867}4868}48694870~G1StringSymbolTableUnlinkTask() {4871guarantee(!_process_strings || !_do_in_parallel || StringTable::parallel_claimed_index() >= _initial_string_table_size,4872err_msg("claim value " INT32_FORMAT " after unlink less than initial string table size " INT32_FORMAT,4873StringTable::parallel_claimed_index(), _initial_string_table_size));4874guarantee(!_process_symbols || !_do_in_parallel || SymbolTable::parallel_claimed_index() >= _initial_symbol_table_size,4875err_msg("claim value " INT32_FORMAT " after unlink less than initial symbol table size " INT32_FORMAT,4876SymbolTable::parallel_claimed_index(), _initial_symbol_table_size));48774878if (G1TraceStringSymbolTableScrubbing) {4879gclog_or_tty->print_cr("Cleaned string and symbol table, "4880"strings: " SIZE_FORMAT " processed, " SIZE_FORMAT " removed, "4881"symbols: " SIZE_FORMAT " processed, " SIZE_FORMAT " removed",4882strings_processed(), strings_removed(),4883symbols_processed(), symbols_removed());4884}4885}48864887void work(uint worker_id) {4888if (_do_in_parallel) {4889int strings_processed = 0;4890int strings_removed = 0;4891int symbols_processed = 0;4892int symbols_removed = 0;4893if (_process_strings) {4894StringTable::possibly_parallel_unlink(_is_alive, &strings_processed, &strings_removed);4895Atomic::add(strings_processed, &_strings_processed);4896Atomic::add(strings_removed, &_strings_removed);4897}4898if (_process_symbols) {4899SymbolTable::possibly_parallel_unlink(&symbols_processed, &symbols_removed);4900Atomic::add(symbols_processed, &_symbols_processed);4901Atomic::add(symbols_removed, &_symbols_removed);4902}4903} else {4904if (_process_strings) {4905StringTable::unlink(_is_alive, &_strings_processed, &_strings_removed);4906}4907if (_process_symbols) {4908SymbolTable::unlink(&_symbols_processed, &_symbols_removed);4909}4910}4911}49124913size_t strings_processed() const { return (size_t)_strings_processed; }4914size_t strings_removed() const { return (size_t)_strings_removed; }49154916size_t symbols_processed() const { return (size_t)_symbols_processed; }4917size_t symbols_removed() const { return (size_t)_symbols_removed; }4918};49194920class G1CodeCacheUnloadingTask VALUE_OBJ_CLASS_SPEC {4921private:4922static Monitor* _lock;49234924BoolObjectClosure* const _is_alive;4925const bool _unloading_occurred;4926const uint _num_workers;49274928// Variables used to claim nmethods.4929nmethod* _first_nmethod;4930volatile nmethod* _claimed_nmethod;49314932// The list of nmethods that need to be processed by the second pass.4933volatile nmethod* _postponed_list;4934volatile uint _num_entered_barrier;49354936public:4937G1CodeCacheUnloadingTask(uint num_workers, BoolObjectClosure* is_alive, bool unloading_occurred) :4938_is_alive(is_alive),4939_unloading_occurred(unloading_occurred),4940_num_workers(num_workers),4941_first_nmethod(NULL),4942_claimed_nmethod(NULL),4943_postponed_list(NULL),4944_num_entered_barrier(0)4945{4946nmethod::increase_unloading_clock();4947_first_nmethod = CodeCache::alive_nmethod(CodeCache::first());4948_claimed_nmethod = (volatile nmethod*)_first_nmethod;4949}49504951~G1CodeCacheUnloadingTask() {4952CodeCache::verify_clean_inline_caches();49534954CodeCache::set_needs_cache_clean(false);4955guarantee(CodeCache::scavenge_root_nmethods() == NULL, "Must be");49564957CodeCache::verify_icholder_relocations();4958}49594960private:4961void add_to_postponed_list(nmethod* nm) {4962nmethod* old;4963do {4964old = (nmethod*)_postponed_list;4965nm->set_unloading_next(old);4966} while ((nmethod*)Atomic::cmpxchg_ptr(nm, &_postponed_list, old) != old);4967}49684969void clean_nmethod(nmethod* nm) {4970bool postponed = nm->do_unloading_parallel(_is_alive, _unloading_occurred);49714972if (postponed) {4973// This nmethod referred to an nmethod that has not been cleaned/unloaded yet.4974add_to_postponed_list(nm);4975}49764977// Mark that this thread has been cleaned/unloaded.4978// After this call, it will be safe to ask if this nmethod was unloaded or not.4979nm->set_unloading_clock(nmethod::global_unloading_clock());4980}49814982void clean_nmethod_postponed(nmethod* nm) {4983nm->do_unloading_parallel_postponed(_is_alive, _unloading_occurred);4984}49854986static const int MaxClaimNmethods = 16;49874988void claim_nmethods(nmethod** claimed_nmethods, int *num_claimed_nmethods) {4989nmethod* first;4990nmethod* last;49914992do {4993*num_claimed_nmethods = 0;49944995first = last = (nmethod*)_claimed_nmethod;49964997if (first != NULL) {4998for (int i = 0; i < MaxClaimNmethods; i++) {4999last = CodeCache::alive_nmethod(CodeCache::next(last));50005001if (last == NULL) {5002break;5003}50045005claimed_nmethods[i] = last;5006(*num_claimed_nmethods)++;5007}5008}50095010} while ((nmethod*)Atomic::cmpxchg_ptr(last, &_claimed_nmethod, first) != first);5011}50125013nmethod* claim_postponed_nmethod() {5014nmethod* claim;5015nmethod* next;50165017do {5018claim = (nmethod*)_postponed_list;5019if (claim == NULL) {5020return NULL;5021}50225023next = claim->unloading_next();50245025} while ((nmethod*)Atomic::cmpxchg_ptr(next, &_postponed_list, claim) != claim);50265027return claim;5028}50295030public:5031// Mark that we're done with the first pass of nmethod cleaning.5032void barrier_mark(uint worker_id) {5033MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);5034_num_entered_barrier++;5035if (_num_entered_barrier == _num_workers) {5036ml.notify_all();5037}5038}50395040// See if we have to wait for the other workers to5041// finish their first-pass nmethod cleaning work.5042void barrier_wait(uint worker_id) {5043if (_num_entered_barrier < _num_workers) {5044MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);5045while (_num_entered_barrier < _num_workers) {5046ml.wait(Mutex::_no_safepoint_check_flag, 0, false);5047}5048}5049}50505051// Cleaning and unloading of nmethods. Some work has to be postponed5052// to the second pass, when we know which nmethods survive.5053void work_first_pass(uint worker_id) {5054// The first nmethods is claimed by the first worker.5055if (worker_id == 0 && _first_nmethod != NULL) {5056clean_nmethod(_first_nmethod);5057_first_nmethod = NULL;5058}50595060int num_claimed_nmethods;5061nmethod* claimed_nmethods[MaxClaimNmethods];50625063while (true) {5064claim_nmethods(claimed_nmethods, &num_claimed_nmethods);50655066if (num_claimed_nmethods == 0) {5067break;5068}50695070for (int i = 0; i < num_claimed_nmethods; i++) {5071clean_nmethod(claimed_nmethods[i]);5072}5073}50745075// The nmethod cleaning helps out and does the CodeCache part of MetadataOnStackMark.5076// Need to retire the buffers now that this thread has stopped cleaning nmethods.5077MetadataOnStackMark::retire_buffer_for_thread(Thread::current());5078}50795080void work_second_pass(uint worker_id) {5081nmethod* nm;5082// Take care of postponed nmethods.5083while ((nm = claim_postponed_nmethod()) != NULL) {5084clean_nmethod_postponed(nm);5085}5086}5087};50885089Monitor* G1CodeCacheUnloadingTask::_lock = new Monitor(Mutex::leaf, "Code Cache Unload lock");50905091class G1KlassCleaningTask : public StackObj {5092BoolObjectClosure* _is_alive;5093volatile jint _clean_klass_tree_claimed;5094ClassLoaderDataGraphKlassIteratorAtomic _klass_iterator;50955096public:5097G1KlassCleaningTask(BoolObjectClosure* is_alive) :5098_is_alive(is_alive),5099_clean_klass_tree_claimed(0),5100_klass_iterator() {5101}51025103private:5104bool claim_clean_klass_tree_task() {5105if (_clean_klass_tree_claimed) {5106return false;5107}51085109return Atomic::cmpxchg(1, (jint*)&_clean_klass_tree_claimed, 0) == 0;5110}51115112InstanceKlass* claim_next_klass() {5113Klass* klass;5114do {5115klass =_klass_iterator.next_klass();5116} while (klass != NULL && !klass->oop_is_instance());51175118return (InstanceKlass*)klass;5119}51205121public:51225123void clean_klass(InstanceKlass* ik) {5124ik->clean_weak_instanceklass_links(_is_alive);51255126if (JvmtiExport::has_redefined_a_class()) {5127InstanceKlass::purge_previous_versions(ik);5128}5129}51305131void work() {5132ResourceMark rm;51335134// One worker will clean the subklass/sibling klass tree.5135if (claim_clean_klass_tree_task()) {5136Klass::clean_subklass_tree(_is_alive);5137}51385139// All workers will help cleaning the classes,5140InstanceKlass* klass;5141while ((klass = claim_next_klass()) != NULL) {5142clean_klass(klass);5143}5144}5145};51465147// To minimize the remark pause times, the tasks below are done in parallel.5148class G1ParallelCleaningTask : public AbstractGangTask {5149private:5150G1StringSymbolTableUnlinkTask _string_symbol_task;5151G1CodeCacheUnloadingTask _code_cache_task;5152G1KlassCleaningTask _klass_cleaning_task;51535154public:5155// The constructor is run in the VMThread.5156G1ParallelCleaningTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols, uint num_workers, bool unloading_occurred) :5157AbstractGangTask("Parallel Cleaning"),5158_string_symbol_task(is_alive, process_strings, process_symbols),5159_code_cache_task(num_workers, is_alive, unloading_occurred),5160_klass_cleaning_task(is_alive) {5161}51625163void pre_work_verification() {5164// The VM Thread will have registered Metadata during the single-threaded phase of MetadataStackOnMark.5165assert(Thread::current()->is_VM_thread()5166|| !MetadataOnStackMark::has_buffer_for_thread(Thread::current()), "Should be empty");5167}51685169void post_work_verification() {5170assert(!MetadataOnStackMark::has_buffer_for_thread(Thread::current()), "Should be empty");5171}51725173// The parallel work done by all worker threads.5174void work(uint worker_id) {5175pre_work_verification();51765177// Do first pass of code cache cleaning.5178_code_cache_task.work_first_pass(worker_id);51795180// Let the threads mark that the first pass is done.5181_code_cache_task.barrier_mark(worker_id);51825183// Clean the Strings and Symbols.5184_string_symbol_task.work(worker_id);51855186// Wait for all workers to finish the first code cache cleaning pass.5187_code_cache_task.barrier_wait(worker_id);51885189// Do the second code cache cleaning work, which realize on5190// the liveness information gathered during the first pass.5191_code_cache_task.work_second_pass(worker_id);51925193// Clean all klasses that were not unloaded.5194_klass_cleaning_task.work();51955196post_work_verification();5197}5198};519952005201void G1CollectedHeap::parallel_cleaning(BoolObjectClosure* is_alive,5202bool process_strings,5203bool process_symbols,5204bool class_unloading_occurred) {5205uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?5206workers()->active_workers() : 1);52075208G1ParallelCleaningTask g1_unlink_task(is_alive, process_strings, process_symbols,5209n_workers, class_unloading_occurred);5210if (G1CollectedHeap::use_parallel_gc_threads()) {5211set_par_threads(n_workers);5212workers()->run_task(&g1_unlink_task);5213set_par_threads(0);5214} else {5215g1_unlink_task.work(0);5216}5217}52185219void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive,5220bool process_strings, bool process_symbols) {5221{5222uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?5223_g1h->workers()->active_workers() : 1);5224G1StringSymbolTableUnlinkTask g1_unlink_task(is_alive, process_strings, process_symbols);5225if (G1CollectedHeap::use_parallel_gc_threads()) {5226set_par_threads(n_workers);5227workers()->run_task(&g1_unlink_task);5228set_par_threads(0);5229} else {5230g1_unlink_task.work(0);5231}5232}52335234if (G1StringDedup::is_enabled()) {5235G1StringDedup::unlink(is_alive);5236}5237}52385239class G1RedirtyLoggedCardsTask : public AbstractGangTask {5240private:5241DirtyCardQueueSet* _queue;5242public:5243G1RedirtyLoggedCardsTask(DirtyCardQueueSet* queue) : AbstractGangTask("Redirty Cards"), _queue(queue) { }52445245virtual void work(uint worker_id) {5246G1GCPhaseTimes* phase_times = G1CollectedHeap::heap()->g1_policy()->phase_times();5247G1GCParPhaseTimesTracker x(phase_times, G1GCPhaseTimes::RedirtyCards, worker_id);52485249RedirtyLoggedCardTableEntryClosure cl;5250if (G1CollectedHeap::heap()->use_parallel_gc_threads()) {5251_queue->par_apply_closure_to_all_completed_buffers(&cl);5252} else {5253_queue->apply_closure_to_all_completed_buffers(&cl);5254}52555256phase_times->record_thread_work_item(G1GCPhaseTimes::RedirtyCards, worker_id, cl.num_processed());5257}5258};52595260void G1CollectedHeap::redirty_logged_cards() {5261double redirty_logged_cards_start = os::elapsedTime();52625263uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?5264_g1h->workers()->active_workers() : 1);52655266G1RedirtyLoggedCardsTask redirty_task(&dirty_card_queue_set());5267dirty_card_queue_set().reset_for_par_iteration();5268if (use_parallel_gc_threads()) {5269set_par_threads(n_workers);5270workers()->run_task(&redirty_task);5271set_par_threads(0);5272} else {5273redirty_task.work(0);5274}52755276DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set();5277dcq.merge_bufferlists(&dirty_card_queue_set());5278assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");52795280g1_policy()->phase_times()->record_redirty_logged_cards_time_ms((os::elapsedTime() - redirty_logged_cards_start) * 1000.0);5281}52825283// Weak Reference Processing support52845285// An always "is_alive" closure that is used to preserve referents.5286// If the object is non-null then it's alive. Used in the preservation5287// of referent objects that are pointed to by reference objects5288// discovered by the CM ref processor.5289class G1AlwaysAliveClosure: public BoolObjectClosure {5290G1CollectedHeap* _g1;5291public:5292G1AlwaysAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}5293bool do_object_b(oop p) {5294if (p != NULL) {5295return true;5296}5297return false;5298}5299};53005301bool G1STWIsAliveClosure::do_object_b(oop p) {5302// An object is reachable if it is outside the collection set,5303// or is inside and copied.5304return !_g1->obj_in_cs(p) || p->is_forwarded();5305}53065307// Non Copying Keep Alive closure5308class G1KeepAliveClosure: public OopClosure {5309G1CollectedHeap* _g1;5310public:5311G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}5312void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }5313void do_oop(oop* p) {5314oop obj = *p;5315assert(obj != NULL, "the caller should have filtered out NULL values");53165317const InCSetState cset_state = _g1->in_cset_state(obj);5318if (!cset_state.is_in_cset_or_humongous()) {5319return;5320}5321if (cset_state.is_in_cset()) {5322assert( obj->is_forwarded(), "invariant" );5323*p = obj->forwardee();5324} else {5325assert(!obj->is_forwarded(), "invariant" );5326assert(cset_state.is_humongous(),5327err_msg("Only allowed InCSet state is IsHumongous, but is %d", cset_state.value()));5328_g1->set_humongous_is_live(obj);5329}5330}5331};53325333// Copying Keep Alive closure - can be called from both5334// serial and parallel code as long as different worker5335// threads utilize different G1ParScanThreadState instances5336// and different queues.53375338class G1CopyingKeepAliveClosure: public OopClosure {5339G1CollectedHeap* _g1h;5340OopClosure* _copy_non_heap_obj_cl;5341G1ParScanThreadState* _par_scan_state;53425343public:5344G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,5345OopClosure* non_heap_obj_cl,5346G1ParScanThreadState* pss):5347_g1h(g1h),5348_copy_non_heap_obj_cl(non_heap_obj_cl),5349_par_scan_state(pss)5350{}53515352virtual void do_oop(narrowOop* p) { do_oop_work(p); }5353virtual void do_oop( oop* p) { do_oop_work(p); }53545355template <class T> void do_oop_work(T* p) {5356oop obj = oopDesc::load_decode_heap_oop(p);53575358if (_g1h->is_in_cset_or_humongous(obj)) {5359// If the referent object has been forwarded (either copied5360// to a new location or to itself in the event of an5361// evacuation failure) then we need to update the reference5362// field and, if both reference and referent are in the G15363// heap, update the RSet for the referent.5364//5365// If the referent has not been forwarded then we have to keep5366// it alive by policy. Therefore we have copy the referent.5367//5368// If the reference field is in the G1 heap then we can push5369// on the PSS queue. When the queue is drained (after each5370// phase of reference processing) the object and it's followers5371// will be copied, the reference field set to point to the5372// new location, and the RSet updated. Otherwise we need to5373// use the the non-heap or metadata closures directly to copy5374// the referent object and update the pointer, while avoiding5375// updating the RSet.53765377if (_g1h->is_in_g1_reserved(p)) {5378_par_scan_state->push_on_queue(p);5379} else {5380assert(!Metaspace::contains((const void*)p),5381err_msg("Unexpectedly found a pointer from metadata: "5382PTR_FORMAT, p));5383_copy_non_heap_obj_cl->do_oop(p);5384}5385}5386}5387};53885389// Serial drain queue closure. Called as the 'complete_gc'5390// closure for each discovered list in some of the5391// reference processing phases.53925393class G1STWDrainQueueClosure: public VoidClosure {5394protected:5395G1CollectedHeap* _g1h;5396G1ParScanThreadState* _par_scan_state;53975398G1ParScanThreadState* par_scan_state() { return _par_scan_state; }53995400public:5401G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :5402_g1h(g1h),5403_par_scan_state(pss)5404{ }54055406void do_void() {5407G1ParScanThreadState* const pss = par_scan_state();5408pss->trim_queue();5409}5410};54115412// Parallel Reference Processing closures54135414// Implementation of AbstractRefProcTaskExecutor for parallel reference5415// processing during G1 evacuation pauses.54165417class G1STWRefProcTaskExecutor: public AbstractRefProcTaskExecutor {5418private:5419G1CollectedHeap* _g1h;5420RefToScanQueueSet* _queues;5421FlexibleWorkGang* _workers;5422int _active_workers;54235424public:5425G1STWRefProcTaskExecutor(G1CollectedHeap* g1h,5426FlexibleWorkGang* workers,5427RefToScanQueueSet *task_queues,5428int n_workers) :5429_g1h(g1h),5430_queues(task_queues),5431_workers(workers),5432_active_workers(n_workers)5433{5434assert(n_workers > 0, "shouldn't call this otherwise");5435}54365437// Executes the given task using concurrent marking worker threads.5438virtual void execute(ProcessTask& task);5439virtual void execute(EnqueueTask& task);5440};54415442// Gang task for possibly parallel reference processing54435444class G1STWRefProcTaskProxy: public AbstractGangTask {5445typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;5446ProcessTask& _proc_task;5447G1CollectedHeap* _g1h;5448RefToScanQueueSet *_task_queues;5449ParallelTaskTerminator* _terminator;54505451public:5452G1STWRefProcTaskProxy(ProcessTask& proc_task,5453G1CollectedHeap* g1h,5454RefToScanQueueSet *task_queues,5455ParallelTaskTerminator* terminator) :5456AbstractGangTask("Process reference objects in parallel"),5457_proc_task(proc_task),5458_g1h(g1h),5459_task_queues(task_queues),5460_terminator(terminator)5461{}54625463virtual void work(uint worker_id) {5464// The reference processing task executed by a single worker.5465ResourceMark rm;5466HandleMark hm;54675468G1STWIsAliveClosure is_alive(_g1h);54695470G1ParScanThreadState pss(_g1h, worker_id, NULL);5471G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);54725473pss.set_evac_failure_closure(&evac_failure_cl);54745475G1ParScanExtRootClosure only_copy_non_heap_cl(_g1h, &pss, NULL);54765477G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);54785479OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl;54805481if (_g1h->g1_policy()->during_initial_mark_pause()) {5482// We also need to mark copied objects.5483copy_non_heap_cl = ©_mark_non_heap_cl;5484}54855486// Keep alive closure.5487G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss);54885489// Complete GC closure5490G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _task_queues, _terminator);54915492// Call the reference processing task's work routine.5493_proc_task.work(worker_id, is_alive, keep_alive, drain_queue);54945495// Note we cannot assert that the refs array is empty here as not all5496// of the processing tasks (specifically phase2 - pp2_work) execute5497// the complete_gc closure (which ordinarily would drain the queue) so5498// the queue may not be empty.5499}5500};55015502// Driver routine for parallel reference processing.5503// Creates an instance of the ref processing gang5504// task and has the worker threads execute it.5505void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task) {5506assert(_workers != NULL, "Need parallel worker threads.");55075508ParallelTaskTerminator terminator(_active_workers, _queues);5509G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _queues, &terminator);55105511_g1h->set_par_threads(_active_workers);5512_workers->run_task(&proc_task_proxy);5513_g1h->set_par_threads(0);5514}55155516// Gang task for parallel reference enqueueing.55175518class G1STWRefEnqueueTaskProxy: public AbstractGangTask {5519typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;5520EnqueueTask& _enq_task;55215522public:5523G1STWRefEnqueueTaskProxy(EnqueueTask& enq_task) :5524AbstractGangTask("Enqueue reference objects in parallel"),5525_enq_task(enq_task)5526{ }55275528virtual void work(uint worker_id) {5529_enq_task.work(worker_id);5530}5531};55325533// Driver routine for parallel reference enqueueing.5534// Creates an instance of the ref enqueueing gang5535// task and has the worker threads execute it.55365537void G1STWRefProcTaskExecutor::execute(EnqueueTask& enq_task) {5538assert(_workers != NULL, "Need parallel worker threads.");55395540G1STWRefEnqueueTaskProxy enq_task_proxy(enq_task);55415542_g1h->set_par_threads(_active_workers);5543_workers->run_task(&enq_task_proxy);5544_g1h->set_par_threads(0);5545}55465547// End of weak reference support closures55485549// Abstract task used to preserve (i.e. copy) any referent objects5550// that are in the collection set and are pointed to by reference5551// objects discovered by the CM ref processor.55525553class G1ParPreserveCMReferentsTask: public AbstractGangTask {5554protected:5555G1CollectedHeap* _g1h;5556RefToScanQueueSet *_queues;5557ParallelTaskTerminator _terminator;5558uint _n_workers;55595560public:5561G1ParPreserveCMReferentsTask(G1CollectedHeap* g1h,int workers, RefToScanQueueSet *task_queues) :5562AbstractGangTask("ParPreserveCMReferents"),5563_g1h(g1h),5564_queues(task_queues),5565_terminator(workers, _queues),5566_n_workers(workers)5567{ }55685569void work(uint worker_id) {5570ResourceMark rm;5571HandleMark hm;55725573G1ParScanThreadState pss(_g1h, worker_id, NULL);5574G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);55755576pss.set_evac_failure_closure(&evac_failure_cl);55775578assert(pss.queue_is_empty(), "both queue and overflow should be empty");55795580G1ParScanExtRootClosure only_copy_non_heap_cl(_g1h, &pss, NULL);55815582G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);55835584OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl;55855586if (_g1h->g1_policy()->during_initial_mark_pause()) {5587// We also need to mark copied objects.5588copy_non_heap_cl = ©_mark_non_heap_cl;5589}55905591// Is alive closure5592G1AlwaysAliveClosure always_alive(_g1h);55935594// Copying keep alive closure. Applied to referent objects that need5595// to be copied.5596G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss);55975598ReferenceProcessor* rp = _g1h->ref_processor_cm();55995600uint limit = ReferenceProcessor::number_of_subclasses_of_ref() * rp->max_num_q();5601uint stride = MIN2(MAX2(_n_workers, 1U), limit);56025603// limit is set using max_num_q() - which was set using ParallelGCThreads.5604// So this must be true - but assert just in case someone decides to5605// change the worker ids.5606assert(0 <= worker_id && worker_id < limit, "sanity");5607assert(!rp->discovery_is_atomic(), "check this code");56085609// Select discovered lists [i, i+stride, i+2*stride,...,limit)5610for (uint idx = worker_id; idx < limit; idx += stride) {5611DiscoveredList& ref_list = rp->discovered_refs()[idx];56125613DiscoveredListIterator iter(ref_list, &keep_alive, &always_alive);5614while (iter.has_next()) {5615// Since discovery is not atomic for the CM ref processor, we5616// can see some null referent objects.5617iter.load_ptrs(DEBUG_ONLY(true));5618oop ref = iter.obj();56195620// This will filter nulls.5621if (iter.is_referent_alive()) {5622iter.make_referent_alive();5623}5624iter.move_to_next();5625}5626}56275628// Drain the queue - which may cause stealing5629G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _queues, &_terminator);5630drain_queue.do_void();5631// Allocation buffers were retired at the end of G1ParEvacuateFollowersClosure5632assert(pss.queue_is_empty(), "should be");5633}5634};56355636// Weak Reference processing during an evacuation pause (part 1).5637void G1CollectedHeap::process_discovered_references(uint no_of_gc_workers) {5638double ref_proc_start = os::elapsedTime();56395640ReferenceProcessor* rp = _ref_processor_stw;5641assert(rp->discovery_enabled(), "should have been enabled");56425643// Any reference objects, in the collection set, that were 'discovered'5644// by the CM ref processor should have already been copied (either by5645// applying the external root copy closure to the discovered lists, or5646// by following an RSet entry).5647//5648// But some of the referents, that are in the collection set, that these5649// reference objects point to may not have been copied: the STW ref5650// processor would have seen that the reference object had already5651// been 'discovered' and would have skipped discovering the reference,5652// but would not have treated the reference object as a regular oop.5653// As a result the copy closure would not have been applied to the5654// referent object.5655//5656// We need to explicitly copy these referent objects - the references5657// will be processed at the end of remarking.5658//5659// We also need to do this copying before we process the reference5660// objects discovered by the STW ref processor in case one of these5661// referents points to another object which is also referenced by an5662// object discovered by the STW ref processor.56635664assert(!G1CollectedHeap::use_parallel_gc_threads() ||5665no_of_gc_workers == workers()->active_workers(),5666"Need to reset active GC workers");56675668set_par_threads(no_of_gc_workers);5669G1ParPreserveCMReferentsTask keep_cm_referents(this,5670no_of_gc_workers,5671_task_queues);56725673if (G1CollectedHeap::use_parallel_gc_threads()) {5674workers()->run_task(&keep_cm_referents);5675} else {5676keep_cm_referents.work(0);5677}56785679set_par_threads(0);56805681// Closure to test whether a referent is alive.5682G1STWIsAliveClosure is_alive(this);56835684// Even when parallel reference processing is enabled, the processing5685// of JNI refs is serial and performed serially by the current thread5686// rather than by a worker. The following PSS will be used for processing5687// JNI refs.56885689// Use only a single queue for this PSS.5690G1ParScanThreadState pss(this, 0, NULL);56915692// We do not embed a reference processor in the copying/scanning5693// closures while we're actually processing the discovered5694// reference objects.5695G1ParScanHeapEvacFailureClosure evac_failure_cl(this, &pss, NULL);56965697pss.set_evac_failure_closure(&evac_failure_cl);56985699assert(pss.queue_is_empty(), "pre-condition");57005701G1ParScanExtRootClosure only_copy_non_heap_cl(this, &pss, NULL);57025703G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(this, &pss, NULL);57045705OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl;57065707if (_g1h->g1_policy()->during_initial_mark_pause()) {5708// We also need to mark copied objects.5709copy_non_heap_cl = ©_mark_non_heap_cl;5710}57115712// Keep alive closure.5713G1CopyingKeepAliveClosure keep_alive(this, copy_non_heap_cl, &pss);57145715// Serial Complete GC closure5716G1STWDrainQueueClosure drain_queue(this, &pss);57175718// Setup the soft refs policy...5719rp->setup_policy(false);57205721ReferenceProcessorStats stats;5722if (!rp->processing_is_mt()) {5723// Serial reference processing...5724stats = rp->process_discovered_references(&is_alive,5725&keep_alive,5726&drain_queue,5727NULL,5728_gc_timer_stw,5729_gc_tracer_stw->gc_id());5730} else {5731// Parallel reference processing5732assert(rp->num_q() == no_of_gc_workers, "sanity");5733assert(no_of_gc_workers <= rp->max_num_q(), "sanity");57345735G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);5736stats = rp->process_discovered_references(&is_alive,5737&keep_alive,5738&drain_queue,5739&par_task_executor,5740_gc_timer_stw,5741_gc_tracer_stw->gc_id());5742}57435744_gc_tracer_stw->report_gc_reference_stats(stats);57455746// We have completed copying any necessary live referent objects.5747assert(pss.queue_is_empty(), "both queue and overflow should be empty");57485749double ref_proc_time = os::elapsedTime() - ref_proc_start;5750g1_policy()->phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);5751}57525753// Weak Reference processing during an evacuation pause (part 2).5754void G1CollectedHeap::enqueue_discovered_references(uint no_of_gc_workers) {5755double ref_enq_start = os::elapsedTime();57565757ReferenceProcessor* rp = _ref_processor_stw;5758assert(!rp->discovery_enabled(), "should have been disabled as part of processing");57595760// Now enqueue any remaining on the discovered lists on to5761// the pending list.5762if (!rp->processing_is_mt()) {5763// Serial reference processing...5764rp->enqueue_discovered_references();5765} else {5766// Parallel reference enqueueing57675768assert(no_of_gc_workers == workers()->active_workers(),5769"Need to reset active workers");5770assert(rp->num_q() == no_of_gc_workers, "sanity");5771assert(no_of_gc_workers <= rp->max_num_q(), "sanity");57725773G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);5774rp->enqueue_discovered_references(&par_task_executor);5775}57765777rp->verify_no_references_recorded();5778assert(!rp->discovery_enabled(), "should have been disabled");57795780// FIXME5781// CM's reference processing also cleans up the string and symbol tables.5782// Should we do that here also? We could, but it is a serial operation5783// and could significantly increase the pause time.57845785double ref_enq_time = os::elapsedTime() - ref_enq_start;5786g1_policy()->phase_times()->record_ref_enq_time(ref_enq_time * 1000.0);5787}57885789void G1CollectedHeap::evacuate_collection_set(EvacuationInfo& evacuation_info) {5790_expand_heap_after_alloc_failure = true;5791_evacuation_failed = false;57925793// Should G1EvacuationFailureALot be in effect for this GC?5794NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)57955796g1_rem_set()->prepare_for_oops_into_collection_set_do();57975798// Disable the hot card cache.5799G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();5800hot_card_cache->reset_hot_cache_claimed_index();5801hot_card_cache->set_use_cache(false);58025803const uint n_workers = workers()->active_workers();5804assert(UseDynamicNumberOfGCThreads ||5805n_workers == workers()->total_workers(),5806"If not dynamic should be using all the workers");5807set_par_threads(n_workers);58085809init_for_evac_failure(NULL);58105811rem_set()->prepare_for_younger_refs_iterate(true);58125813assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty");5814double start_par_time_sec = os::elapsedTime();5815double end_par_time_sec;58165817{5818G1RootProcessor root_processor(this);5819G1ParTask g1_par_task(this, _task_queues, &root_processor);5820// InitialMark needs claim bits to keep track of the marked-through CLDs.5821if (g1_policy()->during_initial_mark_pause()) {5822ClassLoaderDataGraph::clear_claimed_marks();5823}58245825if (G1CollectedHeap::use_parallel_gc_threads()) {5826// The individual threads will set their evac-failure closures.5827if (ParallelGCVerbose) G1ParScanThreadState::print_termination_stats_hdr();5828// These tasks use ShareHeap::_process_strong_tasks5829assert(UseDynamicNumberOfGCThreads ||5830workers()->active_workers() == workers()->total_workers(),5831"If not dynamic should be using all the workers");5832workers()->run_task(&g1_par_task);5833} else {5834g1_par_task.set_for_termination(n_workers);5835g1_par_task.work(0);5836}5837end_par_time_sec = os::elapsedTime();58385839// Closing the inner scope will execute the destructor5840// for the G1RootProcessor object. We record the current5841// elapsed time before closing the scope so that time5842// taken for the destructor is NOT included in the5843// reported parallel time.5844}58455846G1GCPhaseTimes* phase_times = g1_policy()->phase_times();58475848double par_time_ms = (end_par_time_sec - start_par_time_sec) * 1000.0;5849phase_times->record_par_time(par_time_ms);58505851double code_root_fixup_time_ms =5852(os::elapsedTime() - end_par_time_sec) * 1000.0;5853phase_times->record_code_root_fixup_time(code_root_fixup_time_ms);58545855set_par_threads(0);58565857// Process any discovered reference objects - we have5858// to do this _before_ we retire the GC alloc regions5859// as we may have to copy some 'reachable' referent5860// objects (and their reachable sub-graphs) that were5861// not copied during the pause.5862process_discovered_references(n_workers);58635864if (G1StringDedup::is_enabled()) {5865double fixup_start = os::elapsedTime();58665867G1STWIsAliveClosure is_alive(this);5868G1KeepAliveClosure keep_alive(this);5869G1StringDedup::unlink_or_oops_do(&is_alive, &keep_alive, true, phase_times);58705871double fixup_time_ms = (os::elapsedTime() - fixup_start) * 1000.0;5872phase_times->record_string_dedup_fixup_time(fixup_time_ms);5873}58745875_allocator->release_gc_alloc_regions(n_workers, evacuation_info);5876g1_rem_set()->cleanup_after_oops_into_collection_set_do();58775878// Reset and re-enable the hot card cache.5879// Note the counts for the cards in the regions in the5880// collection set are reset when the collection set is freed.5881hot_card_cache->reset_hot_cache();5882hot_card_cache->set_use_cache(true);58835884purge_code_root_memory();58855886if (g1_policy()->during_initial_mark_pause()) {5887// Reset the claim values set during marking the strong code roots5888reset_heap_region_claim_values();5889}58905891finalize_for_evac_failure();58925893if (evacuation_failed()) {5894remove_self_forwarding_pointers();58955896// Reset the G1EvacuationFailureALot counters and flags5897// Note: the values are reset only when an actual5898// evacuation failure occurs.5899NOT_PRODUCT(reset_evacuation_should_fail();)5900}59015902// Enqueue any remaining references remaining on the STW5903// reference processor's discovered lists. We need to do5904// this after the card table is cleaned (and verified) as5905// the act of enqueueing entries on to the pending list5906// will log these updates (and dirty their associated5907// cards). We need these updates logged to update any5908// RSets.5909enqueue_discovered_references(n_workers);59105911redirty_logged_cards();5912COMPILER2_PRESENT(DerivedPointerTable::update_pointers());5913}59145915void G1CollectedHeap::free_region(HeapRegion* hr,5916FreeRegionList* free_list,5917bool par,5918bool locked) {5919assert(!hr->is_free(), "the region should not be free");5920assert(!hr->is_empty(), "the region should not be empty");5921assert(_hrm.is_available(hr->hrm_index()), "region should be committed");5922assert(free_list != NULL, "pre-condition");59235924if (G1VerifyBitmaps) {5925MemRegion mr(hr->bottom(), hr->end());5926concurrent_mark()->clearRangePrevBitmap(mr);5927}59285929// Clear the card counts for this region.5930// Note: we only need to do this if the region is not young5931// (since we don't refine cards in young regions).5932if (!hr->is_young()) {5933_cg1r->hot_card_cache()->reset_card_counts(hr);5934}5935hr->hr_clear(par, true /* clear_space */, locked /* locked */);5936free_list->add_ordered(hr);5937}59385939void G1CollectedHeap::free_humongous_region(HeapRegion* hr,5940FreeRegionList* free_list,5941bool par) {5942assert(hr->startsHumongous(), "this is only for starts humongous regions");5943assert(free_list != NULL, "pre-condition");59445945size_t hr_capacity = hr->capacity();5946// We need to read this before we make the region non-humongous,5947// otherwise the information will be gone.5948uint last_index = hr->last_hc_index();5949hr->clear_humongous();5950free_region(hr, free_list, par);59515952uint i = hr->hrm_index() + 1;5953while (i < last_index) {5954HeapRegion* curr_hr = region_at(i);5955assert(curr_hr->continuesHumongous(), "invariant");5956curr_hr->clear_humongous();5957free_region(curr_hr, free_list, par);5958i += 1;5959}5960}59615962void G1CollectedHeap::remove_from_old_sets(const HeapRegionSetCount& old_regions_removed,5963const HeapRegionSetCount& humongous_regions_removed) {5964if (old_regions_removed.length() > 0 || humongous_regions_removed.length() > 0) {5965MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag);5966_old_set.bulk_remove(old_regions_removed);5967_humongous_set.bulk_remove(humongous_regions_removed);5968}59695970}59715972void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {5973assert(list != NULL, "list can't be null");5974if (!list->is_empty()) {5975MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag);5976_hrm.insert_list_into_free_list(list);5977}5978}59795980void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {5981_allocator->decrease_used(bytes);5982}59835984class G1ParCleanupCTTask : public AbstractGangTask {5985G1SATBCardTableModRefBS* _ct_bs;5986G1CollectedHeap* _g1h;5987HeapRegion* volatile _su_head;5988public:5989G1ParCleanupCTTask(G1SATBCardTableModRefBS* ct_bs,5990G1CollectedHeap* g1h) :5991AbstractGangTask("G1 Par Cleanup CT Task"),5992_ct_bs(ct_bs), _g1h(g1h) { }59935994void work(uint worker_id) {5995HeapRegion* r;5996while (r = _g1h->pop_dirty_cards_region()) {5997clear_cards(r);5998}5999}60006001void clear_cards(HeapRegion* r) {6002// Cards of the survivors should have already been dirtied.6003if (!r->is_survivor()) {6004_ct_bs->clear(MemRegion(r->bottom(), r->end()));6005}6006}6007};60086009#ifndef PRODUCT6010class G1VerifyCardTableCleanup: public HeapRegionClosure {6011G1CollectedHeap* _g1h;6012G1SATBCardTableModRefBS* _ct_bs;6013public:6014G1VerifyCardTableCleanup(G1CollectedHeap* g1h, G1SATBCardTableModRefBS* ct_bs)6015: _g1h(g1h), _ct_bs(ct_bs) { }6016virtual bool doHeapRegion(HeapRegion* r) {6017if (r->is_survivor()) {6018_g1h->verify_dirty_region(r);6019} else {6020_g1h->verify_not_dirty_region(r);6021}6022return false;6023}6024};60256026void G1CollectedHeap::verify_not_dirty_region(HeapRegion* hr) {6027// All of the region should be clean.6028G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();6029MemRegion mr(hr->bottom(), hr->end());6030ct_bs->verify_not_dirty_region(mr);6031}60326033void G1CollectedHeap::verify_dirty_region(HeapRegion* hr) {6034// We cannot guarantee that [bottom(),end()] is dirty. Threads6035// dirty allocated blocks as they allocate them. The thread that6036// retires each region and replaces it with a new one will do a6037// maximal allocation to fill in [pre_dummy_top(),end()] but will6038// not dirty that area (one less thing to have to do while holding6039// a lock). So we can only verify that [bottom(),pre_dummy_top()]6040// is dirty.6041G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();6042MemRegion mr(hr->bottom(), hr->pre_dummy_top());6043if (hr->is_young()) {6044ct_bs->verify_g1_young_region(mr);6045} else {6046ct_bs->verify_dirty_region(mr);6047}6048}60496050void G1CollectedHeap::verify_dirty_young_list(HeapRegion* head) {6051G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();6052for (HeapRegion* hr = head; hr != NULL; hr = hr->get_next_young_region()) {6053verify_dirty_region(hr);6054}6055}60566057void G1CollectedHeap::verify_dirty_young_regions() {6058verify_dirty_young_list(_young_list->first_region());6059}60606061bool G1CollectedHeap::verify_no_bits_over_tams(const char* bitmap_name, CMBitMapRO* bitmap,6062HeapWord* tams, HeapWord* end) {6063guarantee(tams <= end,6064err_msg("tams: " PTR_FORMAT " end: " PTR_FORMAT, tams, end));6065HeapWord* result = bitmap->getNextMarkedWordAddress(tams, end);6066if (result < end) {6067gclog_or_tty->cr();6068gclog_or_tty->print_cr("## wrong marked address on %s bitmap: " PTR_FORMAT,6069bitmap_name, result);6070gclog_or_tty->print_cr("## %s tams: " PTR_FORMAT " end: " PTR_FORMAT,6071bitmap_name, tams, end);6072return false;6073}6074return true;6075}60766077bool G1CollectedHeap::verify_bitmaps(const char* caller, HeapRegion* hr) {6078CMBitMapRO* prev_bitmap = concurrent_mark()->prevMarkBitMap();6079CMBitMapRO* next_bitmap = (CMBitMapRO*) concurrent_mark()->nextMarkBitMap();60806081HeapWord* bottom = hr->bottom();6082HeapWord* ptams = hr->prev_top_at_mark_start();6083HeapWord* ntams = hr->next_top_at_mark_start();6084HeapWord* end = hr->end();60856086bool res_p = verify_no_bits_over_tams("prev", prev_bitmap, ptams, end);60876088bool res_n = true;6089// We reset mark_in_progress() before we reset _cmThread->in_progress() and in this window6090// we do the clearing of the next bitmap concurrently. Thus, we can not verify the bitmap6091// if we happen to be in that state.6092if (mark_in_progress() || !_cmThread->in_progress()) {6093res_n = verify_no_bits_over_tams("next", next_bitmap, ntams, end);6094}6095if (!res_p || !res_n) {6096gclog_or_tty->print_cr("#### Bitmap verification failed for " HR_FORMAT,6097HR_FORMAT_PARAMS(hr));6098gclog_or_tty->print_cr("#### Caller: %s", caller);6099return false;6100}6101return true;6102}61036104void G1CollectedHeap::check_bitmaps(const char* caller, HeapRegion* hr) {6105if (!G1VerifyBitmaps) return;61066107guarantee(verify_bitmaps(caller, hr), "bitmap verification");6108}61096110class G1VerifyBitmapClosure : public HeapRegionClosure {6111private:6112const char* _caller;6113G1CollectedHeap* _g1h;6114bool _failures;61156116public:6117G1VerifyBitmapClosure(const char* caller, G1CollectedHeap* g1h) :6118_caller(caller), _g1h(g1h), _failures(false) { }61196120bool failures() { return _failures; }61216122virtual bool doHeapRegion(HeapRegion* hr) {6123if (hr->continuesHumongous()) return false;61246125bool result = _g1h->verify_bitmaps(_caller, hr);6126if (!result) {6127_failures = true;6128}6129return false;6130}6131};61326133void G1CollectedHeap::check_bitmaps(const char* caller) {6134if (!G1VerifyBitmaps) return;61356136G1VerifyBitmapClosure cl(caller, this);6137heap_region_iterate(&cl);6138guarantee(!cl.failures(), "bitmap verification");6139}61406141class G1CheckCSetFastTableClosure : public HeapRegionClosure {6142private:6143bool _failures;6144public:6145G1CheckCSetFastTableClosure() : HeapRegionClosure(), _failures(false) { }61466147virtual bool doHeapRegion(HeapRegion* hr) {6148uint i = hr->hrm_index();6149InCSetState cset_state = (InCSetState) G1CollectedHeap::heap()->_in_cset_fast_test.get_by_index(i);6150if (hr->isHumongous()) {6151if (hr->in_collection_set()) {6152gclog_or_tty->print_cr("\n## humongous region %u in CSet", i);6153_failures = true;6154return true;6155}6156if (cset_state.is_in_cset()) {6157gclog_or_tty->print_cr("\n## inconsistent cset state %d for humongous region %u", cset_state.value(), i);6158_failures = true;6159return true;6160}6161if (hr->continuesHumongous() && cset_state.is_humongous()) {6162gclog_or_tty->print_cr("\n## inconsistent cset state %d for continues humongous region %u", cset_state.value(), i);6163_failures = true;6164return true;6165}6166} else {6167if (cset_state.is_humongous()) {6168gclog_or_tty->print_cr("\n## inconsistent cset state %d for non-humongous region %u", cset_state.value(), i);6169_failures = true;6170return true;6171}6172if (hr->in_collection_set() != cset_state.is_in_cset()) {6173gclog_or_tty->print_cr("\n## in CSet %d / cset state %d inconsistency for region %u",6174hr->in_collection_set(), cset_state.value(), i);6175_failures = true;6176return true;6177}6178if (cset_state.is_in_cset()) {6179if (hr->is_young() != (cset_state.is_young())) {6180gclog_or_tty->print_cr("\n## is_young %d / cset state %d inconsistency for region %u",6181hr->is_young(), cset_state.value(), i);6182_failures = true;6183return true;6184}6185if (hr->is_old() != (cset_state.is_old())) {6186gclog_or_tty->print_cr("\n## is_old %d / cset state %d inconsistency for region %u",6187hr->is_old(), cset_state.value(), i);6188_failures = true;6189return true;6190}6191}6192}6193return false;6194}61956196bool failures() const { return _failures; }6197};61986199bool G1CollectedHeap::check_cset_fast_test() {6200G1CheckCSetFastTableClosure cl;6201_hrm.iterate(&cl);6202return !cl.failures();6203}6204#endif // PRODUCT62056206void G1CollectedHeap::cleanUpCardTable() {6207G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();6208double start = os::elapsedTime();62096210{6211// Iterate over the dirty cards region list.6212G1ParCleanupCTTask cleanup_task(ct_bs, this);62136214if (G1CollectedHeap::use_parallel_gc_threads()) {6215set_par_threads();6216workers()->run_task(&cleanup_task);6217set_par_threads(0);6218} else {6219while (_dirty_cards_region_list) {6220HeapRegion* r = _dirty_cards_region_list;6221cleanup_task.clear_cards(r);6222_dirty_cards_region_list = r->get_next_dirty_cards_region();6223if (_dirty_cards_region_list == r) {6224// The last region.6225_dirty_cards_region_list = NULL;6226}6227r->set_next_dirty_cards_region(NULL);6228}6229}6230#ifndef PRODUCT6231if (G1VerifyCTCleanup || VerifyAfterGC) {6232G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs);6233heap_region_iterate(&cleanup_verifier);6234}6235#endif6236}62376238double elapsed = os::elapsedTime() - start;6239g1_policy()->phase_times()->record_clear_ct_time(elapsed * 1000.0);6240}62416242void G1CollectedHeap::free_collection_set(HeapRegion* cs_head, EvacuationInfo& evacuation_info) {6243size_t pre_used = 0;6244FreeRegionList local_free_list("Local List for CSet Freeing");62456246double young_time_ms = 0.0;6247double non_young_time_ms = 0.0;62486249// Since the collection set is a superset of the the young list,6250// all we need to do to clear the young list is clear its6251// head and length, and unlink any young regions in the code below6252_young_list->clear();62536254G1CollectorPolicy* policy = g1_policy();62556256double start_sec = os::elapsedTime();6257bool non_young = true;62586259HeapRegion* cur = cs_head;6260int age_bound = -1;6261size_t rs_lengths = 0;62626263while (cur != NULL) {6264assert(!is_on_master_free_list(cur), "sanity");6265if (non_young) {6266if (cur->is_young()) {6267double end_sec = os::elapsedTime();6268double elapsed_ms = (end_sec - start_sec) * 1000.0;6269non_young_time_ms += elapsed_ms;62706271start_sec = os::elapsedTime();6272non_young = false;6273}6274} else {6275if (!cur->is_young()) {6276double end_sec = os::elapsedTime();6277double elapsed_ms = (end_sec - start_sec) * 1000.0;6278young_time_ms += elapsed_ms;62796280start_sec = os::elapsedTime();6281non_young = true;6282}6283}62846285rs_lengths += cur->rem_set()->occupied_locked();62866287HeapRegion* next = cur->next_in_collection_set();6288assert(cur->in_collection_set(), "bad CS");6289cur->set_next_in_collection_set(NULL);6290cur->set_in_collection_set(false);62916292if (cur->is_young()) {6293int index = cur->young_index_in_cset();6294assert(index != -1, "invariant");6295assert((uint) index < policy->young_cset_region_length(), "invariant");6296size_t words_survived = _surviving_young_words[index];6297cur->record_surv_words_in_group(words_survived);62986299// At this point the we have 'popped' cur from the collection set6300// (linked via next_in_collection_set()) but it is still in the6301// young list (linked via next_young_region()). Clear the6302// _next_young_region field.6303cur->set_next_young_region(NULL);6304} else {6305int index = cur->young_index_in_cset();6306assert(index == -1, "invariant");6307}63086309assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||6310(!cur->is_young() && cur->young_index_in_cset() == -1),6311"invariant" );63126313if (!cur->evacuation_failed()) {6314MemRegion used_mr = cur->used_region();63156316// And the region is empty.6317assert(!used_mr.is_empty(), "Should not have empty regions in a CS.");6318pre_used += cur->used();6319free_region(cur, &local_free_list, false /* par */, true /* locked */);6320} else {6321cur->uninstall_surv_rate_group();6322if (cur->is_young()) {6323cur->set_young_index_in_cset(-1);6324}6325cur->set_evacuation_failed(false);6326// The region is now considered to be old.6327cur->set_old();6328_old_set.add(cur);6329evacuation_info.increment_collectionset_used_after(cur->used());6330}6331cur = next;6332}63336334evacuation_info.set_regions_freed(local_free_list.length());6335policy->record_max_rs_lengths(rs_lengths);6336policy->cset_regions_freed();63376338double end_sec = os::elapsedTime();6339double elapsed_ms = (end_sec - start_sec) * 1000.0;63406341if (non_young) {6342non_young_time_ms += elapsed_ms;6343} else {6344young_time_ms += elapsed_ms;6345}63466347prepend_to_freelist(&local_free_list);6348decrement_summary_bytes(pre_used);6349policy->phase_times()->record_young_free_cset_time_ms(young_time_ms);6350policy->phase_times()->record_non_young_free_cset_time_ms(non_young_time_ms);6351}63526353class G1FreeHumongousRegionClosure : public HeapRegionClosure {6354private:6355FreeRegionList* _free_region_list;6356HeapRegionSet* _proxy_set;6357HeapRegionSetCount _humongous_regions_removed;6358size_t _freed_bytes;6359public:63606361G1FreeHumongousRegionClosure(FreeRegionList* free_region_list) :6362_free_region_list(free_region_list), _humongous_regions_removed(), _freed_bytes(0) {6363}63646365virtual bool doHeapRegion(HeapRegion* r) {6366if (!r->startsHumongous()) {6367return false;6368}63696370G1CollectedHeap* g1h = G1CollectedHeap::heap();63716372oop obj = (oop)r->bottom();6373CMBitMap* next_bitmap = g1h->concurrent_mark()->nextMarkBitMap();63746375// The following checks whether the humongous object is live are sufficient.6376// The main additional check (in addition to having a reference from the roots6377// or the young gen) is whether the humongous object has a remembered set entry.6378//6379// A humongous object cannot be live if there is no remembered set for it6380// because:6381// - there can be no references from within humongous starts regions referencing6382// the object because we never allocate other objects into them.6383// (I.e. there are no intra-region references that may be missed by the6384// remembered set)6385// - as soon there is a remembered set entry to the humongous starts region6386// (i.e. it has "escaped" to an old object) this remembered set entry will stay6387// until the end of a concurrent mark.6388//6389// It is not required to check whether the object has been found dead by marking6390// or not, in fact it would prevent reclamation within a concurrent cycle, as6391// all objects allocated during that time are considered live.6392// SATB marking is even more conservative than the remembered set.6393// So if at this point in the collection there is no remembered set entry,6394// nobody has a reference to it.6395// At the start of collection we flush all refinement logs, and remembered sets6396// are completely up-to-date wrt to references to the humongous object.6397//6398// Other implementation considerations:6399// - never consider object arrays at this time because they would pose6400// considerable effort for cleaning up the the remembered sets. This is6401// required because stale remembered sets might reference locations that6402// are currently allocated into.6403uint region_idx = r->hrm_index();6404if (!g1h->is_humongous_reclaim_candidate(region_idx) ||6405!r->rem_set()->is_empty()) {64066407if (G1TraceEagerReclaimHumongousObjects) {6408gclog_or_tty->print_cr("Live humongous region %u size " SIZE_FORMAT " start " PTR_FORMAT " length " UINT32_FORMAT " with remset " SIZE_FORMAT " code roots " SIZE_FORMAT " is marked %d reclaim candidate %d type array %d",6409region_idx,6410obj->size()*HeapWordSize,6411r->bottom(),6412r->region_num(),6413r->rem_set()->occupied(),6414r->rem_set()->strong_code_roots_list_length(),6415next_bitmap->isMarked(r->bottom()),6416g1h->is_humongous_reclaim_candidate(region_idx),6417obj->is_typeArray()6418);6419}64206421return false;6422}64236424guarantee(obj->is_typeArray(),6425err_msg("Only eagerly reclaiming type arrays is supported, but the object "6426PTR_FORMAT " is not.",6427r->bottom()));64286429if (G1TraceEagerReclaimHumongousObjects) {6430gclog_or_tty->print_cr("Dead humongous region %u size " SIZE_FORMAT " start " PTR_FORMAT " length " UINT32_FORMAT " with remset " SIZE_FORMAT " code roots " SIZE_FORMAT " is marked %d reclaim candidate %d type array %d",6431region_idx,6432obj->size()*HeapWordSize,6433r->bottom(),6434r->region_num(),6435r->rem_set()->occupied(),6436r->rem_set()->strong_code_roots_list_length(),6437next_bitmap->isMarked(r->bottom()),6438g1h->is_humongous_reclaim_candidate(region_idx),6439obj->is_typeArray()6440);6441}6442// Need to clear mark bit of the humongous object if already set.6443if (next_bitmap->isMarked(r->bottom())) {6444next_bitmap->clear(r->bottom());6445}6446_freed_bytes += r->used();6447r->set_containing_set(NULL);6448_humongous_regions_removed.increment(1u, r->capacity());6449g1h->free_humongous_region(r, _free_region_list, false);64506451return false;6452}64536454HeapRegionSetCount& humongous_free_count() {6455return _humongous_regions_removed;6456}64576458size_t bytes_freed() const {6459return _freed_bytes;6460}64616462size_t humongous_reclaimed() const {6463return _humongous_regions_removed.length();6464}6465};64666467void G1CollectedHeap::eagerly_reclaim_humongous_regions() {6468assert_at_safepoint(true);64696470if (!G1EagerReclaimHumongousObjects ||6471(!_has_humongous_reclaim_candidates && !G1TraceEagerReclaimHumongousObjects)) {6472g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms(0.0, 0);6473return;6474}64756476double start_time = os::elapsedTime();64776478FreeRegionList local_cleanup_list("Local Humongous Cleanup List");64796480G1FreeHumongousRegionClosure cl(&local_cleanup_list);6481heap_region_iterate(&cl);64826483HeapRegionSetCount empty_set;6484remove_from_old_sets(empty_set, cl.humongous_free_count());64856486G1HRPrinter* hr_printer = _g1h->hr_printer();6487if (hr_printer->is_active()) {6488FreeRegionListIterator iter(&local_cleanup_list);6489while (iter.more_available()) {6490HeapRegion* hr = iter.get_next();6491hr_printer->cleanup(hr);6492}6493}64946495prepend_to_freelist(&local_cleanup_list);6496decrement_summary_bytes(cl.bytes_freed());64976498g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms((os::elapsedTime() - start_time) * 1000.0,6499cl.humongous_reclaimed());6500}65016502// This routine is similar to the above but does not record6503// any policy statistics or update free lists; we are abandoning6504// the current incremental collection set in preparation of a6505// full collection. After the full GC we will start to build up6506// the incremental collection set again.6507// This is only called when we're doing a full collection6508// and is immediately followed by the tearing down of the young list.65096510void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) {6511HeapRegion* cur = cs_head;65126513while (cur != NULL) {6514HeapRegion* next = cur->next_in_collection_set();6515assert(cur->in_collection_set(), "bad CS");6516cur->set_next_in_collection_set(NULL);6517cur->set_in_collection_set(false);6518cur->set_young_index_in_cset(-1);6519cur = next;6520}6521}65226523void G1CollectedHeap::set_free_regions_coming() {6524if (G1ConcRegionFreeingVerbose) {6525gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "6526"setting free regions coming");6527}65286529assert(!free_regions_coming(), "pre-condition");6530_free_regions_coming = true;6531}65326533void G1CollectedHeap::reset_free_regions_coming() {6534assert(free_regions_coming(), "pre-condition");65356536{6537MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);6538_free_regions_coming = false;6539SecondaryFreeList_lock->notify_all();6540}65416542if (G1ConcRegionFreeingVerbose) {6543gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "6544"reset free regions coming");6545}6546}65476548void G1CollectedHeap::wait_while_free_regions_coming() {6549// Most of the time we won't have to wait, so let's do a quick test6550// first before we take the lock.6551if (!free_regions_coming()) {6552return;6553}65546555if (G1ConcRegionFreeingVerbose) {6556gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "6557"waiting for free regions");6558}65596560{6561MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);6562while (free_regions_coming()) {6563SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);6564}6565}65666567if (G1ConcRegionFreeingVerbose) {6568gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "6569"done waiting for free regions");6570}6571}65726573void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {6574assert(heap_lock_held_for_gc(),6575"the heap lock should already be held by or for this thread");6576_young_list->push_region(hr);6577}65786579class NoYoungRegionsClosure: public HeapRegionClosure {6580private:6581bool _success;6582public:6583NoYoungRegionsClosure() : _success(true) { }6584bool doHeapRegion(HeapRegion* r) {6585if (r->is_young()) {6586gclog_or_tty->print_cr("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young",6587r->bottom(), r->end());6588_success = false;6589}6590return false;6591}6592bool success() { return _success; }6593};65946595bool G1CollectedHeap::check_young_list_empty(bool check_heap, bool check_sample) {6596bool ret = _young_list->check_list_empty(check_sample);65976598if (check_heap) {6599NoYoungRegionsClosure closure;6600heap_region_iterate(&closure);6601ret = ret && closure.success();6602}66036604return ret;6605}66066607class TearDownRegionSetsClosure : public HeapRegionClosure {6608private:6609HeapRegionSet *_old_set;66106611public:6612TearDownRegionSetsClosure(HeapRegionSet* old_set) : _old_set(old_set) { }66136614bool doHeapRegion(HeapRegion* r) {6615if (r->is_old()) {6616_old_set->remove(r);6617} else {6618// We ignore free regions, we'll empty the free list afterwards.6619// We ignore young regions, we'll empty the young list afterwards.6620// We ignore humongous regions, we're not tearing down the6621// humongous regions set.6622assert(r->is_free() || r->is_young() || r->isHumongous(),6623"it cannot be another type");6624}6625return false;6626}66276628~TearDownRegionSetsClosure() {6629assert(_old_set->is_empty(), "post-condition");6630}6631};66326633void G1CollectedHeap::tear_down_region_sets(bool free_list_only) {6634assert_at_safepoint(true /* should_be_vm_thread */);66356636if (!free_list_only) {6637TearDownRegionSetsClosure cl(&_old_set);6638heap_region_iterate(&cl);66396640// Note that emptying the _young_list is postponed and instead done as6641// the first step when rebuilding the regions sets again. The reason for6642// this is that during a full GC string deduplication needs to know if6643// a collected region was young or old when the full GC was initiated.6644}6645_hrm.remove_all_free_regions();6646}66476648class RebuildRegionSetsClosure : public HeapRegionClosure {6649private:6650bool _free_list_only;6651HeapRegionSet* _old_set;6652HeapRegionManager* _hrm;6653size_t _total_used;66546655public:6656RebuildRegionSetsClosure(bool free_list_only,6657HeapRegionSet* old_set, HeapRegionManager* hrm) :6658_free_list_only(free_list_only),6659_old_set(old_set), _hrm(hrm), _total_used(0) {6660assert(_hrm->num_free_regions() == 0, "pre-condition");6661if (!free_list_only) {6662assert(_old_set->is_empty(), "pre-condition");6663}6664}66656666bool doHeapRegion(HeapRegion* r) {6667if (r->continuesHumongous()) {6668return false;6669}66706671if (r->is_empty()) {6672// Add free regions to the free list6673r->set_free();6674r->set_allocation_context(AllocationContext::system());6675_hrm->insert_into_free_list(r);6676} else if (!_free_list_only) {6677assert(!r->is_young(), "we should not come across young regions");66786679if (r->isHumongous()) {6680// We ignore humongous regions, we left the humongous set unchanged6681} else {6682// Objects that were compacted would have ended up on regions6683// that were previously old or free.6684assert(r->is_free() || r->is_old(), "invariant");6685// We now consider them old, so register as such.6686r->set_old();6687_old_set->add(r);6688}6689_total_used += r->used();6690}66916692return false;6693}66946695size_t total_used() {6696return _total_used;6697}6698};66996700void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {6701assert_at_safepoint(true /* should_be_vm_thread */);67026703if (!free_list_only) {6704_young_list->empty_list();6705}67066707RebuildRegionSetsClosure cl(free_list_only, &_old_set, &_hrm);6708heap_region_iterate(&cl);67096710if (!free_list_only) {6711_allocator->set_used(cl.total_used());6712}6713assert(_allocator->used_unlocked() == recalculate_used(),6714err_msg("inconsistent _allocator->used_unlocked(), "6715"value: " SIZE_FORMAT " recalculated: " SIZE_FORMAT,6716_allocator->used_unlocked(), recalculate_used()));6717}67186719void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {6720_refine_cte_cl->set_concurrent(concurrent);6721}67226723bool G1CollectedHeap::is_in_closed_subset(const void* p) const {6724HeapRegion* hr = heap_region_containing(p);6725return hr->is_in(p);6726}67276728// Methods for the mutator alloc region67296730HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,6731bool force) {6732assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);6733assert(!force || g1_policy()->can_expand_young_list(),6734"if force is true we should be able to expand the young list");6735bool young_list_full = g1_policy()->is_young_list_full();6736if (force || !young_list_full) {6737HeapRegion* new_alloc_region = new_region(word_size,6738false /* is_old */,6739false /* do_expand */);6740if (new_alloc_region != NULL) {6741set_region_short_lived_locked(new_alloc_region);6742_hr_printer.alloc(new_alloc_region, G1HRPrinter::Eden, young_list_full);6743check_bitmaps("Mutator Region Allocation", new_alloc_region);6744return new_alloc_region;6745}6746}6747return NULL;6748}67496750void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,6751size_t allocated_bytes) {6752assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);6753assert(alloc_region->is_eden(), "all mutator alloc regions should be eden");67546755g1_policy()->add_region_to_incremental_cset_lhs(alloc_region);6756_allocator->increase_used(allocated_bytes);6757_hr_printer.retire(alloc_region);6758// We update the eden sizes here, when the region is retired,6759// instead of when it's allocated, since this is the point that its6760// used space has been recored in _summary_bytes_used.6761g1mm()->update_eden_size();6762}67636764void G1CollectedHeap::set_par_threads() {6765// Don't change the number of workers. Use the value previously set6766// in the workgroup.6767assert(G1CollectedHeap::use_parallel_gc_threads(), "shouldn't be here otherwise");6768uint n_workers = workers()->active_workers();6769assert(UseDynamicNumberOfGCThreads ||6770n_workers == workers()->total_workers(),6771"Otherwise should be using the total number of workers");6772if (n_workers == 0) {6773assert(false, "Should have been set in prior evacuation pause.");6774n_workers = ParallelGCThreads;6775workers()->set_active_workers(n_workers);6776}6777set_par_threads(n_workers);6778}67796780// Methods for the GC alloc regions67816782HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size,6783uint count,6784InCSetState dest) {6785assert(FreeList_lock->owned_by_self(), "pre-condition");67866787if (count < g1_policy()->max_regions(dest)) {6788const bool is_survivor = (dest.is_young());6789HeapRegion* new_alloc_region = new_region(word_size,6790!is_survivor,6791true /* do_expand */);6792if (new_alloc_region != NULL) {6793// We really only need to do this for old regions given that we6794// should never scan survivors. But it doesn't hurt to do it6795// for survivors too.6796new_alloc_region->record_timestamp();6797if (is_survivor) {6798new_alloc_region->set_survivor();6799_hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor);6800check_bitmaps("Survivor Region Allocation", new_alloc_region);6801} else {6802new_alloc_region->set_old();6803_hr_printer.alloc(new_alloc_region, G1HRPrinter::Old);6804check_bitmaps("Old Region Allocation", new_alloc_region);6805}6806bool during_im = g1_policy()->during_initial_mark_pause();6807new_alloc_region->note_start_of_copying(during_im);6808return new_alloc_region;6809}6810}6811return NULL;6812}68136814void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,6815size_t allocated_bytes,6816InCSetState dest) {6817bool during_im = g1_policy()->during_initial_mark_pause();6818alloc_region->note_end_of_copying(during_im);6819g1_policy()->record_bytes_copied_during_gc(allocated_bytes);6820if (dest.is_young()) {6821young_list()->add_survivor_region(alloc_region);6822} else {6823_old_set.add(alloc_region);6824}6825_hr_printer.retire(alloc_region);6826}68276828// Heap region set verification68296830class VerifyRegionListsClosure : public HeapRegionClosure {6831private:6832HeapRegionSet* _old_set;6833HeapRegionSet* _humongous_set;6834HeapRegionManager* _hrm;68356836public:6837HeapRegionSetCount _old_count;6838HeapRegionSetCount _humongous_count;6839HeapRegionSetCount _free_count;68406841VerifyRegionListsClosure(HeapRegionSet* old_set,6842HeapRegionSet* humongous_set,6843HeapRegionManager* hrm) :6844_old_set(old_set), _humongous_set(humongous_set), _hrm(hrm),6845_old_count(), _humongous_count(), _free_count(){ }68466847bool doHeapRegion(HeapRegion* hr) {6848if (hr->continuesHumongous()) {6849return false;6850}68516852if (hr->is_young()) {6853// TODO6854} else if (hr->startsHumongous()) {6855assert(hr->containing_set() == _humongous_set, err_msg("Heap region %u is starts humongous but not in humongous set.", hr->hrm_index()));6856_humongous_count.increment(1u, hr->capacity());6857} else if (hr->is_empty()) {6858assert(_hrm->is_free(hr), err_msg("Heap region %u is empty but not on the free list.", hr->hrm_index()));6859_free_count.increment(1u, hr->capacity());6860} else if (hr->is_old()) {6861assert(hr->containing_set() == _old_set, err_msg("Heap region %u is old but not in the old set.", hr->hrm_index()));6862_old_count.increment(1u, hr->capacity());6863} else {6864ShouldNotReachHere();6865}6866return false;6867}68686869void verify_counts(HeapRegionSet* old_set, HeapRegionSet* humongous_set, HeapRegionManager* free_list) {6870guarantee(old_set->length() == _old_count.length(), err_msg("Old set count mismatch. Expected %u, actual %u.", old_set->length(), _old_count.length()));6871guarantee(old_set->total_capacity_bytes() == _old_count.capacity(), err_msg("Old set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,6872old_set->total_capacity_bytes(), _old_count.capacity()));68736874guarantee(humongous_set->length() == _humongous_count.length(), err_msg("Hum set count mismatch. Expected %u, actual %u.", humongous_set->length(), _humongous_count.length()));6875guarantee(humongous_set->total_capacity_bytes() == _humongous_count.capacity(), err_msg("Hum set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,6876humongous_set->total_capacity_bytes(), _humongous_count.capacity()));68776878guarantee(free_list->num_free_regions() == _free_count.length(), err_msg("Free list count mismatch. Expected %u, actual %u.", free_list->num_free_regions(), _free_count.length()));6879guarantee(free_list->total_capacity_bytes() == _free_count.capacity(), err_msg("Free list capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,6880free_list->total_capacity_bytes(), _free_count.capacity()));6881}6882};68836884void G1CollectedHeap::verify_region_sets() {6885assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);68866887// First, check the explicit lists.6888_hrm.verify();6889{6890// Given that a concurrent operation might be adding regions to6891// the secondary free list we have to take the lock before6892// verifying it.6893MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);6894_secondary_free_list.verify_list();6895}68966897// If a concurrent region freeing operation is in progress it will6898// be difficult to correctly attributed any free regions we come6899// across to the correct free list given that they might belong to6900// one of several (free_list, secondary_free_list, any local lists,6901// etc.). So, if that's the case we will skip the rest of the6902// verification operation. Alternatively, waiting for the concurrent6903// operation to complete will have a non-trivial effect on the GC's6904// operation (no concurrent operation will last longer than the6905// interval between two calls to verification) and it might hide6906// any issues that we would like to catch during testing.6907if (free_regions_coming()) {6908return;6909}69106911// Make sure we append the secondary_free_list on the free_list so6912// that all free regions we will come across can be safely6913// attributed to the free_list.6914append_secondary_free_list_if_not_empty_with_lock();69156916// Finally, make sure that the region accounting in the lists is6917// consistent with what we see in the heap.69186919VerifyRegionListsClosure cl(&_old_set, &_humongous_set, &_hrm);6920heap_region_iterate(&cl);6921cl.verify_counts(&_old_set, &_humongous_set, &_hrm);6922}69236924// Optimized nmethod scanning69256926class RegisterNMethodOopClosure: public OopClosure {6927G1CollectedHeap* _g1h;6928nmethod* _nm;69296930template <class T> void do_oop_work(T* p) {6931T heap_oop = oopDesc::load_heap_oop(p);6932if (!oopDesc::is_null(heap_oop)) {6933oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);6934HeapRegion* hr = _g1h->heap_region_containing(obj);6935assert(!hr->continuesHumongous(),6936err_msg("trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT6937" starting at " HR_FORMAT,6938_nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));69396940// HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries.6941hr->add_strong_code_root_locked(_nm);6942}6943}69446945public:6946RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :6947_g1h(g1h), _nm(nm) {}69486949void do_oop(oop* p) { do_oop_work(p); }6950void do_oop(narrowOop* p) { do_oop_work(p); }6951};69526953class UnregisterNMethodOopClosure: public OopClosure {6954G1CollectedHeap* _g1h;6955nmethod* _nm;69566957template <class T> void do_oop_work(T* p) {6958T heap_oop = oopDesc::load_heap_oop(p);6959if (!oopDesc::is_null(heap_oop)) {6960oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);6961HeapRegion* hr = _g1h->heap_region_containing(obj);6962assert(!hr->continuesHumongous(),6963err_msg("trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT6964" starting at " HR_FORMAT,6965_nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));69666967hr->remove_strong_code_root(_nm);6968}6969}69706971public:6972UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :6973_g1h(g1h), _nm(nm) {}69746975void do_oop(oop* p) { do_oop_work(p); }6976void do_oop(narrowOop* p) { do_oop_work(p); }6977};69786979void G1CollectedHeap::register_nmethod(nmethod* nm) {6980CollectedHeap::register_nmethod(nm);69816982guarantee(nm != NULL, "sanity");6983RegisterNMethodOopClosure reg_cl(this, nm);6984nm->oops_do(®_cl);6985}69866987void G1CollectedHeap::unregister_nmethod(nmethod* nm) {6988CollectedHeap::unregister_nmethod(nm);69896990guarantee(nm != NULL, "sanity");6991UnregisterNMethodOopClosure reg_cl(this, nm);6992nm->oops_do(®_cl, true);6993}69946995void G1CollectedHeap::purge_code_root_memory() {6996double purge_start = os::elapsedTime();6997G1CodeRootSet::purge();6998double purge_time_ms = (os::elapsedTime() - purge_start) * 1000.0;6999g1_policy()->phase_times()->record_strong_code_root_purge_time(purge_time_ms);7000}70017002class RebuildStrongCodeRootClosure: public CodeBlobClosure {7003G1CollectedHeap* _g1h;70047005public:7006RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :7007_g1h(g1h) {}70087009void do_code_blob(CodeBlob* cb) {7010nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;7011if (nm == NULL) {7012return;7013}70147015if (ScavengeRootsInCode) {7016_g1h->register_nmethod(nm);7017}7018}7019};70207021void G1CollectedHeap::rebuild_strong_code_roots() {7022RebuildStrongCodeRootClosure blob_cl(this);7023CodeCache::blobs_do(&blob_cl);7024}702570267027