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