Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp
38920 views
/*1* Copyright (c) 2001, 2013, 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#ifndef SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CONCURRENTMARKSWEEPGENERATION_HPP25#define SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CONCURRENTMARKSWEEPGENERATION_HPP2627#include "gc_implementation/shared/gcHeapSummary.hpp"28#include "gc_implementation/shared/gSpaceCounters.hpp"29#include "gc_implementation/shared/gcStats.hpp"30#include "gc_implementation/shared/gcWhen.hpp"31#include "gc_implementation/shared/generationCounters.hpp"32#include "memory/freeBlockDictionary.hpp"33#include "memory/generation.hpp"34#include "memory/iterator.hpp"35#include "runtime/mutexLocker.hpp"36#include "runtime/virtualspace.hpp"37#include "services/memoryService.hpp"38#include "utilities/bitMap.inline.hpp"39#include "utilities/stack.inline.hpp"40#include "utilities/taskqueue.hpp"41#include "utilities/yieldingWorkgroup.hpp"4243// ConcurrentMarkSweepGeneration is in support of a concurrent44// mark-sweep old generation in the Detlefs-Printezis--Boehm-Demers-Schenker45// style. We assume, for now, that this generation is always the46// seniormost generation and for simplicity47// in the first implementation, that this generation is a single compactible48// space. Neither of these restrictions appears essential, and will be49// relaxed in the future when more time is available to implement the50// greater generality (and there's a need for it).51//52// Concurrent mode failures are currently handled by53// means of a sliding mark-compact.5455class CMSAdaptiveSizePolicy;56class CMSConcMarkingTask;57class CMSGCAdaptivePolicyCounters;58class CMSTracer;59class ConcurrentGCTimer;60class ConcurrentMarkSweepGeneration;61class ConcurrentMarkSweepPolicy;62class ConcurrentMarkSweepThread;63class CompactibleFreeListSpace;64class FreeChunk;65class PromotionInfo;66class ScanMarkedObjectsAgainCarefullyClosure;67class TenuredGeneration;68class SerialOldTracer;6970// A generic CMS bit map. It's the basis for both the CMS marking bit map71// as well as for the mod union table (in each case only a subset of the72// methods are used). This is essentially a wrapper around the BitMap class,73// with one bit per (1<<_shifter) HeapWords. (i.e. for the marking bit map,74// we have _shifter == 0. and for the mod union table we have75// shifter == CardTableModRefBS::card_shift - LogHeapWordSize.)76// XXX 64-bit issues in BitMap?77class CMSBitMap VALUE_OBJ_CLASS_SPEC {78friend class VMStructs;7980HeapWord* _bmStartWord; // base address of range covered by map81size_t _bmWordSize; // map size (in #HeapWords covered)82const int _shifter; // shifts to convert HeapWord to bit position83VirtualSpace _virtual_space; // underlying the bit map84BitMap _bm; // the bit map itself85public:86Mutex* const _lock; // mutex protecting _bm;8788public:89// constructor90CMSBitMap(int shifter, int mutex_rank, const char* mutex_name);9192// allocates the actual storage for the map93bool allocate(MemRegion mr);94// field getter95Mutex* lock() const { return _lock; }96// locking verifier convenience function97void assert_locked() const PRODUCT_RETURN;9899// inquiries100HeapWord* startWord() const { return _bmStartWord; }101size_t sizeInWords() const { return _bmWordSize; }102size_t sizeInBits() const { return _bm.size(); }103// the following is one past the last word in space104HeapWord* endWord() const { return _bmStartWord + _bmWordSize; }105106// reading marks107bool isMarked(HeapWord* addr) const;108bool par_isMarked(HeapWord* addr) const; // do not lock checks109bool isUnmarked(HeapWord* addr) const;110bool isAllClear() const;111112// writing marks113void mark(HeapWord* addr);114// For marking by parallel GC threads;115// returns true if we did, false if another thread did116bool par_mark(HeapWord* addr);117118void mark_range(MemRegion mr);119void par_mark_range(MemRegion mr);120void mark_large_range(MemRegion mr);121void par_mark_large_range(MemRegion mr);122void par_clear(HeapWord* addr); // For unmarking by parallel GC threads.123void clear_range(MemRegion mr);124void par_clear_range(MemRegion mr);125void clear_large_range(MemRegion mr);126void par_clear_large_range(MemRegion mr);127void clear_all();128void clear_all_incrementally(); // Not yet implemented!!129130NOT_PRODUCT(131// checks the memory region for validity132void region_invariant(MemRegion mr);133)134135// iteration136void iterate(BitMapClosure* cl) {137_bm.iterate(cl);138}139void iterate(BitMapClosure* cl, HeapWord* left, HeapWord* right);140void dirty_range_iterate_clear(MemRegionClosure* cl);141void dirty_range_iterate_clear(MemRegion mr, MemRegionClosure* cl);142143// auxiliary support for iteration144HeapWord* getNextMarkedWordAddress(HeapWord* addr) const;145HeapWord* getNextMarkedWordAddress(HeapWord* start_addr,146HeapWord* end_addr) const;147HeapWord* getNextUnmarkedWordAddress(HeapWord* addr) const;148HeapWord* getNextUnmarkedWordAddress(HeapWord* start_addr,149HeapWord* end_addr) const;150MemRegion getAndClearMarkedRegion(HeapWord* addr);151MemRegion getAndClearMarkedRegion(HeapWord* start_addr,152HeapWord* end_addr);153154// conversion utilities155HeapWord* offsetToHeapWord(size_t offset) const;156size_t heapWordToOffset(HeapWord* addr) const;157size_t heapWordDiffToOffsetDiff(size_t diff) const;158159void print_on_error(outputStream* st, const char* prefix) const;160161// debugging162// is this address range covered by the bit-map?163NOT_PRODUCT(164bool covers(MemRegion mr) const;165bool covers(HeapWord* start, size_t size = 0) const;166)167void verifyNoOneBitsInRange(HeapWord* left, HeapWord* right) PRODUCT_RETURN;168};169170// Represents a marking stack used by the CMS collector.171// Ideally this should be GrowableArray<> just like MSC's marking stack(s).172class CMSMarkStack: public CHeapObj<mtGC> {173//174friend class CMSCollector; // to get at expasion stats further below175//176177VirtualSpace _virtual_space; // space for the stack178oop* _base; // bottom of stack179size_t _index; // one more than last occupied index180size_t _capacity; // max #elements181Mutex _par_lock; // an advisory lock used in case of parallel access182NOT_PRODUCT(size_t _max_depth;) // max depth plumbed during run183184protected:185size_t _hit_limit; // we hit max stack size limit186size_t _failed_double; // we failed expansion before hitting limit187188public:189CMSMarkStack():190_par_lock(Mutex::event, "CMSMarkStack._par_lock", true),191_hit_limit(0),192_failed_double(0) {}193194bool allocate(size_t size);195196size_t capacity() const { return _capacity; }197198oop pop() {199if (!isEmpty()) {200return _base[--_index] ;201}202return NULL;203}204205bool push(oop ptr) {206if (isFull()) {207return false;208} else {209_base[_index++] = ptr;210NOT_PRODUCT(_max_depth = MAX2(_max_depth, _index));211return true;212}213}214215bool isEmpty() const { return _index == 0; }216bool isFull() const {217assert(_index <= _capacity, "buffer overflow");218return _index == _capacity;219}220221size_t length() { return _index; }222223// "Parallel versions" of some of the above224oop par_pop() {225// lock and pop226MutexLockerEx x(&_par_lock, Mutex::_no_safepoint_check_flag);227return pop();228}229230bool par_push(oop ptr) {231// lock and push232MutexLockerEx x(&_par_lock, Mutex::_no_safepoint_check_flag);233return push(ptr);234}235236// Forcibly reset the stack, losing all of its contents.237void reset() {238_index = 0;239}240241// Expand the stack, typically in response to an overflow condition242void expand();243244// Compute the least valued stack element.245oop least_value(HeapWord* low) {246oop least = (oop)low;247for (size_t i = 0; i < _index; i++) {248least = MIN2(least, _base[i]);249}250return least;251}252253// Exposed here to allow stack expansion in || case254Mutex* par_lock() { return &_par_lock; }255};256257class CardTableRS;258class CMSParGCThreadState;259260class ModUnionClosure: public MemRegionClosure {261protected:262CMSBitMap* _t;263public:264ModUnionClosure(CMSBitMap* t): _t(t) { }265void do_MemRegion(MemRegion mr);266};267268class ModUnionClosurePar: public ModUnionClosure {269public:270ModUnionClosurePar(CMSBitMap* t): ModUnionClosure(t) { }271void do_MemRegion(MemRegion mr);272};273274// Survivor Chunk Array in support of parallelization of275// Survivor Space rescan.276class ChunkArray: public CHeapObj<mtGC> {277size_t _index;278size_t _capacity;279size_t _overflows;280HeapWord** _array; // storage for array281282public:283ChunkArray() : _index(0), _capacity(0), _overflows(0), _array(NULL) {}284ChunkArray(HeapWord** a, size_t c):285_index(0), _capacity(c), _overflows(0), _array(a) {}286287HeapWord** array() { return _array; }288void set_array(HeapWord** a) { _array = a; }289290size_t capacity() { return _capacity; }291void set_capacity(size_t c) { _capacity = c; }292293size_t end() {294assert(_index <= capacity(),295err_msg("_index (" SIZE_FORMAT ") > _capacity (" SIZE_FORMAT "): out of bounds",296_index, _capacity));297return _index;298} // exclusive299300HeapWord* nth(size_t n) {301assert(n < end(), "Out of bounds access");302return _array[n];303}304305void reset() {306_index = 0;307if (_overflows > 0 && PrintCMSStatistics > 1) {308warning("CMS: ChunkArray[" SIZE_FORMAT "] overflowed " SIZE_FORMAT " times",309_capacity, _overflows);310}311_overflows = 0;312}313314void record_sample(HeapWord* p, size_t sz) {315// For now we do not do anything with the size316if (_index < _capacity) {317_array[_index++] = p;318} else {319++_overflows;320assert(_index == _capacity,321err_msg("_index (" SIZE_FORMAT ") > _capacity (" SIZE_FORMAT322"): out of bounds at overflow#" SIZE_FORMAT,323_index, _capacity, _overflows));324}325}326};327328//329// Timing, allocation and promotion statistics for gc scheduling and incremental330// mode pacing. Most statistics are exponential averages.331//332class CMSStats VALUE_OBJ_CLASS_SPEC {333private:334ConcurrentMarkSweepGeneration* const _cms_gen; // The cms (old) gen.335336// The following are exponential averages with factor alpha:337// avg = (100 - alpha) * avg + alpha * cur_sample338//339// The durations measure: end_time[n] - start_time[n]340// The periods measure: start_time[n] - start_time[n-1]341//342// The cms period and duration include only concurrent collections; time spent343// in foreground cms collections due to System.gc() or because of a failure to344// keep up are not included.345//346// There are 3 alphas to "bootstrap" the statistics. The _saved_alpha is the347// real value, but is used only after the first period. A value of 100 is348// used for the first sample so it gets the entire weight.349unsigned int _saved_alpha; // 0-100350unsigned int _gc0_alpha;351unsigned int _cms_alpha;352353double _gc0_duration;354double _gc0_period;355size_t _gc0_promoted; // bytes promoted per gc0356double _cms_duration;357double _cms_duration_pre_sweep; // time from initiation to start of sweep358double _cms_duration_per_mb;359double _cms_period;360size_t _cms_allocated; // bytes of direct allocation per gc0 period361362// Timers.363elapsedTimer _cms_timer;364TimeStamp _gc0_begin_time;365TimeStamp _cms_begin_time;366TimeStamp _cms_end_time;367368// Snapshots of the amount used in the CMS generation.369size_t _cms_used_at_gc0_begin;370size_t _cms_used_at_gc0_end;371size_t _cms_used_at_cms_begin;372373// Used to prevent the duty cycle from being reduced in the middle of a cms374// cycle.375bool _allow_duty_cycle_reduction;376377enum {378_GC0_VALID = 0x1,379_CMS_VALID = 0x2,380_ALL_VALID = _GC0_VALID | _CMS_VALID381};382383unsigned int _valid_bits;384385unsigned int _icms_duty_cycle; // icms duty cycle (0-100).386387protected:388389// Return a duty cycle that avoids wild oscillations, by limiting the amount390// of change between old_duty_cycle and new_duty_cycle (the latter is treated391// as a recommended value).392static unsigned int icms_damped_duty_cycle(unsigned int old_duty_cycle,393unsigned int new_duty_cycle);394unsigned int icms_update_duty_cycle_impl();395396// In support of adjusting of cms trigger ratios based on history397// of concurrent mode failure.398double cms_free_adjustment_factor(size_t free) const;399void adjust_cms_free_adjustment_factor(bool fail, size_t free);400401public:402CMSStats(ConcurrentMarkSweepGeneration* cms_gen,403unsigned int alpha = CMSExpAvgFactor);404405// Whether or not the statistics contain valid data; higher level statistics406// cannot be called until this returns true (they require at least one young407// gen and one cms cycle to have completed).408bool valid() const;409410// Record statistics.411void record_gc0_begin();412void record_gc0_end(size_t cms_gen_bytes_used);413void record_cms_begin();414void record_cms_end();415416// Allow management of the cms timer, which must be stopped/started around417// yield points.418elapsedTimer& cms_timer() { return _cms_timer; }419void start_cms_timer() { _cms_timer.start(); }420void stop_cms_timer() { _cms_timer.stop(); }421422// Basic statistics; units are seconds or bytes.423double gc0_period() const { return _gc0_period; }424double gc0_duration() const { return _gc0_duration; }425size_t gc0_promoted() const { return _gc0_promoted; }426double cms_period() const { return _cms_period; }427double cms_duration() const { return _cms_duration; }428double cms_duration_per_mb() const { return _cms_duration_per_mb; }429size_t cms_allocated() const { return _cms_allocated; }430431size_t cms_used_at_gc0_end() const { return _cms_used_at_gc0_end;}432433// Seconds since the last background cms cycle began or ended.434double cms_time_since_begin() const;435double cms_time_since_end() const;436437// Higher level statistics--caller must check that valid() returns true before438// calling.439440// Returns bytes promoted per second of wall clock time.441double promotion_rate() const;442443// Returns bytes directly allocated per second of wall clock time.444double cms_allocation_rate() const;445446// Rate at which space in the cms generation is being consumed (sum of the447// above two).448double cms_consumption_rate() const;449450// Returns an estimate of the number of seconds until the cms generation will451// fill up, assuming no collection work is done.452double time_until_cms_gen_full() const;453454// Returns an estimate of the number of seconds remaining until455// the cms generation collection should start.456double time_until_cms_start() const;457458// End of higher level statistics.459460// Returns the cms incremental mode duty cycle, as a percentage (0-100).461unsigned int icms_duty_cycle() const { return _icms_duty_cycle; }462463// Update the duty cycle and return the new value.464unsigned int icms_update_duty_cycle();465466// Debugging.467void print_on(outputStream* st) const PRODUCT_RETURN;468void print() const { print_on(gclog_or_tty); }469};470471// A closure related to weak references processing which472// we embed in the CMSCollector, since we need to pass473// it to the reference processor for secondary filtering474// of references based on reachability of referent;475// see role of _is_alive_non_header closure in the476// ReferenceProcessor class.477// For objects in the CMS generation, this closure checks478// if the object is "live" (reachable). Used in weak479// reference processing.480class CMSIsAliveClosure: public BoolObjectClosure {481const MemRegion _span;482const CMSBitMap* _bit_map;483484friend class CMSCollector;485public:486CMSIsAliveClosure(MemRegion span,487CMSBitMap* bit_map):488_span(span),489_bit_map(bit_map) {490assert(!span.is_empty(), "Empty span could spell trouble");491}492493bool do_object_b(oop obj);494};495496497// Implements AbstractRefProcTaskExecutor for CMS.498class CMSRefProcTaskExecutor: public AbstractRefProcTaskExecutor {499public:500501CMSRefProcTaskExecutor(CMSCollector& collector)502: _collector(collector)503{ }504505// Executes a task using worker threads.506virtual void execute(ProcessTask& task);507virtual void execute(EnqueueTask& task);508private:509CMSCollector& _collector;510};511512513class CMSCollector: public CHeapObj<mtGC> {514friend class VMStructs;515friend class ConcurrentMarkSweepThread;516friend class ConcurrentMarkSweepGeneration;517friend class CompactibleFreeListSpace;518friend class CMSParMarkTask;519friend class CMSParInitialMarkTask;520friend class CMSParRemarkTask;521friend class CMSConcMarkingTask;522friend class CMSRefProcTaskProxy;523friend class CMSRefProcTaskExecutor;524friend class ScanMarkedObjectsAgainCarefullyClosure; // for sampling eden525friend class SurvivorSpacePrecleanClosure; // --- ditto -------526friend class PushOrMarkClosure; // to access _restart_addr527friend class Par_PushOrMarkClosure; // to access _restart_addr528friend class MarkFromRootsClosure; // -- ditto --529// ... and for clearing cards530friend class Par_MarkFromRootsClosure; // to access _restart_addr531// ... and for clearing cards532friend class Par_ConcMarkingClosure; // to access _restart_addr etc.533friend class MarkFromRootsVerifyClosure; // to access _restart_addr534friend class PushAndMarkVerifyClosure; // -- ditto --535friend class MarkRefsIntoAndScanClosure; // to access _overflow_list536friend class PushAndMarkClosure; // -- ditto --537friend class Par_PushAndMarkClosure; // -- ditto --538friend class CMSKeepAliveClosure; // -- ditto --539friend class CMSDrainMarkingStackClosure; // -- ditto --540friend class CMSInnerParMarkAndPushClosure; // -- ditto --541NOT_PRODUCT(friend class ScanMarkedObjectsAgainClosure;) // assertion on _overflow_list542friend class ReleaseForegroundGC; // to access _foregroundGCShouldWait543friend class VM_CMS_Operation;544friend class VM_CMS_Initial_Mark;545friend class VM_CMS_Final_Remark;546friend class TraceCMSMemoryManagerStats;547548private:549jlong _time_of_last_gc;550void update_time_of_last_gc(jlong now) {551_time_of_last_gc = now;552}553554OopTaskQueueSet* _task_queues;555556// Overflow list of grey objects, threaded through mark-word557// Manipulated with CAS in the parallel/multi-threaded case.558oop _overflow_list;559// The following array-pair keeps track of mark words560// displaced for accomodating overflow list above.561// This code will likely be revisited under RFE#4922830.562Stack<oop, mtGC> _preserved_oop_stack;563Stack<markOop, mtGC> _preserved_mark_stack;564565int* _hash_seed;566567// In support of multi-threaded concurrent phases568YieldingFlexibleWorkGang* _conc_workers;569570// Performance Counters571CollectorCounters* _gc_counters;572573// Initialization Errors574bool _completed_initialization;575576// In support of ExplicitGCInvokesConcurrent577static bool _full_gc_requested;578static GCCause::Cause _full_gc_cause;579unsigned int _collection_count_start;580581// Should we unload classes this concurrent cycle?582bool _should_unload_classes;583unsigned int _concurrent_cycles_since_last_unload;584unsigned int concurrent_cycles_since_last_unload() const {585return _concurrent_cycles_since_last_unload;586}587// Did we (allow) unload classes in the previous concurrent cycle?588bool unloaded_classes_last_cycle() const {589return concurrent_cycles_since_last_unload() == 0;590}591// Root scanning options for perm gen592int _roots_scanning_options;593int roots_scanning_options() const { return _roots_scanning_options; }594void add_root_scanning_option(int o) { _roots_scanning_options |= o; }595void remove_root_scanning_option(int o) { _roots_scanning_options &= ~o; }596597// Verification support598CMSBitMap _verification_mark_bm;599void verify_after_remark_work_1();600void verify_after_remark_work_2();601602// true if any verification flag is on.603bool _verifying;604bool verifying() const { return _verifying; }605void set_verifying(bool v) { _verifying = v; }606607// Collector policy608ConcurrentMarkSweepPolicy* _collector_policy;609ConcurrentMarkSweepPolicy* collector_policy() { return _collector_policy; }610611void set_did_compact(bool v);612613// XXX Move these to CMSStats ??? FIX ME !!!614elapsedTimer _inter_sweep_timer; // time between sweeps615elapsedTimer _intra_sweep_timer; // time _in_ sweeps616// padded decaying average estimates of the above617AdaptivePaddedAverage _inter_sweep_estimate;618AdaptivePaddedAverage _intra_sweep_estimate;619620CMSTracer* _gc_tracer_cm;621ConcurrentGCTimer* _gc_timer_cm;622623bool _cms_start_registered;624625GCHeapSummary _last_heap_summary;626MetaspaceSummary _last_metaspace_summary;627628void register_foreground_gc_start(GCCause::Cause cause);629void register_gc_start(GCCause::Cause cause);630void register_gc_end();631void save_heap_summary();632void report_heap_summary(GCWhen::Type when);633634protected:635ConcurrentMarkSweepGeneration* _cmsGen; // old gen (CMS)636MemRegion _span; // span covering above two637CardTableRS* _ct; // card table638639// CMS marking support structures640CMSBitMap _markBitMap;641CMSBitMap _modUnionTable;642CMSMarkStack _markStack;643644HeapWord* _restart_addr; // in support of marking stack overflow645void lower_restart_addr(HeapWord* low);646647// Counters in support of marking stack / work queue overflow handling:648// a non-zero value indicates certain types of overflow events during649// the current CMS cycle and could lead to stack resizing efforts at650// an opportune future time.651size_t _ser_pmc_preclean_ovflw;652size_t _ser_pmc_remark_ovflw;653size_t _par_pmc_remark_ovflw;654size_t _ser_kac_preclean_ovflw;655size_t _ser_kac_ovflw;656size_t _par_kac_ovflw;657NOT_PRODUCT(ssize_t _num_par_pushes;)658659// ("Weak") Reference processing support660ReferenceProcessor* _ref_processor;661CMSIsAliveClosure _is_alive_closure;662// keep this textually after _markBitMap and _span; c'tor dependency663664ConcurrentMarkSweepThread* _cmsThread; // the thread doing the work665ModUnionClosure _modUnionClosure;666ModUnionClosurePar _modUnionClosurePar;667668// CMS abstract state machine669// initial_state: Idling670// next_state(Idling) = {Marking}671// next_state(Marking) = {Precleaning, Sweeping}672// next_state(Precleaning) = {AbortablePreclean, FinalMarking}673// next_state(AbortablePreclean) = {FinalMarking}674// next_state(FinalMarking) = {Sweeping}675// next_state(Sweeping) = {Resizing}676// next_state(Resizing) = {Resetting}677// next_state(Resetting) = {Idling}678// The numeric values below are chosen so that:679// . _collectorState <= Idling == post-sweep && pre-mark680// . _collectorState in (Idling, Sweeping) == {initial,final}marking ||681// precleaning || abortablePrecleanb682public:683enum CollectorState {684Resizing = 0,685Resetting = 1,686Idling = 2,687InitialMarking = 3,688Marking = 4,689Precleaning = 5,690AbortablePreclean = 6,691FinalMarking = 7,692Sweeping = 8693};694protected:695static CollectorState _collectorState;696697// State related to prologue/epilogue invocation for my generations698bool _between_prologue_and_epilogue;699700// Signalling/State related to coordination between fore- and backgroud GC701// Note: When the baton has been passed from background GC to foreground GC,702// _foregroundGCIsActive is true and _foregroundGCShouldWait is false.703static bool _foregroundGCIsActive; // true iff foreground collector is active or704// wants to go active705static bool _foregroundGCShouldWait; // true iff background GC is active and has not706// yet passed the baton to the foreground GC707708// Support for CMSScheduleRemark (abortable preclean)709bool _abort_preclean;710bool _start_sampling;711712int _numYields;713size_t _numDirtyCards;714size_t _sweep_count;715// number of full gc's since the last concurrent gc.716uint _full_gcs_since_conc_gc;717718// occupancy used for bootstrapping stats719double _bootstrap_occupancy;720721// timer722elapsedTimer _timer;723724// Timing, allocation and promotion statistics, used for scheduling.725CMSStats _stats;726727// Allocation limits installed in the young gen, used only in728// CMSIncrementalMode. When an allocation in the young gen would cross one of729// these limits, the cms generation is notified and the cms thread is started730// or stopped, respectively.731HeapWord* _icms_start_limit;732HeapWord* _icms_stop_limit;733734enum CMS_op_type {735CMS_op_checkpointRootsInitial,736CMS_op_checkpointRootsFinal737};738739void do_CMS_operation(CMS_op_type op, GCCause::Cause gc_cause);740bool stop_world_and_do(CMS_op_type op);741742OopTaskQueueSet* task_queues() { return _task_queues; }743int* hash_seed(int i) { return &_hash_seed[i]; }744YieldingFlexibleWorkGang* conc_workers() { return _conc_workers; }745746// Support for parallelizing Eden rescan in CMS remark phase747void sample_eden(); // ... sample Eden space top748749private:750// Support for parallelizing young gen rescan in CMS remark phase751Generation* _young_gen; // the younger gen752HeapWord** _top_addr; // ... Top of Eden753HeapWord** _end_addr; // ... End of Eden754Mutex* _eden_chunk_lock;755HeapWord** _eden_chunk_array; // ... Eden partitioning array756size_t _eden_chunk_index; // ... top (exclusive) of array757size_t _eden_chunk_capacity; // ... max entries in array758759// Support for parallelizing survivor space rescan760HeapWord** _survivor_chunk_array;761size_t _survivor_chunk_index;762size_t _survivor_chunk_capacity;763size_t* _cursor;764ChunkArray* _survivor_plab_array;765766// A bounded minimum size of PLABs, should not return too small values since767// this will affect the size of the data structures used for parallel young gen rescan768size_t plab_sample_minimum_size();769770// Support for marking stack overflow handling771bool take_from_overflow_list(size_t num, CMSMarkStack* to_stack);772bool par_take_from_overflow_list(size_t num,773OopTaskQueue* to_work_q,774int no_of_gc_threads);775void push_on_overflow_list(oop p);776void par_push_on_overflow_list(oop p);777// the following is, obviously, not, in general, "MT-stable"778bool overflow_list_is_empty() const;779780void preserve_mark_if_necessary(oop p);781void par_preserve_mark_if_necessary(oop p);782void preserve_mark_work(oop p, markOop m);783void restore_preserved_marks_if_any();784NOT_PRODUCT(bool no_preserved_marks() const;)785// in support of testing overflow code786NOT_PRODUCT(int _overflow_counter;)787NOT_PRODUCT(bool simulate_overflow();) // sequential788NOT_PRODUCT(bool par_simulate_overflow();) // MT version789790// CMS work methods791void checkpointRootsInitialWork(bool asynch); // initial checkpoint work792793// a return value of false indicates failure due to stack overflow794bool markFromRootsWork(bool asynch); // concurrent marking work795796public: // FIX ME!!! only for testing797bool do_marking_st(bool asynch); // single-threaded marking798bool do_marking_mt(bool asynch); // multi-threaded marking799800private:801802// concurrent precleaning work803size_t preclean_mod_union_table(ConcurrentMarkSweepGeneration* gen,804ScanMarkedObjectsAgainCarefullyClosure* cl);805size_t preclean_card_table(ConcurrentMarkSweepGeneration* gen,806ScanMarkedObjectsAgainCarefullyClosure* cl);807// Does precleaning work, returning a quantity indicative of808// the amount of "useful work" done.809size_t preclean_work(bool clean_refs, bool clean_survivors);810void preclean_klasses(MarkRefsIntoAndScanClosure* cl, Mutex* freelistLock);811void abortable_preclean(); // Preclean while looking for possible abort812void initialize_sequential_subtasks_for_young_gen_rescan(int i);813// Helper function for above; merge-sorts the per-thread plab samples814void merge_survivor_plab_arrays(ContiguousSpace* surv, int no_of_gc_threads);815// Resets (i.e. clears) the per-thread plab sample vectors816void reset_survivor_plab_arrays();817818// final (second) checkpoint work819void checkpointRootsFinalWork(bool asynch, bool clear_all_soft_refs,820bool init_mark_was_synchronous);821// work routine for parallel version of remark822void do_remark_parallel();823// work routine for non-parallel version of remark824void do_remark_non_parallel();825// reference processing work routine (during second checkpoint)826void refProcessingWork(bool asynch, bool clear_all_soft_refs);827828// concurrent sweeping work829void sweepWork(ConcurrentMarkSweepGeneration* gen, bool asynch);830831// (concurrent) resetting of support data structures832void reset(bool asynch);833834// Clear _expansion_cause fields of constituent generations835void clear_expansion_cause();836837// An auxilliary method used to record the ends of838// used regions of each generation to limit the extent of sweep839void save_sweep_limits();840841// A work method used by foreground collection to determine842// what type of collection (compacting or not, continuing or fresh)843// it should do.844void decide_foreground_collection_type(bool clear_all_soft_refs,845bool* should_compact, bool* should_start_over);846847// A work method used by the foreground collector to do848// a mark-sweep-compact.849void do_compaction_work(bool clear_all_soft_refs);850851// A work method used by the foreground collector to do852// a mark-sweep, after taking over from a possibly on-going853// concurrent mark-sweep collection.854void do_mark_sweep_work(bool clear_all_soft_refs,855CollectorState first_state, bool should_start_over);856857// Work methods for reporting concurrent mode interruption or failure858bool is_external_interruption();859void report_concurrent_mode_interruption();860861// If the backgrould GC is active, acquire control from the background862// GC and do the collection.863void acquire_control_and_collect(bool full, bool clear_all_soft_refs);864865// For synchronizing passing of control from background to foreground866// GC. waitForForegroundGC() is called by the background867// collector. It if had to wait for a foreground collection,868// it returns true and the background collection should assume869// that the collection was finished by the foreground870// collector.871bool waitForForegroundGC();872873// Incremental mode triggering: recompute the icms duty cycle and set the874// allocation limits in the young gen.875void icms_update_allocation_limits();876877size_t block_size_using_printezis_bits(HeapWord* addr) const;878size_t block_size_if_printezis_bits(HeapWord* addr) const;879HeapWord* next_card_start_after_block(HeapWord* addr) const;880881void setup_cms_unloading_and_verification_state();882public:883CMSCollector(ConcurrentMarkSweepGeneration* cmsGen,884CardTableRS* ct,885ConcurrentMarkSweepPolicy* cp);886ConcurrentMarkSweepThread* cmsThread() { return _cmsThread; }887888ReferenceProcessor* ref_processor() { return _ref_processor; }889void ref_processor_init();890891Mutex* bitMapLock() const { return _markBitMap.lock(); }892static CollectorState abstract_state() { return _collectorState; }893894bool should_abort_preclean() const; // Whether preclean should be aborted.895size_t get_eden_used() const;896size_t get_eden_capacity() const;897898ConcurrentMarkSweepGeneration* cmsGen() { return _cmsGen; }899900// locking checks901NOT_PRODUCT(static bool have_cms_token();)902903// XXXPERM bool should_collect(bool full, size_t size, bool tlab);904bool shouldConcurrentCollect();905906void collect(bool full,907bool clear_all_soft_refs,908size_t size,909bool tlab);910void collect_in_background(bool clear_all_soft_refs, GCCause::Cause cause);911void collect_in_foreground(bool clear_all_soft_refs, GCCause::Cause cause);912913// In support of ExplicitGCInvokesConcurrent914static void request_full_gc(unsigned int full_gc_count, GCCause::Cause cause);915// Should we unload classes in a particular concurrent cycle?916bool should_unload_classes() const {917return _should_unload_classes;918}919void update_should_unload_classes();920921void direct_allocated(HeapWord* start, size_t size);922923// Object is dead if not marked and current phase is sweeping.924bool is_dead_obj(oop obj) const;925926// After a promotion (of "start"), do any necessary marking.927// If "par", then it's being done by a parallel GC thread.928// The last two args indicate if we need precise marking929// and if so the size of the object so it can be dirtied930// in its entirety.931void promoted(bool par, HeapWord* start,932bool is_obj_array, size_t obj_size);933934HeapWord* allocation_limit_reached(Space* space, HeapWord* top,935size_t word_size);936937void getFreelistLocks() const;938void releaseFreelistLocks() const;939bool haveFreelistLocks() const;940941// Adjust size of underlying generation942void compute_new_size();943944// GC prologue and epilogue945void gc_prologue(bool full);946void gc_epilogue(bool full);947948jlong time_of_last_gc(jlong now) {949if (_collectorState <= Idling) {950// gc not in progress951return _time_of_last_gc;952} else {953// collection in progress954return now;955}956}957958// Support for parallel remark of survivor space959void* get_data_recorder(int thr_num);960void sample_eden_chunk();961962CMSBitMap* markBitMap() { return &_markBitMap; }963void directAllocated(HeapWord* start, size_t size);964965// main CMS steps and related support966void checkpointRootsInitial(bool asynch);967bool markFromRoots(bool asynch); // a return value of false indicates failure968// due to stack overflow969void preclean();970void checkpointRootsFinal(bool asynch, bool clear_all_soft_refs,971bool init_mark_was_synchronous);972void sweep(bool asynch);973974// Check that the currently executing thread is the expected975// one (foreground collector or background collector).976static void check_correct_thread_executing() PRODUCT_RETURN;977// XXXPERM void print_statistics() PRODUCT_RETURN;978979bool is_cms_reachable(HeapWord* addr);980981// Performance Counter Support982CollectorCounters* counters() { return _gc_counters; }983984// timer stuff985void startTimer() { assert(!_timer.is_active(), "Error"); _timer.start(); }986void stopTimer() { assert( _timer.is_active(), "Error"); _timer.stop(); }987void resetTimer() { assert(!_timer.is_active(), "Error"); _timer.reset(); }988double timerValue() { assert(!_timer.is_active(), "Error"); return _timer.seconds(); }989990int yields() { return _numYields; }991void resetYields() { _numYields = 0; }992void incrementYields() { _numYields++; }993void resetNumDirtyCards() { _numDirtyCards = 0; }994void incrementNumDirtyCards(size_t num) { _numDirtyCards += num; }995size_t numDirtyCards() { return _numDirtyCards; }996997static bool foregroundGCShouldWait() { return _foregroundGCShouldWait; }998static void set_foregroundGCShouldWait(bool v) { _foregroundGCShouldWait = v; }999static bool foregroundGCIsActive() { return _foregroundGCIsActive; }1000static void set_foregroundGCIsActive(bool v) { _foregroundGCIsActive = v; }1001size_t sweep_count() const { return _sweep_count; }1002void increment_sweep_count() { _sweep_count++; }10031004// Timers/stats for gc scheduling and incremental mode pacing.1005CMSStats& stats() { return _stats; }10061007// Convenience methods that check whether CMSIncrementalMode is enabled and1008// forward to the corresponding methods in ConcurrentMarkSweepThread.1009static void start_icms();1010static void stop_icms(); // Called at the end of the cms cycle.1011static void disable_icms(); // Called before a foreground collection.1012static void enable_icms(); // Called after a foreground collection.1013void icms_wait(); // Called at yield points.10141015// Adaptive size policy1016CMSAdaptiveSizePolicy* size_policy();1017CMSGCAdaptivePolicyCounters* gc_adaptive_policy_counters();10181019static void print_on_error(outputStream* st);10201021// debugging1022void verify();1023bool verify_after_remark(bool silent = VerifySilently);1024void verify_ok_to_terminate() const PRODUCT_RETURN;1025void verify_work_stacks_empty() const PRODUCT_RETURN;1026void verify_overflow_empty() const PRODUCT_RETURN;10271028// convenience methods in support of debugging1029static const size_t skip_header_HeapWords() PRODUCT_RETURN0;1030HeapWord* block_start(const void* p) const PRODUCT_RETURN0;10311032// accessors1033CMSMarkStack* verification_mark_stack() { return &_markStack; }1034CMSBitMap* verification_mark_bm() { return &_verification_mark_bm; }10351036// Initialization errors1037bool completed_initialization() { return _completed_initialization; }10381039void print_eden_and_survivor_chunk_arrays();1040};10411042class CMSExpansionCause : public AllStatic {1043public:1044enum Cause {1045_no_expansion,1046_satisfy_free_ratio,1047_satisfy_promotion,1048_satisfy_allocation,1049_allocate_par_lab,1050_allocate_par_spooling_space,1051_adaptive_size_policy1052};1053// Return a string describing the cause of the expansion.1054static const char* to_string(CMSExpansionCause::Cause cause);1055};10561057class ConcurrentMarkSweepGeneration: public CardGeneration {1058friend class VMStructs;1059friend class ConcurrentMarkSweepThread;1060friend class ConcurrentMarkSweep;1061friend class CMSCollector;1062protected:1063static CMSCollector* _collector; // the collector that collects us1064CompactibleFreeListSpace* _cmsSpace; // underlying space (only one for now)10651066// Performance Counters1067GenerationCounters* _gen_counters;1068GSpaceCounters* _space_counters;10691070// Words directly allocated, used by CMSStats.1071size_t _direct_allocated_words;10721073// Non-product stat counters1074NOT_PRODUCT(1075size_t _numObjectsPromoted;1076size_t _numWordsPromoted;1077size_t _numObjectsAllocated;1078size_t _numWordsAllocated;1079)10801081// Used for sizing decisions1082bool _incremental_collection_failed;1083bool incremental_collection_failed() {1084return _incremental_collection_failed;1085}1086void set_incremental_collection_failed() {1087_incremental_collection_failed = true;1088}1089void clear_incremental_collection_failed() {1090_incremental_collection_failed = false;1091}10921093// accessors1094void set_expansion_cause(CMSExpansionCause::Cause v) { _expansion_cause = v;}1095CMSExpansionCause::Cause expansion_cause() const { return _expansion_cause; }10961097private:1098// For parallel young-gen GC support.1099CMSParGCThreadState** _par_gc_thread_states;11001101// Reason generation was expanded1102CMSExpansionCause::Cause _expansion_cause;11031104// In support of MinChunkSize being larger than min object size1105const double _dilatation_factor;11061107enum CollectionTypes {1108Concurrent_collection_type = 0,1109MS_foreground_collection_type = 1,1110MSC_foreground_collection_type = 2,1111Unknown_collection_type = 31112};11131114CollectionTypes _debug_collection_type;11151116// True if a compactiing collection was done.1117bool _did_compact;1118bool did_compact() { return _did_compact; }11191120// Fraction of current occupancy at which to start a CMS collection which1121// will collect this generation (at least).1122double _initiating_occupancy;11231124protected:1125// Shrink generation by specified size (returns false if unable to shrink)1126void shrink_free_list_by(size_t bytes);11271128// Update statistics for GC1129virtual void update_gc_stats(int level, bool full);11301131// Maximum available space in the generation (including uncommitted)1132// space.1133size_t max_available() const;11341135// getter and initializer for _initiating_occupancy field.1136double initiating_occupancy() const { return _initiating_occupancy; }1137void init_initiating_occupancy(intx io, uintx tr);11381139public:1140ConcurrentMarkSweepGeneration(ReservedSpace rs, size_t initial_byte_size,1141int level, CardTableRS* ct,1142bool use_adaptive_freelists,1143FreeBlockDictionary<FreeChunk>::DictionaryChoice);11441145// Accessors1146CMSCollector* collector() const { return _collector; }1147static void set_collector(CMSCollector* collector) {1148assert(_collector == NULL, "already set");1149_collector = collector;1150}1151CompactibleFreeListSpace* cmsSpace() const { return _cmsSpace; }11521153Mutex* freelistLock() const;11541155virtual Generation::Name kind() { return Generation::ConcurrentMarkSweep; }11561157// Adaptive size policy1158CMSAdaptiveSizePolicy* size_policy();11591160void set_did_compact(bool v) { _did_compact = v; }11611162bool refs_discovery_is_atomic() const { return false; }1163bool refs_discovery_is_mt() const {1164// Note: CMS does MT-discovery during the parallel-remark1165// phases. Use ReferenceProcessorMTMutator to make refs1166// discovery MT-safe during such phases or other parallel1167// discovery phases in the future. This may all go away1168// if/when we decide that refs discovery is sufficiently1169// rare that the cost of the CAS's involved is in the1170// noise. That's a measurement that should be done, and1171// the code simplified if that turns out to be the case.1172return ConcGCThreads > 1;1173}11741175// Override1176virtual void ref_processor_init();11771178// Grow generation by specified size (returns false if unable to grow)1179bool grow_by(size_t bytes);1180// Grow generation to reserved size.1181bool grow_to_reserved();11821183void clear_expansion_cause() { _expansion_cause = CMSExpansionCause::_no_expansion; }11841185// Space enquiries1186size_t capacity() const;1187size_t used() const;1188size_t free() const;1189double occupancy() const { return ((double)used())/((double)capacity()); }1190size_t contiguous_available() const;1191size_t unsafe_max_alloc_nogc() const;1192size_t used_stable() const;11931194// over-rides1195MemRegion used_region() const;1196MemRegion used_region_at_save_marks() const;11971198// Does a "full" (forced) collection invoked on this generation collect1199// all younger generations as well? Note that the second conjunct is a1200// hack to allow the collection of the younger gen first if the flag is1201// set. This is better than using th policy's should_collect_gen0_first()1202// since that causes us to do an extra unnecessary pair of restart-&-stop-world.1203virtual bool full_collects_younger_generations() const {1204return UseCMSCompactAtFullCollection && !CollectGen0First;1205}12061207void space_iterate(SpaceClosure* blk, bool usedOnly = false);12081209// Support for compaction1210CompactibleSpace* first_compaction_space() const;1211// Adjust quantites in the generation affected by1212// the compaction.1213void reset_after_compaction();12141215// Allocation support1216HeapWord* allocate(size_t size, bool tlab);1217HeapWord* have_lock_and_allocate(size_t size, bool tlab);1218oop promote(oop obj, size_t obj_size);1219HeapWord* par_allocate(size_t size, bool tlab) {1220return allocate(size, tlab);1221}12221223// Incremental mode triggering.1224HeapWord* allocation_limit_reached(Space* space, HeapWord* top,1225size_t word_size);12261227// Used by CMSStats to track direct allocation. The value is sampled and1228// reset after each young gen collection.1229size_t direct_allocated_words() const { return _direct_allocated_words; }1230void reset_direct_allocated_words() { _direct_allocated_words = 0; }12311232// Overrides for parallel promotion.1233virtual oop par_promote(int thread_num,1234oop obj, markOop m, size_t word_sz);1235// This one should not be called for CMS.1236virtual void par_promote_alloc_undo(int thread_num,1237HeapWord* obj, size_t word_sz);1238virtual void par_promote_alloc_done(int thread_num);1239virtual void par_oop_since_save_marks_iterate_done(int thread_num);12401241virtual bool promotion_attempt_is_safe(size_t promotion_in_bytes) const;12421243// Inform this (non-young) generation that a promotion failure was1244// encountered during a collection of a younger generation that1245// promotes into this generation.1246virtual void promotion_failure_occurred();12471248bool should_collect(bool full, size_t size, bool tlab);1249virtual bool should_concurrent_collect() const;1250virtual bool is_too_full() const;1251void collect(bool full,1252bool clear_all_soft_refs,1253size_t size,1254bool tlab);12551256HeapWord* expand_and_allocate(size_t word_size,1257bool tlab,1258bool parallel = false);12591260// GC prologue and epilogue1261void gc_prologue(bool full);1262void gc_prologue_work(bool full, bool registerClosure,1263ModUnionClosure* modUnionClosure);1264void gc_epilogue(bool full);1265void gc_epilogue_work(bool full);12661267// Time since last GC of this generation1268jlong time_of_last_gc(jlong now) {1269return collector()->time_of_last_gc(now);1270}1271void update_time_of_last_gc(jlong now) {1272collector()-> update_time_of_last_gc(now);1273}12741275// Allocation failure1276void expand(size_t bytes, size_t expand_bytes,1277CMSExpansionCause::Cause cause);1278virtual bool expand(size_t bytes, size_t expand_bytes);1279void shrink(size_t bytes);1280void shrink_by(size_t bytes);1281HeapWord* expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz);1282bool expand_and_ensure_spooling_space(PromotionInfo* promo);12831284// Iteration support and related enquiries1285void save_marks();1286bool no_allocs_since_save_marks();1287void younger_refs_iterate(OopsInGenClosure* cl);12881289// Iteration support specific to CMS generations1290void save_sweep_limit();12911292// More iteration support1293virtual void oop_iterate(ExtendedOopClosure* cl);1294virtual void safe_object_iterate(ObjectClosure* cl);1295virtual void object_iterate(ObjectClosure* cl);12961297// Need to declare the full complement of closures, whether we'll1298// override them or not, or get message from the compiler:1299// oop_since_save_marks_iterate_nv hides virtual function...1300#define CMS_SINCE_SAVE_MARKS_DECL(OopClosureType, nv_suffix) \1301void oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl);1302ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DECL)13031304// Smart allocation XXX -- move to CFLSpace?1305void setNearLargestChunk();1306bool isNearLargestChunk(HeapWord* addr);13071308// Get the chunk at the end of the space. Delagates to1309// the space.1310FreeChunk* find_chunk_at_end();13111312void post_compact();13131314// Debugging1315void prepare_for_verify();1316void verify();1317void print_statistics() PRODUCT_RETURN;13181319// Performance Counters support1320virtual void update_counters();1321virtual void update_counters(size_t used);1322void initialize_performance_counters();1323CollectorCounters* counters() { return collector()->counters(); }13241325// Support for parallel remark of survivor space1326void* get_data_recorder(int thr_num) {1327//Delegate to collector1328return collector()->get_data_recorder(thr_num);1329}1330void sample_eden_chunk() {1331//Delegate to collector1332return collector()->sample_eden_chunk();1333}13341335// Printing1336const char* name() const;1337virtual const char* short_name() const { return "CMS"; }1338void print() const;1339void printOccupancy(const char* s);1340bool must_be_youngest() const { return false; }1341bool must_be_oldest() const { return true; }13421343// Resize the generation after a compacting GC. The1344// generation can be treated as a contiguous space1345// after the compaction.1346virtual void compute_new_size();1347// Resize the generation after a non-compacting1348// collection.1349void compute_new_size_free_list();13501351CollectionTypes debug_collection_type() { return _debug_collection_type; }1352void rotate_debug_collection_type();1353};13541355class ASConcurrentMarkSweepGeneration : public ConcurrentMarkSweepGeneration {13561357// Return the size policy from the heap's collector1358// policy casted to CMSAdaptiveSizePolicy*.1359CMSAdaptiveSizePolicy* cms_size_policy() const;13601361// Resize the generation based on the adaptive size1362// policy.1363void resize(size_t cur_promo, size_t desired_promo);13641365// Return the GC counters from the collector policy1366CMSGCAdaptivePolicyCounters* gc_adaptive_policy_counters();13671368virtual void shrink_by(size_t bytes);13691370public:1371ASConcurrentMarkSweepGeneration(ReservedSpace rs, size_t initial_byte_size,1372int level, CardTableRS* ct,1373bool use_adaptive_freelists,1374FreeBlockDictionary<FreeChunk>::DictionaryChoice1375dictionaryChoice) :1376ConcurrentMarkSweepGeneration(rs, initial_byte_size, level, ct,1377use_adaptive_freelists, dictionaryChoice) {}13781379virtual const char* short_name() const { return "ASCMS"; }1380virtual Generation::Name kind() { return Generation::ASConcurrentMarkSweep; }13811382virtual void update_counters();1383virtual void update_counters(size_t used);1384};13851386//1387// Closures of various sorts used by CMS to accomplish its work1388//13891390// This closure is used to do concurrent marking from the roots1391// following the first checkpoint.1392class MarkFromRootsClosure: public BitMapClosure {1393CMSCollector* _collector;1394MemRegion _span;1395CMSBitMap* _bitMap;1396CMSBitMap* _mut;1397CMSMarkStack* _markStack;1398bool _yield;1399int _skipBits;1400HeapWord* _finger;1401HeapWord* _threshold;1402DEBUG_ONLY(bool _verifying;)14031404public:1405MarkFromRootsClosure(CMSCollector* collector, MemRegion span,1406CMSBitMap* bitMap,1407CMSMarkStack* markStack,1408bool should_yield, bool verifying = false);1409bool do_bit(size_t offset);1410void reset(HeapWord* addr);1411inline void do_yield_check();14121413private:1414void scanOopsInOop(HeapWord* ptr);1415void do_yield_work();1416};14171418// This closure is used to do concurrent multi-threaded1419// marking from the roots following the first checkpoint.1420// XXX This should really be a subclass of The serial version1421// above, but i have not had the time to refactor things cleanly.1422// That willbe done for Dolphin.1423class Par_MarkFromRootsClosure: public BitMapClosure {1424CMSCollector* _collector;1425MemRegion _whole_span;1426MemRegion _span;1427CMSBitMap* _bit_map;1428CMSBitMap* _mut;1429OopTaskQueue* _work_queue;1430CMSMarkStack* _overflow_stack;1431bool _yield;1432int _skip_bits;1433HeapWord* _finger;1434HeapWord* _threshold;1435CMSConcMarkingTask* _task;1436public:1437Par_MarkFromRootsClosure(CMSConcMarkingTask* task, CMSCollector* collector,1438MemRegion span,1439CMSBitMap* bit_map,1440OopTaskQueue* work_queue,1441CMSMarkStack* overflow_stack,1442bool should_yield);1443bool do_bit(size_t offset);1444inline void do_yield_check();14451446private:1447void scan_oops_in_oop(HeapWord* ptr);1448void do_yield_work();1449bool get_work_from_overflow_stack();1450};14511452// The following closures are used to do certain kinds of verification of1453// CMS marking.1454class PushAndMarkVerifyClosure: public MetadataAwareOopClosure {1455CMSCollector* _collector;1456MemRegion _span;1457CMSBitMap* _verification_bm;1458CMSBitMap* _cms_bm;1459CMSMarkStack* _mark_stack;1460protected:1461void do_oop(oop p);1462template <class T> inline void do_oop_work(T *p) {1463oop obj = oopDesc::load_decode_heap_oop(p);1464do_oop(obj);1465}1466public:1467PushAndMarkVerifyClosure(CMSCollector* cms_collector,1468MemRegion span,1469CMSBitMap* verification_bm,1470CMSBitMap* cms_bm,1471CMSMarkStack* mark_stack);1472void do_oop(oop* p);1473void do_oop(narrowOop* p);14741475// Deal with a stack overflow condition1476void handle_stack_overflow(HeapWord* lost);1477};14781479class MarkFromRootsVerifyClosure: public BitMapClosure {1480CMSCollector* _collector;1481MemRegion _span;1482CMSBitMap* _verification_bm;1483CMSBitMap* _cms_bm;1484CMSMarkStack* _mark_stack;1485HeapWord* _finger;1486PushAndMarkVerifyClosure _pam_verify_closure;1487public:1488MarkFromRootsVerifyClosure(CMSCollector* collector, MemRegion span,1489CMSBitMap* verification_bm,1490CMSBitMap* cms_bm,1491CMSMarkStack* mark_stack);1492bool do_bit(size_t offset);1493void reset(HeapWord* addr);1494};149514961497// This closure is used to check that a certain set of bits is1498// "empty" (i.e. the bit vector doesn't have any 1-bits).1499class FalseBitMapClosure: public BitMapClosure {1500public:1501bool do_bit(size_t offset) {1502guarantee(false, "Should not have a 1 bit");1503return true;1504}1505};15061507// A version of ObjectClosure with "memory" (see _previous_address below)1508class UpwardsObjectClosure: public BoolObjectClosure {1509HeapWord* _previous_address;1510public:1511UpwardsObjectClosure() : _previous_address(NULL) { }1512void set_previous(HeapWord* addr) { _previous_address = addr; }1513HeapWord* previous() { return _previous_address; }1514// A return value of "true" can be used by the caller to decide1515// if this object's end should *NOT* be recorded in1516// _previous_address above.1517virtual bool do_object_bm(oop obj, MemRegion mr) = 0;1518};15191520// This closure is used during the second checkpointing phase1521// to rescan the marked objects on the dirty cards in the mod1522// union table and the card table proper. It's invoked via1523// MarkFromDirtyCardsClosure below. It uses either1524// [Par_]MarkRefsIntoAndScanClosure (Par_ in the parallel case)1525// declared in genOopClosures.hpp to accomplish some of its work.1526// In the parallel case the bitMap is shared, so access to1527// it needs to be suitably synchronized for updates by embedded1528// closures that update it; however, this closure itself only1529// reads the bit_map and because it is idempotent, is immune to1530// reading stale values.1531class ScanMarkedObjectsAgainClosure: public UpwardsObjectClosure {1532#ifdef ASSERT1533CMSCollector* _collector;1534MemRegion _span;1535union {1536CMSMarkStack* _mark_stack;1537OopTaskQueue* _work_queue;1538};1539#endif // ASSERT1540bool _parallel;1541CMSBitMap* _bit_map;1542union {1543MarkRefsIntoAndScanClosure* _scan_closure;1544Par_MarkRefsIntoAndScanClosure* _par_scan_closure;1545};15461547public:1548ScanMarkedObjectsAgainClosure(CMSCollector* collector,1549MemRegion span,1550ReferenceProcessor* rp,1551CMSBitMap* bit_map,1552CMSMarkStack* mark_stack,1553MarkRefsIntoAndScanClosure* cl):1554#ifdef ASSERT1555_collector(collector),1556_span(span),1557_mark_stack(mark_stack),1558#endif // ASSERT1559_parallel(false),1560_bit_map(bit_map),1561_scan_closure(cl) { }15621563ScanMarkedObjectsAgainClosure(CMSCollector* collector,1564MemRegion span,1565ReferenceProcessor* rp,1566CMSBitMap* bit_map,1567OopTaskQueue* work_queue,1568Par_MarkRefsIntoAndScanClosure* cl):1569#ifdef ASSERT1570_collector(collector),1571_span(span),1572_work_queue(work_queue),1573#endif // ASSERT1574_parallel(true),1575_bit_map(bit_map),1576_par_scan_closure(cl) { }15771578bool do_object_b(oop obj) {1579guarantee(false, "Call do_object_b(oop, MemRegion) form instead");1580return false;1581}1582bool do_object_bm(oop p, MemRegion mr);1583};15841585// This closure is used during the second checkpointing phase1586// to rescan the marked objects on the dirty cards in the mod1587// union table and the card table proper. It invokes1588// ScanMarkedObjectsAgainClosure above to accomplish much of its work.1589// In the parallel case, the bit map is shared and requires1590// synchronized access.1591class MarkFromDirtyCardsClosure: public MemRegionClosure {1592CompactibleFreeListSpace* _space;1593ScanMarkedObjectsAgainClosure _scan_cl;1594size_t _num_dirty_cards;15951596public:1597MarkFromDirtyCardsClosure(CMSCollector* collector,1598MemRegion span,1599CompactibleFreeListSpace* space,1600CMSBitMap* bit_map,1601CMSMarkStack* mark_stack,1602MarkRefsIntoAndScanClosure* cl):1603_space(space),1604_num_dirty_cards(0),1605_scan_cl(collector, span, collector->ref_processor(), bit_map,1606mark_stack, cl) { }16071608MarkFromDirtyCardsClosure(CMSCollector* collector,1609MemRegion span,1610CompactibleFreeListSpace* space,1611CMSBitMap* bit_map,1612OopTaskQueue* work_queue,1613Par_MarkRefsIntoAndScanClosure* cl):1614_space(space),1615_num_dirty_cards(0),1616_scan_cl(collector, span, collector->ref_processor(), bit_map,1617work_queue, cl) { }16181619void do_MemRegion(MemRegion mr);1620void set_space(CompactibleFreeListSpace* space) { _space = space; }1621size_t num_dirty_cards() { return _num_dirty_cards; }1622};16231624// This closure is used in the non-product build to check1625// that there are no MemRegions with a certain property.1626class FalseMemRegionClosure: public MemRegionClosure {1627void do_MemRegion(MemRegion mr) {1628guarantee(!mr.is_empty(), "Shouldn't be empty");1629guarantee(false, "Should never be here");1630}1631};16321633// This closure is used during the precleaning phase1634// to "carefully" rescan marked objects on dirty cards.1635// It uses MarkRefsIntoAndScanClosure declared in genOopClosures.hpp1636// to accomplish some of its work.1637class ScanMarkedObjectsAgainCarefullyClosure: public ObjectClosureCareful {1638CMSCollector* _collector;1639MemRegion _span;1640bool _yield;1641Mutex* _freelistLock;1642CMSBitMap* _bitMap;1643CMSMarkStack* _markStack;1644MarkRefsIntoAndScanClosure* _scanningClosure;16451646public:1647ScanMarkedObjectsAgainCarefullyClosure(CMSCollector* collector,1648MemRegion span,1649CMSBitMap* bitMap,1650CMSMarkStack* markStack,1651MarkRefsIntoAndScanClosure* cl,1652bool should_yield):1653_collector(collector),1654_span(span),1655_yield(should_yield),1656_bitMap(bitMap),1657_markStack(markStack),1658_scanningClosure(cl) {1659}16601661void do_object(oop p) {1662guarantee(false, "call do_object_careful instead");1663}16641665size_t do_object_careful(oop p) {1666guarantee(false, "Unexpected caller");1667return 0;1668}16691670size_t do_object_careful_m(oop p, MemRegion mr);16711672void setFreelistLock(Mutex* m) {1673_freelistLock = m;1674_scanningClosure->set_freelistLock(m);1675}16761677private:1678inline bool do_yield_check();16791680void do_yield_work();1681};16821683class SurvivorSpacePrecleanClosure: public ObjectClosureCareful {1684CMSCollector* _collector;1685MemRegion _span;1686bool _yield;1687CMSBitMap* _bit_map;1688CMSMarkStack* _mark_stack;1689PushAndMarkClosure* _scanning_closure;1690unsigned int _before_count;16911692public:1693SurvivorSpacePrecleanClosure(CMSCollector* collector,1694MemRegion span,1695CMSBitMap* bit_map,1696CMSMarkStack* mark_stack,1697PushAndMarkClosure* cl,1698unsigned int before_count,1699bool should_yield):1700_collector(collector),1701_span(span),1702_yield(should_yield),1703_bit_map(bit_map),1704_mark_stack(mark_stack),1705_scanning_closure(cl),1706_before_count(before_count)1707{ }17081709void do_object(oop p) {1710guarantee(false, "call do_object_careful instead");1711}17121713size_t do_object_careful(oop p);17141715size_t do_object_careful_m(oop p, MemRegion mr) {1716guarantee(false, "Unexpected caller");1717return 0;1718}17191720private:1721inline void do_yield_check();1722void do_yield_work();1723};17241725// This closure is used to accomplish the sweeping work1726// after the second checkpoint but before the concurrent reset1727// phase.1728//1729// Terminology1730// left hand chunk (LHC) - block of one or more chunks currently being1731// coalesced. The LHC is available for coalescing with a new chunk.1732// right hand chunk (RHC) - block that is currently being swept that is1733// free or garbage that can be coalesced with the LHC.1734// _inFreeRange is true if there is currently a LHC1735// _lastFreeRangeCoalesced is true if the LHC consists of more than one chunk.1736// _freeRangeInFreeLists is true if the LHC is in the free lists.1737// _freeFinger is the address of the current LHC1738class SweepClosure: public BlkClosureCareful {1739CMSCollector* _collector; // collector doing the work1740ConcurrentMarkSweepGeneration* _g; // Generation being swept1741CompactibleFreeListSpace* _sp; // Space being swept1742HeapWord* _limit;// the address at or above which the sweep should stop1743// because we do not expect newly garbage blocks1744// eligible for sweeping past that address.1745Mutex* _freelistLock; // Free list lock (in space)1746CMSBitMap* _bitMap; // Marking bit map (in1747// generation)1748bool _inFreeRange; // Indicates if we are in the1749// midst of a free run1750bool _freeRangeInFreeLists;1751// Often, we have just found1752// a free chunk and started1753// a new free range; we do not1754// eagerly remove this chunk from1755// the free lists unless there is1756// a possibility of coalescing.1757// When true, this flag indicates1758// that the _freeFinger below1759// points to a potentially free chunk1760// that may still be in the free lists1761bool _lastFreeRangeCoalesced;1762// free range contains chunks1763// coalesced1764bool _yield;1765// Whether sweeping should be1766// done with yields. For instance1767// when done by the foreground1768// collector we shouldn't yield.1769HeapWord* _freeFinger; // When _inFreeRange is set, the1770// pointer to the "left hand1771// chunk"1772size_t _freeRangeSize;1773// When _inFreeRange is set, this1774// indicates the accumulated size1775// of the "left hand chunk"1776NOT_PRODUCT(1777size_t _numObjectsFreed;1778size_t _numWordsFreed;1779size_t _numObjectsLive;1780size_t _numWordsLive;1781size_t _numObjectsAlreadyFree;1782size_t _numWordsAlreadyFree;1783FreeChunk* _last_fc;1784)1785private:1786// Code that is common to a free chunk or garbage when1787// encountered during sweeping.1788void do_post_free_or_garbage_chunk(FreeChunk *fc, size_t chunkSize);1789// Process a free chunk during sweeping.1790void do_already_free_chunk(FreeChunk *fc);1791// Work method called when processing an already free or a1792// freshly garbage chunk to do a lookahead and possibly a1793// premptive flush if crossing over _limit.1794void lookahead_and_flush(FreeChunk* fc, size_t chunkSize);1795// Process a garbage chunk during sweeping.1796size_t do_garbage_chunk(FreeChunk *fc);1797// Process a live chunk during sweeping.1798size_t do_live_chunk(FreeChunk* fc);17991800// Accessors.1801HeapWord* freeFinger() const { return _freeFinger; }1802void set_freeFinger(HeapWord* v) { _freeFinger = v; }1803bool inFreeRange() const { return _inFreeRange; }1804void set_inFreeRange(bool v) { _inFreeRange = v; }1805bool lastFreeRangeCoalesced() const { return _lastFreeRangeCoalesced; }1806void set_lastFreeRangeCoalesced(bool v) { _lastFreeRangeCoalesced = v; }1807bool freeRangeInFreeLists() const { return _freeRangeInFreeLists; }1808void set_freeRangeInFreeLists(bool v) { _freeRangeInFreeLists = v; }18091810// Initialize a free range.1811void initialize_free_range(HeapWord* freeFinger, bool freeRangeInFreeLists);1812// Return this chunk to the free lists.1813void flush_cur_free_chunk(HeapWord* chunk, size_t size);18141815// Check if we should yield and do so when necessary.1816inline void do_yield_check(HeapWord* addr);18171818// Yield1819void do_yield_work(HeapWord* addr);18201821// Debugging/Printing1822void print_free_block_coalesced(FreeChunk* fc) const;18231824public:1825SweepClosure(CMSCollector* collector, ConcurrentMarkSweepGeneration* g,1826CMSBitMap* bitMap, bool should_yield);1827~SweepClosure() PRODUCT_RETURN;18281829size_t do_blk_careful(HeapWord* addr);1830void print() const { print_on(tty); }1831void print_on(outputStream *st) const;1832};18331834// Closures related to weak references processing18351836// During CMS' weak reference processing, this is a1837// work-routine/closure used to complete transitive1838// marking of objects as live after a certain point1839// in which an initial set has been completely accumulated.1840// This closure is currently used both during the final1841// remark stop-world phase, as well as during the concurrent1842// precleaning of the discovered reference lists.1843class CMSDrainMarkingStackClosure: public VoidClosure {1844CMSCollector* _collector;1845MemRegion _span;1846CMSMarkStack* _mark_stack;1847CMSBitMap* _bit_map;1848CMSKeepAliveClosure* _keep_alive;1849bool _concurrent_precleaning;1850public:1851CMSDrainMarkingStackClosure(CMSCollector* collector, MemRegion span,1852CMSBitMap* bit_map, CMSMarkStack* mark_stack,1853CMSKeepAliveClosure* keep_alive,1854bool cpc):1855_collector(collector),1856_span(span),1857_bit_map(bit_map),1858_mark_stack(mark_stack),1859_keep_alive(keep_alive),1860_concurrent_precleaning(cpc) {1861assert(_concurrent_precleaning == _keep_alive->concurrent_precleaning(),1862"Mismatch");1863}18641865void do_void();1866};18671868// A parallel version of CMSDrainMarkingStackClosure above.1869class CMSParDrainMarkingStackClosure: public VoidClosure {1870CMSCollector* _collector;1871MemRegion _span;1872OopTaskQueue* _work_queue;1873CMSBitMap* _bit_map;1874CMSInnerParMarkAndPushClosure _mark_and_push;18751876public:1877CMSParDrainMarkingStackClosure(CMSCollector* collector,1878MemRegion span, CMSBitMap* bit_map,1879OopTaskQueue* work_queue):1880_collector(collector),1881_span(span),1882_bit_map(bit_map),1883_work_queue(work_queue),1884_mark_and_push(collector, span, bit_map, work_queue) { }18851886public:1887void trim_queue(uint max);1888void do_void();1889};18901891// Allow yielding or short-circuiting of reference list1892// prelceaning work.1893class CMSPrecleanRefsYieldClosure: public YieldClosure {1894CMSCollector* _collector;1895void do_yield_work();1896public:1897CMSPrecleanRefsYieldClosure(CMSCollector* collector):1898_collector(collector) {}1899virtual bool should_return();1900};190119021903// Convenience class that locks free list locks for given CMS collector1904class FreelistLocker: public StackObj {1905private:1906CMSCollector* _collector;1907public:1908FreelistLocker(CMSCollector* collector):1909_collector(collector) {1910_collector->getFreelistLocks();1911}19121913~FreelistLocker() {1914_collector->releaseFreelistLocks();1915}1916};19171918// Mark all dead objects in a given space.1919class MarkDeadObjectsClosure: public BlkClosure {1920const CMSCollector* _collector;1921const CompactibleFreeListSpace* _sp;1922CMSBitMap* _live_bit_map;1923CMSBitMap* _dead_bit_map;1924public:1925MarkDeadObjectsClosure(const CMSCollector* collector,1926const CompactibleFreeListSpace* sp,1927CMSBitMap *live_bit_map,1928CMSBitMap *dead_bit_map) :1929_collector(collector),1930_sp(sp),1931_live_bit_map(live_bit_map),1932_dead_bit_map(dead_bit_map) {}1933size_t do_blk(HeapWord* addr);1934};19351936class TraceCMSMemoryManagerStats : public TraceMemoryManagerStats {19371938public:1939TraceCMSMemoryManagerStats(CMSCollector::CollectorState phase, GCCause::Cause cause);1940};194119421943#endif // SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CONCURRENTMARKSWEEPGENERATION_HPP194419451946