|
68 // Leave this one last.
69 GCH_PS_NumElements
70 };
71
72 GenCollectedHeap::GenCollectedHeap(GenCollectorPolicy *policy) :
73 SharedHeap(policy),
74 _gen_policy(policy),
75 _gen_process_roots_tasks(new SubTasksDone(GCH_PS_NumElements)),
76 _full_collections_completed(0)
77 {
78 if (_gen_process_roots_tasks == NULL ||
79 !_gen_process_roots_tasks->valid()) {
80 vm_exit_during_initialization("Failed necessary allocation.");
81 }
82 assert(policy != NULL, "Sanity check");
83 }
84
85 jint GenCollectedHeap::initialize() {
86 CollectedHeap::pre_initialize();
87
88 // While there are no constraints in the GC code that HeapWordSize
89 // be any particular value, there are multiple other areas in the
90 // system which believe this to be true (e.g. oop->object_size in some
91 // cases incorrectly returns the size in wordSize units rather than
92 // HeapWordSize).
93 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
94
95 // Allocate space for the heap.
96
97 char* heap_address;
98 size_t total_reserved = 0;
99 int n_covered_regions = 0;
100 ReservedSpace heap_rs;
101
102 size_t heap_alignment = collector_policy()->heap_alignment();
103
104 heap_address = allocate(heap_alignment, &total_reserved,
105 &n_covered_regions, &heap_rs);
106
107 if (!heap_rs.is_reserved()) {
108 vm_shutdown_during_initialization(
109 "Could not reserve enough space for object heap");
110 return JNI_ENOMEM;
111 }
112
113 initialize_reserved_region((HeapWord*)heap_rs.base(), (HeapWord*)(heap_rs.base() + heap_rs.size()));
114
115 _rem_set = collector_policy()->create_rem_set(reserved_region(), n_covered_regions);
116 set_barrier_set(rem_set()->bs());
117
118 _gch = this;
119
120 ReservedSpace young_rs = heap_rs.first_part(gen_policy()->young_gen_spec()->max_size(), false, false);
121 _young_gen = gen_policy()->young_gen_spec()->init(young_rs, rem_set());
122 heap_rs = heap_rs.last_part(gen_policy()->young_gen_spec()->max_size());
123
124 ReservedSpace old_rs = heap_rs.first_part(gen_policy()->old_gen_spec()->max_size(), false, false);
125 _old_gen = gen_policy()->old_gen_spec()->init(old_rs, rem_set());
126 heap_rs = heap_rs.last_part(gen_policy()->old_gen_spec()->max_size());
127
128 clear_incremental_collection_failed();
129
130 #if INCLUDE_ALL_GCS
131 // If we are running CMS, create the collector responsible
132 // for collecting the CMS generations.
133 if (collector_policy()->is_concurrent_mark_sweep_policy()) {
134 bool success = create_cms_collector();
135 if (!success) return JNI_ENOMEM;
136 }
137 #endif // INCLUDE_ALL_GCS
138
139 return JNI_OK;
140 }
141
142 char* GenCollectedHeap::allocate(size_t alignment,
143 size_t* _total_reserved,
144 int* _n_covered_regions,
145 ReservedSpace* heap_rs){
146 const char overflow_msg[] = "The size of the object heap + VM data exceeds "
147 "the maximum representable size";
148
149 // Now figure out the total size.
150 const size_t pageSize = UseLargePages ? os::large_page_size() : os::vm_page_size();
151 assert(alignment % pageSize == 0, "Must be");
152
153 size_t total_reserved = gen_policy()->young_gen_spec()->max_size() +
154 gen_policy()->old_gen_spec()->max_size();
155 if (total_reserved < gen_policy()->young_gen_spec()->max_size() ||
156 total_reserved < gen_policy()->old_gen_spec()->max_size()) {
157 vm_exit_during_initialization(overflow_msg);
158 }
159 assert(total_reserved % alignment == 0,
160 err_msg("Gen size; total_reserved=" SIZE_FORMAT ", alignment="
161 SIZE_FORMAT, total_reserved, alignment));
162
163 int n_covered_regions = 2; // Young + Old
164
165 // Needed until the cardtable is fixed to have the right number
166 // of covered regions.
167 n_covered_regions += 2;
168
169 *_total_reserved = total_reserved;
170 *_n_covered_regions = n_covered_regions;
171
172 *heap_rs = Universe::reserve_heap(total_reserved, alignment);
173 return heap_rs->base();
174 }
175
176 void GenCollectedHeap::post_initialize() {
177 SharedHeap::post_initialize();
178 GenCollectorPolicy *policy = (GenCollectorPolicy *)collector_policy();
179 guarantee(policy->is_generation_policy(), "Illegal policy type");
180 DefNewGeneration* def_new_gen = (DefNewGeneration*) _young_gen;
181 assert(def_new_gen->kind() == Generation::DefNew ||
182 def_new_gen->kind() == Generation::ParNew,
183 "Wrong generation kind");
184
185 assert(_old_gen->kind() == Generation::ConcurrentMarkSweep ||
186 _old_gen->kind() == Generation::MarkSweepCompact,
187 "Wrong generation kind");
188
189 policy->initialize_size_policy(def_new_gen->eden()->capacity(),
190 _old_gen->capacity(),
191 def_new_gen->from()->capacity());
192 policy->initialize_gc_policy_counters();
193 }
194
195 void GenCollectedHeap::ref_processing_init() {
196 SharedHeap::ref_processing_init();
197 _young_gen->ref_processor_init();
198 _old_gen->ref_processor_init();
199 }
200
201 size_t GenCollectedHeap::capacity() const {
202 return _young_gen->capacity() + _old_gen->capacity();
203 }
204
205 size_t GenCollectedHeap::used() const {
206 return _young_gen->used() + _old_gen->used();
207 }
208
209 void GenCollectedHeap::save_used_regions() {
210 _old_gen->save_used_region();
211 _young_gen->save_used_region();
212 }
213
214 size_t GenCollectedHeap::max_capacity() const {
215 return _young_gen->max_capacity() + _old_gen->max_capacity();
216 }
217
218 // Update the _full_collections_completed counter
219 // at the end of a stop-world full GC.
220 unsigned int GenCollectedHeap::update_full_collections_completed() {
221 MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
222 assert(_full_collections_completed <= _total_full_collections,
223 "Can't complete more collections than were started");
224 _full_collections_completed = _total_full_collections;
225 ml.notify_all();
226 return _full_collections_completed;
227 }
228
229 // Update the _full_collections_completed counter, as appropriate,
230 // at the end of a concurrent GC cycle. Note the conditional update
231 // below to allow this method to be called by a concurrent collector
232 // without synchronizing in any manner with the VM thread (which
233 // may already have initiated a STW full collection "concurrently").
234 unsigned int GenCollectedHeap::update_full_collections_completed(unsigned int count) {
235 MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
259 // higher than we are prepared to pay for such rudimentary debugging
260 // support.
261 void GenCollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr,
262 size_t size) {
263 if (CheckMemoryInitialization && ZapUnusedHeapArea) {
264 // We are asked to check a size in HeapWords,
265 // but the memory is mangled in juint words.
266 juint* start = (juint*) (addr + skip_header_HeapWords());
267 juint* end = (juint*) (addr + size);
268 for (juint* slot = start; slot < end; slot += 1) {
269 assert(*slot == badHeapWordVal,
270 "Found non badHeapWordValue in pre-allocation check");
271 }
272 }
273 }
274 #endif
275
276 HeapWord* GenCollectedHeap::attempt_allocation(size_t size,
277 bool is_tlab,
278 bool first_only) {
279 HeapWord* res = NULL;
280
281 if (_young_gen->should_allocate(size, is_tlab)) {
282 res = _young_gen->allocate(size, is_tlab);
283 if (res != NULL || first_only) {
284 return res;
285 }
286 }
287
288 if (_old_gen->should_allocate(size, is_tlab)) {
289 res = _old_gen->allocate(size, is_tlab);
290 }
291
292 return res;
293 }
294
295 HeapWord* GenCollectedHeap::mem_allocate(size_t size,
296 bool* gc_overhead_limit_was_exceeded) {
297 return collector_policy()->mem_allocate_work(size,
298 false /* is_tlab */,
299 gc_overhead_limit_was_exceeded);
300 }
301
302 bool GenCollectedHeap::must_clear_all_soft_refs() {
303 return _gc_cause == GCCause::_last_ditch_collection;
304 }
305
306 bool GenCollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
307 return UseConcMarkSweepGC &&
308 ((cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) ||
309 (cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent));
310 }
311
312 void GenCollectedHeap::collect_generation(Generation* gen, bool full, size_t size,
313 bool is_tlab, bool run_verification, bool clear_soft_refs) {
314 // Timer for individual generations. Last argument is false: no CR
315 // FIXME: We should try to start the timing earlier to cover more of the GC pause
316 // The PrintGCDetails logging starts before we have incremented the GC id. We will do that later
317 // so we can assume here that the next GC id is what we want.
318 GCTraceTime t1(gen->short_name(), PrintGCDetails, false, NULL, GCId::peek());
319 TraceCollectorStats tcs(gen->counters());
320 TraceMemoryManagerStats tmms(gen->kind(),gc_cause());
321
322 size_t prev_used = gen->used();
323 gen->stat_record()->invocations++;
324 gen->stat_record()->accumulated_time.start();
325
326 // Must be done anew before each collection because
327 // a previous collection will do mangling and will
328 // change top of some spaces.
329 record_gen_tops_before_GC();
330
331 if (PrintGC && Verbose) {
332 // I didn't want to change the logging when removing the level concept,
333 // but I guess this logging could say young/old or something instead of 0/1.
334 int level;
335 if (gen == GenCollectedHeap::heap()->young_gen()) {
336 level = 0;
337 } else {
338 level = 1;
339 }
340 gclog_or_tty->print("level=%d invoke=%d size=" SIZE_FORMAT,
341 level,
342 gen->stat_record()->invocations,
343 size * HeapWordSize);
344 }
345
346 if (run_verification && VerifyBeforeGC) {
347 HandleMark hm; // Discard invalid handles created during verification
348 Universe::verify(" VerifyBeforeGC:");
349 }
350 COMPILER2_PRESENT(DerivedPointerTable::clear());
351
352 // Do collection work
353 {
354 // Note on ref discovery: For what appear to be historical reasons,
355 // GCH enables and disabled (by enqueing) refs discovery.
356 // In the future this should be moved into the generation's
357 // collect method so that ref discovery and enqueueing concerns
358 // are local to a generation. The collect method could return
359 // an appropriate indication in the case that notification on
360 // the ref lock was needed. This will make the treatment of
361 // weak refs more uniform (and indeed remove such concerns
362 // from GCH). XXX
363
364 HandleMark hm; // Discard invalid handles created during gc
365 save_marks(); // save marks for all gens
366 // We want to discover references, but not process them yet.
367 // This mode is disabled in process_discovered_references if the
368 // generation does some collection work, or in
369 // enqueue_discovered_references if the generation returns
370 // without doing any work.
371 ReferenceProcessor* rp = gen->ref_processor();
372 // If the discovery of ("weak") refs in this generation is
373 // atomic wrt other collectors in this configuration, we
374 // are guaranteed to have empty discovered ref lists.
375 if (rp->discovery_is_atomic()) {
376 rp->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
377 rp->setup_policy(clear_soft_refs);
378 } else {
379 // collect() below will enable discovery as appropriate
380 }
381 gen->collect(full, clear_soft_refs, size, is_tlab);
382 if (!rp->enqueuing_is_done()) {
383 rp->enqueue_discovered_references();
384 } else {
385 rp->set_enqueuing_is_done(false);
386 }
387 rp->verify_no_references_recorded();
388 }
389
390 // Determine if allocation request was met.
391 if (size > 0) {
392 if (!is_tlab || gen->supports_tlab_allocation()) {
393 if (size * HeapWordSize <= gen->unsafe_max_alloc_nogc()) {
394 size = 0;
395 }
396 }
397 }
398
399 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
400
401 gen->stat_record()->accumulated_time.stop();
402
403 update_gc_stats(gen, full);
404
405 if (run_verification && VerifyAfterGC) {
406 HandleMark hm; // Discard invalid handles created during verification
407 Universe::verify(" VerifyAfterGC:");
408 }
409
410 if (PrintGCDetails) {
411 gclog_or_tty->print(":");
412 gen->print_heap_change(prev_used);
413 }
414 }
415
416 void GenCollectedHeap::do_collection(bool full,
417 bool clear_all_soft_refs,
418 size_t size,
419 bool is_tlab,
420 Generation::Type max_generation) {
421 ResourceMark rm;
422 DEBUG_ONLY(Thread* my_thread = Thread::current();)
423
424 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
425 assert(my_thread->is_VM_thread() ||
426 my_thread->is_ConcurrentGC_thread(),
427 "incorrect thread type capability");
428 assert(Heap_lock->is_locked(),
429 "the requesting thread should have the Heap_lock");
430 guarantee(!is_gc_active(), "collection is not reentrant");
431
432 if (GC_locker::check_active_before_gc()) {
433 return; // GC is disabled (e.g. JNI GetXXXCritical operation)
434 }
435
436 const bool do_clear_all_soft_refs = clear_all_soft_refs ||
437 collector_policy()->should_clear_all_soft_refs();
438
439 ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());
440
441 const size_t metadata_prev_used = MetaspaceAux::used_bytes();
442
443 print_heap_before_gc();
444
445 {
446 FlagSetting fl(_is_gc_active, true);
447
448 bool complete = full && (max_generation == Generation::Old);
449 const char* gc_cause_prefix = complete ? "Full GC" : "GC";
450 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
451 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
452 // The PrintGCDetails logging starts before we have incremented the GC id. We will do that later
453 // so we can assume here that the next GC id is what we want.
454 GCTraceTime t(GCCauseString(gc_cause_prefix, gc_cause()), PrintGCDetails, false, NULL, GCId::peek());
455
456 gc_prologue(complete);
457 increment_total_collections(complete);
458
459 size_t gch_prev_used = used();
460 bool must_restore_marks_for_biased_locking = false;
461 bool old_collected = false;
462 bool run_verification = total_collections() >= VerifyGCStartAt;
463
464 if (_young_gen->performs_in_place_marking() ||
465 _old_gen->performs_in_place_marking()) {
466 // We want to avoid doing this for
467 // scavenge-only collections where it's unnecessary.
468 must_restore_marks_for_biased_locking = true;
469 BiasedLocking::preserve_marks();
470 }
471
472 bool prepared_for_verification = false;
473 if (!(full && _old_gen->full_collects_younger_generations()) &&
474 _young_gen->should_collect(full, size, is_tlab)) {
475 if (run_verification && VerifyGCLevel <= 0 && VerifyBeforeGC) {
476 prepare_for_verify();
477 prepared_for_verification = true;
478 }
479 collect_generation(_young_gen, full, size, is_tlab, run_verification && VerifyGCLevel <= 0, do_clear_all_soft_refs);
480 }
481 if (max_generation == Generation::Old && _old_gen->should_collect(full, size, is_tlab)) {
482 if (!complete) {
483 // The full_collections increment was missed above.
484 increment_total_full_collections();
485 }
486 pre_full_gc_dump(NULL); // do any pre full gc dumps
487 if (run_verification && VerifyGCLevel <= 1 && VerifyBeforeGC) {
488 if (!prepared_for_verification) {
489 prepare_for_verify();
490 }
491 }
492 collect_generation(_old_gen, full, size, is_tlab, run_verification && VerifyGCLevel <= 1, do_clear_all_soft_refs);
493 old_collected = true;
494 }
495
496 // Update "complete" boolean wrt what actually transpired --
497 // for instance, a promotion failure could have led to
498 // a whole heap collection.
499 complete = complete || old_collected;
500
501 if (complete) { // We did a "major" collection
502 // FIXME: See comment at pre_full_gc_dump call
503 post_full_gc_dump(NULL); // do any post full gc dumps
504 }
505
506 if (PrintGCDetails) {
507 print_heap_change(gch_prev_used);
508
509 // Print metaspace info for full GC with PrintGCDetails flag.
510 if (complete) {
511 MetaspaceAux::print_metaspace_change(metadata_prev_used);
512 }
513 }
514
515 // Adjust generation sizes.
516 if (old_collected) {
517 _old_gen->compute_new_size();
518 }
519 _young_gen->compute_new_size();
520
521 if (complete) {
522 // Delete metaspaces for unloaded class loaders and clean up loader_data graph
523 ClassLoaderDataGraph::purge();
524 MetaspaceAux::verify_metrics();
525 // Resize the metaspace capacity after full collections
526 MetaspaceGC::compute_new_size();
527 update_full_collections_completed();
528 }
529
530 // Track memory usage and detect low memory after GC finishes
531 MemoryService::track_memory_usage();
532
533 gc_epilogue(complete);
534
535 if (must_restore_marks_for_biased_locking) {
536 BiasedLocking::restore_marks();
537 }
538 }
539
540 print_heap_after_gc();
541
542 #ifdef TRACESPINNING
543 ParallelTaskTerminator::print_termination_counts();
544 #endif
545 }
546
547 HeapWord* GenCollectedHeap::satisfy_failed_allocation(size_t size, bool is_tlab) {
548 return collector_policy()->satisfy_failed_allocation(size, is_tlab);
549 }
550
551 void GenCollectedHeap::set_par_threads(uint t) {
552 SharedHeap::set_par_threads(t);
553 _gen_process_roots_tasks->set_n_threads(t);
554 }
555
556 void GenCollectedHeap::
557 gen_process_roots(Generation::Type type,
558 bool younger_gens_as_roots,
559 bool activate_scope,
560 SharedHeap::ScanningOption so,
561 OopsInGenClosure* not_older_gens,
562 OopsInGenClosure* weak_roots,
563 OopsInGenClosure* older_gens,
564 CLDClosure* cld_closure,
565 CLDClosure* weak_cld_closure,
566 CodeBlobClosure* code_closure) {
567
568 // General roots.
569 SharedHeap::process_roots(activate_scope, so,
570 not_older_gens, weak_roots,
571 cld_closure, weak_cld_closure,
572 code_closure);
573
574 if (younger_gens_as_roots) {
575 if (!_gen_process_roots_tasks->is_task_claimed(GCH_PS_younger_gens)) {
576 if (type == Generation::Old) {
577 not_older_gens->set_generation(_young_gen);
578 _young_gen->oop_iterate(not_older_gens);
579 }
580 not_older_gens->reset_generation();
581 }
582 }
583 // When collection is parallel, all threads get to cooperate to do
584 // old generation scanning.
585 if (type == Generation::Young) {
586 older_gens->set_generation(_old_gen);
587 rem_set()->younger_refs_iterate(_old_gen, older_gens);
588 older_gens->reset_generation();
589 }
590
591 _gen_process_roots_tasks->all_tasks_completed();
592 }
593
594 void GenCollectedHeap::
595 gen_process_roots(Generation::Type type,
596 bool younger_gens_as_roots,
597 bool activate_scope,
598 SharedHeap::ScanningOption so,
599 bool only_strong_roots,
600 OopsInGenClosure* not_older_gens,
601 OopsInGenClosure* older_gens,
602 CLDClosure* cld_closure) {
603
604 const bool is_adjust_phase = !only_strong_roots && !younger_gens_as_roots;
605
606 bool is_moving_collection = false;
607 if (type == Generation::Young || is_adjust_phase) {
608 // young collections are always moving
609 is_moving_collection = true;
610 }
611
612 MarkingCodeBlobClosure mark_code_closure(not_older_gens, is_moving_collection);
613 CodeBlobClosure* code_closure = &mark_code_closure;
614
615 gen_process_roots(type,
616 younger_gens_as_roots,
617 activate_scope, so,
618 not_older_gens, only_strong_roots ? NULL : not_older_gens,
619 older_gens,
620 cld_closure, only_strong_roots ? NULL : cld_closure,
621 code_closure);
622
623 }
624
625 void GenCollectedHeap::gen_process_weak_roots(OopClosure* root_closure) {
626 SharedHeap::process_weak_roots(root_closure);
627 // "Local" "weak" refs
628 _young_gen->ref_processor()->weak_oops_do(root_closure);
629 _old_gen->ref_processor()->weak_oops_do(root_closure);
630 }
631
632 #define GCH_SINCE_SAVE_MARKS_ITERATE_DEFN(OopClosureType, nv_suffix) \
633 void GenCollectedHeap:: \
634 oop_since_save_marks_iterate(Generation::Type gen, \
635 OopClosureType* cur, \
636 OopClosureType* older) { \
637 if (gen == Generation::Young) { \
638 _young_gen->oop_since_save_marks_iterate##nv_suffix(cur); \
639 _old_gen->oop_since_save_marks_iterate##nv_suffix(older); \
640 } else { \
641 _old_gen->oop_since_save_marks_iterate##nv_suffix(cur); \
642 } \
643 }
644
645 ALL_SINCE_SAVE_MARKS_CLOSURES(GCH_SINCE_SAVE_MARKS_ITERATE_DEFN)
646
647 #undef GCH_SINCE_SAVE_MARKS_ITERATE_DEFN
648
649 bool GenCollectedHeap::no_allocs_since_save_marks(bool include_young) {
650 return include_young && _young_gen->no_allocs_since_save_marks() ||
651 _old_gen->no_allocs_since_save_marks();
652 }
653
654 bool GenCollectedHeap::supports_inline_contig_alloc() const {
655 return _young_gen->supports_inline_contig_alloc();
656 }
657
658 HeapWord** GenCollectedHeap::top_addr() const {
659 return _young_gen->top_addr();
660 }
661
662 HeapWord** GenCollectedHeap::end_addr() const {
663 return _young_gen->end_addr();
664 }
665
666 // public collection interfaces
667
668 void GenCollectedHeap::collect(GCCause::Cause cause) {
669 if (should_do_concurrent_full_gc(cause)) {
670 #if INCLUDE_ALL_GCS
671 // mostly concurrent full collection
672 collect_mostly_concurrent(cause);
673 #else // INCLUDE_ALL_GCS
674 ShouldNotReachHere();
675 #endif // INCLUDE_ALL_GCS
676 } else if (cause == GCCause::_wb_young_gc) {
677 // minor collection for WhiteBox API
678 collect(cause, Generation::Young);
679 } else {
680 #ifdef ASSERT
681 if (cause == GCCause::_scavenge_alot) {
682 // minor collection only
683 collect(cause, Generation::Young);
684 } else {
685 // Stop-the-world full collection
686 collect(cause, Generation::Old);
687 }
688 #else
689 // Stop-the-world full collection
690 collect(cause, Generation::Old);
691 #endif
692 }
693 }
694
695 void GenCollectedHeap::collect(GCCause::Cause cause, Generation::Type max_gen) {
696 // The caller doesn't have the Heap_lock
697 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
698 MutexLocker ml(Heap_lock);
699 collect_locked(cause, max_gen);
700 }
701
702 void GenCollectedHeap::collect_locked(GCCause::Cause cause) {
703 // The caller has the Heap_lock
704 assert(Heap_lock->owned_by_self(), "this thread should own the Heap_lock");
705 collect_locked(cause, Generation::Old);
706 }
707
708 // this is the private collection interface
709 // The Heap_lock is expected to be held on entry.
710
711 void GenCollectedHeap::collect_locked(GCCause::Cause cause, Generation::Type max_generation) {
712 // Read the GC count while holding the Heap_lock
713 unsigned int gc_count_before = total_collections();
714 unsigned int full_gc_count_before = total_full_collections();
715 {
716 MutexUnlocker mu(Heap_lock); // give up heap lock, execute gets it back
717 VM_GenCollectFull op(gc_count_before, full_gc_count_before,
718 cause, max_generation);
719 VMThread::execute(&op);
720 }
721 }
722
723 #if INCLUDE_ALL_GCS
724 bool GenCollectedHeap::create_cms_collector() {
725
726 assert(_old_gen->kind() == Generation::ConcurrentMarkSweep,
727 "Unexpected generation kinds");
728 // Skip two header words in the block content verification
729 NOT_PRODUCT(_skip_header_HeapWords = CMSCollector::skip_header_HeapWords();)
730 CMSCollector* collector = new CMSCollector(
731 (ConcurrentMarkSweepGeneration*)_old_gen,
732 _rem_set->as_CardTableRS(),
733 (ConcurrentMarkSweepPolicy*) collector_policy());
734
735 if (collector == NULL || !collector->completed_initialization()) {
736 if (collector) {
737 delete collector; // Be nice in embedded situation
738 }
739 vm_shutdown_during_initialization("Could not create CMS collector");
740 return false;
741 }
742 return true; // success
743 }
744
745 void GenCollectedHeap::collect_mostly_concurrent(GCCause::Cause cause) {
746 assert(!Heap_lock->owned_by_self(), "Should not own Heap_lock");
747
748 MutexLocker ml(Heap_lock);
749 // Read the GC counts while holding the Heap_lock
750 unsigned int full_gc_count_before = total_full_collections();
751 unsigned int gc_count_before = total_collections();
752 {
753 MutexUnlocker mu(Heap_lock);
754 VM_GenCollectFullConcurrent op(gc_count_before, full_gc_count_before, cause);
755 VMThread::execute(&op);
756 }
757 }
758 #endif // INCLUDE_ALL_GCS
759
760 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs) {
761 do_full_collection(clear_all_soft_refs, Generation::Old);
762 }
763
764 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs,
765 Generation::Type max_gen) {
766 Generation::Type local_max_gen;
767 if (!incremental_collection_will_fail(false /* don't consult_young */) &&
768 gc_cause() == GCCause::_gc_locker) {
769 local_max_gen = Generation::Young;
770 } else {
771 local_max_gen = max_gen;
772 }
773
774 do_collection(true /* full */,
775 clear_all_soft_refs /* clear_all_soft_refs */,
776 0 /* size */,
777 false /* is_tlab */,
778 local_max_gen /* max_gen */);
779 // Hack XXX FIX ME !!!
780 // A scavenge may not have been attempted, or may have
781 // been attempted and failed, because the old gen was too full
782 if (local_max_gen == Generation::Young && gc_cause() == GCCause::_gc_locker &&
783 incremental_collection_will_fail(false /* don't consult_young */)) {
784 if (PrintGCDetails) {
785 gclog_or_tty->print_cr("GC locker: Trying a full collection "
786 "because scavenge failed");
787 }
788 // This time allow the old gen to be collected as well
789 do_collection(true /* full */,
790 clear_all_soft_refs /* clear_all_soft_refs */,
791 0 /* size */,
792 false /* is_tlab */,
793 Generation::Old /* max_gen */);
794 }
795 }
796
797 bool GenCollectedHeap::is_in_young(oop p) {
798 bool result = ((HeapWord*)p) < _old_gen->reserved().start();
799 assert(result == _young_gen->is_in_reserved(p),
800 err_msg("incorrect test - result=%d, p=" INTPTR_FORMAT, result, p2i((void*)p)));
801 return result;
802 }
803
804 // Returns "TRUE" iff "p" points into the committed areas of the heap.
805 bool GenCollectedHeap::is_in(const void* p) const {
806 #ifndef ASSERT
807 guarantee(VerifyBeforeGC ||
808 VerifyDuringGC ||
809 VerifyBeforeExit ||
810 VerifyDuringStartup ||
811 PrintAssembly ||
812 tty->count() != 0 || // already printing
813 VerifyAfterGC ||
814 VMError::fatal_error_in_progress(), "too expensive");
815
816 #endif
817 // This might be sped up with a cache of the last generation that
818 // answered yes.
819 if (_young_gen->is_in(p) || _old_gen->is_in(p)) {
820 return true;
821 }
822 // Otherwise...
823 return false;
824 }
825
826 #ifdef ASSERT
827 // Don't implement this by using is_in_young(). This method is used
828 // in some cases to check that is_in_young() is correct.
829 bool GenCollectedHeap::is_in_partial_collection(const void* p) {
830 assert(is_in_reserved(p) || p == NULL,
831 "Does not work if address is non-null and outside of the heap");
832 return p < _young_gen->reserved().end() && p != NULL;
833 }
834 #endif
835
836 void GenCollectedHeap::oop_iterate(ExtendedOopClosure* cl) {
837 _young_gen->oop_iterate(cl);
838 _old_gen->oop_iterate(cl);
839 }
840
841 void GenCollectedHeap::object_iterate(ObjectClosure* cl) {
842 _young_gen->object_iterate(cl);
843 _old_gen->object_iterate(cl);
844 }
845
846 void GenCollectedHeap::safe_object_iterate(ObjectClosure* cl) {
847 _young_gen->safe_object_iterate(cl);
848 _old_gen->safe_object_iterate(cl);
849 }
850
851 Space* GenCollectedHeap::space_containing(const void* addr) const {
852 Space* res = _young_gen->space_containing(addr);
853 if (res != NULL) {
854 return res;
855 }
856 res = _old_gen->space_containing(addr);
857 assert(res != NULL, "Could not find containing space");
858 return res;
859 }
860
861 HeapWord* GenCollectedHeap::block_start(const void* addr) const {
862 assert(is_in_reserved(addr), "block_start of address outside of heap");
863 if (_young_gen->is_in_reserved(addr)) {
864 assert(_young_gen->is_in(addr), "addr should be in allocated part of generation");
865 return _young_gen->block_start(addr);
866 }
867
868 assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
869 assert(_old_gen->is_in(addr), "addr should be in allocated part of generation");
870 return _old_gen->block_start(addr);
871 }
872
873 size_t GenCollectedHeap::block_size(const HeapWord* addr) const {
874 assert(is_in_reserved(addr), "block_size of address outside of heap");
875 if (_young_gen->is_in_reserved(addr)) {
876 assert(_young_gen->is_in(addr), "addr should be in allocated part of generation");
877 return _young_gen->block_size(addr);
878 }
879
880 assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
881 assert(_old_gen->is_in(addr), "addr should be in allocated part of generation");
882 return _old_gen->block_size(addr);
883 }
884
885 bool GenCollectedHeap::block_is_obj(const HeapWord* addr) const {
886 assert(is_in_reserved(addr), "block_is_obj of address outside of heap");
887 assert(block_start(addr) == addr, "addr must be a block start");
888 if (_young_gen->is_in_reserved(addr)) {
889 return _young_gen->block_is_obj(addr);
890 }
891
892 assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
893 return _old_gen->block_is_obj(addr);
894 }
895
896 bool GenCollectedHeap::supports_tlab_allocation() const {
897 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
898 return _young_gen->supports_tlab_allocation();
899 }
900
901 size_t GenCollectedHeap::tlab_capacity(Thread* thr) const {
902 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
903 if (_young_gen->supports_tlab_allocation()) {
904 return _young_gen->tlab_capacity();
905 }
906 return 0;
907 }
908
909 size_t GenCollectedHeap::tlab_used(Thread* thr) const {
910 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
911 if (_young_gen->supports_tlab_allocation()) {
912 return _young_gen->tlab_used();
913 }
914 return 0;
915 }
916
917 size_t GenCollectedHeap::unsafe_max_tlab_alloc(Thread* thr) const {
918 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
919 if (_young_gen->supports_tlab_allocation()) {
920 return _young_gen->unsafe_max_tlab_alloc();
921 }
922 return 0;
923 }
924
925 HeapWord* GenCollectedHeap::allocate_new_tlab(size_t size) {
926 bool gc_overhead_limit_was_exceeded;
927 return collector_policy()->mem_allocate_work(size /* size */,
928 true /* is_tlab */,
929 &gc_overhead_limit_was_exceeded);
930 }
931
932 // Requires "*prev_ptr" to be non-NULL. Deletes and a block of minimal size
933 // from the list headed by "*prev_ptr".
934 static ScratchBlock *removeSmallestScratch(ScratchBlock **prev_ptr) {
935 bool first = true;
936 size_t min_size = 0; // "first" makes this conceptually infinite.
937 ScratchBlock **smallest_ptr, *smallest;
938 ScratchBlock *cur = *prev_ptr;
939 while (cur) {
940 assert(*prev_ptr == cur, "just checking");
941 if (first || cur->num_words < min_size) {
942 smallest_ptr = prev_ptr;
951 *smallest_ptr = smallest->next;
952 return smallest;
953 }
954
955 // Sort the scratch block list headed by res into decreasing size order,
956 // and set "res" to the result.
957 static void sort_scratch_list(ScratchBlock*& list) {
958 ScratchBlock* sorted = NULL;
959 ScratchBlock* unsorted = list;
960 while (unsorted) {
961 ScratchBlock *smallest = removeSmallestScratch(&unsorted);
962 smallest->next = sorted;
963 sorted = smallest;
964 }
965 list = sorted;
966 }
967
968 ScratchBlock* GenCollectedHeap::gather_scratch(Generation* requestor,
969 size_t max_alloc_words) {
970 ScratchBlock* res = NULL;
971 _young_gen->contribute_scratch(res, requestor, max_alloc_words);
972 _old_gen->contribute_scratch(res, requestor, max_alloc_words);
973 sort_scratch_list(res);
974 return res;
975 }
976
977 void GenCollectedHeap::release_scratch() {
978 _young_gen->reset_scratch();
979 _old_gen->reset_scratch();
980 }
981
982 class GenPrepareForVerifyClosure: public GenCollectedHeap::GenClosure {
983 void do_generation(Generation* gen) {
984 gen->prepare_for_verify();
985 }
986 };
987
988 void GenCollectedHeap::prepare_for_verify() {
989 ensure_parsability(false); // no need to retire TLABs
990 GenPrepareForVerifyClosure blk;
991 generation_iterate(&blk, false);
992 }
993
994 void GenCollectedHeap::generation_iterate(GenClosure* cl,
995 bool old_to_young) {
996 if (old_to_young) {
997 cl->do_generation(_old_gen);
998 cl->do_generation(_young_gen);
999 } else {
1000 cl->do_generation(_young_gen);
1001 cl->do_generation(_old_gen);
1002 }
1003 }
1004
1005 void GenCollectedHeap::space_iterate(SpaceClosure* cl) {
1006 _young_gen->space_iterate(cl, true);
1007 _old_gen->space_iterate(cl, true);
1008 }
1009
1010 bool GenCollectedHeap::is_maximal_no_gc() const {
1011 return _young_gen->is_maximal_no_gc() && _old_gen->is_maximal_no_gc();
1012 }
1013
1014 void GenCollectedHeap::save_marks() {
1015 _young_gen->save_marks();
1016 _old_gen->save_marks();
1017 }
1018
1019 GenCollectedHeap* GenCollectedHeap::heap() {
1020 assert(_gch != NULL, "Uninitialized access to GenCollectedHeap::heap()");
1021 assert(_gch->kind() == CollectedHeap::GenCollectedHeap, "not a generational heap");
1022 return _gch;
1023 }
1024
1025 void GenCollectedHeap::prepare_for_compaction() {
1026 // Start by compacting into same gen.
1027 CompactPoint cp(_old_gen);
1028 _old_gen->prepare_for_compaction(&cp);
1029 _young_gen->prepare_for_compaction(&cp);
1030 }
1031
1032 void GenCollectedHeap::verify(bool silent, VerifyOption option /* ignored */) {
1033 if (!silent) {
1034 gclog_or_tty->print("%s", _old_gen->name());
1035 gclog_or_tty->print(" ");
1036 }
1037 _old_gen->verify();
1038
1039 if (!silent) {
1040 gclog_or_tty->print("%s", _young_gen->name());
1041 gclog_or_tty->print(" ");
1042 }
1043 _young_gen->verify();
1044
1045 if (!silent) {
1046 gclog_or_tty->print("remset ");
1047 }
1048 rem_set()->verify();
1049 }
1050
1051 void GenCollectedHeap::print_on(outputStream* st) const {
1052 _young_gen->print_on(st);
1053 _old_gen->print_on(st);
1054 MetaspaceAux::print_on(st);
1055 }
1056
1057 void GenCollectedHeap::gc_threads_do(ThreadClosure* tc) const {
1058 if (workers() != NULL) {
1059 workers()->threads_do(tc);
1060 }
1061 #if INCLUDE_ALL_GCS
1062 if (UseConcMarkSweepGC) {
1063 ConcurrentMarkSweepThread::threads_do(tc);
1064 }
1065 #endif // INCLUDE_ALL_GCS
1066 }
1067
1068 void GenCollectedHeap::print_gc_threads_on(outputStream* st) const {
1069 #if INCLUDE_ALL_GCS
1070 if (UseParNewGC) {
1071 workers()->print_worker_threads_on(st);
1072 }
1073 if (UseConcMarkSweepGC) {
1074 ConcurrentMarkSweepThread::print_all_on(st);
1075 }
1076 #endif // INCLUDE_ALL_GCS
1077 }
1078
1079 void GenCollectedHeap::print_on_error(outputStream* st) const {
1080 this->CollectedHeap::print_on_error(st);
1081
1082 #if INCLUDE_ALL_GCS
1083 if (UseConcMarkSweepGC) {
1084 st->cr();
1085 CMSCollector::print_on_error(st);
1086 }
1087 #endif // INCLUDE_ALL_GCS
1088 }
1089
1090 void GenCollectedHeap::print_tracing_info() const {
1091 if (TraceYoungGenTime) {
1092 _young_gen->print_summary_info();
1093 }
1094 if (TraceOldGenTime) {
1095 _old_gen->print_summary_info();
1096 }
1097 }
1098
1099 void GenCollectedHeap::print_heap_change(size_t prev_used) const {
1100 if (PrintGCDetails && Verbose) {
1101 gclog_or_tty->print(" " SIZE_FORMAT
1102 "->" SIZE_FORMAT
1103 "(" SIZE_FORMAT ")",
1104 prev_used, used(), capacity());
1105 } else {
1106 gclog_or_tty->print(" " SIZE_FORMAT "K"
1107 "->" SIZE_FORMAT "K"
1108 "(" SIZE_FORMAT "K)",
1109 prev_used / K, used() / K, capacity() / K);
1110 }
1111 }
1112
1113 class GenGCPrologueClosure: public GenCollectedHeap::GenClosure {
1114 private:
1115 bool _full;
1181 }
1182 }
1183 #endif // not PRODUCT
1184
1185 class GenEnsureParsabilityClosure: public GenCollectedHeap::GenClosure {
1186 public:
1187 void do_generation(Generation* gen) {
1188 gen->ensure_parsability();
1189 }
1190 };
1191
1192 void GenCollectedHeap::ensure_parsability(bool retire_tlabs) {
1193 CollectedHeap::ensure_parsability(retire_tlabs);
1194 GenEnsureParsabilityClosure ep_cl;
1195 generation_iterate(&ep_cl, false);
1196 }
1197
1198 oop GenCollectedHeap::handle_failed_promotion(Generation* old_gen,
1199 oop obj,
1200 size_t obj_size) {
1201 guarantee(old_gen == _old_gen, "We only get here with an old generation");
1202 assert(obj_size == (size_t)obj->size(), "bad obj_size passed in");
1203 HeapWord* result = NULL;
1204
1205 result = old_gen->expand_and_allocate(obj_size, false);
1206
1207 if (result != NULL) {
1208 Copy::aligned_disjoint_words((HeapWord*)obj, result, obj_size);
1209 }
1210 return oop(result);
1211 }
1212
1213 class GenTimeOfLastGCClosure: public GenCollectedHeap::GenClosure {
1214 jlong _time; // in ms
1215 jlong _now; // in ms
1216
1217 public:
1218 GenTimeOfLastGCClosure(jlong now) : _time(now), _now(now) { }
1219
1220 jlong time() { return _time; }
1221
|