Mon, 03 May 2010 20:19:05 -0700
6919638: CMS: ExplicitGCInvokesConcurrent misinteracts with gc locker
Summary: GC-locker induced concurrent full gc should be asynchronous; policy now controlled by a separate flag, which defaults to false.
Reviewed-by: jmasa
1 /*
2 * Copyright 2000-2010 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 *
23 */
25 # include "incls/_precompiled.incl"
26 # include "incls/_genCollectedHeap.cpp.incl"
28 GenCollectedHeap* GenCollectedHeap::_gch;
29 NOT_PRODUCT(size_t GenCollectedHeap::_skip_header_HeapWords = 0;)
31 // The set of potentially parallel tasks in strong root scanning.
32 enum GCH_process_strong_roots_tasks {
33 // We probably want to parallelize both of these internally, but for now...
34 GCH_PS_younger_gens,
35 // Leave this one last.
36 GCH_PS_NumElements
37 };
39 GenCollectedHeap::GenCollectedHeap(GenCollectorPolicy *policy) :
40 SharedHeap(policy),
41 _gen_policy(policy),
42 _gen_process_strong_tasks(new SubTasksDone(GCH_PS_NumElements)),
43 _full_collections_completed(0)
44 {
45 if (_gen_process_strong_tasks == NULL ||
46 !_gen_process_strong_tasks->valid()) {
47 vm_exit_during_initialization("Failed necessary allocation.");
48 }
49 assert(policy != NULL, "Sanity check");
50 _preloading_shared_classes = false;
51 }
53 jint GenCollectedHeap::initialize() {
54 CollectedHeap::pre_initialize();
56 int i;
57 _n_gens = gen_policy()->number_of_generations();
59 // While there are no constraints in the GC code that HeapWordSize
60 // be any particular value, there are multiple other areas in the
61 // system which believe this to be true (e.g. oop->object_size in some
62 // cases incorrectly returns the size in wordSize units rather than
63 // HeapWordSize).
64 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
66 // The heap must be at least as aligned as generations.
67 size_t alignment = Generation::GenGrain;
69 _gen_specs = gen_policy()->generations();
70 PermanentGenerationSpec *perm_gen_spec =
71 collector_policy()->permanent_generation();
73 // Make sure the sizes are all aligned.
74 for (i = 0; i < _n_gens; i++) {
75 _gen_specs[i]->align(alignment);
76 }
77 perm_gen_spec->align(alignment);
79 // If we are dumping the heap, then allocate a wasted block of address
80 // space in order to push the heap to a lower address. This extra
81 // address range allows for other (or larger) libraries to be loaded
82 // without them occupying the space required for the shared spaces.
84 if (DumpSharedSpaces) {
85 uintx reserved = 0;
86 uintx block_size = 64*1024*1024;
87 while (reserved < SharedDummyBlockSize) {
88 char* dummy = os::reserve_memory(block_size);
89 reserved += block_size;
90 }
91 }
93 // Allocate space for the heap.
95 char* heap_address;
96 size_t total_reserved = 0;
97 int n_covered_regions = 0;
98 ReservedSpace heap_rs(0);
100 heap_address = allocate(alignment, perm_gen_spec, &total_reserved,
101 &n_covered_regions, &heap_rs);
103 if (UseSharedSpaces) {
104 if (!heap_rs.is_reserved() || heap_address != heap_rs.base()) {
105 if (heap_rs.is_reserved()) {
106 heap_rs.release();
107 }
108 FileMapInfo* mapinfo = FileMapInfo::current_info();
109 mapinfo->fail_continue("Unable to reserve shared region.");
110 allocate(alignment, perm_gen_spec, &total_reserved, &n_covered_regions,
111 &heap_rs);
112 }
113 }
115 if (!heap_rs.is_reserved()) {
116 vm_shutdown_during_initialization(
117 "Could not reserve enough space for object heap");
118 return JNI_ENOMEM;
119 }
121 _reserved = MemRegion((HeapWord*)heap_rs.base(),
122 (HeapWord*)(heap_rs.base() + heap_rs.size()));
124 // It is important to do this in a way such that concurrent readers can't
125 // temporarily think somethings in the heap. (Seen this happen in asserts.)
126 _reserved.set_word_size(0);
127 _reserved.set_start((HeapWord*)heap_rs.base());
128 size_t actual_heap_size = heap_rs.size() - perm_gen_spec->misc_data_size()
129 - perm_gen_spec->misc_code_size();
130 _reserved.set_end((HeapWord*)(heap_rs.base() + actual_heap_size));
132 _rem_set = collector_policy()->create_rem_set(_reserved, n_covered_regions);
133 set_barrier_set(rem_set()->bs());
135 _gch = this;
137 for (i = 0; i < _n_gens; i++) {
138 ReservedSpace this_rs = heap_rs.first_part(_gen_specs[i]->max_size(),
139 UseSharedSpaces, UseSharedSpaces);
140 _gens[i] = _gen_specs[i]->init(this_rs, i, rem_set());
141 heap_rs = heap_rs.last_part(_gen_specs[i]->max_size());
142 }
143 _perm_gen = perm_gen_spec->init(heap_rs, PermSize, rem_set());
145 clear_incremental_collection_will_fail();
146 clear_last_incremental_collection_failed();
148 #ifndef SERIALGC
149 // If we are running CMS, create the collector responsible
150 // for collecting the CMS generations.
151 if (collector_policy()->is_concurrent_mark_sweep_policy()) {
152 bool success = create_cms_collector();
153 if (!success) return JNI_ENOMEM;
154 }
155 #endif // SERIALGC
157 return JNI_OK;
158 }
161 char* GenCollectedHeap::allocate(size_t alignment,
162 PermanentGenerationSpec* perm_gen_spec,
163 size_t* _total_reserved,
164 int* _n_covered_regions,
165 ReservedSpace* heap_rs){
166 const char overflow_msg[] = "The size of the object heap + VM data exceeds "
167 "the maximum representable size";
169 // Now figure out the total size.
170 size_t total_reserved = 0;
171 int n_covered_regions = 0;
172 const size_t pageSize = UseLargePages ?
173 os::large_page_size() : os::vm_page_size();
175 for (int i = 0; i < _n_gens; i++) {
176 total_reserved += _gen_specs[i]->max_size();
177 if (total_reserved < _gen_specs[i]->max_size()) {
178 vm_exit_during_initialization(overflow_msg);
179 }
180 n_covered_regions += _gen_specs[i]->n_covered_regions();
181 }
182 assert(total_reserved % pageSize == 0, "Gen size");
183 total_reserved += perm_gen_spec->max_size();
184 assert(total_reserved % pageSize == 0, "Perm Gen size");
186 if (total_reserved < perm_gen_spec->max_size()) {
187 vm_exit_during_initialization(overflow_msg);
188 }
189 n_covered_regions += perm_gen_spec->n_covered_regions();
191 // Add the size of the data area which shares the same reserved area
192 // as the heap, but which is not actually part of the heap.
193 size_t s = perm_gen_spec->misc_data_size() + perm_gen_spec->misc_code_size();
195 total_reserved += s;
196 if (total_reserved < s) {
197 vm_exit_during_initialization(overflow_msg);
198 }
200 if (UseLargePages) {
201 assert(total_reserved != 0, "total_reserved cannot be 0");
202 total_reserved = round_to(total_reserved, os::large_page_size());
203 if (total_reserved < os::large_page_size()) {
204 vm_exit_during_initialization(overflow_msg);
205 }
206 }
208 // Calculate the address at which the heap must reside in order for
209 // the shared data to be at the required address.
211 char* heap_address;
212 if (UseSharedSpaces) {
214 // Calculate the address of the first word beyond the heap.
215 FileMapInfo* mapinfo = FileMapInfo::current_info();
216 int lr = CompactingPermGenGen::n_regions - 1;
217 size_t capacity = align_size_up(mapinfo->space_capacity(lr), alignment);
218 heap_address = mapinfo->region_base(lr) + capacity;
220 // Calculate the address of the first word of the heap.
221 heap_address -= total_reserved;
222 } else {
223 heap_address = NULL; // any address will do.
224 if (UseCompressedOops) {
225 heap_address = Universe::preferred_heap_base(total_reserved, Universe::UnscaledNarrowOop);
226 *_total_reserved = total_reserved;
227 *_n_covered_regions = n_covered_regions;
228 *heap_rs = ReservedHeapSpace(total_reserved, alignment,
229 UseLargePages, heap_address);
231 if (heap_address != NULL && !heap_rs->is_reserved()) {
232 // Failed to reserve at specified address - the requested memory
233 // region is taken already, for example, by 'java' launcher.
234 // Try again to reserver heap higher.
235 heap_address = Universe::preferred_heap_base(total_reserved, Universe::ZeroBasedNarrowOop);
236 *heap_rs = ReservedHeapSpace(total_reserved, alignment,
237 UseLargePages, heap_address);
239 if (heap_address != NULL && !heap_rs->is_reserved()) {
240 // Failed to reserve at specified address again - give up.
241 heap_address = Universe::preferred_heap_base(total_reserved, Universe::HeapBasedNarrowOop);
242 assert(heap_address == NULL, "");
243 *heap_rs = ReservedHeapSpace(total_reserved, alignment,
244 UseLargePages, heap_address);
245 }
246 }
247 return heap_address;
248 }
249 }
251 *_total_reserved = total_reserved;
252 *_n_covered_regions = n_covered_regions;
253 *heap_rs = ReservedHeapSpace(total_reserved, alignment,
254 UseLargePages, heap_address);
256 return heap_address;
257 }
260 void GenCollectedHeap::post_initialize() {
261 SharedHeap::post_initialize();
262 TwoGenerationCollectorPolicy *policy =
263 (TwoGenerationCollectorPolicy *)collector_policy();
264 guarantee(policy->is_two_generation_policy(), "Illegal policy type");
265 DefNewGeneration* def_new_gen = (DefNewGeneration*) get_gen(0);
266 assert(def_new_gen->kind() == Generation::DefNew ||
267 def_new_gen->kind() == Generation::ParNew ||
268 def_new_gen->kind() == Generation::ASParNew,
269 "Wrong generation kind");
271 Generation* old_gen = get_gen(1);
272 assert(old_gen->kind() == Generation::ConcurrentMarkSweep ||
273 old_gen->kind() == Generation::ASConcurrentMarkSweep ||
274 old_gen->kind() == Generation::MarkSweepCompact,
275 "Wrong generation kind");
277 policy->initialize_size_policy(def_new_gen->eden()->capacity(),
278 old_gen->capacity(),
279 def_new_gen->from()->capacity());
280 policy->initialize_gc_policy_counters();
281 }
283 void GenCollectedHeap::ref_processing_init() {
284 SharedHeap::ref_processing_init();
285 for (int i = 0; i < _n_gens; i++) {
286 _gens[i]->ref_processor_init();
287 }
288 }
290 size_t GenCollectedHeap::capacity() const {
291 size_t res = 0;
292 for (int i = 0; i < _n_gens; i++) {
293 res += _gens[i]->capacity();
294 }
295 return res;
296 }
298 size_t GenCollectedHeap::used() const {
299 size_t res = 0;
300 for (int i = 0; i < _n_gens; i++) {
301 res += _gens[i]->used();
302 }
303 return res;
304 }
306 // Save the "used_region" for generations level and lower,
307 // and, if perm is true, for perm gen.
308 void GenCollectedHeap::save_used_regions(int level, bool perm) {
309 assert(level < _n_gens, "Illegal level parameter");
310 for (int i = level; i >= 0; i--) {
311 _gens[i]->save_used_region();
312 }
313 if (perm) {
314 perm_gen()->save_used_region();
315 }
316 }
318 size_t GenCollectedHeap::max_capacity() const {
319 size_t res = 0;
320 for (int i = 0; i < _n_gens; i++) {
321 res += _gens[i]->max_capacity();
322 }
323 return res;
324 }
326 // Update the _full_collections_completed counter
327 // at the end of a stop-world full GC.
328 unsigned int GenCollectedHeap::update_full_collections_completed() {
329 MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
330 assert(_full_collections_completed <= _total_full_collections,
331 "Can't complete more collections than were started");
332 _full_collections_completed = _total_full_collections;
333 ml.notify_all();
334 return _full_collections_completed;
335 }
337 // Update the _full_collections_completed counter, as appropriate,
338 // at the end of a concurrent GC cycle. Note the conditional update
339 // below to allow this method to be called by a concurrent collector
340 // without synchronizing in any manner with the VM thread (which
341 // may already have initiated a STW full collection "concurrently").
342 unsigned int GenCollectedHeap::update_full_collections_completed(unsigned int count) {
343 MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
344 assert((_full_collections_completed <= _total_full_collections) &&
345 (count <= _total_full_collections),
346 "Can't complete more collections than were started");
347 if (count > _full_collections_completed) {
348 _full_collections_completed = count;
349 ml.notify_all();
350 }
351 return _full_collections_completed;
352 }
355 #ifndef PRODUCT
356 // Override of memory state checking method in CollectedHeap:
357 // Some collectors (CMS for example) can't have badHeapWordVal written
358 // in the first two words of an object. (For instance , in the case of
359 // CMS these words hold state used to synchronize between certain
360 // (concurrent) GC steps and direct allocating mutators.)
361 // The skip_header_HeapWords() method below, allows us to skip
362 // over the requisite number of HeapWord's. Note that (for
363 // generational collectors) this means that those many words are
364 // skipped in each object, irrespective of the generation in which
365 // that object lives. The resultant loss of precision seems to be
366 // harmless and the pain of avoiding that imprecision appears somewhat
367 // higher than we are prepared to pay for such rudimentary debugging
368 // support.
369 void GenCollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr,
370 size_t size) {
371 if (CheckMemoryInitialization && ZapUnusedHeapArea) {
372 // We are asked to check a size in HeapWords,
373 // but the memory is mangled in juint words.
374 juint* start = (juint*) (addr + skip_header_HeapWords());
375 juint* end = (juint*) (addr + size);
376 for (juint* slot = start; slot < end; slot += 1) {
377 assert(*slot == badHeapWordVal,
378 "Found non badHeapWordValue in pre-allocation check");
379 }
380 }
381 }
382 #endif
384 HeapWord* GenCollectedHeap::attempt_allocation(size_t size,
385 bool is_tlab,
386 bool first_only) {
387 HeapWord* res;
388 for (int i = 0; i < _n_gens; i++) {
389 if (_gens[i]->should_allocate(size, is_tlab)) {
390 res = _gens[i]->allocate(size, is_tlab);
391 if (res != NULL) return res;
392 else if (first_only) break;
393 }
394 }
395 // Otherwise...
396 return NULL;
397 }
399 HeapWord* GenCollectedHeap::mem_allocate(size_t size,
400 bool is_large_noref,
401 bool is_tlab,
402 bool* gc_overhead_limit_was_exceeded) {
403 return collector_policy()->mem_allocate_work(size,
404 is_tlab,
405 gc_overhead_limit_was_exceeded);
406 }
408 bool GenCollectedHeap::must_clear_all_soft_refs() {
409 return _gc_cause == GCCause::_last_ditch_collection;
410 }
412 bool GenCollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
413 return UseConcMarkSweepGC &&
414 ((cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) ||
415 (cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent));
416 }
418 void GenCollectedHeap::do_collection(bool full,
419 bool clear_all_soft_refs,
420 size_t size,
421 bool is_tlab,
422 int max_level) {
423 bool prepared_for_verification = false;
424 ResourceMark rm;
425 DEBUG_ONLY(Thread* my_thread = Thread::current();)
427 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
428 assert(my_thread->is_VM_thread() ||
429 my_thread->is_ConcurrentGC_thread(),
430 "incorrect thread type capability");
431 assert(Heap_lock->is_locked(),
432 "the requesting thread should have the Heap_lock");
433 guarantee(!is_gc_active(), "collection is not reentrant");
434 assert(max_level < n_gens(), "sanity check");
436 if (GC_locker::check_active_before_gc()) {
437 return; // GC is disabled (e.g. JNI GetXXXCritical operation)
438 }
440 const bool do_clear_all_soft_refs = clear_all_soft_refs ||
441 collector_policy()->should_clear_all_soft_refs();
443 ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());
445 const size_t perm_prev_used = perm_gen()->used();
447 if (PrintHeapAtGC) {
448 Universe::print_heap_before_gc();
449 if (Verbose) {
450 gclog_or_tty->print_cr("GC Cause: %s", GCCause::to_string(gc_cause()));
451 }
452 }
454 {
455 FlagSetting fl(_is_gc_active, true);
457 bool complete = full && (max_level == (n_gens()-1));
458 const char* gc_cause_str = "GC ";
459 if (complete) {
460 GCCause::Cause cause = gc_cause();
461 if (cause == GCCause::_java_lang_system_gc) {
462 gc_cause_str = "Full GC (System) ";
463 } else {
464 gc_cause_str = "Full GC ";
465 }
466 }
467 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
468 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
469 TraceTime t(gc_cause_str, PrintGCDetails, false, gclog_or_tty);
471 gc_prologue(complete);
472 increment_total_collections(complete);
474 size_t gch_prev_used = used();
476 int starting_level = 0;
477 if (full) {
478 // Search for the oldest generation which will collect all younger
479 // generations, and start collection loop there.
480 for (int i = max_level; i >= 0; i--) {
481 if (_gens[i]->full_collects_younger_generations()) {
482 starting_level = i;
483 break;
484 }
485 }
486 }
488 bool must_restore_marks_for_biased_locking = false;
490 int max_level_collected = starting_level;
491 for (int i = starting_level; i <= max_level; i++) {
492 if (_gens[i]->should_collect(full, size, is_tlab)) {
493 if (i == n_gens() - 1) { // a major collection is to happen
494 if (!complete) {
495 // The full_collections increment was missed above.
496 increment_total_full_collections();
497 }
498 pre_full_gc_dump(); // do any pre full gc dumps
499 }
500 // Timer for individual generations. Last argument is false: no CR
501 TraceTime t1(_gens[i]->short_name(), PrintGCDetails, false, gclog_or_tty);
502 TraceCollectorStats tcs(_gens[i]->counters());
503 TraceMemoryManagerStats tmms(_gens[i]->kind());
505 size_t prev_used = _gens[i]->used();
506 _gens[i]->stat_record()->invocations++;
507 _gens[i]->stat_record()->accumulated_time.start();
509 // Must be done anew before each collection because
510 // a previous collection will do mangling and will
511 // change top of some spaces.
512 record_gen_tops_before_GC();
514 if (PrintGC && Verbose) {
515 gclog_or_tty->print("level=%d invoke=%d size=" SIZE_FORMAT,
516 i,
517 _gens[i]->stat_record()->invocations,
518 size*HeapWordSize);
519 }
521 if (VerifyBeforeGC && i >= VerifyGCLevel &&
522 total_collections() >= VerifyGCStartAt) {
523 HandleMark hm; // Discard invalid handles created during verification
524 if (!prepared_for_verification) {
525 prepare_for_verify();
526 prepared_for_verification = true;
527 }
528 gclog_or_tty->print(" VerifyBeforeGC:");
529 Universe::verify(true);
530 }
531 COMPILER2_PRESENT(DerivedPointerTable::clear());
533 if (!must_restore_marks_for_biased_locking &&
534 _gens[i]->performs_in_place_marking()) {
535 // We perform this mark word preservation work lazily
536 // because it's only at this point that we know whether we
537 // absolutely have to do it; we want to avoid doing it for
538 // scavenge-only collections where it's unnecessary
539 must_restore_marks_for_biased_locking = true;
540 BiasedLocking::preserve_marks();
541 }
543 // Do collection work
544 {
545 // Note on ref discovery: For what appear to be historical reasons,
546 // GCH enables and disabled (by enqueing) refs discovery.
547 // In the future this should be moved into the generation's
548 // collect method so that ref discovery and enqueueing concerns
549 // are local to a generation. The collect method could return
550 // an appropriate indication in the case that notification on
551 // the ref lock was needed. This will make the treatment of
552 // weak refs more uniform (and indeed remove such concerns
553 // from GCH). XXX
555 HandleMark hm; // Discard invalid handles created during gc
556 save_marks(); // save marks for all gens
557 // We want to discover references, but not process them yet.
558 // This mode is disabled in process_discovered_references if the
559 // generation does some collection work, or in
560 // enqueue_discovered_references if the generation returns
561 // without doing any work.
562 ReferenceProcessor* rp = _gens[i]->ref_processor();
563 // If the discovery of ("weak") refs in this generation is
564 // atomic wrt other collectors in this configuration, we
565 // are guaranteed to have empty discovered ref lists.
566 if (rp->discovery_is_atomic()) {
567 rp->verify_no_references_recorded();
568 rp->enable_discovery();
569 rp->setup_policy(do_clear_all_soft_refs);
570 } else {
571 // collect() below will enable discovery as appropriate
572 }
573 _gens[i]->collect(full, do_clear_all_soft_refs, size, is_tlab);
574 if (!rp->enqueuing_is_done()) {
575 rp->enqueue_discovered_references();
576 } else {
577 rp->set_enqueuing_is_done(false);
578 }
579 rp->verify_no_references_recorded();
580 }
581 max_level_collected = i;
583 // Determine if allocation request was met.
584 if (size > 0) {
585 if (!is_tlab || _gens[i]->supports_tlab_allocation()) {
586 if (size*HeapWordSize <= _gens[i]->unsafe_max_alloc_nogc()) {
587 size = 0;
588 }
589 }
590 }
592 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
594 _gens[i]->stat_record()->accumulated_time.stop();
596 update_gc_stats(i, full);
598 if (VerifyAfterGC && i >= VerifyGCLevel &&
599 total_collections() >= VerifyGCStartAt) {
600 HandleMark hm; // Discard invalid handles created during verification
601 gclog_or_tty->print(" VerifyAfterGC:");
602 Universe::verify(false);
603 }
605 if (PrintGCDetails) {
606 gclog_or_tty->print(":");
607 _gens[i]->print_heap_change(prev_used);
608 }
609 }
610 }
612 // Update "complete" boolean wrt what actually transpired --
613 // for instance, a promotion failure could have led to
614 // a whole heap collection.
615 complete = complete || (max_level_collected == n_gens() - 1);
617 if (complete) { // We did a "major" collection
618 post_full_gc_dump(); // do any post full gc dumps
619 }
621 if (PrintGCDetails) {
622 print_heap_change(gch_prev_used);
624 // Print perm gen info for full GC with PrintGCDetails flag.
625 if (complete) {
626 print_perm_heap_change(perm_prev_used);
627 }
628 }
630 for (int j = max_level_collected; j >= 0; j -= 1) {
631 // Adjust generation sizes.
632 _gens[j]->compute_new_size();
633 }
635 if (complete) {
636 // Ask the permanent generation to adjust size for full collections
637 perm()->compute_new_size();
638 update_full_collections_completed();
639 }
641 // Track memory usage and detect low memory after GC finishes
642 MemoryService::track_memory_usage();
644 gc_epilogue(complete);
646 if (must_restore_marks_for_biased_locking) {
647 BiasedLocking::restore_marks();
648 }
649 }
651 AdaptiveSizePolicy* sp = gen_policy()->size_policy();
652 AdaptiveSizePolicyOutput(sp, total_collections());
654 if (PrintHeapAtGC) {
655 Universe::print_heap_after_gc();
656 }
658 #ifdef TRACESPINNING
659 ParallelTaskTerminator::print_termination_counts();
660 #endif
662 if (ExitAfterGCNum > 0 && total_collections() == ExitAfterGCNum) {
663 tty->print_cr("Stopping after GC #%d", ExitAfterGCNum);
664 vm_exit(-1);
665 }
666 }
668 HeapWord* GenCollectedHeap::satisfy_failed_allocation(size_t size, bool is_tlab) {
669 return collector_policy()->satisfy_failed_allocation(size, is_tlab);
670 }
672 void GenCollectedHeap::set_par_threads(int t) {
673 SharedHeap::set_par_threads(t);
674 _gen_process_strong_tasks->set_par_threads(t);
675 }
677 class AssertIsPermClosure: public OopClosure {
678 public:
679 void do_oop(oop* p) {
680 assert((*p) == NULL || (*p)->is_perm(), "Referent should be perm.");
681 }
682 void do_oop(narrowOop* p) { ShouldNotReachHere(); }
683 };
684 static AssertIsPermClosure assert_is_perm_closure;
686 void GenCollectedHeap::
687 gen_process_strong_roots(int level,
688 bool younger_gens_as_roots,
689 bool activate_scope,
690 bool collecting_perm_gen,
691 SharedHeap::ScanningOption so,
692 OopsInGenClosure* not_older_gens,
693 bool do_code_roots,
694 OopsInGenClosure* older_gens) {
695 // General strong roots.
697 if (!do_code_roots) {
698 SharedHeap::process_strong_roots(activate_scope, collecting_perm_gen, so,
699 not_older_gens, NULL, older_gens);
700 } else {
701 bool do_code_marking = (activate_scope || nmethod::oops_do_marking_is_active());
702 CodeBlobToOopClosure code_roots(not_older_gens, /*do_marking=*/ do_code_marking);
703 SharedHeap::process_strong_roots(activate_scope, collecting_perm_gen, so,
704 not_older_gens, &code_roots, older_gens);
705 }
707 if (younger_gens_as_roots) {
708 if (!_gen_process_strong_tasks->is_task_claimed(GCH_PS_younger_gens)) {
709 for (int i = 0; i < level; i++) {
710 not_older_gens->set_generation(_gens[i]);
711 _gens[i]->oop_iterate(not_older_gens);
712 }
713 not_older_gens->reset_generation();
714 }
715 }
716 // When collection is parallel, all threads get to cooperate to do
717 // older-gen scanning.
718 for (int i = level+1; i < _n_gens; i++) {
719 older_gens->set_generation(_gens[i]);
720 rem_set()->younger_refs_iterate(_gens[i], older_gens);
721 older_gens->reset_generation();
722 }
724 _gen_process_strong_tasks->all_tasks_completed();
725 }
727 void GenCollectedHeap::gen_process_weak_roots(OopClosure* root_closure,
728 CodeBlobClosure* code_roots,
729 OopClosure* non_root_closure) {
730 SharedHeap::process_weak_roots(root_closure, code_roots, non_root_closure);
731 // "Local" "weak" refs
732 for (int i = 0; i < _n_gens; i++) {
733 _gens[i]->ref_processor()->weak_oops_do(root_closure);
734 }
735 }
737 #define GCH_SINCE_SAVE_MARKS_ITERATE_DEFN(OopClosureType, nv_suffix) \
738 void GenCollectedHeap:: \
739 oop_since_save_marks_iterate(int level, \
740 OopClosureType* cur, \
741 OopClosureType* older) { \
742 _gens[level]->oop_since_save_marks_iterate##nv_suffix(cur); \
743 for (int i = level+1; i < n_gens(); i++) { \
744 _gens[i]->oop_since_save_marks_iterate##nv_suffix(older); \
745 } \
746 perm_gen()->oop_since_save_marks_iterate##nv_suffix(older); \
747 }
749 ALL_SINCE_SAVE_MARKS_CLOSURES(GCH_SINCE_SAVE_MARKS_ITERATE_DEFN)
751 #undef GCH_SINCE_SAVE_MARKS_ITERATE_DEFN
753 bool GenCollectedHeap::no_allocs_since_save_marks(int level) {
754 for (int i = level; i < _n_gens; i++) {
755 if (!_gens[i]->no_allocs_since_save_marks()) return false;
756 }
757 return perm_gen()->no_allocs_since_save_marks();
758 }
760 bool GenCollectedHeap::supports_inline_contig_alloc() const {
761 return _gens[0]->supports_inline_contig_alloc();
762 }
764 HeapWord** GenCollectedHeap::top_addr() const {
765 return _gens[0]->top_addr();
766 }
768 HeapWord** GenCollectedHeap::end_addr() const {
769 return _gens[0]->end_addr();
770 }
772 size_t GenCollectedHeap::unsafe_max_alloc() {
773 return _gens[0]->unsafe_max_alloc_nogc();
774 }
776 // public collection interfaces
778 void GenCollectedHeap::collect(GCCause::Cause cause) {
779 if (should_do_concurrent_full_gc(cause)) {
780 #ifndef SERIALGC
781 // mostly concurrent full collection
782 collect_mostly_concurrent(cause);
783 #else // SERIALGC
784 ShouldNotReachHere();
785 #endif // SERIALGC
786 } else {
787 #ifdef ASSERT
788 if (cause == GCCause::_scavenge_alot) {
789 // minor collection only
790 collect(cause, 0);
791 } else {
792 // Stop-the-world full collection
793 collect(cause, n_gens() - 1);
794 }
795 #else
796 // Stop-the-world full collection
797 collect(cause, n_gens() - 1);
798 #endif
799 }
800 }
802 void GenCollectedHeap::collect(GCCause::Cause cause, int max_level) {
803 // The caller doesn't have the Heap_lock
804 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
805 MutexLocker ml(Heap_lock);
806 collect_locked(cause, max_level);
807 }
809 // This interface assumes that it's being called by the
810 // vm thread. It collects the heap assuming that the
811 // heap lock is already held and that we are executing in
812 // the context of the vm thread.
813 void GenCollectedHeap::collect_as_vm_thread(GCCause::Cause cause) {
814 assert(Thread::current()->is_VM_thread(), "Precondition#1");
815 assert(Heap_lock->is_locked(), "Precondition#2");
816 GCCauseSetter gcs(this, cause);
817 switch (cause) {
818 case GCCause::_heap_inspection:
819 case GCCause::_heap_dump: {
820 HandleMark hm;
821 do_full_collection(false, // don't clear all soft refs
822 n_gens() - 1);
823 break;
824 }
825 default: // XXX FIX ME
826 ShouldNotReachHere(); // Unexpected use of this function
827 }
828 }
830 void GenCollectedHeap::collect_locked(GCCause::Cause cause) {
831 // The caller has the Heap_lock
832 assert(Heap_lock->owned_by_self(), "this thread should own the Heap_lock");
833 collect_locked(cause, n_gens() - 1);
834 }
836 // this is the private collection interface
837 // The Heap_lock is expected to be held on entry.
839 void GenCollectedHeap::collect_locked(GCCause::Cause cause, int max_level) {
840 if (_preloading_shared_classes) {
841 warning("\nThe permanent generation is not large enough to preload "
842 "requested classes.\nUse -XX:PermSize= to increase the initial "
843 "size of the permanent generation.\n");
844 vm_exit(2);
845 }
846 // Read the GC count while holding the Heap_lock
847 unsigned int gc_count_before = total_collections();
848 unsigned int full_gc_count_before = total_full_collections();
849 {
850 MutexUnlocker mu(Heap_lock); // give up heap lock, execute gets it back
851 VM_GenCollectFull op(gc_count_before, full_gc_count_before,
852 cause, max_level);
853 VMThread::execute(&op);
854 }
855 }
857 #ifndef SERIALGC
858 bool GenCollectedHeap::create_cms_collector() {
860 assert(((_gens[1]->kind() == Generation::ConcurrentMarkSweep) ||
861 (_gens[1]->kind() == Generation::ASConcurrentMarkSweep)) &&
862 _perm_gen->as_gen()->kind() == Generation::ConcurrentMarkSweep,
863 "Unexpected generation kinds");
864 // Skip two header words in the block content verification
865 NOT_PRODUCT(_skip_header_HeapWords = CMSCollector::skip_header_HeapWords();)
866 CMSCollector* collector = new CMSCollector(
867 (ConcurrentMarkSweepGeneration*)_gens[1],
868 (ConcurrentMarkSweepGeneration*)_perm_gen->as_gen(),
869 _rem_set->as_CardTableRS(),
870 (ConcurrentMarkSweepPolicy*) collector_policy());
872 if (collector == NULL || !collector->completed_initialization()) {
873 if (collector) {
874 delete collector; // Be nice in embedded situation
875 }
876 vm_shutdown_during_initialization("Could not create CMS collector");
877 return false;
878 }
879 return true; // success
880 }
882 void GenCollectedHeap::collect_mostly_concurrent(GCCause::Cause cause) {
883 assert(!Heap_lock->owned_by_self(), "Should not own Heap_lock");
885 MutexLocker ml(Heap_lock);
886 // Read the GC counts while holding the Heap_lock
887 unsigned int full_gc_count_before = total_full_collections();
888 unsigned int gc_count_before = total_collections();
889 {
890 MutexUnlocker mu(Heap_lock);
891 VM_GenCollectFullConcurrent op(gc_count_before, full_gc_count_before, cause);
892 VMThread::execute(&op);
893 }
894 }
895 #endif // SERIALGC
898 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs,
899 int max_level) {
900 int local_max_level;
901 if (!incremental_collection_will_fail() &&
902 gc_cause() == GCCause::_gc_locker) {
903 local_max_level = 0;
904 } else {
905 local_max_level = max_level;
906 }
908 do_collection(true /* full */,
909 clear_all_soft_refs /* clear_all_soft_refs */,
910 0 /* size */,
911 false /* is_tlab */,
912 local_max_level /* max_level */);
913 // Hack XXX FIX ME !!!
914 // A scavenge may not have been attempted, or may have
915 // been attempted and failed, because the old gen was too full
916 if (local_max_level == 0 && gc_cause() == GCCause::_gc_locker &&
917 incremental_collection_will_fail()) {
918 if (PrintGCDetails) {
919 gclog_or_tty->print_cr("GC locker: Trying a full collection "
920 "because scavenge failed");
921 }
922 // This time allow the old gen to be collected as well
923 do_collection(true /* full */,
924 clear_all_soft_refs /* clear_all_soft_refs */,
925 0 /* size */,
926 false /* is_tlab */,
927 n_gens() - 1 /* max_level */);
928 }
929 }
931 // Returns "TRUE" iff "p" points into the allocated area of the heap.
932 bool GenCollectedHeap::is_in(const void* p) const {
933 #ifndef ASSERT
934 guarantee(VerifyBeforeGC ||
935 VerifyDuringGC ||
936 VerifyBeforeExit ||
937 PrintAssembly ||
938 tty->count() != 0 || // already printing
939 VerifyAfterGC, "too expensive");
940 #endif
941 // This might be sped up with a cache of the last generation that
942 // answered yes.
943 for (int i = 0; i < _n_gens; i++) {
944 if (_gens[i]->is_in(p)) return true;
945 }
946 if (_perm_gen->as_gen()->is_in(p)) return true;
947 // Otherwise...
948 return false;
949 }
951 // Returns "TRUE" iff "p" points into the allocated area of the heap.
952 bool GenCollectedHeap::is_in_youngest(void* p) {
953 return _gens[0]->is_in(p);
954 }
956 void GenCollectedHeap::oop_iterate(OopClosure* cl) {
957 for (int i = 0; i < _n_gens; i++) {
958 _gens[i]->oop_iterate(cl);
959 }
960 }
962 void GenCollectedHeap::oop_iterate(MemRegion mr, OopClosure* cl) {
963 for (int i = 0; i < _n_gens; i++) {
964 _gens[i]->oop_iterate(mr, cl);
965 }
966 }
968 void GenCollectedHeap::object_iterate(ObjectClosure* cl) {
969 for (int i = 0; i < _n_gens; i++) {
970 _gens[i]->object_iterate(cl);
971 }
972 perm_gen()->object_iterate(cl);
973 }
975 void GenCollectedHeap::safe_object_iterate(ObjectClosure* cl) {
976 for (int i = 0; i < _n_gens; i++) {
977 _gens[i]->safe_object_iterate(cl);
978 }
979 perm_gen()->safe_object_iterate(cl);
980 }
982 void GenCollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) {
983 for (int i = 0; i < _n_gens; i++) {
984 _gens[i]->object_iterate_since_last_GC(cl);
985 }
986 }
988 Space* GenCollectedHeap::space_containing(const void* addr) const {
989 for (int i = 0; i < _n_gens; i++) {
990 Space* res = _gens[i]->space_containing(addr);
991 if (res != NULL) return res;
992 }
993 Space* res = perm_gen()->space_containing(addr);
994 if (res != NULL) return res;
995 // Otherwise...
996 assert(false, "Could not find containing space");
997 return NULL;
998 }
1001 HeapWord* GenCollectedHeap::block_start(const void* addr) const {
1002 assert(is_in_reserved(addr), "block_start of address outside of heap");
1003 for (int i = 0; i < _n_gens; i++) {
1004 if (_gens[i]->is_in_reserved(addr)) {
1005 assert(_gens[i]->is_in(addr),
1006 "addr should be in allocated part of generation");
1007 return _gens[i]->block_start(addr);
1008 }
1009 }
1010 if (perm_gen()->is_in_reserved(addr)) {
1011 assert(perm_gen()->is_in(addr),
1012 "addr should be in allocated part of perm gen");
1013 return perm_gen()->block_start(addr);
1014 }
1015 assert(false, "Some generation should contain the address");
1016 return NULL;
1017 }
1019 size_t GenCollectedHeap::block_size(const HeapWord* addr) const {
1020 assert(is_in_reserved(addr), "block_size of address outside of heap");
1021 for (int i = 0; i < _n_gens; i++) {
1022 if (_gens[i]->is_in_reserved(addr)) {
1023 assert(_gens[i]->is_in(addr),
1024 "addr should be in allocated part of generation");
1025 return _gens[i]->block_size(addr);
1026 }
1027 }
1028 if (perm_gen()->is_in_reserved(addr)) {
1029 assert(perm_gen()->is_in(addr),
1030 "addr should be in allocated part of perm gen");
1031 return perm_gen()->block_size(addr);
1032 }
1033 assert(false, "Some generation should contain the address");
1034 return 0;
1035 }
1037 bool GenCollectedHeap::block_is_obj(const HeapWord* addr) const {
1038 assert(is_in_reserved(addr), "block_is_obj of address outside of heap");
1039 assert(block_start(addr) == addr, "addr must be a block start");
1040 for (int i = 0; i < _n_gens; i++) {
1041 if (_gens[i]->is_in_reserved(addr)) {
1042 return _gens[i]->block_is_obj(addr);
1043 }
1044 }
1045 if (perm_gen()->is_in_reserved(addr)) {
1046 return perm_gen()->block_is_obj(addr);
1047 }
1048 assert(false, "Some generation should contain the address");
1049 return false;
1050 }
1052 bool GenCollectedHeap::supports_tlab_allocation() const {
1053 for (int i = 0; i < _n_gens; i += 1) {
1054 if (_gens[i]->supports_tlab_allocation()) {
1055 return true;
1056 }
1057 }
1058 return false;
1059 }
1061 size_t GenCollectedHeap::tlab_capacity(Thread* thr) const {
1062 size_t result = 0;
1063 for (int i = 0; i < _n_gens; i += 1) {
1064 if (_gens[i]->supports_tlab_allocation()) {
1065 result += _gens[i]->tlab_capacity();
1066 }
1067 }
1068 return result;
1069 }
1071 size_t GenCollectedHeap::unsafe_max_tlab_alloc(Thread* thr) const {
1072 size_t result = 0;
1073 for (int i = 0; i < _n_gens; i += 1) {
1074 if (_gens[i]->supports_tlab_allocation()) {
1075 result += _gens[i]->unsafe_max_tlab_alloc();
1076 }
1077 }
1078 return result;
1079 }
1081 HeapWord* GenCollectedHeap::allocate_new_tlab(size_t size) {
1082 bool gc_overhead_limit_was_exceeded;
1083 HeapWord* result = mem_allocate(size /* size */,
1084 false /* is_large_noref */,
1085 true /* is_tlab */,
1086 &gc_overhead_limit_was_exceeded);
1087 return result;
1088 }
1090 // Requires "*prev_ptr" to be non-NULL. Deletes and a block of minimal size
1091 // from the list headed by "*prev_ptr".
1092 static ScratchBlock *removeSmallestScratch(ScratchBlock **prev_ptr) {
1093 bool first = true;
1094 size_t min_size = 0; // "first" makes this conceptually infinite.
1095 ScratchBlock **smallest_ptr, *smallest;
1096 ScratchBlock *cur = *prev_ptr;
1097 while (cur) {
1098 assert(*prev_ptr == cur, "just checking");
1099 if (first || cur->num_words < min_size) {
1100 smallest_ptr = prev_ptr;
1101 smallest = cur;
1102 min_size = smallest->num_words;
1103 first = false;
1104 }
1105 prev_ptr = &cur->next;
1106 cur = cur->next;
1107 }
1108 smallest = *smallest_ptr;
1109 *smallest_ptr = smallest->next;
1110 return smallest;
1111 }
1113 // Sort the scratch block list headed by res into decreasing size order,
1114 // and set "res" to the result.
1115 static void sort_scratch_list(ScratchBlock*& list) {
1116 ScratchBlock* sorted = NULL;
1117 ScratchBlock* unsorted = list;
1118 while (unsorted) {
1119 ScratchBlock *smallest = removeSmallestScratch(&unsorted);
1120 smallest->next = sorted;
1121 sorted = smallest;
1122 }
1123 list = sorted;
1124 }
1126 ScratchBlock* GenCollectedHeap::gather_scratch(Generation* requestor,
1127 size_t max_alloc_words) {
1128 ScratchBlock* res = NULL;
1129 for (int i = 0; i < _n_gens; i++) {
1130 _gens[i]->contribute_scratch(res, requestor, max_alloc_words);
1131 }
1132 sort_scratch_list(res);
1133 return res;
1134 }
1136 void GenCollectedHeap::release_scratch() {
1137 for (int i = 0; i < _n_gens; i++) {
1138 _gens[i]->reset_scratch();
1139 }
1140 }
1142 size_t GenCollectedHeap::large_typearray_limit() {
1143 return gen_policy()->large_typearray_limit();
1144 }
1146 class GenPrepareForVerifyClosure: public GenCollectedHeap::GenClosure {
1147 void do_generation(Generation* gen) {
1148 gen->prepare_for_verify();
1149 }
1150 };
1152 void GenCollectedHeap::prepare_for_verify() {
1153 ensure_parsability(false); // no need to retire TLABs
1154 GenPrepareForVerifyClosure blk;
1155 generation_iterate(&blk, false);
1156 perm_gen()->prepare_for_verify();
1157 }
1160 void GenCollectedHeap::generation_iterate(GenClosure* cl,
1161 bool old_to_young) {
1162 if (old_to_young) {
1163 for (int i = _n_gens-1; i >= 0; i--) {
1164 cl->do_generation(_gens[i]);
1165 }
1166 } else {
1167 for (int i = 0; i < _n_gens; i++) {
1168 cl->do_generation(_gens[i]);
1169 }
1170 }
1171 }
1173 void GenCollectedHeap::space_iterate(SpaceClosure* cl) {
1174 for (int i = 0; i < _n_gens; i++) {
1175 _gens[i]->space_iterate(cl, true);
1176 }
1177 perm_gen()->space_iterate(cl, true);
1178 }
1180 bool GenCollectedHeap::is_maximal_no_gc() const {
1181 for (int i = 0; i < _n_gens; i++) { // skip perm gen
1182 if (!_gens[i]->is_maximal_no_gc()) {
1183 return false;
1184 }
1185 }
1186 return true;
1187 }
1189 void GenCollectedHeap::save_marks() {
1190 for (int i = 0; i < _n_gens; i++) {
1191 _gens[i]->save_marks();
1192 }
1193 perm_gen()->save_marks();
1194 }
1196 void GenCollectedHeap::compute_new_generation_sizes(int collectedGen) {
1197 for (int i = 0; i <= collectedGen; i++) {
1198 _gens[i]->compute_new_size();
1199 }
1200 }
1202 GenCollectedHeap* GenCollectedHeap::heap() {
1203 assert(_gch != NULL, "Uninitialized access to GenCollectedHeap::heap()");
1204 assert(_gch->kind() == CollectedHeap::GenCollectedHeap, "not a generational heap");
1205 return _gch;
1206 }
1209 void GenCollectedHeap::prepare_for_compaction() {
1210 Generation* scanning_gen = _gens[_n_gens-1];
1211 // Start by compacting into same gen.
1212 CompactPoint cp(scanning_gen, NULL, NULL);
1213 while (scanning_gen != NULL) {
1214 scanning_gen->prepare_for_compaction(&cp);
1215 scanning_gen = prev_gen(scanning_gen);
1216 }
1217 }
1219 GCStats* GenCollectedHeap::gc_stats(int level) const {
1220 return _gens[level]->gc_stats();
1221 }
1223 void GenCollectedHeap::verify(bool allow_dirty, bool silent, bool option /* ignored */) {
1224 if (!silent) {
1225 gclog_or_tty->print("permgen ");
1226 }
1227 perm_gen()->verify(allow_dirty);
1228 for (int i = _n_gens-1; i >= 0; i--) {
1229 Generation* g = _gens[i];
1230 if (!silent) {
1231 gclog_or_tty->print(g->name());
1232 gclog_or_tty->print(" ");
1233 }
1234 g->verify(allow_dirty);
1235 }
1236 if (!silent) {
1237 gclog_or_tty->print("remset ");
1238 }
1239 rem_set()->verify();
1240 if (!silent) {
1241 gclog_or_tty->print("ref_proc ");
1242 }
1243 ReferenceProcessor::verify();
1244 }
1246 void GenCollectedHeap::print() const { print_on(tty); }
1247 void GenCollectedHeap::print_on(outputStream* st) const {
1248 for (int i = 0; i < _n_gens; i++) {
1249 _gens[i]->print_on(st);
1250 }
1251 perm_gen()->print_on(st);
1252 }
1254 void GenCollectedHeap::gc_threads_do(ThreadClosure* tc) const {
1255 if (workers() != NULL) {
1256 workers()->threads_do(tc);
1257 }
1258 #ifndef SERIALGC
1259 if (UseConcMarkSweepGC) {
1260 ConcurrentMarkSweepThread::threads_do(tc);
1261 }
1262 #endif // SERIALGC
1263 }
1265 void GenCollectedHeap::print_gc_threads_on(outputStream* st) const {
1266 #ifndef SERIALGC
1267 if (UseParNewGC) {
1268 workers()->print_worker_threads_on(st);
1269 }
1270 if (UseConcMarkSweepGC) {
1271 ConcurrentMarkSweepThread::print_all_on(st);
1272 }
1273 #endif // SERIALGC
1274 }
1276 void GenCollectedHeap::print_tracing_info() const {
1277 if (TraceGen0Time) {
1278 get_gen(0)->print_summary_info();
1279 }
1280 if (TraceGen1Time) {
1281 get_gen(1)->print_summary_info();
1282 }
1283 }
1285 void GenCollectedHeap::print_heap_change(size_t prev_used) const {
1286 if (PrintGCDetails && Verbose) {
1287 gclog_or_tty->print(" " SIZE_FORMAT
1288 "->" SIZE_FORMAT
1289 "(" SIZE_FORMAT ")",
1290 prev_used, used(), capacity());
1291 } else {
1292 gclog_or_tty->print(" " SIZE_FORMAT "K"
1293 "->" SIZE_FORMAT "K"
1294 "(" SIZE_FORMAT "K)",
1295 prev_used / K, used() / K, capacity() / K);
1296 }
1297 }
1299 //New method to print perm gen info with PrintGCDetails flag
1300 void GenCollectedHeap::print_perm_heap_change(size_t perm_prev_used) const {
1301 gclog_or_tty->print(", [%s :", perm_gen()->short_name());
1302 perm_gen()->print_heap_change(perm_prev_used);
1303 gclog_or_tty->print("]");
1304 }
1306 class GenGCPrologueClosure: public GenCollectedHeap::GenClosure {
1307 private:
1308 bool _full;
1309 public:
1310 void do_generation(Generation* gen) {
1311 gen->gc_prologue(_full);
1312 }
1313 GenGCPrologueClosure(bool full) : _full(full) {};
1314 };
1316 void GenCollectedHeap::gc_prologue(bool full) {
1317 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
1319 always_do_update_barrier = false;
1320 // Fill TLAB's and such
1321 CollectedHeap::accumulate_statistics_all_tlabs();
1322 ensure_parsability(true); // retire TLABs
1324 // Call allocation profiler
1325 AllocationProfiler::iterate_since_last_gc();
1326 // Walk generations
1327 GenGCPrologueClosure blk(full);
1328 generation_iterate(&blk, false); // not old-to-young.
1329 perm_gen()->gc_prologue(full);
1330 };
1332 class GenGCEpilogueClosure: public GenCollectedHeap::GenClosure {
1333 private:
1334 bool _full;
1335 public:
1336 void do_generation(Generation* gen) {
1337 gen->gc_epilogue(_full);
1338 }
1339 GenGCEpilogueClosure(bool full) : _full(full) {};
1340 };
1342 void GenCollectedHeap::gc_epilogue(bool full) {
1343 // Remember if a partial collection of the heap failed, and
1344 // we did a complete collection.
1345 if (full && incremental_collection_will_fail()) {
1346 set_last_incremental_collection_failed();
1347 } else {
1348 clear_last_incremental_collection_failed();
1349 }
1350 // Clear the flag, if set; the generation gc_epilogues will set the
1351 // flag again if the condition persists despite the collection.
1352 clear_incremental_collection_will_fail();
1354 #ifdef COMPILER2
1355 assert(DerivedPointerTable::is_empty(), "derived pointer present");
1356 size_t actual_gap = pointer_delta((HeapWord*) (max_uintx-3), *(end_addr()));
1357 guarantee(actual_gap > (size_t)FastAllocateSizeLimit, "inline allocation wraps");
1358 #endif /* COMPILER2 */
1360 resize_all_tlabs();
1362 GenGCEpilogueClosure blk(full);
1363 generation_iterate(&blk, false); // not old-to-young.
1364 perm_gen()->gc_epilogue(full);
1366 always_do_update_barrier = UseConcMarkSweepGC;
1367 };
1369 #ifndef PRODUCT
1370 class GenGCSaveTopsBeforeGCClosure: public GenCollectedHeap::GenClosure {
1371 private:
1372 public:
1373 void do_generation(Generation* gen) {
1374 gen->record_spaces_top();
1375 }
1376 };
1378 void GenCollectedHeap::record_gen_tops_before_GC() {
1379 if (ZapUnusedHeapArea) {
1380 GenGCSaveTopsBeforeGCClosure blk;
1381 generation_iterate(&blk, false); // not old-to-young.
1382 perm_gen()->record_spaces_top();
1383 }
1384 }
1385 #endif // not PRODUCT
1387 class GenEnsureParsabilityClosure: public GenCollectedHeap::GenClosure {
1388 public:
1389 void do_generation(Generation* gen) {
1390 gen->ensure_parsability();
1391 }
1392 };
1394 void GenCollectedHeap::ensure_parsability(bool retire_tlabs) {
1395 CollectedHeap::ensure_parsability(retire_tlabs);
1396 GenEnsureParsabilityClosure ep_cl;
1397 generation_iterate(&ep_cl, false);
1398 perm_gen()->ensure_parsability();
1399 }
1401 oop GenCollectedHeap::handle_failed_promotion(Generation* gen,
1402 oop obj,
1403 size_t obj_size) {
1404 assert(obj_size == (size_t)obj->size(), "bad obj_size passed in");
1405 HeapWord* result = NULL;
1407 // First give each higher generation a chance to allocate the promoted object.
1408 Generation* allocator = next_gen(gen);
1409 if (allocator != NULL) {
1410 do {
1411 result = allocator->allocate(obj_size, false);
1412 } while (result == NULL && (allocator = next_gen(allocator)) != NULL);
1413 }
1415 if (result == NULL) {
1416 // Then give gen and higher generations a chance to expand and allocate the
1417 // object.
1418 do {
1419 result = gen->expand_and_allocate(obj_size, false);
1420 } while (result == NULL && (gen = next_gen(gen)) != NULL);
1421 }
1423 if (result != NULL) {
1424 Copy::aligned_disjoint_words((HeapWord*)obj, result, obj_size);
1425 }
1426 return oop(result);
1427 }
1429 class GenTimeOfLastGCClosure: public GenCollectedHeap::GenClosure {
1430 jlong _time; // in ms
1431 jlong _now; // in ms
1433 public:
1434 GenTimeOfLastGCClosure(jlong now) : _time(now), _now(now) { }
1436 jlong time() { return _time; }
1438 void do_generation(Generation* gen) {
1439 _time = MIN2(_time, gen->time_of_last_gc(_now));
1440 }
1441 };
1443 jlong GenCollectedHeap::millis_since_last_gc() {
1444 jlong now = os::javaTimeMillis();
1445 GenTimeOfLastGCClosure tolgc_cl(now);
1446 // iterate over generations getting the oldest
1447 // time that a generation was collected
1448 generation_iterate(&tolgc_cl, false);
1449 tolgc_cl.do_generation(perm_gen());
1450 // XXX Despite the assert above, since javaTimeMillis()
1451 // doesnot guarantee monotonically increasing return
1452 // values (note, i didn't say "strictly monotonic"),
1453 // we need to guard against getting back a time
1454 // later than now. This should be fixed by basing
1455 // on someting like gethrtime() which guarantees
1456 // monotonicity. Note that cond_wait() is susceptible
1457 // to a similar problem, because its interface is
1458 // based on absolute time in the form of the
1459 // system time's notion of UCT. See also 4506635
1460 // for yet another problem of similar nature. XXX
1461 jlong retVal = now - tolgc_cl.time();
1462 if (retVal < 0) {
1463 NOT_PRODUCT(warning("time warp: %d", retVal);)
1464 return 0;
1465 }
1466 return retVal;
1467 }