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