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