Mon, 24 Aug 2009 10:36:31 -0700
6798898: CMS: bugs related to class unloading
Summary: Override should_remember_klasses() and remember_klass() as needed.
Reviewed-by: ysr, jcoomes
1 /*
2 * Copyright 2001-2009 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 *
23 */
25 # include "incls/_precompiled.incl"
26 # include "incls/_concurrentMarkSweepGeneration.cpp.incl"
28 // statics
29 CMSCollector* ConcurrentMarkSweepGeneration::_collector = NULL;
30 bool CMSCollector::_full_gc_requested = false;
32 //////////////////////////////////////////////////////////////////
33 // In support of CMS/VM thread synchronization
34 //////////////////////////////////////////////////////////////////
35 // We split use of the CGC_lock into 2 "levels".
36 // The low-level locking is of the usual CGC_lock monitor. We introduce
37 // a higher level "token" (hereafter "CMS token") built on top of the
38 // low level monitor (hereafter "CGC lock").
39 // The token-passing protocol gives priority to the VM thread. The
40 // CMS-lock doesn't provide any fairness guarantees, but clients
41 // should ensure that it is only held for very short, bounded
42 // durations.
43 //
44 // When either of the CMS thread or the VM thread is involved in
45 // collection operations during which it does not want the other
46 // thread to interfere, it obtains the CMS token.
47 //
48 // If either thread tries to get the token while the other has
49 // it, that thread waits. However, if the VM thread and CMS thread
50 // both want the token, then the VM thread gets priority while the
51 // CMS thread waits. This ensures, for instance, that the "concurrent"
52 // phases of the CMS thread's work do not block out the VM thread
53 // for long periods of time as the CMS thread continues to hog
54 // the token. (See bug 4616232).
55 //
56 // The baton-passing functions are, however, controlled by the
57 // flags _foregroundGCShouldWait and _foregroundGCIsActive,
58 // and here the low-level CMS lock, not the high level token,
59 // ensures mutual exclusion.
60 //
61 // Two important conditions that we have to satisfy:
62 // 1. if a thread does a low-level wait on the CMS lock, then it
63 // relinquishes the CMS token if it were holding that token
64 // when it acquired the low-level CMS lock.
65 // 2. any low-level notifications on the low-level lock
66 // should only be sent when a thread has relinquished the token.
67 //
68 // In the absence of either property, we'd have potential deadlock.
69 //
70 // We protect each of the CMS (concurrent and sequential) phases
71 // with the CMS _token_, not the CMS _lock_.
72 //
73 // The only code protected by CMS lock is the token acquisition code
74 // itself, see ConcurrentMarkSweepThread::[de]synchronize(), and the
75 // baton-passing code.
76 //
77 // Unfortunately, i couldn't come up with a good abstraction to factor and
78 // hide the naked CGC_lock manipulation in the baton-passing code
79 // further below. That's something we should try to do. Also, the proof
80 // of correctness of this 2-level locking scheme is far from obvious,
81 // and potentially quite slippery. We have an uneasy supsicion, for instance,
82 // that there may be a theoretical possibility of delay/starvation in the
83 // low-level lock/wait/notify scheme used for the baton-passing because of
84 // potential intereference with the priority scheme embodied in the
85 // CMS-token-passing protocol. See related comments at a CGC_lock->wait()
86 // invocation further below and marked with "XXX 20011219YSR".
87 // Indeed, as we note elsewhere, this may become yet more slippery
88 // in the presence of multiple CMS and/or multiple VM threads. XXX
90 class CMSTokenSync: public StackObj {
91 private:
92 bool _is_cms_thread;
93 public:
94 CMSTokenSync(bool is_cms_thread):
95 _is_cms_thread(is_cms_thread) {
96 assert(is_cms_thread == Thread::current()->is_ConcurrentGC_thread(),
97 "Incorrect argument to constructor");
98 ConcurrentMarkSweepThread::synchronize(_is_cms_thread);
99 }
101 ~CMSTokenSync() {
102 assert(_is_cms_thread ?
103 ConcurrentMarkSweepThread::cms_thread_has_cms_token() :
104 ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
105 "Incorrect state");
106 ConcurrentMarkSweepThread::desynchronize(_is_cms_thread);
107 }
108 };
110 // Convenience class that does a CMSTokenSync, and then acquires
111 // upto three locks.
112 class CMSTokenSyncWithLocks: public CMSTokenSync {
113 private:
114 // Note: locks are acquired in textual declaration order
115 // and released in the opposite order
116 MutexLockerEx _locker1, _locker2, _locker3;
117 public:
118 CMSTokenSyncWithLocks(bool is_cms_thread, Mutex* mutex1,
119 Mutex* mutex2 = NULL, Mutex* mutex3 = NULL):
120 CMSTokenSync(is_cms_thread),
121 _locker1(mutex1, Mutex::_no_safepoint_check_flag),
122 _locker2(mutex2, Mutex::_no_safepoint_check_flag),
123 _locker3(mutex3, Mutex::_no_safepoint_check_flag)
124 { }
125 };
128 // Wrapper class to temporarily disable icms during a foreground cms collection.
129 class ICMSDisabler: public StackObj {
130 public:
131 // The ctor disables icms and wakes up the thread so it notices the change;
132 // the dtor re-enables icms. Note that the CMSCollector methods will check
133 // CMSIncrementalMode.
134 ICMSDisabler() { CMSCollector::disable_icms(); CMSCollector::start_icms(); }
135 ~ICMSDisabler() { CMSCollector::enable_icms(); }
136 };
138 //////////////////////////////////////////////////////////////////
139 // Concurrent Mark-Sweep Generation /////////////////////////////
140 //////////////////////////////////////////////////////////////////
142 NOT_PRODUCT(CompactibleFreeListSpace* debug_cms_space;)
144 // This struct contains per-thread things necessary to support parallel
145 // young-gen collection.
146 class CMSParGCThreadState: public CHeapObj {
147 public:
148 CFLS_LAB lab;
149 PromotionInfo promo;
151 // Constructor.
152 CMSParGCThreadState(CompactibleFreeListSpace* cfls) : lab(cfls) {
153 promo.setSpace(cfls);
154 }
155 };
157 ConcurrentMarkSweepGeneration::ConcurrentMarkSweepGeneration(
158 ReservedSpace rs, size_t initial_byte_size, int level,
159 CardTableRS* ct, bool use_adaptive_freelists,
160 FreeBlockDictionary::DictionaryChoice dictionaryChoice) :
161 CardGeneration(rs, initial_byte_size, level, ct),
162 _dilatation_factor(((double)MinChunkSize)/((double)(oopDesc::header_size()))),
163 _debug_collection_type(Concurrent_collection_type)
164 {
165 HeapWord* bottom = (HeapWord*) _virtual_space.low();
166 HeapWord* end = (HeapWord*) _virtual_space.high();
168 _direct_allocated_words = 0;
169 NOT_PRODUCT(
170 _numObjectsPromoted = 0;
171 _numWordsPromoted = 0;
172 _numObjectsAllocated = 0;
173 _numWordsAllocated = 0;
174 )
176 _cmsSpace = new CompactibleFreeListSpace(_bts, MemRegion(bottom, end),
177 use_adaptive_freelists,
178 dictionaryChoice);
179 NOT_PRODUCT(debug_cms_space = _cmsSpace;)
180 if (_cmsSpace == NULL) {
181 vm_exit_during_initialization(
182 "CompactibleFreeListSpace allocation failure");
183 }
184 _cmsSpace->_gen = this;
186 _gc_stats = new CMSGCStats();
188 // Verify the assumption that FreeChunk::_prev and OopDesc::_klass
189 // offsets match. The ability to tell free chunks from objects
190 // depends on this property.
191 debug_only(
192 FreeChunk* junk = NULL;
193 assert(UseCompressedOops ||
194 junk->prev_addr() == (void*)(oop(junk)->klass_addr()),
195 "Offset of FreeChunk::_prev within FreeChunk must match"
196 " that of OopDesc::_klass within OopDesc");
197 )
198 if (ParallelGCThreads > 0) {
199 typedef CMSParGCThreadState* CMSParGCThreadStatePtr;
200 _par_gc_thread_states =
201 NEW_C_HEAP_ARRAY(CMSParGCThreadStatePtr, ParallelGCThreads);
202 if (_par_gc_thread_states == NULL) {
203 vm_exit_during_initialization("Could not allocate par gc structs");
204 }
205 for (uint i = 0; i < ParallelGCThreads; i++) {
206 _par_gc_thread_states[i] = new CMSParGCThreadState(cmsSpace());
207 if (_par_gc_thread_states[i] == NULL) {
208 vm_exit_during_initialization("Could not allocate par gc structs");
209 }
210 }
211 } else {
212 _par_gc_thread_states = NULL;
213 }
214 _incremental_collection_failed = false;
215 // The "dilatation_factor" is the expansion that can occur on
216 // account of the fact that the minimum object size in the CMS
217 // generation may be larger than that in, say, a contiguous young
218 // generation.
219 // Ideally, in the calculation below, we'd compute the dilatation
220 // factor as: MinChunkSize/(promoting_gen's min object size)
221 // Since we do not have such a general query interface for the
222 // promoting generation, we'll instead just use the mimimum
223 // object size (which today is a header's worth of space);
224 // note that all arithmetic is in units of HeapWords.
225 assert(MinChunkSize >= oopDesc::header_size(), "just checking");
226 assert(_dilatation_factor >= 1.0, "from previous assert");
227 }
230 // The field "_initiating_occupancy" represents the occupancy percentage
231 // at which we trigger a new collection cycle. Unless explicitly specified
232 // via CMSInitiating[Perm]OccupancyFraction (argument "io" below), it
233 // is calculated by:
234 //
235 // Let "f" be MinHeapFreeRatio in
236 //
237 // _intiating_occupancy = 100-f +
238 // f * (CMSTrigger[Perm]Ratio/100)
239 // where CMSTrigger[Perm]Ratio is the argument "tr" below.
240 //
241 // That is, if we assume the heap is at its desired maximum occupancy at the
242 // end of a collection, we let CMSTrigger[Perm]Ratio of the (purported) free
243 // space be allocated before initiating a new collection cycle.
244 //
245 void ConcurrentMarkSweepGeneration::init_initiating_occupancy(intx io, intx tr) {
246 assert(io <= 100 && tr >= 0 && tr <= 100, "Check the arguments");
247 if (io >= 0) {
248 _initiating_occupancy = (double)io / 100.0;
249 } else {
250 _initiating_occupancy = ((100 - MinHeapFreeRatio) +
251 (double)(tr * MinHeapFreeRatio) / 100.0)
252 / 100.0;
253 }
254 }
257 void ConcurrentMarkSweepGeneration::ref_processor_init() {
258 assert(collector() != NULL, "no collector");
259 collector()->ref_processor_init();
260 }
262 void CMSCollector::ref_processor_init() {
263 if (_ref_processor == NULL) {
264 // Allocate and initialize a reference processor
265 _ref_processor = ReferenceProcessor::create_ref_processor(
266 _span, // span
267 _cmsGen->refs_discovery_is_atomic(), // atomic_discovery
268 _cmsGen->refs_discovery_is_mt(), // mt_discovery
269 &_is_alive_closure,
270 ParallelGCThreads,
271 ParallelRefProcEnabled);
272 // Initialize the _ref_processor field of CMSGen
273 _cmsGen->set_ref_processor(_ref_processor);
275 // Allocate a dummy ref processor for perm gen.
276 ReferenceProcessor* rp2 = new ReferenceProcessor();
277 if (rp2 == NULL) {
278 vm_exit_during_initialization("Could not allocate ReferenceProcessor object");
279 }
280 _permGen->set_ref_processor(rp2);
281 }
282 }
284 CMSAdaptiveSizePolicy* CMSCollector::size_policy() {
285 GenCollectedHeap* gch = GenCollectedHeap::heap();
286 assert(gch->kind() == CollectedHeap::GenCollectedHeap,
287 "Wrong type of heap");
288 CMSAdaptiveSizePolicy* sp = (CMSAdaptiveSizePolicy*)
289 gch->gen_policy()->size_policy();
290 assert(sp->is_gc_cms_adaptive_size_policy(),
291 "Wrong type of size policy");
292 return sp;
293 }
295 CMSGCAdaptivePolicyCounters* CMSCollector::gc_adaptive_policy_counters() {
296 CMSGCAdaptivePolicyCounters* results =
297 (CMSGCAdaptivePolicyCounters*) collector_policy()->counters();
298 assert(
299 results->kind() == GCPolicyCounters::CMSGCAdaptivePolicyCountersKind,
300 "Wrong gc policy counter kind");
301 return results;
302 }
305 void ConcurrentMarkSweepGeneration::initialize_performance_counters() {
307 const char* gen_name = "old";
309 // Generation Counters - generation 1, 1 subspace
310 _gen_counters = new GenerationCounters(gen_name, 1, 1, &_virtual_space);
312 _space_counters = new GSpaceCounters(gen_name, 0,
313 _virtual_space.reserved_size(),
314 this, _gen_counters);
315 }
317 CMSStats::CMSStats(ConcurrentMarkSweepGeneration* cms_gen, unsigned int alpha):
318 _cms_gen(cms_gen)
319 {
320 assert(alpha <= 100, "bad value");
321 _saved_alpha = alpha;
323 // Initialize the alphas to the bootstrap value of 100.
324 _gc0_alpha = _cms_alpha = 100;
326 _cms_begin_time.update();
327 _cms_end_time.update();
329 _gc0_duration = 0.0;
330 _gc0_period = 0.0;
331 _gc0_promoted = 0;
333 _cms_duration = 0.0;
334 _cms_period = 0.0;
335 _cms_allocated = 0;
337 _cms_used_at_gc0_begin = 0;
338 _cms_used_at_gc0_end = 0;
339 _allow_duty_cycle_reduction = false;
340 _valid_bits = 0;
341 _icms_duty_cycle = CMSIncrementalDutyCycle;
342 }
344 // If promotion failure handling is on use
345 // the padded average size of the promotion for each
346 // young generation collection.
347 double CMSStats::time_until_cms_gen_full() const {
348 size_t cms_free = _cms_gen->cmsSpace()->free();
349 GenCollectedHeap* gch = GenCollectedHeap::heap();
350 size_t expected_promotion = gch->get_gen(0)->capacity();
351 if (HandlePromotionFailure) {
352 expected_promotion = MIN2(
353 (size_t) _cms_gen->gc_stats()->avg_promoted()->padded_average(),
354 expected_promotion);
355 }
356 if (cms_free > expected_promotion) {
357 // Start a cms collection if there isn't enough space to promote
358 // for the next minor collection. Use the padded average as
359 // a safety factor.
360 cms_free -= expected_promotion;
362 // Adjust by the safety factor.
363 double cms_free_dbl = (double)cms_free;
364 cms_free_dbl = cms_free_dbl * (100.0 - CMSIncrementalSafetyFactor) / 100.0;
366 if (PrintGCDetails && Verbose) {
367 gclog_or_tty->print_cr("CMSStats::time_until_cms_gen_full: cms_free "
368 SIZE_FORMAT " expected_promotion " SIZE_FORMAT,
369 cms_free, expected_promotion);
370 gclog_or_tty->print_cr(" cms_free_dbl %f cms_consumption_rate %f",
371 cms_free_dbl, cms_consumption_rate() + 1.0);
372 }
373 // Add 1 in case the consumption rate goes to zero.
374 return cms_free_dbl / (cms_consumption_rate() + 1.0);
375 }
376 return 0.0;
377 }
379 // Compare the duration of the cms collection to the
380 // time remaining before the cms generation is empty.
381 // Note that the time from the start of the cms collection
382 // to the start of the cms sweep (less than the total
383 // duration of the cms collection) can be used. This
384 // has been tried and some applications experienced
385 // promotion failures early in execution. This was
386 // possibly because the averages were not accurate
387 // enough at the beginning.
388 double CMSStats::time_until_cms_start() const {
389 // We add "gc0_period" to the "work" calculation
390 // below because this query is done (mostly) at the
391 // end of a scavenge, so we need to conservatively
392 // account for that much possible delay
393 // in the query so as to avoid concurrent mode failures
394 // due to starting the collection just a wee bit too
395 // late.
396 double work = cms_duration() + gc0_period();
397 double deadline = time_until_cms_gen_full();
398 if (work > deadline) {
399 if (Verbose && PrintGCDetails) {
400 gclog_or_tty->print(
401 " CMSCollector: collect because of anticipated promotion "
402 "before full %3.7f + %3.7f > %3.7f ", cms_duration(),
403 gc0_period(), time_until_cms_gen_full());
404 }
405 return 0.0;
406 }
407 return work - deadline;
408 }
410 // Return a duty cycle based on old_duty_cycle and new_duty_cycle, limiting the
411 // amount of change to prevent wild oscillation.
412 unsigned int CMSStats::icms_damped_duty_cycle(unsigned int old_duty_cycle,
413 unsigned int new_duty_cycle) {
414 assert(old_duty_cycle <= 100, "bad input value");
415 assert(new_duty_cycle <= 100, "bad input value");
417 // Note: use subtraction with caution since it may underflow (values are
418 // unsigned). Addition is safe since we're in the range 0-100.
419 unsigned int damped_duty_cycle = new_duty_cycle;
420 if (new_duty_cycle < old_duty_cycle) {
421 const unsigned int largest_delta = MAX2(old_duty_cycle / 4, 5U);
422 if (new_duty_cycle + largest_delta < old_duty_cycle) {
423 damped_duty_cycle = old_duty_cycle - largest_delta;
424 }
425 } else if (new_duty_cycle > old_duty_cycle) {
426 const unsigned int largest_delta = MAX2(old_duty_cycle / 4, 15U);
427 if (new_duty_cycle > old_duty_cycle + largest_delta) {
428 damped_duty_cycle = MIN2(old_duty_cycle + largest_delta, 100U);
429 }
430 }
431 assert(damped_duty_cycle <= 100, "invalid duty cycle computed");
433 if (CMSTraceIncrementalPacing) {
434 gclog_or_tty->print(" [icms_damped_duty_cycle(%d,%d) = %d] ",
435 old_duty_cycle, new_duty_cycle, damped_duty_cycle);
436 }
437 return damped_duty_cycle;
438 }
440 unsigned int CMSStats::icms_update_duty_cycle_impl() {
441 assert(CMSIncrementalPacing && valid(),
442 "should be handled in icms_update_duty_cycle()");
444 double cms_time_so_far = cms_timer().seconds();
445 double scaled_duration = cms_duration_per_mb() * _cms_used_at_gc0_end / M;
446 double scaled_duration_remaining = fabsd(scaled_duration - cms_time_so_far);
448 // Avoid division by 0.
449 double time_until_full = MAX2(time_until_cms_gen_full(), 0.01);
450 double duty_cycle_dbl = 100.0 * scaled_duration_remaining / time_until_full;
452 unsigned int new_duty_cycle = MIN2((unsigned int)duty_cycle_dbl, 100U);
453 if (new_duty_cycle > _icms_duty_cycle) {
454 // Avoid very small duty cycles (1 or 2); 0 is allowed.
455 if (new_duty_cycle > 2) {
456 _icms_duty_cycle = icms_damped_duty_cycle(_icms_duty_cycle,
457 new_duty_cycle);
458 }
459 } else if (_allow_duty_cycle_reduction) {
460 // The duty cycle is reduced only once per cms cycle (see record_cms_end()).
461 new_duty_cycle = icms_damped_duty_cycle(_icms_duty_cycle, new_duty_cycle);
462 // Respect the minimum duty cycle.
463 unsigned int min_duty_cycle = (unsigned int)CMSIncrementalDutyCycleMin;
464 _icms_duty_cycle = MAX2(new_duty_cycle, min_duty_cycle);
465 }
467 if (PrintGCDetails || CMSTraceIncrementalPacing) {
468 gclog_or_tty->print(" icms_dc=%d ", _icms_duty_cycle);
469 }
471 _allow_duty_cycle_reduction = false;
472 return _icms_duty_cycle;
473 }
475 #ifndef PRODUCT
476 void CMSStats::print_on(outputStream *st) const {
477 st->print(" gc0_alpha=%d,cms_alpha=%d", _gc0_alpha, _cms_alpha);
478 st->print(",gc0_dur=%g,gc0_per=%g,gc0_promo=" SIZE_FORMAT,
479 gc0_duration(), gc0_period(), gc0_promoted());
480 st->print(",cms_dur=%g,cms_dur_per_mb=%g,cms_per=%g,cms_alloc=" SIZE_FORMAT,
481 cms_duration(), cms_duration_per_mb(),
482 cms_period(), cms_allocated());
483 st->print(",cms_since_beg=%g,cms_since_end=%g",
484 cms_time_since_begin(), cms_time_since_end());
485 st->print(",cms_used_beg=" SIZE_FORMAT ",cms_used_end=" SIZE_FORMAT,
486 _cms_used_at_gc0_begin, _cms_used_at_gc0_end);
487 if (CMSIncrementalMode) {
488 st->print(",dc=%d", icms_duty_cycle());
489 }
491 if (valid()) {
492 st->print(",promo_rate=%g,cms_alloc_rate=%g",
493 promotion_rate(), cms_allocation_rate());
494 st->print(",cms_consumption_rate=%g,time_until_full=%g",
495 cms_consumption_rate(), time_until_cms_gen_full());
496 }
497 st->print(" ");
498 }
499 #endif // #ifndef PRODUCT
501 CMSCollector::CollectorState CMSCollector::_collectorState =
502 CMSCollector::Idling;
503 bool CMSCollector::_foregroundGCIsActive = false;
504 bool CMSCollector::_foregroundGCShouldWait = false;
506 CMSCollector::CMSCollector(ConcurrentMarkSweepGeneration* cmsGen,
507 ConcurrentMarkSweepGeneration* permGen,
508 CardTableRS* ct,
509 ConcurrentMarkSweepPolicy* cp):
510 _cmsGen(cmsGen),
511 _permGen(permGen),
512 _ct(ct),
513 _ref_processor(NULL), // will be set later
514 _conc_workers(NULL), // may be set later
515 _abort_preclean(false),
516 _start_sampling(false),
517 _between_prologue_and_epilogue(false),
518 _markBitMap(0, Mutex::leaf + 1, "CMS_markBitMap_lock"),
519 _perm_gen_verify_bit_map(0, -1 /* no mutex */, "No_lock"),
520 _modUnionTable((CardTableModRefBS::card_shift - LogHeapWordSize),
521 -1 /* lock-free */, "No_lock" /* dummy */),
522 _modUnionClosure(&_modUnionTable),
523 _modUnionClosurePar(&_modUnionTable),
524 // Adjust my span to cover old (cms) gen and perm gen
525 _span(cmsGen->reserved()._union(permGen->reserved())),
526 // Construct the is_alive_closure with _span & markBitMap
527 _is_alive_closure(_span, &_markBitMap),
528 _restart_addr(NULL),
529 _overflow_list(NULL),
530 _preserved_oop_stack(NULL),
531 _preserved_mark_stack(NULL),
532 _stats(cmsGen),
533 _eden_chunk_array(NULL), // may be set in ctor body
534 _eden_chunk_capacity(0), // -- ditto --
535 _eden_chunk_index(0), // -- ditto --
536 _survivor_plab_array(NULL), // -- ditto --
537 _survivor_chunk_array(NULL), // -- ditto --
538 _survivor_chunk_capacity(0), // -- ditto --
539 _survivor_chunk_index(0), // -- ditto --
540 _ser_pmc_preclean_ovflw(0),
541 _ser_kac_preclean_ovflw(0),
542 _ser_pmc_remark_ovflw(0),
543 _par_pmc_remark_ovflw(0),
544 _ser_kac_ovflw(0),
545 _par_kac_ovflw(0),
546 #ifndef PRODUCT
547 _num_par_pushes(0),
548 #endif
549 _collection_count_start(0),
550 _verifying(false),
551 _icms_start_limit(NULL),
552 _icms_stop_limit(NULL),
553 _verification_mark_bm(0, Mutex::leaf + 1, "CMS_verification_mark_bm_lock"),
554 _completed_initialization(false),
555 _collector_policy(cp),
556 _should_unload_classes(false),
557 _concurrent_cycles_since_last_unload(0),
558 _roots_scanning_options(0),
559 _sweep_estimate(CMS_SweepWeight, CMS_SweepPadding)
560 {
561 if (ExplicitGCInvokesConcurrentAndUnloadsClasses) {
562 ExplicitGCInvokesConcurrent = true;
563 }
564 // Now expand the span and allocate the collection support structures
565 // (MUT, marking bit map etc.) to cover both generations subject to
566 // collection.
568 // First check that _permGen is adjacent to _cmsGen and above it.
569 assert( _cmsGen->reserved().word_size() > 0
570 && _permGen->reserved().word_size() > 0,
571 "generations should not be of zero size");
572 assert(_cmsGen->reserved().intersection(_permGen->reserved()).is_empty(),
573 "_cmsGen and _permGen should not overlap");
574 assert(_cmsGen->reserved().end() == _permGen->reserved().start(),
575 "_cmsGen->end() different from _permGen->start()");
577 // For use by dirty card to oop closures.
578 _cmsGen->cmsSpace()->set_collector(this);
579 _permGen->cmsSpace()->set_collector(this);
581 // Allocate MUT and marking bit map
582 {
583 MutexLockerEx x(_markBitMap.lock(), Mutex::_no_safepoint_check_flag);
584 if (!_markBitMap.allocate(_span)) {
585 warning("Failed to allocate CMS Bit Map");
586 return;
587 }
588 assert(_markBitMap.covers(_span), "_markBitMap inconsistency?");
589 }
590 {
591 _modUnionTable.allocate(_span);
592 assert(_modUnionTable.covers(_span), "_modUnionTable inconsistency?");
593 }
595 if (!_markStack.allocate(CMSMarkStackSize)) {
596 warning("Failed to allocate CMS Marking Stack");
597 return;
598 }
599 if (!_revisitStack.allocate(CMSRevisitStackSize)) {
600 warning("Failed to allocate CMS Revisit Stack");
601 return;
602 }
604 // Support for multi-threaded concurrent phases
605 if (ParallelGCThreads > 0 && CMSConcurrentMTEnabled) {
606 if (FLAG_IS_DEFAULT(ParallelCMSThreads)) {
607 // just for now
608 FLAG_SET_DEFAULT(ParallelCMSThreads, (ParallelGCThreads + 3)/4);
609 }
610 if (ParallelCMSThreads > 1) {
611 _conc_workers = new YieldingFlexibleWorkGang("Parallel CMS Threads",
612 ParallelCMSThreads, true);
613 if (_conc_workers == NULL) {
614 warning("GC/CMS: _conc_workers allocation failure: "
615 "forcing -CMSConcurrentMTEnabled");
616 CMSConcurrentMTEnabled = false;
617 }
618 } else {
619 CMSConcurrentMTEnabled = false;
620 }
621 }
622 if (!CMSConcurrentMTEnabled) {
623 ParallelCMSThreads = 0;
624 } else {
625 // Turn off CMSCleanOnEnter optimization temporarily for
626 // the MT case where it's not fixed yet; see 6178663.
627 CMSCleanOnEnter = false;
628 }
629 assert((_conc_workers != NULL) == (ParallelCMSThreads > 1),
630 "Inconsistency");
632 // Parallel task queues; these are shared for the
633 // concurrent and stop-world phases of CMS, but
634 // are not shared with parallel scavenge (ParNew).
635 {
636 uint i;
637 uint num_queues = (uint) MAX2(ParallelGCThreads, ParallelCMSThreads);
639 if ((CMSParallelRemarkEnabled || CMSConcurrentMTEnabled
640 || ParallelRefProcEnabled)
641 && num_queues > 0) {
642 _task_queues = new OopTaskQueueSet(num_queues);
643 if (_task_queues == NULL) {
644 warning("task_queues allocation failure.");
645 return;
646 }
647 _hash_seed = NEW_C_HEAP_ARRAY(int, num_queues);
648 if (_hash_seed == NULL) {
649 warning("_hash_seed array allocation failure");
650 return;
651 }
653 // XXX use a global constant instead of 64!
654 typedef struct OopTaskQueuePadded {
655 OopTaskQueue work_queue;
656 char pad[64 - sizeof(OopTaskQueue)]; // prevent false sharing
657 } OopTaskQueuePadded;
659 for (i = 0; i < num_queues; i++) {
660 OopTaskQueuePadded *q_padded = new OopTaskQueuePadded();
661 if (q_padded == NULL) {
662 warning("work_queue allocation failure.");
663 return;
664 }
665 _task_queues->register_queue(i, &q_padded->work_queue);
666 }
667 for (i = 0; i < num_queues; i++) {
668 _task_queues->queue(i)->initialize();
669 _hash_seed[i] = 17; // copied from ParNew
670 }
671 }
672 }
674 _cmsGen ->init_initiating_occupancy(CMSInitiatingOccupancyFraction, CMSTriggerRatio);
675 _permGen->init_initiating_occupancy(CMSInitiatingPermOccupancyFraction, CMSTriggerPermRatio);
677 // Clip CMSBootstrapOccupancy between 0 and 100.
678 _bootstrap_occupancy = ((double)MIN2((uintx)100, MAX2((uintx)0, CMSBootstrapOccupancy)))
679 /(double)100;
681 _full_gcs_since_conc_gc = 0;
683 // Now tell CMS generations the identity of their collector
684 ConcurrentMarkSweepGeneration::set_collector(this);
686 // Create & start a CMS thread for this CMS collector
687 _cmsThread = ConcurrentMarkSweepThread::start(this);
688 assert(cmsThread() != NULL, "CMS Thread should have been created");
689 assert(cmsThread()->collector() == this,
690 "CMS Thread should refer to this gen");
691 assert(CGC_lock != NULL, "Where's the CGC_lock?");
693 // Support for parallelizing young gen rescan
694 GenCollectedHeap* gch = GenCollectedHeap::heap();
695 _young_gen = gch->prev_gen(_cmsGen);
696 if (gch->supports_inline_contig_alloc()) {
697 _top_addr = gch->top_addr();
698 _end_addr = gch->end_addr();
699 assert(_young_gen != NULL, "no _young_gen");
700 _eden_chunk_index = 0;
701 _eden_chunk_capacity = (_young_gen->max_capacity()+CMSSamplingGrain)/CMSSamplingGrain;
702 _eden_chunk_array = NEW_C_HEAP_ARRAY(HeapWord*, _eden_chunk_capacity);
703 if (_eden_chunk_array == NULL) {
704 _eden_chunk_capacity = 0;
705 warning("GC/CMS: _eden_chunk_array allocation failure");
706 }
707 }
708 assert(_eden_chunk_array != NULL || _eden_chunk_capacity == 0, "Error");
710 // Support for parallelizing survivor space rescan
711 if (CMSParallelRemarkEnabled && CMSParallelSurvivorRemarkEnabled) {
712 size_t max_plab_samples = MaxNewSize/((SurvivorRatio+2)*MinTLABSize);
713 _survivor_plab_array = NEW_C_HEAP_ARRAY(ChunkArray, ParallelGCThreads);
714 _survivor_chunk_array = NEW_C_HEAP_ARRAY(HeapWord*, 2*max_plab_samples);
715 _cursor = NEW_C_HEAP_ARRAY(size_t, ParallelGCThreads);
716 if (_survivor_plab_array == NULL || _survivor_chunk_array == NULL
717 || _cursor == NULL) {
718 warning("Failed to allocate survivor plab/chunk array");
719 if (_survivor_plab_array != NULL) {
720 FREE_C_HEAP_ARRAY(ChunkArray, _survivor_plab_array);
721 _survivor_plab_array = NULL;
722 }
723 if (_survivor_chunk_array != NULL) {
724 FREE_C_HEAP_ARRAY(HeapWord*, _survivor_chunk_array);
725 _survivor_chunk_array = NULL;
726 }
727 if (_cursor != NULL) {
728 FREE_C_HEAP_ARRAY(size_t, _cursor);
729 _cursor = NULL;
730 }
731 } else {
732 _survivor_chunk_capacity = 2*max_plab_samples;
733 for (uint i = 0; i < ParallelGCThreads; i++) {
734 HeapWord** vec = NEW_C_HEAP_ARRAY(HeapWord*, max_plab_samples);
735 if (vec == NULL) {
736 warning("Failed to allocate survivor plab array");
737 for (int j = i; j > 0; j--) {
738 FREE_C_HEAP_ARRAY(HeapWord*, _survivor_plab_array[j-1].array());
739 }
740 FREE_C_HEAP_ARRAY(ChunkArray, _survivor_plab_array);
741 FREE_C_HEAP_ARRAY(HeapWord*, _survivor_chunk_array);
742 _survivor_plab_array = NULL;
743 _survivor_chunk_array = NULL;
744 _survivor_chunk_capacity = 0;
745 break;
746 } else {
747 ChunkArray* cur =
748 ::new (&_survivor_plab_array[i]) ChunkArray(vec,
749 max_plab_samples);
750 assert(cur->end() == 0, "Should be 0");
751 assert(cur->array() == vec, "Should be vec");
752 assert(cur->capacity() == max_plab_samples, "Error");
753 }
754 }
755 }
756 }
757 assert( ( _survivor_plab_array != NULL
758 && _survivor_chunk_array != NULL)
759 || ( _survivor_chunk_capacity == 0
760 && _survivor_chunk_index == 0),
761 "Error");
763 // Choose what strong roots should be scanned depending on verification options
764 // and perm gen collection mode.
765 if (!CMSClassUnloadingEnabled) {
766 // If class unloading is disabled we want to include all classes into the root set.
767 add_root_scanning_option(SharedHeap::SO_AllClasses);
768 } else {
769 add_root_scanning_option(SharedHeap::SO_SystemClasses);
770 }
772 NOT_PRODUCT(_overflow_counter = CMSMarkStackOverflowInterval;)
773 _gc_counters = new CollectorCounters("CMS", 1);
774 _completed_initialization = true;
775 _sweep_timer.start(); // start of time
776 }
778 const char* ConcurrentMarkSweepGeneration::name() const {
779 return "concurrent mark-sweep generation";
780 }
781 void ConcurrentMarkSweepGeneration::update_counters() {
782 if (UsePerfData) {
783 _space_counters->update_all();
784 _gen_counters->update_all();
785 }
786 }
788 // this is an optimized version of update_counters(). it takes the
789 // used value as a parameter rather than computing it.
790 //
791 void ConcurrentMarkSweepGeneration::update_counters(size_t used) {
792 if (UsePerfData) {
793 _space_counters->update_used(used);
794 _space_counters->update_capacity();
795 _gen_counters->update_all();
796 }
797 }
799 void ConcurrentMarkSweepGeneration::print() const {
800 Generation::print();
801 cmsSpace()->print();
802 }
804 #ifndef PRODUCT
805 void ConcurrentMarkSweepGeneration::print_statistics() {
806 cmsSpace()->printFLCensus(0);
807 }
808 #endif
810 void ConcurrentMarkSweepGeneration::printOccupancy(const char *s) {
811 GenCollectedHeap* gch = GenCollectedHeap::heap();
812 if (PrintGCDetails) {
813 if (Verbose) {
814 gclog_or_tty->print(" [%d %s-%s: "SIZE_FORMAT"("SIZE_FORMAT")]",
815 level(), short_name(), s, used(), capacity());
816 } else {
817 gclog_or_tty->print(" [%d %s-%s: "SIZE_FORMAT"K("SIZE_FORMAT"K)]",
818 level(), short_name(), s, used() / K, capacity() / K);
819 }
820 }
821 if (Verbose) {
822 gclog_or_tty->print(" "SIZE_FORMAT"("SIZE_FORMAT")",
823 gch->used(), gch->capacity());
824 } else {
825 gclog_or_tty->print(" "SIZE_FORMAT"K("SIZE_FORMAT"K)",
826 gch->used() / K, gch->capacity() / K);
827 }
828 }
830 size_t
831 ConcurrentMarkSweepGeneration::contiguous_available() const {
832 // dld proposes an improvement in precision here. If the committed
833 // part of the space ends in a free block we should add that to
834 // uncommitted size in the calculation below. Will make this
835 // change later, staying with the approximation below for the
836 // time being. -- ysr.
837 return MAX2(_virtual_space.uncommitted_size(), unsafe_max_alloc_nogc());
838 }
840 size_t
841 ConcurrentMarkSweepGeneration::unsafe_max_alloc_nogc() const {
842 return _cmsSpace->max_alloc_in_words() * HeapWordSize;
843 }
845 size_t ConcurrentMarkSweepGeneration::max_available() const {
846 return free() + _virtual_space.uncommitted_size();
847 }
849 bool ConcurrentMarkSweepGeneration::promotion_attempt_is_safe(
850 size_t max_promotion_in_bytes,
851 bool younger_handles_promotion_failure) const {
853 // This is the most conservative test. Full promotion is
854 // guaranteed if this is used. The multiplicative factor is to
855 // account for the worst case "dilatation".
856 double adjusted_max_promo_bytes = _dilatation_factor * max_promotion_in_bytes;
857 if (adjusted_max_promo_bytes > (double)max_uintx) { // larger than size_t
858 adjusted_max_promo_bytes = (double)max_uintx;
859 }
860 bool result = (max_contiguous_available() >= (size_t)adjusted_max_promo_bytes);
862 if (younger_handles_promotion_failure && !result) {
863 // Full promotion is not guaranteed because fragmentation
864 // of the cms generation can prevent the full promotion.
865 result = (max_available() >= (size_t)adjusted_max_promo_bytes);
867 if (!result) {
868 // With promotion failure handling the test for the ability
869 // to support the promotion does not have to be guaranteed.
870 // Use an average of the amount promoted.
871 result = max_available() >= (size_t)
872 gc_stats()->avg_promoted()->padded_average();
873 if (PrintGC && Verbose && result) {
874 gclog_or_tty->print_cr(
875 "\nConcurrentMarkSweepGeneration::promotion_attempt_is_safe"
876 " max_available: " SIZE_FORMAT
877 " avg_promoted: " SIZE_FORMAT,
878 max_available(), (size_t)
879 gc_stats()->avg_promoted()->padded_average());
880 }
881 } else {
882 if (PrintGC && Verbose) {
883 gclog_or_tty->print_cr(
884 "\nConcurrentMarkSweepGeneration::promotion_attempt_is_safe"
885 " max_available: " SIZE_FORMAT
886 " adj_max_promo_bytes: " SIZE_FORMAT,
887 max_available(), (size_t)adjusted_max_promo_bytes);
888 }
889 }
890 } else {
891 if (PrintGC && Verbose) {
892 gclog_or_tty->print_cr(
893 "\nConcurrentMarkSweepGeneration::promotion_attempt_is_safe"
894 " contiguous_available: " SIZE_FORMAT
895 " adj_max_promo_bytes: " SIZE_FORMAT,
896 max_contiguous_available(), (size_t)adjusted_max_promo_bytes);
897 }
898 }
899 return result;
900 }
902 CompactibleSpace*
903 ConcurrentMarkSweepGeneration::first_compaction_space() const {
904 return _cmsSpace;
905 }
907 void ConcurrentMarkSweepGeneration::reset_after_compaction() {
908 // Clear the promotion information. These pointers can be adjusted
909 // along with all the other pointers into the heap but
910 // compaction is expected to be a rare event with
911 // a heap using cms so don't do it without seeing the need.
912 if (ParallelGCThreads > 0) {
913 for (uint i = 0; i < ParallelGCThreads; i++) {
914 _par_gc_thread_states[i]->promo.reset();
915 }
916 }
917 }
919 void ConcurrentMarkSweepGeneration::space_iterate(SpaceClosure* blk, bool usedOnly) {
920 blk->do_space(_cmsSpace);
921 }
923 void ConcurrentMarkSweepGeneration::compute_new_size() {
924 assert_locked_or_safepoint(Heap_lock);
926 // If incremental collection failed, we just want to expand
927 // to the limit.
928 if (incremental_collection_failed()) {
929 clear_incremental_collection_failed();
930 grow_to_reserved();
931 return;
932 }
934 size_t expand_bytes = 0;
935 double free_percentage = ((double) free()) / capacity();
936 double desired_free_percentage = (double) MinHeapFreeRatio / 100;
937 double maximum_free_percentage = (double) MaxHeapFreeRatio / 100;
939 // compute expansion delta needed for reaching desired free percentage
940 if (free_percentage < desired_free_percentage) {
941 size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage));
942 assert(desired_capacity >= capacity(), "invalid expansion size");
943 expand_bytes = MAX2(desired_capacity - capacity(), MinHeapDeltaBytes);
944 }
945 if (expand_bytes > 0) {
946 if (PrintGCDetails && Verbose) {
947 size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage));
948 gclog_or_tty->print_cr("\nFrom compute_new_size: ");
949 gclog_or_tty->print_cr(" Free fraction %f", free_percentage);
950 gclog_or_tty->print_cr(" Desired free fraction %f",
951 desired_free_percentage);
952 gclog_or_tty->print_cr(" Maximum free fraction %f",
953 maximum_free_percentage);
954 gclog_or_tty->print_cr(" Capactiy "SIZE_FORMAT, capacity()/1000);
955 gclog_or_tty->print_cr(" Desired capacity "SIZE_FORMAT,
956 desired_capacity/1000);
957 int prev_level = level() - 1;
958 if (prev_level >= 0) {
959 size_t prev_size = 0;
960 GenCollectedHeap* gch = GenCollectedHeap::heap();
961 Generation* prev_gen = gch->_gens[prev_level];
962 prev_size = prev_gen->capacity();
963 gclog_or_tty->print_cr(" Younger gen size "SIZE_FORMAT,
964 prev_size/1000);
965 }
966 gclog_or_tty->print_cr(" unsafe_max_alloc_nogc "SIZE_FORMAT,
967 unsafe_max_alloc_nogc()/1000);
968 gclog_or_tty->print_cr(" contiguous available "SIZE_FORMAT,
969 contiguous_available()/1000);
970 gclog_or_tty->print_cr(" Expand by "SIZE_FORMAT" (bytes)",
971 expand_bytes);
972 }
973 // safe if expansion fails
974 expand(expand_bytes, 0, CMSExpansionCause::_satisfy_free_ratio);
975 if (PrintGCDetails && Verbose) {
976 gclog_or_tty->print_cr(" Expanded free fraction %f",
977 ((double) free()) / capacity());
978 }
979 }
980 }
982 Mutex* ConcurrentMarkSweepGeneration::freelistLock() const {
983 return cmsSpace()->freelistLock();
984 }
986 HeapWord* ConcurrentMarkSweepGeneration::allocate(size_t size,
987 bool tlab) {
988 CMSSynchronousYieldRequest yr;
989 MutexLockerEx x(freelistLock(),
990 Mutex::_no_safepoint_check_flag);
991 return have_lock_and_allocate(size, tlab);
992 }
994 HeapWord* ConcurrentMarkSweepGeneration::have_lock_and_allocate(size_t size,
995 bool tlab) {
996 assert_lock_strong(freelistLock());
997 size_t adjustedSize = CompactibleFreeListSpace::adjustObjectSize(size);
998 HeapWord* res = cmsSpace()->allocate(adjustedSize);
999 // Allocate the object live (grey) if the background collector has
1000 // started marking. This is necessary because the marker may
1001 // have passed this address and consequently this object will
1002 // not otherwise be greyed and would be incorrectly swept up.
1003 // Note that if this object contains references, the writing
1004 // of those references will dirty the card containing this object
1005 // allowing the object to be blackened (and its references scanned)
1006 // either during a preclean phase or at the final checkpoint.
1007 if (res != NULL) {
1008 collector()->direct_allocated(res, adjustedSize);
1009 _direct_allocated_words += adjustedSize;
1010 // allocation counters
1011 NOT_PRODUCT(
1012 _numObjectsAllocated++;
1013 _numWordsAllocated += (int)adjustedSize;
1014 )
1015 }
1016 return res;
1017 }
1019 // In the case of direct allocation by mutators in a generation that
1020 // is being concurrently collected, the object must be allocated
1021 // live (grey) if the background collector has started marking.
1022 // This is necessary because the marker may
1023 // have passed this address and consequently this object will
1024 // not otherwise be greyed and would be incorrectly swept up.
1025 // Note that if this object contains references, the writing
1026 // of those references will dirty the card containing this object
1027 // allowing the object to be blackened (and its references scanned)
1028 // either during a preclean phase or at the final checkpoint.
1029 void CMSCollector::direct_allocated(HeapWord* start, size_t size) {
1030 assert(_markBitMap.covers(start, size), "Out of bounds");
1031 if (_collectorState >= Marking) {
1032 MutexLockerEx y(_markBitMap.lock(),
1033 Mutex::_no_safepoint_check_flag);
1034 // [see comments preceding SweepClosure::do_blk() below for details]
1035 // 1. need to mark the object as live so it isn't collected
1036 // 2. need to mark the 2nd bit to indicate the object may be uninitialized
1037 // 3. need to mark the end of the object so sweeper can skip over it
1038 // if it's uninitialized when the sweeper reaches it.
1039 _markBitMap.mark(start); // object is live
1040 _markBitMap.mark(start + 1); // object is potentially uninitialized?
1041 _markBitMap.mark(start + size - 1);
1042 // mark end of object
1043 }
1044 // check that oop looks uninitialized
1045 assert(oop(start)->klass_or_null() == NULL, "_klass should be NULL");
1046 }
1048 void CMSCollector::promoted(bool par, HeapWord* start,
1049 bool is_obj_array, size_t obj_size) {
1050 assert(_markBitMap.covers(start), "Out of bounds");
1051 // See comment in direct_allocated() about when objects should
1052 // be allocated live.
1053 if (_collectorState >= Marking) {
1054 // we already hold the marking bit map lock, taken in
1055 // the prologue
1056 if (par) {
1057 _markBitMap.par_mark(start);
1058 } else {
1059 _markBitMap.mark(start);
1060 }
1061 // We don't need to mark the object as uninitialized (as
1062 // in direct_allocated above) because this is being done with the
1063 // world stopped and the object will be initialized by the
1064 // time the sweeper gets to look at it.
1065 assert(SafepointSynchronize::is_at_safepoint(),
1066 "expect promotion only at safepoints");
1068 if (_collectorState < Sweeping) {
1069 // Mark the appropriate cards in the modUnionTable, so that
1070 // this object gets scanned before the sweep. If this is
1071 // not done, CMS generation references in the object might
1072 // not get marked.
1073 // For the case of arrays, which are otherwise precisely
1074 // marked, we need to dirty the entire array, not just its head.
1075 if (is_obj_array) {
1076 // The [par_]mark_range() method expects mr.end() below to
1077 // be aligned to the granularity of a bit's representation
1078 // in the heap. In the case of the MUT below, that's a
1079 // card size.
1080 MemRegion mr(start,
1081 (HeapWord*)round_to((intptr_t)(start + obj_size),
1082 CardTableModRefBS::card_size /* bytes */));
1083 if (par) {
1084 _modUnionTable.par_mark_range(mr);
1085 } else {
1086 _modUnionTable.mark_range(mr);
1087 }
1088 } else { // not an obj array; we can just mark the head
1089 if (par) {
1090 _modUnionTable.par_mark(start);
1091 } else {
1092 _modUnionTable.mark(start);
1093 }
1094 }
1095 }
1096 }
1097 }
1099 static inline size_t percent_of_space(Space* space, HeapWord* addr)
1100 {
1101 size_t delta = pointer_delta(addr, space->bottom());
1102 return (size_t)(delta * 100.0 / (space->capacity() / HeapWordSize));
1103 }
1105 void CMSCollector::icms_update_allocation_limits()
1106 {
1107 Generation* gen0 = GenCollectedHeap::heap()->get_gen(0);
1108 EdenSpace* eden = gen0->as_DefNewGeneration()->eden();
1110 const unsigned int duty_cycle = stats().icms_update_duty_cycle();
1111 if (CMSTraceIncrementalPacing) {
1112 stats().print();
1113 }
1115 assert(duty_cycle <= 100, "invalid duty cycle");
1116 if (duty_cycle != 0) {
1117 // The duty_cycle is a percentage between 0 and 100; convert to words and
1118 // then compute the offset from the endpoints of the space.
1119 size_t free_words = eden->free() / HeapWordSize;
1120 double free_words_dbl = (double)free_words;
1121 size_t duty_cycle_words = (size_t)(free_words_dbl * duty_cycle / 100.0);
1122 size_t offset_words = (free_words - duty_cycle_words) / 2;
1124 _icms_start_limit = eden->top() + offset_words;
1125 _icms_stop_limit = eden->end() - offset_words;
1127 // The limits may be adjusted (shifted to the right) by
1128 // CMSIncrementalOffset, to allow the application more mutator time after a
1129 // young gen gc (when all mutators were stopped) and before CMS starts and
1130 // takes away one or more cpus.
1131 if (CMSIncrementalOffset != 0) {
1132 double adjustment_dbl = free_words_dbl * CMSIncrementalOffset / 100.0;
1133 size_t adjustment = (size_t)adjustment_dbl;
1134 HeapWord* tmp_stop = _icms_stop_limit + adjustment;
1135 if (tmp_stop > _icms_stop_limit && tmp_stop < eden->end()) {
1136 _icms_start_limit += adjustment;
1137 _icms_stop_limit = tmp_stop;
1138 }
1139 }
1140 }
1141 if (duty_cycle == 0 || (_icms_start_limit == _icms_stop_limit)) {
1142 _icms_start_limit = _icms_stop_limit = eden->end();
1143 }
1145 // Install the new start limit.
1146 eden->set_soft_end(_icms_start_limit);
1148 if (CMSTraceIncrementalMode) {
1149 gclog_or_tty->print(" icms alloc limits: "
1150 PTR_FORMAT "," PTR_FORMAT
1151 " (" SIZE_FORMAT "%%," SIZE_FORMAT "%%) ",
1152 _icms_start_limit, _icms_stop_limit,
1153 percent_of_space(eden, _icms_start_limit),
1154 percent_of_space(eden, _icms_stop_limit));
1155 if (Verbose) {
1156 gclog_or_tty->print("eden: ");
1157 eden->print_on(gclog_or_tty);
1158 }
1159 }
1160 }
1162 // Any changes here should try to maintain the invariant
1163 // that if this method is called with _icms_start_limit
1164 // and _icms_stop_limit both NULL, then it should return NULL
1165 // and not notify the icms thread.
1166 HeapWord*
1167 CMSCollector::allocation_limit_reached(Space* space, HeapWord* top,
1168 size_t word_size)
1169 {
1170 // A start_limit equal to end() means the duty cycle is 0, so treat that as a
1171 // nop.
1172 if (CMSIncrementalMode && _icms_start_limit != space->end()) {
1173 if (top <= _icms_start_limit) {
1174 if (CMSTraceIncrementalMode) {
1175 space->print_on(gclog_or_tty);
1176 gclog_or_tty->stamp();
1177 gclog_or_tty->print_cr(" start limit top=" PTR_FORMAT
1178 ", new limit=" PTR_FORMAT
1179 " (" SIZE_FORMAT "%%)",
1180 top, _icms_stop_limit,
1181 percent_of_space(space, _icms_stop_limit));
1182 }
1183 ConcurrentMarkSweepThread::start_icms();
1184 assert(top < _icms_stop_limit, "Tautology");
1185 if (word_size < pointer_delta(_icms_stop_limit, top)) {
1186 return _icms_stop_limit;
1187 }
1189 // The allocation will cross both the _start and _stop limits, so do the
1190 // stop notification also and return end().
1191 if (CMSTraceIncrementalMode) {
1192 space->print_on(gclog_or_tty);
1193 gclog_or_tty->stamp();
1194 gclog_or_tty->print_cr(" +stop limit top=" PTR_FORMAT
1195 ", new limit=" PTR_FORMAT
1196 " (" SIZE_FORMAT "%%)",
1197 top, space->end(),
1198 percent_of_space(space, space->end()));
1199 }
1200 ConcurrentMarkSweepThread::stop_icms();
1201 return space->end();
1202 }
1204 if (top <= _icms_stop_limit) {
1205 if (CMSTraceIncrementalMode) {
1206 space->print_on(gclog_or_tty);
1207 gclog_or_tty->stamp();
1208 gclog_or_tty->print_cr(" stop limit top=" PTR_FORMAT
1209 ", new limit=" PTR_FORMAT
1210 " (" SIZE_FORMAT "%%)",
1211 top, space->end(),
1212 percent_of_space(space, space->end()));
1213 }
1214 ConcurrentMarkSweepThread::stop_icms();
1215 return space->end();
1216 }
1218 if (CMSTraceIncrementalMode) {
1219 space->print_on(gclog_or_tty);
1220 gclog_or_tty->stamp();
1221 gclog_or_tty->print_cr(" end limit top=" PTR_FORMAT
1222 ", new limit=" PTR_FORMAT,
1223 top, NULL);
1224 }
1225 }
1227 return NULL;
1228 }
1230 oop ConcurrentMarkSweepGeneration::promote(oop obj, size_t obj_size) {
1231 assert(obj_size == (size_t)obj->size(), "bad obj_size passed in");
1232 // allocate, copy and if necessary update promoinfo --
1233 // delegate to underlying space.
1234 assert_lock_strong(freelistLock());
1236 #ifndef PRODUCT
1237 if (Universe::heap()->promotion_should_fail()) {
1238 return NULL;
1239 }
1240 #endif // #ifndef PRODUCT
1242 oop res = _cmsSpace->promote(obj, obj_size);
1243 if (res == NULL) {
1244 // expand and retry
1245 size_t s = _cmsSpace->expansionSpaceRequired(obj_size); // HeapWords
1246 expand(s*HeapWordSize, MinHeapDeltaBytes,
1247 CMSExpansionCause::_satisfy_promotion);
1248 // Since there's currently no next generation, we don't try to promote
1249 // into a more senior generation.
1250 assert(next_gen() == NULL, "assumption, based upon which no attempt "
1251 "is made to pass on a possibly failing "
1252 "promotion to next generation");
1253 res = _cmsSpace->promote(obj, obj_size);
1254 }
1255 if (res != NULL) {
1256 // See comment in allocate() about when objects should
1257 // be allocated live.
1258 assert(obj->is_oop(), "Will dereference klass pointer below");
1259 collector()->promoted(false, // Not parallel
1260 (HeapWord*)res, obj->is_objArray(), obj_size);
1261 // promotion counters
1262 NOT_PRODUCT(
1263 _numObjectsPromoted++;
1264 _numWordsPromoted +=
1265 (int)(CompactibleFreeListSpace::adjustObjectSize(obj->size()));
1266 )
1267 }
1268 return res;
1269 }
1272 HeapWord*
1273 ConcurrentMarkSweepGeneration::allocation_limit_reached(Space* space,
1274 HeapWord* top,
1275 size_t word_sz)
1276 {
1277 return collector()->allocation_limit_reached(space, top, word_sz);
1278 }
1280 // Things to support parallel young-gen collection.
1281 oop
1282 ConcurrentMarkSweepGeneration::par_promote(int thread_num,
1283 oop old, markOop m,
1284 size_t word_sz) {
1285 #ifndef PRODUCT
1286 if (Universe::heap()->promotion_should_fail()) {
1287 return NULL;
1288 }
1289 #endif // #ifndef PRODUCT
1291 CMSParGCThreadState* ps = _par_gc_thread_states[thread_num];
1292 PromotionInfo* promoInfo = &ps->promo;
1293 // if we are tracking promotions, then first ensure space for
1294 // promotion (including spooling space for saving header if necessary).
1295 // then allocate and copy, then track promoted info if needed.
1296 // When tracking (see PromotionInfo::track()), the mark word may
1297 // be displaced and in this case restoration of the mark word
1298 // occurs in the (oop_since_save_marks_)iterate phase.
1299 if (promoInfo->tracking() && !promoInfo->ensure_spooling_space()) {
1300 // Out of space for allocating spooling buffers;
1301 // try expanding and allocating spooling buffers.
1302 if (!expand_and_ensure_spooling_space(promoInfo)) {
1303 return NULL;
1304 }
1305 }
1306 assert(promoInfo->has_spooling_space(), "Control point invariant");
1307 HeapWord* obj_ptr = ps->lab.alloc(word_sz);
1308 if (obj_ptr == NULL) {
1309 obj_ptr = expand_and_par_lab_allocate(ps, word_sz);
1310 if (obj_ptr == NULL) {
1311 return NULL;
1312 }
1313 }
1314 oop obj = oop(obj_ptr);
1315 assert(obj->klass_or_null() == NULL, "Object should be uninitialized here.");
1316 // Otherwise, copy the object. Here we must be careful to insert the
1317 // klass pointer last, since this marks the block as an allocated object.
1318 // Except with compressed oops it's the mark word.
1319 HeapWord* old_ptr = (HeapWord*)old;
1320 if (word_sz > (size_t)oopDesc::header_size()) {
1321 Copy::aligned_disjoint_words(old_ptr + oopDesc::header_size(),
1322 obj_ptr + oopDesc::header_size(),
1323 word_sz - oopDesc::header_size());
1324 }
1326 if (UseCompressedOops) {
1327 // Copy gap missed by (aligned) header size calculation above
1328 obj->set_klass_gap(old->klass_gap());
1329 }
1331 // Restore the mark word copied above.
1332 obj->set_mark(m);
1334 // Now we can track the promoted object, if necessary. We take care
1335 // To delay the transition from uninitialized to full object
1336 // (i.e., insertion of klass pointer) until after, so that it
1337 // atomically becomes a promoted object.
1338 if (promoInfo->tracking()) {
1339 promoInfo->track((PromotedObject*)obj, old->klass());
1340 }
1342 // Finally, install the klass pointer (this should be volatile).
1343 obj->set_klass(old->klass());
1345 assert(old->is_oop(), "Will dereference klass ptr below");
1346 collector()->promoted(true, // parallel
1347 obj_ptr, old->is_objArray(), word_sz);
1349 NOT_PRODUCT(
1350 Atomic::inc(&_numObjectsPromoted);
1351 Atomic::add((jint)CompactibleFreeListSpace::adjustObjectSize(obj->size()),
1352 &_numWordsPromoted);
1353 )
1355 return obj;
1356 }
1358 void
1359 ConcurrentMarkSweepGeneration::
1360 par_promote_alloc_undo(int thread_num,
1361 HeapWord* obj, size_t word_sz) {
1362 // CMS does not support promotion undo.
1363 ShouldNotReachHere();
1364 }
1366 void
1367 ConcurrentMarkSweepGeneration::
1368 par_promote_alloc_done(int thread_num) {
1369 CMSParGCThreadState* ps = _par_gc_thread_states[thread_num];
1370 ps->lab.retire();
1371 #if CFLS_LAB_REFILL_STATS
1372 if (thread_num == 0) {
1373 _cmsSpace->print_par_alloc_stats();
1374 }
1375 #endif
1376 }
1378 void
1379 ConcurrentMarkSweepGeneration::
1380 par_oop_since_save_marks_iterate_done(int thread_num) {
1381 CMSParGCThreadState* ps = _par_gc_thread_states[thread_num];
1382 ParScanWithoutBarrierClosure* dummy_cl = NULL;
1383 ps->promo.promoted_oops_iterate_nv(dummy_cl);
1384 }
1386 // XXXPERM
1387 bool ConcurrentMarkSweepGeneration::should_collect(bool full,
1388 size_t size,
1389 bool tlab)
1390 {
1391 // We allow a STW collection only if a full
1392 // collection was requested.
1393 return full || should_allocate(size, tlab); // FIX ME !!!
1394 // This and promotion failure handling are connected at the
1395 // hip and should be fixed by untying them.
1396 }
1398 bool CMSCollector::shouldConcurrentCollect() {
1399 if (_full_gc_requested) {
1400 assert(ExplicitGCInvokesConcurrent, "Unexpected state");
1401 if (Verbose && PrintGCDetails) {
1402 gclog_or_tty->print_cr("CMSCollector: collect because of explicit "
1403 " gc request");
1404 }
1405 return true;
1406 }
1408 // For debugging purposes, change the type of collection.
1409 // If the rotation is not on the concurrent collection
1410 // type, don't start a concurrent collection.
1411 NOT_PRODUCT(
1412 if (RotateCMSCollectionTypes &&
1413 (_cmsGen->debug_collection_type() !=
1414 ConcurrentMarkSweepGeneration::Concurrent_collection_type)) {
1415 assert(_cmsGen->debug_collection_type() !=
1416 ConcurrentMarkSweepGeneration::Unknown_collection_type,
1417 "Bad cms collection type");
1418 return false;
1419 }
1420 )
1422 FreelistLocker x(this);
1423 // ------------------------------------------------------------------
1424 // Print out lots of information which affects the initiation of
1425 // a collection.
1426 if (PrintCMSInitiationStatistics && stats().valid()) {
1427 gclog_or_tty->print("CMSCollector shouldConcurrentCollect: ");
1428 gclog_or_tty->stamp();
1429 gclog_or_tty->print_cr("");
1430 stats().print_on(gclog_or_tty);
1431 gclog_or_tty->print_cr("time_until_cms_gen_full %3.7f",
1432 stats().time_until_cms_gen_full());
1433 gclog_or_tty->print_cr("free="SIZE_FORMAT, _cmsGen->free());
1434 gclog_or_tty->print_cr("contiguous_available="SIZE_FORMAT,
1435 _cmsGen->contiguous_available());
1436 gclog_or_tty->print_cr("promotion_rate=%g", stats().promotion_rate());
1437 gclog_or_tty->print_cr("cms_allocation_rate=%g", stats().cms_allocation_rate());
1438 gclog_or_tty->print_cr("occupancy=%3.7f", _cmsGen->occupancy());
1439 gclog_or_tty->print_cr("initiatingOccupancy=%3.7f", _cmsGen->initiating_occupancy());
1440 gclog_or_tty->print_cr("initiatingPermOccupancy=%3.7f", _permGen->initiating_occupancy());
1441 }
1442 // ------------------------------------------------------------------
1444 // If the estimated time to complete a cms collection (cms_duration())
1445 // is less than the estimated time remaining until the cms generation
1446 // is full, start a collection.
1447 if (!UseCMSInitiatingOccupancyOnly) {
1448 if (stats().valid()) {
1449 if (stats().time_until_cms_start() == 0.0) {
1450 return true;
1451 }
1452 } else {
1453 // We want to conservatively collect somewhat early in order
1454 // to try and "bootstrap" our CMS/promotion statistics;
1455 // this branch will not fire after the first successful CMS
1456 // collection because the stats should then be valid.
1457 if (_cmsGen->occupancy() >= _bootstrap_occupancy) {
1458 if (Verbose && PrintGCDetails) {
1459 gclog_or_tty->print_cr(
1460 " CMSCollector: collect for bootstrapping statistics:"
1461 " occupancy = %f, boot occupancy = %f", _cmsGen->occupancy(),
1462 _bootstrap_occupancy);
1463 }
1464 return true;
1465 }
1466 }
1467 }
1469 // Otherwise, we start a collection cycle if either the perm gen or
1470 // old gen want a collection cycle started. Each may use
1471 // an appropriate criterion for making this decision.
1472 // XXX We need to make sure that the gen expansion
1473 // criterion dovetails well with this. XXX NEED TO FIX THIS
1474 if (_cmsGen->should_concurrent_collect()) {
1475 if (Verbose && PrintGCDetails) {
1476 gclog_or_tty->print_cr("CMS old gen initiated");
1477 }
1478 return true;
1479 }
1481 // We start a collection if we believe an incremental collection may fail;
1482 // this is not likely to be productive in practice because it's probably too
1483 // late anyway.
1484 GenCollectedHeap* gch = GenCollectedHeap::heap();
1485 assert(gch->collector_policy()->is_two_generation_policy(),
1486 "You may want to check the correctness of the following");
1487 if (gch->incremental_collection_will_fail()) {
1488 if (PrintGCDetails && Verbose) {
1489 gclog_or_tty->print("CMSCollector: collect because incremental collection will fail ");
1490 }
1491 return true;
1492 }
1494 if (CMSClassUnloadingEnabled && _permGen->should_concurrent_collect()) {
1495 bool res = update_should_unload_classes();
1496 if (res) {
1497 if (Verbose && PrintGCDetails) {
1498 gclog_or_tty->print_cr("CMS perm gen initiated");
1499 }
1500 return true;
1501 }
1502 }
1503 return false;
1504 }
1506 // Clear _expansion_cause fields of constituent generations
1507 void CMSCollector::clear_expansion_cause() {
1508 _cmsGen->clear_expansion_cause();
1509 _permGen->clear_expansion_cause();
1510 }
1512 // We should be conservative in starting a collection cycle. To
1513 // start too eagerly runs the risk of collecting too often in the
1514 // extreme. To collect too rarely falls back on full collections,
1515 // which works, even if not optimum in terms of concurrent work.
1516 // As a work around for too eagerly collecting, use the flag
1517 // UseCMSInitiatingOccupancyOnly. This also has the advantage of
1518 // giving the user an easily understandable way of controlling the
1519 // collections.
1520 // We want to start a new collection cycle if any of the following
1521 // conditions hold:
1522 // . our current occupancy exceeds the configured initiating occupancy
1523 // for this generation, or
1524 // . we recently needed to expand this space and have not, since that
1525 // expansion, done a collection of this generation, or
1526 // . the underlying space believes that it may be a good idea to initiate
1527 // a concurrent collection (this may be based on criteria such as the
1528 // following: the space uses linear allocation and linear allocation is
1529 // going to fail, or there is believed to be excessive fragmentation in
1530 // the generation, etc... or ...
1531 // [.(currently done by CMSCollector::shouldConcurrentCollect() only for
1532 // the case of the old generation, not the perm generation; see CR 6543076):
1533 // we may be approaching a point at which allocation requests may fail because
1534 // we will be out of sufficient free space given allocation rate estimates.]
1535 bool ConcurrentMarkSweepGeneration::should_concurrent_collect() const {
1537 assert_lock_strong(freelistLock());
1538 if (occupancy() > initiating_occupancy()) {
1539 if (PrintGCDetails && Verbose) {
1540 gclog_or_tty->print(" %s: collect because of occupancy %f / %f ",
1541 short_name(), occupancy(), initiating_occupancy());
1542 }
1543 return true;
1544 }
1545 if (UseCMSInitiatingOccupancyOnly) {
1546 return false;
1547 }
1548 if (expansion_cause() == CMSExpansionCause::_satisfy_allocation) {
1549 if (PrintGCDetails && Verbose) {
1550 gclog_or_tty->print(" %s: collect because expanded for allocation ",
1551 short_name());
1552 }
1553 return true;
1554 }
1555 if (_cmsSpace->should_concurrent_collect()) {
1556 if (PrintGCDetails && Verbose) {
1557 gclog_or_tty->print(" %s: collect because cmsSpace says so ",
1558 short_name());
1559 }
1560 return true;
1561 }
1562 return false;
1563 }
1565 void ConcurrentMarkSweepGeneration::collect(bool full,
1566 bool clear_all_soft_refs,
1567 size_t size,
1568 bool tlab)
1569 {
1570 collector()->collect(full, clear_all_soft_refs, size, tlab);
1571 }
1573 void CMSCollector::collect(bool full,
1574 bool clear_all_soft_refs,
1575 size_t size,
1576 bool tlab)
1577 {
1578 if (!UseCMSCollectionPassing && _collectorState > Idling) {
1579 // For debugging purposes skip the collection if the state
1580 // is not currently idle
1581 if (TraceCMSState) {
1582 gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " skipped full:%d CMS state %d",
1583 Thread::current(), full, _collectorState);
1584 }
1585 return;
1586 }
1588 // The following "if" branch is present for defensive reasons.
1589 // In the current uses of this interface, it can be replaced with:
1590 // assert(!GC_locker.is_active(), "Can't be called otherwise");
1591 // But I am not placing that assert here to allow future
1592 // generality in invoking this interface.
1593 if (GC_locker::is_active()) {
1594 // A consistency test for GC_locker
1595 assert(GC_locker::needs_gc(), "Should have been set already");
1596 // Skip this foreground collection, instead
1597 // expanding the heap if necessary.
1598 // Need the free list locks for the call to free() in compute_new_size()
1599 compute_new_size();
1600 return;
1601 }
1602 acquire_control_and_collect(full, clear_all_soft_refs);
1603 _full_gcs_since_conc_gc++;
1605 }
1607 void CMSCollector::request_full_gc(unsigned int full_gc_count) {
1608 GenCollectedHeap* gch = GenCollectedHeap::heap();
1609 unsigned int gc_count = gch->total_full_collections();
1610 if (gc_count == full_gc_count) {
1611 MutexLockerEx y(CGC_lock, Mutex::_no_safepoint_check_flag);
1612 _full_gc_requested = true;
1613 CGC_lock->notify(); // nudge CMS thread
1614 }
1615 }
1618 // The foreground and background collectors need to coordinate in order
1619 // to make sure that they do not mutually interfere with CMS collections.
1620 // When a background collection is active,
1621 // the foreground collector may need to take over (preempt) and
1622 // synchronously complete an ongoing collection. Depending on the
1623 // frequency of the background collections and the heap usage
1624 // of the application, this preemption can be seldom or frequent.
1625 // There are only certain
1626 // points in the background collection that the "collection-baton"
1627 // can be passed to the foreground collector.
1628 //
1629 // The foreground collector will wait for the baton before
1630 // starting any part of the collection. The foreground collector
1631 // will only wait at one location.
1632 //
1633 // The background collector will yield the baton before starting a new
1634 // phase of the collection (e.g., before initial marking, marking from roots,
1635 // precleaning, final re-mark, sweep etc.) This is normally done at the head
1636 // of the loop which switches the phases. The background collector does some
1637 // of the phases (initial mark, final re-mark) with the world stopped.
1638 // Because of locking involved in stopping the world,
1639 // the foreground collector should not block waiting for the background
1640 // collector when it is doing a stop-the-world phase. The background
1641 // collector will yield the baton at an additional point just before
1642 // it enters a stop-the-world phase. Once the world is stopped, the
1643 // background collector checks the phase of the collection. If the
1644 // phase has not changed, it proceeds with the collection. If the
1645 // phase has changed, it skips that phase of the collection. See
1646 // the comments on the use of the Heap_lock in collect_in_background().
1647 //
1648 // Variable used in baton passing.
1649 // _foregroundGCIsActive - Set to true by the foreground collector when
1650 // it wants the baton. The foreground clears it when it has finished
1651 // the collection.
1652 // _foregroundGCShouldWait - Set to true by the background collector
1653 // when it is running. The foreground collector waits while
1654 // _foregroundGCShouldWait is true.
1655 // CGC_lock - monitor used to protect access to the above variables
1656 // and to notify the foreground and background collectors.
1657 // _collectorState - current state of the CMS collection.
1658 //
1659 // The foreground collector
1660 // acquires the CGC_lock
1661 // sets _foregroundGCIsActive
1662 // waits on the CGC_lock for _foregroundGCShouldWait to be false
1663 // various locks acquired in preparation for the collection
1664 // are released so as not to block the background collector
1665 // that is in the midst of a collection
1666 // proceeds with the collection
1667 // clears _foregroundGCIsActive
1668 // returns
1669 //
1670 // The background collector in a loop iterating on the phases of the
1671 // collection
1672 // acquires the CGC_lock
1673 // sets _foregroundGCShouldWait
1674 // if _foregroundGCIsActive is set
1675 // clears _foregroundGCShouldWait, notifies _CGC_lock
1676 // waits on _CGC_lock for _foregroundGCIsActive to become false
1677 // and exits the loop.
1678 // otherwise
1679 // proceed with that phase of the collection
1680 // if the phase is a stop-the-world phase,
1681 // yield the baton once more just before enqueueing
1682 // the stop-world CMS operation (executed by the VM thread).
1683 // returns after all phases of the collection are done
1684 //
1686 void CMSCollector::acquire_control_and_collect(bool full,
1687 bool clear_all_soft_refs) {
1688 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
1689 assert(!Thread::current()->is_ConcurrentGC_thread(),
1690 "shouldn't try to acquire control from self!");
1692 // Start the protocol for acquiring control of the
1693 // collection from the background collector (aka CMS thread).
1694 assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
1695 "VM thread should have CMS token");
1696 // Remember the possibly interrupted state of an ongoing
1697 // concurrent collection
1698 CollectorState first_state = _collectorState;
1700 // Signal to a possibly ongoing concurrent collection that
1701 // we want to do a foreground collection.
1702 _foregroundGCIsActive = true;
1704 // Disable incremental mode during a foreground collection.
1705 ICMSDisabler icms_disabler;
1707 // release locks and wait for a notify from the background collector
1708 // releasing the locks in only necessary for phases which
1709 // do yields to improve the granularity of the collection.
1710 assert_lock_strong(bitMapLock());
1711 // We need to lock the Free list lock for the space that we are
1712 // currently collecting.
1713 assert(haveFreelistLocks(), "Must be holding free list locks");
1714 bitMapLock()->unlock();
1715 releaseFreelistLocks();
1716 {
1717 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
1718 if (_foregroundGCShouldWait) {
1719 // We are going to be waiting for action for the CMS thread;
1720 // it had better not be gone (for instance at shutdown)!
1721 assert(ConcurrentMarkSweepThread::cmst() != NULL,
1722 "CMS thread must be running");
1723 // Wait here until the background collector gives us the go-ahead
1724 ConcurrentMarkSweepThread::clear_CMS_flag(
1725 ConcurrentMarkSweepThread::CMS_vm_has_token); // release token
1726 // Get a possibly blocked CMS thread going:
1727 // Note that we set _foregroundGCIsActive true above,
1728 // without protection of the CGC_lock.
1729 CGC_lock->notify();
1730 assert(!ConcurrentMarkSweepThread::vm_thread_wants_cms_token(),
1731 "Possible deadlock");
1732 while (_foregroundGCShouldWait) {
1733 // wait for notification
1734 CGC_lock->wait(Mutex::_no_safepoint_check_flag);
1735 // Possibility of delay/starvation here, since CMS token does
1736 // not know to give priority to VM thread? Actually, i think
1737 // there wouldn't be any delay/starvation, but the proof of
1738 // that "fact" (?) appears non-trivial. XXX 20011219YSR
1739 }
1740 ConcurrentMarkSweepThread::set_CMS_flag(
1741 ConcurrentMarkSweepThread::CMS_vm_has_token);
1742 }
1743 }
1744 // The CMS_token is already held. Get back the other locks.
1745 assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
1746 "VM thread should have CMS token");
1747 getFreelistLocks();
1748 bitMapLock()->lock_without_safepoint_check();
1749 if (TraceCMSState) {
1750 gclog_or_tty->print_cr("CMS foreground collector has asked for control "
1751 INTPTR_FORMAT " with first state %d", Thread::current(), first_state);
1752 gclog_or_tty->print_cr(" gets control with state %d", _collectorState);
1753 }
1755 // Check if we need to do a compaction, or if not, whether
1756 // we need to start the mark-sweep from scratch.
1757 bool should_compact = false;
1758 bool should_start_over = false;
1759 decide_foreground_collection_type(clear_all_soft_refs,
1760 &should_compact, &should_start_over);
1762 NOT_PRODUCT(
1763 if (RotateCMSCollectionTypes) {
1764 if (_cmsGen->debug_collection_type() ==
1765 ConcurrentMarkSweepGeneration::MSC_foreground_collection_type) {
1766 should_compact = true;
1767 } else if (_cmsGen->debug_collection_type() ==
1768 ConcurrentMarkSweepGeneration::MS_foreground_collection_type) {
1769 should_compact = false;
1770 }
1771 }
1772 )
1774 if (PrintGCDetails && first_state > Idling) {
1775 GCCause::Cause cause = GenCollectedHeap::heap()->gc_cause();
1776 if (GCCause::is_user_requested_gc(cause) ||
1777 GCCause::is_serviceability_requested_gc(cause)) {
1778 gclog_or_tty->print(" (concurrent mode interrupted)");
1779 } else {
1780 gclog_or_tty->print(" (concurrent mode failure)");
1781 }
1782 }
1784 if (should_compact) {
1785 // If the collection is being acquired from the background
1786 // collector, there may be references on the discovered
1787 // references lists that have NULL referents (being those
1788 // that were concurrently cleared by a mutator) or
1789 // that are no longer active (having been enqueued concurrently
1790 // by the mutator).
1791 // Scrub the list of those references because Mark-Sweep-Compact
1792 // code assumes referents are not NULL and that all discovered
1793 // Reference objects are active.
1794 ref_processor()->clean_up_discovered_references();
1796 do_compaction_work(clear_all_soft_refs);
1798 // Has the GC time limit been exceeded?
1799 check_gc_time_limit();
1801 } else {
1802 do_mark_sweep_work(clear_all_soft_refs, first_state,
1803 should_start_over);
1804 }
1805 // Reset the expansion cause, now that we just completed
1806 // a collection cycle.
1807 clear_expansion_cause();
1808 _foregroundGCIsActive = false;
1809 return;
1810 }
1812 void CMSCollector::check_gc_time_limit() {
1814 // Ignore explicit GC's. Exiting here does not set the flag and
1815 // does not reset the count. Updating of the averages for system
1816 // GC's is still controlled by UseAdaptiveSizePolicyWithSystemGC.
1817 GCCause::Cause gc_cause = GenCollectedHeap::heap()->gc_cause();
1818 if (GCCause::is_user_requested_gc(gc_cause) ||
1819 GCCause::is_serviceability_requested_gc(gc_cause)) {
1820 return;
1821 }
1823 // Calculate the fraction of the CMS generation was freed during
1824 // the last collection.
1825 // Only consider the STW compacting cost for now.
1826 //
1827 // Note that the gc time limit test only works for the collections
1828 // of the young gen + tenured gen and not for collections of the
1829 // permanent gen. That is because the calculation of the space
1830 // freed by the collection is the free space in the young gen +
1831 // tenured gen.
1833 double fraction_free =
1834 ((double)_cmsGen->free())/((double)_cmsGen->max_capacity());
1835 if ((100.0 * size_policy()->compacting_gc_cost()) >
1836 ((double) GCTimeLimit) &&
1837 ((fraction_free * 100) < GCHeapFreeLimit)) {
1838 size_policy()->inc_gc_time_limit_count();
1839 if (UseGCOverheadLimit &&
1840 (size_policy()->gc_time_limit_count() >
1841 AdaptiveSizePolicyGCTimeLimitThreshold)) {
1842 size_policy()->set_gc_time_limit_exceeded(true);
1843 // Avoid consecutive OOM due to the gc time limit by resetting
1844 // the counter.
1845 size_policy()->reset_gc_time_limit_count();
1846 if (PrintGCDetails) {
1847 gclog_or_tty->print_cr(" GC is exceeding overhead limit "
1848 "of %d%%", GCTimeLimit);
1849 }
1850 } else {
1851 if (PrintGCDetails) {
1852 gclog_or_tty->print_cr(" GC would exceed overhead limit "
1853 "of %d%%", GCTimeLimit);
1854 }
1855 }
1856 } else {
1857 size_policy()->reset_gc_time_limit_count();
1858 }
1859 }
1861 // Resize the perm generation and the tenured generation
1862 // after obtaining the free list locks for the
1863 // two generations.
1864 void CMSCollector::compute_new_size() {
1865 assert_locked_or_safepoint(Heap_lock);
1866 FreelistLocker z(this);
1867 _permGen->compute_new_size();
1868 _cmsGen->compute_new_size();
1869 }
1871 // A work method used by foreground collection to determine
1872 // what type of collection (compacting or not, continuing or fresh)
1873 // it should do.
1874 // NOTE: the intent is to make UseCMSCompactAtFullCollection
1875 // and CMSCompactWhenClearAllSoftRefs the default in the future
1876 // and do away with the flags after a suitable period.
1877 void CMSCollector::decide_foreground_collection_type(
1878 bool clear_all_soft_refs, bool* should_compact,
1879 bool* should_start_over) {
1880 // Normally, we'll compact only if the UseCMSCompactAtFullCollection
1881 // flag is set, and we have either requested a System.gc() or
1882 // the number of full gc's since the last concurrent cycle
1883 // has exceeded the threshold set by CMSFullGCsBeforeCompaction,
1884 // or if an incremental collection has failed
1885 GenCollectedHeap* gch = GenCollectedHeap::heap();
1886 assert(gch->collector_policy()->is_two_generation_policy(),
1887 "You may want to check the correctness of the following");
1888 // Inform cms gen if this was due to partial collection failing.
1889 // The CMS gen may use this fact to determine its expansion policy.
1890 if (gch->incremental_collection_will_fail()) {
1891 assert(!_cmsGen->incremental_collection_failed(),
1892 "Should have been noticed, reacted to and cleared");
1893 _cmsGen->set_incremental_collection_failed();
1894 }
1895 *should_compact =
1896 UseCMSCompactAtFullCollection &&
1897 ((_full_gcs_since_conc_gc >= CMSFullGCsBeforeCompaction) ||
1898 GCCause::is_user_requested_gc(gch->gc_cause()) ||
1899 gch->incremental_collection_will_fail());
1900 *should_start_over = false;
1901 if (clear_all_soft_refs && !*should_compact) {
1902 // We are about to do a last ditch collection attempt
1903 // so it would normally make sense to do a compaction
1904 // to reclaim as much space as possible.
1905 if (CMSCompactWhenClearAllSoftRefs) {
1906 // Default: The rationale is that in this case either
1907 // we are past the final marking phase, in which case
1908 // we'd have to start over, or so little has been done
1909 // that there's little point in saving that work. Compaction
1910 // appears to be the sensible choice in either case.
1911 *should_compact = true;
1912 } else {
1913 // We have been asked to clear all soft refs, but not to
1914 // compact. Make sure that we aren't past the final checkpoint
1915 // phase, for that is where we process soft refs. If we are already
1916 // past that phase, we'll need to redo the refs discovery phase and
1917 // if necessary clear soft refs that weren't previously
1918 // cleared. We do so by remembering the phase in which
1919 // we came in, and if we are past the refs processing
1920 // phase, we'll choose to just redo the mark-sweep
1921 // collection from scratch.
1922 if (_collectorState > FinalMarking) {
1923 // We are past the refs processing phase;
1924 // start over and do a fresh synchronous CMS cycle
1925 _collectorState = Resetting; // skip to reset to start new cycle
1926 reset(false /* == !asynch */);
1927 *should_start_over = true;
1928 } // else we can continue a possibly ongoing current cycle
1929 }
1930 }
1931 }
1933 // A work method used by the foreground collector to do
1934 // a mark-sweep-compact.
1935 void CMSCollector::do_compaction_work(bool clear_all_soft_refs) {
1936 GenCollectedHeap* gch = GenCollectedHeap::heap();
1937 TraceTime t("CMS:MSC ", PrintGCDetails && Verbose, true, gclog_or_tty);
1938 if (PrintGC && Verbose && !(GCCause::is_user_requested_gc(gch->gc_cause()))) {
1939 gclog_or_tty->print_cr("Compact ConcurrentMarkSweepGeneration after %d "
1940 "collections passed to foreground collector", _full_gcs_since_conc_gc);
1941 }
1943 // Sample collection interval time and reset for collection pause.
1944 if (UseAdaptiveSizePolicy) {
1945 size_policy()->msc_collection_begin();
1946 }
1948 // Temporarily widen the span of the weak reference processing to
1949 // the entire heap.
1950 MemRegion new_span(GenCollectedHeap::heap()->reserved_region());
1951 ReferenceProcessorSpanMutator x(ref_processor(), new_span);
1953 // Temporarily, clear the "is_alive_non_header" field of the
1954 // reference processor.
1955 ReferenceProcessorIsAliveMutator y(ref_processor(), NULL);
1957 // Temporarily make reference _processing_ single threaded (non-MT).
1958 ReferenceProcessorMTProcMutator z(ref_processor(), false);
1960 // Temporarily make refs discovery atomic
1961 ReferenceProcessorAtomicMutator w(ref_processor(), true);
1963 ref_processor()->set_enqueuing_is_done(false);
1964 ref_processor()->enable_discovery();
1965 ref_processor()->setup_policy(clear_all_soft_refs);
1966 // If an asynchronous collection finishes, the _modUnionTable is
1967 // all clear. If we are assuming the collection from an asynchronous
1968 // collection, clear the _modUnionTable.
1969 assert(_collectorState != Idling || _modUnionTable.isAllClear(),
1970 "_modUnionTable should be clear if the baton was not passed");
1971 _modUnionTable.clear_all();
1973 // We must adjust the allocation statistics being maintained
1974 // in the free list space. We do so by reading and clearing
1975 // the sweep timer and updating the block flux rate estimates below.
1976 assert(_sweep_timer.is_active(), "We should never see the timer inactive");
1977 _sweep_timer.stop();
1978 // Note that we do not use this sample to update the _sweep_estimate.
1979 _cmsGen->cmsSpace()->beginSweepFLCensus((float)(_sweep_timer.seconds()),
1980 _sweep_estimate.padded_average());
1982 GenMarkSweep::invoke_at_safepoint(_cmsGen->level(),
1983 ref_processor(), clear_all_soft_refs);
1984 #ifdef ASSERT
1985 CompactibleFreeListSpace* cms_space = _cmsGen->cmsSpace();
1986 size_t free_size = cms_space->free();
1987 assert(free_size ==
1988 pointer_delta(cms_space->end(), cms_space->compaction_top())
1989 * HeapWordSize,
1990 "All the free space should be compacted into one chunk at top");
1991 assert(cms_space->dictionary()->totalChunkSize(
1992 debug_only(cms_space->freelistLock())) == 0 ||
1993 cms_space->totalSizeInIndexedFreeLists() == 0,
1994 "All the free space should be in a single chunk");
1995 size_t num = cms_space->totalCount();
1996 assert((free_size == 0 && num == 0) ||
1997 (free_size > 0 && (num == 1 || num == 2)),
1998 "There should be at most 2 free chunks after compaction");
1999 #endif // ASSERT
2000 _collectorState = Resetting;
2001 assert(_restart_addr == NULL,
2002 "Should have been NULL'd before baton was passed");
2003 reset(false /* == !asynch */);
2004 _cmsGen->reset_after_compaction();
2005 _concurrent_cycles_since_last_unload = 0;
2007 if (verifying() && !should_unload_classes()) {
2008 perm_gen_verify_bit_map()->clear_all();
2009 }
2011 // Clear any data recorded in the PLAB chunk arrays.
2012 if (_survivor_plab_array != NULL) {
2013 reset_survivor_plab_arrays();
2014 }
2016 // Adjust the per-size allocation stats for the next epoch.
2017 _cmsGen->cmsSpace()->endSweepFLCensus(sweepCount() /* fake */);
2018 // Restart the "sweep timer" for next epoch.
2019 _sweep_timer.reset();
2020 _sweep_timer.start();
2022 // Sample collection pause time and reset for collection interval.
2023 if (UseAdaptiveSizePolicy) {
2024 size_policy()->msc_collection_end(gch->gc_cause());
2025 }
2027 // For a mark-sweep-compact, compute_new_size() will be called
2028 // in the heap's do_collection() method.
2029 }
2031 // A work method used by the foreground collector to do
2032 // a mark-sweep, after taking over from a possibly on-going
2033 // concurrent mark-sweep collection.
2034 void CMSCollector::do_mark_sweep_work(bool clear_all_soft_refs,
2035 CollectorState first_state, bool should_start_over) {
2036 if (PrintGC && Verbose) {
2037 gclog_or_tty->print_cr("Pass concurrent collection to foreground "
2038 "collector with count %d",
2039 _full_gcs_since_conc_gc);
2040 }
2041 switch (_collectorState) {
2042 case Idling:
2043 if (first_state == Idling || should_start_over) {
2044 // The background GC was not active, or should
2045 // restarted from scratch; start the cycle.
2046 _collectorState = InitialMarking;
2047 }
2048 // If first_state was not Idling, then a background GC
2049 // was in progress and has now finished. No need to do it
2050 // again. Leave the state as Idling.
2051 break;
2052 case Precleaning:
2053 // In the foreground case don't do the precleaning since
2054 // it is not done concurrently and there is extra work
2055 // required.
2056 _collectorState = FinalMarking;
2057 }
2058 if (PrintGCDetails &&
2059 (_collectorState > Idling ||
2060 !GCCause::is_user_requested_gc(GenCollectedHeap::heap()->gc_cause()))) {
2061 gclog_or_tty->print(" (concurrent mode failure)");
2062 }
2063 collect_in_foreground(clear_all_soft_refs);
2065 // For a mark-sweep, compute_new_size() will be called
2066 // in the heap's do_collection() method.
2067 }
2070 void CMSCollector::getFreelistLocks() const {
2071 // Get locks for all free lists in all generations that this
2072 // collector is responsible for
2073 _cmsGen->freelistLock()->lock_without_safepoint_check();
2074 _permGen->freelistLock()->lock_without_safepoint_check();
2075 }
2077 void CMSCollector::releaseFreelistLocks() const {
2078 // Release locks for all free lists in all generations that this
2079 // collector is responsible for
2080 _cmsGen->freelistLock()->unlock();
2081 _permGen->freelistLock()->unlock();
2082 }
2084 bool CMSCollector::haveFreelistLocks() const {
2085 // Check locks for all free lists in all generations that this
2086 // collector is responsible for
2087 assert_lock_strong(_cmsGen->freelistLock());
2088 assert_lock_strong(_permGen->freelistLock());
2089 PRODUCT_ONLY(ShouldNotReachHere());
2090 return true;
2091 }
2093 // A utility class that is used by the CMS collector to
2094 // temporarily "release" the foreground collector from its
2095 // usual obligation to wait for the background collector to
2096 // complete an ongoing phase before proceeding.
2097 class ReleaseForegroundGC: public StackObj {
2098 private:
2099 CMSCollector* _c;
2100 public:
2101 ReleaseForegroundGC(CMSCollector* c) : _c(c) {
2102 assert(_c->_foregroundGCShouldWait, "Else should not need to call");
2103 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
2104 // allow a potentially blocked foreground collector to proceed
2105 _c->_foregroundGCShouldWait = false;
2106 if (_c->_foregroundGCIsActive) {
2107 CGC_lock->notify();
2108 }
2109 assert(!ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
2110 "Possible deadlock");
2111 }
2113 ~ReleaseForegroundGC() {
2114 assert(!_c->_foregroundGCShouldWait, "Usage protocol violation?");
2115 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
2116 _c->_foregroundGCShouldWait = true;
2117 }
2118 };
2120 // There are separate collect_in_background and collect_in_foreground because of
2121 // the different locking requirements of the background collector and the
2122 // foreground collector. There was originally an attempt to share
2123 // one "collect" method between the background collector and the foreground
2124 // collector but the if-then-else required made it cleaner to have
2125 // separate methods.
2126 void CMSCollector::collect_in_background(bool clear_all_soft_refs) {
2127 assert(Thread::current()->is_ConcurrentGC_thread(),
2128 "A CMS asynchronous collection is only allowed on a CMS thread.");
2130 GenCollectedHeap* gch = GenCollectedHeap::heap();
2131 {
2132 bool safepoint_check = Mutex::_no_safepoint_check_flag;
2133 MutexLockerEx hl(Heap_lock, safepoint_check);
2134 FreelistLocker fll(this);
2135 MutexLockerEx x(CGC_lock, safepoint_check);
2136 if (_foregroundGCIsActive || !UseAsyncConcMarkSweepGC) {
2137 // The foreground collector is active or we're
2138 // not using asynchronous collections. Skip this
2139 // background collection.
2140 assert(!_foregroundGCShouldWait, "Should be clear");
2141 return;
2142 } else {
2143 assert(_collectorState == Idling, "Should be idling before start.");
2144 _collectorState = InitialMarking;
2145 // Reset the expansion cause, now that we are about to begin
2146 // a new cycle.
2147 clear_expansion_cause();
2148 }
2149 // Decide if we want to enable class unloading as part of the
2150 // ensuing concurrent GC cycle.
2151 update_should_unload_classes();
2152 _full_gc_requested = false; // acks all outstanding full gc requests
2153 // Signal that we are about to start a collection
2154 gch->increment_total_full_collections(); // ... starting a collection cycle
2155 _collection_count_start = gch->total_full_collections();
2156 }
2158 // Used for PrintGC
2159 size_t prev_used;
2160 if (PrintGC && Verbose) {
2161 prev_used = _cmsGen->used(); // XXXPERM
2162 }
2164 // The change of the collection state is normally done at this level;
2165 // the exceptions are phases that are executed while the world is
2166 // stopped. For those phases the change of state is done while the
2167 // world is stopped. For baton passing purposes this allows the
2168 // background collector to finish the phase and change state atomically.
2169 // The foreground collector cannot wait on a phase that is done
2170 // while the world is stopped because the foreground collector already
2171 // has the world stopped and would deadlock.
2172 while (_collectorState != Idling) {
2173 if (TraceCMSState) {
2174 gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " in CMS state %d",
2175 Thread::current(), _collectorState);
2176 }
2177 // The foreground collector
2178 // holds the Heap_lock throughout its collection.
2179 // holds the CMS token (but not the lock)
2180 // except while it is waiting for the background collector to yield.
2181 //
2182 // The foreground collector should be blocked (not for long)
2183 // if the background collector is about to start a phase
2184 // executed with world stopped. If the background
2185 // collector has already started such a phase, the
2186 // foreground collector is blocked waiting for the
2187 // Heap_lock. The stop-world phases (InitialMarking and FinalMarking)
2188 // are executed in the VM thread.
2189 //
2190 // The locking order is
2191 // PendingListLock (PLL) -- if applicable (FinalMarking)
2192 // Heap_lock (both this & PLL locked in VM_CMS_Operation::prologue())
2193 // CMS token (claimed in
2194 // stop_world_and_do() -->
2195 // safepoint_synchronize() -->
2196 // CMSThread::synchronize())
2198 {
2199 // Check if the FG collector wants us to yield.
2200 CMSTokenSync x(true); // is cms thread
2201 if (waitForForegroundGC()) {
2202 // We yielded to a foreground GC, nothing more to be
2203 // done this round.
2204 assert(_foregroundGCShouldWait == false, "We set it to false in "
2205 "waitForForegroundGC()");
2206 if (TraceCMSState) {
2207 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT
2208 " exiting collection CMS state %d",
2209 Thread::current(), _collectorState);
2210 }
2211 return;
2212 } else {
2213 // The background collector can run but check to see if the
2214 // foreground collector has done a collection while the
2215 // background collector was waiting to get the CGC_lock
2216 // above. If yes, break so that _foregroundGCShouldWait
2217 // is cleared before returning.
2218 if (_collectorState == Idling) {
2219 break;
2220 }
2221 }
2222 }
2224 assert(_foregroundGCShouldWait, "Foreground collector, if active, "
2225 "should be waiting");
2227 switch (_collectorState) {
2228 case InitialMarking:
2229 {
2230 ReleaseForegroundGC x(this);
2231 stats().record_cms_begin();
2233 VM_CMS_Initial_Mark initial_mark_op(this);
2234 VMThread::execute(&initial_mark_op);
2235 }
2236 // The collector state may be any legal state at this point
2237 // since the background collector may have yielded to the
2238 // foreground collector.
2239 break;
2240 case Marking:
2241 // initial marking in checkpointRootsInitialWork has been completed
2242 if (markFromRoots(true)) { // we were successful
2243 assert(_collectorState == Precleaning, "Collector state should "
2244 "have changed");
2245 } else {
2246 assert(_foregroundGCIsActive, "Internal state inconsistency");
2247 }
2248 break;
2249 case Precleaning:
2250 if (UseAdaptiveSizePolicy) {
2251 size_policy()->concurrent_precleaning_begin();
2252 }
2253 // marking from roots in markFromRoots has been completed
2254 preclean();
2255 if (UseAdaptiveSizePolicy) {
2256 size_policy()->concurrent_precleaning_end();
2257 }
2258 assert(_collectorState == AbortablePreclean ||
2259 _collectorState == FinalMarking,
2260 "Collector state should have changed");
2261 break;
2262 case AbortablePreclean:
2263 if (UseAdaptiveSizePolicy) {
2264 size_policy()->concurrent_phases_resume();
2265 }
2266 abortable_preclean();
2267 if (UseAdaptiveSizePolicy) {
2268 size_policy()->concurrent_precleaning_end();
2269 }
2270 assert(_collectorState == FinalMarking, "Collector state should "
2271 "have changed");
2272 break;
2273 case FinalMarking:
2274 {
2275 ReleaseForegroundGC x(this);
2277 VM_CMS_Final_Remark final_remark_op(this);
2278 VMThread::execute(&final_remark_op);
2279 }
2280 assert(_foregroundGCShouldWait, "block post-condition");
2281 break;
2282 case Sweeping:
2283 if (UseAdaptiveSizePolicy) {
2284 size_policy()->concurrent_sweeping_begin();
2285 }
2286 // final marking in checkpointRootsFinal has been completed
2287 sweep(true);
2288 assert(_collectorState == Resizing, "Collector state change "
2289 "to Resizing must be done under the free_list_lock");
2290 _full_gcs_since_conc_gc = 0;
2292 // Stop the timers for adaptive size policy for the concurrent phases
2293 if (UseAdaptiveSizePolicy) {
2294 size_policy()->concurrent_sweeping_end();
2295 size_policy()->concurrent_phases_end(gch->gc_cause(),
2296 gch->prev_gen(_cmsGen)->capacity(),
2297 _cmsGen->free());
2298 }
2300 case Resizing: {
2301 // Sweeping has been completed...
2302 // At this point the background collection has completed.
2303 // Don't move the call to compute_new_size() down
2304 // into code that might be executed if the background
2305 // collection was preempted.
2306 {
2307 ReleaseForegroundGC x(this); // unblock FG collection
2308 MutexLockerEx y(Heap_lock, Mutex::_no_safepoint_check_flag);
2309 CMSTokenSync z(true); // not strictly needed.
2310 if (_collectorState == Resizing) {
2311 compute_new_size();
2312 _collectorState = Resetting;
2313 } else {
2314 assert(_collectorState == Idling, "The state should only change"
2315 " because the foreground collector has finished the collection");
2316 }
2317 }
2318 break;
2319 }
2320 case Resetting:
2321 // CMS heap resizing has been completed
2322 reset(true);
2323 assert(_collectorState == Idling, "Collector state should "
2324 "have changed");
2325 stats().record_cms_end();
2326 // Don't move the concurrent_phases_end() and compute_new_size()
2327 // calls to here because a preempted background collection
2328 // has it's state set to "Resetting".
2329 break;
2330 case Idling:
2331 default:
2332 ShouldNotReachHere();
2333 break;
2334 }
2335 if (TraceCMSState) {
2336 gclog_or_tty->print_cr(" Thread " INTPTR_FORMAT " done - next CMS state %d",
2337 Thread::current(), _collectorState);
2338 }
2339 assert(_foregroundGCShouldWait, "block post-condition");
2340 }
2342 // Should this be in gc_epilogue?
2343 collector_policy()->counters()->update_counters();
2345 {
2346 // Clear _foregroundGCShouldWait and, in the event that the
2347 // foreground collector is waiting, notify it, before
2348 // returning.
2349 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
2350 _foregroundGCShouldWait = false;
2351 if (_foregroundGCIsActive) {
2352 CGC_lock->notify();
2353 }
2354 assert(!ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
2355 "Possible deadlock");
2356 }
2357 if (TraceCMSState) {
2358 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT
2359 " exiting collection CMS state %d",
2360 Thread::current(), _collectorState);
2361 }
2362 if (PrintGC && Verbose) {
2363 _cmsGen->print_heap_change(prev_used);
2364 }
2365 }
2367 void CMSCollector::collect_in_foreground(bool clear_all_soft_refs) {
2368 assert(_foregroundGCIsActive && !_foregroundGCShouldWait,
2369 "Foreground collector should be waiting, not executing");
2370 assert(Thread::current()->is_VM_thread(), "A foreground collection"
2371 "may only be done by the VM Thread with the world stopped");
2372 assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
2373 "VM thread should have CMS token");
2375 NOT_PRODUCT(TraceTime t("CMS:MS (foreground) ", PrintGCDetails && Verbose,
2376 true, gclog_or_tty);)
2377 if (UseAdaptiveSizePolicy) {
2378 size_policy()->ms_collection_begin();
2379 }
2380 COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact);
2382 HandleMark hm; // Discard invalid handles created during verification
2384 if (VerifyBeforeGC &&
2385 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
2386 Universe::verify(true);
2387 }
2389 // Snapshot the soft reference policy to be used in this collection cycle.
2390 ref_processor()->setup_policy(clear_all_soft_refs);
2392 bool init_mark_was_synchronous = false; // until proven otherwise
2393 while (_collectorState != Idling) {
2394 if (TraceCMSState) {
2395 gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " in CMS state %d",
2396 Thread::current(), _collectorState);
2397 }
2398 switch (_collectorState) {
2399 case InitialMarking:
2400 init_mark_was_synchronous = true; // fact to be exploited in re-mark
2401 checkpointRootsInitial(false);
2402 assert(_collectorState == Marking, "Collector state should have changed"
2403 " within checkpointRootsInitial()");
2404 break;
2405 case Marking:
2406 // initial marking in checkpointRootsInitialWork has been completed
2407 if (VerifyDuringGC &&
2408 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
2409 gclog_or_tty->print("Verify before initial mark: ");
2410 Universe::verify(true);
2411 }
2412 {
2413 bool res = markFromRoots(false);
2414 assert(res && _collectorState == FinalMarking, "Collector state should "
2415 "have changed");
2416 break;
2417 }
2418 case FinalMarking:
2419 if (VerifyDuringGC &&
2420 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
2421 gclog_or_tty->print("Verify before re-mark: ");
2422 Universe::verify(true);
2423 }
2424 checkpointRootsFinal(false, clear_all_soft_refs,
2425 init_mark_was_synchronous);
2426 assert(_collectorState == Sweeping, "Collector state should not "
2427 "have changed within checkpointRootsFinal()");
2428 break;
2429 case Sweeping:
2430 // final marking in checkpointRootsFinal has been completed
2431 if (VerifyDuringGC &&
2432 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
2433 gclog_or_tty->print("Verify before sweep: ");
2434 Universe::verify(true);
2435 }
2436 sweep(false);
2437 assert(_collectorState == Resizing, "Incorrect state");
2438 break;
2439 case Resizing: {
2440 // Sweeping has been completed; the actual resize in this case
2441 // is done separately; nothing to be done in this state.
2442 _collectorState = Resetting;
2443 break;
2444 }
2445 case Resetting:
2446 // The heap has been resized.
2447 if (VerifyDuringGC &&
2448 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
2449 gclog_or_tty->print("Verify before reset: ");
2450 Universe::verify(true);
2451 }
2452 reset(false);
2453 assert(_collectorState == Idling, "Collector state should "
2454 "have changed");
2455 break;
2456 case Precleaning:
2457 case AbortablePreclean:
2458 // Elide the preclean phase
2459 _collectorState = FinalMarking;
2460 break;
2461 default:
2462 ShouldNotReachHere();
2463 }
2464 if (TraceCMSState) {
2465 gclog_or_tty->print_cr(" Thread " INTPTR_FORMAT " done - next CMS state %d",
2466 Thread::current(), _collectorState);
2467 }
2468 }
2470 if (UseAdaptiveSizePolicy) {
2471 GenCollectedHeap* gch = GenCollectedHeap::heap();
2472 size_policy()->ms_collection_end(gch->gc_cause());
2473 }
2475 if (VerifyAfterGC &&
2476 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
2477 Universe::verify(true);
2478 }
2479 if (TraceCMSState) {
2480 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT
2481 " exiting collection CMS state %d",
2482 Thread::current(), _collectorState);
2483 }
2484 }
2486 bool CMSCollector::waitForForegroundGC() {
2487 bool res = false;
2488 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
2489 "CMS thread should have CMS token");
2490 // Block the foreground collector until the
2491 // background collectors decides whether to
2492 // yield.
2493 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
2494 _foregroundGCShouldWait = true;
2495 if (_foregroundGCIsActive) {
2496 // The background collector yields to the
2497 // foreground collector and returns a value
2498 // indicating that it has yielded. The foreground
2499 // collector can proceed.
2500 res = true;
2501 _foregroundGCShouldWait = false;
2502 ConcurrentMarkSweepThread::clear_CMS_flag(
2503 ConcurrentMarkSweepThread::CMS_cms_has_token);
2504 ConcurrentMarkSweepThread::set_CMS_flag(
2505 ConcurrentMarkSweepThread::CMS_cms_wants_token);
2506 // Get a possibly blocked foreground thread going
2507 CGC_lock->notify();
2508 if (TraceCMSState) {
2509 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " waiting at CMS state %d",
2510 Thread::current(), _collectorState);
2511 }
2512 while (_foregroundGCIsActive) {
2513 CGC_lock->wait(Mutex::_no_safepoint_check_flag);
2514 }
2515 ConcurrentMarkSweepThread::set_CMS_flag(
2516 ConcurrentMarkSweepThread::CMS_cms_has_token);
2517 ConcurrentMarkSweepThread::clear_CMS_flag(
2518 ConcurrentMarkSweepThread::CMS_cms_wants_token);
2519 }
2520 if (TraceCMSState) {
2521 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " continuing at CMS state %d",
2522 Thread::current(), _collectorState);
2523 }
2524 return res;
2525 }
2527 // Because of the need to lock the free lists and other structures in
2528 // the collector, common to all the generations that the collector is
2529 // collecting, we need the gc_prologues of individual CMS generations
2530 // delegate to their collector. It may have been simpler had the
2531 // current infrastructure allowed one to call a prologue on a
2532 // collector. In the absence of that we have the generation's
2533 // prologue delegate to the collector, which delegates back
2534 // some "local" work to a worker method in the individual generations
2535 // that it's responsible for collecting, while itself doing any
2536 // work common to all generations it's responsible for. A similar
2537 // comment applies to the gc_epilogue()'s.
2538 // The role of the varaible _between_prologue_and_epilogue is to
2539 // enforce the invocation protocol.
2540 void CMSCollector::gc_prologue(bool full) {
2541 // Call gc_prologue_work() for each CMSGen and PermGen that
2542 // we are responsible for.
2544 // The following locking discipline assumes that we are only called
2545 // when the world is stopped.
2546 assert(SafepointSynchronize::is_at_safepoint(), "world is stopped assumption");
2548 // The CMSCollector prologue must call the gc_prologues for the
2549 // "generations" (including PermGen if any) that it's responsible
2550 // for.
2552 assert( Thread::current()->is_VM_thread()
2553 || ( CMSScavengeBeforeRemark
2554 && Thread::current()->is_ConcurrentGC_thread()),
2555 "Incorrect thread type for prologue execution");
2557 if (_between_prologue_and_epilogue) {
2558 // We have already been invoked; this is a gc_prologue delegation
2559 // from yet another CMS generation that we are responsible for, just
2560 // ignore it since all relevant work has already been done.
2561 return;
2562 }
2564 // set a bit saying prologue has been called; cleared in epilogue
2565 _between_prologue_and_epilogue = true;
2566 // Claim locks for common data structures, then call gc_prologue_work()
2567 // for each CMSGen and PermGen that we are responsible for.
2569 getFreelistLocks(); // gets free list locks on constituent spaces
2570 bitMapLock()->lock_without_safepoint_check();
2572 // Should call gc_prologue_work() for all cms gens we are responsible for
2573 bool registerClosure = _collectorState >= Marking
2574 && _collectorState < Sweeping;
2575 ModUnionClosure* muc = ParallelGCThreads > 0 ? &_modUnionClosurePar
2576 : &_modUnionClosure;
2577 _cmsGen->gc_prologue_work(full, registerClosure, muc);
2578 _permGen->gc_prologue_work(full, registerClosure, muc);
2580 if (!full) {
2581 stats().record_gc0_begin();
2582 }
2583 }
2585 void ConcurrentMarkSweepGeneration::gc_prologue(bool full) {
2586 // Delegate to CMScollector which knows how to coordinate between
2587 // this and any other CMS generations that it is responsible for
2588 // collecting.
2589 collector()->gc_prologue(full);
2590 }
2592 // This is a "private" interface for use by this generation's CMSCollector.
2593 // Not to be called directly by any other entity (for instance,
2594 // GenCollectedHeap, which calls the "public" gc_prologue method above).
2595 void ConcurrentMarkSweepGeneration::gc_prologue_work(bool full,
2596 bool registerClosure, ModUnionClosure* modUnionClosure) {
2597 assert(!incremental_collection_failed(), "Shouldn't be set yet");
2598 assert(cmsSpace()->preconsumptionDirtyCardClosure() == NULL,
2599 "Should be NULL");
2600 if (registerClosure) {
2601 cmsSpace()->setPreconsumptionDirtyCardClosure(modUnionClosure);
2602 }
2603 cmsSpace()->gc_prologue();
2604 // Clear stat counters
2605 NOT_PRODUCT(
2606 assert(_numObjectsPromoted == 0, "check");
2607 assert(_numWordsPromoted == 0, "check");
2608 if (Verbose && PrintGC) {
2609 gclog_or_tty->print("Allocated "SIZE_FORMAT" objects, "
2610 SIZE_FORMAT" bytes concurrently",
2611 _numObjectsAllocated, _numWordsAllocated*sizeof(HeapWord));
2612 }
2613 _numObjectsAllocated = 0;
2614 _numWordsAllocated = 0;
2615 )
2616 }
2618 void CMSCollector::gc_epilogue(bool full) {
2619 // The following locking discipline assumes that we are only called
2620 // when the world is stopped.
2621 assert(SafepointSynchronize::is_at_safepoint(),
2622 "world is stopped assumption");
2624 // Currently the CMS epilogue (see CompactibleFreeListSpace) merely checks
2625 // if linear allocation blocks need to be appropriately marked to allow the
2626 // the blocks to be parsable. We also check here whether we need to nudge the
2627 // CMS collector thread to start a new cycle (if it's not already active).
2628 assert( Thread::current()->is_VM_thread()
2629 || ( CMSScavengeBeforeRemark
2630 && Thread::current()->is_ConcurrentGC_thread()),
2631 "Incorrect thread type for epilogue execution");
2633 if (!_between_prologue_and_epilogue) {
2634 // We have already been invoked; this is a gc_epilogue delegation
2635 // from yet another CMS generation that we are responsible for, just
2636 // ignore it since all relevant work has already been done.
2637 return;
2638 }
2639 assert(haveFreelistLocks(), "must have freelist locks");
2640 assert_lock_strong(bitMapLock());
2642 _cmsGen->gc_epilogue_work(full);
2643 _permGen->gc_epilogue_work(full);
2645 if (_collectorState == AbortablePreclean || _collectorState == Precleaning) {
2646 // in case sampling was not already enabled, enable it
2647 _start_sampling = true;
2648 }
2649 // reset _eden_chunk_array so sampling starts afresh
2650 _eden_chunk_index = 0;
2652 size_t cms_used = _cmsGen->cmsSpace()->used();
2653 size_t perm_used = _permGen->cmsSpace()->used();
2655 // update performance counters - this uses a special version of
2656 // update_counters() that allows the utilization to be passed as a
2657 // parameter, avoiding multiple calls to used().
2658 //
2659 _cmsGen->update_counters(cms_used);
2660 _permGen->update_counters(perm_used);
2662 if (CMSIncrementalMode) {
2663 icms_update_allocation_limits();
2664 }
2666 bitMapLock()->unlock();
2667 releaseFreelistLocks();
2669 _between_prologue_and_epilogue = false; // ready for next cycle
2670 }
2672 void ConcurrentMarkSweepGeneration::gc_epilogue(bool full) {
2673 collector()->gc_epilogue(full);
2675 // Also reset promotion tracking in par gc thread states.
2676 if (ParallelGCThreads > 0) {
2677 for (uint i = 0; i < ParallelGCThreads; i++) {
2678 _par_gc_thread_states[i]->promo.stopTrackingPromotions();
2679 }
2680 }
2681 }
2683 void ConcurrentMarkSweepGeneration::gc_epilogue_work(bool full) {
2684 assert(!incremental_collection_failed(), "Should have been cleared");
2685 cmsSpace()->setPreconsumptionDirtyCardClosure(NULL);
2686 cmsSpace()->gc_epilogue();
2687 // Print stat counters
2688 NOT_PRODUCT(
2689 assert(_numObjectsAllocated == 0, "check");
2690 assert(_numWordsAllocated == 0, "check");
2691 if (Verbose && PrintGC) {
2692 gclog_or_tty->print("Promoted "SIZE_FORMAT" objects, "
2693 SIZE_FORMAT" bytes",
2694 _numObjectsPromoted, _numWordsPromoted*sizeof(HeapWord));
2695 }
2696 _numObjectsPromoted = 0;
2697 _numWordsPromoted = 0;
2698 )
2700 if (PrintGC && Verbose) {
2701 // Call down the chain in contiguous_available needs the freelistLock
2702 // so print this out before releasing the freeListLock.
2703 gclog_or_tty->print(" Contiguous available "SIZE_FORMAT" bytes ",
2704 contiguous_available());
2705 }
2706 }
2708 #ifndef PRODUCT
2709 bool CMSCollector::have_cms_token() {
2710 Thread* thr = Thread::current();
2711 if (thr->is_VM_thread()) {
2712 return ConcurrentMarkSweepThread::vm_thread_has_cms_token();
2713 } else if (thr->is_ConcurrentGC_thread()) {
2714 return ConcurrentMarkSweepThread::cms_thread_has_cms_token();
2715 } else if (thr->is_GC_task_thread()) {
2716 return ConcurrentMarkSweepThread::vm_thread_has_cms_token() &&
2717 ParGCRareEvent_lock->owned_by_self();
2718 }
2719 return false;
2720 }
2721 #endif
2723 // Check reachability of the given heap address in CMS generation,
2724 // treating all other generations as roots.
2725 bool CMSCollector::is_cms_reachable(HeapWord* addr) {
2726 // We could "guarantee" below, rather than assert, but i'll
2727 // leave these as "asserts" so that an adventurous debugger
2728 // could try this in the product build provided some subset of
2729 // the conditions were met, provided they were intersted in the
2730 // results and knew that the computation below wouldn't interfere
2731 // with other concurrent computations mutating the structures
2732 // being read or written.
2733 assert(SafepointSynchronize::is_at_safepoint(),
2734 "Else mutations in object graph will make answer suspect");
2735 assert(have_cms_token(), "Should hold cms token");
2736 assert(haveFreelistLocks(), "must hold free list locks");
2737 assert_lock_strong(bitMapLock());
2739 // Clear the marking bit map array before starting, but, just
2740 // for kicks, first report if the given address is already marked
2741 gclog_or_tty->print_cr("Start: Address 0x%x is%s marked", addr,
2742 _markBitMap.isMarked(addr) ? "" : " not");
2744 if (verify_after_remark()) {
2745 MutexLockerEx x(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag);
2746 bool result = verification_mark_bm()->isMarked(addr);
2747 gclog_or_tty->print_cr("TransitiveMark: Address 0x%x %s marked", addr,
2748 result ? "IS" : "is NOT");
2749 return result;
2750 } else {
2751 gclog_or_tty->print_cr("Could not compute result");
2752 return false;
2753 }
2754 }
2756 ////////////////////////////////////////////////////////
2757 // CMS Verification Support
2758 ////////////////////////////////////////////////////////
2759 // Following the remark phase, the following invariant
2760 // should hold -- each object in the CMS heap which is
2761 // marked in markBitMap() should be marked in the verification_mark_bm().
2763 class VerifyMarkedClosure: public BitMapClosure {
2764 CMSBitMap* _marks;
2765 bool _failed;
2767 public:
2768 VerifyMarkedClosure(CMSBitMap* bm): _marks(bm), _failed(false) {}
2770 bool do_bit(size_t offset) {
2771 HeapWord* addr = _marks->offsetToHeapWord(offset);
2772 if (!_marks->isMarked(addr)) {
2773 oop(addr)->print();
2774 gclog_or_tty->print_cr(" ("INTPTR_FORMAT" should have been marked)", addr);
2775 _failed = true;
2776 }
2777 return true;
2778 }
2780 bool failed() { return _failed; }
2781 };
2783 bool CMSCollector::verify_after_remark() {
2784 gclog_or_tty->print(" [Verifying CMS Marking... ");
2785 MutexLockerEx ml(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag);
2786 static bool init = false;
2788 assert(SafepointSynchronize::is_at_safepoint(),
2789 "Else mutations in object graph will make answer suspect");
2790 assert(have_cms_token(),
2791 "Else there may be mutual interference in use of "
2792 " verification data structures");
2793 assert(_collectorState > Marking && _collectorState <= Sweeping,
2794 "Else marking info checked here may be obsolete");
2795 assert(haveFreelistLocks(), "must hold free list locks");
2796 assert_lock_strong(bitMapLock());
2799 // Allocate marking bit map if not already allocated
2800 if (!init) { // first time
2801 if (!verification_mark_bm()->allocate(_span)) {
2802 return false;
2803 }
2804 init = true;
2805 }
2807 assert(verification_mark_stack()->isEmpty(), "Should be empty");
2809 // Turn off refs discovery -- so we will be tracing through refs.
2810 // This is as intended, because by this time
2811 // GC must already have cleared any refs that need to be cleared,
2812 // and traced those that need to be marked; moreover,
2813 // the marking done here is not going to intefere in any
2814 // way with the marking information used by GC.
2815 NoRefDiscovery no_discovery(ref_processor());
2817 COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
2819 // Clear any marks from a previous round
2820 verification_mark_bm()->clear_all();
2821 assert(verification_mark_stack()->isEmpty(), "markStack should be empty");
2822 assert(overflow_list_is_empty(), "overflow list should be empty");
2824 GenCollectedHeap* gch = GenCollectedHeap::heap();
2825 gch->ensure_parsability(false); // fill TLABs, but no need to retire them
2826 // Update the saved marks which may affect the root scans.
2827 gch->save_marks();
2829 if (CMSRemarkVerifyVariant == 1) {
2830 // In this first variant of verification, we complete
2831 // all marking, then check if the new marks-verctor is
2832 // a subset of the CMS marks-vector.
2833 verify_after_remark_work_1();
2834 } else if (CMSRemarkVerifyVariant == 2) {
2835 // In this second variant of verification, we flag an error
2836 // (i.e. an object reachable in the new marks-vector not reachable
2837 // in the CMS marks-vector) immediately, also indicating the
2838 // identify of an object (A) that references the unmarked object (B) --
2839 // presumably, a mutation to A failed to be picked up by preclean/remark?
2840 verify_after_remark_work_2();
2841 } else {
2842 warning("Unrecognized value %d for CMSRemarkVerifyVariant",
2843 CMSRemarkVerifyVariant);
2844 }
2845 gclog_or_tty->print(" done] ");
2846 return true;
2847 }
2849 void CMSCollector::verify_after_remark_work_1() {
2850 ResourceMark rm;
2851 HandleMark hm;
2852 GenCollectedHeap* gch = GenCollectedHeap::heap();
2854 // Mark from roots one level into CMS
2855 MarkRefsIntoClosure notOlder(_span, verification_mark_bm(), true /* nmethods */);
2856 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
2858 gch->gen_process_strong_roots(_cmsGen->level(),
2859 true, // younger gens are roots
2860 true, // collecting perm gen
2861 SharedHeap::ScanningOption(roots_scanning_options()),
2862 NULL, ¬Older);
2864 // Now mark from the roots
2865 assert(_revisitStack.isEmpty(), "Should be empty");
2866 MarkFromRootsClosure markFromRootsClosure(this, _span,
2867 verification_mark_bm(), verification_mark_stack(), &_revisitStack,
2868 false /* don't yield */, true /* verifying */);
2869 assert(_restart_addr == NULL, "Expected pre-condition");
2870 verification_mark_bm()->iterate(&markFromRootsClosure);
2871 while (_restart_addr != NULL) {
2872 // Deal with stack overflow: by restarting at the indicated
2873 // address.
2874 HeapWord* ra = _restart_addr;
2875 markFromRootsClosure.reset(ra);
2876 _restart_addr = NULL;
2877 verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end());
2878 }
2879 assert(verification_mark_stack()->isEmpty(), "Should have been drained");
2880 verify_work_stacks_empty();
2881 // Should reset the revisit stack above, since no class tree
2882 // surgery is forthcoming.
2883 _revisitStack.reset(); // throwing away all contents
2885 // Marking completed -- now verify that each bit marked in
2886 // verification_mark_bm() is also marked in markBitMap(); flag all
2887 // errors by printing corresponding objects.
2888 VerifyMarkedClosure vcl(markBitMap());
2889 verification_mark_bm()->iterate(&vcl);
2890 if (vcl.failed()) {
2891 gclog_or_tty->print("Verification failed");
2892 Universe::heap()->print();
2893 fatal(" ... aborting");
2894 }
2895 }
2897 void CMSCollector::verify_after_remark_work_2() {
2898 ResourceMark rm;
2899 HandleMark hm;
2900 GenCollectedHeap* gch = GenCollectedHeap::heap();
2902 // Mark from roots one level into CMS
2903 MarkRefsIntoVerifyClosure notOlder(_span, verification_mark_bm(),
2904 markBitMap(), true /* nmethods */);
2905 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
2906 gch->gen_process_strong_roots(_cmsGen->level(),
2907 true, // younger gens are roots
2908 true, // collecting perm gen
2909 SharedHeap::ScanningOption(roots_scanning_options()),
2910 NULL, ¬Older);
2912 // Now mark from the roots
2913 assert(_revisitStack.isEmpty(), "Should be empty");
2914 MarkFromRootsVerifyClosure markFromRootsClosure(this, _span,
2915 verification_mark_bm(), markBitMap(), verification_mark_stack());
2916 assert(_restart_addr == NULL, "Expected pre-condition");
2917 verification_mark_bm()->iterate(&markFromRootsClosure);
2918 while (_restart_addr != NULL) {
2919 // Deal with stack overflow: by restarting at the indicated
2920 // address.
2921 HeapWord* ra = _restart_addr;
2922 markFromRootsClosure.reset(ra);
2923 _restart_addr = NULL;
2924 verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end());
2925 }
2926 assert(verification_mark_stack()->isEmpty(), "Should have been drained");
2927 verify_work_stacks_empty();
2928 // Should reset the revisit stack above, since no class tree
2929 // surgery is forthcoming.
2930 _revisitStack.reset(); // throwing away all contents
2932 // Marking completed -- now verify that each bit marked in
2933 // verification_mark_bm() is also marked in markBitMap(); flag all
2934 // errors by printing corresponding objects.
2935 VerifyMarkedClosure vcl(markBitMap());
2936 verification_mark_bm()->iterate(&vcl);
2937 assert(!vcl.failed(), "Else verification above should not have succeeded");
2938 }
2940 void ConcurrentMarkSweepGeneration::save_marks() {
2941 // delegate to CMS space
2942 cmsSpace()->save_marks();
2943 for (uint i = 0; i < ParallelGCThreads; i++) {
2944 _par_gc_thread_states[i]->promo.startTrackingPromotions();
2945 }
2946 }
2948 bool ConcurrentMarkSweepGeneration::no_allocs_since_save_marks() {
2949 return cmsSpace()->no_allocs_since_save_marks();
2950 }
2952 #define CMS_SINCE_SAVE_MARKS_DEFN(OopClosureType, nv_suffix) \
2953 \
2954 void ConcurrentMarkSweepGeneration:: \
2955 oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl) { \
2956 cl->set_generation(this); \
2957 cmsSpace()->oop_since_save_marks_iterate##nv_suffix(cl); \
2958 cl->reset_generation(); \
2959 save_marks(); \
2960 }
2962 ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DEFN)
2964 void
2965 ConcurrentMarkSweepGeneration::object_iterate_since_last_GC(ObjectClosure* blk)
2966 {
2967 // Not currently implemented; need to do the following. -- ysr.
2968 // dld -- I think that is used for some sort of allocation profiler. So it
2969 // really means the objects allocated by the mutator since the last
2970 // GC. We could potentially implement this cheaply by recording only
2971 // the direct allocations in a side data structure.
2972 //
2973 // I think we probably ought not to be required to support these
2974 // iterations at any arbitrary point; I think there ought to be some
2975 // call to enable/disable allocation profiling in a generation/space,
2976 // and the iterator ought to return the objects allocated in the
2977 // gen/space since the enable call, or the last iterator call (which
2978 // will probably be at a GC.) That way, for gens like CM&S that would
2979 // require some extra data structure to support this, we only pay the
2980 // cost when it's in use...
2981 cmsSpace()->object_iterate_since_last_GC(blk);
2982 }
2984 void
2985 ConcurrentMarkSweepGeneration::younger_refs_iterate(OopsInGenClosure* cl) {
2986 cl->set_generation(this);
2987 younger_refs_in_space_iterate(_cmsSpace, cl);
2988 cl->reset_generation();
2989 }
2991 void
2992 ConcurrentMarkSweepGeneration::oop_iterate(MemRegion mr, OopClosure* cl) {
2993 if (freelistLock()->owned_by_self()) {
2994 Generation::oop_iterate(mr, cl);
2995 } else {
2996 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
2997 Generation::oop_iterate(mr, cl);
2998 }
2999 }
3001 void
3002 ConcurrentMarkSweepGeneration::oop_iterate(OopClosure* cl) {
3003 if (freelistLock()->owned_by_self()) {
3004 Generation::oop_iterate(cl);
3005 } else {
3006 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
3007 Generation::oop_iterate(cl);
3008 }
3009 }
3011 void
3012 ConcurrentMarkSweepGeneration::object_iterate(ObjectClosure* cl) {
3013 if (freelistLock()->owned_by_self()) {
3014 Generation::object_iterate(cl);
3015 } else {
3016 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
3017 Generation::object_iterate(cl);
3018 }
3019 }
3021 void
3022 ConcurrentMarkSweepGeneration::safe_object_iterate(ObjectClosure* cl) {
3023 if (freelistLock()->owned_by_self()) {
3024 Generation::safe_object_iterate(cl);
3025 } else {
3026 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
3027 Generation::safe_object_iterate(cl);
3028 }
3029 }
3031 void
3032 ConcurrentMarkSweepGeneration::pre_adjust_pointers() {
3033 }
3035 void
3036 ConcurrentMarkSweepGeneration::post_compact() {
3037 }
3039 void
3040 ConcurrentMarkSweepGeneration::prepare_for_verify() {
3041 // Fix the linear allocation blocks to look like free blocks.
3043 // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those
3044 // are not called when the heap is verified during universe initialization and
3045 // at vm shutdown.
3046 if (freelistLock()->owned_by_self()) {
3047 cmsSpace()->prepare_for_verify();
3048 } else {
3049 MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag);
3050 cmsSpace()->prepare_for_verify();
3051 }
3052 }
3054 void
3055 ConcurrentMarkSweepGeneration::verify(bool allow_dirty /* ignored */) {
3056 // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those
3057 // are not called when the heap is verified during universe initialization and
3058 // at vm shutdown.
3059 if (freelistLock()->owned_by_self()) {
3060 cmsSpace()->verify(false /* ignored */);
3061 } else {
3062 MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag);
3063 cmsSpace()->verify(false /* ignored */);
3064 }
3065 }
3067 void CMSCollector::verify(bool allow_dirty /* ignored */) {
3068 _cmsGen->verify(allow_dirty);
3069 _permGen->verify(allow_dirty);
3070 }
3072 #ifndef PRODUCT
3073 bool CMSCollector::overflow_list_is_empty() const {
3074 assert(_num_par_pushes >= 0, "Inconsistency");
3075 if (_overflow_list == NULL) {
3076 assert(_num_par_pushes == 0, "Inconsistency");
3077 }
3078 return _overflow_list == NULL;
3079 }
3081 // The methods verify_work_stacks_empty() and verify_overflow_empty()
3082 // merely consolidate assertion checks that appear to occur together frequently.
3083 void CMSCollector::verify_work_stacks_empty() const {
3084 assert(_markStack.isEmpty(), "Marking stack should be empty");
3085 assert(overflow_list_is_empty(), "Overflow list should be empty");
3086 }
3088 void CMSCollector::verify_overflow_empty() const {
3089 assert(overflow_list_is_empty(), "Overflow list should be empty");
3090 assert(no_preserved_marks(), "No preserved marks");
3091 }
3092 #endif // PRODUCT
3094 // Decide if we want to enable class unloading as part of the
3095 // ensuing concurrent GC cycle. We will collect the perm gen and
3096 // unload classes if it's the case that:
3097 // (1) an explicit gc request has been made and the flag
3098 // ExplicitGCInvokesConcurrentAndUnloadsClasses is set, OR
3099 // (2) (a) class unloading is enabled at the command line, and
3100 // (b) (i) perm gen threshold has been crossed, or
3101 // (ii) old gen is getting really full, or
3102 // (iii) the previous N CMS collections did not collect the
3103 // perm gen
3104 // NOTE: Provided there is no change in the state of the heap between
3105 // calls to this method, it should have idempotent results. Moreover,
3106 // its results should be monotonically increasing (i.e. going from 0 to 1,
3107 // but not 1 to 0) between successive calls between which the heap was
3108 // not collected. For the implementation below, it must thus rely on
3109 // the property that concurrent_cycles_since_last_unload()
3110 // will not decrease unless a collection cycle happened and that
3111 // _permGen->should_concurrent_collect() and _cmsGen->is_too_full() are
3112 // themselves also monotonic in that sense. See check_monotonicity()
3113 // below.
3114 bool CMSCollector::update_should_unload_classes() {
3115 _should_unload_classes = false;
3116 // Condition 1 above
3117 if (_full_gc_requested && ExplicitGCInvokesConcurrentAndUnloadsClasses) {
3118 _should_unload_classes = true;
3119 } else if (CMSClassUnloadingEnabled) { // Condition 2.a above
3120 // Disjuncts 2.b.(i,ii,iii) above
3121 _should_unload_classes = (concurrent_cycles_since_last_unload() >=
3122 CMSClassUnloadingMaxInterval)
3123 || _permGen->should_concurrent_collect()
3124 || _cmsGen->is_too_full();
3125 }
3126 return _should_unload_classes;
3127 }
3129 bool ConcurrentMarkSweepGeneration::is_too_full() const {
3130 bool res = should_concurrent_collect();
3131 res = res && (occupancy() > (double)CMSIsTooFullPercentage/100.0);
3132 return res;
3133 }
3135 void CMSCollector::setup_cms_unloading_and_verification_state() {
3136 const bool should_verify = VerifyBeforeGC || VerifyAfterGC || VerifyDuringGC
3137 || VerifyBeforeExit;
3138 const int rso = SharedHeap::SO_Symbols | SharedHeap::SO_Strings
3139 | SharedHeap::SO_CodeCache;
3141 if (should_unload_classes()) { // Should unload classes this cycle
3142 remove_root_scanning_option(rso); // Shrink the root set appropriately
3143 set_verifying(should_verify); // Set verification state for this cycle
3144 return; // Nothing else needs to be done at this time
3145 }
3147 // Not unloading classes this cycle
3148 assert(!should_unload_classes(), "Inconsitency!");
3149 if ((!verifying() || unloaded_classes_last_cycle()) && should_verify) {
3150 // We were not verifying, or we _were_ unloading classes in the last cycle,
3151 // AND some verification options are enabled this cycle; in this case,
3152 // we must make sure that the deadness map is allocated if not already so,
3153 // and cleared (if already allocated previously --
3154 // CMSBitMap::sizeInBits() is used to determine if it's allocated).
3155 if (perm_gen_verify_bit_map()->sizeInBits() == 0) {
3156 if (!perm_gen_verify_bit_map()->allocate(_permGen->reserved())) {
3157 warning("Failed to allocate permanent generation verification CMS Bit Map;\n"
3158 "permanent generation verification disabled");
3159 return; // Note that we leave verification disabled, so we'll retry this
3160 // allocation next cycle. We _could_ remember this failure
3161 // and skip further attempts and permanently disable verification
3162 // attempts if that is considered more desirable.
3163 }
3164 assert(perm_gen_verify_bit_map()->covers(_permGen->reserved()),
3165 "_perm_gen_ver_bit_map inconsistency?");
3166 } else {
3167 perm_gen_verify_bit_map()->clear_all();
3168 }
3169 // Include symbols, strings and code cache elements to prevent their resurrection.
3170 add_root_scanning_option(rso);
3171 set_verifying(true);
3172 } else if (verifying() && !should_verify) {
3173 // We were verifying, but some verification flags got disabled.
3174 set_verifying(false);
3175 // Exclude symbols, strings and code cache elements from root scanning to
3176 // reduce IM and RM pauses.
3177 remove_root_scanning_option(rso);
3178 }
3179 }
3182 #ifndef PRODUCT
3183 HeapWord* CMSCollector::block_start(const void* p) const {
3184 const HeapWord* addr = (HeapWord*)p;
3185 if (_span.contains(p)) {
3186 if (_cmsGen->cmsSpace()->is_in_reserved(addr)) {
3187 return _cmsGen->cmsSpace()->block_start(p);
3188 } else {
3189 assert(_permGen->cmsSpace()->is_in_reserved(addr),
3190 "Inconsistent _span?");
3191 return _permGen->cmsSpace()->block_start(p);
3192 }
3193 }
3194 return NULL;
3195 }
3196 #endif
3198 HeapWord*
3199 ConcurrentMarkSweepGeneration::expand_and_allocate(size_t word_size,
3200 bool tlab,
3201 bool parallel) {
3202 assert(!tlab, "Can't deal with TLAB allocation");
3203 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
3204 expand(word_size*HeapWordSize, MinHeapDeltaBytes,
3205 CMSExpansionCause::_satisfy_allocation);
3206 if (GCExpandToAllocateDelayMillis > 0) {
3207 os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
3208 }
3209 return have_lock_and_allocate(word_size, tlab);
3210 }
3212 // YSR: All of this generation expansion/shrinking stuff is an exact copy of
3213 // OneContigSpaceCardGeneration, which makes me wonder if we should move this
3214 // to CardGeneration and share it...
3215 bool ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes) {
3216 return CardGeneration::expand(bytes, expand_bytes);
3217 }
3219 void ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes,
3220 CMSExpansionCause::Cause cause)
3221 {
3223 bool success = expand(bytes, expand_bytes);
3225 // remember why we expanded; this information is used
3226 // by shouldConcurrentCollect() when making decisions on whether to start
3227 // a new CMS cycle.
3228 if (success) {
3229 set_expansion_cause(cause);
3230 if (PrintGCDetails && Verbose) {
3231 gclog_or_tty->print_cr("Expanded CMS gen for %s",
3232 CMSExpansionCause::to_string(cause));
3233 }
3234 }
3235 }
3237 HeapWord* ConcurrentMarkSweepGeneration::expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz) {
3238 HeapWord* res = NULL;
3239 MutexLocker x(ParGCRareEvent_lock);
3240 while (true) {
3241 // Expansion by some other thread might make alloc OK now:
3242 res = ps->lab.alloc(word_sz);
3243 if (res != NULL) return res;
3244 // If there's not enough expansion space available, give up.
3245 if (_virtual_space.uncommitted_size() < (word_sz * HeapWordSize)) {
3246 return NULL;
3247 }
3248 // Otherwise, we try expansion.
3249 expand(word_sz*HeapWordSize, MinHeapDeltaBytes,
3250 CMSExpansionCause::_allocate_par_lab);
3251 // Now go around the loop and try alloc again;
3252 // A competing par_promote might beat us to the expansion space,
3253 // so we may go around the loop again if promotion fails agaion.
3254 if (GCExpandToAllocateDelayMillis > 0) {
3255 os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
3256 }
3257 }
3258 }
3261 bool ConcurrentMarkSweepGeneration::expand_and_ensure_spooling_space(
3262 PromotionInfo* promo) {
3263 MutexLocker x(ParGCRareEvent_lock);
3264 size_t refill_size_bytes = promo->refillSize() * HeapWordSize;
3265 while (true) {
3266 // Expansion by some other thread might make alloc OK now:
3267 if (promo->ensure_spooling_space()) {
3268 assert(promo->has_spooling_space(),
3269 "Post-condition of successful ensure_spooling_space()");
3270 return true;
3271 }
3272 // If there's not enough expansion space available, give up.
3273 if (_virtual_space.uncommitted_size() < refill_size_bytes) {
3274 return false;
3275 }
3276 // Otherwise, we try expansion.
3277 expand(refill_size_bytes, MinHeapDeltaBytes,
3278 CMSExpansionCause::_allocate_par_spooling_space);
3279 // Now go around the loop and try alloc again;
3280 // A competing allocation might beat us to the expansion space,
3281 // so we may go around the loop again if allocation fails again.
3282 if (GCExpandToAllocateDelayMillis > 0) {
3283 os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
3284 }
3285 }
3286 }
3290 void ConcurrentMarkSweepGeneration::shrink(size_t bytes) {
3291 assert_locked_or_safepoint(Heap_lock);
3292 size_t size = ReservedSpace::page_align_size_down(bytes);
3293 if (size > 0) {
3294 shrink_by(size);
3295 }
3296 }
3298 bool ConcurrentMarkSweepGeneration::grow_by(size_t bytes) {
3299 assert_locked_or_safepoint(Heap_lock);
3300 bool result = _virtual_space.expand_by(bytes);
3301 if (result) {
3302 HeapWord* old_end = _cmsSpace->end();
3303 size_t new_word_size =
3304 heap_word_size(_virtual_space.committed_size());
3305 MemRegion mr(_cmsSpace->bottom(), new_word_size);
3306 _bts->resize(new_word_size); // resize the block offset shared array
3307 Universe::heap()->barrier_set()->resize_covered_region(mr);
3308 // Hmmmm... why doesn't CFLS::set_end verify locking?
3309 // This is quite ugly; FIX ME XXX
3310 _cmsSpace->assert_locked();
3311 _cmsSpace->set_end((HeapWord*)_virtual_space.high());
3313 // update the space and generation capacity counters
3314 if (UsePerfData) {
3315 _space_counters->update_capacity();
3316 _gen_counters->update_all();
3317 }
3319 if (Verbose && PrintGC) {
3320 size_t new_mem_size = _virtual_space.committed_size();
3321 size_t old_mem_size = new_mem_size - bytes;
3322 gclog_or_tty->print_cr("Expanding %s from %ldK by %ldK to %ldK",
3323 name(), old_mem_size/K, bytes/K, new_mem_size/K);
3324 }
3325 }
3326 return result;
3327 }
3329 bool ConcurrentMarkSweepGeneration::grow_to_reserved() {
3330 assert_locked_or_safepoint(Heap_lock);
3331 bool success = true;
3332 const size_t remaining_bytes = _virtual_space.uncommitted_size();
3333 if (remaining_bytes > 0) {
3334 success = grow_by(remaining_bytes);
3335 DEBUG_ONLY(if (!success) warning("grow to reserved failed");)
3336 }
3337 return success;
3338 }
3340 void ConcurrentMarkSweepGeneration::shrink_by(size_t bytes) {
3341 assert_locked_or_safepoint(Heap_lock);
3342 assert_lock_strong(freelistLock());
3343 // XXX Fix when compaction is implemented.
3344 warning("Shrinking of CMS not yet implemented");
3345 return;
3346 }
3349 // Simple ctor/dtor wrapper for accounting & timer chores around concurrent
3350 // phases.
3351 class CMSPhaseAccounting: public StackObj {
3352 public:
3353 CMSPhaseAccounting(CMSCollector *collector,
3354 const char *phase,
3355 bool print_cr = true);
3356 ~CMSPhaseAccounting();
3358 private:
3359 CMSCollector *_collector;
3360 const char *_phase;
3361 elapsedTimer _wallclock;
3362 bool _print_cr;
3364 public:
3365 // Not MT-safe; so do not pass around these StackObj's
3366 // where they may be accessed by other threads.
3367 jlong wallclock_millis() {
3368 assert(_wallclock.is_active(), "Wall clock should not stop");
3369 _wallclock.stop(); // to record time
3370 jlong ret = _wallclock.milliseconds();
3371 _wallclock.start(); // restart
3372 return ret;
3373 }
3374 };
3376 CMSPhaseAccounting::CMSPhaseAccounting(CMSCollector *collector,
3377 const char *phase,
3378 bool print_cr) :
3379 _collector(collector), _phase(phase), _print_cr(print_cr) {
3381 if (PrintCMSStatistics != 0) {
3382 _collector->resetYields();
3383 }
3384 if (PrintGCDetails && PrintGCTimeStamps) {
3385 gclog_or_tty->date_stamp(PrintGCDateStamps);
3386 gclog_or_tty->stamp();
3387 gclog_or_tty->print_cr(": [%s-concurrent-%s-start]",
3388 _collector->cmsGen()->short_name(), _phase);
3389 }
3390 _collector->resetTimer();
3391 _wallclock.start();
3392 _collector->startTimer();
3393 }
3395 CMSPhaseAccounting::~CMSPhaseAccounting() {
3396 assert(_wallclock.is_active(), "Wall clock should not have stopped");
3397 _collector->stopTimer();
3398 _wallclock.stop();
3399 if (PrintGCDetails) {
3400 gclog_or_tty->date_stamp(PrintGCDateStamps);
3401 if (PrintGCTimeStamps) {
3402 gclog_or_tty->stamp();
3403 gclog_or_tty->print(": ");
3404 }
3405 gclog_or_tty->print("[%s-concurrent-%s: %3.3f/%3.3f secs]",
3406 _collector->cmsGen()->short_name(),
3407 _phase, _collector->timerValue(), _wallclock.seconds());
3408 if (_print_cr) {
3409 gclog_or_tty->print_cr("");
3410 }
3411 if (PrintCMSStatistics != 0) {
3412 gclog_or_tty->print_cr(" (CMS-concurrent-%s yielded %d times)", _phase,
3413 _collector->yields());
3414 }
3415 }
3416 }
3418 // CMS work
3420 // Checkpoint the roots into this generation from outside
3421 // this generation. [Note this initial checkpoint need only
3422 // be approximate -- we'll do a catch up phase subsequently.]
3423 void CMSCollector::checkpointRootsInitial(bool asynch) {
3424 assert(_collectorState == InitialMarking, "Wrong collector state");
3425 check_correct_thread_executing();
3426 ReferenceProcessor* rp = ref_processor();
3427 SpecializationStats::clear();
3428 assert(_restart_addr == NULL, "Control point invariant");
3429 if (asynch) {
3430 // acquire locks for subsequent manipulations
3431 MutexLockerEx x(bitMapLock(),
3432 Mutex::_no_safepoint_check_flag);
3433 checkpointRootsInitialWork(asynch);
3434 rp->verify_no_references_recorded();
3435 rp->enable_discovery(); // enable ("weak") refs discovery
3436 _collectorState = Marking;
3437 } else {
3438 // (Weak) Refs discovery: this is controlled from genCollectedHeap::do_collection
3439 // which recognizes if we are a CMS generation, and doesn't try to turn on
3440 // discovery; verify that they aren't meddling.
3441 assert(!rp->discovery_is_atomic(),
3442 "incorrect setting of discovery predicate");
3443 assert(!rp->discovery_enabled(), "genCollectedHeap shouldn't control "
3444 "ref discovery for this generation kind");
3445 // already have locks
3446 checkpointRootsInitialWork(asynch);
3447 rp->enable_discovery(); // now enable ("weak") refs discovery
3448 _collectorState = Marking;
3449 }
3450 SpecializationStats::print();
3451 }
3453 void CMSCollector::checkpointRootsInitialWork(bool asynch) {
3454 assert(SafepointSynchronize::is_at_safepoint(), "world should be stopped");
3455 assert(_collectorState == InitialMarking, "just checking");
3457 // If there has not been a GC[n-1] since last GC[n] cycle completed,
3458 // precede our marking with a collection of all
3459 // younger generations to keep floating garbage to a minimum.
3460 // XXX: we won't do this for now -- it's an optimization to be done later.
3462 // already have locks
3463 assert_lock_strong(bitMapLock());
3464 assert(_markBitMap.isAllClear(), "was reset at end of previous cycle");
3466 // Setup the verification and class unloading state for this
3467 // CMS collection cycle.
3468 setup_cms_unloading_and_verification_state();
3470 NOT_PRODUCT(TraceTime t("\ncheckpointRootsInitialWork",
3471 PrintGCDetails && Verbose, true, gclog_or_tty);)
3472 if (UseAdaptiveSizePolicy) {
3473 size_policy()->checkpoint_roots_initial_begin();
3474 }
3476 // Reset all the PLAB chunk arrays if necessary.
3477 if (_survivor_plab_array != NULL && !CMSPLABRecordAlways) {
3478 reset_survivor_plab_arrays();
3479 }
3481 ResourceMark rm;
3482 HandleMark hm;
3484 FalseClosure falseClosure;
3485 // In the case of a synchronous collection, we will elide the
3486 // remark step, so it's important to catch all the nmethod oops
3487 // in this step; hence the last argument to the constrcutor below.
3488 MarkRefsIntoClosure notOlder(_span, &_markBitMap, !asynch /* nmethods */);
3489 GenCollectedHeap* gch = GenCollectedHeap::heap();
3491 verify_work_stacks_empty();
3492 verify_overflow_empty();
3494 gch->ensure_parsability(false); // fill TLABs, but no need to retire them
3495 // Update the saved marks which may affect the root scans.
3496 gch->save_marks();
3498 // weak reference processing has not started yet.
3499 ref_processor()->set_enqueuing_is_done(false);
3501 {
3502 // This is not needed. DEBUG_ONLY(RememberKlassesChecker imx(true);)
3503 COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
3504 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
3505 gch->gen_process_strong_roots(_cmsGen->level(),
3506 true, // younger gens are roots
3507 true, // collecting perm gen
3508 SharedHeap::ScanningOption(roots_scanning_options()),
3509 NULL, ¬Older);
3510 }
3512 // Clear mod-union table; it will be dirtied in the prologue of
3513 // CMS generation per each younger generation collection.
3515 assert(_modUnionTable.isAllClear(),
3516 "Was cleared in most recent final checkpoint phase"
3517 " or no bits are set in the gc_prologue before the start of the next "
3518 "subsequent marking phase.");
3520 // Temporarily disabled, since pre/post-consumption closures don't
3521 // care about precleaned cards
3522 #if 0
3523 {
3524 MemRegion mr = MemRegion((HeapWord*)_virtual_space.low(),
3525 (HeapWord*)_virtual_space.high());
3526 _ct->ct_bs()->preclean_dirty_cards(mr);
3527 }
3528 #endif
3530 // Save the end of the used_region of the constituent generations
3531 // to be used to limit the extent of sweep in each generation.
3532 save_sweep_limits();
3533 if (UseAdaptiveSizePolicy) {
3534 size_policy()->checkpoint_roots_initial_end(gch->gc_cause());
3535 }
3536 verify_overflow_empty();
3537 }
3539 bool CMSCollector::markFromRoots(bool asynch) {
3540 // we might be tempted to assert that:
3541 // assert(asynch == !SafepointSynchronize::is_at_safepoint(),
3542 // "inconsistent argument?");
3543 // However that wouldn't be right, because it's possible that
3544 // a safepoint is indeed in progress as a younger generation
3545 // stop-the-world GC happens even as we mark in this generation.
3546 assert(_collectorState == Marking, "inconsistent state?");
3547 check_correct_thread_executing();
3548 verify_overflow_empty();
3550 bool res;
3551 if (asynch) {
3553 // Start the timers for adaptive size policy for the concurrent phases
3554 // Do it here so that the foreground MS can use the concurrent
3555 // timer since a foreground MS might has the sweep done concurrently
3556 // or STW.
3557 if (UseAdaptiveSizePolicy) {
3558 size_policy()->concurrent_marking_begin();
3559 }
3561 // Weak ref discovery note: We may be discovering weak
3562 // refs in this generation concurrent (but interleaved) with
3563 // weak ref discovery by a younger generation collector.
3565 CMSTokenSyncWithLocks ts(true, bitMapLock());
3566 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
3567 CMSPhaseAccounting pa(this, "mark", !PrintGCDetails);
3568 res = markFromRootsWork(asynch);
3569 if (res) {
3570 _collectorState = Precleaning;
3571 } else { // We failed and a foreground collection wants to take over
3572 assert(_foregroundGCIsActive, "internal state inconsistency");
3573 assert(_restart_addr == NULL, "foreground will restart from scratch");
3574 if (PrintGCDetails) {
3575 gclog_or_tty->print_cr("bailing out to foreground collection");
3576 }
3577 }
3578 if (UseAdaptiveSizePolicy) {
3579 size_policy()->concurrent_marking_end();
3580 }
3581 } else {
3582 assert(SafepointSynchronize::is_at_safepoint(),
3583 "inconsistent with asynch == false");
3584 if (UseAdaptiveSizePolicy) {
3585 size_policy()->ms_collection_marking_begin();
3586 }
3587 // already have locks
3588 res = markFromRootsWork(asynch);
3589 _collectorState = FinalMarking;
3590 if (UseAdaptiveSizePolicy) {
3591 GenCollectedHeap* gch = GenCollectedHeap::heap();
3592 size_policy()->ms_collection_marking_end(gch->gc_cause());
3593 }
3594 }
3595 verify_overflow_empty();
3596 return res;
3597 }
3599 bool CMSCollector::markFromRootsWork(bool asynch) {
3600 // iterate over marked bits in bit map, doing a full scan and mark
3601 // from these roots using the following algorithm:
3602 // . if oop is to the right of the current scan pointer,
3603 // mark corresponding bit (we'll process it later)
3604 // . else (oop is to left of current scan pointer)
3605 // push oop on marking stack
3606 // . drain the marking stack
3608 // Note that when we do a marking step we need to hold the
3609 // bit map lock -- recall that direct allocation (by mutators)
3610 // and promotion (by younger generation collectors) is also
3611 // marking the bit map. [the so-called allocate live policy.]
3612 // Because the implementation of bit map marking is not
3613 // robust wrt simultaneous marking of bits in the same word,
3614 // we need to make sure that there is no such interference
3615 // between concurrent such updates.
3617 // already have locks
3618 assert_lock_strong(bitMapLock());
3620 // Clear the revisit stack, just in case there are any
3621 // obsolete contents from a short-circuited previous CMS cycle.
3622 _revisitStack.reset();
3623 verify_work_stacks_empty();
3624 verify_overflow_empty();
3625 assert(_revisitStack.isEmpty(), "tabula rasa");
3627 DEBUG_ONLY(RememberKlassesChecker cmx(CMSClassUnloadingEnabled);)
3629 bool result = false;
3630 if (CMSConcurrentMTEnabled && ParallelCMSThreads > 0) {
3631 result = do_marking_mt(asynch);
3632 } else {
3633 result = do_marking_st(asynch);
3634 }
3635 return result;
3636 }
3638 // Forward decl
3639 class CMSConcMarkingTask;
3641 class CMSConcMarkingTerminator: public ParallelTaskTerminator {
3642 CMSCollector* _collector;
3643 CMSConcMarkingTask* _task;
3644 bool _yield;
3645 protected:
3646 virtual void yield();
3647 public:
3648 // "n_threads" is the number of threads to be terminated.
3649 // "queue_set" is a set of work queues of other threads.
3650 // "collector" is the CMS collector associated with this task terminator.
3651 // "yield" indicates whether we need the gang as a whole to yield.
3652 CMSConcMarkingTerminator(int n_threads, TaskQueueSetSuper* queue_set,
3653 CMSCollector* collector, bool yield) :
3654 ParallelTaskTerminator(n_threads, queue_set),
3655 _collector(collector),
3656 _yield(yield) { }
3658 void set_task(CMSConcMarkingTask* task) {
3659 _task = task;
3660 }
3661 };
3663 // MT Concurrent Marking Task
3664 class CMSConcMarkingTask: public YieldingFlexibleGangTask {
3665 CMSCollector* _collector;
3666 YieldingFlexibleWorkGang* _workers; // the whole gang
3667 int _n_workers; // requested/desired # workers
3668 bool _asynch;
3669 bool _result;
3670 CompactibleFreeListSpace* _cms_space;
3671 CompactibleFreeListSpace* _perm_space;
3672 HeapWord* _global_finger;
3673 HeapWord* _restart_addr;
3675 // Exposed here for yielding support
3676 Mutex* const _bit_map_lock;
3678 // The per thread work queues, available here for stealing
3679 OopTaskQueueSet* _task_queues;
3680 CMSConcMarkingTerminator _term;
3682 public:
3683 CMSConcMarkingTask(CMSCollector* collector,
3684 CompactibleFreeListSpace* cms_space,
3685 CompactibleFreeListSpace* perm_space,
3686 bool asynch, int n_workers,
3687 YieldingFlexibleWorkGang* workers,
3688 OopTaskQueueSet* task_queues):
3689 YieldingFlexibleGangTask("Concurrent marking done multi-threaded"),
3690 _collector(collector),
3691 _cms_space(cms_space),
3692 _perm_space(perm_space),
3693 _asynch(asynch), _n_workers(n_workers), _result(true),
3694 _workers(workers), _task_queues(task_queues),
3695 _term(n_workers, task_queues, _collector, asynch),
3696 _bit_map_lock(collector->bitMapLock())
3697 {
3698 assert(n_workers <= workers->total_workers(),
3699 "Else termination won't work correctly today"); // XXX FIX ME!
3700 _requested_size = n_workers;
3701 _term.set_task(this);
3702 assert(_cms_space->bottom() < _perm_space->bottom(),
3703 "Finger incorrectly initialized below");
3704 _restart_addr = _global_finger = _cms_space->bottom();
3705 }
3708 OopTaskQueueSet* task_queues() { return _task_queues; }
3710 OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
3712 HeapWord** global_finger_addr() { return &_global_finger; }
3714 CMSConcMarkingTerminator* terminator() { return &_term; }
3716 void work(int i);
3718 virtual void coordinator_yield(); // stuff done by coordinator
3719 bool result() { return _result; }
3721 void reset(HeapWord* ra) {
3722 assert(_global_finger >= _cms_space->end(), "Postcondition of ::work(i)");
3723 assert(_global_finger >= _perm_space->end(), "Postcondition of ::work(i)");
3724 assert(ra < _perm_space->end(), "ra too large");
3725 _restart_addr = _global_finger = ra;
3726 _term.reset_for_reuse();
3727 }
3729 static bool get_work_from_overflow_stack(CMSMarkStack* ovflw_stk,
3730 OopTaskQueue* work_q);
3732 private:
3733 void do_scan_and_mark(int i, CompactibleFreeListSpace* sp);
3734 void do_work_steal(int i);
3735 void bump_global_finger(HeapWord* f);
3736 };
3738 void CMSConcMarkingTerminator::yield() {
3739 if (ConcurrentMarkSweepThread::should_yield() &&
3740 !_collector->foregroundGCIsActive() &&
3741 _yield) {
3742 _task->yield();
3743 } else {
3744 ParallelTaskTerminator::yield();
3745 }
3746 }
3748 ////////////////////////////////////////////////////////////////
3749 // Concurrent Marking Algorithm Sketch
3750 ////////////////////////////////////////////////////////////////
3751 // Until all tasks exhausted (both spaces):
3752 // -- claim next available chunk
3753 // -- bump global finger via CAS
3754 // -- find first object that starts in this chunk
3755 // and start scanning bitmap from that position
3756 // -- scan marked objects for oops
3757 // -- CAS-mark target, and if successful:
3758 // . if target oop is above global finger (volatile read)
3759 // nothing to do
3760 // . if target oop is in chunk and above local finger
3761 // then nothing to do
3762 // . else push on work-queue
3763 // -- Deal with possible overflow issues:
3764 // . local work-queue overflow causes stuff to be pushed on
3765 // global (common) overflow queue
3766 // . always first empty local work queue
3767 // . then get a batch of oops from global work queue if any
3768 // . then do work stealing
3769 // -- When all tasks claimed (both spaces)
3770 // and local work queue empty,
3771 // then in a loop do:
3772 // . check global overflow stack; steal a batch of oops and trace
3773 // . try to steal from other threads oif GOS is empty
3774 // . if neither is available, offer termination
3775 // -- Terminate and return result
3776 //
3777 void CMSConcMarkingTask::work(int i) {
3778 elapsedTimer _timer;
3779 ResourceMark rm;
3780 HandleMark hm;
3782 DEBUG_ONLY(_collector->verify_overflow_empty();)
3784 // Before we begin work, our work queue should be empty
3785 assert(work_queue(i)->size() == 0, "Expected to be empty");
3786 // Scan the bitmap covering _cms_space, tracing through grey objects.
3787 _timer.start();
3788 do_scan_and_mark(i, _cms_space);
3789 _timer.stop();
3790 if (PrintCMSStatistics != 0) {
3791 gclog_or_tty->print_cr("Finished cms space scanning in %dth thread: %3.3f sec",
3792 i, _timer.seconds()); // XXX: need xxx/xxx type of notation, two timers
3793 }
3795 // ... do the same for the _perm_space
3796 _timer.reset();
3797 _timer.start();
3798 do_scan_and_mark(i, _perm_space);
3799 _timer.stop();
3800 if (PrintCMSStatistics != 0) {
3801 gclog_or_tty->print_cr("Finished perm space scanning in %dth thread: %3.3f sec",
3802 i, _timer.seconds()); // XXX: need xxx/xxx type of notation, two timers
3803 }
3805 // ... do work stealing
3806 _timer.reset();
3807 _timer.start();
3808 do_work_steal(i);
3809 _timer.stop();
3810 if (PrintCMSStatistics != 0) {
3811 gclog_or_tty->print_cr("Finished work stealing in %dth thread: %3.3f sec",
3812 i, _timer.seconds()); // XXX: need xxx/xxx type of notation, two timers
3813 }
3814 assert(_collector->_markStack.isEmpty(), "Should have been emptied");
3815 assert(work_queue(i)->size() == 0, "Should have been emptied");
3816 // Note that under the current task protocol, the
3817 // following assertion is true even of the spaces
3818 // expanded since the completion of the concurrent
3819 // marking. XXX This will likely change under a strict
3820 // ABORT semantics.
3821 assert(_global_finger > _cms_space->end() &&
3822 _global_finger >= _perm_space->end(),
3823 "All tasks have been completed");
3824 DEBUG_ONLY(_collector->verify_overflow_empty();)
3825 }
3827 void CMSConcMarkingTask::bump_global_finger(HeapWord* f) {
3828 HeapWord* read = _global_finger;
3829 HeapWord* cur = read;
3830 while (f > read) {
3831 cur = read;
3832 read = (HeapWord*) Atomic::cmpxchg_ptr(f, &_global_finger, cur);
3833 if (cur == read) {
3834 // our cas succeeded
3835 assert(_global_finger >= f, "protocol consistency");
3836 break;
3837 }
3838 }
3839 }
3841 // This is really inefficient, and should be redone by
3842 // using (not yet available) block-read and -write interfaces to the
3843 // stack and the work_queue. XXX FIX ME !!!
3844 bool CMSConcMarkingTask::get_work_from_overflow_stack(CMSMarkStack* ovflw_stk,
3845 OopTaskQueue* work_q) {
3846 // Fast lock-free check
3847 if (ovflw_stk->length() == 0) {
3848 return false;
3849 }
3850 assert(work_q->size() == 0, "Shouldn't steal");
3851 MutexLockerEx ml(ovflw_stk->par_lock(),
3852 Mutex::_no_safepoint_check_flag);
3853 // Grab up to 1/4 the size of the work queue
3854 size_t num = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
3855 (size_t)ParGCDesiredObjsFromOverflowList);
3856 num = MIN2(num, ovflw_stk->length());
3857 for (int i = (int) num; i > 0; i--) {
3858 oop cur = ovflw_stk->pop();
3859 assert(cur != NULL, "Counted wrong?");
3860 work_q->push(cur);
3861 }
3862 return num > 0;
3863 }
3865 void CMSConcMarkingTask::do_scan_and_mark(int i, CompactibleFreeListSpace* sp) {
3866 SequentialSubTasksDone* pst = sp->conc_par_seq_tasks();
3867 int n_tasks = pst->n_tasks();
3868 // We allow that there may be no tasks to do here because
3869 // we are restarting after a stack overflow.
3870 assert(pst->valid() || n_tasks == 0, "Uninitialized use?");
3871 int nth_task = 0;
3873 HeapWord* aligned_start = sp->bottom();
3874 if (sp->used_region().contains(_restart_addr)) {
3875 // Align down to a card boundary for the start of 0th task
3876 // for this space.
3877 aligned_start =
3878 (HeapWord*)align_size_down((uintptr_t)_restart_addr,
3879 CardTableModRefBS::card_size);
3880 }
3882 size_t chunk_size = sp->marking_task_size();
3883 while (!pst->is_task_claimed(/* reference */ nth_task)) {
3884 // Having claimed the nth task in this space,
3885 // compute the chunk that it corresponds to:
3886 MemRegion span = MemRegion(aligned_start + nth_task*chunk_size,
3887 aligned_start + (nth_task+1)*chunk_size);
3888 // Try and bump the global finger via a CAS;
3889 // note that we need to do the global finger bump
3890 // _before_ taking the intersection below, because
3891 // the task corresponding to that region will be
3892 // deemed done even if the used_region() expands
3893 // because of allocation -- as it almost certainly will
3894 // during start-up while the threads yield in the
3895 // closure below.
3896 HeapWord* finger = span.end();
3897 bump_global_finger(finger); // atomically
3898 // There are null tasks here corresponding to chunks
3899 // beyond the "top" address of the space.
3900 span = span.intersection(sp->used_region());
3901 if (!span.is_empty()) { // Non-null task
3902 HeapWord* prev_obj;
3903 assert(!span.contains(_restart_addr) || nth_task == 0,
3904 "Inconsistency");
3905 if (nth_task == 0) {
3906 // For the 0th task, we'll not need to compute a block_start.
3907 if (span.contains(_restart_addr)) {
3908 // In the case of a restart because of stack overflow,
3909 // we might additionally skip a chunk prefix.
3910 prev_obj = _restart_addr;
3911 } else {
3912 prev_obj = span.start();
3913 }
3914 } else {
3915 // We want to skip the first object because
3916 // the protocol is to scan any object in its entirety
3917 // that _starts_ in this span; a fortiori, any
3918 // object starting in an earlier span is scanned
3919 // as part of an earlier claimed task.
3920 // Below we use the "careful" version of block_start
3921 // so we do not try to navigate uninitialized objects.
3922 prev_obj = sp->block_start_careful(span.start());
3923 // Below we use a variant of block_size that uses the
3924 // Printezis bits to avoid waiting for allocated
3925 // objects to become initialized/parsable.
3926 while (prev_obj < span.start()) {
3927 size_t sz = sp->block_size_no_stall(prev_obj, _collector);
3928 if (sz > 0) {
3929 prev_obj += sz;
3930 } else {
3931 // In this case we may end up doing a bit of redundant
3932 // scanning, but that appears unavoidable, short of
3933 // locking the free list locks; see bug 6324141.
3934 break;
3935 }
3936 }
3937 }
3938 if (prev_obj < span.end()) {
3939 MemRegion my_span = MemRegion(prev_obj, span.end());
3940 // Do the marking work within a non-empty span --
3941 // the last argument to the constructor indicates whether the
3942 // iteration should be incremental with periodic yields.
3943 Par_MarkFromRootsClosure cl(this, _collector, my_span,
3944 &_collector->_markBitMap,
3945 work_queue(i),
3946 &_collector->_markStack,
3947 &_collector->_revisitStack,
3948 _asynch);
3949 _collector->_markBitMap.iterate(&cl, my_span.start(), my_span.end());
3950 } // else nothing to do for this task
3951 } // else nothing to do for this task
3952 }
3953 // We'd be tempted to assert here that since there are no
3954 // more tasks left to claim in this space, the global_finger
3955 // must exceed space->top() and a fortiori space->end(). However,
3956 // that would not quite be correct because the bumping of
3957 // global_finger occurs strictly after the claiming of a task,
3958 // so by the time we reach here the global finger may not yet
3959 // have been bumped up by the thread that claimed the last
3960 // task.
3961 pst->all_tasks_completed();
3962 }
3964 class Par_ConcMarkingClosure: public Par_KlassRememberingOopClosure {
3965 private:
3966 MemRegion _span;
3967 CMSBitMap* _bit_map;
3968 CMSMarkStack* _overflow_stack;
3969 OopTaskQueue* _work_queue;
3970 protected:
3971 DO_OOP_WORK_DEFN
3972 public:
3973 Par_ConcMarkingClosure(CMSCollector* collector, OopTaskQueue* work_queue,
3974 CMSBitMap* bit_map, CMSMarkStack* overflow_stack,
3975 CMSMarkStack* revisit_stack):
3976 Par_KlassRememberingOopClosure(collector, NULL, revisit_stack),
3977 _span(_collector->_span),
3978 _work_queue(work_queue),
3979 _bit_map(bit_map),
3980 _overflow_stack(overflow_stack)
3981 { }
3982 virtual void do_oop(oop* p);
3983 virtual void do_oop(narrowOop* p);
3984 void trim_queue(size_t max);
3985 void handle_stack_overflow(HeapWord* lost);
3986 };
3988 // Grey object scanning during work stealing phase --
3989 // the salient assumption here is that any references
3990 // that are in these stolen objects being scanned must
3991 // already have been initialized (else they would not have
3992 // been published), so we do not need to check for
3993 // uninitialized objects before pushing here.
3994 void Par_ConcMarkingClosure::do_oop(oop obj) {
3995 assert(obj->is_oop_or_null(true), "expected an oop or NULL");
3996 HeapWord* addr = (HeapWord*)obj;
3997 // Check if oop points into the CMS generation
3998 // and is not marked
3999 if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
4000 // a white object ...
4001 // If we manage to "claim" the object, by being the
4002 // first thread to mark it, then we push it on our
4003 // marking stack
4004 if (_bit_map->par_mark(addr)) { // ... now grey
4005 // push on work queue (grey set)
4006 bool simulate_overflow = false;
4007 NOT_PRODUCT(
4008 if (CMSMarkStackOverflowALot &&
4009 _collector->simulate_overflow()) {
4010 // simulate a stack overflow
4011 simulate_overflow = true;
4012 }
4013 )
4014 if (simulate_overflow ||
4015 !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) {
4016 // stack overflow
4017 if (PrintCMSStatistics != 0) {
4018 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
4019 SIZE_FORMAT, _overflow_stack->capacity());
4020 }
4021 // We cannot assert that the overflow stack is full because
4022 // it may have been emptied since.
4023 assert(simulate_overflow ||
4024 _work_queue->size() == _work_queue->max_elems(),
4025 "Else push should have succeeded");
4026 handle_stack_overflow(addr);
4027 }
4028 } // Else, some other thread got there first
4029 }
4030 }
4032 void Par_ConcMarkingClosure::do_oop(oop* p) { Par_ConcMarkingClosure::do_oop_work(p); }
4033 void Par_ConcMarkingClosure::do_oop(narrowOop* p) { Par_ConcMarkingClosure::do_oop_work(p); }
4035 void Par_ConcMarkingClosure::trim_queue(size_t max) {
4036 while (_work_queue->size() > max) {
4037 oop new_oop;
4038 if (_work_queue->pop_local(new_oop)) {
4039 assert(new_oop->is_oop(), "Should be an oop");
4040 assert(_bit_map->isMarked((HeapWord*)new_oop), "Grey object");
4041 assert(_span.contains((HeapWord*)new_oop), "Not in span");
4042 assert(new_oop->is_parsable(), "Should be parsable");
4043 new_oop->oop_iterate(this); // do_oop() above
4044 }
4045 }
4046 }
4048 // Upon stack overflow, we discard (part of) the stack,
4049 // remembering the least address amongst those discarded
4050 // in CMSCollector's _restart_address.
4051 void Par_ConcMarkingClosure::handle_stack_overflow(HeapWord* lost) {
4052 // We need to do this under a mutex to prevent other
4053 // workers from interfering with the work done below.
4054 MutexLockerEx ml(_overflow_stack->par_lock(),
4055 Mutex::_no_safepoint_check_flag);
4056 // Remember the least grey address discarded
4057 HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost);
4058 _collector->lower_restart_addr(ra);
4059 _overflow_stack->reset(); // discard stack contents
4060 _overflow_stack->expand(); // expand the stack if possible
4061 }
4064 void CMSConcMarkingTask::do_work_steal(int i) {
4065 OopTaskQueue* work_q = work_queue(i);
4066 oop obj_to_scan;
4067 CMSBitMap* bm = &(_collector->_markBitMap);
4068 CMSMarkStack* ovflw = &(_collector->_markStack);
4069 CMSMarkStack* revisit = &(_collector->_revisitStack);
4070 int* seed = _collector->hash_seed(i);
4071 Par_ConcMarkingClosure cl(_collector, work_q, bm, ovflw, revisit);
4072 while (true) {
4073 cl.trim_queue(0);
4074 assert(work_q->size() == 0, "Should have been emptied above");
4075 if (get_work_from_overflow_stack(ovflw, work_q)) {
4076 // Can't assert below because the work obtained from the
4077 // overflow stack may already have been stolen from us.
4078 // assert(work_q->size() > 0, "Work from overflow stack");
4079 continue;
4080 } else if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
4081 assert(obj_to_scan->is_oop(), "Should be an oop");
4082 assert(bm->isMarked((HeapWord*)obj_to_scan), "Grey object");
4083 obj_to_scan->oop_iterate(&cl);
4084 } else if (terminator()->offer_termination()) {
4085 assert(work_q->size() == 0, "Impossible!");
4086 break;
4087 }
4088 }
4089 }
4091 // This is run by the CMS (coordinator) thread.
4092 void CMSConcMarkingTask::coordinator_yield() {
4093 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
4094 "CMS thread should hold CMS token");
4096 DEBUG_ONLY(RememberKlassesChecker mux(false);)
4097 // First give up the locks, then yield, then re-lock
4098 // We should probably use a constructor/destructor idiom to
4099 // do this unlock/lock or modify the MutexUnlocker class to
4100 // serve our purpose. XXX
4101 assert_lock_strong(_bit_map_lock);
4102 _bit_map_lock->unlock();
4103 ConcurrentMarkSweepThread::desynchronize(true);
4104 ConcurrentMarkSweepThread::acknowledge_yield_request();
4105 _collector->stopTimer();
4106 if (PrintCMSStatistics != 0) {
4107 _collector->incrementYields();
4108 }
4109 _collector->icms_wait();
4111 // It is possible for whichever thread initiated the yield request
4112 // not to get a chance to wake up and take the bitmap lock between
4113 // this thread releasing it and reacquiring it. So, while the
4114 // should_yield() flag is on, let's sleep for a bit to give the
4115 // other thread a chance to wake up. The limit imposed on the number
4116 // of iterations is defensive, to avoid any unforseen circumstances
4117 // putting us into an infinite loop. Since it's always been this
4118 // (coordinator_yield()) method that was observed to cause the
4119 // problem, we are using a parameter (CMSCoordinatorYieldSleepCount)
4120 // which is by default non-zero. For the other seven methods that
4121 // also perform the yield operation, as are using a different
4122 // parameter (CMSYieldSleepCount) which is by default zero. This way we
4123 // can enable the sleeping for those methods too, if necessary.
4124 // See 6442774.
4125 //
4126 // We really need to reconsider the synchronization between the GC
4127 // thread and the yield-requesting threads in the future and we
4128 // should really use wait/notify, which is the recommended
4129 // way of doing this type of interaction. Additionally, we should
4130 // consolidate the eight methods that do the yield operation and they
4131 // are almost identical into one for better maintenability and
4132 // readability. See 6445193.
4133 //
4134 // Tony 2006.06.29
4135 for (unsigned i = 0; i < CMSCoordinatorYieldSleepCount &&
4136 ConcurrentMarkSweepThread::should_yield() &&
4137 !CMSCollector::foregroundGCIsActive(); ++i) {
4138 os::sleep(Thread::current(), 1, false);
4139 ConcurrentMarkSweepThread::acknowledge_yield_request();
4140 }
4142 ConcurrentMarkSweepThread::synchronize(true);
4143 _bit_map_lock->lock_without_safepoint_check();
4144 _collector->startTimer();
4145 }
4147 bool CMSCollector::do_marking_mt(bool asynch) {
4148 assert(ParallelCMSThreads > 0 && conc_workers() != NULL, "precondition");
4149 // In the future this would be determined ergonomically, based
4150 // on #cpu's, # active mutator threads (and load), and mutation rate.
4151 int num_workers = ParallelCMSThreads;
4153 CompactibleFreeListSpace* cms_space = _cmsGen->cmsSpace();
4154 CompactibleFreeListSpace* perm_space = _permGen->cmsSpace();
4156 CMSConcMarkingTask tsk(this, cms_space, perm_space,
4157 asynch, num_workers /* number requested XXX */,
4158 conc_workers(), task_queues());
4160 // Since the actual number of workers we get may be different
4161 // from the number we requested above, do we need to do anything different
4162 // below? In particular, may be we need to subclass the SequantialSubTasksDone
4163 // class?? XXX
4164 cms_space ->initialize_sequential_subtasks_for_marking(num_workers);
4165 perm_space->initialize_sequential_subtasks_for_marking(num_workers);
4167 // Refs discovery is already non-atomic.
4168 assert(!ref_processor()->discovery_is_atomic(), "Should be non-atomic");
4169 // Mutate the Refs discovery so it is MT during the
4170 // multi-threaded marking phase.
4171 ReferenceProcessorMTMutator mt(ref_processor(), num_workers > 1);
4173 DEBUG_ONLY(RememberKlassesChecker cmx(CMSClassUnloadingEnabled);)
4175 conc_workers()->start_task(&tsk);
4176 while (tsk.yielded()) {
4177 tsk.coordinator_yield();
4178 conc_workers()->continue_task(&tsk);
4179 }
4180 // If the task was aborted, _restart_addr will be non-NULL
4181 assert(tsk.completed() || _restart_addr != NULL, "Inconsistency");
4182 while (_restart_addr != NULL) {
4183 // XXX For now we do not make use of ABORTED state and have not
4184 // yet implemented the right abort semantics (even in the original
4185 // single-threaded CMS case). That needs some more investigation
4186 // and is deferred for now; see CR# TBF. 07252005YSR. XXX
4187 assert(!CMSAbortSemantics || tsk.aborted(), "Inconsistency");
4188 // If _restart_addr is non-NULL, a marking stack overflow
4189 // occurred; we need to do a fresh marking iteration from the
4190 // indicated restart address.
4191 if (_foregroundGCIsActive && asynch) {
4192 // We may be running into repeated stack overflows, having
4193 // reached the limit of the stack size, while making very
4194 // slow forward progress. It may be best to bail out and
4195 // let the foreground collector do its job.
4196 // Clear _restart_addr, so that foreground GC
4197 // works from scratch. This avoids the headache of
4198 // a "rescan" which would otherwise be needed because
4199 // of the dirty mod union table & card table.
4200 _restart_addr = NULL;
4201 return false;
4202 }
4203 // Adjust the task to restart from _restart_addr
4204 tsk.reset(_restart_addr);
4205 cms_space ->initialize_sequential_subtasks_for_marking(num_workers,
4206 _restart_addr);
4207 perm_space->initialize_sequential_subtasks_for_marking(num_workers,
4208 _restart_addr);
4209 _restart_addr = NULL;
4210 // Get the workers going again
4211 conc_workers()->start_task(&tsk);
4212 while (tsk.yielded()) {
4213 tsk.coordinator_yield();
4214 conc_workers()->continue_task(&tsk);
4215 }
4216 }
4217 assert(tsk.completed(), "Inconsistency");
4218 assert(tsk.result() == true, "Inconsistency");
4219 return true;
4220 }
4222 bool CMSCollector::do_marking_st(bool asynch) {
4223 ResourceMark rm;
4224 HandleMark hm;
4226 MarkFromRootsClosure markFromRootsClosure(this, _span, &_markBitMap,
4227 &_markStack, &_revisitStack, CMSYield && asynch);
4228 // the last argument to iterate indicates whether the iteration
4229 // should be incremental with periodic yields.
4230 _markBitMap.iterate(&markFromRootsClosure);
4231 // If _restart_addr is non-NULL, a marking stack overflow
4232 // occurred; we need to do a fresh iteration from the
4233 // indicated restart address.
4234 while (_restart_addr != NULL) {
4235 if (_foregroundGCIsActive && asynch) {
4236 // We may be running into repeated stack overflows, having
4237 // reached the limit of the stack size, while making very
4238 // slow forward progress. It may be best to bail out and
4239 // let the foreground collector do its job.
4240 // Clear _restart_addr, so that foreground GC
4241 // works from scratch. This avoids the headache of
4242 // a "rescan" which would otherwise be needed because
4243 // of the dirty mod union table & card table.
4244 _restart_addr = NULL;
4245 return false; // indicating failure to complete marking
4246 }
4247 // Deal with stack overflow:
4248 // we restart marking from _restart_addr
4249 HeapWord* ra = _restart_addr;
4250 markFromRootsClosure.reset(ra);
4251 _restart_addr = NULL;
4252 _markBitMap.iterate(&markFromRootsClosure, ra, _span.end());
4253 }
4254 return true;
4255 }
4257 void CMSCollector::preclean() {
4258 check_correct_thread_executing();
4259 assert(Thread::current()->is_ConcurrentGC_thread(), "Wrong thread");
4260 verify_work_stacks_empty();
4261 verify_overflow_empty();
4262 _abort_preclean = false;
4263 if (CMSPrecleaningEnabled) {
4264 _eden_chunk_index = 0;
4265 size_t used = get_eden_used();
4266 size_t capacity = get_eden_capacity();
4267 // Don't start sampling unless we will get sufficiently
4268 // many samples.
4269 if (used < (capacity/(CMSScheduleRemarkSamplingRatio * 100)
4270 * CMSScheduleRemarkEdenPenetration)) {
4271 _start_sampling = true;
4272 } else {
4273 _start_sampling = false;
4274 }
4275 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
4276 CMSPhaseAccounting pa(this, "preclean", !PrintGCDetails);
4277 preclean_work(CMSPrecleanRefLists1, CMSPrecleanSurvivors1);
4278 }
4279 CMSTokenSync x(true); // is cms thread
4280 if (CMSPrecleaningEnabled) {
4281 sample_eden();
4282 _collectorState = AbortablePreclean;
4283 } else {
4284 _collectorState = FinalMarking;
4285 }
4286 verify_work_stacks_empty();
4287 verify_overflow_empty();
4288 }
4290 // Try and schedule the remark such that young gen
4291 // occupancy is CMSScheduleRemarkEdenPenetration %.
4292 void CMSCollector::abortable_preclean() {
4293 check_correct_thread_executing();
4294 assert(CMSPrecleaningEnabled, "Inconsistent control state");
4295 assert(_collectorState == AbortablePreclean, "Inconsistent control state");
4297 // If Eden's current occupancy is below this threshold,
4298 // immediately schedule the remark; else preclean
4299 // past the next scavenge in an effort to
4300 // schedule the pause as described avove. By choosing
4301 // CMSScheduleRemarkEdenSizeThreshold >= max eden size
4302 // we will never do an actual abortable preclean cycle.
4303 if (get_eden_used() > CMSScheduleRemarkEdenSizeThreshold) {
4304 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
4305 CMSPhaseAccounting pa(this, "abortable-preclean", !PrintGCDetails);
4306 // We need more smarts in the abortable preclean
4307 // loop below to deal with cases where allocation
4308 // in young gen is very very slow, and our precleaning
4309 // is running a losing race against a horde of
4310 // mutators intent on flooding us with CMS updates
4311 // (dirty cards).
4312 // One, admittedly dumb, strategy is to give up
4313 // after a certain number of abortable precleaning loops
4314 // or after a certain maximum time. We want to make
4315 // this smarter in the next iteration.
4316 // XXX FIX ME!!! YSR
4317 size_t loops = 0, workdone = 0, cumworkdone = 0, waited = 0;
4318 while (!(should_abort_preclean() ||
4319 ConcurrentMarkSweepThread::should_terminate())) {
4320 workdone = preclean_work(CMSPrecleanRefLists2, CMSPrecleanSurvivors2);
4321 cumworkdone += workdone;
4322 loops++;
4323 // Voluntarily terminate abortable preclean phase if we have
4324 // been at it for too long.
4325 if ((CMSMaxAbortablePrecleanLoops != 0) &&
4326 loops >= CMSMaxAbortablePrecleanLoops) {
4327 if (PrintGCDetails) {
4328 gclog_or_tty->print(" CMS: abort preclean due to loops ");
4329 }
4330 break;
4331 }
4332 if (pa.wallclock_millis() > CMSMaxAbortablePrecleanTime) {
4333 if (PrintGCDetails) {
4334 gclog_or_tty->print(" CMS: abort preclean due to time ");
4335 }
4336 break;
4337 }
4338 // If we are doing little work each iteration, we should
4339 // take a short break.
4340 if (workdone < CMSAbortablePrecleanMinWorkPerIteration) {
4341 // Sleep for some time, waiting for work to accumulate
4342 stopTimer();
4343 cmsThread()->wait_on_cms_lock(CMSAbortablePrecleanWaitMillis);
4344 startTimer();
4345 waited++;
4346 }
4347 }
4348 if (PrintCMSStatistics > 0) {
4349 gclog_or_tty->print(" [%d iterations, %d waits, %d cards)] ",
4350 loops, waited, cumworkdone);
4351 }
4352 }
4353 CMSTokenSync x(true); // is cms thread
4354 if (_collectorState != Idling) {
4355 assert(_collectorState == AbortablePreclean,
4356 "Spontaneous state transition?");
4357 _collectorState = FinalMarking;
4358 } // Else, a foreground collection completed this CMS cycle.
4359 return;
4360 }
4362 // Respond to an Eden sampling opportunity
4363 void CMSCollector::sample_eden() {
4364 // Make sure a young gc cannot sneak in between our
4365 // reading and recording of a sample.
4366 assert(Thread::current()->is_ConcurrentGC_thread(),
4367 "Only the cms thread may collect Eden samples");
4368 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
4369 "Should collect samples while holding CMS token");
4370 if (!_start_sampling) {
4371 return;
4372 }
4373 if (_eden_chunk_array) {
4374 if (_eden_chunk_index < _eden_chunk_capacity) {
4375 _eden_chunk_array[_eden_chunk_index] = *_top_addr; // take sample
4376 assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
4377 "Unexpected state of Eden");
4378 // We'd like to check that what we just sampled is an oop-start address;
4379 // however, we cannot do that here since the object may not yet have been
4380 // initialized. So we'll instead do the check when we _use_ this sample
4381 // later.
4382 if (_eden_chunk_index == 0 ||
4383 (pointer_delta(_eden_chunk_array[_eden_chunk_index],
4384 _eden_chunk_array[_eden_chunk_index-1])
4385 >= CMSSamplingGrain)) {
4386 _eden_chunk_index++; // commit sample
4387 }
4388 }
4389 }
4390 if ((_collectorState == AbortablePreclean) && !_abort_preclean) {
4391 size_t used = get_eden_used();
4392 size_t capacity = get_eden_capacity();
4393 assert(used <= capacity, "Unexpected state of Eden");
4394 if (used > (capacity/100 * CMSScheduleRemarkEdenPenetration)) {
4395 _abort_preclean = true;
4396 }
4397 }
4398 }
4401 size_t CMSCollector::preclean_work(bool clean_refs, bool clean_survivor) {
4402 assert(_collectorState == Precleaning ||
4403 _collectorState == AbortablePreclean, "incorrect state");
4404 ResourceMark rm;
4405 HandleMark hm;
4406 // Do one pass of scrubbing the discovered reference lists
4407 // to remove any reference objects with strongly-reachable
4408 // referents.
4409 if (clean_refs) {
4410 ReferenceProcessor* rp = ref_processor();
4411 CMSPrecleanRefsYieldClosure yield_cl(this);
4412 assert(rp->span().equals(_span), "Spans should be equal");
4413 CMSKeepAliveClosure keep_alive(this, _span, &_markBitMap,
4414 &_markStack, &_revisitStack,
4415 true /* preclean */);
4416 CMSDrainMarkingStackClosure complete_trace(this,
4417 _span, &_markBitMap, &_markStack,
4418 &keep_alive, true /* preclean */);
4420 // We don't want this step to interfere with a young
4421 // collection because we don't want to take CPU
4422 // or memory bandwidth away from the young GC threads
4423 // (which may be as many as there are CPUs).
4424 // Note that we don't need to protect ourselves from
4425 // interference with mutators because they can't
4426 // manipulate the discovered reference lists nor affect
4427 // the computed reachability of the referents, the
4428 // only properties manipulated by the precleaning
4429 // of these reference lists.
4430 stopTimer();
4431 CMSTokenSyncWithLocks x(true /* is cms thread */,
4432 bitMapLock());
4433 startTimer();
4434 sample_eden();
4436 // The following will yield to allow foreground
4437 // collection to proceed promptly. XXX YSR:
4438 // The code in this method may need further
4439 // tweaking for better performance and some restructuring
4440 // for cleaner interfaces.
4441 rp->preclean_discovered_references(
4442 rp->is_alive_non_header(), &keep_alive, &complete_trace,
4443 &yield_cl);
4444 }
4446 if (clean_survivor) { // preclean the active survivor space(s)
4447 assert(_young_gen->kind() == Generation::DefNew ||
4448 _young_gen->kind() == Generation::ParNew ||
4449 _young_gen->kind() == Generation::ASParNew,
4450 "incorrect type for cast");
4451 DefNewGeneration* dng = (DefNewGeneration*)_young_gen;
4452 PushAndMarkClosure pam_cl(this, _span, ref_processor(),
4453 &_markBitMap, &_modUnionTable,
4454 &_markStack, &_revisitStack,
4455 true /* precleaning phase */);
4456 stopTimer();
4457 CMSTokenSyncWithLocks ts(true /* is cms thread */,
4458 bitMapLock());
4459 startTimer();
4460 unsigned int before_count =
4461 GenCollectedHeap::heap()->total_collections();
4462 SurvivorSpacePrecleanClosure
4463 sss_cl(this, _span, &_markBitMap, &_markStack,
4464 &pam_cl, before_count, CMSYield);
4465 DEBUG_ONLY(RememberKlassesChecker mx(CMSClassUnloadingEnabled);)
4466 dng->from()->object_iterate_careful(&sss_cl);
4467 dng->to()->object_iterate_careful(&sss_cl);
4468 }
4469 MarkRefsIntoAndScanClosure
4470 mrias_cl(_span, ref_processor(), &_markBitMap, &_modUnionTable,
4471 &_markStack, &_revisitStack, this, CMSYield,
4472 true /* precleaning phase */);
4473 // CAUTION: The following closure has persistent state that may need to
4474 // be reset upon a decrease in the sequence of addresses it
4475 // processes.
4476 ScanMarkedObjectsAgainCarefullyClosure
4477 smoac_cl(this, _span,
4478 &_markBitMap, &_markStack, &_revisitStack, &mrias_cl, CMSYield);
4480 // Preclean dirty cards in ModUnionTable and CardTable using
4481 // appropriate convergence criterion;
4482 // repeat CMSPrecleanIter times unless we find that
4483 // we are losing.
4484 assert(CMSPrecleanIter < 10, "CMSPrecleanIter is too large");
4485 assert(CMSPrecleanNumerator < CMSPrecleanDenominator,
4486 "Bad convergence multiplier");
4487 assert(CMSPrecleanThreshold >= 100,
4488 "Unreasonably low CMSPrecleanThreshold");
4490 size_t numIter, cumNumCards, lastNumCards, curNumCards;
4491 for (numIter = 0, cumNumCards = lastNumCards = curNumCards = 0;
4492 numIter < CMSPrecleanIter;
4493 numIter++, lastNumCards = curNumCards, cumNumCards += curNumCards) {
4494 curNumCards = preclean_mod_union_table(_cmsGen, &smoac_cl);
4495 if (CMSPermGenPrecleaningEnabled) {
4496 curNumCards += preclean_mod_union_table(_permGen, &smoac_cl);
4497 }
4498 if (Verbose && PrintGCDetails) {
4499 gclog_or_tty->print(" (modUnionTable: %d cards)", curNumCards);
4500 }
4501 // Either there are very few dirty cards, so re-mark
4502 // pause will be small anyway, or our pre-cleaning isn't
4503 // that much faster than the rate at which cards are being
4504 // dirtied, so we might as well stop and re-mark since
4505 // precleaning won't improve our re-mark time by much.
4506 if (curNumCards <= CMSPrecleanThreshold ||
4507 (numIter > 0 &&
4508 (curNumCards * CMSPrecleanDenominator >
4509 lastNumCards * CMSPrecleanNumerator))) {
4510 numIter++;
4511 cumNumCards += curNumCards;
4512 break;
4513 }
4514 }
4515 curNumCards = preclean_card_table(_cmsGen, &smoac_cl);
4516 if (CMSPermGenPrecleaningEnabled) {
4517 curNumCards += preclean_card_table(_permGen, &smoac_cl);
4518 }
4519 cumNumCards += curNumCards;
4520 if (PrintGCDetails && PrintCMSStatistics != 0) {
4521 gclog_or_tty->print_cr(" (cardTable: %d cards, re-scanned %d cards, %d iterations)",
4522 curNumCards, cumNumCards, numIter);
4523 }
4524 return cumNumCards; // as a measure of useful work done
4525 }
4527 // PRECLEANING NOTES:
4528 // Precleaning involves:
4529 // . reading the bits of the modUnionTable and clearing the set bits.
4530 // . For the cards corresponding to the set bits, we scan the
4531 // objects on those cards. This means we need the free_list_lock
4532 // so that we can safely iterate over the CMS space when scanning
4533 // for oops.
4534 // . When we scan the objects, we'll be both reading and setting
4535 // marks in the marking bit map, so we'll need the marking bit map.
4536 // . For protecting _collector_state transitions, we take the CGC_lock.
4537 // Note that any races in the reading of of card table entries by the
4538 // CMS thread on the one hand and the clearing of those entries by the
4539 // VM thread or the setting of those entries by the mutator threads on the
4540 // other are quite benign. However, for efficiency it makes sense to keep
4541 // the VM thread from racing with the CMS thread while the latter is
4542 // dirty card info to the modUnionTable. We therefore also use the
4543 // CGC_lock to protect the reading of the card table and the mod union
4544 // table by the CM thread.
4545 // . We run concurrently with mutator updates, so scanning
4546 // needs to be done carefully -- we should not try to scan
4547 // potentially uninitialized objects.
4548 //
4549 // Locking strategy: While holding the CGC_lock, we scan over and
4550 // reset a maximal dirty range of the mod union / card tables, then lock
4551 // the free_list_lock and bitmap lock to do a full marking, then
4552 // release these locks; and repeat the cycle. This allows for a
4553 // certain amount of fairness in the sharing of these locks between
4554 // the CMS collector on the one hand, and the VM thread and the
4555 // mutators on the other.
4557 // NOTE: preclean_mod_union_table() and preclean_card_table()
4558 // further below are largely identical; if you need to modify
4559 // one of these methods, please check the other method too.
4561 size_t CMSCollector::preclean_mod_union_table(
4562 ConcurrentMarkSweepGeneration* gen,
4563 ScanMarkedObjectsAgainCarefullyClosure* cl) {
4564 verify_work_stacks_empty();
4565 verify_overflow_empty();
4567 // Turn off checking for this method but turn it back on
4568 // selectively. There are yield points in this method
4569 // but it is difficult to turn the checking off just around
4570 // the yield points. It is simpler to selectively turn
4571 // it on.
4572 DEBUG_ONLY(RememberKlassesChecker mux(false);)
4574 // strategy: starting with the first card, accumulate contiguous
4575 // ranges of dirty cards; clear these cards, then scan the region
4576 // covered by these cards.
4578 // Since all of the MUT is committed ahead, we can just use
4579 // that, in case the generations expand while we are precleaning.
4580 // It might also be fine to just use the committed part of the
4581 // generation, but we might potentially miss cards when the
4582 // generation is rapidly expanding while we are in the midst
4583 // of precleaning.
4584 HeapWord* startAddr = gen->reserved().start();
4585 HeapWord* endAddr = gen->reserved().end();
4587 cl->setFreelistLock(gen->freelistLock()); // needed for yielding
4589 size_t numDirtyCards, cumNumDirtyCards;
4590 HeapWord *nextAddr, *lastAddr;
4591 for (cumNumDirtyCards = numDirtyCards = 0,
4592 nextAddr = lastAddr = startAddr;
4593 nextAddr < endAddr;
4594 nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) {
4596 ResourceMark rm;
4597 HandleMark hm;
4599 MemRegion dirtyRegion;
4600 {
4601 stopTimer();
4602 // Potential yield point
4603 CMSTokenSync ts(true);
4604 startTimer();
4605 sample_eden();
4606 // Get dirty region starting at nextOffset (inclusive),
4607 // simultaneously clearing it.
4608 dirtyRegion =
4609 _modUnionTable.getAndClearMarkedRegion(nextAddr, endAddr);
4610 assert(dirtyRegion.start() >= nextAddr,
4611 "returned region inconsistent?");
4612 }
4613 // Remember where the next search should begin.
4614 // The returned region (if non-empty) is a right open interval,
4615 // so lastOffset is obtained from the right end of that
4616 // interval.
4617 lastAddr = dirtyRegion.end();
4618 // Should do something more transparent and less hacky XXX
4619 numDirtyCards =
4620 _modUnionTable.heapWordDiffToOffsetDiff(dirtyRegion.word_size());
4622 // We'll scan the cards in the dirty region (with periodic
4623 // yields for foreground GC as needed).
4624 if (!dirtyRegion.is_empty()) {
4625 assert(numDirtyCards > 0, "consistency check");
4626 HeapWord* stop_point = NULL;
4627 stopTimer();
4628 // Potential yield point
4629 CMSTokenSyncWithLocks ts(true, gen->freelistLock(),
4630 bitMapLock());
4631 startTimer();
4632 {
4633 verify_work_stacks_empty();
4634 verify_overflow_empty();
4635 sample_eden();
4636 DEBUG_ONLY(RememberKlassesChecker mx(CMSClassUnloadingEnabled);)
4637 stop_point =
4638 gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl);
4639 }
4640 if (stop_point != NULL) {
4641 // The careful iteration stopped early either because it found an
4642 // uninitialized object, or because we were in the midst of an
4643 // "abortable preclean", which should now be aborted. Redirty
4644 // the bits corresponding to the partially-scanned or unscanned
4645 // cards. We'll either restart at the next block boundary or
4646 // abort the preclean.
4647 assert((CMSPermGenPrecleaningEnabled && (gen == _permGen)) ||
4648 (_collectorState == AbortablePreclean && should_abort_preclean()),
4649 "Unparsable objects should only be in perm gen.");
4650 _modUnionTable.mark_range(MemRegion(stop_point, dirtyRegion.end()));
4651 if (should_abort_preclean()) {
4652 break; // out of preclean loop
4653 } else {
4654 // Compute the next address at which preclean should pick up;
4655 // might need bitMapLock in order to read P-bits.
4656 lastAddr = next_card_start_after_block(stop_point);
4657 }
4658 }
4659 } else {
4660 assert(lastAddr == endAddr, "consistency check");
4661 assert(numDirtyCards == 0, "consistency check");
4662 break;
4663 }
4664 }
4665 verify_work_stacks_empty();
4666 verify_overflow_empty();
4667 return cumNumDirtyCards;
4668 }
4670 // NOTE: preclean_mod_union_table() above and preclean_card_table()
4671 // below are largely identical; if you need to modify
4672 // one of these methods, please check the other method too.
4674 size_t CMSCollector::preclean_card_table(ConcurrentMarkSweepGeneration* gen,
4675 ScanMarkedObjectsAgainCarefullyClosure* cl) {
4676 // strategy: it's similar to precleamModUnionTable above, in that
4677 // we accumulate contiguous ranges of dirty cards, mark these cards
4678 // precleaned, then scan the region covered by these cards.
4679 HeapWord* endAddr = (HeapWord*)(gen->_virtual_space.high());
4680 HeapWord* startAddr = (HeapWord*)(gen->_virtual_space.low());
4682 cl->setFreelistLock(gen->freelistLock()); // needed for yielding
4684 size_t numDirtyCards, cumNumDirtyCards;
4685 HeapWord *lastAddr, *nextAddr;
4687 for (cumNumDirtyCards = numDirtyCards = 0,
4688 nextAddr = lastAddr = startAddr;
4689 nextAddr < endAddr;
4690 nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) {
4692 ResourceMark rm;
4693 HandleMark hm;
4695 MemRegion dirtyRegion;
4696 {
4697 // See comments in "Precleaning notes" above on why we
4698 // do this locking. XXX Could the locking overheads be
4699 // too high when dirty cards are sparse? [I don't think so.]
4700 stopTimer();
4701 CMSTokenSync x(true); // is cms thread
4702 startTimer();
4703 sample_eden();
4704 // Get and clear dirty region from card table
4705 dirtyRegion = _ct->ct_bs()->dirty_card_range_after_reset(
4706 MemRegion(nextAddr, endAddr),
4707 true,
4708 CardTableModRefBS::precleaned_card_val());
4710 assert(dirtyRegion.start() >= nextAddr,
4711 "returned region inconsistent?");
4712 }
4713 lastAddr = dirtyRegion.end();
4714 numDirtyCards =
4715 dirtyRegion.word_size()/CardTableModRefBS::card_size_in_words;
4717 if (!dirtyRegion.is_empty()) {
4718 stopTimer();
4719 CMSTokenSyncWithLocks ts(true, gen->freelistLock(), bitMapLock());
4720 startTimer();
4721 sample_eden();
4722 verify_work_stacks_empty();
4723 verify_overflow_empty();
4724 DEBUG_ONLY(RememberKlassesChecker mx(CMSClassUnloadingEnabled);)
4725 HeapWord* stop_point =
4726 gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl);
4727 if (stop_point != NULL) {
4728 // The careful iteration stopped early because it found an
4729 // uninitialized object. Redirty the bits corresponding to the
4730 // partially-scanned or unscanned cards, and start again at the
4731 // next block boundary.
4732 assert(CMSPermGenPrecleaningEnabled ||
4733 (_collectorState == AbortablePreclean && should_abort_preclean()),
4734 "Unparsable objects should only be in perm gen.");
4735 _ct->ct_bs()->invalidate(MemRegion(stop_point, dirtyRegion.end()));
4736 if (should_abort_preclean()) {
4737 break; // out of preclean loop
4738 } else {
4739 // Compute the next address at which preclean should pick up.
4740 lastAddr = next_card_start_after_block(stop_point);
4741 }
4742 }
4743 } else {
4744 break;
4745 }
4746 }
4747 verify_work_stacks_empty();
4748 verify_overflow_empty();
4749 return cumNumDirtyCards;
4750 }
4752 void CMSCollector::checkpointRootsFinal(bool asynch,
4753 bool clear_all_soft_refs, bool init_mark_was_synchronous) {
4754 assert(_collectorState == FinalMarking, "incorrect state transition?");
4755 check_correct_thread_executing();
4756 // world is stopped at this checkpoint
4757 assert(SafepointSynchronize::is_at_safepoint(),
4758 "world should be stopped");
4759 verify_work_stacks_empty();
4760 verify_overflow_empty();
4762 SpecializationStats::clear();
4763 if (PrintGCDetails) {
4764 gclog_or_tty->print("[YG occupancy: "SIZE_FORMAT" K ("SIZE_FORMAT" K)]",
4765 _young_gen->used() / K,
4766 _young_gen->capacity() / K);
4767 }
4768 if (asynch) {
4769 if (CMSScavengeBeforeRemark) {
4770 GenCollectedHeap* gch = GenCollectedHeap::heap();
4771 // Temporarily set flag to false, GCH->do_collection will
4772 // expect it to be false and set to true
4773 FlagSetting fl(gch->_is_gc_active, false);
4774 NOT_PRODUCT(TraceTime t("Scavenge-Before-Remark",
4775 PrintGCDetails && Verbose, true, gclog_or_tty);)
4776 int level = _cmsGen->level() - 1;
4777 if (level >= 0) {
4778 gch->do_collection(true, // full (i.e. force, see below)
4779 false, // !clear_all_soft_refs
4780 0, // size
4781 false, // is_tlab
4782 level // max_level
4783 );
4784 }
4785 }
4786 FreelistLocker x(this);
4787 MutexLockerEx y(bitMapLock(),
4788 Mutex::_no_safepoint_check_flag);
4789 assert(!init_mark_was_synchronous, "but that's impossible!");
4790 checkpointRootsFinalWork(asynch, clear_all_soft_refs, false);
4791 } else {
4792 // already have all the locks
4793 checkpointRootsFinalWork(asynch, clear_all_soft_refs,
4794 init_mark_was_synchronous);
4795 }
4796 verify_work_stacks_empty();
4797 verify_overflow_empty();
4798 SpecializationStats::print();
4799 }
4801 void CMSCollector::checkpointRootsFinalWork(bool asynch,
4802 bool clear_all_soft_refs, bool init_mark_was_synchronous) {
4804 NOT_PRODUCT(TraceTime tr("checkpointRootsFinalWork", PrintGCDetails, false, gclog_or_tty);)
4806 assert(haveFreelistLocks(), "must have free list locks");
4807 assert_lock_strong(bitMapLock());
4809 if (UseAdaptiveSizePolicy) {
4810 size_policy()->checkpoint_roots_final_begin();
4811 }
4813 ResourceMark rm;
4814 HandleMark hm;
4816 GenCollectedHeap* gch = GenCollectedHeap::heap();
4818 if (should_unload_classes()) {
4819 CodeCache::gc_prologue();
4820 }
4821 assert(haveFreelistLocks(), "must have free list locks");
4822 assert_lock_strong(bitMapLock());
4824 DEBUG_ONLY(RememberKlassesChecker fmx(CMSClassUnloadingEnabled);)
4825 if (!init_mark_was_synchronous) {
4826 // We might assume that we need not fill TLAB's when
4827 // CMSScavengeBeforeRemark is set, because we may have just done
4828 // a scavenge which would have filled all TLAB's -- and besides
4829 // Eden would be empty. This however may not always be the case --
4830 // for instance although we asked for a scavenge, it may not have
4831 // happened because of a JNI critical section. We probably need
4832 // a policy for deciding whether we can in that case wait until
4833 // the critical section releases and then do the remark following
4834 // the scavenge, and skip it here. In the absence of that policy,
4835 // or of an indication of whether the scavenge did indeed occur,
4836 // we cannot rely on TLAB's having been filled and must do
4837 // so here just in case a scavenge did not happen.
4838 gch->ensure_parsability(false); // fill TLAB's, but no need to retire them
4839 // Update the saved marks which may affect the root scans.
4840 gch->save_marks();
4842 {
4843 COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
4845 // Note on the role of the mod union table:
4846 // Since the marker in "markFromRoots" marks concurrently with
4847 // mutators, it is possible for some reachable objects not to have been
4848 // scanned. For instance, an only reference to an object A was
4849 // placed in object B after the marker scanned B. Unless B is rescanned,
4850 // A would be collected. Such updates to references in marked objects
4851 // are detected via the mod union table which is the set of all cards
4852 // dirtied since the first checkpoint in this GC cycle and prior to
4853 // the most recent young generation GC, minus those cleaned up by the
4854 // concurrent precleaning.
4855 if (CMSParallelRemarkEnabled && ParallelGCThreads > 0) {
4856 TraceTime t("Rescan (parallel) ", PrintGCDetails, false, gclog_or_tty);
4857 do_remark_parallel();
4858 } else {
4859 TraceTime t("Rescan (non-parallel) ", PrintGCDetails, false,
4860 gclog_or_tty);
4861 do_remark_non_parallel();
4862 }
4863 }
4864 } else {
4865 assert(!asynch, "Can't have init_mark_was_synchronous in asynch mode");
4866 // The initial mark was stop-world, so there's no rescanning to
4867 // do; go straight on to the next step below.
4868 }
4869 verify_work_stacks_empty();
4870 verify_overflow_empty();
4872 {
4873 NOT_PRODUCT(TraceTime ts("refProcessingWork", PrintGCDetails, false, gclog_or_tty);)
4874 refProcessingWork(asynch, clear_all_soft_refs);
4875 }
4876 verify_work_stacks_empty();
4877 verify_overflow_empty();
4879 if (should_unload_classes()) {
4880 CodeCache::gc_epilogue();
4881 }
4883 // If we encountered any (marking stack / work queue) overflow
4884 // events during the current CMS cycle, take appropriate
4885 // remedial measures, where possible, so as to try and avoid
4886 // recurrence of that condition.
4887 assert(_markStack.isEmpty(), "No grey objects");
4888 size_t ser_ovflw = _ser_pmc_remark_ovflw + _ser_pmc_preclean_ovflw +
4889 _ser_kac_ovflw + _ser_kac_preclean_ovflw;
4890 if (ser_ovflw > 0) {
4891 if (PrintCMSStatistics != 0) {
4892 gclog_or_tty->print_cr("Marking stack overflow (benign) "
4893 "(pmc_pc="SIZE_FORMAT", pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT
4894 ", kac_preclean="SIZE_FORMAT")",
4895 _ser_pmc_preclean_ovflw, _ser_pmc_remark_ovflw,
4896 _ser_kac_ovflw, _ser_kac_preclean_ovflw);
4897 }
4898 _markStack.expand();
4899 _ser_pmc_remark_ovflw = 0;
4900 _ser_pmc_preclean_ovflw = 0;
4901 _ser_kac_preclean_ovflw = 0;
4902 _ser_kac_ovflw = 0;
4903 }
4904 if (_par_pmc_remark_ovflw > 0 || _par_kac_ovflw > 0) {
4905 if (PrintCMSStatistics != 0) {
4906 gclog_or_tty->print_cr("Work queue overflow (benign) "
4907 "(pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT")",
4908 _par_pmc_remark_ovflw, _par_kac_ovflw);
4909 }
4910 _par_pmc_remark_ovflw = 0;
4911 _par_kac_ovflw = 0;
4912 }
4913 if (PrintCMSStatistics != 0) {
4914 if (_markStack._hit_limit > 0) {
4915 gclog_or_tty->print_cr(" (benign) Hit max stack size limit ("SIZE_FORMAT")",
4916 _markStack._hit_limit);
4917 }
4918 if (_markStack._failed_double > 0) {
4919 gclog_or_tty->print_cr(" (benign) Failed stack doubling ("SIZE_FORMAT"),"
4920 " current capacity "SIZE_FORMAT,
4921 _markStack._failed_double,
4922 _markStack.capacity());
4923 }
4924 }
4925 _markStack._hit_limit = 0;
4926 _markStack._failed_double = 0;
4928 // Check that all the klasses have been checked
4929 assert(_revisitStack.isEmpty(), "Not all klasses revisited");
4931 if ((VerifyAfterGC || VerifyDuringGC) &&
4932 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
4933 verify_after_remark();
4934 }
4936 // Change under the freelistLocks.
4937 _collectorState = Sweeping;
4938 // Call isAllClear() under bitMapLock
4939 assert(_modUnionTable.isAllClear(), "Should be clear by end of the"
4940 " final marking");
4941 if (UseAdaptiveSizePolicy) {
4942 size_policy()->checkpoint_roots_final_end(gch->gc_cause());
4943 }
4944 }
4946 // Parallel remark task
4947 class CMSParRemarkTask: public AbstractGangTask {
4948 CMSCollector* _collector;
4949 WorkGang* _workers;
4950 int _n_workers;
4951 CompactibleFreeListSpace* _cms_space;
4952 CompactibleFreeListSpace* _perm_space;
4954 // The per-thread work queues, available here for stealing.
4955 OopTaskQueueSet* _task_queues;
4956 ParallelTaskTerminator _term;
4958 public:
4959 CMSParRemarkTask(CMSCollector* collector,
4960 CompactibleFreeListSpace* cms_space,
4961 CompactibleFreeListSpace* perm_space,
4962 int n_workers, WorkGang* workers,
4963 OopTaskQueueSet* task_queues):
4964 AbstractGangTask("Rescan roots and grey objects in parallel"),
4965 _collector(collector),
4966 _cms_space(cms_space), _perm_space(perm_space),
4967 _n_workers(n_workers),
4968 _workers(workers),
4969 _task_queues(task_queues),
4970 _term(workers->total_workers(), task_queues) { }
4972 OopTaskQueueSet* task_queues() { return _task_queues; }
4974 OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
4976 ParallelTaskTerminator* terminator() { return &_term; }
4978 void work(int i);
4980 private:
4981 // Work method in support of parallel rescan ... of young gen spaces
4982 void do_young_space_rescan(int i, Par_MarkRefsIntoAndScanClosure* cl,
4983 ContiguousSpace* space,
4984 HeapWord** chunk_array, size_t chunk_top);
4986 // ... of dirty cards in old space
4987 void do_dirty_card_rescan_tasks(CompactibleFreeListSpace* sp, int i,
4988 Par_MarkRefsIntoAndScanClosure* cl);
4990 // ... work stealing for the above
4991 void do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl, int* seed);
4992 };
4994 void CMSParRemarkTask::work(int i) {
4995 elapsedTimer _timer;
4996 ResourceMark rm;
4997 HandleMark hm;
4999 // ---------- rescan from roots --------------
5000 _timer.start();
5001 GenCollectedHeap* gch = GenCollectedHeap::heap();
5002 Par_MarkRefsIntoAndScanClosure par_mrias_cl(_collector,
5003 _collector->_span, _collector->ref_processor(),
5004 &(_collector->_markBitMap),
5005 work_queue(i), &(_collector->_revisitStack));
5007 // Rescan young gen roots first since these are likely
5008 // coarsely partitioned and may, on that account, constitute
5009 // the critical path; thus, it's best to start off that
5010 // work first.
5011 // ---------- young gen roots --------------
5012 {
5013 DefNewGeneration* dng = _collector->_young_gen->as_DefNewGeneration();
5014 EdenSpace* eden_space = dng->eden();
5015 ContiguousSpace* from_space = dng->from();
5016 ContiguousSpace* to_space = dng->to();
5018 HeapWord** eca = _collector->_eden_chunk_array;
5019 size_t ect = _collector->_eden_chunk_index;
5020 HeapWord** sca = _collector->_survivor_chunk_array;
5021 size_t sct = _collector->_survivor_chunk_index;
5023 assert(ect <= _collector->_eden_chunk_capacity, "out of bounds");
5024 assert(sct <= _collector->_survivor_chunk_capacity, "out of bounds");
5026 do_young_space_rescan(i, &par_mrias_cl, to_space, NULL, 0);
5027 do_young_space_rescan(i, &par_mrias_cl, from_space, sca, sct);
5028 do_young_space_rescan(i, &par_mrias_cl, eden_space, eca, ect);
5030 _timer.stop();
5031 if (PrintCMSStatistics != 0) {
5032 gclog_or_tty->print_cr(
5033 "Finished young gen rescan work in %dth thread: %3.3f sec",
5034 i, _timer.seconds());
5035 }
5036 }
5038 // ---------- remaining roots --------------
5039 _timer.reset();
5040 _timer.start();
5041 gch->gen_process_strong_roots(_collector->_cmsGen->level(),
5042 false, // yg was scanned above
5043 true, // collecting perm gen
5044 SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
5045 NULL, &par_mrias_cl);
5046 _timer.stop();
5047 if (PrintCMSStatistics != 0) {
5048 gclog_or_tty->print_cr(
5049 "Finished remaining root rescan work in %dth thread: %3.3f sec",
5050 i, _timer.seconds());
5051 }
5053 // ---------- rescan dirty cards ------------
5054 _timer.reset();
5055 _timer.start();
5057 // Do the rescan tasks for each of the two spaces
5058 // (cms_space and perm_space) in turn.
5059 do_dirty_card_rescan_tasks(_cms_space, i, &par_mrias_cl);
5060 do_dirty_card_rescan_tasks(_perm_space, i, &par_mrias_cl);
5061 _timer.stop();
5062 if (PrintCMSStatistics != 0) {
5063 gclog_or_tty->print_cr(
5064 "Finished dirty card rescan work in %dth thread: %3.3f sec",
5065 i, _timer.seconds());
5066 }
5068 // ---------- steal work from other threads ...
5069 // ---------- ... and drain overflow list.
5070 _timer.reset();
5071 _timer.start();
5072 do_work_steal(i, &par_mrias_cl, _collector->hash_seed(i));
5073 _timer.stop();
5074 if (PrintCMSStatistics != 0) {
5075 gclog_or_tty->print_cr(
5076 "Finished work stealing in %dth thread: %3.3f sec",
5077 i, _timer.seconds());
5078 }
5079 }
5081 void
5082 CMSParRemarkTask::do_young_space_rescan(int i,
5083 Par_MarkRefsIntoAndScanClosure* cl, ContiguousSpace* space,
5084 HeapWord** chunk_array, size_t chunk_top) {
5085 // Until all tasks completed:
5086 // . claim an unclaimed task
5087 // . compute region boundaries corresponding to task claimed
5088 // using chunk_array
5089 // . par_oop_iterate(cl) over that region
5091 ResourceMark rm;
5092 HandleMark hm;
5094 SequentialSubTasksDone* pst = space->par_seq_tasks();
5095 assert(pst->valid(), "Uninitialized use?");
5097 int nth_task = 0;
5098 int n_tasks = pst->n_tasks();
5100 HeapWord *start, *end;
5101 while (!pst->is_task_claimed(/* reference */ nth_task)) {
5102 // We claimed task # nth_task; compute its boundaries.
5103 if (chunk_top == 0) { // no samples were taken
5104 assert(nth_task == 0 && n_tasks == 1, "Can have only 1 EdenSpace task");
5105 start = space->bottom();
5106 end = space->top();
5107 } else if (nth_task == 0) {
5108 start = space->bottom();
5109 end = chunk_array[nth_task];
5110 } else if (nth_task < (jint)chunk_top) {
5111 assert(nth_task >= 1, "Control point invariant");
5112 start = chunk_array[nth_task - 1];
5113 end = chunk_array[nth_task];
5114 } else {
5115 assert(nth_task == (jint)chunk_top, "Control point invariant");
5116 start = chunk_array[chunk_top - 1];
5117 end = space->top();
5118 }
5119 MemRegion mr(start, end);
5120 // Verify that mr is in space
5121 assert(mr.is_empty() || space->used_region().contains(mr),
5122 "Should be in space");
5123 // Verify that "start" is an object boundary
5124 assert(mr.is_empty() || oop(mr.start())->is_oop(),
5125 "Should be an oop");
5126 space->par_oop_iterate(mr, cl);
5127 }
5128 pst->all_tasks_completed();
5129 }
5131 void
5132 CMSParRemarkTask::do_dirty_card_rescan_tasks(
5133 CompactibleFreeListSpace* sp, int i,
5134 Par_MarkRefsIntoAndScanClosure* cl) {
5135 // Until all tasks completed:
5136 // . claim an unclaimed task
5137 // . compute region boundaries corresponding to task claimed
5138 // . transfer dirty bits ct->mut for that region
5139 // . apply rescanclosure to dirty mut bits for that region
5141 ResourceMark rm;
5142 HandleMark hm;
5144 OopTaskQueue* work_q = work_queue(i);
5145 ModUnionClosure modUnionClosure(&(_collector->_modUnionTable));
5146 // CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION!
5147 // CAUTION: This closure has state that persists across calls to
5148 // the work method dirty_range_iterate_clear() in that it has
5149 // imbedded in it a (subtype of) UpwardsObjectClosure. The
5150 // use of that state in the imbedded UpwardsObjectClosure instance
5151 // assumes that the cards are always iterated (even if in parallel
5152 // by several threads) in monotonically increasing order per each
5153 // thread. This is true of the implementation below which picks
5154 // card ranges (chunks) in monotonically increasing order globally
5155 // and, a-fortiori, in monotonically increasing order per thread
5156 // (the latter order being a subsequence of the former).
5157 // If the work code below is ever reorganized into a more chaotic
5158 // work-partitioning form than the current "sequential tasks"
5159 // paradigm, the use of that persistent state will have to be
5160 // revisited and modified appropriately. See also related
5161 // bug 4756801 work on which should examine this code to make
5162 // sure that the changes there do not run counter to the
5163 // assumptions made here and necessary for correctness and
5164 // efficiency. Note also that this code might yield inefficient
5165 // behaviour in the case of very large objects that span one or
5166 // more work chunks. Such objects would potentially be scanned
5167 // several times redundantly. Work on 4756801 should try and
5168 // address that performance anomaly if at all possible. XXX
5169 MemRegion full_span = _collector->_span;
5170 CMSBitMap* bm = &(_collector->_markBitMap); // shared
5171 CMSMarkStack* rs = &(_collector->_revisitStack); // shared
5172 MarkFromDirtyCardsClosure
5173 greyRescanClosure(_collector, full_span, // entire span of interest
5174 sp, bm, work_q, rs, cl);
5176 SequentialSubTasksDone* pst = sp->conc_par_seq_tasks();
5177 assert(pst->valid(), "Uninitialized use?");
5178 int nth_task = 0;
5179 const int alignment = CardTableModRefBS::card_size * BitsPerWord;
5180 MemRegion span = sp->used_region();
5181 HeapWord* start_addr = span.start();
5182 HeapWord* end_addr = (HeapWord*)round_to((intptr_t)span.end(),
5183 alignment);
5184 const size_t chunk_size = sp->rescan_task_size(); // in HeapWord units
5185 assert((HeapWord*)round_to((intptr_t)start_addr, alignment) ==
5186 start_addr, "Check alignment");
5187 assert((size_t)round_to((intptr_t)chunk_size, alignment) ==
5188 chunk_size, "Check alignment");
5190 while (!pst->is_task_claimed(/* reference */ nth_task)) {
5191 // Having claimed the nth_task, compute corresponding mem-region,
5192 // which is a-fortiori aligned correctly (i.e. at a MUT bopundary).
5193 // The alignment restriction ensures that we do not need any
5194 // synchronization with other gang-workers while setting or
5195 // clearing bits in thus chunk of the MUT.
5196 MemRegion this_span = MemRegion(start_addr + nth_task*chunk_size,
5197 start_addr + (nth_task+1)*chunk_size);
5198 // The last chunk's end might be way beyond end of the
5199 // used region. In that case pull back appropriately.
5200 if (this_span.end() > end_addr) {
5201 this_span.set_end(end_addr);
5202 assert(!this_span.is_empty(), "Program logic (calculation of n_tasks)");
5203 }
5204 // Iterate over the dirty cards covering this chunk, marking them
5205 // precleaned, and setting the corresponding bits in the mod union
5206 // table. Since we have been careful to partition at Card and MUT-word
5207 // boundaries no synchronization is needed between parallel threads.
5208 _collector->_ct->ct_bs()->dirty_card_iterate(this_span,
5209 &modUnionClosure);
5211 // Having transferred these marks into the modUnionTable,
5212 // rescan the marked objects on the dirty cards in the modUnionTable.
5213 // Even if this is at a synchronous collection, the initial marking
5214 // may have been done during an asynchronous collection so there
5215 // may be dirty bits in the mod-union table.
5216 _collector->_modUnionTable.dirty_range_iterate_clear(
5217 this_span, &greyRescanClosure);
5218 _collector->_modUnionTable.verifyNoOneBitsInRange(
5219 this_span.start(),
5220 this_span.end());
5221 }
5222 pst->all_tasks_completed(); // declare that i am done
5223 }
5225 // . see if we can share work_queues with ParNew? XXX
5226 void
5227 CMSParRemarkTask::do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl,
5228 int* seed) {
5229 OopTaskQueue* work_q = work_queue(i);
5230 NOT_PRODUCT(int num_steals = 0;)
5231 oop obj_to_scan;
5232 CMSBitMap* bm = &(_collector->_markBitMap);
5234 while (true) {
5235 // Completely finish any left over work from (an) earlier round(s)
5236 cl->trim_queue(0);
5237 size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
5238 (size_t)ParGCDesiredObjsFromOverflowList);
5239 // Now check if there's any work in the overflow list
5240 if (_collector->par_take_from_overflow_list(num_from_overflow_list,
5241 work_q)) {
5242 // found something in global overflow list;
5243 // not yet ready to go stealing work from others.
5244 // We'd like to assert(work_q->size() != 0, ...)
5245 // because we just took work from the overflow list,
5246 // but of course we can't since all of that could have
5247 // been already stolen from us.
5248 // "He giveth and He taketh away."
5249 continue;
5250 }
5251 // Verify that we have no work before we resort to stealing
5252 assert(work_q->size() == 0, "Have work, shouldn't steal");
5253 // Try to steal from other queues that have work
5254 if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
5255 NOT_PRODUCT(num_steals++;)
5256 assert(obj_to_scan->is_oop(), "Oops, not an oop!");
5257 assert(bm->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?");
5258 // Do scanning work
5259 obj_to_scan->oop_iterate(cl);
5260 // Loop around, finish this work, and try to steal some more
5261 } else if (terminator()->offer_termination()) {
5262 break; // nirvana from the infinite cycle
5263 }
5264 }
5265 NOT_PRODUCT(
5266 if (PrintCMSStatistics != 0) {
5267 gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals);
5268 }
5269 )
5270 assert(work_q->size() == 0 && _collector->overflow_list_is_empty(),
5271 "Else our work is not yet done");
5272 }
5274 // Return a thread-local PLAB recording array, as appropriate.
5275 void* CMSCollector::get_data_recorder(int thr_num) {
5276 if (_survivor_plab_array != NULL &&
5277 (CMSPLABRecordAlways ||
5278 (_collectorState > Marking && _collectorState < FinalMarking))) {
5279 assert(thr_num < (int)ParallelGCThreads, "thr_num is out of bounds");
5280 ChunkArray* ca = &_survivor_plab_array[thr_num];
5281 ca->reset(); // clear it so that fresh data is recorded
5282 return (void*) ca;
5283 } else {
5284 return NULL;
5285 }
5286 }
5288 // Reset all the thread-local PLAB recording arrays
5289 void CMSCollector::reset_survivor_plab_arrays() {
5290 for (uint i = 0; i < ParallelGCThreads; i++) {
5291 _survivor_plab_array[i].reset();
5292 }
5293 }
5295 // Merge the per-thread plab arrays into the global survivor chunk
5296 // array which will provide the partitioning of the survivor space
5297 // for CMS rescan.
5298 void CMSCollector::merge_survivor_plab_arrays(ContiguousSpace* surv) {
5299 assert(_survivor_plab_array != NULL, "Error");
5300 assert(_survivor_chunk_array != NULL, "Error");
5301 assert(_collectorState == FinalMarking, "Error");
5302 for (uint j = 0; j < ParallelGCThreads; j++) {
5303 _cursor[j] = 0;
5304 }
5305 HeapWord* top = surv->top();
5306 size_t i;
5307 for (i = 0; i < _survivor_chunk_capacity; i++) { // all sca entries
5308 HeapWord* min_val = top; // Higher than any PLAB address
5309 uint min_tid = 0; // position of min_val this round
5310 for (uint j = 0; j < ParallelGCThreads; j++) {
5311 ChunkArray* cur_sca = &_survivor_plab_array[j];
5312 if (_cursor[j] == cur_sca->end()) {
5313 continue;
5314 }
5315 assert(_cursor[j] < cur_sca->end(), "ctl pt invariant");
5316 HeapWord* cur_val = cur_sca->nth(_cursor[j]);
5317 assert(surv->used_region().contains(cur_val), "Out of bounds value");
5318 if (cur_val < min_val) {
5319 min_tid = j;
5320 min_val = cur_val;
5321 } else {
5322 assert(cur_val < top, "All recorded addresses should be less");
5323 }
5324 }
5325 // At this point min_val and min_tid are respectively
5326 // the least address in _survivor_plab_array[j]->nth(_cursor[j])
5327 // and the thread (j) that witnesses that address.
5328 // We record this address in the _survivor_chunk_array[i]
5329 // and increment _cursor[min_tid] prior to the next round i.
5330 if (min_val == top) {
5331 break;
5332 }
5333 _survivor_chunk_array[i] = min_val;
5334 _cursor[min_tid]++;
5335 }
5336 // We are all done; record the size of the _survivor_chunk_array
5337 _survivor_chunk_index = i; // exclusive: [0, i)
5338 if (PrintCMSStatistics > 0) {
5339 gclog_or_tty->print(" (Survivor:" SIZE_FORMAT "chunks) ", i);
5340 }
5341 // Verify that we used up all the recorded entries
5342 #ifdef ASSERT
5343 size_t total = 0;
5344 for (uint j = 0; j < ParallelGCThreads; j++) {
5345 assert(_cursor[j] == _survivor_plab_array[j].end(), "Ctl pt invariant");
5346 total += _cursor[j];
5347 }
5348 assert(total == _survivor_chunk_index, "Ctl Pt Invariant");
5349 // Check that the merged array is in sorted order
5350 if (total > 0) {
5351 for (size_t i = 0; i < total - 1; i++) {
5352 if (PrintCMSStatistics > 0) {
5353 gclog_or_tty->print(" (chunk" SIZE_FORMAT ":" INTPTR_FORMAT ") ",
5354 i, _survivor_chunk_array[i]);
5355 }
5356 assert(_survivor_chunk_array[i] < _survivor_chunk_array[i+1],
5357 "Not sorted");
5358 }
5359 }
5360 #endif // ASSERT
5361 }
5363 // Set up the space's par_seq_tasks structure for work claiming
5364 // for parallel rescan of young gen.
5365 // See ParRescanTask where this is currently used.
5366 void
5367 CMSCollector::
5368 initialize_sequential_subtasks_for_young_gen_rescan(int n_threads) {
5369 assert(n_threads > 0, "Unexpected n_threads argument");
5370 DefNewGeneration* dng = (DefNewGeneration*)_young_gen;
5372 // Eden space
5373 {
5374 SequentialSubTasksDone* pst = dng->eden()->par_seq_tasks();
5375 assert(!pst->valid(), "Clobbering existing data?");
5376 // Each valid entry in [0, _eden_chunk_index) represents a task.
5377 size_t n_tasks = _eden_chunk_index + 1;
5378 assert(n_tasks == 1 || _eden_chunk_array != NULL, "Error");
5379 pst->set_par_threads(n_threads);
5380 pst->set_n_tasks((int)n_tasks);
5381 }
5383 // Merge the survivor plab arrays into _survivor_chunk_array
5384 if (_survivor_plab_array != NULL) {
5385 merge_survivor_plab_arrays(dng->from());
5386 } else {
5387 assert(_survivor_chunk_index == 0, "Error");
5388 }
5390 // To space
5391 {
5392 SequentialSubTasksDone* pst = dng->to()->par_seq_tasks();
5393 assert(!pst->valid(), "Clobbering existing data?");
5394 pst->set_par_threads(n_threads);
5395 pst->set_n_tasks(1);
5396 assert(pst->valid(), "Error");
5397 }
5399 // From space
5400 {
5401 SequentialSubTasksDone* pst = dng->from()->par_seq_tasks();
5402 assert(!pst->valid(), "Clobbering existing data?");
5403 size_t n_tasks = _survivor_chunk_index + 1;
5404 assert(n_tasks == 1 || _survivor_chunk_array != NULL, "Error");
5405 pst->set_par_threads(n_threads);
5406 pst->set_n_tasks((int)n_tasks);
5407 assert(pst->valid(), "Error");
5408 }
5409 }
5411 // Parallel version of remark
5412 void CMSCollector::do_remark_parallel() {
5413 GenCollectedHeap* gch = GenCollectedHeap::heap();
5414 WorkGang* workers = gch->workers();
5415 assert(workers != NULL, "Need parallel worker threads.");
5416 int n_workers = workers->total_workers();
5417 CompactibleFreeListSpace* cms_space = _cmsGen->cmsSpace();
5418 CompactibleFreeListSpace* perm_space = _permGen->cmsSpace();
5420 CMSParRemarkTask tsk(this,
5421 cms_space, perm_space,
5422 n_workers, workers, task_queues());
5424 // Set up for parallel process_strong_roots work.
5425 gch->set_par_threads(n_workers);
5426 gch->change_strong_roots_parity();
5427 // We won't be iterating over the cards in the card table updating
5428 // the younger_gen cards, so we shouldn't call the following else
5429 // the verification code as well as subsequent younger_refs_iterate
5430 // code would get confused. XXX
5431 // gch->rem_set()->prepare_for_younger_refs_iterate(true); // parallel
5433 // The young gen rescan work will not be done as part of
5434 // process_strong_roots (which currently doesn't knw how to
5435 // parallelize such a scan), but rather will be broken up into
5436 // a set of parallel tasks (via the sampling that the [abortable]
5437 // preclean phase did of EdenSpace, plus the [two] tasks of
5438 // scanning the [two] survivor spaces. Further fine-grain
5439 // parallelization of the scanning of the survivor spaces
5440 // themselves, and of precleaning of the younger gen itself
5441 // is deferred to the future.
5442 initialize_sequential_subtasks_for_young_gen_rescan(n_workers);
5444 // The dirty card rescan work is broken up into a "sequence"
5445 // of parallel tasks (per constituent space) that are dynamically
5446 // claimed by the parallel threads.
5447 cms_space->initialize_sequential_subtasks_for_rescan(n_workers);
5448 perm_space->initialize_sequential_subtasks_for_rescan(n_workers);
5450 // It turns out that even when we're using 1 thread, doing the work in a
5451 // separate thread causes wide variance in run times. We can't help this
5452 // in the multi-threaded case, but we special-case n=1 here to get
5453 // repeatable measurements of the 1-thread overhead of the parallel code.
5454 if (n_workers > 1) {
5455 // Make refs discovery MT-safe
5456 ReferenceProcessorMTMutator mt(ref_processor(), true);
5457 workers->run_task(&tsk);
5458 } else {
5459 tsk.work(0);
5460 }
5461 gch->set_par_threads(0); // 0 ==> non-parallel.
5462 // restore, single-threaded for now, any preserved marks
5463 // as a result of work_q overflow
5464 restore_preserved_marks_if_any();
5465 }
5467 // Non-parallel version of remark
5468 void CMSCollector::do_remark_non_parallel() {
5469 ResourceMark rm;
5470 HandleMark hm;
5471 GenCollectedHeap* gch = GenCollectedHeap::heap();
5472 MarkRefsIntoAndScanClosure
5473 mrias_cl(_span, ref_processor(), &_markBitMap, &_modUnionTable,
5474 &_markStack, &_revisitStack, this,
5475 false /* should_yield */, false /* not precleaning */);
5476 MarkFromDirtyCardsClosure
5477 markFromDirtyCardsClosure(this, _span,
5478 NULL, // space is set further below
5479 &_markBitMap, &_markStack, &_revisitStack,
5480 &mrias_cl);
5481 {
5482 TraceTime t("grey object rescan", PrintGCDetails, false, gclog_or_tty);
5483 // Iterate over the dirty cards, setting the corresponding bits in the
5484 // mod union table.
5485 {
5486 ModUnionClosure modUnionClosure(&_modUnionTable);
5487 _ct->ct_bs()->dirty_card_iterate(
5488 _cmsGen->used_region(),
5489 &modUnionClosure);
5490 _ct->ct_bs()->dirty_card_iterate(
5491 _permGen->used_region(),
5492 &modUnionClosure);
5493 }
5494 // Having transferred these marks into the modUnionTable, we just need
5495 // to rescan the marked objects on the dirty cards in the modUnionTable.
5496 // The initial marking may have been done during an asynchronous
5497 // collection so there may be dirty bits in the mod-union table.
5498 const int alignment =
5499 CardTableModRefBS::card_size * BitsPerWord;
5500 {
5501 // ... First handle dirty cards in CMS gen
5502 markFromDirtyCardsClosure.set_space(_cmsGen->cmsSpace());
5503 MemRegion ur = _cmsGen->used_region();
5504 HeapWord* lb = ur.start();
5505 HeapWord* ub = (HeapWord*)round_to((intptr_t)ur.end(), alignment);
5506 MemRegion cms_span(lb, ub);
5507 _modUnionTable.dirty_range_iterate_clear(cms_span,
5508 &markFromDirtyCardsClosure);
5509 verify_work_stacks_empty();
5510 if (PrintCMSStatistics != 0) {
5511 gclog_or_tty->print(" (re-scanned "SIZE_FORMAT" dirty cards in cms gen) ",
5512 markFromDirtyCardsClosure.num_dirty_cards());
5513 }
5514 }
5515 {
5516 // .. and then repeat for dirty cards in perm gen
5517 markFromDirtyCardsClosure.set_space(_permGen->cmsSpace());
5518 MemRegion ur = _permGen->used_region();
5519 HeapWord* lb = ur.start();
5520 HeapWord* ub = (HeapWord*)round_to((intptr_t)ur.end(), alignment);
5521 MemRegion perm_span(lb, ub);
5522 _modUnionTable.dirty_range_iterate_clear(perm_span,
5523 &markFromDirtyCardsClosure);
5524 verify_work_stacks_empty();
5525 if (PrintCMSStatistics != 0) {
5526 gclog_or_tty->print(" (re-scanned "SIZE_FORMAT" dirty cards in perm gen) ",
5527 markFromDirtyCardsClosure.num_dirty_cards());
5528 }
5529 }
5530 }
5531 if (VerifyDuringGC &&
5532 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
5533 HandleMark hm; // Discard invalid handles created during verification
5534 Universe::verify(true);
5535 }
5536 {
5537 TraceTime t("root rescan", PrintGCDetails, false, gclog_or_tty);
5539 verify_work_stacks_empty();
5541 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
5542 gch->gen_process_strong_roots(_cmsGen->level(),
5543 true, // younger gens as roots
5544 true, // collecting perm gen
5545 SharedHeap::ScanningOption(roots_scanning_options()),
5546 NULL, &mrias_cl);
5547 }
5548 verify_work_stacks_empty();
5549 // Restore evacuated mark words, if any, used for overflow list links
5550 if (!CMSOverflowEarlyRestoration) {
5551 restore_preserved_marks_if_any();
5552 }
5553 verify_overflow_empty();
5554 }
5556 ////////////////////////////////////////////////////////
5557 // Parallel Reference Processing Task Proxy Class
5558 ////////////////////////////////////////////////////////
5559 class CMSRefProcTaskProxy: public AbstractGangTask {
5560 typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
5561 CMSCollector* _collector;
5562 CMSBitMap* _mark_bit_map;
5563 const MemRegion _span;
5564 OopTaskQueueSet* _task_queues;
5565 ParallelTaskTerminator _term;
5566 ProcessTask& _task;
5568 public:
5569 CMSRefProcTaskProxy(ProcessTask& task,
5570 CMSCollector* collector,
5571 const MemRegion& span,
5572 CMSBitMap* mark_bit_map,
5573 int total_workers,
5574 OopTaskQueueSet* task_queues):
5575 AbstractGangTask("Process referents by policy in parallel"),
5576 _task(task),
5577 _collector(collector), _span(span), _mark_bit_map(mark_bit_map),
5578 _task_queues(task_queues),
5579 _term(total_workers, task_queues)
5580 {
5581 assert(_collector->_span.equals(_span) && !_span.is_empty(),
5582 "Inconsistency in _span");
5583 }
5585 OopTaskQueueSet* task_queues() { return _task_queues; }
5587 OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
5589 ParallelTaskTerminator* terminator() { return &_term; }
5591 void do_work_steal(int i,
5592 CMSParDrainMarkingStackClosure* drain,
5593 CMSParKeepAliveClosure* keep_alive,
5594 int* seed);
5596 virtual void work(int i);
5597 };
5599 void CMSRefProcTaskProxy::work(int i) {
5600 assert(_collector->_span.equals(_span), "Inconsistency in _span");
5601 CMSParKeepAliveClosure par_keep_alive(_collector, _span,
5602 _mark_bit_map,
5603 &_collector->_revisitStack,
5604 work_queue(i));
5605 CMSParDrainMarkingStackClosure par_drain_stack(_collector, _span,
5606 _mark_bit_map,
5607 &_collector->_revisitStack,
5608 work_queue(i));
5609 CMSIsAliveClosure is_alive_closure(_span, _mark_bit_map);
5610 _task.work(i, is_alive_closure, par_keep_alive, par_drain_stack);
5611 if (_task.marks_oops_alive()) {
5612 do_work_steal(i, &par_drain_stack, &par_keep_alive,
5613 _collector->hash_seed(i));
5614 }
5615 assert(work_queue(i)->size() == 0, "work_queue should be empty");
5616 assert(_collector->_overflow_list == NULL, "non-empty _overflow_list");
5617 }
5619 class CMSRefEnqueueTaskProxy: public AbstractGangTask {
5620 typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
5621 EnqueueTask& _task;
5623 public:
5624 CMSRefEnqueueTaskProxy(EnqueueTask& task)
5625 : AbstractGangTask("Enqueue reference objects in parallel"),
5626 _task(task)
5627 { }
5629 virtual void work(int i)
5630 {
5631 _task.work(i);
5632 }
5633 };
5635 CMSParKeepAliveClosure::CMSParKeepAliveClosure(CMSCollector* collector,
5636 MemRegion span, CMSBitMap* bit_map, CMSMarkStack* revisit_stack,
5637 OopTaskQueue* work_queue):
5638 Par_KlassRememberingOopClosure(collector, NULL, revisit_stack),
5639 _span(span),
5640 _bit_map(bit_map),
5641 _work_queue(work_queue),
5642 _mark_and_push(collector, span, bit_map, revisit_stack, work_queue),
5643 _low_water_mark(MIN2((uint)(work_queue->max_elems()/4),
5644 (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads)))
5645 { }
5647 // . see if we can share work_queues with ParNew? XXX
5648 void CMSRefProcTaskProxy::do_work_steal(int i,
5649 CMSParDrainMarkingStackClosure* drain,
5650 CMSParKeepAliveClosure* keep_alive,
5651 int* seed) {
5652 OopTaskQueue* work_q = work_queue(i);
5653 NOT_PRODUCT(int num_steals = 0;)
5654 oop obj_to_scan;
5656 while (true) {
5657 // Completely finish any left over work from (an) earlier round(s)
5658 drain->trim_queue(0);
5659 size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
5660 (size_t)ParGCDesiredObjsFromOverflowList);
5661 // Now check if there's any work in the overflow list
5662 if (_collector->par_take_from_overflow_list(num_from_overflow_list,
5663 work_q)) {
5664 // Found something in global overflow list;
5665 // not yet ready to go stealing work from others.
5666 // We'd like to assert(work_q->size() != 0, ...)
5667 // because we just took work from the overflow list,
5668 // but of course we can't, since all of that might have
5669 // been already stolen from us.
5670 continue;
5671 }
5672 // Verify that we have no work before we resort to stealing
5673 assert(work_q->size() == 0, "Have work, shouldn't steal");
5674 // Try to steal from other queues that have work
5675 if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
5676 NOT_PRODUCT(num_steals++;)
5677 assert(obj_to_scan->is_oop(), "Oops, not an oop!");
5678 assert(_mark_bit_map->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?");
5679 // Do scanning work
5680 obj_to_scan->oop_iterate(keep_alive);
5681 // Loop around, finish this work, and try to steal some more
5682 } else if (terminator()->offer_termination()) {
5683 break; // nirvana from the infinite cycle
5684 }
5685 }
5686 NOT_PRODUCT(
5687 if (PrintCMSStatistics != 0) {
5688 gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals);
5689 }
5690 )
5691 }
5693 void CMSRefProcTaskExecutor::execute(ProcessTask& task)
5694 {
5695 GenCollectedHeap* gch = GenCollectedHeap::heap();
5696 WorkGang* workers = gch->workers();
5697 assert(workers != NULL, "Need parallel worker threads.");
5698 int n_workers = workers->total_workers();
5699 CMSRefProcTaskProxy rp_task(task, &_collector,
5700 _collector.ref_processor()->span(),
5701 _collector.markBitMap(),
5702 n_workers, _collector.task_queues());
5703 workers->run_task(&rp_task);
5704 }
5706 void CMSRefProcTaskExecutor::execute(EnqueueTask& task)
5707 {
5709 GenCollectedHeap* gch = GenCollectedHeap::heap();
5710 WorkGang* workers = gch->workers();
5711 assert(workers != NULL, "Need parallel worker threads.");
5712 CMSRefEnqueueTaskProxy enq_task(task);
5713 workers->run_task(&enq_task);
5714 }
5716 void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) {
5718 ResourceMark rm;
5719 HandleMark hm;
5721 ReferenceProcessor* rp = ref_processor();
5722 assert(rp->span().equals(_span), "Spans should be equal");
5723 assert(!rp->enqueuing_is_done(), "Enqueuing should not be complete");
5724 // Process weak references.
5725 rp->setup_policy(clear_all_soft_refs);
5726 verify_work_stacks_empty();
5728 CMSKeepAliveClosure cmsKeepAliveClosure(this, _span, &_markBitMap,
5729 &_markStack, &_revisitStack,
5730 false /* !preclean */);
5731 CMSDrainMarkingStackClosure cmsDrainMarkingStackClosure(this,
5732 _span, &_markBitMap, &_markStack,
5733 &cmsKeepAliveClosure, false /* !preclean */);
5734 {
5735 TraceTime t("weak refs processing", PrintGCDetails, false, gclog_or_tty);
5736 if (rp->processing_is_mt()) {
5737 CMSRefProcTaskExecutor task_executor(*this);
5738 rp->process_discovered_references(&_is_alive_closure,
5739 &cmsKeepAliveClosure,
5740 &cmsDrainMarkingStackClosure,
5741 &task_executor);
5742 } else {
5743 rp->process_discovered_references(&_is_alive_closure,
5744 &cmsKeepAliveClosure,
5745 &cmsDrainMarkingStackClosure,
5746 NULL);
5747 }
5748 verify_work_stacks_empty();
5749 }
5751 if (should_unload_classes()) {
5752 {
5753 TraceTime t("class unloading", PrintGCDetails, false, gclog_or_tty);
5755 // Follow SystemDictionary roots and unload classes
5756 bool purged_class = SystemDictionary::do_unloading(&_is_alive_closure);
5758 // Follow CodeCache roots and unload any methods marked for unloading
5759 CodeCache::do_unloading(&_is_alive_closure,
5760 &cmsKeepAliveClosure,
5761 purged_class);
5763 cmsDrainMarkingStackClosure.do_void();
5764 verify_work_stacks_empty();
5766 // Update subklass/sibling/implementor links in KlassKlass descendants
5767 assert(!_revisitStack.isEmpty(), "revisit stack should not be empty");
5768 oop k;
5769 while ((k = _revisitStack.pop()) != NULL) {
5770 ((Klass*)(oopDesc*)k)->follow_weak_klass_links(
5771 &_is_alive_closure,
5772 &cmsKeepAliveClosure);
5773 }
5774 assert(!ClassUnloading ||
5775 (_markStack.isEmpty() && overflow_list_is_empty()),
5776 "Should not have found new reachable objects");
5777 assert(_revisitStack.isEmpty(), "revisit stack should have been drained");
5778 cmsDrainMarkingStackClosure.do_void();
5779 verify_work_stacks_empty();
5780 }
5782 {
5783 TraceTime t("scrub symbol & string tables", PrintGCDetails, false, gclog_or_tty);
5784 // Now clean up stale oops in SymbolTable and StringTable
5785 SymbolTable::unlink(&_is_alive_closure);
5786 StringTable::unlink(&_is_alive_closure);
5787 }
5788 }
5790 verify_work_stacks_empty();
5791 // Restore any preserved marks as a result of mark stack or
5792 // work queue overflow
5793 restore_preserved_marks_if_any(); // done single-threaded for now
5795 rp->set_enqueuing_is_done(true);
5796 if (rp->processing_is_mt()) {
5797 CMSRefProcTaskExecutor task_executor(*this);
5798 rp->enqueue_discovered_references(&task_executor);
5799 } else {
5800 rp->enqueue_discovered_references(NULL);
5801 }
5802 rp->verify_no_references_recorded();
5803 assert(!rp->discovery_enabled(), "should have been disabled");
5805 // JVMTI object tagging is based on JNI weak refs. If any of these
5806 // refs were cleared then JVMTI needs to update its maps and
5807 // maybe post ObjectFrees to agents.
5808 JvmtiExport::cms_ref_processing_epilogue();
5809 }
5811 #ifndef PRODUCT
5812 void CMSCollector::check_correct_thread_executing() {
5813 Thread* t = Thread::current();
5814 // Only the VM thread or the CMS thread should be here.
5815 assert(t->is_ConcurrentGC_thread() || t->is_VM_thread(),
5816 "Unexpected thread type");
5817 // If this is the vm thread, the foreground process
5818 // should not be waiting. Note that _foregroundGCIsActive is
5819 // true while the foreground collector is waiting.
5820 if (_foregroundGCShouldWait) {
5821 // We cannot be the VM thread
5822 assert(t->is_ConcurrentGC_thread(),
5823 "Should be CMS thread");
5824 } else {
5825 // We can be the CMS thread only if we are in a stop-world
5826 // phase of CMS collection.
5827 if (t->is_ConcurrentGC_thread()) {
5828 assert(_collectorState == InitialMarking ||
5829 _collectorState == FinalMarking,
5830 "Should be a stop-world phase");
5831 // The CMS thread should be holding the CMS_token.
5832 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
5833 "Potential interference with concurrently "
5834 "executing VM thread");
5835 }
5836 }
5837 }
5838 #endif
5840 void CMSCollector::sweep(bool asynch) {
5841 assert(_collectorState == Sweeping, "just checking");
5842 check_correct_thread_executing();
5843 verify_work_stacks_empty();
5844 verify_overflow_empty();
5845 incrementSweepCount();
5846 _sweep_timer.stop();
5847 _sweep_estimate.sample(_sweep_timer.seconds());
5848 size_policy()->avg_cms_free_at_sweep()->sample(_cmsGen->free());
5850 // PermGen verification support: If perm gen sweeping is disabled in
5851 // this cycle, we preserve the perm gen object "deadness" information
5852 // in the perm_gen_verify_bit_map. In order to do that we traverse
5853 // all blocks in perm gen and mark all dead objects.
5854 if (verifying() && !should_unload_classes()) {
5855 assert(perm_gen_verify_bit_map()->sizeInBits() != 0,
5856 "Should have already been allocated");
5857 MarkDeadObjectsClosure mdo(this, _permGen->cmsSpace(),
5858 markBitMap(), perm_gen_verify_bit_map());
5859 if (asynch) {
5860 CMSTokenSyncWithLocks ts(true, _permGen->freelistLock(),
5861 bitMapLock());
5862 _permGen->cmsSpace()->blk_iterate(&mdo);
5863 } else {
5864 // In the case of synchronous sweep, we already have
5865 // the requisite locks/tokens.
5866 _permGen->cmsSpace()->blk_iterate(&mdo);
5867 }
5868 }
5870 if (asynch) {
5871 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
5872 CMSPhaseAccounting pa(this, "sweep", !PrintGCDetails);
5873 // First sweep the old gen then the perm gen
5874 {
5875 CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock(),
5876 bitMapLock());
5877 sweepWork(_cmsGen, asynch);
5878 }
5880 // Now repeat for perm gen
5881 if (should_unload_classes()) {
5882 CMSTokenSyncWithLocks ts(true, _permGen->freelistLock(),
5883 bitMapLock());
5884 sweepWork(_permGen, asynch);
5885 }
5887 // Update Universe::_heap_*_at_gc figures.
5888 // We need all the free list locks to make the abstract state
5889 // transition from Sweeping to Resetting. See detailed note
5890 // further below.
5891 {
5892 CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock(),
5893 _permGen->freelistLock());
5894 // Update heap occupancy information which is used as
5895 // input to soft ref clearing policy at the next gc.
5896 Universe::update_heap_info_at_gc();
5897 _collectorState = Resizing;
5898 }
5899 } else {
5900 // already have needed locks
5901 sweepWork(_cmsGen, asynch);
5903 if (should_unload_classes()) {
5904 sweepWork(_permGen, asynch);
5905 }
5906 // Update heap occupancy information which is used as
5907 // input to soft ref clearing policy at the next gc.
5908 Universe::update_heap_info_at_gc();
5909 _collectorState = Resizing;
5910 }
5911 verify_work_stacks_empty();
5912 verify_overflow_empty();
5914 _sweep_timer.reset();
5915 _sweep_timer.start();
5917 update_time_of_last_gc(os::javaTimeMillis());
5919 // NOTE on abstract state transitions:
5920 // Mutators allocate-live and/or mark the mod-union table dirty
5921 // based on the state of the collection. The former is done in
5922 // the interval [Marking, Sweeping] and the latter in the interval
5923 // [Marking, Sweeping). Thus the transitions into the Marking state
5924 // and out of the Sweeping state must be synchronously visible
5925 // globally to the mutators.
5926 // The transition into the Marking state happens with the world
5927 // stopped so the mutators will globally see it. Sweeping is
5928 // done asynchronously by the background collector so the transition
5929 // from the Sweeping state to the Resizing state must be done
5930 // under the freelistLock (as is the check for whether to
5931 // allocate-live and whether to dirty the mod-union table).
5932 assert(_collectorState == Resizing, "Change of collector state to"
5933 " Resizing must be done under the freelistLocks (plural)");
5935 // Now that sweeping has been completed, if the GCH's
5936 // incremental_collection_will_fail flag is set, clear it,
5937 // thus inviting a younger gen collection to promote into
5938 // this generation. If such a promotion may still fail,
5939 // the flag will be set again when a young collection is
5940 // attempted.
5941 // I think the incremental_collection_will_fail flag's use
5942 // is specific to a 2 generation collection policy, so i'll
5943 // assert that that's the configuration we are operating within.
5944 // The use of the flag can and should be generalized appropriately
5945 // in the future to deal with a general n-generation system.
5947 GenCollectedHeap* gch = GenCollectedHeap::heap();
5948 assert(gch->collector_policy()->is_two_generation_policy(),
5949 "Resetting of incremental_collection_will_fail flag"
5950 " may be incorrect otherwise");
5951 gch->clear_incremental_collection_will_fail();
5952 gch->update_full_collections_completed(_collection_count_start);
5953 }
5955 // FIX ME!!! Looks like this belongs in CFLSpace, with
5956 // CMSGen merely delegating to it.
5957 void ConcurrentMarkSweepGeneration::setNearLargestChunk() {
5958 double nearLargestPercent = 0.999;
5959 HeapWord* minAddr = _cmsSpace->bottom();
5960 HeapWord* largestAddr =
5961 (HeapWord*) _cmsSpace->dictionary()->findLargestDict();
5962 if (largestAddr == 0) {
5963 // The dictionary appears to be empty. In this case
5964 // try to coalesce at the end of the heap.
5965 largestAddr = _cmsSpace->end();
5966 }
5967 size_t largestOffset = pointer_delta(largestAddr, minAddr);
5968 size_t nearLargestOffset =
5969 (size_t)((double)largestOffset * nearLargestPercent) - MinChunkSize;
5970 _cmsSpace->set_nearLargestChunk(minAddr + nearLargestOffset);
5971 }
5973 bool ConcurrentMarkSweepGeneration::isNearLargestChunk(HeapWord* addr) {
5974 return addr >= _cmsSpace->nearLargestChunk();
5975 }
5977 FreeChunk* ConcurrentMarkSweepGeneration::find_chunk_at_end() {
5978 return _cmsSpace->find_chunk_at_end();
5979 }
5981 void ConcurrentMarkSweepGeneration::update_gc_stats(int current_level,
5982 bool full) {
5983 // The next lower level has been collected. Gather any statistics
5984 // that are of interest at this point.
5985 if (!full && (current_level + 1) == level()) {
5986 // Gather statistics on the young generation collection.
5987 collector()->stats().record_gc0_end(used());
5988 }
5989 }
5991 CMSAdaptiveSizePolicy* ConcurrentMarkSweepGeneration::size_policy() {
5992 GenCollectedHeap* gch = GenCollectedHeap::heap();
5993 assert(gch->kind() == CollectedHeap::GenCollectedHeap,
5994 "Wrong type of heap");
5995 CMSAdaptiveSizePolicy* sp = (CMSAdaptiveSizePolicy*)
5996 gch->gen_policy()->size_policy();
5997 assert(sp->is_gc_cms_adaptive_size_policy(),
5998 "Wrong type of size policy");
5999 return sp;
6000 }
6002 void ConcurrentMarkSweepGeneration::rotate_debug_collection_type() {
6003 if (PrintGCDetails && Verbose) {
6004 gclog_or_tty->print("Rotate from %d ", _debug_collection_type);
6005 }
6006 _debug_collection_type = (CollectionTypes) (_debug_collection_type + 1);
6007 _debug_collection_type =
6008 (CollectionTypes) (_debug_collection_type % Unknown_collection_type);
6009 if (PrintGCDetails && Verbose) {
6010 gclog_or_tty->print_cr("to %d ", _debug_collection_type);
6011 }
6012 }
6014 void CMSCollector::sweepWork(ConcurrentMarkSweepGeneration* gen,
6015 bool asynch) {
6016 // We iterate over the space(s) underlying this generation,
6017 // checking the mark bit map to see if the bits corresponding
6018 // to specific blocks are marked or not. Blocks that are
6019 // marked are live and are not swept up. All remaining blocks
6020 // are swept up, with coalescing on-the-fly as we sweep up
6021 // contiguous free and/or garbage blocks:
6022 // We need to ensure that the sweeper synchronizes with allocators
6023 // and stop-the-world collectors. In particular, the following
6024 // locks are used:
6025 // . CMS token: if this is held, a stop the world collection cannot occur
6026 // . freelistLock: if this is held no allocation can occur from this
6027 // generation by another thread
6028 // . bitMapLock: if this is held, no other thread can access or update
6029 //
6031 // Note that we need to hold the freelistLock if we use
6032 // block iterate below; else the iterator might go awry if
6033 // a mutator (or promotion) causes block contents to change
6034 // (for instance if the allocator divvies up a block).
6035 // If we hold the free list lock, for all practical purposes
6036 // young generation GC's can't occur (they'll usually need to
6037 // promote), so we might as well prevent all young generation
6038 // GC's while we do a sweeping step. For the same reason, we might
6039 // as well take the bit map lock for the entire duration
6041 // check that we hold the requisite locks
6042 assert(have_cms_token(), "Should hold cms token");
6043 assert( (asynch && ConcurrentMarkSweepThread::cms_thread_has_cms_token())
6044 || (!asynch && ConcurrentMarkSweepThread::vm_thread_has_cms_token()),
6045 "Should possess CMS token to sweep");
6046 assert_lock_strong(gen->freelistLock());
6047 assert_lock_strong(bitMapLock());
6049 assert(!_sweep_timer.is_active(), "Was switched off in an outer context");
6050 gen->cmsSpace()->beginSweepFLCensus((float)(_sweep_timer.seconds()),
6051 _sweep_estimate.padded_average());
6052 gen->setNearLargestChunk();
6054 {
6055 SweepClosure sweepClosure(this, gen, &_markBitMap,
6056 CMSYield && asynch);
6057 gen->cmsSpace()->blk_iterate_careful(&sweepClosure);
6058 // We need to free-up/coalesce garbage/blocks from a
6059 // co-terminal free run. This is done in the SweepClosure
6060 // destructor; so, do not remove this scope, else the
6061 // end-of-sweep-census below will be off by a little bit.
6062 }
6063 gen->cmsSpace()->sweep_completed();
6064 gen->cmsSpace()->endSweepFLCensus(sweepCount());
6065 if (should_unload_classes()) { // unloaded classes this cycle,
6066 _concurrent_cycles_since_last_unload = 0; // ... reset count
6067 } else { // did not unload classes,
6068 _concurrent_cycles_since_last_unload++; // ... increment count
6069 }
6070 }
6072 // Reset CMS data structures (for now just the marking bit map)
6073 // preparatory for the next cycle.
6074 void CMSCollector::reset(bool asynch) {
6075 GenCollectedHeap* gch = GenCollectedHeap::heap();
6076 CMSAdaptiveSizePolicy* sp = size_policy();
6077 AdaptiveSizePolicyOutput(sp, gch->total_collections());
6078 if (asynch) {
6079 CMSTokenSyncWithLocks ts(true, bitMapLock());
6081 // If the state is not "Resetting", the foreground thread
6082 // has done a collection and the resetting.
6083 if (_collectorState != Resetting) {
6084 assert(_collectorState == Idling, "The state should only change"
6085 " because the foreground collector has finished the collection");
6086 return;
6087 }
6089 // Clear the mark bitmap (no grey objects to start with)
6090 // for the next cycle.
6091 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
6092 CMSPhaseAccounting cmspa(this, "reset", !PrintGCDetails);
6094 HeapWord* curAddr = _markBitMap.startWord();
6095 while (curAddr < _markBitMap.endWord()) {
6096 size_t remaining = pointer_delta(_markBitMap.endWord(), curAddr);
6097 MemRegion chunk(curAddr, MIN2(CMSBitMapYieldQuantum, remaining));
6098 _markBitMap.clear_large_range(chunk);
6099 if (ConcurrentMarkSweepThread::should_yield() &&
6100 !foregroundGCIsActive() &&
6101 CMSYield) {
6102 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
6103 "CMS thread should hold CMS token");
6104 assert_lock_strong(bitMapLock());
6105 bitMapLock()->unlock();
6106 ConcurrentMarkSweepThread::desynchronize(true);
6107 ConcurrentMarkSweepThread::acknowledge_yield_request();
6108 stopTimer();
6109 if (PrintCMSStatistics != 0) {
6110 incrementYields();
6111 }
6112 icms_wait();
6114 // See the comment in coordinator_yield()
6115 for (unsigned i = 0; i < CMSYieldSleepCount &&
6116 ConcurrentMarkSweepThread::should_yield() &&
6117 !CMSCollector::foregroundGCIsActive(); ++i) {
6118 os::sleep(Thread::current(), 1, false);
6119 ConcurrentMarkSweepThread::acknowledge_yield_request();
6120 }
6122 ConcurrentMarkSweepThread::synchronize(true);
6123 bitMapLock()->lock_without_safepoint_check();
6124 startTimer();
6125 }
6126 curAddr = chunk.end();
6127 }
6128 _collectorState = Idling;
6129 } else {
6130 // already have the lock
6131 assert(_collectorState == Resetting, "just checking");
6132 assert_lock_strong(bitMapLock());
6133 _markBitMap.clear_all();
6134 _collectorState = Idling;
6135 }
6137 // Stop incremental mode after a cycle completes, so that any future cycles
6138 // are triggered by allocation.
6139 stop_icms();
6141 NOT_PRODUCT(
6142 if (RotateCMSCollectionTypes) {
6143 _cmsGen->rotate_debug_collection_type();
6144 }
6145 )
6146 }
6148 void CMSCollector::do_CMS_operation(CMS_op_type op) {
6149 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
6150 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
6151 TraceTime t("GC", PrintGC, !PrintGCDetails, gclog_or_tty);
6152 TraceCollectorStats tcs(counters());
6154 switch (op) {
6155 case CMS_op_checkpointRootsInitial: {
6156 checkpointRootsInitial(true); // asynch
6157 if (PrintGC) {
6158 _cmsGen->printOccupancy("initial-mark");
6159 }
6160 break;
6161 }
6162 case CMS_op_checkpointRootsFinal: {
6163 checkpointRootsFinal(true, // asynch
6164 false, // !clear_all_soft_refs
6165 false); // !init_mark_was_synchronous
6166 if (PrintGC) {
6167 _cmsGen->printOccupancy("remark");
6168 }
6169 break;
6170 }
6171 default:
6172 fatal("No such CMS_op");
6173 }
6174 }
6176 #ifndef PRODUCT
6177 size_t const CMSCollector::skip_header_HeapWords() {
6178 return FreeChunk::header_size();
6179 }
6181 // Try and collect here conditions that should hold when
6182 // CMS thread is exiting. The idea is that the foreground GC
6183 // thread should not be blocked if it wants to terminate
6184 // the CMS thread and yet continue to run the VM for a while
6185 // after that.
6186 void CMSCollector::verify_ok_to_terminate() const {
6187 assert(Thread::current()->is_ConcurrentGC_thread(),
6188 "should be called by CMS thread");
6189 assert(!_foregroundGCShouldWait, "should be false");
6190 // We could check here that all the various low-level locks
6191 // are not held by the CMS thread, but that is overkill; see
6192 // also CMSThread::verify_ok_to_terminate() where the CGC_lock
6193 // is checked.
6194 }
6195 #endif
6197 size_t CMSCollector::block_size_using_printezis_bits(HeapWord* addr) const {
6198 assert(_markBitMap.isMarked(addr) && _markBitMap.isMarked(addr + 1),
6199 "missing Printezis mark?");
6200 HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2);
6201 size_t size = pointer_delta(nextOneAddr + 1, addr);
6202 assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
6203 "alignment problem");
6204 assert(size >= 3, "Necessary for Printezis marks to work");
6205 return size;
6206 }
6208 // A variant of the above (block_size_using_printezis_bits()) except
6209 // that we return 0 if the P-bits are not yet set.
6210 size_t CMSCollector::block_size_if_printezis_bits(HeapWord* addr) const {
6211 if (_markBitMap.isMarked(addr)) {
6212 assert(_markBitMap.isMarked(addr + 1), "Missing Printezis bit?");
6213 HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2);
6214 size_t size = pointer_delta(nextOneAddr + 1, addr);
6215 assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
6216 "alignment problem");
6217 assert(size >= 3, "Necessary for Printezis marks to work");
6218 return size;
6219 } else {
6220 assert(!_markBitMap.isMarked(addr + 1), "Bit map inconsistency?");
6221 return 0;
6222 }
6223 }
6225 HeapWord* CMSCollector::next_card_start_after_block(HeapWord* addr) const {
6226 size_t sz = 0;
6227 oop p = (oop)addr;
6228 if (p->klass_or_null() != NULL && p->is_parsable()) {
6229 sz = CompactibleFreeListSpace::adjustObjectSize(p->size());
6230 } else {
6231 sz = block_size_using_printezis_bits(addr);
6232 }
6233 assert(sz > 0, "size must be nonzero");
6234 HeapWord* next_block = addr + sz;
6235 HeapWord* next_card = (HeapWord*)round_to((uintptr_t)next_block,
6236 CardTableModRefBS::card_size);
6237 assert(round_down((uintptr_t)addr, CardTableModRefBS::card_size) <
6238 round_down((uintptr_t)next_card, CardTableModRefBS::card_size),
6239 "must be different cards");
6240 return next_card;
6241 }
6244 // CMS Bit Map Wrapper /////////////////////////////////////////
6246 // Construct a CMS bit map infrastructure, but don't create the
6247 // bit vector itself. That is done by a separate call CMSBitMap::allocate()
6248 // further below.
6249 CMSBitMap::CMSBitMap(int shifter, int mutex_rank, const char* mutex_name):
6250 _bm(),
6251 _shifter(shifter),
6252 _lock(mutex_rank >= 0 ? new Mutex(mutex_rank, mutex_name, true) : NULL)
6253 {
6254 _bmStartWord = 0;
6255 _bmWordSize = 0;
6256 }
6258 bool CMSBitMap::allocate(MemRegion mr) {
6259 _bmStartWord = mr.start();
6260 _bmWordSize = mr.word_size();
6261 ReservedSpace brs(ReservedSpace::allocation_align_size_up(
6262 (_bmWordSize >> (_shifter + LogBitsPerByte)) + 1));
6263 if (!brs.is_reserved()) {
6264 warning("CMS bit map allocation failure");
6265 return false;
6266 }
6267 // For now we'll just commit all of the bit map up fromt.
6268 // Later on we'll try to be more parsimonious with swap.
6269 if (!_virtual_space.initialize(brs, brs.size())) {
6270 warning("CMS bit map backing store failure");
6271 return false;
6272 }
6273 assert(_virtual_space.committed_size() == brs.size(),
6274 "didn't reserve backing store for all of CMS bit map?");
6275 _bm.set_map((BitMap::bm_word_t*)_virtual_space.low());
6276 assert(_virtual_space.committed_size() << (_shifter + LogBitsPerByte) >=
6277 _bmWordSize, "inconsistency in bit map sizing");
6278 _bm.set_size(_bmWordSize >> _shifter);
6280 // bm.clear(); // can we rely on getting zero'd memory? verify below
6281 assert(isAllClear(),
6282 "Expected zero'd memory from ReservedSpace constructor");
6283 assert(_bm.size() == heapWordDiffToOffsetDiff(sizeInWords()),
6284 "consistency check");
6285 return true;
6286 }
6288 void CMSBitMap::dirty_range_iterate_clear(MemRegion mr, MemRegionClosure* cl) {
6289 HeapWord *next_addr, *end_addr, *last_addr;
6290 assert_locked();
6291 assert(covers(mr), "out-of-range error");
6292 // XXX assert that start and end are appropriately aligned
6293 for (next_addr = mr.start(), end_addr = mr.end();
6294 next_addr < end_addr; next_addr = last_addr) {
6295 MemRegion dirty_region = getAndClearMarkedRegion(next_addr, end_addr);
6296 last_addr = dirty_region.end();
6297 if (!dirty_region.is_empty()) {
6298 cl->do_MemRegion(dirty_region);
6299 } else {
6300 assert(last_addr == end_addr, "program logic");
6301 return;
6302 }
6303 }
6304 }
6306 #ifndef PRODUCT
6307 void CMSBitMap::assert_locked() const {
6308 CMSLockVerifier::assert_locked(lock());
6309 }
6311 bool CMSBitMap::covers(MemRegion mr) const {
6312 // assert(_bm.map() == _virtual_space.low(), "map inconsistency");
6313 assert((size_t)_bm.size() == (_bmWordSize >> _shifter),
6314 "size inconsistency");
6315 return (mr.start() >= _bmStartWord) &&
6316 (mr.end() <= endWord());
6317 }
6319 bool CMSBitMap::covers(HeapWord* start, size_t size) const {
6320 return (start >= _bmStartWord && (start + size) <= endWord());
6321 }
6323 void CMSBitMap::verifyNoOneBitsInRange(HeapWord* left, HeapWord* right) {
6324 // verify that there are no 1 bits in the interval [left, right)
6325 FalseBitMapClosure falseBitMapClosure;
6326 iterate(&falseBitMapClosure, left, right);
6327 }
6329 void CMSBitMap::region_invariant(MemRegion mr)
6330 {
6331 assert_locked();
6332 // mr = mr.intersection(MemRegion(_bmStartWord, _bmWordSize));
6333 assert(!mr.is_empty(), "unexpected empty region");
6334 assert(covers(mr), "mr should be covered by bit map");
6335 // convert address range into offset range
6336 size_t start_ofs = heapWordToOffset(mr.start());
6337 // Make sure that end() is appropriately aligned
6338 assert(mr.end() == (HeapWord*)round_to((intptr_t)mr.end(),
6339 (1 << (_shifter+LogHeapWordSize))),
6340 "Misaligned mr.end()");
6341 size_t end_ofs = heapWordToOffset(mr.end());
6342 assert(end_ofs > start_ofs, "Should mark at least one bit");
6343 }
6345 #endif
6347 bool CMSMarkStack::allocate(size_t size) {
6348 // allocate a stack of the requisite depth
6349 ReservedSpace rs(ReservedSpace::allocation_align_size_up(
6350 size * sizeof(oop)));
6351 if (!rs.is_reserved()) {
6352 warning("CMSMarkStack allocation failure");
6353 return false;
6354 }
6355 if (!_virtual_space.initialize(rs, rs.size())) {
6356 warning("CMSMarkStack backing store failure");
6357 return false;
6358 }
6359 assert(_virtual_space.committed_size() == rs.size(),
6360 "didn't reserve backing store for all of CMS stack?");
6361 _base = (oop*)(_virtual_space.low());
6362 _index = 0;
6363 _capacity = size;
6364 NOT_PRODUCT(_max_depth = 0);
6365 return true;
6366 }
6368 // XXX FIX ME !!! In the MT case we come in here holding a
6369 // leaf lock. For printing we need to take a further lock
6370 // which has lower rank. We need to recallibrate the two
6371 // lock-ranks involved in order to be able to rpint the
6372 // messages below. (Or defer the printing to the caller.
6373 // For now we take the expedient path of just disabling the
6374 // messages for the problematic case.)
6375 void CMSMarkStack::expand() {
6376 assert(_capacity <= CMSMarkStackSizeMax, "stack bigger than permitted");
6377 if (_capacity == CMSMarkStackSizeMax) {
6378 if (_hit_limit++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) {
6379 // We print a warning message only once per CMS cycle.
6380 gclog_or_tty->print_cr(" (benign) Hit CMSMarkStack max size limit");
6381 }
6382 return;
6383 }
6384 // Double capacity if possible
6385 size_t new_capacity = MIN2(_capacity*2, CMSMarkStackSizeMax);
6386 // Do not give up existing stack until we have managed to
6387 // get the double capacity that we desired.
6388 ReservedSpace rs(ReservedSpace::allocation_align_size_up(
6389 new_capacity * sizeof(oop)));
6390 if (rs.is_reserved()) {
6391 // Release the backing store associated with old stack
6392 _virtual_space.release();
6393 // Reinitialize virtual space for new stack
6394 if (!_virtual_space.initialize(rs, rs.size())) {
6395 fatal("Not enough swap for expanded marking stack");
6396 }
6397 _base = (oop*)(_virtual_space.low());
6398 _index = 0;
6399 _capacity = new_capacity;
6400 } else if (_failed_double++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) {
6401 // Failed to double capacity, continue;
6402 // we print a detail message only once per CMS cycle.
6403 gclog_or_tty->print(" (benign) Failed to expand marking stack from "SIZE_FORMAT"K to "
6404 SIZE_FORMAT"K",
6405 _capacity / K, new_capacity / K);
6406 }
6407 }
6410 // Closures
6411 // XXX: there seems to be a lot of code duplication here;
6412 // should refactor and consolidate common code.
6414 // This closure is used to mark refs into the CMS generation in
6415 // the CMS bit map. Called at the first checkpoint. This closure
6416 // assumes that we do not need to re-mark dirty cards; if the CMS
6417 // generation on which this is used is not an oldest (modulo perm gen)
6418 // generation then this will lose younger_gen cards!
6420 MarkRefsIntoClosure::MarkRefsIntoClosure(
6421 MemRegion span, CMSBitMap* bitMap, bool should_do_nmethods):
6422 _span(span),
6423 _bitMap(bitMap),
6424 _should_do_nmethods(should_do_nmethods)
6425 {
6426 assert(_ref_processor == NULL, "deliberately left NULL");
6427 assert(_bitMap->covers(_span), "_bitMap/_span mismatch");
6428 }
6430 void MarkRefsIntoClosure::do_oop(oop obj) {
6431 // if p points into _span, then mark corresponding bit in _markBitMap
6432 assert(obj->is_oop(), "expected an oop");
6433 HeapWord* addr = (HeapWord*)obj;
6434 if (_span.contains(addr)) {
6435 // this should be made more efficient
6436 _bitMap->mark(addr);
6437 }
6438 }
6440 void MarkRefsIntoClosure::do_oop(oop* p) { MarkRefsIntoClosure::do_oop_work(p); }
6441 void MarkRefsIntoClosure::do_oop(narrowOop* p) { MarkRefsIntoClosure::do_oop_work(p); }
6443 // A variant of the above, used for CMS marking verification.
6444 MarkRefsIntoVerifyClosure::MarkRefsIntoVerifyClosure(
6445 MemRegion span, CMSBitMap* verification_bm, CMSBitMap* cms_bm,
6446 bool should_do_nmethods):
6447 _span(span),
6448 _verification_bm(verification_bm),
6449 _cms_bm(cms_bm),
6450 _should_do_nmethods(should_do_nmethods) {
6451 assert(_ref_processor == NULL, "deliberately left NULL");
6452 assert(_verification_bm->covers(_span), "_verification_bm/_span mismatch");
6453 }
6455 void MarkRefsIntoVerifyClosure::do_oop(oop obj) {
6456 // if p points into _span, then mark corresponding bit in _markBitMap
6457 assert(obj->is_oop(), "expected an oop");
6458 HeapWord* addr = (HeapWord*)obj;
6459 if (_span.contains(addr)) {
6460 _verification_bm->mark(addr);
6461 if (!_cms_bm->isMarked(addr)) {
6462 oop(addr)->print();
6463 gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", addr);
6464 fatal("... aborting");
6465 }
6466 }
6467 }
6469 void MarkRefsIntoVerifyClosure::do_oop(oop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); }
6470 void MarkRefsIntoVerifyClosure::do_oop(narrowOop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); }
6472 //////////////////////////////////////////////////
6473 // MarkRefsIntoAndScanClosure
6474 //////////////////////////////////////////////////
6476 MarkRefsIntoAndScanClosure::MarkRefsIntoAndScanClosure(MemRegion span,
6477 ReferenceProcessor* rp,
6478 CMSBitMap* bit_map,
6479 CMSBitMap* mod_union_table,
6480 CMSMarkStack* mark_stack,
6481 CMSMarkStack* revisit_stack,
6482 CMSCollector* collector,
6483 bool should_yield,
6484 bool concurrent_precleaning):
6485 _collector(collector),
6486 _span(span),
6487 _bit_map(bit_map),
6488 _mark_stack(mark_stack),
6489 _pushAndMarkClosure(collector, span, rp, bit_map, mod_union_table,
6490 mark_stack, revisit_stack, concurrent_precleaning),
6491 _yield(should_yield),
6492 _concurrent_precleaning(concurrent_precleaning),
6493 _freelistLock(NULL)
6494 {
6495 _ref_processor = rp;
6496 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
6497 }
6499 // This closure is used to mark refs into the CMS generation at the
6500 // second (final) checkpoint, and to scan and transitively follow
6501 // the unmarked oops. It is also used during the concurrent precleaning
6502 // phase while scanning objects on dirty cards in the CMS generation.
6503 // The marks are made in the marking bit map and the marking stack is
6504 // used for keeping the (newly) grey objects during the scan.
6505 // The parallel version (Par_...) appears further below.
6506 void MarkRefsIntoAndScanClosure::do_oop(oop obj) {
6507 if (obj != NULL) {
6508 assert(obj->is_oop(), "expected an oop");
6509 HeapWord* addr = (HeapWord*)obj;
6510 assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)");
6511 assert(_collector->overflow_list_is_empty(),
6512 "overflow list should be empty");
6513 if (_span.contains(addr) &&
6514 !_bit_map->isMarked(addr)) {
6515 // mark bit map (object is now grey)
6516 _bit_map->mark(addr);
6517 // push on marking stack (stack should be empty), and drain the
6518 // stack by applying this closure to the oops in the oops popped
6519 // from the stack (i.e. blacken the grey objects)
6520 bool res = _mark_stack->push(obj);
6521 assert(res, "Should have space to push on empty stack");
6522 do {
6523 oop new_oop = _mark_stack->pop();
6524 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
6525 assert(new_oop->is_parsable(), "Found unparsable oop");
6526 assert(_bit_map->isMarked((HeapWord*)new_oop),
6527 "only grey objects on this stack");
6528 // iterate over the oops in this oop, marking and pushing
6529 // the ones in CMS heap (i.e. in _span).
6530 new_oop->oop_iterate(&_pushAndMarkClosure);
6531 // check if it's time to yield
6532 do_yield_check();
6533 } while (!_mark_stack->isEmpty() ||
6534 (!_concurrent_precleaning && take_from_overflow_list()));
6535 // if marking stack is empty, and we are not doing this
6536 // during precleaning, then check the overflow list
6537 }
6538 assert(_mark_stack->isEmpty(), "post-condition (eager drainage)");
6539 assert(_collector->overflow_list_is_empty(),
6540 "overflow list was drained above");
6541 // We could restore evacuated mark words, if any, used for
6542 // overflow list links here because the overflow list is
6543 // provably empty here. That would reduce the maximum
6544 // size requirements for preserved_{oop,mark}_stack.
6545 // But we'll just postpone it until we are all done
6546 // so we can just stream through.
6547 if (!_concurrent_precleaning && CMSOverflowEarlyRestoration) {
6548 _collector->restore_preserved_marks_if_any();
6549 assert(_collector->no_preserved_marks(), "No preserved marks");
6550 }
6551 assert(!CMSOverflowEarlyRestoration || _collector->no_preserved_marks(),
6552 "All preserved marks should have been restored above");
6553 }
6554 }
6556 void MarkRefsIntoAndScanClosure::do_oop(oop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); }
6557 void MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); }
6559 void MarkRefsIntoAndScanClosure::do_yield_work() {
6560 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
6561 "CMS thread should hold CMS token");
6562 assert_lock_strong(_freelistLock);
6563 assert_lock_strong(_bit_map->lock());
6564 // relinquish the free_list_lock and bitMaplock()
6565 DEBUG_ONLY(RememberKlassesChecker mux(false);)
6566 _bit_map->lock()->unlock();
6567 _freelistLock->unlock();
6568 ConcurrentMarkSweepThread::desynchronize(true);
6569 ConcurrentMarkSweepThread::acknowledge_yield_request();
6570 _collector->stopTimer();
6571 GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
6572 if (PrintCMSStatistics != 0) {
6573 _collector->incrementYields();
6574 }
6575 _collector->icms_wait();
6577 // See the comment in coordinator_yield()
6578 for (unsigned i = 0;
6579 i < CMSYieldSleepCount &&
6580 ConcurrentMarkSweepThread::should_yield() &&
6581 !CMSCollector::foregroundGCIsActive();
6582 ++i) {
6583 os::sleep(Thread::current(), 1, false);
6584 ConcurrentMarkSweepThread::acknowledge_yield_request();
6585 }
6587 ConcurrentMarkSweepThread::synchronize(true);
6588 _freelistLock->lock_without_safepoint_check();
6589 _bit_map->lock()->lock_without_safepoint_check();
6590 _collector->startTimer();
6591 }
6593 ///////////////////////////////////////////////////////////
6594 // Par_MarkRefsIntoAndScanClosure: a parallel version of
6595 // MarkRefsIntoAndScanClosure
6596 ///////////////////////////////////////////////////////////
6597 Par_MarkRefsIntoAndScanClosure::Par_MarkRefsIntoAndScanClosure(
6598 CMSCollector* collector, MemRegion span, ReferenceProcessor* rp,
6599 CMSBitMap* bit_map, OopTaskQueue* work_queue, CMSMarkStack* revisit_stack):
6600 _span(span),
6601 _bit_map(bit_map),
6602 _work_queue(work_queue),
6603 _low_water_mark(MIN2((uint)(work_queue->max_elems()/4),
6604 (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads))),
6605 _par_pushAndMarkClosure(collector, span, rp, bit_map, work_queue,
6606 revisit_stack)
6607 {
6608 _ref_processor = rp;
6609 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
6610 }
6612 // This closure is used to mark refs into the CMS generation at the
6613 // second (final) checkpoint, and to scan and transitively follow
6614 // the unmarked oops. The marks are made in the marking bit map and
6615 // the work_queue is used for keeping the (newly) grey objects during
6616 // the scan phase whence they are also available for stealing by parallel
6617 // threads. Since the marking bit map is shared, updates are
6618 // synchronized (via CAS).
6619 void Par_MarkRefsIntoAndScanClosure::do_oop(oop obj) {
6620 if (obj != NULL) {
6621 // Ignore mark word because this could be an already marked oop
6622 // that may be chained at the end of the overflow list.
6623 assert(obj->is_oop(true), "expected an oop");
6624 HeapWord* addr = (HeapWord*)obj;
6625 if (_span.contains(addr) &&
6626 !_bit_map->isMarked(addr)) {
6627 // mark bit map (object will become grey):
6628 // It is possible for several threads to be
6629 // trying to "claim" this object concurrently;
6630 // the unique thread that succeeds in marking the
6631 // object first will do the subsequent push on
6632 // to the work queue (or overflow list).
6633 if (_bit_map->par_mark(addr)) {
6634 // push on work_queue (which may not be empty), and trim the
6635 // queue to an appropriate length by applying this closure to
6636 // the oops in the oops popped from the stack (i.e. blacken the
6637 // grey objects)
6638 bool res = _work_queue->push(obj);
6639 assert(res, "Low water mark should be less than capacity?");
6640 trim_queue(_low_water_mark);
6641 } // Else, another thread claimed the object
6642 }
6643 }
6644 }
6646 void Par_MarkRefsIntoAndScanClosure::do_oop(oop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); }
6647 void Par_MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); }
6649 // This closure is used to rescan the marked objects on the dirty cards
6650 // in the mod union table and the card table proper.
6651 size_t ScanMarkedObjectsAgainCarefullyClosure::do_object_careful_m(
6652 oop p, MemRegion mr) {
6654 size_t size = 0;
6655 HeapWord* addr = (HeapWord*)p;
6656 DEBUG_ONLY(_collector->verify_work_stacks_empty();)
6657 assert(_span.contains(addr), "we are scanning the CMS generation");
6658 // check if it's time to yield
6659 if (do_yield_check()) {
6660 // We yielded for some foreground stop-world work,
6661 // and we have been asked to abort this ongoing preclean cycle.
6662 return 0;
6663 }
6664 if (_bitMap->isMarked(addr)) {
6665 // it's marked; is it potentially uninitialized?
6666 if (p->klass_or_null() != NULL) {
6667 // If is_conc_safe is false, the object may be undergoing
6668 // change by the VM outside a safepoint. Don't try to
6669 // scan it, but rather leave it for the remark phase.
6670 if (CMSPermGenPrecleaningEnabled &&
6671 (!p->is_conc_safe() || !p->is_parsable())) {
6672 // Signal precleaning to redirty the card since
6673 // the klass pointer is already installed.
6674 assert(size == 0, "Initial value");
6675 } else {
6676 assert(p->is_parsable(), "must be parsable.");
6677 // an initialized object; ignore mark word in verification below
6678 // since we are running concurrent with mutators
6679 assert(p->is_oop(true), "should be an oop");
6680 if (p->is_objArray()) {
6681 // objArrays are precisely marked; restrict scanning
6682 // to dirty cards only.
6683 size = CompactibleFreeListSpace::adjustObjectSize(
6684 p->oop_iterate(_scanningClosure, mr));
6685 } else {
6686 // A non-array may have been imprecisely marked; we need
6687 // to scan object in its entirety.
6688 size = CompactibleFreeListSpace::adjustObjectSize(
6689 p->oop_iterate(_scanningClosure));
6690 }
6691 #ifdef DEBUG
6692 size_t direct_size =
6693 CompactibleFreeListSpace::adjustObjectSize(p->size());
6694 assert(size == direct_size, "Inconsistency in size");
6695 assert(size >= 3, "Necessary for Printezis marks to work");
6696 if (!_bitMap->isMarked(addr+1)) {
6697 _bitMap->verifyNoOneBitsInRange(addr+2, addr+size);
6698 } else {
6699 _bitMap->verifyNoOneBitsInRange(addr+2, addr+size-1);
6700 assert(_bitMap->isMarked(addr+size-1),
6701 "inconsistent Printezis mark");
6702 }
6703 #endif // DEBUG
6704 }
6705 } else {
6706 // an unitialized object
6707 assert(_bitMap->isMarked(addr+1), "missing Printezis mark?");
6708 HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2);
6709 size = pointer_delta(nextOneAddr + 1, addr);
6710 assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
6711 "alignment problem");
6712 // Note that pre-cleaning needn't redirty the card. OopDesc::set_klass()
6713 // will dirty the card when the klass pointer is installed in the
6714 // object (signalling the completion of initialization).
6715 }
6716 } else {
6717 // Either a not yet marked object or an uninitialized object
6718 if (p->klass_or_null() == NULL || !p->is_parsable()) {
6719 // An uninitialized object, skip to the next card, since
6720 // we may not be able to read its P-bits yet.
6721 assert(size == 0, "Initial value");
6722 } else {
6723 // An object not (yet) reached by marking: we merely need to
6724 // compute its size so as to go look at the next block.
6725 assert(p->is_oop(true), "should be an oop");
6726 size = CompactibleFreeListSpace::adjustObjectSize(p->size());
6727 }
6728 }
6729 DEBUG_ONLY(_collector->verify_work_stacks_empty();)
6730 return size;
6731 }
6733 void ScanMarkedObjectsAgainCarefullyClosure::do_yield_work() {
6734 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
6735 "CMS thread should hold CMS token");
6736 assert_lock_strong(_freelistLock);
6737 assert_lock_strong(_bitMap->lock());
6738 DEBUG_ONLY(RememberKlassesChecker mux(false);)
6739 // relinquish the free_list_lock and bitMaplock()
6740 _bitMap->lock()->unlock();
6741 _freelistLock->unlock();
6742 ConcurrentMarkSweepThread::desynchronize(true);
6743 ConcurrentMarkSweepThread::acknowledge_yield_request();
6744 _collector->stopTimer();
6745 GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
6746 if (PrintCMSStatistics != 0) {
6747 _collector->incrementYields();
6748 }
6749 _collector->icms_wait();
6751 // See the comment in coordinator_yield()
6752 for (unsigned i = 0; i < CMSYieldSleepCount &&
6753 ConcurrentMarkSweepThread::should_yield() &&
6754 !CMSCollector::foregroundGCIsActive(); ++i) {
6755 os::sleep(Thread::current(), 1, false);
6756 ConcurrentMarkSweepThread::acknowledge_yield_request();
6757 }
6759 ConcurrentMarkSweepThread::synchronize(true);
6760 _freelistLock->lock_without_safepoint_check();
6761 _bitMap->lock()->lock_without_safepoint_check();
6762 _collector->startTimer();
6763 }
6766 //////////////////////////////////////////////////////////////////
6767 // SurvivorSpacePrecleanClosure
6768 //////////////////////////////////////////////////////////////////
6769 // This (single-threaded) closure is used to preclean the oops in
6770 // the survivor spaces.
6771 size_t SurvivorSpacePrecleanClosure::do_object_careful(oop p) {
6773 HeapWord* addr = (HeapWord*)p;
6774 DEBUG_ONLY(_collector->verify_work_stacks_empty();)
6775 assert(!_span.contains(addr), "we are scanning the survivor spaces");
6776 assert(p->klass_or_null() != NULL, "object should be initializd");
6777 assert(p->is_parsable(), "must be parsable.");
6778 // an initialized object; ignore mark word in verification below
6779 // since we are running concurrent with mutators
6780 assert(p->is_oop(true), "should be an oop");
6781 // Note that we do not yield while we iterate over
6782 // the interior oops of p, pushing the relevant ones
6783 // on our marking stack.
6784 size_t size = p->oop_iterate(_scanning_closure);
6785 do_yield_check();
6786 // Observe that below, we do not abandon the preclean
6787 // phase as soon as we should; rather we empty the
6788 // marking stack before returning. This is to satisfy
6789 // some existing assertions. In general, it may be a
6790 // good idea to abort immediately and complete the marking
6791 // from the grey objects at a later time.
6792 while (!_mark_stack->isEmpty()) {
6793 oop new_oop = _mark_stack->pop();
6794 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
6795 assert(new_oop->is_parsable(), "Found unparsable oop");
6796 assert(_bit_map->isMarked((HeapWord*)new_oop),
6797 "only grey objects on this stack");
6798 // iterate over the oops in this oop, marking and pushing
6799 // the ones in CMS heap (i.e. in _span).
6800 new_oop->oop_iterate(_scanning_closure);
6801 // check if it's time to yield
6802 do_yield_check();
6803 }
6804 unsigned int after_count =
6805 GenCollectedHeap::heap()->total_collections();
6806 bool abort = (_before_count != after_count) ||
6807 _collector->should_abort_preclean();
6808 return abort ? 0 : size;
6809 }
6811 void SurvivorSpacePrecleanClosure::do_yield_work() {
6812 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
6813 "CMS thread should hold CMS token");
6814 assert_lock_strong(_bit_map->lock());
6815 DEBUG_ONLY(RememberKlassesChecker smx(false);)
6816 // Relinquish the bit map lock
6817 _bit_map->lock()->unlock();
6818 ConcurrentMarkSweepThread::desynchronize(true);
6819 ConcurrentMarkSweepThread::acknowledge_yield_request();
6820 _collector->stopTimer();
6821 GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
6822 if (PrintCMSStatistics != 0) {
6823 _collector->incrementYields();
6824 }
6825 _collector->icms_wait();
6827 // See the comment in coordinator_yield()
6828 for (unsigned i = 0; i < CMSYieldSleepCount &&
6829 ConcurrentMarkSweepThread::should_yield() &&
6830 !CMSCollector::foregroundGCIsActive(); ++i) {
6831 os::sleep(Thread::current(), 1, false);
6832 ConcurrentMarkSweepThread::acknowledge_yield_request();
6833 }
6835 ConcurrentMarkSweepThread::synchronize(true);
6836 _bit_map->lock()->lock_without_safepoint_check();
6837 _collector->startTimer();
6838 }
6840 // This closure is used to rescan the marked objects on the dirty cards
6841 // in the mod union table and the card table proper. In the parallel
6842 // case, although the bitMap is shared, we do a single read so the
6843 // isMarked() query is "safe".
6844 bool ScanMarkedObjectsAgainClosure::do_object_bm(oop p, MemRegion mr) {
6845 // Ignore mark word because we are running concurrent with mutators
6846 assert(p->is_oop_or_null(true), "expected an oop or null");
6847 HeapWord* addr = (HeapWord*)p;
6848 assert(_span.contains(addr), "we are scanning the CMS generation");
6849 bool is_obj_array = false;
6850 #ifdef DEBUG
6851 if (!_parallel) {
6852 assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)");
6853 assert(_collector->overflow_list_is_empty(),
6854 "overflow list should be empty");
6856 }
6857 #endif // DEBUG
6858 if (_bit_map->isMarked(addr)) {
6859 // Obj arrays are precisely marked, non-arrays are not;
6860 // so we scan objArrays precisely and non-arrays in their
6861 // entirety.
6862 if (p->is_objArray()) {
6863 is_obj_array = true;
6864 if (_parallel) {
6865 p->oop_iterate(_par_scan_closure, mr);
6866 } else {
6867 p->oop_iterate(_scan_closure, mr);
6868 }
6869 } else {
6870 if (_parallel) {
6871 p->oop_iterate(_par_scan_closure);
6872 } else {
6873 p->oop_iterate(_scan_closure);
6874 }
6875 }
6876 }
6877 #ifdef DEBUG
6878 if (!_parallel) {
6879 assert(_mark_stack->isEmpty(), "post-condition (eager drainage)");
6880 assert(_collector->overflow_list_is_empty(),
6881 "overflow list should be empty");
6883 }
6884 #endif // DEBUG
6885 return is_obj_array;
6886 }
6888 MarkFromRootsClosure::MarkFromRootsClosure(CMSCollector* collector,
6889 MemRegion span,
6890 CMSBitMap* bitMap, CMSMarkStack* markStack,
6891 CMSMarkStack* revisitStack,
6892 bool should_yield, bool verifying):
6893 _collector(collector),
6894 _span(span),
6895 _bitMap(bitMap),
6896 _mut(&collector->_modUnionTable),
6897 _markStack(markStack),
6898 _revisitStack(revisitStack),
6899 _yield(should_yield),
6900 _skipBits(0)
6901 {
6902 assert(_markStack->isEmpty(), "stack should be empty");
6903 _finger = _bitMap->startWord();
6904 _threshold = _finger;
6905 assert(_collector->_restart_addr == NULL, "Sanity check");
6906 assert(_span.contains(_finger), "Out of bounds _finger?");
6907 DEBUG_ONLY(_verifying = verifying;)
6908 }
6910 void MarkFromRootsClosure::reset(HeapWord* addr) {
6911 assert(_markStack->isEmpty(), "would cause duplicates on stack");
6912 assert(_span.contains(addr), "Out of bounds _finger?");
6913 _finger = addr;
6914 _threshold = (HeapWord*)round_to(
6915 (intptr_t)_finger, CardTableModRefBS::card_size);
6916 }
6918 // Should revisit to see if this should be restructured for
6919 // greater efficiency.
6920 bool MarkFromRootsClosure::do_bit(size_t offset) {
6921 if (_skipBits > 0) {
6922 _skipBits--;
6923 return true;
6924 }
6925 // convert offset into a HeapWord*
6926 HeapWord* addr = _bitMap->startWord() + offset;
6927 assert(_bitMap->endWord() && addr < _bitMap->endWord(),
6928 "address out of range");
6929 assert(_bitMap->isMarked(addr), "tautology");
6930 if (_bitMap->isMarked(addr+1)) {
6931 // this is an allocated but not yet initialized object
6932 assert(_skipBits == 0, "tautology");
6933 _skipBits = 2; // skip next two marked bits ("Printezis-marks")
6934 oop p = oop(addr);
6935 if (p->klass_or_null() == NULL || !p->is_parsable()) {
6936 DEBUG_ONLY(if (!_verifying) {)
6937 // We re-dirty the cards on which this object lies and increase
6938 // the _threshold so that we'll come back to scan this object
6939 // during the preclean or remark phase. (CMSCleanOnEnter)
6940 if (CMSCleanOnEnter) {
6941 size_t sz = _collector->block_size_using_printezis_bits(addr);
6942 HeapWord* end_card_addr = (HeapWord*)round_to(
6943 (intptr_t)(addr+sz), CardTableModRefBS::card_size);
6944 MemRegion redirty_range = MemRegion(addr, end_card_addr);
6945 assert(!redirty_range.is_empty(), "Arithmetical tautology");
6946 // Bump _threshold to end_card_addr; note that
6947 // _threshold cannot possibly exceed end_card_addr, anyhow.
6948 // This prevents future clearing of the card as the scan proceeds
6949 // to the right.
6950 assert(_threshold <= end_card_addr,
6951 "Because we are just scanning into this object");
6952 if (_threshold < end_card_addr) {
6953 _threshold = end_card_addr;
6954 }
6955 if (p->klass_or_null() != NULL) {
6956 // Redirty the range of cards...
6957 _mut->mark_range(redirty_range);
6958 } // ...else the setting of klass will dirty the card anyway.
6959 }
6960 DEBUG_ONLY(})
6961 return true;
6962 }
6963 }
6964 scanOopsInOop(addr);
6965 return true;
6966 }
6968 // We take a break if we've been at this for a while,
6969 // so as to avoid monopolizing the locks involved.
6970 void MarkFromRootsClosure::do_yield_work() {
6971 // First give up the locks, then yield, then re-lock
6972 // We should probably use a constructor/destructor idiom to
6973 // do this unlock/lock or modify the MutexUnlocker class to
6974 // serve our purpose. XXX
6975 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
6976 "CMS thread should hold CMS token");
6977 assert_lock_strong(_bitMap->lock());
6978 DEBUG_ONLY(RememberKlassesChecker mux(false);)
6979 _bitMap->lock()->unlock();
6980 ConcurrentMarkSweepThread::desynchronize(true);
6981 ConcurrentMarkSweepThread::acknowledge_yield_request();
6982 _collector->stopTimer();
6983 GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
6984 if (PrintCMSStatistics != 0) {
6985 _collector->incrementYields();
6986 }
6987 _collector->icms_wait();
6989 // See the comment in coordinator_yield()
6990 for (unsigned i = 0; i < CMSYieldSleepCount &&
6991 ConcurrentMarkSweepThread::should_yield() &&
6992 !CMSCollector::foregroundGCIsActive(); ++i) {
6993 os::sleep(Thread::current(), 1, false);
6994 ConcurrentMarkSweepThread::acknowledge_yield_request();
6995 }
6997 ConcurrentMarkSweepThread::synchronize(true);
6998 _bitMap->lock()->lock_without_safepoint_check();
6999 _collector->startTimer();
7000 }
7002 void MarkFromRootsClosure::scanOopsInOop(HeapWord* ptr) {
7003 assert(_bitMap->isMarked(ptr), "expected bit to be set");
7004 assert(_markStack->isEmpty(),
7005 "should drain stack to limit stack usage");
7006 // convert ptr to an oop preparatory to scanning
7007 oop obj = oop(ptr);
7008 // Ignore mark word in verification below, since we
7009 // may be running concurrent with mutators.
7010 assert(obj->is_oop(true), "should be an oop");
7011 assert(_finger <= ptr, "_finger runneth ahead");
7012 // advance the finger to right end of this object
7013 _finger = ptr + obj->size();
7014 assert(_finger > ptr, "we just incremented it above");
7015 // On large heaps, it may take us some time to get through
7016 // the marking phase (especially if running iCMS). During
7017 // this time it's possible that a lot of mutations have
7018 // accumulated in the card table and the mod union table --
7019 // these mutation records are redundant until we have
7020 // actually traced into the corresponding card.
7021 // Here, we check whether advancing the finger would make
7022 // us cross into a new card, and if so clear corresponding
7023 // cards in the MUT (preclean them in the card-table in the
7024 // future).
7026 DEBUG_ONLY(if (!_verifying) {)
7027 // The clean-on-enter optimization is disabled by default,
7028 // until we fix 6178663.
7029 if (CMSCleanOnEnter && (_finger > _threshold)) {
7030 // [_threshold, _finger) represents the interval
7031 // of cards to be cleared in MUT (or precleaned in card table).
7032 // The set of cards to be cleared is all those that overlap
7033 // with the interval [_threshold, _finger); note that
7034 // _threshold is always kept card-aligned but _finger isn't
7035 // always card-aligned.
7036 HeapWord* old_threshold = _threshold;
7037 assert(old_threshold == (HeapWord*)round_to(
7038 (intptr_t)old_threshold, CardTableModRefBS::card_size),
7039 "_threshold should always be card-aligned");
7040 _threshold = (HeapWord*)round_to(
7041 (intptr_t)_finger, CardTableModRefBS::card_size);
7042 MemRegion mr(old_threshold, _threshold);
7043 assert(!mr.is_empty(), "Control point invariant");
7044 assert(_span.contains(mr), "Should clear within span");
7045 // XXX When _finger crosses from old gen into perm gen
7046 // we may be doing unnecessary cleaning; do better in the
7047 // future by detecting that condition and clearing fewer
7048 // MUT/CT entries.
7049 _mut->clear_range(mr);
7050 }
7051 DEBUG_ONLY(})
7052 // Note: the finger doesn't advance while we drain
7053 // the stack below.
7054 PushOrMarkClosure pushOrMarkClosure(_collector,
7055 _span, _bitMap, _markStack,
7056 _revisitStack,
7057 _finger, this);
7058 bool res = _markStack->push(obj);
7059 assert(res, "Empty non-zero size stack should have space for single push");
7060 while (!_markStack->isEmpty()) {
7061 oop new_oop = _markStack->pop();
7062 // Skip verifying header mark word below because we are
7063 // running concurrent with mutators.
7064 assert(new_oop->is_oop(true), "Oops! expected to pop an oop");
7065 // now scan this oop's oops
7066 new_oop->oop_iterate(&pushOrMarkClosure);
7067 do_yield_check();
7068 }
7069 assert(_markStack->isEmpty(), "tautology, emphasizing post-condition");
7070 }
7072 Par_MarkFromRootsClosure::Par_MarkFromRootsClosure(CMSConcMarkingTask* task,
7073 CMSCollector* collector, MemRegion span,
7074 CMSBitMap* bit_map,
7075 OopTaskQueue* work_queue,
7076 CMSMarkStack* overflow_stack,
7077 CMSMarkStack* revisit_stack,
7078 bool should_yield):
7079 _collector(collector),
7080 _whole_span(collector->_span),
7081 _span(span),
7082 _bit_map(bit_map),
7083 _mut(&collector->_modUnionTable),
7084 _work_queue(work_queue),
7085 _overflow_stack(overflow_stack),
7086 _revisit_stack(revisit_stack),
7087 _yield(should_yield),
7088 _skip_bits(0),
7089 _task(task)
7090 {
7091 assert(_work_queue->size() == 0, "work_queue should be empty");
7092 _finger = span.start();
7093 _threshold = _finger; // XXX Defer clear-on-enter optimization for now
7094 assert(_span.contains(_finger), "Out of bounds _finger?");
7095 }
7097 // Should revisit to see if this should be restructured for
7098 // greater efficiency.
7099 bool Par_MarkFromRootsClosure::do_bit(size_t offset) {
7100 if (_skip_bits > 0) {
7101 _skip_bits--;
7102 return true;
7103 }
7104 // convert offset into a HeapWord*
7105 HeapWord* addr = _bit_map->startWord() + offset;
7106 assert(_bit_map->endWord() && addr < _bit_map->endWord(),
7107 "address out of range");
7108 assert(_bit_map->isMarked(addr), "tautology");
7109 if (_bit_map->isMarked(addr+1)) {
7110 // this is an allocated object that might not yet be initialized
7111 assert(_skip_bits == 0, "tautology");
7112 _skip_bits = 2; // skip next two marked bits ("Printezis-marks")
7113 oop p = oop(addr);
7114 if (p->klass_or_null() == NULL || !p->is_parsable()) {
7115 // in the case of Clean-on-Enter optimization, redirty card
7116 // and avoid clearing card by increasing the threshold.
7117 return true;
7118 }
7119 }
7120 scan_oops_in_oop(addr);
7121 return true;
7122 }
7124 void Par_MarkFromRootsClosure::scan_oops_in_oop(HeapWord* ptr) {
7125 assert(_bit_map->isMarked(ptr), "expected bit to be set");
7126 // Should we assert that our work queue is empty or
7127 // below some drain limit?
7128 assert(_work_queue->size() == 0,
7129 "should drain stack to limit stack usage");
7130 // convert ptr to an oop preparatory to scanning
7131 oop obj = oop(ptr);
7132 // Ignore mark word in verification below, since we
7133 // may be running concurrent with mutators.
7134 assert(obj->is_oop(true), "should be an oop");
7135 assert(_finger <= ptr, "_finger runneth ahead");
7136 // advance the finger to right end of this object
7137 _finger = ptr + obj->size();
7138 assert(_finger > ptr, "we just incremented it above");
7139 // On large heaps, it may take us some time to get through
7140 // the marking phase (especially if running iCMS). During
7141 // this time it's possible that a lot of mutations have
7142 // accumulated in the card table and the mod union table --
7143 // these mutation records are redundant until we have
7144 // actually traced into the corresponding card.
7145 // Here, we check whether advancing the finger would make
7146 // us cross into a new card, and if so clear corresponding
7147 // cards in the MUT (preclean them in the card-table in the
7148 // future).
7150 // The clean-on-enter optimization is disabled by default,
7151 // until we fix 6178663.
7152 if (CMSCleanOnEnter && (_finger > _threshold)) {
7153 // [_threshold, _finger) represents the interval
7154 // of cards to be cleared in MUT (or precleaned in card table).
7155 // The set of cards to be cleared is all those that overlap
7156 // with the interval [_threshold, _finger); note that
7157 // _threshold is always kept card-aligned but _finger isn't
7158 // always card-aligned.
7159 HeapWord* old_threshold = _threshold;
7160 assert(old_threshold == (HeapWord*)round_to(
7161 (intptr_t)old_threshold, CardTableModRefBS::card_size),
7162 "_threshold should always be card-aligned");
7163 _threshold = (HeapWord*)round_to(
7164 (intptr_t)_finger, CardTableModRefBS::card_size);
7165 MemRegion mr(old_threshold, _threshold);
7166 assert(!mr.is_empty(), "Control point invariant");
7167 assert(_span.contains(mr), "Should clear within span"); // _whole_span ??
7168 // XXX When _finger crosses from old gen into perm gen
7169 // we may be doing unnecessary cleaning; do better in the
7170 // future by detecting that condition and clearing fewer
7171 // MUT/CT entries.
7172 _mut->clear_range(mr);
7173 }
7175 // Note: the local finger doesn't advance while we drain
7176 // the stack below, but the global finger sure can and will.
7177 HeapWord** gfa = _task->global_finger_addr();
7178 Par_PushOrMarkClosure pushOrMarkClosure(_collector,
7179 _span, _bit_map,
7180 _work_queue,
7181 _overflow_stack,
7182 _revisit_stack,
7183 _finger,
7184 gfa, this);
7185 bool res = _work_queue->push(obj); // overflow could occur here
7186 assert(res, "Will hold once we use workqueues");
7187 while (true) {
7188 oop new_oop;
7189 if (!_work_queue->pop_local(new_oop)) {
7190 // We emptied our work_queue; check if there's stuff that can
7191 // be gotten from the overflow stack.
7192 if (CMSConcMarkingTask::get_work_from_overflow_stack(
7193 _overflow_stack, _work_queue)) {
7194 do_yield_check();
7195 continue;
7196 } else { // done
7197 break;
7198 }
7199 }
7200 // Skip verifying header mark word below because we are
7201 // running concurrent with mutators.
7202 assert(new_oop->is_oop(true), "Oops! expected to pop an oop");
7203 // now scan this oop's oops
7204 new_oop->oop_iterate(&pushOrMarkClosure);
7205 do_yield_check();
7206 }
7207 assert(_work_queue->size() == 0, "tautology, emphasizing post-condition");
7208 }
7210 // Yield in response to a request from VM Thread or
7211 // from mutators.
7212 void Par_MarkFromRootsClosure::do_yield_work() {
7213 assert(_task != NULL, "sanity");
7214 _task->yield();
7215 }
7217 // A variant of the above used for verifying CMS marking work.
7218 MarkFromRootsVerifyClosure::MarkFromRootsVerifyClosure(CMSCollector* collector,
7219 MemRegion span,
7220 CMSBitMap* verification_bm, CMSBitMap* cms_bm,
7221 CMSMarkStack* mark_stack):
7222 _collector(collector),
7223 _span(span),
7224 _verification_bm(verification_bm),
7225 _cms_bm(cms_bm),
7226 _mark_stack(mark_stack),
7227 _pam_verify_closure(collector, span, verification_bm, cms_bm,
7228 mark_stack)
7229 {
7230 assert(_mark_stack->isEmpty(), "stack should be empty");
7231 _finger = _verification_bm->startWord();
7232 assert(_collector->_restart_addr == NULL, "Sanity check");
7233 assert(_span.contains(_finger), "Out of bounds _finger?");
7234 }
7236 void MarkFromRootsVerifyClosure::reset(HeapWord* addr) {
7237 assert(_mark_stack->isEmpty(), "would cause duplicates on stack");
7238 assert(_span.contains(addr), "Out of bounds _finger?");
7239 _finger = addr;
7240 }
7242 // Should revisit to see if this should be restructured for
7243 // greater efficiency.
7244 bool MarkFromRootsVerifyClosure::do_bit(size_t offset) {
7245 // convert offset into a HeapWord*
7246 HeapWord* addr = _verification_bm->startWord() + offset;
7247 assert(_verification_bm->endWord() && addr < _verification_bm->endWord(),
7248 "address out of range");
7249 assert(_verification_bm->isMarked(addr), "tautology");
7250 assert(_cms_bm->isMarked(addr), "tautology");
7252 assert(_mark_stack->isEmpty(),
7253 "should drain stack to limit stack usage");
7254 // convert addr to an oop preparatory to scanning
7255 oop obj = oop(addr);
7256 assert(obj->is_oop(), "should be an oop");
7257 assert(_finger <= addr, "_finger runneth ahead");
7258 // advance the finger to right end of this object
7259 _finger = addr + obj->size();
7260 assert(_finger > addr, "we just incremented it above");
7261 // Note: the finger doesn't advance while we drain
7262 // the stack below.
7263 bool res = _mark_stack->push(obj);
7264 assert(res, "Empty non-zero size stack should have space for single push");
7265 while (!_mark_stack->isEmpty()) {
7266 oop new_oop = _mark_stack->pop();
7267 assert(new_oop->is_oop(), "Oops! expected to pop an oop");
7268 // now scan this oop's oops
7269 new_oop->oop_iterate(&_pam_verify_closure);
7270 }
7271 assert(_mark_stack->isEmpty(), "tautology, emphasizing post-condition");
7272 return true;
7273 }
7275 PushAndMarkVerifyClosure::PushAndMarkVerifyClosure(
7276 CMSCollector* collector, MemRegion span,
7277 CMSBitMap* verification_bm, CMSBitMap* cms_bm,
7278 CMSMarkStack* mark_stack):
7279 OopClosure(collector->ref_processor()),
7280 _collector(collector),
7281 _span(span),
7282 _verification_bm(verification_bm),
7283 _cms_bm(cms_bm),
7284 _mark_stack(mark_stack)
7285 { }
7287 void PushAndMarkVerifyClosure::do_oop(oop* p) { PushAndMarkVerifyClosure::do_oop_work(p); }
7288 void PushAndMarkVerifyClosure::do_oop(narrowOop* p) { PushAndMarkVerifyClosure::do_oop_work(p); }
7290 // Upon stack overflow, we discard (part of) the stack,
7291 // remembering the least address amongst those discarded
7292 // in CMSCollector's _restart_address.
7293 void PushAndMarkVerifyClosure::handle_stack_overflow(HeapWord* lost) {
7294 // Remember the least grey address discarded
7295 HeapWord* ra = (HeapWord*)_mark_stack->least_value(lost);
7296 _collector->lower_restart_addr(ra);
7297 _mark_stack->reset(); // discard stack contents
7298 _mark_stack->expand(); // expand the stack if possible
7299 }
7301 void PushAndMarkVerifyClosure::do_oop(oop obj) {
7302 assert(obj->is_oop_or_null(), "expected an oop or NULL");
7303 HeapWord* addr = (HeapWord*)obj;
7304 if (_span.contains(addr) && !_verification_bm->isMarked(addr)) {
7305 // Oop lies in _span and isn't yet grey or black
7306 _verification_bm->mark(addr); // now grey
7307 if (!_cms_bm->isMarked(addr)) {
7308 oop(addr)->print();
7309 gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)",
7310 addr);
7311 fatal("... aborting");
7312 }
7314 if (!_mark_stack->push(obj)) { // stack overflow
7315 if (PrintCMSStatistics != 0) {
7316 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
7317 SIZE_FORMAT, _mark_stack->capacity());
7318 }
7319 assert(_mark_stack->isFull(), "Else push should have succeeded");
7320 handle_stack_overflow(addr);
7321 }
7322 // anything including and to the right of _finger
7323 // will be scanned as we iterate over the remainder of the
7324 // bit map
7325 }
7326 }
7328 PushOrMarkClosure::PushOrMarkClosure(CMSCollector* collector,
7329 MemRegion span,
7330 CMSBitMap* bitMap, CMSMarkStack* markStack,
7331 CMSMarkStack* revisitStack,
7332 HeapWord* finger, MarkFromRootsClosure* parent) :
7333 KlassRememberingOopClosure(collector, collector->ref_processor(), revisitStack),
7334 _span(span),
7335 _bitMap(bitMap),
7336 _markStack(markStack),
7337 _finger(finger),
7338 _parent(parent)
7339 { }
7341 Par_PushOrMarkClosure::Par_PushOrMarkClosure(CMSCollector* collector,
7342 MemRegion span,
7343 CMSBitMap* bit_map,
7344 OopTaskQueue* work_queue,
7345 CMSMarkStack* overflow_stack,
7346 CMSMarkStack* revisit_stack,
7347 HeapWord* finger,
7348 HeapWord** global_finger_addr,
7349 Par_MarkFromRootsClosure* parent) :
7350 Par_KlassRememberingOopClosure(collector,
7351 collector->ref_processor(),
7352 revisit_stack),
7353 _whole_span(collector->_span),
7354 _span(span),
7355 _bit_map(bit_map),
7356 _work_queue(work_queue),
7357 _overflow_stack(overflow_stack),
7358 _finger(finger),
7359 _global_finger_addr(global_finger_addr),
7360 _parent(parent)
7361 { }
7363 // Assumes thread-safe access by callers, who are
7364 // responsible for mutual exclusion.
7365 void CMSCollector::lower_restart_addr(HeapWord* low) {
7366 assert(_span.contains(low), "Out of bounds addr");
7367 if (_restart_addr == NULL) {
7368 _restart_addr = low;
7369 } else {
7370 _restart_addr = MIN2(_restart_addr, low);
7371 }
7372 }
7374 // Upon stack overflow, we discard (part of) the stack,
7375 // remembering the least address amongst those discarded
7376 // in CMSCollector's _restart_address.
7377 void PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) {
7378 // Remember the least grey address discarded
7379 HeapWord* ra = (HeapWord*)_markStack->least_value(lost);
7380 _collector->lower_restart_addr(ra);
7381 _markStack->reset(); // discard stack contents
7382 _markStack->expand(); // expand the stack if possible
7383 }
7385 // Upon stack overflow, we discard (part of) the stack,
7386 // remembering the least address amongst those discarded
7387 // in CMSCollector's _restart_address.
7388 void Par_PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) {
7389 // We need to do this under a mutex to prevent other
7390 // workers from interfering with the work done below.
7391 MutexLockerEx ml(_overflow_stack->par_lock(),
7392 Mutex::_no_safepoint_check_flag);
7393 // Remember the least grey address discarded
7394 HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost);
7395 _collector->lower_restart_addr(ra);
7396 _overflow_stack->reset(); // discard stack contents
7397 _overflow_stack->expand(); // expand the stack if possible
7398 }
7400 void PushOrMarkClosure::do_oop(oop obj) {
7401 // Ignore mark word because we are running concurrent with mutators.
7402 assert(obj->is_oop_or_null(true), "expected an oop or NULL");
7403 HeapWord* addr = (HeapWord*)obj;
7404 if (_span.contains(addr) && !_bitMap->isMarked(addr)) {
7405 // Oop lies in _span and isn't yet grey or black
7406 _bitMap->mark(addr); // now grey
7407 if (addr < _finger) {
7408 // the bit map iteration has already either passed, or
7409 // sampled, this bit in the bit map; we'll need to
7410 // use the marking stack to scan this oop's oops.
7411 bool simulate_overflow = false;
7412 NOT_PRODUCT(
7413 if (CMSMarkStackOverflowALot &&
7414 _collector->simulate_overflow()) {
7415 // simulate a stack overflow
7416 simulate_overflow = true;
7417 }
7418 )
7419 if (simulate_overflow || !_markStack->push(obj)) { // stack overflow
7420 if (PrintCMSStatistics != 0) {
7421 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
7422 SIZE_FORMAT, _markStack->capacity());
7423 }
7424 assert(simulate_overflow || _markStack->isFull(), "Else push should have succeeded");
7425 handle_stack_overflow(addr);
7426 }
7427 }
7428 // anything including and to the right of _finger
7429 // will be scanned as we iterate over the remainder of the
7430 // bit map
7431 do_yield_check();
7432 }
7433 }
7435 void PushOrMarkClosure::do_oop(oop* p) { PushOrMarkClosure::do_oop_work(p); }
7436 void PushOrMarkClosure::do_oop(narrowOop* p) { PushOrMarkClosure::do_oop_work(p); }
7438 void Par_PushOrMarkClosure::do_oop(oop obj) {
7439 // Ignore mark word because we are running concurrent with mutators.
7440 assert(obj->is_oop_or_null(true), "expected an oop or NULL");
7441 HeapWord* addr = (HeapWord*)obj;
7442 if (_whole_span.contains(addr) && !_bit_map->isMarked(addr)) {
7443 // Oop lies in _span and isn't yet grey or black
7444 // We read the global_finger (volatile read) strictly after marking oop
7445 bool res = _bit_map->par_mark(addr); // now grey
7446 volatile HeapWord** gfa = (volatile HeapWord**)_global_finger_addr;
7447 // Should we push this marked oop on our stack?
7448 // -- if someone else marked it, nothing to do
7449 // -- if target oop is above global finger nothing to do
7450 // -- if target oop is in chunk and above local finger
7451 // then nothing to do
7452 // -- else push on work queue
7453 if ( !res // someone else marked it, they will deal with it
7454 || (addr >= *gfa) // will be scanned in a later task
7455 || (_span.contains(addr) && addr >= _finger)) { // later in this chunk
7456 return;
7457 }
7458 // the bit map iteration has already either passed, or
7459 // sampled, this bit in the bit map; we'll need to
7460 // use the marking stack to scan this oop's oops.
7461 bool simulate_overflow = false;
7462 NOT_PRODUCT(
7463 if (CMSMarkStackOverflowALot &&
7464 _collector->simulate_overflow()) {
7465 // simulate a stack overflow
7466 simulate_overflow = true;
7467 }
7468 )
7469 if (simulate_overflow ||
7470 !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) {
7471 // stack overflow
7472 if (PrintCMSStatistics != 0) {
7473 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
7474 SIZE_FORMAT, _overflow_stack->capacity());
7475 }
7476 // We cannot assert that the overflow stack is full because
7477 // it may have been emptied since.
7478 assert(simulate_overflow ||
7479 _work_queue->size() == _work_queue->max_elems(),
7480 "Else push should have succeeded");
7481 handle_stack_overflow(addr);
7482 }
7483 do_yield_check();
7484 }
7485 }
7487 void Par_PushOrMarkClosure::do_oop(oop* p) { Par_PushOrMarkClosure::do_oop_work(p); }
7488 void Par_PushOrMarkClosure::do_oop(narrowOop* p) { Par_PushOrMarkClosure::do_oop_work(p); }
7490 KlassRememberingOopClosure::KlassRememberingOopClosure(CMSCollector* collector,
7491 ReferenceProcessor* rp,
7492 CMSMarkStack* revisit_stack) :
7493 OopClosure(rp),
7494 _collector(collector),
7495 _revisit_stack(revisit_stack),
7496 _should_remember_klasses(collector->should_unload_classes()) {}
7498 PushAndMarkClosure::PushAndMarkClosure(CMSCollector* collector,
7499 MemRegion span,
7500 ReferenceProcessor* rp,
7501 CMSBitMap* bit_map,
7502 CMSBitMap* mod_union_table,
7503 CMSMarkStack* mark_stack,
7504 CMSMarkStack* revisit_stack,
7505 bool concurrent_precleaning):
7506 KlassRememberingOopClosure(collector, rp, revisit_stack),
7507 _span(span),
7508 _bit_map(bit_map),
7509 _mod_union_table(mod_union_table),
7510 _mark_stack(mark_stack),
7511 _concurrent_precleaning(concurrent_precleaning)
7512 {
7513 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
7514 }
7516 // Grey object rescan during pre-cleaning and second checkpoint phases --
7517 // the non-parallel version (the parallel version appears further below.)
7518 void PushAndMarkClosure::do_oop(oop obj) {
7519 // Ignore mark word verification. If during concurrent precleaning,
7520 // the object monitor may be locked. If during the checkpoint
7521 // phases, the object may already have been reached by a different
7522 // path and may be at the end of the global overflow list (so
7523 // the mark word may be NULL).
7524 assert(obj->is_oop_or_null(true /* ignore mark word */),
7525 "expected an oop or NULL");
7526 HeapWord* addr = (HeapWord*)obj;
7527 // Check if oop points into the CMS generation
7528 // and is not marked
7529 if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
7530 // a white object ...
7531 _bit_map->mark(addr); // ... now grey
7532 // push on the marking stack (grey set)
7533 bool simulate_overflow = false;
7534 NOT_PRODUCT(
7535 if (CMSMarkStackOverflowALot &&
7536 _collector->simulate_overflow()) {
7537 // simulate a stack overflow
7538 simulate_overflow = true;
7539 }
7540 )
7541 if (simulate_overflow || !_mark_stack->push(obj)) {
7542 if (_concurrent_precleaning) {
7543 // During precleaning we can just dirty the appropriate card(s)
7544 // in the mod union table, thus ensuring that the object remains
7545 // in the grey set and continue. In the case of object arrays
7546 // we need to dirty all of the cards that the object spans,
7547 // since the rescan of object arrays will be limited to the
7548 // dirty cards.
7549 // Note that no one can be intefering with us in this action
7550 // of dirtying the mod union table, so no locking or atomics
7551 // are required.
7552 if (obj->is_objArray()) {
7553 size_t sz = obj->size();
7554 HeapWord* end_card_addr = (HeapWord*)round_to(
7555 (intptr_t)(addr+sz), CardTableModRefBS::card_size);
7556 MemRegion redirty_range = MemRegion(addr, end_card_addr);
7557 assert(!redirty_range.is_empty(), "Arithmetical tautology");
7558 _mod_union_table->mark_range(redirty_range);
7559 } else {
7560 _mod_union_table->mark(addr);
7561 }
7562 _collector->_ser_pmc_preclean_ovflw++;
7563 } else {
7564 // During the remark phase, we need to remember this oop
7565 // in the overflow list.
7566 _collector->push_on_overflow_list(obj);
7567 _collector->_ser_pmc_remark_ovflw++;
7568 }
7569 }
7570 }
7571 }
7573 Par_PushAndMarkClosure::Par_PushAndMarkClosure(CMSCollector* collector,
7574 MemRegion span,
7575 ReferenceProcessor* rp,
7576 CMSBitMap* bit_map,
7577 OopTaskQueue* work_queue,
7578 CMSMarkStack* revisit_stack):
7579 Par_KlassRememberingOopClosure(collector, rp, revisit_stack),
7580 _span(span),
7581 _bit_map(bit_map),
7582 _work_queue(work_queue)
7583 {
7584 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
7585 }
7587 void PushAndMarkClosure::do_oop(oop* p) { PushAndMarkClosure::do_oop_work(p); }
7588 void PushAndMarkClosure::do_oop(narrowOop* p) { PushAndMarkClosure::do_oop_work(p); }
7590 // Grey object rescan during second checkpoint phase --
7591 // the parallel version.
7592 void Par_PushAndMarkClosure::do_oop(oop obj) {
7593 // In the assert below, we ignore the mark word because
7594 // this oop may point to an already visited object that is
7595 // on the overflow stack (in which case the mark word has
7596 // been hijacked for chaining into the overflow stack --
7597 // if this is the last object in the overflow stack then
7598 // its mark word will be NULL). Because this object may
7599 // have been subsequently popped off the global overflow
7600 // stack, and the mark word possibly restored to the prototypical
7601 // value, by the time we get to examined this failing assert in
7602 // the debugger, is_oop_or_null(false) may subsequently start
7603 // to hold.
7604 assert(obj->is_oop_or_null(true),
7605 "expected an oop or NULL");
7606 HeapWord* addr = (HeapWord*)obj;
7607 // Check if oop points into the CMS generation
7608 // and is not marked
7609 if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
7610 // a white object ...
7611 // If we manage to "claim" the object, by being the
7612 // first thread to mark it, then we push it on our
7613 // marking stack
7614 if (_bit_map->par_mark(addr)) { // ... now grey
7615 // push on work queue (grey set)
7616 bool simulate_overflow = false;
7617 NOT_PRODUCT(
7618 if (CMSMarkStackOverflowALot &&
7619 _collector->par_simulate_overflow()) {
7620 // simulate a stack overflow
7621 simulate_overflow = true;
7622 }
7623 )
7624 if (simulate_overflow || !_work_queue->push(obj)) {
7625 _collector->par_push_on_overflow_list(obj);
7626 _collector->_par_pmc_remark_ovflw++; // imprecise OK: no need to CAS
7627 }
7628 } // Else, some other thread got there first
7629 }
7630 }
7632 void Par_PushAndMarkClosure::do_oop(oop* p) { Par_PushAndMarkClosure::do_oop_work(p); }
7633 void Par_PushAndMarkClosure::do_oop(narrowOop* p) { Par_PushAndMarkClosure::do_oop_work(p); }
7635 void CMSPrecleanRefsYieldClosure::do_yield_work() {
7636 DEBUG_ONLY(RememberKlassesChecker mux(false);)
7637 Mutex* bml = _collector->bitMapLock();
7638 assert_lock_strong(bml);
7639 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
7640 "CMS thread should hold CMS token");
7642 bml->unlock();
7643 ConcurrentMarkSweepThread::desynchronize(true);
7645 ConcurrentMarkSweepThread::acknowledge_yield_request();
7647 _collector->stopTimer();
7648 GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
7649 if (PrintCMSStatistics != 0) {
7650 _collector->incrementYields();
7651 }
7652 _collector->icms_wait();
7654 // See the comment in coordinator_yield()
7655 for (unsigned i = 0; i < CMSYieldSleepCount &&
7656 ConcurrentMarkSweepThread::should_yield() &&
7657 !CMSCollector::foregroundGCIsActive(); ++i) {
7658 os::sleep(Thread::current(), 1, false);
7659 ConcurrentMarkSweepThread::acknowledge_yield_request();
7660 }
7662 ConcurrentMarkSweepThread::synchronize(true);
7663 bml->lock();
7665 _collector->startTimer();
7666 }
7668 bool CMSPrecleanRefsYieldClosure::should_return() {
7669 if (ConcurrentMarkSweepThread::should_yield()) {
7670 do_yield_work();
7671 }
7672 return _collector->foregroundGCIsActive();
7673 }
7675 void MarkFromDirtyCardsClosure::do_MemRegion(MemRegion mr) {
7676 assert(((size_t)mr.start())%CardTableModRefBS::card_size_in_words == 0,
7677 "mr should be aligned to start at a card boundary");
7678 // We'd like to assert:
7679 // assert(mr.word_size()%CardTableModRefBS::card_size_in_words == 0,
7680 // "mr should be a range of cards");
7681 // However, that would be too strong in one case -- the last
7682 // partition ends at _unallocated_block which, in general, can be
7683 // an arbitrary boundary, not necessarily card aligned.
7684 if (PrintCMSStatistics != 0) {
7685 _num_dirty_cards +=
7686 mr.word_size()/CardTableModRefBS::card_size_in_words;
7687 }
7688 _space->object_iterate_mem(mr, &_scan_cl);
7689 }
7691 SweepClosure::SweepClosure(CMSCollector* collector,
7692 ConcurrentMarkSweepGeneration* g,
7693 CMSBitMap* bitMap, bool should_yield) :
7694 _collector(collector),
7695 _g(g),
7696 _sp(g->cmsSpace()),
7697 _limit(_sp->sweep_limit()),
7698 _freelistLock(_sp->freelistLock()),
7699 _bitMap(bitMap),
7700 _yield(should_yield),
7701 _inFreeRange(false), // No free range at beginning of sweep
7702 _freeRangeInFreeLists(false), // No free range at beginning of sweep
7703 _lastFreeRangeCoalesced(false),
7704 _freeFinger(g->used_region().start())
7705 {
7706 NOT_PRODUCT(
7707 _numObjectsFreed = 0;
7708 _numWordsFreed = 0;
7709 _numObjectsLive = 0;
7710 _numWordsLive = 0;
7711 _numObjectsAlreadyFree = 0;
7712 _numWordsAlreadyFree = 0;
7713 _last_fc = NULL;
7715 _sp->initializeIndexedFreeListArrayReturnedBytes();
7716 _sp->dictionary()->initializeDictReturnedBytes();
7717 )
7718 assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
7719 "sweep _limit out of bounds");
7720 if (CMSTraceSweeper) {
7721 gclog_or_tty->print("\n====================\nStarting new sweep\n");
7722 }
7723 }
7725 // We need this destructor to reclaim any space at the end
7726 // of the space, which do_blk below may not have added back to
7727 // the free lists. [basically dealing with the "fringe effect"]
7728 SweepClosure::~SweepClosure() {
7729 assert_lock_strong(_freelistLock);
7730 // this should be treated as the end of a free run if any
7731 // The current free range should be returned to the free lists
7732 // as one coalesced chunk.
7733 if (inFreeRange()) {
7734 flushCurFreeChunk(freeFinger(),
7735 pointer_delta(_limit, freeFinger()));
7736 assert(freeFinger() < _limit, "the finger pointeth off base");
7737 if (CMSTraceSweeper) {
7738 gclog_or_tty->print("destructor:");
7739 gclog_or_tty->print("Sweep:put_free_blk 0x%x ("SIZE_FORMAT") "
7740 "[coalesced:"SIZE_FORMAT"]\n",
7741 freeFinger(), pointer_delta(_limit, freeFinger()),
7742 lastFreeRangeCoalesced());
7743 }
7744 }
7745 NOT_PRODUCT(
7746 if (Verbose && PrintGC) {
7747 gclog_or_tty->print("Collected "SIZE_FORMAT" objects, "
7748 SIZE_FORMAT " bytes",
7749 _numObjectsFreed, _numWordsFreed*sizeof(HeapWord));
7750 gclog_or_tty->print_cr("\nLive "SIZE_FORMAT" objects, "
7751 SIZE_FORMAT" bytes "
7752 "Already free "SIZE_FORMAT" objects, "SIZE_FORMAT" bytes",
7753 _numObjectsLive, _numWordsLive*sizeof(HeapWord),
7754 _numObjectsAlreadyFree, _numWordsAlreadyFree*sizeof(HeapWord));
7755 size_t totalBytes = (_numWordsFreed + _numWordsLive + _numWordsAlreadyFree) *
7756 sizeof(HeapWord);
7757 gclog_or_tty->print_cr("Total sweep: "SIZE_FORMAT" bytes", totalBytes);
7759 if (PrintCMSStatistics && CMSVerifyReturnedBytes) {
7760 size_t indexListReturnedBytes = _sp->sumIndexedFreeListArrayReturnedBytes();
7761 size_t dictReturnedBytes = _sp->dictionary()->sumDictReturnedBytes();
7762 size_t returnedBytes = indexListReturnedBytes + dictReturnedBytes;
7763 gclog_or_tty->print("Returned "SIZE_FORMAT" bytes", returnedBytes);
7764 gclog_or_tty->print(" Indexed List Returned "SIZE_FORMAT" bytes",
7765 indexListReturnedBytes);
7766 gclog_or_tty->print_cr(" Dictionary Returned "SIZE_FORMAT" bytes",
7767 dictReturnedBytes);
7768 }
7769 }
7770 )
7771 // Now, in debug mode, just null out the sweep_limit
7772 NOT_PRODUCT(_sp->clear_sweep_limit();)
7773 if (CMSTraceSweeper) {
7774 gclog_or_tty->print("end of sweep\n================\n");
7775 }
7776 }
7778 void SweepClosure::initialize_free_range(HeapWord* freeFinger,
7779 bool freeRangeInFreeLists) {
7780 if (CMSTraceSweeper) {
7781 gclog_or_tty->print("---- Start free range 0x%x with free block [%d] (%d)\n",
7782 freeFinger, _sp->block_size(freeFinger),
7783 freeRangeInFreeLists);
7784 }
7785 assert(!inFreeRange(), "Trampling existing free range");
7786 set_inFreeRange(true);
7787 set_lastFreeRangeCoalesced(false);
7789 set_freeFinger(freeFinger);
7790 set_freeRangeInFreeLists(freeRangeInFreeLists);
7791 if (CMSTestInFreeList) {
7792 if (freeRangeInFreeLists) {
7793 FreeChunk* fc = (FreeChunk*) freeFinger;
7794 assert(fc->isFree(), "A chunk on the free list should be free.");
7795 assert(fc->size() > 0, "Free range should have a size");
7796 assert(_sp->verifyChunkInFreeLists(fc), "Chunk is not in free lists");
7797 }
7798 }
7799 }
7801 // Note that the sweeper runs concurrently with mutators. Thus,
7802 // it is possible for direct allocation in this generation to happen
7803 // in the middle of the sweep. Note that the sweeper also coalesces
7804 // contiguous free blocks. Thus, unless the sweeper and the allocator
7805 // synchronize appropriately freshly allocated blocks may get swept up.
7806 // This is accomplished by the sweeper locking the free lists while
7807 // it is sweeping. Thus blocks that are determined to be free are
7808 // indeed free. There is however one additional complication:
7809 // blocks that have been allocated since the final checkpoint and
7810 // mark, will not have been marked and so would be treated as
7811 // unreachable and swept up. To prevent this, the allocator marks
7812 // the bit map when allocating during the sweep phase. This leads,
7813 // however, to a further complication -- objects may have been allocated
7814 // but not yet initialized -- in the sense that the header isn't yet
7815 // installed. The sweeper can not then determine the size of the block
7816 // in order to skip over it. To deal with this case, we use a technique
7817 // (due to Printezis) to encode such uninitialized block sizes in the
7818 // bit map. Since the bit map uses a bit per every HeapWord, but the
7819 // CMS generation has a minimum object size of 3 HeapWords, it follows
7820 // that "normal marks" won't be adjacent in the bit map (there will
7821 // always be at least two 0 bits between successive 1 bits). We make use
7822 // of these "unused" bits to represent uninitialized blocks -- the bit
7823 // corresponding to the start of the uninitialized object and the next
7824 // bit are both set. Finally, a 1 bit marks the end of the object that
7825 // started with the two consecutive 1 bits to indicate its potentially
7826 // uninitialized state.
7828 size_t SweepClosure::do_blk_careful(HeapWord* addr) {
7829 FreeChunk* fc = (FreeChunk*)addr;
7830 size_t res;
7832 // check if we are done sweepinrg
7833 if (addr == _limit) { // we have swept up to the limit, do nothing more
7834 assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
7835 "sweep _limit out of bounds");
7836 // help the closure application finish
7837 return pointer_delta(_sp->end(), _limit);
7838 }
7839 assert(addr <= _limit, "sweep invariant");
7841 // check if we should yield
7842 do_yield_check(addr);
7843 if (fc->isFree()) {
7844 // Chunk that is already free
7845 res = fc->size();
7846 doAlreadyFreeChunk(fc);
7847 debug_only(_sp->verifyFreeLists());
7848 assert(res == fc->size(), "Don't expect the size to change");
7849 NOT_PRODUCT(
7850 _numObjectsAlreadyFree++;
7851 _numWordsAlreadyFree += res;
7852 )
7853 NOT_PRODUCT(_last_fc = fc;)
7854 } else if (!_bitMap->isMarked(addr)) {
7855 // Chunk is fresh garbage
7856 res = doGarbageChunk(fc);
7857 debug_only(_sp->verifyFreeLists());
7858 NOT_PRODUCT(
7859 _numObjectsFreed++;
7860 _numWordsFreed += res;
7861 )
7862 } else {
7863 // Chunk that is alive.
7864 res = doLiveChunk(fc);
7865 debug_only(_sp->verifyFreeLists());
7866 NOT_PRODUCT(
7867 _numObjectsLive++;
7868 _numWordsLive += res;
7869 )
7870 }
7871 return res;
7872 }
7874 // For the smart allocation, record following
7875 // split deaths - a free chunk is removed from its free list because
7876 // it is being split into two or more chunks.
7877 // split birth - a free chunk is being added to its free list because
7878 // a larger free chunk has been split and resulted in this free chunk.
7879 // coal death - a free chunk is being removed from its free list because
7880 // it is being coalesced into a large free chunk.
7881 // coal birth - a free chunk is being added to its free list because
7882 // it was created when two or more free chunks where coalesced into
7883 // this free chunk.
7884 //
7885 // These statistics are used to determine the desired number of free
7886 // chunks of a given size. The desired number is chosen to be relative
7887 // to the end of a CMS sweep. The desired number at the end of a sweep
7888 // is the
7889 // count-at-end-of-previous-sweep (an amount that was enough)
7890 // - count-at-beginning-of-current-sweep (the excess)
7891 // + split-births (gains in this size during interval)
7892 // - split-deaths (demands on this size during interval)
7893 // where the interval is from the end of one sweep to the end of the
7894 // next.
7895 //
7896 // When sweeping the sweeper maintains an accumulated chunk which is
7897 // the chunk that is made up of chunks that have been coalesced. That
7898 // will be termed the left-hand chunk. A new chunk of garbage that
7899 // is being considered for coalescing will be referred to as the
7900 // right-hand chunk.
7901 //
7902 // When making a decision on whether to coalesce a right-hand chunk with
7903 // the current left-hand chunk, the current count vs. the desired count
7904 // of the left-hand chunk is considered. Also if the right-hand chunk
7905 // is near the large chunk at the end of the heap (see
7906 // ConcurrentMarkSweepGeneration::isNearLargestChunk()), then the
7907 // left-hand chunk is coalesced.
7908 //
7909 // When making a decision about whether to split a chunk, the desired count
7910 // vs. the current count of the candidate to be split is also considered.
7911 // If the candidate is underpopulated (currently fewer chunks than desired)
7912 // a chunk of an overpopulated (currently more chunks than desired) size may
7913 // be chosen. The "hint" associated with a free list, if non-null, points
7914 // to a free list which may be overpopulated.
7915 //
7917 void SweepClosure::doAlreadyFreeChunk(FreeChunk* fc) {
7918 size_t size = fc->size();
7919 // Chunks that cannot be coalesced are not in the
7920 // free lists.
7921 if (CMSTestInFreeList && !fc->cantCoalesce()) {
7922 assert(_sp->verifyChunkInFreeLists(fc),
7923 "free chunk should be in free lists");
7924 }
7925 // a chunk that is already free, should not have been
7926 // marked in the bit map
7927 HeapWord* addr = (HeapWord*) fc;
7928 assert(!_bitMap->isMarked(addr), "free chunk should be unmarked");
7929 // Verify that the bit map has no bits marked between
7930 // addr and purported end of this block.
7931 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
7933 // Some chunks cannot be coalesced in under any circumstances.
7934 // See the definition of cantCoalesce().
7935 if (!fc->cantCoalesce()) {
7936 // This chunk can potentially be coalesced.
7937 if (_sp->adaptive_freelists()) {
7938 // All the work is done in
7939 doPostIsFreeOrGarbageChunk(fc, size);
7940 } else { // Not adaptive free lists
7941 // this is a free chunk that can potentially be coalesced by the sweeper;
7942 if (!inFreeRange()) {
7943 // if the next chunk is a free block that can't be coalesced
7944 // it doesn't make sense to remove this chunk from the free lists
7945 FreeChunk* nextChunk = (FreeChunk*)(addr + size);
7946 assert((HeapWord*)nextChunk <= _limit, "sweep invariant");
7947 if ((HeapWord*)nextChunk < _limit && // there's a next chunk...
7948 nextChunk->isFree() && // which is free...
7949 nextChunk->cantCoalesce()) { // ... but cant be coalesced
7950 // nothing to do
7951 } else {
7952 // Potentially the start of a new free range:
7953 // Don't eagerly remove it from the free lists.
7954 // No need to remove it if it will just be put
7955 // back again. (Also from a pragmatic point of view
7956 // if it is a free block in a region that is beyond
7957 // any allocated blocks, an assertion will fail)
7958 // Remember the start of a free run.
7959 initialize_free_range(addr, true);
7960 // end - can coalesce with next chunk
7961 }
7962 } else {
7963 // the midst of a free range, we are coalescing
7964 debug_only(record_free_block_coalesced(fc);)
7965 if (CMSTraceSweeper) {
7966 gclog_or_tty->print(" -- pick up free block 0x%x (%d)\n", fc, size);
7967 }
7968 // remove it from the free lists
7969 _sp->removeFreeChunkFromFreeLists(fc);
7970 set_lastFreeRangeCoalesced(true);
7971 // If the chunk is being coalesced and the current free range is
7972 // in the free lists, remove the current free range so that it
7973 // will be returned to the free lists in its entirety - all
7974 // the coalesced pieces included.
7975 if (freeRangeInFreeLists()) {
7976 FreeChunk* ffc = (FreeChunk*) freeFinger();
7977 assert(ffc->size() == pointer_delta(addr, freeFinger()),
7978 "Size of free range is inconsistent with chunk size.");
7979 if (CMSTestInFreeList) {
7980 assert(_sp->verifyChunkInFreeLists(ffc),
7981 "free range is not in free lists");
7982 }
7983 _sp->removeFreeChunkFromFreeLists(ffc);
7984 set_freeRangeInFreeLists(false);
7985 }
7986 }
7987 }
7988 } else {
7989 // Code path common to both original and adaptive free lists.
7991 // cant coalesce with previous block; this should be treated
7992 // as the end of a free run if any
7993 if (inFreeRange()) {
7994 // we kicked some butt; time to pick up the garbage
7995 assert(freeFinger() < addr, "the finger pointeth off base");
7996 flushCurFreeChunk(freeFinger(), pointer_delta(addr, freeFinger()));
7997 }
7998 // else, nothing to do, just continue
7999 }
8000 }
8002 size_t SweepClosure::doGarbageChunk(FreeChunk* fc) {
8003 // This is a chunk of garbage. It is not in any free list.
8004 // Add it to a free list or let it possibly be coalesced into
8005 // a larger chunk.
8006 HeapWord* addr = (HeapWord*) fc;
8007 size_t size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size());
8009 if (_sp->adaptive_freelists()) {
8010 // Verify that the bit map has no bits marked between
8011 // addr and purported end of just dead object.
8012 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
8014 doPostIsFreeOrGarbageChunk(fc, size);
8015 } else {
8016 if (!inFreeRange()) {
8017 // start of a new free range
8018 assert(size > 0, "A free range should have a size");
8019 initialize_free_range(addr, false);
8021 } else {
8022 // this will be swept up when we hit the end of the
8023 // free range
8024 if (CMSTraceSweeper) {
8025 gclog_or_tty->print(" -- pick up garbage 0x%x (%d) \n", fc, size);
8026 }
8027 // If the chunk is being coalesced and the current free range is
8028 // in the free lists, remove the current free range so that it
8029 // will be returned to the free lists in its entirety - all
8030 // the coalesced pieces included.
8031 if (freeRangeInFreeLists()) {
8032 FreeChunk* ffc = (FreeChunk*)freeFinger();
8033 assert(ffc->size() == pointer_delta(addr, freeFinger()),
8034 "Size of free range is inconsistent with chunk size.");
8035 if (CMSTestInFreeList) {
8036 assert(_sp->verifyChunkInFreeLists(ffc),
8037 "free range is not in free lists");
8038 }
8039 _sp->removeFreeChunkFromFreeLists(ffc);
8040 set_freeRangeInFreeLists(false);
8041 }
8042 set_lastFreeRangeCoalesced(true);
8043 }
8044 // this will be swept up when we hit the end of the free range
8046 // Verify that the bit map has no bits marked between
8047 // addr and purported end of just dead object.
8048 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
8049 }
8050 return size;
8051 }
8053 size_t SweepClosure::doLiveChunk(FreeChunk* fc) {
8054 HeapWord* addr = (HeapWord*) fc;
8055 // The sweeper has just found a live object. Return any accumulated
8056 // left hand chunk to the free lists.
8057 if (inFreeRange()) {
8058 if (_sp->adaptive_freelists()) {
8059 flushCurFreeChunk(freeFinger(),
8060 pointer_delta(addr, freeFinger()));
8061 } else { // not adaptive freelists
8062 set_inFreeRange(false);
8063 // Add the free range back to the free list if it is not already
8064 // there.
8065 if (!freeRangeInFreeLists()) {
8066 assert(freeFinger() < addr, "the finger pointeth off base");
8067 if (CMSTraceSweeper) {
8068 gclog_or_tty->print("Sweep:put_free_blk 0x%x (%d) "
8069 "[coalesced:%d]\n",
8070 freeFinger(), pointer_delta(addr, freeFinger()),
8071 lastFreeRangeCoalesced());
8072 }
8073 _sp->addChunkAndRepairOffsetTable(freeFinger(),
8074 pointer_delta(addr, freeFinger()), lastFreeRangeCoalesced());
8075 }
8076 }
8077 }
8079 // Common code path for original and adaptive free lists.
8081 // this object is live: we'd normally expect this to be
8082 // an oop, and like to assert the following:
8083 // assert(oop(addr)->is_oop(), "live block should be an oop");
8084 // However, as we commented above, this may be an object whose
8085 // header hasn't yet been initialized.
8086 size_t size;
8087 assert(_bitMap->isMarked(addr), "Tautology for this control point");
8088 if (_bitMap->isMarked(addr + 1)) {
8089 // Determine the size from the bit map, rather than trying to
8090 // compute it from the object header.
8091 HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2);
8092 size = pointer_delta(nextOneAddr + 1, addr);
8093 assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
8094 "alignment problem");
8096 #ifdef DEBUG
8097 if (oop(addr)->klass_or_null() != NULL &&
8098 ( !_collector->should_unload_classes()
8099 || (oop(addr)->is_parsable()) &&
8100 oop(addr)->is_conc_safe())) {
8101 // Ignore mark word because we are running concurrent with mutators
8102 assert(oop(addr)->is_oop(true), "live block should be an oop");
8103 // is_conc_safe is checked before performing this assertion
8104 // because an object that is not is_conc_safe may yet have
8105 // the return from size() correct.
8106 assert(size ==
8107 CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()),
8108 "P-mark and computed size do not agree");
8109 }
8110 #endif
8112 } else {
8113 // This should be an initialized object that's alive.
8114 assert(oop(addr)->klass_or_null() != NULL &&
8115 (!_collector->should_unload_classes()
8116 || oop(addr)->is_parsable()),
8117 "Should be an initialized object");
8118 // Note that there are objects used during class redefinition
8119 // (e.g., merge_cp in VM_RedefineClasses::merge_cp_and_rewrite()
8120 // which are discarded with their is_conc_safe state still
8121 // false. These object may be floating garbage so may be
8122 // seen here. If they are floating garbage their size
8123 // should be attainable from their klass. Do not that
8124 // is_conc_safe() is true for oop(addr).
8125 // Ignore mark word because we are running concurrent with mutators
8126 assert(oop(addr)->is_oop(true), "live block should be an oop");
8127 // Verify that the bit map has no bits marked between
8128 // addr and purported end of this block.
8129 size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size());
8130 assert(size >= 3, "Necessary for Printezis marks to work");
8131 assert(!_bitMap->isMarked(addr+1), "Tautology for this control point");
8132 DEBUG_ONLY(_bitMap->verifyNoOneBitsInRange(addr+2, addr+size);)
8133 }
8134 return size;
8135 }
8137 void SweepClosure::doPostIsFreeOrGarbageChunk(FreeChunk* fc,
8138 size_t chunkSize) {
8139 // doPostIsFreeOrGarbageChunk() should only be called in the smart allocation
8140 // scheme.
8141 bool fcInFreeLists = fc->isFree();
8142 assert(_sp->adaptive_freelists(), "Should only be used in this case.");
8143 assert((HeapWord*)fc <= _limit, "sweep invariant");
8144 if (CMSTestInFreeList && fcInFreeLists) {
8145 assert(_sp->verifyChunkInFreeLists(fc),
8146 "free chunk is not in free lists");
8147 }
8150 if (CMSTraceSweeper) {
8151 gclog_or_tty->print_cr(" -- pick up another chunk at 0x%x (%d)", fc, chunkSize);
8152 }
8154 HeapWord* addr = (HeapWord*) fc;
8156 bool coalesce;
8157 size_t left = pointer_delta(addr, freeFinger());
8158 size_t right = chunkSize;
8159 switch (FLSCoalescePolicy) {
8160 // numeric value forms a coalition aggressiveness metric
8161 case 0: { // never coalesce
8162 coalesce = false;
8163 break;
8164 }
8165 case 1: { // coalesce if left & right chunks on overpopulated lists
8166 coalesce = _sp->coalOverPopulated(left) &&
8167 _sp->coalOverPopulated(right);
8168 break;
8169 }
8170 case 2: { // coalesce if left chunk on overpopulated list (default)
8171 coalesce = _sp->coalOverPopulated(left);
8172 break;
8173 }
8174 case 3: { // coalesce if left OR right chunk on overpopulated list
8175 coalesce = _sp->coalOverPopulated(left) ||
8176 _sp->coalOverPopulated(right);
8177 break;
8178 }
8179 case 4: { // always coalesce
8180 coalesce = true;
8181 break;
8182 }
8183 default:
8184 ShouldNotReachHere();
8185 }
8187 // Should the current free range be coalesced?
8188 // If the chunk is in a free range and either we decided to coalesce above
8189 // or the chunk is near the large block at the end of the heap
8190 // (isNearLargestChunk() returns true), then coalesce this chunk.
8191 bool doCoalesce = inFreeRange() &&
8192 (coalesce || _g->isNearLargestChunk((HeapWord*)fc));
8193 if (doCoalesce) {
8194 // Coalesce the current free range on the left with the new
8195 // chunk on the right. If either is on a free list,
8196 // it must be removed from the list and stashed in the closure.
8197 if (freeRangeInFreeLists()) {
8198 FreeChunk* ffc = (FreeChunk*)freeFinger();
8199 assert(ffc->size() == pointer_delta(addr, freeFinger()),
8200 "Size of free range is inconsistent with chunk size.");
8201 if (CMSTestInFreeList) {
8202 assert(_sp->verifyChunkInFreeLists(ffc),
8203 "Chunk is not in free lists");
8204 }
8205 _sp->coalDeath(ffc->size());
8206 _sp->removeFreeChunkFromFreeLists(ffc);
8207 set_freeRangeInFreeLists(false);
8208 }
8209 if (fcInFreeLists) {
8210 _sp->coalDeath(chunkSize);
8211 assert(fc->size() == chunkSize,
8212 "The chunk has the wrong size or is not in the free lists");
8213 _sp->removeFreeChunkFromFreeLists(fc);
8214 }
8215 set_lastFreeRangeCoalesced(true);
8216 } else { // not in a free range and/or should not coalesce
8217 // Return the current free range and start a new one.
8218 if (inFreeRange()) {
8219 // In a free range but cannot coalesce with the right hand chunk.
8220 // Put the current free range into the free lists.
8221 flushCurFreeChunk(freeFinger(),
8222 pointer_delta(addr, freeFinger()));
8223 }
8224 // Set up for new free range. Pass along whether the right hand
8225 // chunk is in the free lists.
8226 initialize_free_range((HeapWord*)fc, fcInFreeLists);
8227 }
8228 }
8229 void SweepClosure::flushCurFreeChunk(HeapWord* chunk, size_t size) {
8230 assert(inFreeRange(), "Should only be called if currently in a free range.");
8231 assert(size > 0,
8232 "A zero sized chunk cannot be added to the free lists.");
8233 if (!freeRangeInFreeLists()) {
8234 if(CMSTestInFreeList) {
8235 FreeChunk* fc = (FreeChunk*) chunk;
8236 fc->setSize(size);
8237 assert(!_sp->verifyChunkInFreeLists(fc),
8238 "chunk should not be in free lists yet");
8239 }
8240 if (CMSTraceSweeper) {
8241 gclog_or_tty->print_cr(" -- add free block 0x%x (%d) to free lists",
8242 chunk, size);
8243 }
8244 // A new free range is going to be starting. The current
8245 // free range has not been added to the free lists yet or
8246 // was removed so add it back.
8247 // If the current free range was coalesced, then the death
8248 // of the free range was recorded. Record a birth now.
8249 if (lastFreeRangeCoalesced()) {
8250 _sp->coalBirth(size);
8251 }
8252 _sp->addChunkAndRepairOffsetTable(chunk, size,
8253 lastFreeRangeCoalesced());
8254 }
8255 set_inFreeRange(false);
8256 set_freeRangeInFreeLists(false);
8257 }
8259 // We take a break if we've been at this for a while,
8260 // so as to avoid monopolizing the locks involved.
8261 void SweepClosure::do_yield_work(HeapWord* addr) {
8262 // Return current free chunk being used for coalescing (if any)
8263 // to the appropriate freelist. After yielding, the next
8264 // free block encountered will start a coalescing range of
8265 // free blocks. If the next free block is adjacent to the
8266 // chunk just flushed, they will need to wait for the next
8267 // sweep to be coalesced.
8268 if (inFreeRange()) {
8269 flushCurFreeChunk(freeFinger(), pointer_delta(addr, freeFinger()));
8270 }
8272 // First give up the locks, then yield, then re-lock.
8273 // We should probably use a constructor/destructor idiom to
8274 // do this unlock/lock or modify the MutexUnlocker class to
8275 // serve our purpose. XXX
8276 assert_lock_strong(_bitMap->lock());
8277 assert_lock_strong(_freelistLock);
8278 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
8279 "CMS thread should hold CMS token");
8280 _bitMap->lock()->unlock();
8281 _freelistLock->unlock();
8282 ConcurrentMarkSweepThread::desynchronize(true);
8283 ConcurrentMarkSweepThread::acknowledge_yield_request();
8284 _collector->stopTimer();
8285 GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
8286 if (PrintCMSStatistics != 0) {
8287 _collector->incrementYields();
8288 }
8289 _collector->icms_wait();
8291 // See the comment in coordinator_yield()
8292 for (unsigned i = 0; i < CMSYieldSleepCount &&
8293 ConcurrentMarkSweepThread::should_yield() &&
8294 !CMSCollector::foregroundGCIsActive(); ++i) {
8295 os::sleep(Thread::current(), 1, false);
8296 ConcurrentMarkSweepThread::acknowledge_yield_request();
8297 }
8299 ConcurrentMarkSweepThread::synchronize(true);
8300 _freelistLock->lock();
8301 _bitMap->lock()->lock_without_safepoint_check();
8302 _collector->startTimer();
8303 }
8305 #ifndef PRODUCT
8306 // This is actually very useful in a product build if it can
8307 // be called from the debugger. Compile it into the product
8308 // as needed.
8309 bool debug_verifyChunkInFreeLists(FreeChunk* fc) {
8310 return debug_cms_space->verifyChunkInFreeLists(fc);
8311 }
8313 void SweepClosure::record_free_block_coalesced(FreeChunk* fc) const {
8314 if (CMSTraceSweeper) {
8315 gclog_or_tty->print("Sweep:coal_free_blk 0x%x (%d)\n", fc, fc->size());
8316 }
8317 }
8318 #endif
8320 // CMSIsAliveClosure
8321 bool CMSIsAliveClosure::do_object_b(oop obj) {
8322 HeapWord* addr = (HeapWord*)obj;
8323 return addr != NULL &&
8324 (!_span.contains(addr) || _bit_map->isMarked(addr));
8325 }
8327 CMSKeepAliveClosure::CMSKeepAliveClosure( CMSCollector* collector,
8328 MemRegion span,
8329 CMSBitMap* bit_map, CMSMarkStack* mark_stack,
8330 CMSMarkStack* revisit_stack, bool cpc):
8331 KlassRememberingOopClosure(collector, NULL, revisit_stack),
8332 _span(span),
8333 _bit_map(bit_map),
8334 _mark_stack(mark_stack),
8335 _concurrent_precleaning(cpc) {
8336 assert(!_span.is_empty(), "Empty span could spell trouble");
8337 }
8340 // CMSKeepAliveClosure: the serial version
8341 void CMSKeepAliveClosure::do_oop(oop obj) {
8342 HeapWord* addr = (HeapWord*)obj;
8343 if (_span.contains(addr) &&
8344 !_bit_map->isMarked(addr)) {
8345 _bit_map->mark(addr);
8346 bool simulate_overflow = false;
8347 NOT_PRODUCT(
8348 if (CMSMarkStackOverflowALot &&
8349 _collector->simulate_overflow()) {
8350 // simulate a stack overflow
8351 simulate_overflow = true;
8352 }
8353 )
8354 if (simulate_overflow || !_mark_stack->push(obj)) {
8355 if (_concurrent_precleaning) {
8356 // We dirty the overflown object and let the remark
8357 // phase deal with it.
8358 assert(_collector->overflow_list_is_empty(), "Error");
8359 // In the case of object arrays, we need to dirty all of
8360 // the cards that the object spans. No locking or atomics
8361 // are needed since no one else can be mutating the mod union
8362 // table.
8363 if (obj->is_objArray()) {
8364 size_t sz = obj->size();
8365 HeapWord* end_card_addr =
8366 (HeapWord*)round_to((intptr_t)(addr+sz), CardTableModRefBS::card_size);
8367 MemRegion redirty_range = MemRegion(addr, end_card_addr);
8368 assert(!redirty_range.is_empty(), "Arithmetical tautology");
8369 _collector->_modUnionTable.mark_range(redirty_range);
8370 } else {
8371 _collector->_modUnionTable.mark(addr);
8372 }
8373 _collector->_ser_kac_preclean_ovflw++;
8374 } else {
8375 _collector->push_on_overflow_list(obj);
8376 _collector->_ser_kac_ovflw++;
8377 }
8378 }
8379 }
8380 }
8382 void CMSKeepAliveClosure::do_oop(oop* p) { CMSKeepAliveClosure::do_oop_work(p); }
8383 void CMSKeepAliveClosure::do_oop(narrowOop* p) { CMSKeepAliveClosure::do_oop_work(p); }
8385 // CMSParKeepAliveClosure: a parallel version of the above.
8386 // The work queues are private to each closure (thread),
8387 // but (may be) available for stealing by other threads.
8388 void CMSParKeepAliveClosure::do_oop(oop obj) {
8389 HeapWord* addr = (HeapWord*)obj;
8390 if (_span.contains(addr) &&
8391 !_bit_map->isMarked(addr)) {
8392 // In general, during recursive tracing, several threads
8393 // may be concurrently getting here; the first one to
8394 // "tag" it, claims it.
8395 if (_bit_map->par_mark(addr)) {
8396 bool res = _work_queue->push(obj);
8397 assert(res, "Low water mark should be much less than capacity");
8398 // Do a recursive trim in the hope that this will keep
8399 // stack usage lower, but leave some oops for potential stealers
8400 trim_queue(_low_water_mark);
8401 } // Else, another thread got there first
8402 }
8403 }
8405 void CMSParKeepAliveClosure::do_oop(oop* p) { CMSParKeepAliveClosure::do_oop_work(p); }
8406 void CMSParKeepAliveClosure::do_oop(narrowOop* p) { CMSParKeepAliveClosure::do_oop_work(p); }
8408 void CMSParKeepAliveClosure::trim_queue(uint max) {
8409 while (_work_queue->size() > max) {
8410 oop new_oop;
8411 if (_work_queue->pop_local(new_oop)) {
8412 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
8413 assert(_bit_map->isMarked((HeapWord*)new_oop),
8414 "no white objects on this stack!");
8415 assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop");
8416 // iterate over the oops in this oop, marking and pushing
8417 // the ones in CMS heap (i.e. in _span).
8418 new_oop->oop_iterate(&_mark_and_push);
8419 }
8420 }
8421 }
8423 CMSInnerParMarkAndPushClosure::CMSInnerParMarkAndPushClosure(
8424 CMSCollector* collector,
8425 MemRegion span, CMSBitMap* bit_map,
8426 CMSMarkStack* revisit_stack,
8427 OopTaskQueue* work_queue):
8428 Par_KlassRememberingOopClosure(collector, NULL, revisit_stack),
8429 _span(span),
8430 _bit_map(bit_map),
8431 _work_queue(work_queue) { }
8433 void CMSInnerParMarkAndPushClosure::do_oop(oop obj) {
8434 HeapWord* addr = (HeapWord*)obj;
8435 if (_span.contains(addr) &&
8436 !_bit_map->isMarked(addr)) {
8437 if (_bit_map->par_mark(addr)) {
8438 bool simulate_overflow = false;
8439 NOT_PRODUCT(
8440 if (CMSMarkStackOverflowALot &&
8441 _collector->par_simulate_overflow()) {
8442 // simulate a stack overflow
8443 simulate_overflow = true;
8444 }
8445 )
8446 if (simulate_overflow || !_work_queue->push(obj)) {
8447 _collector->par_push_on_overflow_list(obj);
8448 _collector->_par_kac_ovflw++;
8449 }
8450 } // Else another thread got there already
8451 }
8452 }
8454 void CMSInnerParMarkAndPushClosure::do_oop(oop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); }
8455 void CMSInnerParMarkAndPushClosure::do_oop(narrowOop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); }
8457 //////////////////////////////////////////////////////////////////
8458 // CMSExpansionCause /////////////////////////////
8459 //////////////////////////////////////////////////////////////////
8460 const char* CMSExpansionCause::to_string(CMSExpansionCause::Cause cause) {
8461 switch (cause) {
8462 case _no_expansion:
8463 return "No expansion";
8464 case _satisfy_free_ratio:
8465 return "Free ratio";
8466 case _satisfy_promotion:
8467 return "Satisfy promotion";
8468 case _satisfy_allocation:
8469 return "allocation";
8470 case _allocate_par_lab:
8471 return "Par LAB";
8472 case _allocate_par_spooling_space:
8473 return "Par Spooling Space";
8474 case _adaptive_size_policy:
8475 return "Ergonomics";
8476 default:
8477 return "unknown";
8478 }
8479 }
8481 void CMSDrainMarkingStackClosure::do_void() {
8482 // the max number to take from overflow list at a time
8483 const size_t num = _mark_stack->capacity()/4;
8484 assert(!_concurrent_precleaning || _collector->overflow_list_is_empty(),
8485 "Overflow list should be NULL during concurrent phases");
8486 while (!_mark_stack->isEmpty() ||
8487 // if stack is empty, check the overflow list
8488 _collector->take_from_overflow_list(num, _mark_stack)) {
8489 oop obj = _mark_stack->pop();
8490 HeapWord* addr = (HeapWord*)obj;
8491 assert(_span.contains(addr), "Should be within span");
8492 assert(_bit_map->isMarked(addr), "Should be marked");
8493 assert(obj->is_oop(), "Should be an oop");
8494 obj->oop_iterate(_keep_alive);
8495 }
8496 }
8498 void CMSParDrainMarkingStackClosure::do_void() {
8499 // drain queue
8500 trim_queue(0);
8501 }
8503 // Trim our work_queue so its length is below max at return
8504 void CMSParDrainMarkingStackClosure::trim_queue(uint max) {
8505 while (_work_queue->size() > max) {
8506 oop new_oop;
8507 if (_work_queue->pop_local(new_oop)) {
8508 assert(new_oop->is_oop(), "Expected an oop");
8509 assert(_bit_map->isMarked((HeapWord*)new_oop),
8510 "no white objects on this stack!");
8511 assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop");
8512 // iterate over the oops in this oop, marking and pushing
8513 // the ones in CMS heap (i.e. in _span).
8514 new_oop->oop_iterate(&_mark_and_push);
8515 }
8516 }
8517 }
8519 ////////////////////////////////////////////////////////////////////
8520 // Support for Marking Stack Overflow list handling and related code
8521 ////////////////////////////////////////////////////////////////////
8522 // Much of the following code is similar in shape and spirit to the
8523 // code used in ParNewGC. We should try and share that code
8524 // as much as possible in the future.
8526 #ifndef PRODUCT
8527 // Debugging support for CMSStackOverflowALot
8529 // It's OK to call this multi-threaded; the worst thing
8530 // that can happen is that we'll get a bunch of closely
8531 // spaced simulated oveflows, but that's OK, in fact
8532 // probably good as it would exercise the overflow code
8533 // under contention.
8534 bool CMSCollector::simulate_overflow() {
8535 if (_overflow_counter-- <= 0) { // just being defensive
8536 _overflow_counter = CMSMarkStackOverflowInterval;
8537 return true;
8538 } else {
8539 return false;
8540 }
8541 }
8543 bool CMSCollector::par_simulate_overflow() {
8544 return simulate_overflow();
8545 }
8546 #endif
8548 // Single-threaded
8549 bool CMSCollector::take_from_overflow_list(size_t num, CMSMarkStack* stack) {
8550 assert(stack->isEmpty(), "Expected precondition");
8551 assert(stack->capacity() > num, "Shouldn't bite more than can chew");
8552 size_t i = num;
8553 oop cur = _overflow_list;
8554 const markOop proto = markOopDesc::prototype();
8555 NOT_PRODUCT(ssize_t n = 0;)
8556 for (oop next; i > 0 && cur != NULL; cur = next, i--) {
8557 next = oop(cur->mark());
8558 cur->set_mark(proto); // until proven otherwise
8559 assert(cur->is_oop(), "Should be an oop");
8560 bool res = stack->push(cur);
8561 assert(res, "Bit off more than can chew?");
8562 NOT_PRODUCT(n++;)
8563 }
8564 _overflow_list = cur;
8565 #ifndef PRODUCT
8566 assert(_num_par_pushes >= n, "Too many pops?");
8567 _num_par_pushes -=n;
8568 #endif
8569 return !stack->isEmpty();
8570 }
8572 #define BUSY (oop(0x1aff1aff))
8573 // (MT-safe) Get a prefix of at most "num" from the list.
8574 // The overflow list is chained through the mark word of
8575 // each object in the list. We fetch the entire list,
8576 // break off a prefix of the right size and return the
8577 // remainder. If other threads try to take objects from
8578 // the overflow list at that time, they will wait for
8579 // some time to see if data becomes available. If (and
8580 // only if) another thread places one or more object(s)
8581 // on the global list before we have returned the suffix
8582 // to the global list, we will walk down our local list
8583 // to find its end and append the global list to
8584 // our suffix before returning it. This suffix walk can
8585 // prove to be expensive (quadratic in the amount of traffic)
8586 // when there are many objects in the overflow list and
8587 // there is much producer-consumer contention on the list.
8588 // *NOTE*: The overflow list manipulation code here and
8589 // in ParNewGeneration:: are very similar in shape,
8590 // except that in the ParNew case we use the old (from/eden)
8591 // copy of the object to thread the list via its klass word.
8592 // Because of the common code, if you make any changes in
8593 // the code below, please check the ParNew version to see if
8594 // similar changes might be needed.
8595 // CR 6797058 has been filed to consolidate the common code.
8596 bool CMSCollector::par_take_from_overflow_list(size_t num,
8597 OopTaskQueue* work_q) {
8598 assert(work_q->size() == 0, "First empty local work queue");
8599 assert(num < work_q->max_elems(), "Can't bite more than we can chew");
8600 if (_overflow_list == NULL) {
8601 return false;
8602 }
8603 // Grab the entire list; we'll put back a suffix
8604 oop prefix = (oop)Atomic::xchg_ptr(BUSY, &_overflow_list);
8605 Thread* tid = Thread::current();
8606 size_t CMSOverflowSpinCount = (size_t)ParallelGCThreads;
8607 size_t sleep_time_millis = MAX2((size_t)1, num/100);
8608 // If the list is busy, we spin for a short while,
8609 // sleeping between attempts to get the list.
8610 for (size_t spin = 0; prefix == BUSY && spin < CMSOverflowSpinCount; spin++) {
8611 os::sleep(tid, sleep_time_millis, false);
8612 if (_overflow_list == NULL) {
8613 // Nothing left to take
8614 return false;
8615 } else if (_overflow_list != BUSY) {
8616 // Try and grab the prefix
8617 prefix = (oop)Atomic::xchg_ptr(BUSY, &_overflow_list);
8618 }
8619 }
8620 // If the list was found to be empty, or we spun long
8621 // enough, we give up and return empty-handed. If we leave
8622 // the list in the BUSY state below, it must be the case that
8623 // some other thread holds the overflow list and will set it
8624 // to a non-BUSY state in the future.
8625 if (prefix == NULL || prefix == BUSY) {
8626 // Nothing to take or waited long enough
8627 if (prefix == NULL) {
8628 // Write back the NULL in case we overwrote it with BUSY above
8629 // and it is still the same value.
8630 (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
8631 }
8632 return false;
8633 }
8634 assert(prefix != NULL && prefix != BUSY, "Error");
8635 size_t i = num;
8636 oop cur = prefix;
8637 // Walk down the first "num" objects, unless we reach the end.
8638 for (; i > 1 && cur->mark() != NULL; cur = oop(cur->mark()), i--);
8639 if (cur->mark() == NULL) {
8640 // We have "num" or fewer elements in the list, so there
8641 // is nothing to return to the global list.
8642 // Write back the NULL in lieu of the BUSY we wrote
8643 // above, if it is still the same value.
8644 if (_overflow_list == BUSY) {
8645 (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
8646 }
8647 } else {
8648 // Chop off the suffix and rerturn it to the global list.
8649 assert(cur->mark() != BUSY, "Error");
8650 oop suffix_head = cur->mark(); // suffix will be put back on global list
8651 cur->set_mark(NULL); // break off suffix
8652 // It's possible that the list is still in the empty(busy) state
8653 // we left it in a short while ago; in that case we may be
8654 // able to place back the suffix without incurring the cost
8655 // of a walk down the list.
8656 oop observed_overflow_list = _overflow_list;
8657 oop cur_overflow_list = observed_overflow_list;
8658 bool attached = false;
8659 while (observed_overflow_list == BUSY || observed_overflow_list == NULL) {
8660 observed_overflow_list =
8661 (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list);
8662 if (cur_overflow_list == observed_overflow_list) {
8663 attached = true;
8664 break;
8665 } else cur_overflow_list = observed_overflow_list;
8666 }
8667 if (!attached) {
8668 // Too bad, someone else sneaked in (at least) an element; we'll need
8669 // to do a splice. Find tail of suffix so we can prepend suffix to global
8670 // list.
8671 for (cur = suffix_head; cur->mark() != NULL; cur = (oop)(cur->mark()));
8672 oop suffix_tail = cur;
8673 assert(suffix_tail != NULL && suffix_tail->mark() == NULL,
8674 "Tautology");
8675 observed_overflow_list = _overflow_list;
8676 do {
8677 cur_overflow_list = observed_overflow_list;
8678 if (cur_overflow_list != BUSY) {
8679 // Do the splice ...
8680 suffix_tail->set_mark(markOop(cur_overflow_list));
8681 } else { // cur_overflow_list == BUSY
8682 suffix_tail->set_mark(NULL);
8683 }
8684 // ... and try to place spliced list back on overflow_list ...
8685 observed_overflow_list =
8686 (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list);
8687 } while (cur_overflow_list != observed_overflow_list);
8688 // ... until we have succeeded in doing so.
8689 }
8690 }
8692 // Push the prefix elements on work_q
8693 assert(prefix != NULL, "control point invariant");
8694 const markOop proto = markOopDesc::prototype();
8695 oop next;
8696 NOT_PRODUCT(ssize_t n = 0;)
8697 for (cur = prefix; cur != NULL; cur = next) {
8698 next = oop(cur->mark());
8699 cur->set_mark(proto); // until proven otherwise
8700 assert(cur->is_oop(), "Should be an oop");
8701 bool res = work_q->push(cur);
8702 assert(res, "Bit off more than we can chew?");
8703 NOT_PRODUCT(n++;)
8704 }
8705 #ifndef PRODUCT
8706 assert(_num_par_pushes >= n, "Too many pops?");
8707 Atomic::add_ptr(-(intptr_t)n, &_num_par_pushes);
8708 #endif
8709 return true;
8710 }
8712 // Single-threaded
8713 void CMSCollector::push_on_overflow_list(oop p) {
8714 NOT_PRODUCT(_num_par_pushes++;)
8715 assert(p->is_oop(), "Not an oop");
8716 preserve_mark_if_necessary(p);
8717 p->set_mark((markOop)_overflow_list);
8718 _overflow_list = p;
8719 }
8721 // Multi-threaded; use CAS to prepend to overflow list
8722 void CMSCollector::par_push_on_overflow_list(oop p) {
8723 NOT_PRODUCT(Atomic::inc_ptr(&_num_par_pushes);)
8724 assert(p->is_oop(), "Not an oop");
8725 par_preserve_mark_if_necessary(p);
8726 oop observed_overflow_list = _overflow_list;
8727 oop cur_overflow_list;
8728 do {
8729 cur_overflow_list = observed_overflow_list;
8730 if (cur_overflow_list != BUSY) {
8731 p->set_mark(markOop(cur_overflow_list));
8732 } else {
8733 p->set_mark(NULL);
8734 }
8735 observed_overflow_list =
8736 (oop) Atomic::cmpxchg_ptr(p, &_overflow_list, cur_overflow_list);
8737 } while (cur_overflow_list != observed_overflow_list);
8738 }
8739 #undef BUSY
8741 // Single threaded
8742 // General Note on GrowableArray: pushes may silently fail
8743 // because we are (temporarily) out of C-heap for expanding
8744 // the stack. The problem is quite ubiquitous and affects
8745 // a lot of code in the JVM. The prudent thing for GrowableArray
8746 // to do (for now) is to exit with an error. However, that may
8747 // be too draconian in some cases because the caller may be
8748 // able to recover without much harm. For such cases, we
8749 // should probably introduce a "soft_push" method which returns
8750 // an indication of success or failure with the assumption that
8751 // the caller may be able to recover from a failure; code in
8752 // the VM can then be changed, incrementally, to deal with such
8753 // failures where possible, thus, incrementally hardening the VM
8754 // in such low resource situations.
8755 void CMSCollector::preserve_mark_work(oop p, markOop m) {
8756 if (_preserved_oop_stack == NULL) {
8757 assert(_preserved_mark_stack == NULL,
8758 "bijection with preserved_oop_stack");
8759 // Allocate the stacks
8760 _preserved_oop_stack = new (ResourceObj::C_HEAP)
8761 GrowableArray<oop>(PreserveMarkStackSize, true);
8762 _preserved_mark_stack = new (ResourceObj::C_HEAP)
8763 GrowableArray<markOop>(PreserveMarkStackSize, true);
8764 if (_preserved_oop_stack == NULL || _preserved_mark_stack == NULL) {
8765 vm_exit_out_of_memory(2* PreserveMarkStackSize * sizeof(oop) /* punt */,
8766 "Preserved Mark/Oop Stack for CMS (C-heap)");
8767 }
8768 }
8769 _preserved_oop_stack->push(p);
8770 _preserved_mark_stack->push(m);
8771 assert(m == p->mark(), "Mark word changed");
8772 assert(_preserved_oop_stack->length() == _preserved_mark_stack->length(),
8773 "bijection");
8774 }
8776 // Single threaded
8777 void CMSCollector::preserve_mark_if_necessary(oop p) {
8778 markOop m = p->mark();
8779 if (m->must_be_preserved(p)) {
8780 preserve_mark_work(p, m);
8781 }
8782 }
8784 void CMSCollector::par_preserve_mark_if_necessary(oop p) {
8785 markOop m = p->mark();
8786 if (m->must_be_preserved(p)) {
8787 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
8788 // Even though we read the mark word without holding
8789 // the lock, we are assured that it will not change
8790 // because we "own" this oop, so no other thread can
8791 // be trying to push it on the overflow list; see
8792 // the assertion in preserve_mark_work() that checks
8793 // that m == p->mark().
8794 preserve_mark_work(p, m);
8795 }
8796 }
8798 // We should be able to do this multi-threaded,
8799 // a chunk of stack being a task (this is
8800 // correct because each oop only ever appears
8801 // once in the overflow list. However, it's
8802 // not very easy to completely overlap this with
8803 // other operations, so will generally not be done
8804 // until all work's been completed. Because we
8805 // expect the preserved oop stack (set) to be small,
8806 // it's probably fine to do this single-threaded.
8807 // We can explore cleverer concurrent/overlapped/parallel
8808 // processing of preserved marks if we feel the
8809 // need for this in the future. Stack overflow should
8810 // be so rare in practice and, when it happens, its
8811 // effect on performance so great that this will
8812 // likely just be in the noise anyway.
8813 void CMSCollector::restore_preserved_marks_if_any() {
8814 if (_preserved_oop_stack == NULL) {
8815 assert(_preserved_mark_stack == NULL,
8816 "bijection with preserved_oop_stack");
8817 return;
8818 }
8820 assert(SafepointSynchronize::is_at_safepoint(),
8821 "world should be stopped");
8822 assert(Thread::current()->is_ConcurrentGC_thread() ||
8823 Thread::current()->is_VM_thread(),
8824 "should be single-threaded");
8826 int length = _preserved_oop_stack->length();
8827 assert(_preserved_mark_stack->length() == length, "bijection");
8828 for (int i = 0; i < length; i++) {
8829 oop p = _preserved_oop_stack->at(i);
8830 assert(p->is_oop(), "Should be an oop");
8831 assert(_span.contains(p), "oop should be in _span");
8832 assert(p->mark() == markOopDesc::prototype(),
8833 "Set when taken from overflow list");
8834 markOop m = _preserved_mark_stack->at(i);
8835 p->set_mark(m);
8836 }
8837 _preserved_mark_stack->clear();
8838 _preserved_oop_stack->clear();
8839 assert(_preserved_mark_stack->is_empty() &&
8840 _preserved_oop_stack->is_empty(),
8841 "stacks were cleared above");
8842 }
8844 #ifndef PRODUCT
8845 bool CMSCollector::no_preserved_marks() const {
8846 return ( ( _preserved_mark_stack == NULL
8847 && _preserved_oop_stack == NULL)
8848 || ( _preserved_mark_stack->is_empty()
8849 && _preserved_oop_stack->is_empty()));
8850 }
8851 #endif
8853 CMSAdaptiveSizePolicy* ASConcurrentMarkSweepGeneration::cms_size_policy() const
8854 {
8855 GenCollectedHeap* gch = (GenCollectedHeap*) GenCollectedHeap::heap();
8856 CMSAdaptiveSizePolicy* size_policy =
8857 (CMSAdaptiveSizePolicy*) gch->gen_policy()->size_policy();
8858 assert(size_policy->is_gc_cms_adaptive_size_policy(),
8859 "Wrong type for size policy");
8860 return size_policy;
8861 }
8863 void ASConcurrentMarkSweepGeneration::resize(size_t cur_promo_size,
8864 size_t desired_promo_size) {
8865 if (cur_promo_size < desired_promo_size) {
8866 size_t expand_bytes = desired_promo_size - cur_promo_size;
8867 if (PrintAdaptiveSizePolicy && Verbose) {
8868 gclog_or_tty->print_cr(" ASConcurrentMarkSweepGeneration::resize "
8869 "Expanding tenured generation by " SIZE_FORMAT " (bytes)",
8870 expand_bytes);
8871 }
8872 expand(expand_bytes,
8873 MinHeapDeltaBytes,
8874 CMSExpansionCause::_adaptive_size_policy);
8875 } else if (desired_promo_size < cur_promo_size) {
8876 size_t shrink_bytes = cur_promo_size - desired_promo_size;
8877 if (PrintAdaptiveSizePolicy && Verbose) {
8878 gclog_or_tty->print_cr(" ASConcurrentMarkSweepGeneration::resize "
8879 "Shrinking tenured generation by " SIZE_FORMAT " (bytes)",
8880 shrink_bytes);
8881 }
8882 shrink(shrink_bytes);
8883 }
8884 }
8886 CMSGCAdaptivePolicyCounters* ASConcurrentMarkSweepGeneration::gc_adaptive_policy_counters() {
8887 GenCollectedHeap* gch = GenCollectedHeap::heap();
8888 CMSGCAdaptivePolicyCounters* counters =
8889 (CMSGCAdaptivePolicyCounters*) gch->collector_policy()->counters();
8890 assert(counters->kind() == GCPolicyCounters::CMSGCAdaptivePolicyCountersKind,
8891 "Wrong kind of counters");
8892 return counters;
8893 }
8896 void ASConcurrentMarkSweepGeneration::update_counters() {
8897 if (UsePerfData) {
8898 _space_counters->update_all();
8899 _gen_counters->update_all();
8900 CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
8901 GenCollectedHeap* gch = GenCollectedHeap::heap();
8902 CMSGCStats* gc_stats_l = (CMSGCStats*) gc_stats();
8903 assert(gc_stats_l->kind() == GCStats::CMSGCStatsKind,
8904 "Wrong gc statistics type");
8905 counters->update_counters(gc_stats_l);
8906 }
8907 }
8909 void ASConcurrentMarkSweepGeneration::update_counters(size_t used) {
8910 if (UsePerfData) {
8911 _space_counters->update_used(used);
8912 _space_counters->update_capacity();
8913 _gen_counters->update_all();
8915 CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
8916 GenCollectedHeap* gch = GenCollectedHeap::heap();
8917 CMSGCStats* gc_stats_l = (CMSGCStats*) gc_stats();
8918 assert(gc_stats_l->kind() == GCStats::CMSGCStatsKind,
8919 "Wrong gc statistics type");
8920 counters->update_counters(gc_stats_l);
8921 }
8922 }
8924 // The desired expansion delta is computed so that:
8925 // . desired free percentage or greater is used
8926 void ASConcurrentMarkSweepGeneration::compute_new_size() {
8927 assert_locked_or_safepoint(Heap_lock);
8929 GenCollectedHeap* gch = (GenCollectedHeap*) GenCollectedHeap::heap();
8931 // If incremental collection failed, we just want to expand
8932 // to the limit.
8933 if (incremental_collection_failed()) {
8934 clear_incremental_collection_failed();
8935 grow_to_reserved();
8936 return;
8937 }
8939 assert(UseAdaptiveSizePolicy, "Should be using adaptive sizing");
8941 assert(gch->kind() == CollectedHeap::GenCollectedHeap,
8942 "Wrong type of heap");
8943 int prev_level = level() - 1;
8944 assert(prev_level >= 0, "The cms generation is the lowest generation");
8945 Generation* prev_gen = gch->get_gen(prev_level);
8946 assert(prev_gen->kind() == Generation::ASParNew,
8947 "Wrong type of young generation");
8948 ParNewGeneration* younger_gen = (ParNewGeneration*) prev_gen;
8949 size_t cur_eden = younger_gen->eden()->capacity();
8950 CMSAdaptiveSizePolicy* size_policy = cms_size_policy();
8951 size_t cur_promo = free();
8952 size_policy->compute_tenured_generation_free_space(cur_promo,
8953 max_available(),
8954 cur_eden);
8955 resize(cur_promo, size_policy->promo_size());
8957 // Record the new size of the space in the cms generation
8958 // that is available for promotions. This is temporary.
8959 // It should be the desired promo size.
8960 size_policy->avg_cms_promo()->sample(free());
8961 size_policy->avg_old_live()->sample(used());
8963 if (UsePerfData) {
8964 CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
8965 counters->update_cms_capacity_counter(capacity());
8966 }
8967 }
8969 void ASConcurrentMarkSweepGeneration::shrink_by(size_t desired_bytes) {
8970 assert_locked_or_safepoint(Heap_lock);
8971 assert_lock_strong(freelistLock());
8972 HeapWord* old_end = _cmsSpace->end();
8973 HeapWord* unallocated_start = _cmsSpace->unallocated_block();
8974 assert(old_end >= unallocated_start, "Miscalculation of unallocated_start");
8975 FreeChunk* chunk_at_end = find_chunk_at_end();
8976 if (chunk_at_end == NULL) {
8977 // No room to shrink
8978 if (PrintGCDetails && Verbose) {
8979 gclog_or_tty->print_cr("No room to shrink: old_end "
8980 PTR_FORMAT " unallocated_start " PTR_FORMAT
8981 " chunk_at_end " PTR_FORMAT,
8982 old_end, unallocated_start, chunk_at_end);
8983 }
8984 return;
8985 } else {
8987 // Find the chunk at the end of the space and determine
8988 // how much it can be shrunk.
8989 size_t shrinkable_size_in_bytes = chunk_at_end->size();
8990 size_t aligned_shrinkable_size_in_bytes =
8991 align_size_down(shrinkable_size_in_bytes, os::vm_page_size());
8992 assert(unallocated_start <= chunk_at_end->end(),
8993 "Inconsistent chunk at end of space");
8994 size_t bytes = MIN2(desired_bytes, aligned_shrinkable_size_in_bytes);
8995 size_t word_size_before = heap_word_size(_virtual_space.committed_size());
8997 // Shrink the underlying space
8998 _virtual_space.shrink_by(bytes);
8999 if (PrintGCDetails && Verbose) {
9000 gclog_or_tty->print_cr("ConcurrentMarkSweepGeneration::shrink_by:"
9001 " desired_bytes " SIZE_FORMAT
9002 " shrinkable_size_in_bytes " SIZE_FORMAT
9003 " aligned_shrinkable_size_in_bytes " SIZE_FORMAT
9004 " bytes " SIZE_FORMAT,
9005 desired_bytes, shrinkable_size_in_bytes,
9006 aligned_shrinkable_size_in_bytes, bytes);
9007 gclog_or_tty->print_cr(" old_end " SIZE_FORMAT
9008 " unallocated_start " SIZE_FORMAT,
9009 old_end, unallocated_start);
9010 }
9012 // If the space did shrink (shrinking is not guaranteed),
9013 // shrink the chunk at the end by the appropriate amount.
9014 if (((HeapWord*)_virtual_space.high()) < old_end) {
9015 size_t new_word_size =
9016 heap_word_size(_virtual_space.committed_size());
9018 // Have to remove the chunk from the dictionary because it is changing
9019 // size and might be someplace elsewhere in the dictionary.
9021 // Get the chunk at end, shrink it, and put it
9022 // back.
9023 _cmsSpace->removeChunkFromDictionary(chunk_at_end);
9024 size_t word_size_change = word_size_before - new_word_size;
9025 size_t chunk_at_end_old_size = chunk_at_end->size();
9026 assert(chunk_at_end_old_size >= word_size_change,
9027 "Shrink is too large");
9028 chunk_at_end->setSize(chunk_at_end_old_size -
9029 word_size_change);
9030 _cmsSpace->freed((HeapWord*) chunk_at_end->end(),
9031 word_size_change);
9033 _cmsSpace->returnChunkToDictionary(chunk_at_end);
9035 MemRegion mr(_cmsSpace->bottom(), new_word_size);
9036 _bts->resize(new_word_size); // resize the block offset shared array
9037 Universe::heap()->barrier_set()->resize_covered_region(mr);
9038 _cmsSpace->assert_locked();
9039 _cmsSpace->set_end((HeapWord*)_virtual_space.high());
9041 NOT_PRODUCT(_cmsSpace->dictionary()->verify());
9043 // update the space and generation capacity counters
9044 if (UsePerfData) {
9045 _space_counters->update_capacity();
9046 _gen_counters->update_all();
9047 }
9049 if (Verbose && PrintGCDetails) {
9050 size_t new_mem_size = _virtual_space.committed_size();
9051 size_t old_mem_size = new_mem_size + bytes;
9052 gclog_or_tty->print_cr("Shrinking %s from %ldK by %ldK to %ldK",
9053 name(), old_mem_size/K, bytes/K, new_mem_size/K);
9054 }
9055 }
9057 assert(_cmsSpace->unallocated_block() <= _cmsSpace->end(),
9058 "Inconsistency at end of space");
9059 assert(chunk_at_end->end() == _cmsSpace->end(),
9060 "Shrinking is inconsistent");
9061 return;
9062 }
9063 }
9065 // Transfer some number of overflown objects to usual marking
9066 // stack. Return true if some objects were transferred.
9067 bool MarkRefsIntoAndScanClosure::take_from_overflow_list() {
9068 size_t num = MIN2((size_t)(_mark_stack->capacity() - _mark_stack->length())/4,
9069 (size_t)ParGCDesiredObjsFromOverflowList);
9071 bool res = _collector->take_from_overflow_list(num, _mark_stack);
9072 assert(_collector->overflow_list_is_empty() || res,
9073 "If list is not empty, we should have taken something");
9074 assert(!res || !_mark_stack->isEmpty(),
9075 "If we took something, it should now be on our stack");
9076 return res;
9077 }
9079 size_t MarkDeadObjectsClosure::do_blk(HeapWord* addr) {
9080 size_t res = _sp->block_size_no_stall(addr, _collector);
9081 assert(res != 0, "Should always be able to compute a size");
9082 if (_sp->block_is_obj(addr)) {
9083 if (_live_bit_map->isMarked(addr)) {
9084 // It can't have been dead in a previous cycle
9085 guarantee(!_dead_bit_map->isMarked(addr), "No resurrection!");
9086 } else {
9087 _dead_bit_map->mark(addr); // mark the dead object
9088 }
9089 }
9090 return res;
9091 }