Thu, 21 Aug 2014 16:44:41 +0200
8055098: WB API should be extended to provide information about size and age of object.
Summary: Extend the WhiteBox API to provide information about the size and age of objects. Further add a mechanism to trigger a young GC.
Reviewed-by: tschatzl, sjohanss
Contributed-by: Leonid Mesnik <leonid.mesnik@oracle.com>
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 */
25 #if !defined(__clang_major__) && defined(__GNUC__)
26 #define ATTRIBUTE_PRINTF(x,y) // FIXME, formats are a mess.
27 #endif
29 #include "precompiled.hpp"
30 #include "code/codeCache.hpp"
31 #include "code/icBuffer.hpp"
32 #include "gc_implementation/g1/bufferingOopClosure.hpp"
33 #include "gc_implementation/g1/concurrentG1Refine.hpp"
34 #include "gc_implementation/g1/concurrentG1RefineThread.hpp"
35 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
36 #include "gc_implementation/g1/g1AllocRegion.inline.hpp"
37 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
38 #include "gc_implementation/g1/g1CollectorPolicy.hpp"
39 #include "gc_implementation/g1/g1ErgoVerbose.hpp"
40 #include "gc_implementation/g1/g1EvacFailure.hpp"
41 #include "gc_implementation/g1/g1GCPhaseTimes.hpp"
42 #include "gc_implementation/g1/g1Log.hpp"
43 #include "gc_implementation/g1/g1MarkSweep.hpp"
44 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
45 #include "gc_implementation/g1/g1ParScanThreadState.inline.hpp"
46 #include "gc_implementation/g1/g1RegionToSpaceMapper.hpp"
47 #include "gc_implementation/g1/g1RemSet.inline.hpp"
48 #include "gc_implementation/g1/g1StringDedup.hpp"
49 #include "gc_implementation/g1/g1YCTypes.hpp"
50 #include "gc_implementation/g1/heapRegion.inline.hpp"
51 #include "gc_implementation/g1/heapRegionRemSet.hpp"
52 #include "gc_implementation/g1/heapRegionSet.inline.hpp"
53 #include "gc_implementation/g1/vm_operations_g1.hpp"
54 #include "gc_implementation/shared/gcHeapSummary.hpp"
55 #include "gc_implementation/shared/gcTimer.hpp"
56 #include "gc_implementation/shared/gcTrace.hpp"
57 #include "gc_implementation/shared/gcTraceTime.hpp"
58 #include "gc_implementation/shared/isGCActiveMark.hpp"
59 #include "memory/allocation.hpp"
60 #include "memory/gcLocker.inline.hpp"
61 #include "memory/generationSpec.hpp"
62 #include "memory/iterator.hpp"
63 #include "memory/referenceProcessor.hpp"
64 #include "oops/oop.inline.hpp"
65 #include "oops/oop.pcgc.inline.hpp"
66 #include "runtime/orderAccess.inline.hpp"
67 #include "runtime/vmThread.hpp"
69 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
71 // turn it on so that the contents of the young list (scan-only /
72 // to-be-collected) are printed at "strategic" points before / during
73 // / after the collection --- this is useful for debugging
74 #define YOUNG_LIST_VERBOSE 0
75 // CURRENT STATUS
76 // This file is under construction. Search for "FIXME".
78 // INVARIANTS/NOTES
79 //
80 // All allocation activity covered by the G1CollectedHeap interface is
81 // serialized by acquiring the HeapLock. This happens in mem_allocate
82 // and allocate_new_tlab, which are the "entry" points to the
83 // allocation code from the rest of the JVM. (Note that this does not
84 // apply to TLAB allocation, which is not part of this interface: it
85 // is done by clients of this interface.)
87 // Notes on implementation of parallelism in different tasks.
88 //
89 // G1ParVerifyTask uses heap_region_par_iterate_chunked() for parallelism.
90 // The number of GC workers is passed to heap_region_par_iterate_chunked().
91 // It does use run_task() which sets _n_workers in the task.
92 // G1ParTask executes g1_process_roots() ->
93 // SharedHeap::process_roots() which calls eventually to
94 // CardTableModRefBS::par_non_clean_card_iterate_work() which uses
95 // SequentialSubTasksDone. SharedHeap::process_roots() also
96 // directly uses SubTasksDone (_process_strong_tasks field in SharedHeap).
97 //
99 // Local to this file.
101 class RefineCardTableEntryClosure: public CardTableEntryClosure {
102 bool _concurrent;
103 public:
104 RefineCardTableEntryClosure() : _concurrent(true) { }
106 bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
107 bool oops_into_cset = G1CollectedHeap::heap()->g1_rem_set()->refine_card(card_ptr, worker_i, false);
108 // This path is executed by the concurrent refine or mutator threads,
109 // concurrently, and so we do not care if card_ptr contains references
110 // that point into the collection set.
111 assert(!oops_into_cset, "should be");
113 if (_concurrent && SuspendibleThreadSet::should_yield()) {
114 // Caller will actually yield.
115 return false;
116 }
117 // Otherwise, we finished successfully; return true.
118 return true;
119 }
121 void set_concurrent(bool b) { _concurrent = b; }
122 };
125 class ClearLoggedCardTableEntryClosure: public CardTableEntryClosure {
126 size_t _num_processed;
127 CardTableModRefBS* _ctbs;
128 int _histo[256];
130 public:
131 ClearLoggedCardTableEntryClosure() :
132 _num_processed(0), _ctbs(G1CollectedHeap::heap()->g1_barrier_set())
133 {
134 for (int i = 0; i < 256; i++) _histo[i] = 0;
135 }
137 bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
138 unsigned char* ujb = (unsigned char*)card_ptr;
139 int ind = (int)(*ujb);
140 _histo[ind]++;
142 *card_ptr = (jbyte)CardTableModRefBS::clean_card_val();
143 _num_processed++;
145 return true;
146 }
148 size_t num_processed() { return _num_processed; }
150 void print_histo() {
151 gclog_or_tty->print_cr("Card table value histogram:");
152 for (int i = 0; i < 256; i++) {
153 if (_histo[i] != 0) {
154 gclog_or_tty->print_cr(" %d: %d", i, _histo[i]);
155 }
156 }
157 }
158 };
160 class RedirtyLoggedCardTableEntryClosure : public CardTableEntryClosure {
161 private:
162 size_t _num_processed;
164 public:
165 RedirtyLoggedCardTableEntryClosure() : CardTableEntryClosure(), _num_processed(0) { }
167 bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
168 *card_ptr = CardTableModRefBS::dirty_card_val();
169 _num_processed++;
170 return true;
171 }
173 size_t num_processed() const { return _num_processed; }
174 };
176 YoungList::YoungList(G1CollectedHeap* g1h) :
177 _g1h(g1h), _head(NULL), _length(0), _last_sampled_rs_lengths(0),
178 _survivor_head(NULL), _survivor_tail(NULL), _survivor_length(0) {
179 guarantee(check_list_empty(false), "just making sure...");
180 }
182 void YoungList::push_region(HeapRegion *hr) {
183 assert(!hr->is_young(), "should not already be young");
184 assert(hr->get_next_young_region() == NULL, "cause it should!");
186 hr->set_next_young_region(_head);
187 _head = hr;
189 _g1h->g1_policy()->set_region_eden(hr, (int) _length);
190 ++_length;
191 }
193 void YoungList::add_survivor_region(HeapRegion* hr) {
194 assert(hr->is_survivor(), "should be flagged as survivor region");
195 assert(hr->get_next_young_region() == NULL, "cause it should!");
197 hr->set_next_young_region(_survivor_head);
198 if (_survivor_head == NULL) {
199 _survivor_tail = hr;
200 }
201 _survivor_head = hr;
202 ++_survivor_length;
203 }
205 void YoungList::empty_list(HeapRegion* list) {
206 while (list != NULL) {
207 HeapRegion* next = list->get_next_young_region();
208 list->set_next_young_region(NULL);
209 list->uninstall_surv_rate_group();
210 list->set_not_young();
211 list = next;
212 }
213 }
215 void YoungList::empty_list() {
216 assert(check_list_well_formed(), "young list should be well formed");
218 empty_list(_head);
219 _head = NULL;
220 _length = 0;
222 empty_list(_survivor_head);
223 _survivor_head = NULL;
224 _survivor_tail = NULL;
225 _survivor_length = 0;
227 _last_sampled_rs_lengths = 0;
229 assert(check_list_empty(false), "just making sure...");
230 }
232 bool YoungList::check_list_well_formed() {
233 bool ret = true;
235 uint length = 0;
236 HeapRegion* curr = _head;
237 HeapRegion* last = NULL;
238 while (curr != NULL) {
239 if (!curr->is_young()) {
240 gclog_or_tty->print_cr("### YOUNG REGION "PTR_FORMAT"-"PTR_FORMAT" "
241 "incorrectly tagged (y: %d, surv: %d)",
242 curr->bottom(), curr->end(),
243 curr->is_young(), curr->is_survivor());
244 ret = false;
245 }
246 ++length;
247 last = curr;
248 curr = curr->get_next_young_region();
249 }
250 ret = ret && (length == _length);
252 if (!ret) {
253 gclog_or_tty->print_cr("### YOUNG LIST seems not well formed!");
254 gclog_or_tty->print_cr("### list has %u entries, _length is %u",
255 length, _length);
256 }
258 return ret;
259 }
261 bool YoungList::check_list_empty(bool check_sample) {
262 bool ret = true;
264 if (_length != 0) {
265 gclog_or_tty->print_cr("### YOUNG LIST should have 0 length, not %u",
266 _length);
267 ret = false;
268 }
269 if (check_sample && _last_sampled_rs_lengths != 0) {
270 gclog_or_tty->print_cr("### YOUNG LIST has non-zero last sampled RS lengths");
271 ret = false;
272 }
273 if (_head != NULL) {
274 gclog_or_tty->print_cr("### YOUNG LIST does not have a NULL head");
275 ret = false;
276 }
277 if (!ret) {
278 gclog_or_tty->print_cr("### YOUNG LIST does not seem empty");
279 }
281 return ret;
282 }
284 void
285 YoungList::rs_length_sampling_init() {
286 _sampled_rs_lengths = 0;
287 _curr = _head;
288 }
290 bool
291 YoungList::rs_length_sampling_more() {
292 return _curr != NULL;
293 }
295 void
296 YoungList::rs_length_sampling_next() {
297 assert( _curr != NULL, "invariant" );
298 size_t rs_length = _curr->rem_set()->occupied();
300 _sampled_rs_lengths += rs_length;
302 // The current region may not yet have been added to the
303 // incremental collection set (it gets added when it is
304 // retired as the current allocation region).
305 if (_curr->in_collection_set()) {
306 // Update the collection set policy information for this region
307 _g1h->g1_policy()->update_incremental_cset_info(_curr, rs_length);
308 }
310 _curr = _curr->get_next_young_region();
311 if (_curr == NULL) {
312 _last_sampled_rs_lengths = _sampled_rs_lengths;
313 // gclog_or_tty->print_cr("last sampled RS lengths = %d", _last_sampled_rs_lengths);
314 }
315 }
317 void
318 YoungList::reset_auxilary_lists() {
319 guarantee( is_empty(), "young list should be empty" );
320 assert(check_list_well_formed(), "young list should be well formed");
322 // Add survivor regions to SurvRateGroup.
323 _g1h->g1_policy()->note_start_adding_survivor_regions();
324 _g1h->g1_policy()->finished_recalculating_age_indexes(true /* is_survivors */);
326 int young_index_in_cset = 0;
327 for (HeapRegion* curr = _survivor_head;
328 curr != NULL;
329 curr = curr->get_next_young_region()) {
330 _g1h->g1_policy()->set_region_survivor(curr, young_index_in_cset);
332 // The region is a non-empty survivor so let's add it to
333 // the incremental collection set for the next evacuation
334 // pause.
335 _g1h->g1_policy()->add_region_to_incremental_cset_rhs(curr);
336 young_index_in_cset += 1;
337 }
338 assert((uint) young_index_in_cset == _survivor_length, "post-condition");
339 _g1h->g1_policy()->note_stop_adding_survivor_regions();
341 _head = _survivor_head;
342 _length = _survivor_length;
343 if (_survivor_head != NULL) {
344 assert(_survivor_tail != NULL, "cause it shouldn't be");
345 assert(_survivor_length > 0, "invariant");
346 _survivor_tail->set_next_young_region(NULL);
347 }
349 // Don't clear the survivor list handles until the start of
350 // the next evacuation pause - we need it in order to re-tag
351 // the survivor regions from this evacuation pause as 'young'
352 // at the start of the next.
354 _g1h->g1_policy()->finished_recalculating_age_indexes(false /* is_survivors */);
356 assert(check_list_well_formed(), "young list should be well formed");
357 }
359 void YoungList::print() {
360 HeapRegion* lists[] = {_head, _survivor_head};
361 const char* names[] = {"YOUNG", "SURVIVOR"};
363 for (unsigned int list = 0; list < ARRAY_SIZE(lists); ++list) {
364 gclog_or_tty->print_cr("%s LIST CONTENTS", names[list]);
365 HeapRegion *curr = lists[list];
366 if (curr == NULL)
367 gclog_or_tty->print_cr(" empty");
368 while (curr != NULL) {
369 gclog_or_tty->print_cr(" "HR_FORMAT", P: "PTR_FORMAT "N: "PTR_FORMAT", age: %4d",
370 HR_FORMAT_PARAMS(curr),
371 curr->prev_top_at_mark_start(),
372 curr->next_top_at_mark_start(),
373 curr->age_in_surv_rate_group_cond());
374 curr = curr->get_next_young_region();
375 }
376 }
378 gclog_or_tty->cr();
379 }
381 void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) {
382 OtherRegionsTable::invalidate(start_idx, num_regions);
383 }
385 void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions) {
386 reset_from_card_cache(start_idx, num_regions);
387 }
389 void G1CollectedHeap::push_dirty_cards_region(HeapRegion* hr)
390 {
391 // Claim the right to put the region on the dirty cards region list
392 // by installing a self pointer.
393 HeapRegion* next = hr->get_next_dirty_cards_region();
394 if (next == NULL) {
395 HeapRegion* res = (HeapRegion*)
396 Atomic::cmpxchg_ptr(hr, hr->next_dirty_cards_region_addr(),
397 NULL);
398 if (res == NULL) {
399 HeapRegion* head;
400 do {
401 // Put the region to the dirty cards region list.
402 head = _dirty_cards_region_list;
403 next = (HeapRegion*)
404 Atomic::cmpxchg_ptr(hr, &_dirty_cards_region_list, head);
405 if (next == head) {
406 assert(hr->get_next_dirty_cards_region() == hr,
407 "hr->get_next_dirty_cards_region() != hr");
408 if (next == NULL) {
409 // The last region in the list points to itself.
410 hr->set_next_dirty_cards_region(hr);
411 } else {
412 hr->set_next_dirty_cards_region(next);
413 }
414 }
415 } while (next != head);
416 }
417 }
418 }
420 HeapRegion* G1CollectedHeap::pop_dirty_cards_region()
421 {
422 HeapRegion* head;
423 HeapRegion* hr;
424 do {
425 head = _dirty_cards_region_list;
426 if (head == NULL) {
427 return NULL;
428 }
429 HeapRegion* new_head = head->get_next_dirty_cards_region();
430 if (head == new_head) {
431 // The last region.
432 new_head = NULL;
433 }
434 hr = (HeapRegion*)Atomic::cmpxchg_ptr(new_head, &_dirty_cards_region_list,
435 head);
436 } while (hr != head);
437 assert(hr != NULL, "invariant");
438 hr->set_next_dirty_cards_region(NULL);
439 return hr;
440 }
442 #ifdef ASSERT
443 // A region is added to the collection set as it is retired
444 // so an address p can point to a region which will be in the
445 // collection set but has not yet been retired. This method
446 // therefore is only accurate during a GC pause after all
447 // regions have been retired. It is used for debugging
448 // to check if an nmethod has references to objects that can
449 // be move during a partial collection. Though it can be
450 // inaccurate, it is sufficient for G1 because the conservative
451 // implementation of is_scavengable() for G1 will indicate that
452 // all nmethods must be scanned during a partial collection.
453 bool G1CollectedHeap::is_in_partial_collection(const void* p) {
454 if (p == NULL) {
455 return false;
456 }
457 return heap_region_containing(p)->in_collection_set();
458 }
459 #endif
461 // Returns true if the reference points to an object that
462 // can move in an incremental collection.
463 bool G1CollectedHeap::is_scavengable(const void* p) {
464 HeapRegion* hr = heap_region_containing(p);
465 return !hr->isHumongous();
466 }
468 void G1CollectedHeap::check_ct_logs_at_safepoint() {
469 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
470 CardTableModRefBS* ct_bs = g1_barrier_set();
472 // Count the dirty cards at the start.
473 CountNonCleanMemRegionClosure count1(this);
474 ct_bs->mod_card_iterate(&count1);
475 int orig_count = count1.n();
477 // First clear the logged cards.
478 ClearLoggedCardTableEntryClosure clear;
479 dcqs.apply_closure_to_all_completed_buffers(&clear);
480 dcqs.iterate_closure_all_threads(&clear, false);
481 clear.print_histo();
483 // Now ensure that there's no dirty cards.
484 CountNonCleanMemRegionClosure count2(this);
485 ct_bs->mod_card_iterate(&count2);
486 if (count2.n() != 0) {
487 gclog_or_tty->print_cr("Card table has %d entries; %d originally",
488 count2.n(), orig_count);
489 }
490 guarantee(count2.n() == 0, "Card table should be clean.");
492 RedirtyLoggedCardTableEntryClosure redirty;
493 dcqs.apply_closure_to_all_completed_buffers(&redirty);
494 dcqs.iterate_closure_all_threads(&redirty, false);
495 gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",
496 clear.num_processed(), orig_count);
497 guarantee(redirty.num_processed() == clear.num_processed(),
498 err_msg("Redirtied "SIZE_FORMAT" cards, bug cleared "SIZE_FORMAT,
499 redirty.num_processed(), clear.num_processed()));
501 CountNonCleanMemRegionClosure count3(this);
502 ct_bs->mod_card_iterate(&count3);
503 if (count3.n() != orig_count) {
504 gclog_or_tty->print_cr("Should have restored them all: orig = %d, final = %d.",
505 orig_count, count3.n());
506 guarantee(count3.n() >= orig_count, "Should have restored them all.");
507 }
508 }
510 // Private class members.
512 G1CollectedHeap* G1CollectedHeap::_g1h;
514 // Private methods.
516 HeapRegion*
517 G1CollectedHeap::new_region_try_secondary_free_list(bool is_old) {
518 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
519 while (!_secondary_free_list.is_empty() || free_regions_coming()) {
520 if (!_secondary_free_list.is_empty()) {
521 if (G1ConcRegionFreeingVerbose) {
522 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
523 "secondary_free_list has %u entries",
524 _secondary_free_list.length());
525 }
526 // It looks as if there are free regions available on the
527 // secondary_free_list. Let's move them to the free_list and try
528 // again to allocate from it.
529 append_secondary_free_list();
531 assert(_hrs.num_free_regions() > 0, "if the secondary_free_list was not "
532 "empty we should have moved at least one entry to the free_list");
533 HeapRegion* res = _hrs.allocate_free_region(is_old);
534 if (G1ConcRegionFreeingVerbose) {
535 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
536 "allocated "HR_FORMAT" from secondary_free_list",
537 HR_FORMAT_PARAMS(res));
538 }
539 return res;
540 }
542 // Wait here until we get notified either when (a) there are no
543 // more free regions coming or (b) some regions have been moved on
544 // the secondary_free_list.
545 SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
546 }
548 if (G1ConcRegionFreeingVerbose) {
549 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
550 "could not allocate from secondary_free_list");
551 }
552 return NULL;
553 }
555 HeapRegion* G1CollectedHeap::new_region(size_t word_size, bool is_old, bool do_expand) {
556 assert(!isHumongous(word_size) || word_size <= HeapRegion::GrainWords,
557 "the only time we use this to allocate a humongous region is "
558 "when we are allocating a single humongous region");
560 HeapRegion* res;
561 if (G1StressConcRegionFreeing) {
562 if (!_secondary_free_list.is_empty()) {
563 if (G1ConcRegionFreeingVerbose) {
564 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
565 "forced to look at the secondary_free_list");
566 }
567 res = new_region_try_secondary_free_list(is_old);
568 if (res != NULL) {
569 return res;
570 }
571 }
572 }
574 res = _hrs.allocate_free_region(is_old);
576 if (res == NULL) {
577 if (G1ConcRegionFreeingVerbose) {
578 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
579 "res == NULL, trying the secondary_free_list");
580 }
581 res = new_region_try_secondary_free_list(is_old);
582 }
583 if (res == NULL && do_expand && _expand_heap_after_alloc_failure) {
584 // Currently, only attempts to allocate GC alloc regions set
585 // do_expand to true. So, we should only reach here during a
586 // safepoint. If this assumption changes we might have to
587 // reconsider the use of _expand_heap_after_alloc_failure.
588 assert(SafepointSynchronize::is_at_safepoint(), "invariant");
590 ergo_verbose1(ErgoHeapSizing,
591 "attempt heap expansion",
592 ergo_format_reason("region allocation request failed")
593 ergo_format_byte("allocation request"),
594 word_size * HeapWordSize);
595 if (expand(word_size * HeapWordSize)) {
596 // Given that expand() succeeded in expanding the heap, and we
597 // always expand the heap by an amount aligned to the heap
598 // region size, the free list should in theory not be empty.
599 // In either case allocate_free_region() will check for NULL.
600 res = _hrs.allocate_free_region(is_old);
601 } else {
602 _expand_heap_after_alloc_failure = false;
603 }
604 }
605 return res;
606 }
608 HeapWord*
609 G1CollectedHeap::humongous_obj_allocate_initialize_regions(uint first,
610 uint num_regions,
611 size_t word_size) {
612 assert(first != G1_NO_HRS_INDEX, "pre-condition");
613 assert(isHumongous(word_size), "word_size should be humongous");
614 assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
616 // Index of last region in the series + 1.
617 uint last = first + num_regions;
619 // We need to initialize the region(s) we just discovered. This is
620 // a bit tricky given that it can happen concurrently with
621 // refinement threads refining cards on these regions and
622 // potentially wanting to refine the BOT as they are scanning
623 // those cards (this can happen shortly after a cleanup; see CR
624 // 6991377). So we have to set up the region(s) carefully and in
625 // a specific order.
627 // The word size sum of all the regions we will allocate.
628 size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;
629 assert(word_size <= word_size_sum, "sanity");
631 // This will be the "starts humongous" region.
632 HeapRegion* first_hr = region_at(first);
633 // The header of the new object will be placed at the bottom of
634 // the first region.
635 HeapWord* new_obj = first_hr->bottom();
636 // This will be the new end of the first region in the series that
637 // should also match the end of the last region in the series.
638 HeapWord* new_end = new_obj + word_size_sum;
639 // This will be the new top of the first region that will reflect
640 // this allocation.
641 HeapWord* new_top = new_obj + word_size;
643 // First, we need to zero the header of the space that we will be
644 // allocating. When we update top further down, some refinement
645 // threads might try to scan the region. By zeroing the header we
646 // ensure that any thread that will try to scan the region will
647 // come across the zero klass word and bail out.
648 //
649 // NOTE: It would not have been correct to have used
650 // CollectedHeap::fill_with_object() and make the space look like
651 // an int array. The thread that is doing the allocation will
652 // later update the object header to a potentially different array
653 // type and, for a very short period of time, the klass and length
654 // fields will be inconsistent. This could cause a refinement
655 // thread to calculate the object size incorrectly.
656 Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
658 // We will set up the first region as "starts humongous". This
659 // will also update the BOT covering all the regions to reflect
660 // that there is a single object that starts at the bottom of the
661 // first region.
662 first_hr->set_startsHumongous(new_top, new_end);
664 // Then, if there are any, we will set up the "continues
665 // humongous" regions.
666 HeapRegion* hr = NULL;
667 for (uint i = first + 1; i < last; ++i) {
668 hr = region_at(i);
669 hr->set_continuesHumongous(first_hr);
670 }
671 // If we have "continues humongous" regions (hr != NULL), then the
672 // end of the last one should match new_end.
673 assert(hr == NULL || hr->end() == new_end, "sanity");
675 // Up to this point no concurrent thread would have been able to
676 // do any scanning on any region in this series. All the top
677 // fields still point to bottom, so the intersection between
678 // [bottom,top] and [card_start,card_end] will be empty. Before we
679 // update the top fields, we'll do a storestore to make sure that
680 // no thread sees the update to top before the zeroing of the
681 // object header and the BOT initialization.
682 OrderAccess::storestore();
684 // Now that the BOT and the object header have been initialized,
685 // we can update top of the "starts humongous" region.
686 assert(first_hr->bottom() < new_top && new_top <= first_hr->end(),
687 "new_top should be in this region");
688 first_hr->set_top(new_top);
689 if (_hr_printer.is_active()) {
690 HeapWord* bottom = first_hr->bottom();
691 HeapWord* end = first_hr->orig_end();
692 if ((first + 1) == last) {
693 // the series has a single humongous region
694 _hr_printer.alloc(G1HRPrinter::SingleHumongous, first_hr, new_top);
695 } else {
696 // the series has more than one humongous regions
697 _hr_printer.alloc(G1HRPrinter::StartsHumongous, first_hr, end);
698 }
699 }
701 // Now, we will update the top fields of the "continues humongous"
702 // regions. The reason we need to do this is that, otherwise,
703 // these regions would look empty and this will confuse parts of
704 // G1. For example, the code that looks for a consecutive number
705 // of empty regions will consider them empty and try to
706 // re-allocate them. We can extend is_empty() to also include
707 // !continuesHumongous(), but it is easier to just update the top
708 // fields here. The way we set top for all regions (i.e., top ==
709 // end for all regions but the last one, top == new_top for the
710 // last one) is actually used when we will free up the humongous
711 // region in free_humongous_region().
712 hr = NULL;
713 for (uint i = first + 1; i < last; ++i) {
714 hr = region_at(i);
715 if ((i + 1) == last) {
716 // last continues humongous region
717 assert(hr->bottom() < new_top && new_top <= hr->end(),
718 "new_top should fall on this region");
719 hr->set_top(new_top);
720 _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, new_top);
721 } else {
722 // not last one
723 assert(new_top > hr->end(), "new_top should be above this region");
724 hr->set_top(hr->end());
725 _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, hr->end());
726 }
727 }
728 // If we have continues humongous regions (hr != NULL), then the
729 // end of the last one should match new_end and its top should
730 // match new_top.
731 assert(hr == NULL ||
732 (hr->end() == new_end && hr->top() == new_top), "sanity");
733 check_bitmaps("Humongous Region Allocation", first_hr);
735 assert(first_hr->used() == word_size * HeapWordSize, "invariant");
736 _summary_bytes_used += first_hr->used();
737 _humongous_set.add(first_hr);
739 return new_obj;
740 }
742 // If could fit into free regions w/o expansion, try.
743 // Otherwise, if can expand, do so.
744 // Otherwise, if using ex regions might help, try with ex given back.
745 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {
746 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
748 verify_region_sets_optional();
750 uint first = G1_NO_HRS_INDEX;
751 uint obj_regions = (uint)(align_size_up_(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords);
753 if (obj_regions == 1) {
754 // Only one region to allocate, try to use a fast path by directly allocating
755 // from the free lists. Do not try to expand here, we will potentially do that
756 // later.
757 HeapRegion* hr = new_region(word_size, true /* is_old */, false /* do_expand */);
758 if (hr != NULL) {
759 first = hr->hrs_index();
760 }
761 } else {
762 // We can't allocate humongous regions spanning more than one region while
763 // cleanupComplete() is running, since some of the regions we find to be
764 // empty might not yet be added to the free list. It is not straightforward
765 // to know in which list they are on so that we can remove them. We only
766 // need to do this if we need to allocate more than one region to satisfy the
767 // current humongous allocation request. If we are only allocating one region
768 // we use the one-region region allocation code (see above), that already
769 // potentially waits for regions from the secondary free list.
770 wait_while_free_regions_coming();
771 append_secondary_free_list_if_not_empty_with_lock();
773 // Policy: Try only empty regions (i.e. already committed first). Maybe we
774 // are lucky enough to find some.
775 first = _hrs.find_contiguous_only_empty(obj_regions);
776 if (first != G1_NO_HRS_INDEX) {
777 _hrs.allocate_free_regions_starting_at(first, obj_regions);
778 }
779 }
781 if (first == G1_NO_HRS_INDEX) {
782 // Policy: We could not find enough regions for the humongous object in the
783 // free list. Look through the heap to find a mix of free and uncommitted regions.
784 // If so, try expansion.
785 first = _hrs.find_contiguous_empty_or_unavailable(obj_regions);
786 if (first != G1_NO_HRS_INDEX) {
787 // We found something. Make sure these regions are committed, i.e. expand
788 // the heap. Alternatively we could do a defragmentation GC.
789 ergo_verbose1(ErgoHeapSizing,
790 "attempt heap expansion",
791 ergo_format_reason("humongous allocation request failed")
792 ergo_format_byte("allocation request"),
793 word_size * HeapWordSize);
795 _hrs.expand_at(first, obj_regions);
796 g1_policy()->record_new_heap_size(num_regions());
798 #ifdef ASSERT
799 for (uint i = first; i < first + obj_regions; ++i) {
800 HeapRegion* hr = region_at(i);
801 assert(hr->is_empty(), "sanity");
802 assert(is_on_master_free_list(hr), "sanity");
803 }
804 #endif
805 _hrs.allocate_free_regions_starting_at(first, obj_regions);
806 } else {
807 // Policy: Potentially trigger a defragmentation GC.
808 }
809 }
811 HeapWord* result = NULL;
812 if (first != G1_NO_HRS_INDEX) {
813 result = humongous_obj_allocate_initialize_regions(first, obj_regions, word_size);
814 assert(result != NULL, "it should always return a valid result");
816 // A successful humongous object allocation changes the used space
817 // information of the old generation so we need to recalculate the
818 // sizes and update the jstat counters here.
819 g1mm()->update_sizes();
820 }
822 verify_region_sets_optional();
824 return result;
825 }
827 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t word_size) {
828 assert_heap_not_locked_and_not_at_safepoint();
829 assert(!isHumongous(word_size), "we do not allow humongous TLABs");
831 unsigned int dummy_gc_count_before;
832 int dummy_gclocker_retry_count = 0;
833 return attempt_allocation(word_size, &dummy_gc_count_before, &dummy_gclocker_retry_count);
834 }
836 HeapWord*
837 G1CollectedHeap::mem_allocate(size_t word_size,
838 bool* gc_overhead_limit_was_exceeded) {
839 assert_heap_not_locked_and_not_at_safepoint();
841 // Loop until the allocation is satisfied, or unsatisfied after GC.
842 for (int try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
843 unsigned int gc_count_before;
845 HeapWord* result = NULL;
846 if (!isHumongous(word_size)) {
847 result = attempt_allocation(word_size, &gc_count_before, &gclocker_retry_count);
848 } else {
849 result = attempt_allocation_humongous(word_size, &gc_count_before, &gclocker_retry_count);
850 }
851 if (result != NULL) {
852 return result;
853 }
855 // Create the garbage collection operation...
856 VM_G1CollectForAllocation op(gc_count_before, word_size);
857 // ...and get the VM thread to execute it.
858 VMThread::execute(&op);
860 if (op.prologue_succeeded() && op.pause_succeeded()) {
861 // If the operation was successful we'll return the result even
862 // if it is NULL. If the allocation attempt failed immediately
863 // after a Full GC, it's unlikely we'll be able to allocate now.
864 HeapWord* result = op.result();
865 if (result != NULL && !isHumongous(word_size)) {
866 // Allocations that take place on VM operations do not do any
867 // card dirtying and we have to do it here. We only have to do
868 // this for non-humongous allocations, though.
869 dirty_young_block(result, word_size);
870 }
871 return result;
872 } else {
873 if (gclocker_retry_count > GCLockerRetryAllocationCount) {
874 return NULL;
875 }
876 assert(op.result() == NULL,
877 "the result should be NULL if the VM op did not succeed");
878 }
880 // Give a warning if we seem to be looping forever.
881 if ((QueuedAllocationWarningCount > 0) &&
882 (try_count % QueuedAllocationWarningCount == 0)) {
883 warning("G1CollectedHeap::mem_allocate retries %d times", try_count);
884 }
885 }
887 ShouldNotReachHere();
888 return NULL;
889 }
891 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size,
892 unsigned int *gc_count_before_ret,
893 int* gclocker_retry_count_ret) {
894 // Make sure you read the note in attempt_allocation_humongous().
896 assert_heap_not_locked_and_not_at_safepoint();
897 assert(!isHumongous(word_size), "attempt_allocation_slow() should not "
898 "be called for humongous allocation requests");
900 // We should only get here after the first-level allocation attempt
901 // (attempt_allocation()) failed to allocate.
903 // We will loop until a) we manage to successfully perform the
904 // allocation or b) we successfully schedule a collection which
905 // fails to perform the allocation. b) is the only case when we'll
906 // return NULL.
907 HeapWord* result = NULL;
908 for (int try_count = 1; /* we'll return */; try_count += 1) {
909 bool should_try_gc;
910 unsigned int gc_count_before;
912 {
913 MutexLockerEx x(Heap_lock);
915 result = _mutator_alloc_region.attempt_allocation_locked(word_size,
916 false /* bot_updates */);
917 if (result != NULL) {
918 return result;
919 }
921 // If we reach here, attempt_allocation_locked() above failed to
922 // allocate a new region. So the mutator alloc region should be NULL.
923 assert(_mutator_alloc_region.get() == NULL, "only way to get here");
925 if (GC_locker::is_active_and_needs_gc()) {
926 if (g1_policy()->can_expand_young_list()) {
927 // No need for an ergo verbose message here,
928 // can_expand_young_list() does this when it returns true.
929 result = _mutator_alloc_region.attempt_allocation_force(word_size,
930 false /* bot_updates */);
931 if (result != NULL) {
932 return result;
933 }
934 }
935 should_try_gc = false;
936 } else {
937 // The GCLocker may not be active but the GCLocker initiated
938 // GC may not yet have been performed (GCLocker::needs_gc()
939 // returns true). In this case we do not try this GC and
940 // wait until the GCLocker initiated GC is performed, and
941 // then retry the allocation.
942 if (GC_locker::needs_gc()) {
943 should_try_gc = false;
944 } else {
945 // Read the GC count while still holding the Heap_lock.
946 gc_count_before = total_collections();
947 should_try_gc = true;
948 }
949 }
950 }
952 if (should_try_gc) {
953 bool succeeded;
954 result = do_collection_pause(word_size, gc_count_before, &succeeded,
955 GCCause::_g1_inc_collection_pause);
956 if (result != NULL) {
957 assert(succeeded, "only way to get back a non-NULL result");
958 return result;
959 }
961 if (succeeded) {
962 // If we get here we successfully scheduled a collection which
963 // failed to allocate. No point in trying to allocate
964 // further. We'll just return NULL.
965 MutexLockerEx x(Heap_lock);
966 *gc_count_before_ret = total_collections();
967 return NULL;
968 }
969 } else {
970 if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
971 MutexLockerEx x(Heap_lock);
972 *gc_count_before_ret = total_collections();
973 return NULL;
974 }
975 // The GCLocker is either active or the GCLocker initiated
976 // GC has not yet been performed. Stall until it is and
977 // then retry the allocation.
978 GC_locker::stall_until_clear();
979 (*gclocker_retry_count_ret) += 1;
980 }
982 // We can reach here if we were unsuccessful in scheduling a
983 // collection (because another thread beat us to it) or if we were
984 // stalled due to the GC locker. In either can we should retry the
985 // allocation attempt in case another thread successfully
986 // performed a collection and reclaimed enough space. We do the
987 // first attempt (without holding the Heap_lock) here and the
988 // follow-on attempt will be at the start of the next loop
989 // iteration (after taking the Heap_lock).
990 result = _mutator_alloc_region.attempt_allocation(word_size,
991 false /* bot_updates */);
992 if (result != NULL) {
993 return result;
994 }
996 // Give a warning if we seem to be looping forever.
997 if ((QueuedAllocationWarningCount > 0) &&
998 (try_count % QueuedAllocationWarningCount == 0)) {
999 warning("G1CollectedHeap::attempt_allocation_slow() "
1000 "retries %d times", try_count);
1001 }
1002 }
1004 ShouldNotReachHere();
1005 return NULL;
1006 }
1008 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size,
1009 unsigned int * gc_count_before_ret,
1010 int* gclocker_retry_count_ret) {
1011 // The structure of this method has a lot of similarities to
1012 // attempt_allocation_slow(). The reason these two were not merged
1013 // into a single one is that such a method would require several "if
1014 // allocation is not humongous do this, otherwise do that"
1015 // conditional paths which would obscure its flow. In fact, an early
1016 // version of this code did use a unified method which was harder to
1017 // follow and, as a result, it had subtle bugs that were hard to
1018 // track down. So keeping these two methods separate allows each to
1019 // be more readable. It will be good to keep these two in sync as
1020 // much as possible.
1022 assert_heap_not_locked_and_not_at_safepoint();
1023 assert(isHumongous(word_size), "attempt_allocation_humongous() "
1024 "should only be called for humongous allocations");
1026 // Humongous objects can exhaust the heap quickly, so we should check if we
1027 // need to start a marking cycle at each humongous object allocation. We do
1028 // the check before we do the actual allocation. The reason for doing it
1029 // before the allocation is that we avoid having to keep track of the newly
1030 // allocated memory while we do a GC.
1031 if (g1_policy()->need_to_start_conc_mark("concurrent humongous allocation",
1032 word_size)) {
1033 collect(GCCause::_g1_humongous_allocation);
1034 }
1036 // We will loop until a) we manage to successfully perform the
1037 // allocation or b) we successfully schedule a collection which
1038 // fails to perform the allocation. b) is the only case when we'll
1039 // return NULL.
1040 HeapWord* result = NULL;
1041 for (int try_count = 1; /* we'll return */; try_count += 1) {
1042 bool should_try_gc;
1043 unsigned int gc_count_before;
1045 {
1046 MutexLockerEx x(Heap_lock);
1048 // Given that humongous objects are not allocated in young
1049 // regions, we'll first try to do the allocation without doing a
1050 // collection hoping that there's enough space in the heap.
1051 result = humongous_obj_allocate(word_size);
1052 if (result != NULL) {
1053 return result;
1054 }
1056 if (GC_locker::is_active_and_needs_gc()) {
1057 should_try_gc = false;
1058 } else {
1059 // The GCLocker may not be active but the GCLocker initiated
1060 // GC may not yet have been performed (GCLocker::needs_gc()
1061 // returns true). In this case we do not try this GC and
1062 // wait until the GCLocker initiated GC is performed, and
1063 // then retry the allocation.
1064 if (GC_locker::needs_gc()) {
1065 should_try_gc = false;
1066 } else {
1067 // Read the GC count while still holding the Heap_lock.
1068 gc_count_before = total_collections();
1069 should_try_gc = true;
1070 }
1071 }
1072 }
1074 if (should_try_gc) {
1075 // If we failed to allocate the humongous object, we should try to
1076 // do a collection pause (if we're allowed) in case it reclaims
1077 // enough space for the allocation to succeed after the pause.
1079 bool succeeded;
1080 result = do_collection_pause(word_size, gc_count_before, &succeeded,
1081 GCCause::_g1_humongous_allocation);
1082 if (result != NULL) {
1083 assert(succeeded, "only way to get back a non-NULL result");
1084 return result;
1085 }
1087 if (succeeded) {
1088 // If we get here we successfully scheduled a collection which
1089 // failed to allocate. No point in trying to allocate
1090 // further. We'll just return NULL.
1091 MutexLockerEx x(Heap_lock);
1092 *gc_count_before_ret = total_collections();
1093 return NULL;
1094 }
1095 } else {
1096 if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
1097 MutexLockerEx x(Heap_lock);
1098 *gc_count_before_ret = total_collections();
1099 return NULL;
1100 }
1101 // The GCLocker is either active or the GCLocker initiated
1102 // GC has not yet been performed. Stall until it is and
1103 // then retry the allocation.
1104 GC_locker::stall_until_clear();
1105 (*gclocker_retry_count_ret) += 1;
1106 }
1108 // We can reach here if we were unsuccessful in scheduling a
1109 // collection (because another thread beat us to it) or if we were
1110 // stalled due to the GC locker. In either can we should retry the
1111 // allocation attempt in case another thread successfully
1112 // performed a collection and reclaimed enough space. Give a
1113 // warning if we seem to be looping forever.
1115 if ((QueuedAllocationWarningCount > 0) &&
1116 (try_count % QueuedAllocationWarningCount == 0)) {
1117 warning("G1CollectedHeap::attempt_allocation_humongous() "
1118 "retries %d times", try_count);
1119 }
1120 }
1122 ShouldNotReachHere();
1123 return NULL;
1124 }
1126 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
1127 bool expect_null_mutator_alloc_region) {
1128 assert_at_safepoint(true /* should_be_vm_thread */);
1129 assert(_mutator_alloc_region.get() == NULL ||
1130 !expect_null_mutator_alloc_region,
1131 "the current alloc region was unexpectedly found to be non-NULL");
1133 if (!isHumongous(word_size)) {
1134 return _mutator_alloc_region.attempt_allocation_locked(word_size,
1135 false /* bot_updates */);
1136 } else {
1137 HeapWord* result = humongous_obj_allocate(word_size);
1138 if (result != NULL && g1_policy()->need_to_start_conc_mark("STW humongous allocation")) {
1139 g1_policy()->set_initiate_conc_mark_if_possible();
1140 }
1141 return result;
1142 }
1144 ShouldNotReachHere();
1145 }
1147 class PostMCRemSetClearClosure: public HeapRegionClosure {
1148 G1CollectedHeap* _g1h;
1149 ModRefBarrierSet* _mr_bs;
1150 public:
1151 PostMCRemSetClearClosure(G1CollectedHeap* g1h, ModRefBarrierSet* mr_bs) :
1152 _g1h(g1h), _mr_bs(mr_bs) {}
1154 bool doHeapRegion(HeapRegion* r) {
1155 HeapRegionRemSet* hrrs = r->rem_set();
1157 if (r->continuesHumongous()) {
1158 // We'll assert that the strong code root list and RSet is empty
1159 assert(hrrs->strong_code_roots_list_length() == 0, "sanity");
1160 assert(hrrs->occupied() == 0, "RSet should be empty");
1161 return false;
1162 }
1164 _g1h->reset_gc_time_stamps(r);
1165 hrrs->clear();
1166 // You might think here that we could clear just the cards
1167 // corresponding to the used region. But no: if we leave a dirty card
1168 // in a region we might allocate into, then it would prevent that card
1169 // from being enqueued, and cause it to be missed.
1170 // Re: the performance cost: we shouldn't be doing full GC anyway!
1171 _mr_bs->clear(MemRegion(r->bottom(), r->end()));
1173 return false;
1174 }
1175 };
1177 void G1CollectedHeap::clear_rsets_post_compaction() {
1178 PostMCRemSetClearClosure rs_clear(this, g1_barrier_set());
1179 heap_region_iterate(&rs_clear);
1180 }
1182 class RebuildRSOutOfRegionClosure: public HeapRegionClosure {
1183 G1CollectedHeap* _g1h;
1184 UpdateRSOopClosure _cl;
1185 int _worker_i;
1186 public:
1187 RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, int worker_i = 0) :
1188 _cl(g1->g1_rem_set(), worker_i),
1189 _worker_i(worker_i),
1190 _g1h(g1)
1191 { }
1193 bool doHeapRegion(HeapRegion* r) {
1194 if (!r->continuesHumongous()) {
1195 _cl.set_from(r);
1196 r->oop_iterate(&_cl);
1197 }
1198 return false;
1199 }
1200 };
1202 class ParRebuildRSTask: public AbstractGangTask {
1203 G1CollectedHeap* _g1;
1204 public:
1205 ParRebuildRSTask(G1CollectedHeap* g1)
1206 : AbstractGangTask("ParRebuildRSTask"),
1207 _g1(g1)
1208 { }
1210 void work(uint worker_id) {
1211 RebuildRSOutOfRegionClosure rebuild_rs(_g1, worker_id);
1212 _g1->heap_region_par_iterate_chunked(&rebuild_rs, worker_id,
1213 _g1->workers()->active_workers(),
1214 HeapRegion::RebuildRSClaimValue);
1215 }
1216 };
1218 class PostCompactionPrinterClosure: public HeapRegionClosure {
1219 private:
1220 G1HRPrinter* _hr_printer;
1221 public:
1222 bool doHeapRegion(HeapRegion* hr) {
1223 assert(!hr->is_young(), "not expecting to find young regions");
1224 // We only generate output for non-empty regions.
1225 if (!hr->is_empty()) {
1226 if (!hr->isHumongous()) {
1227 _hr_printer->post_compaction(hr, G1HRPrinter::Old);
1228 } else if (hr->startsHumongous()) {
1229 if (hr->region_num() == 1) {
1230 // single humongous region
1231 _hr_printer->post_compaction(hr, G1HRPrinter::SingleHumongous);
1232 } else {
1233 _hr_printer->post_compaction(hr, G1HRPrinter::StartsHumongous);
1234 }
1235 } else {
1236 assert(hr->continuesHumongous(), "only way to get here");
1237 _hr_printer->post_compaction(hr, G1HRPrinter::ContinuesHumongous);
1238 }
1239 }
1240 return false;
1241 }
1243 PostCompactionPrinterClosure(G1HRPrinter* hr_printer)
1244 : _hr_printer(hr_printer) { }
1245 };
1247 void G1CollectedHeap::print_hrs_post_compaction() {
1248 PostCompactionPrinterClosure cl(hr_printer());
1249 heap_region_iterate(&cl);
1250 }
1252 bool G1CollectedHeap::do_collection(bool explicit_gc,
1253 bool clear_all_soft_refs,
1254 size_t word_size) {
1255 assert_at_safepoint(true /* should_be_vm_thread */);
1257 if (GC_locker::check_active_before_gc()) {
1258 return false;
1259 }
1261 STWGCTimer* gc_timer = G1MarkSweep::gc_timer();
1262 gc_timer->register_gc_start();
1264 SerialOldTracer* gc_tracer = G1MarkSweep::gc_tracer();
1265 gc_tracer->report_gc_start(gc_cause(), gc_timer->gc_start());
1267 SvcGCMarker sgcm(SvcGCMarker::FULL);
1268 ResourceMark rm;
1270 print_heap_before_gc();
1271 trace_heap_before_gc(gc_tracer);
1273 size_t metadata_prev_used = MetaspaceAux::used_bytes();
1275 verify_region_sets_optional();
1277 const bool do_clear_all_soft_refs = clear_all_soft_refs ||
1278 collector_policy()->should_clear_all_soft_refs();
1280 ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());
1282 {
1283 IsGCActiveMark x;
1285 // Timing
1286 assert(gc_cause() != GCCause::_java_lang_system_gc || explicit_gc, "invariant");
1287 gclog_or_tty->date_stamp(G1Log::fine() && PrintGCDateStamps);
1288 TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
1290 {
1291 GCTraceTime t(GCCauseString("Full GC", gc_cause()), G1Log::fine(), true, NULL, gc_tracer->gc_id());
1292 TraceCollectorStats tcs(g1mm()->full_collection_counters());
1293 TraceMemoryManagerStats tms(true /* fullGC */, gc_cause());
1295 double start = os::elapsedTime();
1296 g1_policy()->record_full_collection_start();
1298 // Note: When we have a more flexible GC logging framework that
1299 // allows us to add optional attributes to a GC log record we
1300 // could consider timing and reporting how long we wait in the
1301 // following two methods.
1302 wait_while_free_regions_coming();
1303 // If we start the compaction before the CM threads finish
1304 // scanning the root regions we might trip them over as we'll
1305 // be moving objects / updating references. So let's wait until
1306 // they are done. By telling them to abort, they should complete
1307 // early.
1308 _cm->root_regions()->abort();
1309 _cm->root_regions()->wait_until_scan_finished();
1310 append_secondary_free_list_if_not_empty_with_lock();
1312 gc_prologue(true);
1313 increment_total_collections(true /* full gc */);
1314 increment_old_marking_cycles_started();
1316 assert(used() == recalculate_used(), "Should be equal");
1318 verify_before_gc();
1320 check_bitmaps("Full GC Start");
1321 pre_full_gc_dump(gc_timer);
1323 COMPILER2_PRESENT(DerivedPointerTable::clear());
1325 // Disable discovery and empty the discovered lists
1326 // for the CM ref processor.
1327 ref_processor_cm()->disable_discovery();
1328 ref_processor_cm()->abandon_partial_discovery();
1329 ref_processor_cm()->verify_no_references_recorded();
1331 // Abandon current iterations of concurrent marking and concurrent
1332 // refinement, if any are in progress. We have to do this before
1333 // wait_until_scan_finished() below.
1334 concurrent_mark()->abort();
1336 // Make sure we'll choose a new allocation region afterwards.
1337 release_mutator_alloc_region();
1338 abandon_gc_alloc_regions();
1339 g1_rem_set()->cleanupHRRS();
1341 // We should call this after we retire any currently active alloc
1342 // regions so that all the ALLOC / RETIRE events are generated
1343 // before the start GC event.
1344 _hr_printer.start_gc(true /* full */, (size_t) total_collections());
1346 // We may have added regions to the current incremental collection
1347 // set between the last GC or pause and now. We need to clear the
1348 // incremental collection set and then start rebuilding it afresh
1349 // after this full GC.
1350 abandon_collection_set(g1_policy()->inc_cset_head());
1351 g1_policy()->clear_incremental_cset();
1352 g1_policy()->stop_incremental_cset_building();
1354 tear_down_region_sets(false /* free_list_only */);
1355 g1_policy()->set_gcs_are_young(true);
1357 // See the comments in g1CollectedHeap.hpp and
1358 // G1CollectedHeap::ref_processing_init() about
1359 // how reference processing currently works in G1.
1361 // Temporarily make discovery by the STW ref processor single threaded (non-MT).
1362 ReferenceProcessorMTDiscoveryMutator stw_rp_disc_ser(ref_processor_stw(), false);
1364 // Temporarily clear the STW ref processor's _is_alive_non_header field.
1365 ReferenceProcessorIsAliveMutator stw_rp_is_alive_null(ref_processor_stw(), NULL);
1367 ref_processor_stw()->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
1368 ref_processor_stw()->setup_policy(do_clear_all_soft_refs);
1370 // Do collection work
1371 {
1372 HandleMark hm; // Discard invalid handles created during gc
1373 G1MarkSweep::invoke_at_safepoint(ref_processor_stw(), do_clear_all_soft_refs);
1374 }
1376 assert(num_free_regions() == 0, "we should not have added any free regions");
1377 rebuild_region_sets(false /* free_list_only */);
1379 // Enqueue any discovered reference objects that have
1380 // not been removed from the discovered lists.
1381 ref_processor_stw()->enqueue_discovered_references();
1383 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
1385 MemoryService::track_memory_usage();
1387 assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
1388 ref_processor_stw()->verify_no_references_recorded();
1390 // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1391 ClassLoaderDataGraph::purge();
1392 MetaspaceAux::verify_metrics();
1394 // Note: since we've just done a full GC, concurrent
1395 // marking is no longer active. Therefore we need not
1396 // re-enable reference discovery for the CM ref processor.
1397 // That will be done at the start of the next marking cycle.
1398 assert(!ref_processor_cm()->discovery_enabled(), "Postcondition");
1399 ref_processor_cm()->verify_no_references_recorded();
1401 reset_gc_time_stamp();
1402 // Since everything potentially moved, we will clear all remembered
1403 // sets, and clear all cards. Later we will rebuild remembered
1404 // sets. We will also reset the GC time stamps of the regions.
1405 clear_rsets_post_compaction();
1406 check_gc_time_stamps();
1408 // Resize the heap if necessary.
1409 resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size);
1411 if (_hr_printer.is_active()) {
1412 // We should do this after we potentially resize the heap so
1413 // that all the COMMIT / UNCOMMIT events are generated before
1414 // the end GC event.
1416 print_hrs_post_compaction();
1417 _hr_printer.end_gc(true /* full */, (size_t) total_collections());
1418 }
1420 G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
1421 if (hot_card_cache->use_cache()) {
1422 hot_card_cache->reset_card_counts();
1423 hot_card_cache->reset_hot_cache();
1424 }
1426 // Rebuild remembered sets of all regions.
1427 if (G1CollectedHeap::use_parallel_gc_threads()) {
1428 uint n_workers =
1429 AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
1430 workers()->active_workers(),
1431 Threads::number_of_non_daemon_threads());
1432 assert(UseDynamicNumberOfGCThreads ||
1433 n_workers == workers()->total_workers(),
1434 "If not dynamic should be using all the workers");
1435 workers()->set_active_workers(n_workers);
1436 // Set parallel threads in the heap (_n_par_threads) only
1437 // before a parallel phase and always reset it to 0 after
1438 // the phase so that the number of parallel threads does
1439 // no get carried forward to a serial phase where there
1440 // may be code that is "possibly_parallel".
1441 set_par_threads(n_workers);
1443 ParRebuildRSTask rebuild_rs_task(this);
1444 assert(check_heap_region_claim_values(
1445 HeapRegion::InitialClaimValue), "sanity check");
1446 assert(UseDynamicNumberOfGCThreads ||
1447 workers()->active_workers() == workers()->total_workers(),
1448 "Unless dynamic should use total workers");
1449 // Use the most recent number of active workers
1450 assert(workers()->active_workers() > 0,
1451 "Active workers not properly set");
1452 set_par_threads(workers()->active_workers());
1453 workers()->run_task(&rebuild_rs_task);
1454 set_par_threads(0);
1455 assert(check_heap_region_claim_values(
1456 HeapRegion::RebuildRSClaimValue), "sanity check");
1457 reset_heap_region_claim_values();
1458 } else {
1459 RebuildRSOutOfRegionClosure rebuild_rs(this);
1460 heap_region_iterate(&rebuild_rs);
1461 }
1463 // Rebuild the strong code root lists for each region
1464 rebuild_strong_code_roots();
1466 if (true) { // FIXME
1467 MetaspaceGC::compute_new_size();
1468 }
1470 #ifdef TRACESPINNING
1471 ParallelTaskTerminator::print_termination_counts();
1472 #endif
1474 // Discard all rset updates
1475 JavaThread::dirty_card_queue_set().abandon_logs();
1476 assert(!G1DeferredRSUpdate
1477 || (G1DeferredRSUpdate &&
1478 (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any");
1480 _young_list->reset_sampled_info();
1481 // At this point there should be no regions in the
1482 // entire heap tagged as young.
1483 assert(check_young_list_empty(true /* check_heap */),
1484 "young list should be empty at this point");
1486 // Update the number of full collections that have been completed.
1487 increment_old_marking_cycles_completed(false /* concurrent */);
1489 _hrs.verify_optional();
1490 verify_region_sets_optional();
1492 verify_after_gc();
1494 // Clear the previous marking bitmap, if needed for bitmap verification.
1495 // Note we cannot do this when we clear the next marking bitmap in
1496 // ConcurrentMark::abort() above since VerifyDuringGC verifies the
1497 // objects marked during a full GC against the previous bitmap.
1498 // But we need to clear it before calling check_bitmaps below since
1499 // the full GC has compacted objects and updated TAMS but not updated
1500 // the prev bitmap.
1501 if (G1VerifyBitmaps) {
1502 ((CMBitMap*) concurrent_mark()->prevMarkBitMap())->clearAll();
1503 }
1504 check_bitmaps("Full GC End");
1506 // Start a new incremental collection set for the next pause
1507 assert(g1_policy()->collection_set() == NULL, "must be");
1508 g1_policy()->start_incremental_cset_building();
1510 clear_cset_fast_test();
1512 init_mutator_alloc_region();
1514 double end = os::elapsedTime();
1515 g1_policy()->record_full_collection_end();
1517 if (G1Log::fine()) {
1518 g1_policy()->print_heap_transition();
1519 }
1521 // We must call G1MonitoringSupport::update_sizes() in the same scoping level
1522 // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
1523 // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
1524 // before any GC notifications are raised.
1525 g1mm()->update_sizes();
1527 gc_epilogue(true);
1528 }
1530 if (G1Log::finer()) {
1531 g1_policy()->print_detailed_heap_transition(true /* full */);
1532 }
1534 print_heap_after_gc();
1535 trace_heap_after_gc(gc_tracer);
1537 post_full_gc_dump(gc_timer);
1539 gc_timer->register_gc_end();
1540 gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions());
1541 }
1543 return true;
1544 }
1546 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1547 // do_collection() will return whether it succeeded in performing
1548 // the GC. Currently, there is no facility on the
1549 // do_full_collection() API to notify the caller than the collection
1550 // did not succeed (e.g., because it was locked out by the GC
1551 // locker). So, right now, we'll ignore the return value.
1552 bool dummy = do_collection(true, /* explicit_gc */
1553 clear_all_soft_refs,
1554 0 /* word_size */);
1555 }
1557 // This code is mostly copied from TenuredGeneration.
1558 void
1559 G1CollectedHeap::
1560 resize_if_necessary_after_full_collection(size_t word_size) {
1561 // Include the current allocation, if any, and bytes that will be
1562 // pre-allocated to support collections, as "used".
1563 const size_t used_after_gc = used();
1564 const size_t capacity_after_gc = capacity();
1565 const size_t free_after_gc = capacity_after_gc - used_after_gc;
1567 // This is enforced in arguments.cpp.
1568 assert(MinHeapFreeRatio <= MaxHeapFreeRatio,
1569 "otherwise the code below doesn't make sense");
1571 // We don't have floating point command-line arguments
1572 const double minimum_free_percentage = (double) MinHeapFreeRatio / 100.0;
1573 const double maximum_used_percentage = 1.0 - minimum_free_percentage;
1574 const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100.0;
1575 const double minimum_used_percentage = 1.0 - maximum_free_percentage;
1577 const size_t min_heap_size = collector_policy()->min_heap_byte_size();
1578 const size_t max_heap_size = collector_policy()->max_heap_byte_size();
1580 // We have to be careful here as these two calculations can overflow
1581 // 32-bit size_t's.
1582 double used_after_gc_d = (double) used_after_gc;
1583 double minimum_desired_capacity_d = used_after_gc_d / maximum_used_percentage;
1584 double maximum_desired_capacity_d = used_after_gc_d / minimum_used_percentage;
1586 // Let's make sure that they are both under the max heap size, which
1587 // by default will make them fit into a size_t.
1588 double desired_capacity_upper_bound = (double) max_heap_size;
1589 minimum_desired_capacity_d = MIN2(minimum_desired_capacity_d,
1590 desired_capacity_upper_bound);
1591 maximum_desired_capacity_d = MIN2(maximum_desired_capacity_d,
1592 desired_capacity_upper_bound);
1594 // We can now safely turn them into size_t's.
1595 size_t minimum_desired_capacity = (size_t) minimum_desired_capacity_d;
1596 size_t maximum_desired_capacity = (size_t) maximum_desired_capacity_d;
1598 // This assert only makes sense here, before we adjust them
1599 // with respect to the min and max heap size.
1600 assert(minimum_desired_capacity <= maximum_desired_capacity,
1601 err_msg("minimum_desired_capacity = "SIZE_FORMAT", "
1602 "maximum_desired_capacity = "SIZE_FORMAT,
1603 minimum_desired_capacity, maximum_desired_capacity));
1605 // Should not be greater than the heap max size. No need to adjust
1606 // it with respect to the heap min size as it's a lower bound (i.e.,
1607 // we'll try to make the capacity larger than it, not smaller).
1608 minimum_desired_capacity = MIN2(minimum_desired_capacity, max_heap_size);
1609 // Should not be less than the heap min size. No need to adjust it
1610 // with respect to the heap max size as it's an upper bound (i.e.,
1611 // we'll try to make the capacity smaller than it, not greater).
1612 maximum_desired_capacity = MAX2(maximum_desired_capacity, min_heap_size);
1614 if (capacity_after_gc < minimum_desired_capacity) {
1615 // Don't expand unless it's significant
1616 size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
1617 ergo_verbose4(ErgoHeapSizing,
1618 "attempt heap expansion",
1619 ergo_format_reason("capacity lower than "
1620 "min desired capacity after Full GC")
1621 ergo_format_byte("capacity")
1622 ergo_format_byte("occupancy")
1623 ergo_format_byte_perc("min desired capacity"),
1624 capacity_after_gc, used_after_gc,
1625 minimum_desired_capacity, (double) MinHeapFreeRatio);
1626 expand(expand_bytes);
1628 // No expansion, now see if we want to shrink
1629 } else if (capacity_after_gc > maximum_desired_capacity) {
1630 // Capacity too large, compute shrinking size
1631 size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;
1632 ergo_verbose4(ErgoHeapSizing,
1633 "attempt heap shrinking",
1634 ergo_format_reason("capacity higher than "
1635 "max desired capacity after Full GC")
1636 ergo_format_byte("capacity")
1637 ergo_format_byte("occupancy")
1638 ergo_format_byte_perc("max desired capacity"),
1639 capacity_after_gc, used_after_gc,
1640 maximum_desired_capacity, (double) MaxHeapFreeRatio);
1641 shrink(shrink_bytes);
1642 }
1643 }
1646 HeapWord*
1647 G1CollectedHeap::satisfy_failed_allocation(size_t word_size,
1648 bool* succeeded) {
1649 assert_at_safepoint(true /* should_be_vm_thread */);
1651 *succeeded = true;
1652 // Let's attempt the allocation first.
1653 HeapWord* result =
1654 attempt_allocation_at_safepoint(word_size,
1655 false /* expect_null_mutator_alloc_region */);
1656 if (result != NULL) {
1657 assert(*succeeded, "sanity");
1658 return result;
1659 }
1661 // In a G1 heap, we're supposed to keep allocation from failing by
1662 // incremental pauses. Therefore, at least for now, we'll favor
1663 // expansion over collection. (This might change in the future if we can
1664 // do something smarter than full collection to satisfy a failed alloc.)
1665 result = expand_and_allocate(word_size);
1666 if (result != NULL) {
1667 assert(*succeeded, "sanity");
1668 return result;
1669 }
1671 // Expansion didn't work, we'll try to do a Full GC.
1672 bool gc_succeeded = do_collection(false, /* explicit_gc */
1673 false, /* clear_all_soft_refs */
1674 word_size);
1675 if (!gc_succeeded) {
1676 *succeeded = false;
1677 return NULL;
1678 }
1680 // Retry the allocation
1681 result = attempt_allocation_at_safepoint(word_size,
1682 true /* expect_null_mutator_alloc_region */);
1683 if (result != NULL) {
1684 assert(*succeeded, "sanity");
1685 return result;
1686 }
1688 // Then, try a Full GC that will collect all soft references.
1689 gc_succeeded = do_collection(false, /* explicit_gc */
1690 true, /* clear_all_soft_refs */
1691 word_size);
1692 if (!gc_succeeded) {
1693 *succeeded = false;
1694 return NULL;
1695 }
1697 // Retry the allocation once more
1698 result = attempt_allocation_at_safepoint(word_size,
1699 true /* expect_null_mutator_alloc_region */);
1700 if (result != NULL) {
1701 assert(*succeeded, "sanity");
1702 return result;
1703 }
1705 assert(!collector_policy()->should_clear_all_soft_refs(),
1706 "Flag should have been handled and cleared prior to this point");
1708 // What else? We might try synchronous finalization later. If the total
1709 // space available is large enough for the allocation, then a more
1710 // complete compaction phase than we've tried so far might be
1711 // appropriate.
1712 assert(*succeeded, "sanity");
1713 return NULL;
1714 }
1716 // Attempting to expand the heap sufficiently
1717 // to support an allocation of the given "word_size". If
1718 // successful, perform the allocation and return the address of the
1719 // allocated block, or else "NULL".
1721 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1722 assert_at_safepoint(true /* should_be_vm_thread */);
1724 verify_region_sets_optional();
1726 size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
1727 ergo_verbose1(ErgoHeapSizing,
1728 "attempt heap expansion",
1729 ergo_format_reason("allocation request failed")
1730 ergo_format_byte("allocation request"),
1731 word_size * HeapWordSize);
1732 if (expand(expand_bytes)) {
1733 _hrs.verify_optional();
1734 verify_region_sets_optional();
1735 return attempt_allocation_at_safepoint(word_size,
1736 false /* expect_null_mutator_alloc_region */);
1737 }
1738 return NULL;
1739 }
1741 bool G1CollectedHeap::expand(size_t expand_bytes) {
1742 size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);
1743 aligned_expand_bytes = align_size_up(aligned_expand_bytes,
1744 HeapRegion::GrainBytes);
1745 ergo_verbose2(ErgoHeapSizing,
1746 "expand the heap",
1747 ergo_format_byte("requested expansion amount")
1748 ergo_format_byte("attempted expansion amount"),
1749 expand_bytes, aligned_expand_bytes);
1751 if (is_maximal_no_gc()) {
1752 ergo_verbose0(ErgoHeapSizing,
1753 "did not expand the heap",
1754 ergo_format_reason("heap already fully expanded"));
1755 return false;
1756 }
1758 uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes);
1759 assert(regions_to_expand > 0, "Must expand by at least one region");
1761 uint expanded_by = _hrs.expand_by(regions_to_expand);
1763 if (expanded_by > 0) {
1764 size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes;
1765 assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
1766 g1_policy()->record_new_heap_size(num_regions());
1767 } else {
1768 ergo_verbose0(ErgoHeapSizing,
1769 "did not expand the heap",
1770 ergo_format_reason("heap expansion operation failed"));
1771 // The expansion of the virtual storage space was unsuccessful.
1772 // Let's see if it was because we ran out of swap.
1773 if (G1ExitOnExpansionFailure &&
1774 _hrs.available() >= regions_to_expand) {
1775 // We had head room...
1776 vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");
1777 }
1778 }
1779 return regions_to_expand > 0;
1780 }
1782 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
1783 size_t aligned_shrink_bytes =
1784 ReservedSpace::page_align_size_down(shrink_bytes);
1785 aligned_shrink_bytes = align_size_down(aligned_shrink_bytes,
1786 HeapRegion::GrainBytes);
1787 uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);
1789 uint num_regions_removed = _hrs.shrink_by(num_regions_to_remove);
1790 size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;
1792 ergo_verbose3(ErgoHeapSizing,
1793 "shrink the heap",
1794 ergo_format_byte("requested shrinking amount")
1795 ergo_format_byte("aligned shrinking amount")
1796 ergo_format_byte("attempted shrinking amount"),
1797 shrink_bytes, aligned_shrink_bytes, shrunk_bytes);
1798 if (num_regions_removed > 0) {
1799 g1_policy()->record_new_heap_size(num_regions());
1800 } else {
1801 ergo_verbose0(ErgoHeapSizing,
1802 "did not shrink the heap",
1803 ergo_format_reason("heap shrinking operation failed"));
1804 }
1805 }
1807 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1808 verify_region_sets_optional();
1810 // We should only reach here at the end of a Full GC which means we
1811 // should not not be holding to any GC alloc regions. The method
1812 // below will make sure of that and do any remaining clean up.
1813 abandon_gc_alloc_regions();
1815 // Instead of tearing down / rebuilding the free lists here, we
1816 // could instead use the remove_all_pending() method on free_list to
1817 // remove only the ones that we need to remove.
1818 tear_down_region_sets(true /* free_list_only */);
1819 shrink_helper(shrink_bytes);
1820 rebuild_region_sets(true /* free_list_only */);
1822 _hrs.verify_optional();
1823 verify_region_sets_optional();
1824 }
1826 // Public methods.
1828 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
1829 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
1830 #endif // _MSC_VER
1833 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :
1834 SharedHeap(policy_),
1835 _g1_policy(policy_),
1836 _dirty_card_queue_set(false),
1837 _into_cset_dirty_card_queue_set(false),
1838 _is_alive_closure_cm(this),
1839 _is_alive_closure_stw(this),
1840 _ref_processor_cm(NULL),
1841 _ref_processor_stw(NULL),
1842 _process_strong_tasks(new SubTasksDone(G1H_PS_NumElements)),
1843 _bot_shared(NULL),
1844 _evac_failure_scan_stack(NULL),
1845 _mark_in_progress(false),
1846 _cg1r(NULL), _summary_bytes_used(0),
1847 _g1mm(NULL),
1848 _refine_cte_cl(NULL),
1849 _full_collection(false),
1850 _secondary_free_list("Secondary Free List", new SecondaryFreeRegionListMtSafeChecker()),
1851 _old_set("Old Set", false /* humongous */, new OldRegionSetMtSafeChecker()),
1852 _humongous_set("Master Humongous Set", true /* humongous */, new HumongousRegionSetMtSafeChecker()),
1853 _humongous_is_live(),
1854 _has_humongous_reclaim_candidates(false),
1855 _free_regions_coming(false),
1856 _young_list(new YoungList(this)),
1857 _gc_time_stamp(0),
1858 _retained_old_gc_alloc_region(NULL),
1859 _survivor_plab_stats(YoungPLABSize, PLABWeight),
1860 _old_plab_stats(OldPLABSize, PLABWeight),
1861 _expand_heap_after_alloc_failure(true),
1862 _surviving_young_words(NULL),
1863 _old_marking_cycles_started(0),
1864 _old_marking_cycles_completed(0),
1865 _concurrent_cycle_started(false),
1866 _in_cset_fast_test(),
1867 _dirty_cards_region_list(NULL),
1868 _worker_cset_start_region(NULL),
1869 _worker_cset_start_region_time_stamp(NULL),
1870 _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),
1871 _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
1872 _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),
1873 _gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) G1OldTracer()) {
1875 _g1h = this;
1876 if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) {
1877 vm_exit_during_initialization("Failed necessary allocation.");
1878 }
1880 _humongous_object_threshold_in_words = HeapRegion::GrainWords / 2;
1882 int n_queues = MAX2((int)ParallelGCThreads, 1);
1883 _task_queues = new RefToScanQueueSet(n_queues);
1885 uint n_rem_sets = HeapRegionRemSet::num_par_rem_sets();
1886 assert(n_rem_sets > 0, "Invariant.");
1888 _worker_cset_start_region = NEW_C_HEAP_ARRAY(HeapRegion*, n_queues, mtGC);
1889 _worker_cset_start_region_time_stamp = NEW_C_HEAP_ARRAY(unsigned int, n_queues, mtGC);
1890 _evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);
1892 for (int i = 0; i < n_queues; i++) {
1893 RefToScanQueue* q = new RefToScanQueue();
1894 q->initialize();
1895 _task_queues->register_queue(i, q);
1896 ::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();
1897 }
1898 clear_cset_start_regions();
1900 // Initialize the G1EvacuationFailureALot counters and flags.
1901 NOT_PRODUCT(reset_evacuation_should_fail();)
1903 guarantee(_task_queues != NULL, "task_queues allocation failure.");
1904 }
1906 jint G1CollectedHeap::initialize() {
1907 CollectedHeap::pre_initialize();
1908 os::enable_vtime();
1910 G1Log::init();
1912 // Necessary to satisfy locking discipline assertions.
1914 MutexLocker x(Heap_lock);
1916 // We have to initialize the printer before committing the heap, as
1917 // it will be used then.
1918 _hr_printer.set_active(G1PrintHeapRegions);
1920 // While there are no constraints in the GC code that HeapWordSize
1921 // be any particular value, there are multiple other areas in the
1922 // system which believe this to be true (e.g. oop->object_size in some
1923 // cases incorrectly returns the size in wordSize units rather than
1924 // HeapWordSize).
1925 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1927 size_t init_byte_size = collector_policy()->initial_heap_byte_size();
1928 size_t max_byte_size = collector_policy()->max_heap_byte_size();
1929 size_t heap_alignment = collector_policy()->heap_alignment();
1931 // Ensure that the sizes are properly aligned.
1932 Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
1933 Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");
1934 Universe::check_alignment(max_byte_size, heap_alignment, "g1 heap");
1936 _refine_cte_cl = new RefineCardTableEntryClosure();
1938 _cg1r = new ConcurrentG1Refine(this, _refine_cte_cl);
1940 // Reserve the maximum.
1942 // When compressed oops are enabled, the preferred heap base
1943 // is calculated by subtracting the requested size from the
1944 // 32Gb boundary and using the result as the base address for
1945 // heap reservation. If the requested size is not aligned to
1946 // HeapRegion::GrainBytes (i.e. the alignment that is passed
1947 // into the ReservedHeapSpace constructor) then the actual
1948 // base of the reserved heap may end up differing from the
1949 // address that was requested (i.e. the preferred heap base).
1950 // If this happens then we could end up using a non-optimal
1951 // compressed oops mode.
1953 ReservedSpace heap_rs = Universe::reserve_heap(max_byte_size,
1954 heap_alignment);
1956 // It is important to do this in a way such that concurrent readers can't
1957 // temporarily think something is in the heap. (I've actually seen this
1958 // happen in asserts: DLD.)
1959 _reserved.set_word_size(0);
1960 _reserved.set_start((HeapWord*)heap_rs.base());
1961 _reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size()));
1963 // Create the gen rem set (and barrier set) for the entire reserved region.
1964 _rem_set = collector_policy()->create_rem_set(_reserved, 2);
1965 set_barrier_set(rem_set()->bs());
1966 if (!barrier_set()->is_a(BarrierSet::G1SATBCTLogging)) {
1967 vm_exit_during_initialization("G1 requires a G1SATBLoggingCardTableModRefBS");
1968 return JNI_ENOMEM;
1969 }
1971 // Also create a G1 rem set.
1972 _g1_rem_set = new G1RemSet(this, g1_barrier_set());
1974 // Carve out the G1 part of the heap.
1976 ReservedSpace g1_rs = heap_rs.first_part(max_byte_size);
1977 G1RegionToSpaceMapper* heap_storage =
1978 G1RegionToSpaceMapper::create_mapper(g1_rs,
1979 UseLargePages ? os::large_page_size() : os::vm_page_size(),
1980 HeapRegion::GrainBytes,
1981 1,
1982 mtJavaHeap);
1983 heap_storage->set_mapping_changed_listener(&_listener);
1985 // Reserve space for the block offset table. We do not support automatic uncommit
1986 // for the card table at this time. BOT only.
1987 ReservedSpace bot_rs(G1BlockOffsetSharedArray::compute_size(g1_rs.size() / HeapWordSize));
1988 G1RegionToSpaceMapper* bot_storage =
1989 G1RegionToSpaceMapper::create_mapper(bot_rs,
1990 os::vm_page_size(),
1991 HeapRegion::GrainBytes,
1992 G1BlockOffsetSharedArray::N_bytes,
1993 mtGC);
1995 ReservedSpace cardtable_rs(G1SATBCardTableLoggingModRefBS::compute_size(g1_rs.size() / HeapWordSize));
1996 G1RegionToSpaceMapper* cardtable_storage =
1997 G1RegionToSpaceMapper::create_mapper(cardtable_rs,
1998 os::vm_page_size(),
1999 HeapRegion::GrainBytes,
2000 G1BlockOffsetSharedArray::N_bytes,
2001 mtGC);
2003 // Reserve space for the card counts table.
2004 ReservedSpace card_counts_rs(G1BlockOffsetSharedArray::compute_size(g1_rs.size() / HeapWordSize));
2005 G1RegionToSpaceMapper* card_counts_storage =
2006 G1RegionToSpaceMapper::create_mapper(card_counts_rs,
2007 os::vm_page_size(),
2008 HeapRegion::GrainBytes,
2009 G1BlockOffsetSharedArray::N_bytes,
2010 mtGC);
2012 // Reserve space for prev and next bitmap.
2013 size_t bitmap_size = CMBitMap::compute_size(g1_rs.size());
2015 ReservedSpace prev_bitmap_rs(ReservedSpace::allocation_align_size_up(bitmap_size));
2016 G1RegionToSpaceMapper* prev_bitmap_storage =
2017 G1RegionToSpaceMapper::create_mapper(prev_bitmap_rs,
2018 os::vm_page_size(),
2019 HeapRegion::GrainBytes,
2020 CMBitMap::mark_distance(),
2021 mtGC);
2023 ReservedSpace next_bitmap_rs(ReservedSpace::allocation_align_size_up(bitmap_size));
2024 G1RegionToSpaceMapper* next_bitmap_storage =
2025 G1RegionToSpaceMapper::create_mapper(next_bitmap_rs,
2026 os::vm_page_size(),
2027 HeapRegion::GrainBytes,
2028 CMBitMap::mark_distance(),
2029 mtGC);
2031 _hrs.initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage);
2032 g1_barrier_set()->initialize(cardtable_storage);
2033 // Do later initialization work for concurrent refinement.
2034 _cg1r->init(card_counts_storage);
2036 // 6843694 - ensure that the maximum region index can fit
2037 // in the remembered set structures.
2038 const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
2039 guarantee((max_regions() - 1) <= max_region_idx, "too many regions");
2041 size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
2042 guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
2043 guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,
2044 "too many cards per region");
2046 FreeRegionList::set_unrealistically_long_length(max_regions() + 1);
2048 _bot_shared = new G1BlockOffsetSharedArray(_reserved, bot_storage);
2050 _g1h = this;
2052 _in_cset_fast_test.initialize(_hrs.reserved().start(), _hrs.reserved().end(), HeapRegion::GrainBytes);
2053 _humongous_is_live.initialize(_hrs.reserved().start(), _hrs.reserved().end(), HeapRegion::GrainBytes);
2055 // Create the ConcurrentMark data structure and thread.
2056 // (Must do this late, so that "max_regions" is defined.)
2057 _cm = new ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage);
2058 if (_cm == NULL || !_cm->completed_initialization()) {
2059 vm_shutdown_during_initialization("Could not create/initialize ConcurrentMark");
2060 return JNI_ENOMEM;
2061 }
2062 _cmThread = _cm->cmThread();
2064 // Initialize the from_card cache structure of HeapRegionRemSet.
2065 HeapRegionRemSet::init_heap(max_regions());
2067 // Now expand into the initial heap size.
2068 if (!expand(init_byte_size)) {
2069 vm_shutdown_during_initialization("Failed to allocate initial heap.");
2070 return JNI_ENOMEM;
2071 }
2073 // Perform any initialization actions delegated to the policy.
2074 g1_policy()->init();
2076 JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
2077 SATB_Q_FL_lock,
2078 G1SATBProcessCompletedThreshold,
2079 Shared_SATB_Q_lock);
2081 JavaThread::dirty_card_queue_set().initialize(_refine_cte_cl,
2082 DirtyCardQ_CBL_mon,
2083 DirtyCardQ_FL_lock,
2084 concurrent_g1_refine()->yellow_zone(),
2085 concurrent_g1_refine()->red_zone(),
2086 Shared_DirtyCardQ_lock);
2088 if (G1DeferredRSUpdate) {
2089 dirty_card_queue_set().initialize(NULL, // Should never be called by the Java code
2090 DirtyCardQ_CBL_mon,
2091 DirtyCardQ_FL_lock,
2092 -1, // never trigger processing
2093 -1, // no limit on length
2094 Shared_DirtyCardQ_lock,
2095 &JavaThread::dirty_card_queue_set());
2096 }
2098 // Initialize the card queue set used to hold cards containing
2099 // references into the collection set.
2100 _into_cset_dirty_card_queue_set.initialize(NULL, // Should never be called by the Java code
2101 DirtyCardQ_CBL_mon,
2102 DirtyCardQ_FL_lock,
2103 -1, // never trigger processing
2104 -1, // no limit on length
2105 Shared_DirtyCardQ_lock,
2106 &JavaThread::dirty_card_queue_set());
2108 // In case we're keeping closure specialization stats, initialize those
2109 // counts and that mechanism.
2110 SpecializationStats::clear();
2112 // Here we allocate the dummy HeapRegion that is required by the
2113 // G1AllocRegion class.
2114 HeapRegion* dummy_region = _hrs.get_dummy_region();
2116 // We'll re-use the same region whether the alloc region will
2117 // require BOT updates or not and, if it doesn't, then a non-young
2118 // region will complain that it cannot support allocations without
2119 // BOT updates. So we'll tag the dummy region as young to avoid that.
2120 dummy_region->set_young();
2121 // Make sure it's full.
2122 dummy_region->set_top(dummy_region->end());
2123 G1AllocRegion::setup(this, dummy_region);
2125 init_mutator_alloc_region();
2127 // Do create of the monitoring and management support so that
2128 // values in the heap have been properly initialized.
2129 _g1mm = new G1MonitoringSupport(this);
2131 G1StringDedup::initialize();
2133 return JNI_OK;
2134 }
2136 void G1CollectedHeap::stop() {
2137 // Stop all concurrent threads. We do this to make sure these threads
2138 // do not continue to execute and access resources (e.g. gclog_or_tty)
2139 // that are destroyed during shutdown.
2140 _cg1r->stop();
2141 _cmThread->stop();
2142 if (G1StringDedup::is_enabled()) {
2143 G1StringDedup::stop();
2144 }
2145 }
2147 void G1CollectedHeap::clear_humongous_is_live_table() {
2148 guarantee(G1ReclaimDeadHumongousObjectsAtYoungGC, "Should only be called if true");
2149 _humongous_is_live.clear();
2150 }
2152 size_t G1CollectedHeap::conservative_max_heap_alignment() {
2153 return HeapRegion::max_region_size();
2154 }
2156 void G1CollectedHeap::ref_processing_init() {
2157 // Reference processing in G1 currently works as follows:
2158 //
2159 // * There are two reference processor instances. One is
2160 // used to record and process discovered references
2161 // during concurrent marking; the other is used to
2162 // record and process references during STW pauses
2163 // (both full and incremental).
2164 // * Both ref processors need to 'span' the entire heap as
2165 // the regions in the collection set may be dotted around.
2166 //
2167 // * For the concurrent marking ref processor:
2168 // * Reference discovery is enabled at initial marking.
2169 // * Reference discovery is disabled and the discovered
2170 // references processed etc during remarking.
2171 // * Reference discovery is MT (see below).
2172 // * Reference discovery requires a barrier (see below).
2173 // * Reference processing may or may not be MT
2174 // (depending on the value of ParallelRefProcEnabled
2175 // and ParallelGCThreads).
2176 // * A full GC disables reference discovery by the CM
2177 // ref processor and abandons any entries on it's
2178 // discovered lists.
2179 //
2180 // * For the STW processor:
2181 // * Non MT discovery is enabled at the start of a full GC.
2182 // * Processing and enqueueing during a full GC is non-MT.
2183 // * During a full GC, references are processed after marking.
2184 //
2185 // * Discovery (may or may not be MT) is enabled at the start
2186 // of an incremental evacuation pause.
2187 // * References are processed near the end of a STW evacuation pause.
2188 // * For both types of GC:
2189 // * Discovery is atomic - i.e. not concurrent.
2190 // * Reference discovery will not need a barrier.
2192 SharedHeap::ref_processing_init();
2193 MemRegion mr = reserved_region();
2195 // Concurrent Mark ref processor
2196 _ref_processor_cm =
2197 new ReferenceProcessor(mr, // span
2198 ParallelRefProcEnabled && (ParallelGCThreads > 1),
2199 // mt processing
2200 (int) ParallelGCThreads,
2201 // degree of mt processing
2202 (ParallelGCThreads > 1) || (ConcGCThreads > 1),
2203 // mt discovery
2204 (int) MAX2(ParallelGCThreads, ConcGCThreads),
2205 // degree of mt discovery
2206 false,
2207 // Reference discovery is not atomic
2208 &_is_alive_closure_cm);
2209 // is alive closure
2210 // (for efficiency/performance)
2212 // STW ref processor
2213 _ref_processor_stw =
2214 new ReferenceProcessor(mr, // span
2215 ParallelRefProcEnabled && (ParallelGCThreads > 1),
2216 // mt processing
2217 MAX2((int)ParallelGCThreads, 1),
2218 // degree of mt processing
2219 (ParallelGCThreads > 1),
2220 // mt discovery
2221 MAX2((int)ParallelGCThreads, 1),
2222 // degree of mt discovery
2223 true,
2224 // Reference discovery is atomic
2225 &_is_alive_closure_stw);
2226 // is alive closure
2227 // (for efficiency/performance)
2228 }
2230 size_t G1CollectedHeap::capacity() const {
2231 return _hrs.length() * HeapRegion::GrainBytes;
2232 }
2234 void G1CollectedHeap::reset_gc_time_stamps(HeapRegion* hr) {
2235 assert(!hr->continuesHumongous(), "pre-condition");
2236 hr->reset_gc_time_stamp();
2237 if (hr->startsHumongous()) {
2238 uint first_index = hr->hrs_index() + 1;
2239 uint last_index = hr->last_hc_index();
2240 for (uint i = first_index; i < last_index; i += 1) {
2241 HeapRegion* chr = region_at(i);
2242 assert(chr->continuesHumongous(), "sanity");
2243 chr->reset_gc_time_stamp();
2244 }
2245 }
2246 }
2248 #ifndef PRODUCT
2249 class CheckGCTimeStampsHRClosure : public HeapRegionClosure {
2250 private:
2251 unsigned _gc_time_stamp;
2252 bool _failures;
2254 public:
2255 CheckGCTimeStampsHRClosure(unsigned gc_time_stamp) :
2256 _gc_time_stamp(gc_time_stamp), _failures(false) { }
2258 virtual bool doHeapRegion(HeapRegion* hr) {
2259 unsigned region_gc_time_stamp = hr->get_gc_time_stamp();
2260 if (_gc_time_stamp != region_gc_time_stamp) {
2261 gclog_or_tty->print_cr("Region "HR_FORMAT" has GC time stamp = %d, "
2262 "expected %d", HR_FORMAT_PARAMS(hr),
2263 region_gc_time_stamp, _gc_time_stamp);
2264 _failures = true;
2265 }
2266 return false;
2267 }
2269 bool failures() { return _failures; }
2270 };
2272 void G1CollectedHeap::check_gc_time_stamps() {
2273 CheckGCTimeStampsHRClosure cl(_gc_time_stamp);
2274 heap_region_iterate(&cl);
2275 guarantee(!cl.failures(), "all GC time stamps should have been reset");
2276 }
2277 #endif // PRODUCT
2279 void G1CollectedHeap::iterate_dirty_card_closure(CardTableEntryClosure* cl,
2280 DirtyCardQueue* into_cset_dcq,
2281 bool concurrent,
2282 uint worker_i) {
2283 // Clean cards in the hot card cache
2284 G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
2285 hot_card_cache->drain(worker_i, g1_rem_set(), into_cset_dcq);
2287 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
2288 int n_completed_buffers = 0;
2289 while (dcqs.apply_closure_to_completed_buffer(cl, worker_i, 0, true)) {
2290 n_completed_buffers++;
2291 }
2292 g1_policy()->phase_times()->record_update_rs_processed_buffers(worker_i, n_completed_buffers);
2293 dcqs.clear_n_completed_buffers();
2294 assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!");
2295 }
2298 // Computes the sum of the storage used by the various regions.
2300 size_t G1CollectedHeap::used() const {
2301 assert(Heap_lock->owner() != NULL,
2302 "Should be owned on this thread's behalf.");
2303 size_t result = _summary_bytes_used;
2304 // Read only once in case it is set to NULL concurrently
2305 HeapRegion* hr = _mutator_alloc_region.get();
2306 if (hr != NULL)
2307 result += hr->used();
2308 return result;
2309 }
2311 size_t G1CollectedHeap::used_unlocked() const {
2312 size_t result = _summary_bytes_used;
2313 return result;
2314 }
2316 class SumUsedClosure: public HeapRegionClosure {
2317 size_t _used;
2318 public:
2319 SumUsedClosure() : _used(0) {}
2320 bool doHeapRegion(HeapRegion* r) {
2321 if (!r->continuesHumongous()) {
2322 _used += r->used();
2323 }
2324 return false;
2325 }
2326 size_t result() { return _used; }
2327 };
2329 size_t G1CollectedHeap::recalculate_used() const {
2330 double recalculate_used_start = os::elapsedTime();
2332 SumUsedClosure blk;
2333 heap_region_iterate(&blk);
2335 g1_policy()->phase_times()->record_evac_fail_recalc_used_time((os::elapsedTime() - recalculate_used_start) * 1000.0);
2336 return blk.result();
2337 }
2339 size_t G1CollectedHeap::unsafe_max_alloc() {
2340 if (num_free_regions() > 0) return HeapRegion::GrainBytes;
2341 // otherwise, is there space in the current allocation region?
2343 // We need to store the current allocation region in a local variable
2344 // here. The problem is that this method doesn't take any locks and
2345 // there may be other threads which overwrite the current allocation
2346 // region field. attempt_allocation(), for example, sets it to NULL
2347 // and this can happen *after* the NULL check here but before the call
2348 // to free(), resulting in a SIGSEGV. Note that this doesn't appear
2349 // to be a problem in the optimized build, since the two loads of the
2350 // current allocation region field are optimized away.
2351 HeapRegion* hr = _mutator_alloc_region.get();
2352 if (hr == NULL) {
2353 return 0;
2354 }
2355 return hr->free();
2356 }
2358 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
2359 switch (cause) {
2360 case GCCause::_gc_locker: return GCLockerInvokesConcurrent;
2361 case GCCause::_java_lang_system_gc: return ExplicitGCInvokesConcurrent;
2362 case GCCause::_g1_humongous_allocation: return true;
2363 default: return false;
2364 }
2365 }
2367 #ifndef PRODUCT
2368 void G1CollectedHeap::allocate_dummy_regions() {
2369 // Let's fill up most of the region
2370 size_t word_size = HeapRegion::GrainWords - 1024;
2371 // And as a result the region we'll allocate will be humongous.
2372 guarantee(isHumongous(word_size), "sanity");
2374 for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {
2375 // Let's use the existing mechanism for the allocation
2376 HeapWord* dummy_obj = humongous_obj_allocate(word_size);
2377 if (dummy_obj != NULL) {
2378 MemRegion mr(dummy_obj, word_size);
2379 CollectedHeap::fill_with_object(mr);
2380 } else {
2381 // If we can't allocate once, we probably cannot allocate
2382 // again. Let's get out of the loop.
2383 break;
2384 }
2385 }
2386 }
2387 #endif // !PRODUCT
2389 void G1CollectedHeap::increment_old_marking_cycles_started() {
2390 assert(_old_marking_cycles_started == _old_marking_cycles_completed ||
2391 _old_marking_cycles_started == _old_marking_cycles_completed + 1,
2392 err_msg("Wrong marking cycle count (started: %d, completed: %d)",
2393 _old_marking_cycles_started, _old_marking_cycles_completed));
2395 _old_marking_cycles_started++;
2396 }
2398 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent) {
2399 MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
2401 // We assume that if concurrent == true, then the caller is a
2402 // concurrent thread that was joined the Suspendible Thread
2403 // Set. If there's ever a cheap way to check this, we should add an
2404 // assert here.
2406 // Given that this method is called at the end of a Full GC or of a
2407 // concurrent cycle, and those can be nested (i.e., a Full GC can
2408 // interrupt a concurrent cycle), the number of full collections
2409 // completed should be either one (in the case where there was no
2410 // nesting) or two (when a Full GC interrupted a concurrent cycle)
2411 // behind the number of full collections started.
2413 // This is the case for the inner caller, i.e. a Full GC.
2414 assert(concurrent ||
2415 (_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||
2416 (_old_marking_cycles_started == _old_marking_cycles_completed + 2),
2417 err_msg("for inner caller (Full GC): _old_marking_cycles_started = %u "
2418 "is inconsistent with _old_marking_cycles_completed = %u",
2419 _old_marking_cycles_started, _old_marking_cycles_completed));
2421 // This is the case for the outer caller, i.e. the concurrent cycle.
2422 assert(!concurrent ||
2423 (_old_marking_cycles_started == _old_marking_cycles_completed + 1),
2424 err_msg("for outer caller (concurrent cycle): "
2425 "_old_marking_cycles_started = %u "
2426 "is inconsistent with _old_marking_cycles_completed = %u",
2427 _old_marking_cycles_started, _old_marking_cycles_completed));
2429 _old_marking_cycles_completed += 1;
2431 // We need to clear the "in_progress" flag in the CM thread before
2432 // we wake up any waiters (especially when ExplicitInvokesConcurrent
2433 // is set) so that if a waiter requests another System.gc() it doesn't
2434 // incorrectly see that a marking cycle is still in progress.
2435 if (concurrent) {
2436 _cmThread->clear_in_progress();
2437 }
2439 // This notify_all() will ensure that a thread that called
2440 // System.gc() with (with ExplicitGCInvokesConcurrent set or not)
2441 // and it's waiting for a full GC to finish will be woken up. It is
2442 // waiting in VM_G1IncCollectionPause::doit_epilogue().
2443 FullGCCount_lock->notify_all();
2444 }
2446 void G1CollectedHeap::register_concurrent_cycle_start(const Ticks& start_time) {
2447 _concurrent_cycle_started = true;
2448 _gc_timer_cm->register_gc_start(start_time);
2450 _gc_tracer_cm->report_gc_start(gc_cause(), _gc_timer_cm->gc_start());
2451 trace_heap_before_gc(_gc_tracer_cm);
2452 }
2454 void G1CollectedHeap::register_concurrent_cycle_end() {
2455 if (_concurrent_cycle_started) {
2456 if (_cm->has_aborted()) {
2457 _gc_tracer_cm->report_concurrent_mode_failure();
2458 }
2460 _gc_timer_cm->register_gc_end();
2461 _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions());
2463 _concurrent_cycle_started = false;
2464 }
2465 }
2467 void G1CollectedHeap::trace_heap_after_concurrent_cycle() {
2468 if (_concurrent_cycle_started) {
2469 trace_heap_after_gc(_gc_tracer_cm);
2470 }
2471 }
2473 G1YCType G1CollectedHeap::yc_type() {
2474 bool is_young = g1_policy()->gcs_are_young();
2475 bool is_initial_mark = g1_policy()->during_initial_mark_pause();
2476 bool is_during_mark = mark_in_progress();
2478 if (is_initial_mark) {
2479 return InitialMark;
2480 } else if (is_during_mark) {
2481 return DuringMark;
2482 } else if (is_young) {
2483 return Normal;
2484 } else {
2485 return Mixed;
2486 }
2487 }
2489 void G1CollectedHeap::collect(GCCause::Cause cause) {
2490 assert_heap_not_locked();
2492 unsigned int gc_count_before;
2493 unsigned int old_marking_count_before;
2494 bool retry_gc;
2496 do {
2497 retry_gc = false;
2499 {
2500 MutexLocker ml(Heap_lock);
2502 // Read the GC count while holding the Heap_lock
2503 gc_count_before = total_collections();
2504 old_marking_count_before = _old_marking_cycles_started;
2505 }
2507 if (should_do_concurrent_full_gc(cause)) {
2508 // Schedule an initial-mark evacuation pause that will start a
2509 // concurrent cycle. We're setting word_size to 0 which means that
2510 // we are not requesting a post-GC allocation.
2511 VM_G1IncCollectionPause op(gc_count_before,
2512 0, /* word_size */
2513 true, /* should_initiate_conc_mark */
2514 g1_policy()->max_pause_time_ms(),
2515 cause);
2517 VMThread::execute(&op);
2518 if (!op.pause_succeeded()) {
2519 if (old_marking_count_before == _old_marking_cycles_started) {
2520 retry_gc = op.should_retry_gc();
2521 } else {
2522 // A Full GC happened while we were trying to schedule the
2523 // initial-mark GC. No point in starting a new cycle given
2524 // that the whole heap was collected anyway.
2525 }
2527 if (retry_gc) {
2528 if (GC_locker::is_active_and_needs_gc()) {
2529 GC_locker::stall_until_clear();
2530 }
2531 }
2532 }
2533 } else {
2534 if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc
2535 DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
2537 // Schedule a standard evacuation pause. We're setting word_size
2538 // to 0 which means that we are not requesting a post-GC allocation.
2539 VM_G1IncCollectionPause op(gc_count_before,
2540 0, /* word_size */
2541 false, /* should_initiate_conc_mark */
2542 g1_policy()->max_pause_time_ms(),
2543 cause);
2544 VMThread::execute(&op);
2545 } else {
2546 // Schedule a Full GC.
2547 VM_G1CollectFull op(gc_count_before, old_marking_count_before, cause);
2548 VMThread::execute(&op);
2549 }
2550 }
2551 } while (retry_gc);
2552 }
2554 bool G1CollectedHeap::is_in(const void* p) const {
2555 if (_hrs.reserved().contains(p)) {
2556 // Given that we know that p is in the reserved space,
2557 // heap_region_containing_raw() should successfully
2558 // return the containing region.
2559 HeapRegion* hr = heap_region_containing_raw(p);
2560 return hr->is_in(p);
2561 } else {
2562 return false;
2563 }
2564 }
2566 #ifdef ASSERT
2567 bool G1CollectedHeap::is_in_exact(const void* p) const {
2568 bool contains = reserved_region().contains(p);
2569 bool available = _hrs.is_available(addr_to_region((HeapWord*)p));
2570 if (contains && available) {
2571 return true;
2572 } else {
2573 return false;
2574 }
2575 }
2576 #endif
2578 // Iteration functions.
2580 // Applies an ExtendedOopClosure onto all references of objects within a HeapRegion.
2582 class IterateOopClosureRegionClosure: public HeapRegionClosure {
2583 ExtendedOopClosure* _cl;
2584 public:
2585 IterateOopClosureRegionClosure(ExtendedOopClosure* cl) : _cl(cl) {}
2586 bool doHeapRegion(HeapRegion* r) {
2587 if (!r->continuesHumongous()) {
2588 r->oop_iterate(_cl);
2589 }
2590 return false;
2591 }
2592 };
2594 void G1CollectedHeap::oop_iterate(ExtendedOopClosure* cl) {
2595 IterateOopClosureRegionClosure blk(cl);
2596 heap_region_iterate(&blk);
2597 }
2599 // Iterates an ObjectClosure over all objects within a HeapRegion.
2601 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
2602 ObjectClosure* _cl;
2603 public:
2604 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
2605 bool doHeapRegion(HeapRegion* r) {
2606 if (! r->continuesHumongous()) {
2607 r->object_iterate(_cl);
2608 }
2609 return false;
2610 }
2611 };
2613 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
2614 IterateObjectClosureRegionClosure blk(cl);
2615 heap_region_iterate(&blk);
2616 }
2618 // Calls a SpaceClosure on a HeapRegion.
2620 class SpaceClosureRegionClosure: public HeapRegionClosure {
2621 SpaceClosure* _cl;
2622 public:
2623 SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {}
2624 bool doHeapRegion(HeapRegion* r) {
2625 _cl->do_space(r);
2626 return false;
2627 }
2628 };
2630 void G1CollectedHeap::space_iterate(SpaceClosure* cl) {
2631 SpaceClosureRegionClosure blk(cl);
2632 heap_region_iterate(&blk);
2633 }
2635 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
2636 _hrs.iterate(cl);
2637 }
2639 void
2640 G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,
2641 uint worker_id,
2642 uint num_workers,
2643 jint claim_value) const {
2644 _hrs.par_iterate(cl, worker_id, num_workers, claim_value);
2645 }
2647 class ResetClaimValuesClosure: public HeapRegionClosure {
2648 public:
2649 bool doHeapRegion(HeapRegion* r) {
2650 r->set_claim_value(HeapRegion::InitialClaimValue);
2651 return false;
2652 }
2653 };
2655 void G1CollectedHeap::reset_heap_region_claim_values() {
2656 ResetClaimValuesClosure blk;
2657 heap_region_iterate(&blk);
2658 }
2660 void G1CollectedHeap::reset_cset_heap_region_claim_values() {
2661 ResetClaimValuesClosure blk;
2662 collection_set_iterate(&blk);
2663 }
2665 #ifdef ASSERT
2666 // This checks whether all regions in the heap have the correct claim
2667 // value. I also piggy-backed on this a check to ensure that the
2668 // humongous_start_region() information on "continues humongous"
2669 // regions is correct.
2671 class CheckClaimValuesClosure : public HeapRegionClosure {
2672 private:
2673 jint _claim_value;
2674 uint _failures;
2675 HeapRegion* _sh_region;
2677 public:
2678 CheckClaimValuesClosure(jint claim_value) :
2679 _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
2680 bool doHeapRegion(HeapRegion* r) {
2681 if (r->claim_value() != _claim_value) {
2682 gclog_or_tty->print_cr("Region " HR_FORMAT ", "
2683 "claim value = %d, should be %d",
2684 HR_FORMAT_PARAMS(r),
2685 r->claim_value(), _claim_value);
2686 ++_failures;
2687 }
2688 if (!r->isHumongous()) {
2689 _sh_region = NULL;
2690 } else if (r->startsHumongous()) {
2691 _sh_region = r;
2692 } else if (r->continuesHumongous()) {
2693 if (r->humongous_start_region() != _sh_region) {
2694 gclog_or_tty->print_cr("Region " HR_FORMAT ", "
2695 "HS = "PTR_FORMAT", should be "PTR_FORMAT,
2696 HR_FORMAT_PARAMS(r),
2697 r->humongous_start_region(),
2698 _sh_region);
2699 ++_failures;
2700 }
2701 }
2702 return false;
2703 }
2704 uint failures() { return _failures; }
2705 };
2707 bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
2708 CheckClaimValuesClosure cl(claim_value);
2709 heap_region_iterate(&cl);
2710 return cl.failures() == 0;
2711 }
2713 class CheckClaimValuesInCSetHRClosure: public HeapRegionClosure {
2714 private:
2715 jint _claim_value;
2716 uint _failures;
2718 public:
2719 CheckClaimValuesInCSetHRClosure(jint claim_value) :
2720 _claim_value(claim_value), _failures(0) { }
2722 uint failures() { return _failures; }
2724 bool doHeapRegion(HeapRegion* hr) {
2725 assert(hr->in_collection_set(), "how?");
2726 assert(!hr->isHumongous(), "H-region in CSet");
2727 if (hr->claim_value() != _claim_value) {
2728 gclog_or_tty->print_cr("CSet Region " HR_FORMAT ", "
2729 "claim value = %d, should be %d",
2730 HR_FORMAT_PARAMS(hr),
2731 hr->claim_value(), _claim_value);
2732 _failures += 1;
2733 }
2734 return false;
2735 }
2736 };
2738 bool G1CollectedHeap::check_cset_heap_region_claim_values(jint claim_value) {
2739 CheckClaimValuesInCSetHRClosure cl(claim_value);
2740 collection_set_iterate(&cl);
2741 return cl.failures() == 0;
2742 }
2743 #endif // ASSERT
2745 // Clear the cached CSet starting regions and (more importantly)
2746 // the time stamps. Called when we reset the GC time stamp.
2747 void G1CollectedHeap::clear_cset_start_regions() {
2748 assert(_worker_cset_start_region != NULL, "sanity");
2749 assert(_worker_cset_start_region_time_stamp != NULL, "sanity");
2751 int n_queues = MAX2((int)ParallelGCThreads, 1);
2752 for (int i = 0; i < n_queues; i++) {
2753 _worker_cset_start_region[i] = NULL;
2754 _worker_cset_start_region_time_stamp[i] = 0;
2755 }
2756 }
2758 // Given the id of a worker, obtain or calculate a suitable
2759 // starting region for iterating over the current collection set.
2760 HeapRegion* G1CollectedHeap::start_cset_region_for_worker(uint worker_i) {
2761 assert(get_gc_time_stamp() > 0, "should have been updated by now");
2763 HeapRegion* result = NULL;
2764 unsigned gc_time_stamp = get_gc_time_stamp();
2766 if (_worker_cset_start_region_time_stamp[worker_i] == gc_time_stamp) {
2767 // Cached starting region for current worker was set
2768 // during the current pause - so it's valid.
2769 // Note: the cached starting heap region may be NULL
2770 // (when the collection set is empty).
2771 result = _worker_cset_start_region[worker_i];
2772 assert(result == NULL || result->in_collection_set(), "sanity");
2773 return result;
2774 }
2776 // The cached entry was not valid so let's calculate
2777 // a suitable starting heap region for this worker.
2779 // We want the parallel threads to start their collection
2780 // set iteration at different collection set regions to
2781 // avoid contention.
2782 // If we have:
2783 // n collection set regions
2784 // p threads
2785 // Then thread t will start at region floor ((t * n) / p)
2787 result = g1_policy()->collection_set();
2788 if (G1CollectedHeap::use_parallel_gc_threads()) {
2789 uint cs_size = g1_policy()->cset_region_length();
2790 uint active_workers = workers()->active_workers();
2791 assert(UseDynamicNumberOfGCThreads ||
2792 active_workers == workers()->total_workers(),
2793 "Unless dynamic should use total workers");
2795 uint end_ind = (cs_size * worker_i) / active_workers;
2796 uint start_ind = 0;
2798 if (worker_i > 0 &&
2799 _worker_cset_start_region_time_stamp[worker_i - 1] == gc_time_stamp) {
2800 // Previous workers starting region is valid
2801 // so let's iterate from there
2802 start_ind = (cs_size * (worker_i - 1)) / active_workers;
2803 result = _worker_cset_start_region[worker_i - 1];
2804 }
2806 for (uint i = start_ind; i < end_ind; i++) {
2807 result = result->next_in_collection_set();
2808 }
2809 }
2811 // Note: the calculated starting heap region may be NULL
2812 // (when the collection set is empty).
2813 assert(result == NULL || result->in_collection_set(), "sanity");
2814 assert(_worker_cset_start_region_time_stamp[worker_i] != gc_time_stamp,
2815 "should be updated only once per pause");
2816 _worker_cset_start_region[worker_i] = result;
2817 OrderAccess::storestore();
2818 _worker_cset_start_region_time_stamp[worker_i] = gc_time_stamp;
2819 return result;
2820 }
2822 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {
2823 HeapRegion* r = g1_policy()->collection_set();
2824 while (r != NULL) {
2825 HeapRegion* next = r->next_in_collection_set();
2826 if (cl->doHeapRegion(r)) {
2827 cl->incomplete();
2828 return;
2829 }
2830 r = next;
2831 }
2832 }
2834 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,
2835 HeapRegionClosure *cl) {
2836 if (r == NULL) {
2837 // The CSet is empty so there's nothing to do.
2838 return;
2839 }
2841 assert(r->in_collection_set(),
2842 "Start region must be a member of the collection set.");
2843 HeapRegion* cur = r;
2844 while (cur != NULL) {
2845 HeapRegion* next = cur->next_in_collection_set();
2846 if (cl->doHeapRegion(cur) && false) {
2847 cl->incomplete();
2848 return;
2849 }
2850 cur = next;
2851 }
2852 cur = g1_policy()->collection_set();
2853 while (cur != r) {
2854 HeapRegion* next = cur->next_in_collection_set();
2855 if (cl->doHeapRegion(cur) && false) {
2856 cl->incomplete();
2857 return;
2858 }
2859 cur = next;
2860 }
2861 }
2863 HeapRegion* G1CollectedHeap::next_compaction_region(const HeapRegion* from) const {
2864 HeapRegion* result = _hrs.next_region_in_heap(from);
2865 while (result != NULL && result->isHumongous()) {
2866 result = _hrs.next_region_in_heap(result);
2867 }
2868 return result;
2869 }
2871 Space* G1CollectedHeap::space_containing(const void* addr) const {
2872 return heap_region_containing(addr);
2873 }
2875 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
2876 Space* sp = space_containing(addr);
2877 return sp->block_start(addr);
2878 }
2880 size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
2881 Space* sp = space_containing(addr);
2882 return sp->block_size(addr);
2883 }
2885 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
2886 Space* sp = space_containing(addr);
2887 return sp->block_is_obj(addr);
2888 }
2890 bool G1CollectedHeap::supports_tlab_allocation() const {
2891 return true;
2892 }
2894 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
2895 return (_g1_policy->young_list_target_length() - young_list()->survivor_length()) * HeapRegion::GrainBytes;
2896 }
2898 size_t G1CollectedHeap::tlab_used(Thread* ignored) const {
2899 return young_list()->eden_used_bytes();
2900 }
2902 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size
2903 // must be smaller than the humongous object limit.
2904 size_t G1CollectedHeap::max_tlab_size() const {
2905 return align_size_down(_humongous_object_threshold_in_words - 1, MinObjAlignment);
2906 }
2908 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
2909 // Return the remaining space in the cur alloc region, but not less than
2910 // the min TLAB size.
2912 // Also, this value can be at most the humongous object threshold,
2913 // since we can't allow tlabs to grow big enough to accommodate
2914 // humongous objects.
2916 HeapRegion* hr = _mutator_alloc_region.get();
2917 size_t max_tlab = max_tlab_size() * wordSize;
2918 if (hr == NULL) {
2919 return max_tlab;
2920 } else {
2921 return MIN2(MAX2(hr->free(), (size_t) MinTLABSize), max_tlab);
2922 }
2923 }
2925 size_t G1CollectedHeap::max_capacity() const {
2926 return _hrs.reserved().byte_size();
2927 }
2929 jlong G1CollectedHeap::millis_since_last_gc() {
2930 // assert(false, "NYI");
2931 return 0;
2932 }
2934 void G1CollectedHeap::prepare_for_verify() {
2935 if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
2936 ensure_parsability(false);
2937 }
2938 g1_rem_set()->prepare_for_verify();
2939 }
2941 bool G1CollectedHeap::allocated_since_marking(oop obj, HeapRegion* hr,
2942 VerifyOption vo) {
2943 switch (vo) {
2944 case VerifyOption_G1UsePrevMarking:
2945 return hr->obj_allocated_since_prev_marking(obj);
2946 case VerifyOption_G1UseNextMarking:
2947 return hr->obj_allocated_since_next_marking(obj);
2948 case VerifyOption_G1UseMarkWord:
2949 return false;
2950 default:
2951 ShouldNotReachHere();
2952 }
2953 return false; // keep some compilers happy
2954 }
2956 HeapWord* G1CollectedHeap::top_at_mark_start(HeapRegion* hr, VerifyOption vo) {
2957 switch (vo) {
2958 case VerifyOption_G1UsePrevMarking: return hr->prev_top_at_mark_start();
2959 case VerifyOption_G1UseNextMarking: return hr->next_top_at_mark_start();
2960 case VerifyOption_G1UseMarkWord: return NULL;
2961 default: ShouldNotReachHere();
2962 }
2963 return NULL; // keep some compilers happy
2964 }
2966 bool G1CollectedHeap::is_marked(oop obj, VerifyOption vo) {
2967 switch (vo) {
2968 case VerifyOption_G1UsePrevMarking: return isMarkedPrev(obj);
2969 case VerifyOption_G1UseNextMarking: return isMarkedNext(obj);
2970 case VerifyOption_G1UseMarkWord: return obj->is_gc_marked();
2971 default: ShouldNotReachHere();
2972 }
2973 return false; // keep some compilers happy
2974 }
2976 const char* G1CollectedHeap::top_at_mark_start_str(VerifyOption vo) {
2977 switch (vo) {
2978 case VerifyOption_G1UsePrevMarking: return "PTAMS";
2979 case VerifyOption_G1UseNextMarking: return "NTAMS";
2980 case VerifyOption_G1UseMarkWord: return "NONE";
2981 default: ShouldNotReachHere();
2982 }
2983 return NULL; // keep some compilers happy
2984 }
2986 class VerifyRootsClosure: public OopClosure {
2987 private:
2988 G1CollectedHeap* _g1h;
2989 VerifyOption _vo;
2990 bool _failures;
2991 public:
2992 // _vo == UsePrevMarking -> use "prev" marking information,
2993 // _vo == UseNextMarking -> use "next" marking information,
2994 // _vo == UseMarkWord -> use mark word from object header.
2995 VerifyRootsClosure(VerifyOption vo) :
2996 _g1h(G1CollectedHeap::heap()),
2997 _vo(vo),
2998 _failures(false) { }
3000 bool failures() { return _failures; }
3002 template <class T> void do_oop_nv(T* p) {
3003 T heap_oop = oopDesc::load_heap_oop(p);
3004 if (!oopDesc::is_null(heap_oop)) {
3005 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
3006 if (_g1h->is_obj_dead_cond(obj, _vo)) {
3007 gclog_or_tty->print_cr("Root location "PTR_FORMAT" "
3008 "points to dead obj "PTR_FORMAT, p, (void*) obj);
3009 if (_vo == VerifyOption_G1UseMarkWord) {
3010 gclog_or_tty->print_cr(" Mark word: "PTR_FORMAT, (void*)(obj->mark()));
3011 }
3012 obj->print_on(gclog_or_tty);
3013 _failures = true;
3014 }
3015 }
3016 }
3018 void do_oop(oop* p) { do_oop_nv(p); }
3019 void do_oop(narrowOop* p) { do_oop_nv(p); }
3020 };
3022 class G1VerifyCodeRootOopClosure: public OopClosure {
3023 G1CollectedHeap* _g1h;
3024 OopClosure* _root_cl;
3025 nmethod* _nm;
3026 VerifyOption _vo;
3027 bool _failures;
3029 template <class T> void do_oop_work(T* p) {
3030 // First verify that this root is live
3031 _root_cl->do_oop(p);
3033 if (!G1VerifyHeapRegionCodeRoots) {
3034 // We're not verifying the code roots attached to heap region.
3035 return;
3036 }
3038 // Don't check the code roots during marking verification in a full GC
3039 if (_vo == VerifyOption_G1UseMarkWord) {
3040 return;
3041 }
3043 // Now verify that the current nmethod (which contains p) is
3044 // in the code root list of the heap region containing the
3045 // object referenced by p.
3047 T heap_oop = oopDesc::load_heap_oop(p);
3048 if (!oopDesc::is_null(heap_oop)) {
3049 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
3051 // Now fetch the region containing the object
3052 HeapRegion* hr = _g1h->heap_region_containing(obj);
3053 HeapRegionRemSet* hrrs = hr->rem_set();
3054 // Verify that the strong code root list for this region
3055 // contains the nmethod
3056 if (!hrrs->strong_code_roots_list_contains(_nm)) {
3057 gclog_or_tty->print_cr("Code root location "PTR_FORMAT" "
3058 "from nmethod "PTR_FORMAT" not in strong "
3059 "code roots for region ["PTR_FORMAT","PTR_FORMAT")",
3060 p, _nm, hr->bottom(), hr->end());
3061 _failures = true;
3062 }
3063 }
3064 }
3066 public:
3067 G1VerifyCodeRootOopClosure(G1CollectedHeap* g1h, OopClosure* root_cl, VerifyOption vo):
3068 _g1h(g1h), _root_cl(root_cl), _vo(vo), _nm(NULL), _failures(false) {}
3070 void do_oop(oop* p) { do_oop_work(p); }
3071 void do_oop(narrowOop* p) { do_oop_work(p); }
3073 void set_nmethod(nmethod* nm) { _nm = nm; }
3074 bool failures() { return _failures; }
3075 };
3077 class G1VerifyCodeRootBlobClosure: public CodeBlobClosure {
3078 G1VerifyCodeRootOopClosure* _oop_cl;
3080 public:
3081 G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure* oop_cl):
3082 _oop_cl(oop_cl) {}
3084 void do_code_blob(CodeBlob* cb) {
3085 nmethod* nm = cb->as_nmethod_or_null();
3086 if (nm != NULL) {
3087 _oop_cl->set_nmethod(nm);
3088 nm->oops_do(_oop_cl);
3089 }
3090 }
3091 };
3093 class YoungRefCounterClosure : public OopClosure {
3094 G1CollectedHeap* _g1h;
3095 int _count;
3096 public:
3097 YoungRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {}
3098 void do_oop(oop* p) { if (_g1h->is_in_young(*p)) { _count++; } }
3099 void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3101 int count() { return _count; }
3102 void reset_count() { _count = 0; };
3103 };
3105 class VerifyKlassClosure: public KlassClosure {
3106 YoungRefCounterClosure _young_ref_counter_closure;
3107 OopClosure *_oop_closure;
3108 public:
3109 VerifyKlassClosure(G1CollectedHeap* g1h, OopClosure* cl) : _young_ref_counter_closure(g1h), _oop_closure(cl) {}
3110 void do_klass(Klass* k) {
3111 k->oops_do(_oop_closure);
3113 _young_ref_counter_closure.reset_count();
3114 k->oops_do(&_young_ref_counter_closure);
3115 if (_young_ref_counter_closure.count() > 0) {
3116 guarantee(k->has_modified_oops(), err_msg("Klass %p, has young refs but is not dirty.", k));
3117 }
3118 }
3119 };
3121 class VerifyLivenessOopClosure: public OopClosure {
3122 G1CollectedHeap* _g1h;
3123 VerifyOption _vo;
3124 public:
3125 VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo):
3126 _g1h(g1h), _vo(vo)
3127 { }
3128 void do_oop(narrowOop *p) { do_oop_work(p); }
3129 void do_oop( oop *p) { do_oop_work(p); }
3131 template <class T> void do_oop_work(T *p) {
3132 oop obj = oopDesc::load_decode_heap_oop(p);
3133 guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo),
3134 "Dead object referenced by a not dead object");
3135 }
3136 };
3138 class VerifyObjsInRegionClosure: public ObjectClosure {
3139 private:
3140 G1CollectedHeap* _g1h;
3141 size_t _live_bytes;
3142 HeapRegion *_hr;
3143 VerifyOption _vo;
3144 public:
3145 // _vo == UsePrevMarking -> use "prev" marking information,
3146 // _vo == UseNextMarking -> use "next" marking information,
3147 // _vo == UseMarkWord -> use mark word from object header.
3148 VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo)
3149 : _live_bytes(0), _hr(hr), _vo(vo) {
3150 _g1h = G1CollectedHeap::heap();
3151 }
3152 void do_object(oop o) {
3153 VerifyLivenessOopClosure isLive(_g1h, _vo);
3154 assert(o != NULL, "Huh?");
3155 if (!_g1h->is_obj_dead_cond(o, _vo)) {
3156 // If the object is alive according to the mark word,
3157 // then verify that the marking information agrees.
3158 // Note we can't verify the contra-positive of the
3159 // above: if the object is dead (according to the mark
3160 // word), it may not be marked, or may have been marked
3161 // but has since became dead, or may have been allocated
3162 // since the last marking.
3163 if (_vo == VerifyOption_G1UseMarkWord) {
3164 guarantee(!_g1h->is_obj_dead(o), "mark word and concurrent mark mismatch");
3165 }
3167 o->oop_iterate_no_header(&isLive);
3168 if (!_hr->obj_allocated_since_prev_marking(o)) {
3169 size_t obj_size = o->size(); // Make sure we don't overflow
3170 _live_bytes += (obj_size * HeapWordSize);
3171 }
3172 }
3173 }
3174 size_t live_bytes() { return _live_bytes; }
3175 };
3177 class PrintObjsInRegionClosure : public ObjectClosure {
3178 HeapRegion *_hr;
3179 G1CollectedHeap *_g1;
3180 public:
3181 PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) {
3182 _g1 = G1CollectedHeap::heap();
3183 };
3185 void do_object(oop o) {
3186 if (o != NULL) {
3187 HeapWord *start = (HeapWord *) o;
3188 size_t word_sz = o->size();
3189 gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT
3190 " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",
3191 (void*) o, word_sz,
3192 _g1->isMarkedPrev(o),
3193 _g1->isMarkedNext(o),
3194 _hr->obj_allocated_since_prev_marking(o));
3195 HeapWord *end = start + word_sz;
3196 HeapWord *cur;
3197 int *val;
3198 for (cur = start; cur < end; cur++) {
3199 val = (int *) cur;
3200 gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val);
3201 }
3202 }
3203 }
3204 };
3206 class VerifyRegionClosure: public HeapRegionClosure {
3207 private:
3208 bool _par;
3209 VerifyOption _vo;
3210 bool _failures;
3211 public:
3212 // _vo == UsePrevMarking -> use "prev" marking information,
3213 // _vo == UseNextMarking -> use "next" marking information,
3214 // _vo == UseMarkWord -> use mark word from object header.
3215 VerifyRegionClosure(bool par, VerifyOption vo)
3216 : _par(par),
3217 _vo(vo),
3218 _failures(false) {}
3220 bool failures() {
3221 return _failures;
3222 }
3224 bool doHeapRegion(HeapRegion* r) {
3225 if (!r->continuesHumongous()) {
3226 bool failures = false;
3227 r->verify(_vo, &failures);
3228 if (failures) {
3229 _failures = true;
3230 } else {
3231 VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo);
3232 r->object_iterate(¬_dead_yet_cl);
3233 if (_vo != VerifyOption_G1UseNextMarking) {
3234 if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
3235 gclog_or_tty->print_cr("["PTR_FORMAT","PTR_FORMAT"] "
3236 "max_live_bytes "SIZE_FORMAT" "
3237 "< calculated "SIZE_FORMAT,
3238 r->bottom(), r->end(),
3239 r->max_live_bytes(),
3240 not_dead_yet_cl.live_bytes());
3241 _failures = true;
3242 }
3243 } else {
3244 // When vo == UseNextMarking we cannot currently do a sanity
3245 // check on the live bytes as the calculation has not been
3246 // finalized yet.
3247 }
3248 }
3249 }
3250 return false; // stop the region iteration if we hit a failure
3251 }
3252 };
3254 // This is the task used for parallel verification of the heap regions
3256 class G1ParVerifyTask: public AbstractGangTask {
3257 private:
3258 G1CollectedHeap* _g1h;
3259 VerifyOption _vo;
3260 bool _failures;
3262 public:
3263 // _vo == UsePrevMarking -> use "prev" marking information,
3264 // _vo == UseNextMarking -> use "next" marking information,
3265 // _vo == UseMarkWord -> use mark word from object header.
3266 G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :
3267 AbstractGangTask("Parallel verify task"),
3268 _g1h(g1h),
3269 _vo(vo),
3270 _failures(false) { }
3272 bool failures() {
3273 return _failures;
3274 }
3276 void work(uint worker_id) {
3277 HandleMark hm;
3278 VerifyRegionClosure blk(true, _vo);
3279 _g1h->heap_region_par_iterate_chunked(&blk, worker_id,
3280 _g1h->workers()->active_workers(),
3281 HeapRegion::ParVerifyClaimValue);
3282 if (blk.failures()) {
3283 _failures = true;
3284 }
3285 }
3286 };
3288 void G1CollectedHeap::verify(bool silent, VerifyOption vo) {
3289 if (SafepointSynchronize::is_at_safepoint()) {
3290 assert(Thread::current()->is_VM_thread(),
3291 "Expected to be executed serially by the VM thread at this point");
3293 if (!silent) { gclog_or_tty->print("Roots "); }
3294 VerifyRootsClosure rootsCl(vo);
3295 VerifyKlassClosure klassCl(this, &rootsCl);
3296 CLDToKlassAndOopClosure cldCl(&klassCl, &rootsCl, false);
3298 // We apply the relevant closures to all the oops in the
3299 // system dictionary, class loader data graph, the string table
3300 // and the nmethods in the code cache.
3301 G1VerifyCodeRootOopClosure codeRootsCl(this, &rootsCl, vo);
3302 G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl);
3304 process_all_roots(true, // activate StrongRootsScope
3305 SO_AllCodeCache, // roots scanning options
3306 &rootsCl,
3307 &cldCl,
3308 &blobsCl);
3310 bool failures = rootsCl.failures() || codeRootsCl.failures();
3312 if (vo != VerifyOption_G1UseMarkWord) {
3313 // If we're verifying during a full GC then the region sets
3314 // will have been torn down at the start of the GC. Therefore
3315 // verifying the region sets will fail. So we only verify
3316 // the region sets when not in a full GC.
3317 if (!silent) { gclog_or_tty->print("HeapRegionSets "); }
3318 verify_region_sets();
3319 }
3321 if (!silent) { gclog_or_tty->print("HeapRegions "); }
3322 if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
3323 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3324 "sanity check");
3326 G1ParVerifyTask task(this, vo);
3327 assert(UseDynamicNumberOfGCThreads ||
3328 workers()->active_workers() == workers()->total_workers(),
3329 "If not dynamic should be using all the workers");
3330 int n_workers = workers()->active_workers();
3331 set_par_threads(n_workers);
3332 workers()->run_task(&task);
3333 set_par_threads(0);
3334 if (task.failures()) {
3335 failures = true;
3336 }
3338 // Checks that the expected amount of parallel work was done.
3339 // The implication is that n_workers is > 0.
3340 assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),
3341 "sanity check");
3343 reset_heap_region_claim_values();
3345 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3346 "sanity check");
3347 } else {
3348 VerifyRegionClosure blk(false, vo);
3349 heap_region_iterate(&blk);
3350 if (blk.failures()) {
3351 failures = true;
3352 }
3353 }
3354 if (!silent) gclog_or_tty->print("RemSet ");
3355 rem_set()->verify();
3357 if (G1StringDedup::is_enabled()) {
3358 if (!silent) gclog_or_tty->print("StrDedup ");
3359 G1StringDedup::verify();
3360 }
3362 if (failures) {
3363 gclog_or_tty->print_cr("Heap:");
3364 // It helps to have the per-region information in the output to
3365 // help us track down what went wrong. This is why we call
3366 // print_extended_on() instead of print_on().
3367 print_extended_on(gclog_or_tty);
3368 gclog_or_tty->cr();
3369 #ifndef PRODUCT
3370 if (VerifyDuringGC && G1VerifyDuringGCPrintReachable) {
3371 concurrent_mark()->print_reachable("at-verification-failure",
3372 vo, false /* all */);
3373 }
3374 #endif
3375 gclog_or_tty->flush();
3376 }
3377 guarantee(!failures, "there should not have been any failures");
3378 } else {
3379 if (!silent) {
3380 gclog_or_tty->print("(SKIPPING Roots, HeapRegionSets, HeapRegions, RemSet");
3381 if (G1StringDedup::is_enabled()) {
3382 gclog_or_tty->print(", StrDedup");
3383 }
3384 gclog_or_tty->print(") ");
3385 }
3386 }
3387 }
3389 void G1CollectedHeap::verify(bool silent) {
3390 verify(silent, VerifyOption_G1UsePrevMarking);
3391 }
3393 double G1CollectedHeap::verify(bool guard, const char* msg) {
3394 double verify_time_ms = 0.0;
3396 if (guard && total_collections() >= VerifyGCStartAt) {
3397 double verify_start = os::elapsedTime();
3398 HandleMark hm; // Discard invalid handles created during verification
3399 prepare_for_verify();
3400 Universe::verify(VerifyOption_G1UsePrevMarking, msg);
3401 verify_time_ms = (os::elapsedTime() - verify_start) * 1000;
3402 }
3404 return verify_time_ms;
3405 }
3407 void G1CollectedHeap::verify_before_gc() {
3408 double verify_time_ms = verify(VerifyBeforeGC, " VerifyBeforeGC:");
3409 g1_policy()->phase_times()->record_verify_before_time_ms(verify_time_ms);
3410 }
3412 void G1CollectedHeap::verify_after_gc() {
3413 double verify_time_ms = verify(VerifyAfterGC, " VerifyAfterGC:");
3414 g1_policy()->phase_times()->record_verify_after_time_ms(verify_time_ms);
3415 }
3417 class PrintRegionClosure: public HeapRegionClosure {
3418 outputStream* _st;
3419 public:
3420 PrintRegionClosure(outputStream* st) : _st(st) {}
3421 bool doHeapRegion(HeapRegion* r) {
3422 r->print_on(_st);
3423 return false;
3424 }
3425 };
3427 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
3428 const HeapRegion* hr,
3429 const VerifyOption vo) const {
3430 switch (vo) {
3431 case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);
3432 case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);
3433 case VerifyOption_G1UseMarkWord: return !obj->is_gc_marked();
3434 default: ShouldNotReachHere();
3435 }
3436 return false; // keep some compilers happy
3437 }
3439 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
3440 const VerifyOption vo) const {
3441 switch (vo) {
3442 case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);
3443 case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);
3444 case VerifyOption_G1UseMarkWord: return !obj->is_gc_marked();
3445 default: ShouldNotReachHere();
3446 }
3447 return false; // keep some compilers happy
3448 }
3450 void G1CollectedHeap::print_on(outputStream* st) const {
3451 st->print(" %-20s", "garbage-first heap");
3452 st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
3453 capacity()/K, used_unlocked()/K);
3454 st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")",
3455 _hrs.reserved().start(),
3456 _hrs.reserved().start() + _hrs.length() + HeapRegion::GrainWords,
3457 _hrs.reserved().end());
3458 st->cr();
3459 st->print(" region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);
3460 uint young_regions = _young_list->length();
3461 st->print("%u young (" SIZE_FORMAT "K), ", young_regions,
3462 (size_t) young_regions * HeapRegion::GrainBytes / K);
3463 uint survivor_regions = g1_policy()->recorded_survivor_regions();
3464 st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,
3465 (size_t) survivor_regions * HeapRegion::GrainBytes / K);
3466 st->cr();
3467 MetaspaceAux::print_on(st);
3468 }
3470 void G1CollectedHeap::print_extended_on(outputStream* st) const {
3471 print_on(st);
3473 // Print the per-region information.
3474 st->cr();
3475 st->print_cr("Heap Regions: (Y=young(eden), SU=young(survivor), "
3476 "HS=humongous(starts), HC=humongous(continues), "
3477 "CS=collection set, F=free, TS=gc time stamp, "
3478 "PTAMS=previous top-at-mark-start, "
3479 "NTAMS=next top-at-mark-start)");
3480 PrintRegionClosure blk(st);
3481 heap_region_iterate(&blk);
3482 }
3484 void G1CollectedHeap::print_on_error(outputStream* st) const {
3485 this->CollectedHeap::print_on_error(st);
3487 if (_cm != NULL) {
3488 st->cr();
3489 _cm->print_on_error(st);
3490 }
3491 }
3493 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
3494 if (G1CollectedHeap::use_parallel_gc_threads()) {
3495 workers()->print_worker_threads_on(st);
3496 }
3497 _cmThread->print_on(st);
3498 st->cr();
3499 _cm->print_worker_threads_on(st);
3500 _cg1r->print_worker_threads_on(st);
3501 if (G1StringDedup::is_enabled()) {
3502 G1StringDedup::print_worker_threads_on(st);
3503 }
3504 }
3506 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
3507 if (G1CollectedHeap::use_parallel_gc_threads()) {
3508 workers()->threads_do(tc);
3509 }
3510 tc->do_thread(_cmThread);
3511 _cg1r->threads_do(tc);
3512 if (G1StringDedup::is_enabled()) {
3513 G1StringDedup::threads_do(tc);
3514 }
3515 }
3517 void G1CollectedHeap::print_tracing_info() const {
3518 // We'll overload this to mean "trace GC pause statistics."
3519 if (TraceGen0Time || TraceGen1Time) {
3520 // The "G1CollectorPolicy" is keeping track of these stats, so delegate
3521 // to that.
3522 g1_policy()->print_tracing_info();
3523 }
3524 if (G1SummarizeRSetStats) {
3525 g1_rem_set()->print_summary_info();
3526 }
3527 if (G1SummarizeConcMark) {
3528 concurrent_mark()->print_summary_info();
3529 }
3530 g1_policy()->print_yg_surv_rate_info();
3531 SpecializationStats::print();
3532 }
3534 #ifndef PRODUCT
3535 // Helpful for debugging RSet issues.
3537 class PrintRSetsClosure : public HeapRegionClosure {
3538 private:
3539 const char* _msg;
3540 size_t _occupied_sum;
3542 public:
3543 bool doHeapRegion(HeapRegion* r) {
3544 HeapRegionRemSet* hrrs = r->rem_set();
3545 size_t occupied = hrrs->occupied();
3546 _occupied_sum += occupied;
3548 gclog_or_tty->print_cr("Printing RSet for region "HR_FORMAT,
3549 HR_FORMAT_PARAMS(r));
3550 if (occupied == 0) {
3551 gclog_or_tty->print_cr(" RSet is empty");
3552 } else {
3553 hrrs->print();
3554 }
3555 gclog_or_tty->print_cr("----------");
3556 return false;
3557 }
3559 PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
3560 gclog_or_tty->cr();
3561 gclog_or_tty->print_cr("========================================");
3562 gclog_or_tty->print_cr("%s", msg);
3563 gclog_or_tty->cr();
3564 }
3566 ~PrintRSetsClosure() {
3567 gclog_or_tty->print_cr("Occupied Sum: "SIZE_FORMAT, _occupied_sum);
3568 gclog_or_tty->print_cr("========================================");
3569 gclog_or_tty->cr();
3570 }
3571 };
3573 void G1CollectedHeap::print_cset_rsets() {
3574 PrintRSetsClosure cl("Printing CSet RSets");
3575 collection_set_iterate(&cl);
3576 }
3578 void G1CollectedHeap::print_all_rsets() {
3579 PrintRSetsClosure cl("Printing All RSets");;
3580 heap_region_iterate(&cl);
3581 }
3582 #endif // PRODUCT
3584 G1CollectedHeap* G1CollectedHeap::heap() {
3585 assert(_sh->kind() == CollectedHeap::G1CollectedHeap,
3586 "not a garbage-first heap");
3587 return _g1h;
3588 }
3590 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {
3591 // always_do_update_barrier = false;
3592 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
3593 // Fill TLAB's and such
3594 accumulate_statistics_all_tlabs();
3595 ensure_parsability(true);
3597 if (G1SummarizeRSetStats && (G1SummarizeRSetStatsPeriod > 0) &&
3598 (total_collections() % G1SummarizeRSetStatsPeriod == 0)) {
3599 g1_rem_set()->print_periodic_summary_info("Before GC RS summary");
3600 }
3601 }
3603 void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) {
3605 if (G1SummarizeRSetStats &&
3606 (G1SummarizeRSetStatsPeriod > 0) &&
3607 // we are at the end of the GC. Total collections has already been increased.
3608 ((total_collections() - 1) % G1SummarizeRSetStatsPeriod == 0)) {
3609 g1_rem_set()->print_periodic_summary_info("After GC RS summary");
3610 }
3612 // FIXME: what is this about?
3613 // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
3614 // is set.
3615 COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),
3616 "derived pointer present"));
3617 // always_do_update_barrier = true;
3619 resize_all_tlabs();
3621 // We have just completed a GC. Update the soft reference
3622 // policy with the new heap occupancy
3623 Universe::update_heap_info_at_gc();
3624 }
3626 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
3627 unsigned int gc_count_before,
3628 bool* succeeded,
3629 GCCause::Cause gc_cause) {
3630 assert_heap_not_locked_and_not_at_safepoint();
3631 g1_policy()->record_stop_world_start();
3632 VM_G1IncCollectionPause op(gc_count_before,
3633 word_size,
3634 false, /* should_initiate_conc_mark */
3635 g1_policy()->max_pause_time_ms(),
3636 gc_cause);
3637 VMThread::execute(&op);
3639 HeapWord* result = op.result();
3640 bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded();
3641 assert(result == NULL || ret_succeeded,
3642 "the result should be NULL if the VM did not succeed");
3643 *succeeded = ret_succeeded;
3645 assert_heap_not_locked();
3646 return result;
3647 }
3649 void
3650 G1CollectedHeap::doConcurrentMark() {
3651 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
3652 if (!_cmThread->in_progress()) {
3653 _cmThread->set_started();
3654 CGC_lock->notify();
3655 }
3656 }
3658 size_t G1CollectedHeap::pending_card_num() {
3659 size_t extra_cards = 0;
3660 JavaThread *curr = Threads::first();
3661 while (curr != NULL) {
3662 DirtyCardQueue& dcq = curr->dirty_card_queue();
3663 extra_cards += dcq.size();
3664 curr = curr->next();
3665 }
3666 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
3667 size_t buffer_size = dcqs.buffer_size();
3668 size_t buffer_num = dcqs.completed_buffers_num();
3670 // PtrQueueSet::buffer_size() and PtrQueue:size() return sizes
3671 // in bytes - not the number of 'entries'. We need to convert
3672 // into a number of cards.
3673 return (buffer_size * buffer_num + extra_cards) / oopSize;
3674 }
3676 size_t G1CollectedHeap::cards_scanned() {
3677 return g1_rem_set()->cardsScanned();
3678 }
3680 bool G1CollectedHeap::humongous_region_is_always_live(uint index) {
3681 HeapRegion* region = region_at(index);
3682 assert(region->startsHumongous(), "Must start a humongous object");
3683 return oop(region->bottom())->is_objArray() || !region->rem_set()->is_empty();
3684 }
3686 class RegisterHumongousWithInCSetFastTestClosure : public HeapRegionClosure {
3687 private:
3688 size_t _total_humongous;
3689 size_t _candidate_humongous;
3690 public:
3691 RegisterHumongousWithInCSetFastTestClosure() : _total_humongous(0), _candidate_humongous(0) {
3692 }
3694 virtual bool doHeapRegion(HeapRegion* r) {
3695 if (!r->startsHumongous()) {
3696 return false;
3697 }
3698 G1CollectedHeap* g1h = G1CollectedHeap::heap();
3700 uint region_idx = r->hrs_index();
3701 bool is_candidate = !g1h->humongous_region_is_always_live(region_idx);
3702 // Is_candidate already filters out humongous regions with some remembered set.
3703 // This will not lead to humongous object that we mistakenly keep alive because
3704 // during young collection the remembered sets will only be added to.
3705 if (is_candidate) {
3706 g1h->register_humongous_region_with_in_cset_fast_test(region_idx);
3707 _candidate_humongous++;
3708 }
3709 _total_humongous++;
3711 return false;
3712 }
3714 size_t total_humongous() const { return _total_humongous; }
3715 size_t candidate_humongous() const { return _candidate_humongous; }
3716 };
3718 void G1CollectedHeap::register_humongous_regions_with_in_cset_fast_test() {
3719 if (!G1ReclaimDeadHumongousObjectsAtYoungGC) {
3720 g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(0, 0);
3721 return;
3722 }
3724 RegisterHumongousWithInCSetFastTestClosure cl;
3725 heap_region_iterate(&cl);
3726 g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(cl.total_humongous(),
3727 cl.candidate_humongous());
3728 _has_humongous_reclaim_candidates = cl.candidate_humongous() > 0;
3730 if (_has_humongous_reclaim_candidates) {
3731 clear_humongous_is_live_table();
3732 }
3733 }
3735 void
3736 G1CollectedHeap::setup_surviving_young_words() {
3737 assert(_surviving_young_words == NULL, "pre-condition");
3738 uint array_length = g1_policy()->young_cset_region_length();
3739 _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, (size_t) array_length, mtGC);
3740 if (_surviving_young_words == NULL) {
3741 vm_exit_out_of_memory(sizeof(size_t) * array_length, OOM_MALLOC_ERROR,
3742 "Not enough space for young surv words summary.");
3743 }
3744 memset(_surviving_young_words, 0, (size_t) array_length * sizeof(size_t));
3745 #ifdef ASSERT
3746 for (uint i = 0; i < array_length; ++i) {
3747 assert( _surviving_young_words[i] == 0, "memset above" );
3748 }
3749 #endif // !ASSERT
3750 }
3752 void
3753 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {
3754 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
3755 uint array_length = g1_policy()->young_cset_region_length();
3756 for (uint i = 0; i < array_length; ++i) {
3757 _surviving_young_words[i] += surv_young_words[i];
3758 }
3759 }
3761 void
3762 G1CollectedHeap::cleanup_surviving_young_words() {
3763 guarantee( _surviving_young_words != NULL, "pre-condition" );
3764 FREE_C_HEAP_ARRAY(size_t, _surviving_young_words, mtGC);
3765 _surviving_young_words = NULL;
3766 }
3768 #ifdef ASSERT
3769 class VerifyCSetClosure: public HeapRegionClosure {
3770 public:
3771 bool doHeapRegion(HeapRegion* hr) {
3772 // Here we check that the CSet region's RSet is ready for parallel
3773 // iteration. The fields that we'll verify are only manipulated
3774 // when the region is part of a CSet and is collected. Afterwards,
3775 // we reset these fields when we clear the region's RSet (when the
3776 // region is freed) so they are ready when the region is
3777 // re-allocated. The only exception to this is if there's an
3778 // evacuation failure and instead of freeing the region we leave
3779 // it in the heap. In that case, we reset these fields during
3780 // evacuation failure handling.
3781 guarantee(hr->rem_set()->verify_ready_for_par_iteration(), "verification");
3783 // Here's a good place to add any other checks we'd like to
3784 // perform on CSet regions.
3785 return false;
3786 }
3787 };
3788 #endif // ASSERT
3790 #if TASKQUEUE_STATS
3791 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
3792 st->print_raw_cr("GC Task Stats");
3793 st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
3794 st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
3795 }
3797 void G1CollectedHeap::print_taskqueue_stats(outputStream* const st) const {
3798 print_taskqueue_stats_hdr(st);
3800 TaskQueueStats totals;
3801 const int n = workers() != NULL ? workers()->total_workers() : 1;
3802 for (int i = 0; i < n; ++i) {
3803 st->print("%3d ", i); task_queue(i)->stats.print(st); st->cr();
3804 totals += task_queue(i)->stats;
3805 }
3806 st->print_raw("tot "); totals.print(st); st->cr();
3808 DEBUG_ONLY(totals.verify());
3809 }
3811 void G1CollectedHeap::reset_taskqueue_stats() {
3812 const int n = workers() != NULL ? workers()->total_workers() : 1;
3813 for (int i = 0; i < n; ++i) {
3814 task_queue(i)->stats.reset();
3815 }
3816 }
3817 #endif // TASKQUEUE_STATS
3819 void G1CollectedHeap::log_gc_header() {
3820 if (!G1Log::fine()) {
3821 return;
3822 }
3824 gclog_or_tty->gclog_stamp(_gc_tracer_stw->gc_id());
3826 GCCauseString gc_cause_str = GCCauseString("GC pause", gc_cause())
3827 .append(g1_policy()->gcs_are_young() ? "(young)" : "(mixed)")
3828 .append(g1_policy()->during_initial_mark_pause() ? " (initial-mark)" : "");
3830 gclog_or_tty->print("[%s", (const char*)gc_cause_str);
3831 }
3833 void G1CollectedHeap::log_gc_footer(double pause_time_sec) {
3834 if (!G1Log::fine()) {
3835 return;
3836 }
3838 if (G1Log::finer()) {
3839 if (evacuation_failed()) {
3840 gclog_or_tty->print(" (to-space exhausted)");
3841 }
3842 gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
3843 g1_policy()->phase_times()->note_gc_end();
3844 g1_policy()->phase_times()->print(pause_time_sec);
3845 g1_policy()->print_detailed_heap_transition();
3846 } else {
3847 if (evacuation_failed()) {
3848 gclog_or_tty->print("--");
3849 }
3850 g1_policy()->print_heap_transition();
3851 gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
3852 }
3853 gclog_or_tty->flush();
3854 }
3856 bool
3857 G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
3858 assert_at_safepoint(true /* should_be_vm_thread */);
3859 guarantee(!is_gc_active(), "collection is not reentrant");
3861 if (GC_locker::check_active_before_gc()) {
3862 return false;
3863 }
3865 _gc_timer_stw->register_gc_start();
3867 _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
3869 SvcGCMarker sgcm(SvcGCMarker::MINOR);
3870 ResourceMark rm;
3872 print_heap_before_gc();
3873 trace_heap_before_gc(_gc_tracer_stw);
3875 verify_region_sets_optional();
3876 verify_dirty_young_regions();
3878 // This call will decide whether this pause is an initial-mark
3879 // pause. If it is, during_initial_mark_pause() will return true
3880 // for the duration of this pause.
3881 g1_policy()->decide_on_conc_mark_initiation();
3883 // We do not allow initial-mark to be piggy-backed on a mixed GC.
3884 assert(!g1_policy()->during_initial_mark_pause() ||
3885 g1_policy()->gcs_are_young(), "sanity");
3887 // We also do not allow mixed GCs during marking.
3888 assert(!mark_in_progress() || g1_policy()->gcs_are_young(), "sanity");
3890 // Record whether this pause is an initial mark. When the current
3891 // thread has completed its logging output and it's safe to signal
3892 // the CM thread, the flag's value in the policy has been reset.
3893 bool should_start_conc_mark = g1_policy()->during_initial_mark_pause();
3895 // Inner scope for scope based logging, timers, and stats collection
3896 {
3897 EvacuationInfo evacuation_info;
3899 if (g1_policy()->during_initial_mark_pause()) {
3900 // We are about to start a marking cycle, so we increment the
3901 // full collection counter.
3902 increment_old_marking_cycles_started();
3903 register_concurrent_cycle_start(_gc_timer_stw->gc_start());
3904 }
3906 _gc_tracer_stw->report_yc_type(yc_type());
3908 TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
3910 int active_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
3911 workers()->active_workers() : 1);
3912 double pause_start_sec = os::elapsedTime();
3913 g1_policy()->phase_times()->note_gc_start(active_workers);
3914 log_gc_header();
3916 TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
3917 TraceMemoryManagerStats tms(false /* fullGC */, gc_cause());
3919 // If the secondary_free_list is not empty, append it to the
3920 // free_list. No need to wait for the cleanup operation to finish;
3921 // the region allocation code will check the secondary_free_list
3922 // and wait if necessary. If the G1StressConcRegionFreeing flag is
3923 // set, skip this step so that the region allocation code has to
3924 // get entries from the secondary_free_list.
3925 if (!G1StressConcRegionFreeing) {
3926 append_secondary_free_list_if_not_empty_with_lock();
3927 }
3929 assert(check_young_list_well_formed(), "young list should be well formed");
3930 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3931 "sanity check");
3933 // Don't dynamically change the number of GC threads this early. A value of
3934 // 0 is used to indicate serial work. When parallel work is done,
3935 // it will be set.
3937 { // Call to jvmpi::post_class_unload_events must occur outside of active GC
3938 IsGCActiveMark x;
3940 gc_prologue(false);
3941 increment_total_collections(false /* full gc */);
3942 increment_gc_time_stamp();
3944 verify_before_gc();
3945 check_bitmaps("GC Start");
3947 COMPILER2_PRESENT(DerivedPointerTable::clear());
3949 // Please see comment in g1CollectedHeap.hpp and
3950 // G1CollectedHeap::ref_processing_init() to see how
3951 // reference processing currently works in G1.
3953 // Enable discovery in the STW reference processor
3954 ref_processor_stw()->enable_discovery(true /*verify_disabled*/,
3955 true /*verify_no_refs*/);
3957 {
3958 // We want to temporarily turn off discovery by the
3959 // CM ref processor, if necessary, and turn it back on
3960 // on again later if we do. Using a scoped
3961 // NoRefDiscovery object will do this.
3962 NoRefDiscovery no_cm_discovery(ref_processor_cm());
3964 // Forget the current alloc region (we might even choose it to be part
3965 // of the collection set!).
3966 release_mutator_alloc_region();
3968 // We should call this after we retire the mutator alloc
3969 // region(s) so that all the ALLOC / RETIRE events are generated
3970 // before the start GC event.
3971 _hr_printer.start_gc(false /* full */, (size_t) total_collections());
3973 // This timing is only used by the ergonomics to handle our pause target.
3974 // It is unclear why this should not include the full pause. We will
3975 // investigate this in CR 7178365.
3976 //
3977 // Preserving the old comment here if that helps the investigation:
3978 //
3979 // The elapsed time induced by the start time below deliberately elides
3980 // the possible verification above.
3981 double sample_start_time_sec = os::elapsedTime();
3983 #if YOUNG_LIST_VERBOSE
3984 gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:");
3985 _young_list->print();
3986 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
3987 #endif // YOUNG_LIST_VERBOSE
3989 g1_policy()->record_collection_pause_start(sample_start_time_sec);
3991 double scan_wait_start = os::elapsedTime();
3992 // We have to wait until the CM threads finish scanning the
3993 // root regions as it's the only way to ensure that all the
3994 // objects on them have been correctly scanned before we start
3995 // moving them during the GC.
3996 bool waited = _cm->root_regions()->wait_until_scan_finished();
3997 double wait_time_ms = 0.0;
3998 if (waited) {
3999 double scan_wait_end = os::elapsedTime();
4000 wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;
4001 }
4002 g1_policy()->phase_times()->record_root_region_scan_wait_time(wait_time_ms);
4004 #if YOUNG_LIST_VERBOSE
4005 gclog_or_tty->print_cr("\nAfter recording pause start.\nYoung_list:");
4006 _young_list->print();
4007 #endif // YOUNG_LIST_VERBOSE
4009 if (g1_policy()->during_initial_mark_pause()) {
4010 concurrent_mark()->checkpointRootsInitialPre();
4011 }
4013 #if YOUNG_LIST_VERBOSE
4014 gclog_or_tty->print_cr("\nBefore choosing collection set.\nYoung_list:");
4015 _young_list->print();
4016 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4017 #endif // YOUNG_LIST_VERBOSE
4019 g1_policy()->finalize_cset(target_pause_time_ms, evacuation_info);
4021 register_humongous_regions_with_in_cset_fast_test();
4023 _cm->note_start_of_gc();
4024 // We should not verify the per-thread SATB buffers given that
4025 // we have not filtered them yet (we'll do so during the
4026 // GC). We also call this after finalize_cset() to
4027 // ensure that the CSet has been finalized.
4028 _cm->verify_no_cset_oops(true /* verify_stacks */,
4029 true /* verify_enqueued_buffers */,
4030 false /* verify_thread_buffers */,
4031 true /* verify_fingers */);
4033 if (_hr_printer.is_active()) {
4034 HeapRegion* hr = g1_policy()->collection_set();
4035 while (hr != NULL) {
4036 G1HRPrinter::RegionType type;
4037 if (!hr->is_young()) {
4038 type = G1HRPrinter::Old;
4039 } else if (hr->is_survivor()) {
4040 type = G1HRPrinter::Survivor;
4041 } else {
4042 type = G1HRPrinter::Eden;
4043 }
4044 _hr_printer.cset(hr);
4045 hr = hr->next_in_collection_set();
4046 }
4047 }
4049 #ifdef ASSERT
4050 VerifyCSetClosure cl;
4051 collection_set_iterate(&cl);
4052 #endif // ASSERT
4054 setup_surviving_young_words();
4056 // Initialize the GC alloc regions.
4057 init_gc_alloc_regions(evacuation_info);
4059 // Actually do the work...
4060 evacuate_collection_set(evacuation_info);
4062 // We do this to mainly verify the per-thread SATB buffers
4063 // (which have been filtered by now) since we didn't verify
4064 // them earlier. No point in re-checking the stacks / enqueued
4065 // buffers given that the CSet has not changed since last time
4066 // we checked.
4067 _cm->verify_no_cset_oops(false /* verify_stacks */,
4068 false /* verify_enqueued_buffers */,
4069 true /* verify_thread_buffers */,
4070 true /* verify_fingers */);
4072 free_collection_set(g1_policy()->collection_set(), evacuation_info);
4074 eagerly_reclaim_humongous_regions();
4076 g1_policy()->clear_collection_set();
4078 cleanup_surviving_young_words();
4080 // Start a new incremental collection set for the next pause.
4081 g1_policy()->start_incremental_cset_building();
4083 clear_cset_fast_test();
4085 _young_list->reset_sampled_info();
4087 // Don't check the whole heap at this point as the
4088 // GC alloc regions from this pause have been tagged
4089 // as survivors and moved on to the survivor list.
4090 // Survivor regions will fail the !is_young() check.
4091 assert(check_young_list_empty(false /* check_heap */),
4092 "young list should be empty");
4094 #if YOUNG_LIST_VERBOSE
4095 gclog_or_tty->print_cr("Before recording survivors.\nYoung List:");
4096 _young_list->print();
4097 #endif // YOUNG_LIST_VERBOSE
4099 g1_policy()->record_survivor_regions(_young_list->survivor_length(),
4100 _young_list->first_survivor_region(),
4101 _young_list->last_survivor_region());
4103 _young_list->reset_auxilary_lists();
4105 if (evacuation_failed()) {
4106 _summary_bytes_used = recalculate_used();
4107 uint n_queues = MAX2((int)ParallelGCThreads, 1);
4108 for (uint i = 0; i < n_queues; i++) {
4109 if (_evacuation_failed_info_array[i].has_failed()) {
4110 _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
4111 }
4112 }
4113 } else {
4114 // The "used" of the the collection set have already been subtracted
4115 // when they were freed. Add in the bytes evacuated.
4116 _summary_bytes_used += g1_policy()->bytes_copied_during_gc();
4117 }
4119 if (g1_policy()->during_initial_mark_pause()) {
4120 // We have to do this before we notify the CM threads that
4121 // they can start working to make sure that all the
4122 // appropriate initialization is done on the CM object.
4123 concurrent_mark()->checkpointRootsInitialPost();
4124 set_marking_started();
4125 // Note that we don't actually trigger the CM thread at
4126 // this point. We do that later when we're sure that
4127 // the current thread has completed its logging output.
4128 }
4130 allocate_dummy_regions();
4132 #if YOUNG_LIST_VERBOSE
4133 gclog_or_tty->print_cr("\nEnd of the pause.\nYoung_list:");
4134 _young_list->print();
4135 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4136 #endif // YOUNG_LIST_VERBOSE
4138 init_mutator_alloc_region();
4140 {
4141 size_t expand_bytes = g1_policy()->expansion_amount();
4142 if (expand_bytes > 0) {
4143 size_t bytes_before = capacity();
4144 // No need for an ergo verbose message here,
4145 // expansion_amount() does this when it returns a value > 0.
4146 if (!expand(expand_bytes)) {
4147 // We failed to expand the heap. Cannot do anything about it.
4148 }
4149 }
4150 }
4152 // We redo the verification but now wrt to the new CSet which
4153 // has just got initialized after the previous CSet was freed.
4154 _cm->verify_no_cset_oops(true /* verify_stacks */,
4155 true /* verify_enqueued_buffers */,
4156 true /* verify_thread_buffers */,
4157 true /* verify_fingers */);
4158 _cm->note_end_of_gc();
4160 // This timing is only used by the ergonomics to handle our pause target.
4161 // It is unclear why this should not include the full pause. We will
4162 // investigate this in CR 7178365.
4163 double sample_end_time_sec = os::elapsedTime();
4164 double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
4165 g1_policy()->record_collection_pause_end(pause_time_ms, evacuation_info);
4167 MemoryService::track_memory_usage();
4169 // In prepare_for_verify() below we'll need to scan the deferred
4170 // update buffers to bring the RSets up-to-date if
4171 // G1HRRSFlushLogBuffersOnVerify has been set. While scanning
4172 // the update buffers we'll probably need to scan cards on the
4173 // regions we just allocated to (i.e., the GC alloc
4174 // regions). However, during the last GC we called
4175 // set_saved_mark() on all the GC alloc regions, so card
4176 // scanning might skip the [saved_mark_word()...top()] area of
4177 // those regions (i.e., the area we allocated objects into
4178 // during the last GC). But it shouldn't. Given that
4179 // saved_mark_word() is conditional on whether the GC time stamp
4180 // on the region is current or not, by incrementing the GC time
4181 // stamp here we invalidate all the GC time stamps on all the
4182 // regions and saved_mark_word() will simply return top() for
4183 // all the regions. This is a nicer way of ensuring this rather
4184 // than iterating over the regions and fixing them. In fact, the
4185 // GC time stamp increment here also ensures that
4186 // saved_mark_word() will return top() between pauses, i.e.,
4187 // during concurrent refinement. So we don't need the
4188 // is_gc_active() check to decided which top to use when
4189 // scanning cards (see CR 7039627).
4190 increment_gc_time_stamp();
4192 verify_after_gc();
4193 check_bitmaps("GC End");
4195 assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
4196 ref_processor_stw()->verify_no_references_recorded();
4198 // CM reference discovery will be re-enabled if necessary.
4199 }
4201 // We should do this after we potentially expand the heap so
4202 // that all the COMMIT events are generated before the end GC
4203 // event, and after we retire the GC alloc regions so that all
4204 // RETIRE events are generated before the end GC event.
4205 _hr_printer.end_gc(false /* full */, (size_t) total_collections());
4207 #ifdef TRACESPINNING
4208 ParallelTaskTerminator::print_termination_counts();
4209 #endif
4211 gc_epilogue(false);
4212 }
4214 // Print the remainder of the GC log output.
4215 log_gc_footer(os::elapsedTime() - pause_start_sec);
4217 // It is not yet to safe to tell the concurrent mark to
4218 // start as we have some optional output below. We don't want the
4219 // output from the concurrent mark thread interfering with this
4220 // logging output either.
4222 _hrs.verify_optional();
4223 verify_region_sets_optional();
4225 TASKQUEUE_STATS_ONLY(if (ParallelGCVerbose) print_taskqueue_stats());
4226 TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
4228 print_heap_after_gc();
4229 trace_heap_after_gc(_gc_tracer_stw);
4231 // We must call G1MonitoringSupport::update_sizes() in the same scoping level
4232 // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
4233 // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
4234 // before any GC notifications are raised.
4235 g1mm()->update_sizes();
4237 _gc_tracer_stw->report_evacuation_info(&evacuation_info);
4238 _gc_tracer_stw->report_tenuring_threshold(_g1_policy->tenuring_threshold());
4239 _gc_timer_stw->register_gc_end();
4240 _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(), _gc_timer_stw->time_partitions());
4241 }
4242 // It should now be safe to tell the concurrent mark thread to start
4243 // without its logging output interfering with the logging output
4244 // that came from the pause.
4246 if (should_start_conc_mark) {
4247 // CAUTION: after the doConcurrentMark() call below,
4248 // the concurrent marking thread(s) could be running
4249 // concurrently with us. Make sure that anything after
4250 // this point does not assume that we are the only GC thread
4251 // running. Note: of course, the actual marking work will
4252 // not start until the safepoint itself is released in
4253 // SuspendibleThreadSet::desynchronize().
4254 doConcurrentMark();
4255 }
4257 return true;
4258 }
4260 size_t G1CollectedHeap::desired_plab_sz(GCAllocPurpose purpose)
4261 {
4262 size_t gclab_word_size;
4263 switch (purpose) {
4264 case GCAllocForSurvived:
4265 gclab_word_size = _survivor_plab_stats.desired_plab_sz();
4266 break;
4267 case GCAllocForTenured:
4268 gclab_word_size = _old_plab_stats.desired_plab_sz();
4269 break;
4270 default:
4271 assert(false, "unknown GCAllocPurpose");
4272 gclab_word_size = _old_plab_stats.desired_plab_sz();
4273 break;
4274 }
4276 // Prevent humongous PLAB sizes for two reasons:
4277 // * PLABs are allocated using a similar paths as oops, but should
4278 // never be in a humongous region
4279 // * Allowing humongous PLABs needlessly churns the region free lists
4280 return MIN2(_humongous_object_threshold_in_words, gclab_word_size);
4281 }
4283 void G1CollectedHeap::init_mutator_alloc_region() {
4284 assert(_mutator_alloc_region.get() == NULL, "pre-condition");
4285 _mutator_alloc_region.init();
4286 }
4288 void G1CollectedHeap::release_mutator_alloc_region() {
4289 _mutator_alloc_region.release();
4290 assert(_mutator_alloc_region.get() == NULL, "post-condition");
4291 }
4293 void G1CollectedHeap::use_retained_old_gc_alloc_region(EvacuationInfo& evacuation_info) {
4294 HeapRegion* retained_region = _retained_old_gc_alloc_region;
4295 _retained_old_gc_alloc_region = NULL;
4297 // We will discard the current GC alloc region if:
4298 // a) it's in the collection set (it can happen!),
4299 // b) it's already full (no point in using it),
4300 // c) it's empty (this means that it was emptied during
4301 // a cleanup and it should be on the free list now), or
4302 // d) it's humongous (this means that it was emptied
4303 // during a cleanup and was added to the free list, but
4304 // has been subsequently used to allocate a humongous
4305 // object that may be less than the region size).
4306 if (retained_region != NULL &&
4307 !retained_region->in_collection_set() &&
4308 !(retained_region->top() == retained_region->end()) &&
4309 !retained_region->is_empty() &&
4310 !retained_region->isHumongous()) {
4311 retained_region->record_top_and_timestamp();
4312 // The retained region was added to the old region set when it was
4313 // retired. We have to remove it now, since we don't allow regions
4314 // we allocate to in the region sets. We'll re-add it later, when
4315 // it's retired again.
4316 _old_set.remove(retained_region);
4317 bool during_im = g1_policy()->during_initial_mark_pause();
4318 retained_region->note_start_of_copying(during_im);
4319 _old_gc_alloc_region.set(retained_region);
4320 _hr_printer.reuse(retained_region);
4321 evacuation_info.set_alloc_regions_used_before(retained_region->used());
4322 }
4323 }
4325 void G1CollectedHeap::init_gc_alloc_regions(EvacuationInfo& evacuation_info) {
4326 assert_at_safepoint(true /* should_be_vm_thread */);
4328 _survivor_gc_alloc_region.init();
4329 _old_gc_alloc_region.init();
4331 use_retained_old_gc_alloc_region(evacuation_info);
4332 }
4334 void G1CollectedHeap::release_gc_alloc_regions(uint no_of_gc_workers, EvacuationInfo& evacuation_info) {
4335 evacuation_info.set_allocation_regions(_survivor_gc_alloc_region.count() +
4336 _old_gc_alloc_region.count());
4337 _survivor_gc_alloc_region.release();
4338 // If we have an old GC alloc region to release, we'll save it in
4339 // _retained_old_gc_alloc_region. If we don't
4340 // _retained_old_gc_alloc_region will become NULL. This is what we
4341 // want either way so no reason to check explicitly for either
4342 // condition.
4343 _retained_old_gc_alloc_region = _old_gc_alloc_region.release();
4345 if (ResizePLAB) {
4346 _survivor_plab_stats.adjust_desired_plab_sz(no_of_gc_workers);
4347 _old_plab_stats.adjust_desired_plab_sz(no_of_gc_workers);
4348 }
4349 }
4351 void G1CollectedHeap::abandon_gc_alloc_regions() {
4352 assert(_survivor_gc_alloc_region.get() == NULL, "pre-condition");
4353 assert(_old_gc_alloc_region.get() == NULL, "pre-condition");
4354 _retained_old_gc_alloc_region = NULL;
4355 }
4357 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {
4358 _drain_in_progress = false;
4359 set_evac_failure_closure(cl);
4360 _evac_failure_scan_stack = new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(40, true);
4361 }
4363 void G1CollectedHeap::finalize_for_evac_failure() {
4364 assert(_evac_failure_scan_stack != NULL &&
4365 _evac_failure_scan_stack->length() == 0,
4366 "Postcondition");
4367 assert(!_drain_in_progress, "Postcondition");
4368 delete _evac_failure_scan_stack;
4369 _evac_failure_scan_stack = NULL;
4370 }
4372 void G1CollectedHeap::remove_self_forwarding_pointers() {
4373 assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
4375 double remove_self_forwards_start = os::elapsedTime();
4377 G1ParRemoveSelfForwardPtrsTask rsfp_task(this);
4379 if (G1CollectedHeap::use_parallel_gc_threads()) {
4380 set_par_threads();
4381 workers()->run_task(&rsfp_task);
4382 set_par_threads(0);
4383 } else {
4384 rsfp_task.work(0);
4385 }
4387 assert(check_cset_heap_region_claim_values(HeapRegion::ParEvacFailureClaimValue), "sanity");
4389 // Reset the claim values in the regions in the collection set.
4390 reset_cset_heap_region_claim_values();
4392 assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
4394 // Now restore saved marks, if any.
4395 assert(_objs_with_preserved_marks.size() ==
4396 _preserved_marks_of_objs.size(), "Both or none.");
4397 while (!_objs_with_preserved_marks.is_empty()) {
4398 oop obj = _objs_with_preserved_marks.pop();
4399 markOop m = _preserved_marks_of_objs.pop();
4400 obj->set_mark(m);
4401 }
4402 _objs_with_preserved_marks.clear(true);
4403 _preserved_marks_of_objs.clear(true);
4405 g1_policy()->phase_times()->record_evac_fail_remove_self_forwards((os::elapsedTime() - remove_self_forwards_start) * 1000.0);
4406 }
4408 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {
4409 _evac_failure_scan_stack->push(obj);
4410 }
4412 void G1CollectedHeap::drain_evac_failure_scan_stack() {
4413 assert(_evac_failure_scan_stack != NULL, "precondition");
4415 while (_evac_failure_scan_stack->length() > 0) {
4416 oop obj = _evac_failure_scan_stack->pop();
4417 _evac_failure_closure->set_region(heap_region_containing(obj));
4418 obj->oop_iterate_backwards(_evac_failure_closure);
4419 }
4420 }
4422 oop
4423 G1CollectedHeap::handle_evacuation_failure_par(G1ParScanThreadState* _par_scan_state,
4424 oop old) {
4425 assert(obj_in_cs(old),
4426 err_msg("obj: "PTR_FORMAT" should still be in the CSet",
4427 (HeapWord*) old));
4428 markOop m = old->mark();
4429 oop forward_ptr = old->forward_to_atomic(old);
4430 if (forward_ptr == NULL) {
4431 // Forward-to-self succeeded.
4432 assert(_par_scan_state != NULL, "par scan state");
4433 OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure();
4434 uint queue_num = _par_scan_state->queue_num();
4436 _evacuation_failed = true;
4437 _evacuation_failed_info_array[queue_num].register_copy_failure(old->size());
4438 if (_evac_failure_closure != cl) {
4439 MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag);
4440 assert(!_drain_in_progress,
4441 "Should only be true while someone holds the lock.");
4442 // Set the global evac-failure closure to the current thread's.
4443 assert(_evac_failure_closure == NULL, "Or locking has failed.");
4444 set_evac_failure_closure(cl);
4445 // Now do the common part.
4446 handle_evacuation_failure_common(old, m);
4447 // Reset to NULL.
4448 set_evac_failure_closure(NULL);
4449 } else {
4450 // The lock is already held, and this is recursive.
4451 assert(_drain_in_progress, "This should only be the recursive case.");
4452 handle_evacuation_failure_common(old, m);
4453 }
4454 return old;
4455 } else {
4456 // Forward-to-self failed. Either someone else managed to allocate
4457 // space for this object (old != forward_ptr) or they beat us in
4458 // self-forwarding it (old == forward_ptr).
4459 assert(old == forward_ptr || !obj_in_cs(forward_ptr),
4460 err_msg("obj: "PTR_FORMAT" forwarded to: "PTR_FORMAT" "
4461 "should not be in the CSet",
4462 (HeapWord*) old, (HeapWord*) forward_ptr));
4463 return forward_ptr;
4464 }
4465 }
4467 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) {
4468 preserve_mark_if_necessary(old, m);
4470 HeapRegion* r = heap_region_containing(old);
4471 if (!r->evacuation_failed()) {
4472 r->set_evacuation_failed(true);
4473 _hr_printer.evac_failure(r);
4474 }
4476 push_on_evac_failure_scan_stack(old);
4478 if (!_drain_in_progress) {
4479 // prevent recursion in copy_to_survivor_space()
4480 _drain_in_progress = true;
4481 drain_evac_failure_scan_stack();
4482 _drain_in_progress = false;
4483 }
4484 }
4486 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) {
4487 assert(evacuation_failed(), "Oversaving!");
4488 // We want to call the "for_promotion_failure" version only in the
4489 // case of a promotion failure.
4490 if (m->must_be_preserved_for_promotion_failure(obj)) {
4491 _objs_with_preserved_marks.push(obj);
4492 _preserved_marks_of_objs.push(m);
4493 }
4494 }
4496 HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose,
4497 size_t word_size) {
4498 if (purpose == GCAllocForSurvived) {
4499 HeapWord* result = survivor_attempt_allocation(word_size);
4500 if (result != NULL) {
4501 return result;
4502 } else {
4503 // Let's try to allocate in the old gen in case we can fit the
4504 // object there.
4505 return old_attempt_allocation(word_size);
4506 }
4507 } else {
4508 assert(purpose == GCAllocForTenured, "sanity");
4509 HeapWord* result = old_attempt_allocation(word_size);
4510 if (result != NULL) {
4511 return result;
4512 } else {
4513 // Let's try to allocate in the survivors in case we can fit the
4514 // object there.
4515 return survivor_attempt_allocation(word_size);
4516 }
4517 }
4519 ShouldNotReachHere();
4520 // Trying to keep some compilers happy.
4521 return NULL;
4522 }
4524 G1ParGCAllocBuffer::G1ParGCAllocBuffer(size_t gclab_word_size) :
4525 ParGCAllocBuffer(gclab_word_size), _retired(true) { }
4527 void G1ParCopyHelper::mark_object(oop obj) {
4528 assert(!_g1->heap_region_containing(obj)->in_collection_set(), "should not mark objects in the CSet");
4530 // We know that the object is not moving so it's safe to read its size.
4531 _cm->grayRoot(obj, (size_t) obj->size(), _worker_id);
4532 }
4534 void G1ParCopyHelper::mark_forwarded_object(oop from_obj, oop to_obj) {
4535 assert(from_obj->is_forwarded(), "from obj should be forwarded");
4536 assert(from_obj->forwardee() == to_obj, "to obj should be the forwardee");
4537 assert(from_obj != to_obj, "should not be self-forwarded");
4539 assert(_g1->heap_region_containing(from_obj)->in_collection_set(), "from obj should be in the CSet");
4540 assert(!_g1->heap_region_containing(to_obj)->in_collection_set(), "should not mark objects in the CSet");
4542 // The object might be in the process of being copied by another
4543 // worker so we cannot trust that its to-space image is
4544 // well-formed. So we have to read its size from its from-space
4545 // image which we know should not be changing.
4546 _cm->grayRoot(to_obj, (size_t) from_obj->size(), _worker_id);
4547 }
4549 template <class T>
4550 void G1ParCopyHelper::do_klass_barrier(T* p, oop new_obj) {
4551 if (_g1->heap_region_containing_raw(new_obj)->is_young()) {
4552 _scanned_klass->record_modified_oops();
4553 }
4554 }
4556 template <G1Barrier barrier, G1Mark do_mark_object>
4557 template <class T>
4558 void G1ParCopyClosure<barrier, do_mark_object>::do_oop_work(T* p) {
4559 T heap_oop = oopDesc::load_heap_oop(p);
4561 if (oopDesc::is_null(heap_oop)) {
4562 return;
4563 }
4565 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
4567 assert(_worker_id == _par_scan_state->queue_num(), "sanity");
4569 G1CollectedHeap::in_cset_state_t state = _g1->in_cset_state(obj);
4571 if (state == G1CollectedHeap::InCSet) {
4572 oop forwardee;
4573 if (obj->is_forwarded()) {
4574 forwardee = obj->forwardee();
4575 } else {
4576 forwardee = _par_scan_state->copy_to_survivor_space(obj);
4577 }
4578 assert(forwardee != NULL, "forwardee should not be NULL");
4579 oopDesc::encode_store_heap_oop(p, forwardee);
4580 if (do_mark_object != G1MarkNone && forwardee != obj) {
4581 // If the object is self-forwarded we don't need to explicitly
4582 // mark it, the evacuation failure protocol will do so.
4583 mark_forwarded_object(obj, forwardee);
4584 }
4586 if (barrier == G1BarrierKlass) {
4587 do_klass_barrier(p, forwardee);
4588 }
4589 } else {
4590 if (state == G1CollectedHeap::IsHumongous) {
4591 _g1->set_humongous_is_live(obj);
4592 }
4593 // The object is not in collection set. If we're a root scanning
4594 // closure during an initial mark pause then attempt to mark the object.
4595 if (do_mark_object == G1MarkFromRoot) {
4596 mark_object(obj);
4597 }
4598 }
4600 if (barrier == G1BarrierEvac) {
4601 _par_scan_state->update_rs(_from, p, _worker_id);
4602 }
4603 }
4605 template void G1ParCopyClosure<G1BarrierEvac, G1MarkNone>::do_oop_work(oop* p);
4606 template void G1ParCopyClosure<G1BarrierEvac, G1MarkNone>::do_oop_work(narrowOop* p);
4608 class G1ParEvacuateFollowersClosure : public VoidClosure {
4609 protected:
4610 G1CollectedHeap* _g1h;
4611 G1ParScanThreadState* _par_scan_state;
4612 RefToScanQueueSet* _queues;
4613 ParallelTaskTerminator* _terminator;
4615 G1ParScanThreadState* par_scan_state() { return _par_scan_state; }
4616 RefToScanQueueSet* queues() { return _queues; }
4617 ParallelTaskTerminator* terminator() { return _terminator; }
4619 public:
4620 G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
4621 G1ParScanThreadState* par_scan_state,
4622 RefToScanQueueSet* queues,
4623 ParallelTaskTerminator* terminator)
4624 : _g1h(g1h), _par_scan_state(par_scan_state),
4625 _queues(queues), _terminator(terminator) {}
4627 void do_void();
4629 private:
4630 inline bool offer_termination();
4631 };
4633 bool G1ParEvacuateFollowersClosure::offer_termination() {
4634 G1ParScanThreadState* const pss = par_scan_state();
4635 pss->start_term_time();
4636 const bool res = terminator()->offer_termination();
4637 pss->end_term_time();
4638 return res;
4639 }
4641 void G1ParEvacuateFollowersClosure::do_void() {
4642 G1ParScanThreadState* const pss = par_scan_state();
4643 pss->trim_queue();
4644 do {
4645 pss->steal_and_trim_queue(queues());
4646 } while (!offer_termination());
4647 }
4649 class G1KlassScanClosure : public KlassClosure {
4650 G1ParCopyHelper* _closure;
4651 bool _process_only_dirty;
4652 int _count;
4653 public:
4654 G1KlassScanClosure(G1ParCopyHelper* closure, bool process_only_dirty)
4655 : _process_only_dirty(process_only_dirty), _closure(closure), _count(0) {}
4656 void do_klass(Klass* klass) {
4657 // If the klass has not been dirtied we know that there's
4658 // no references into the young gen and we can skip it.
4659 if (!_process_only_dirty || klass->has_modified_oops()) {
4660 // Clean the klass since we're going to scavenge all the metadata.
4661 klass->clear_modified_oops();
4663 // Tell the closure that this klass is the Klass to scavenge
4664 // and is the one to dirty if oops are left pointing into the young gen.
4665 _closure->set_scanned_klass(klass);
4667 klass->oops_do(_closure);
4669 _closure->set_scanned_klass(NULL);
4670 }
4671 _count++;
4672 }
4673 };
4675 class G1ParTask : public AbstractGangTask {
4676 protected:
4677 G1CollectedHeap* _g1h;
4678 RefToScanQueueSet *_queues;
4679 ParallelTaskTerminator _terminator;
4680 uint _n_workers;
4682 Mutex _stats_lock;
4683 Mutex* stats_lock() { return &_stats_lock; }
4685 public:
4686 G1ParTask(G1CollectedHeap* g1h, RefToScanQueueSet *task_queues)
4687 : AbstractGangTask("G1 collection"),
4688 _g1h(g1h),
4689 _queues(task_queues),
4690 _terminator(0, _queues),
4691 _stats_lock(Mutex::leaf, "parallel G1 stats lock", true)
4692 {}
4694 RefToScanQueueSet* queues() { return _queues; }
4696 RefToScanQueue *work_queue(int i) {
4697 return queues()->queue(i);
4698 }
4700 ParallelTaskTerminator* terminator() { return &_terminator; }
4702 virtual void set_for_termination(int active_workers) {
4703 // This task calls set_n_termination() in par_non_clean_card_iterate_work()
4704 // in the young space (_par_seq_tasks) in the G1 heap
4705 // for SequentialSubTasksDone.
4706 // This task also uses SubTasksDone in SharedHeap and G1CollectedHeap
4707 // both of which need setting by set_n_termination().
4708 _g1h->SharedHeap::set_n_termination(active_workers);
4709 _g1h->set_n_termination(active_workers);
4710 terminator()->reset_for_reuse(active_workers);
4711 _n_workers = active_workers;
4712 }
4714 // Helps out with CLD processing.
4715 //
4716 // During InitialMark we need to:
4717 // 1) Scavenge all CLDs for the young GC.
4718 // 2) Mark all objects directly reachable from strong CLDs.
4719 template <G1Mark do_mark_object>
4720 class G1CLDClosure : public CLDClosure {
4721 G1ParCopyClosure<G1BarrierNone, do_mark_object>* _oop_closure;
4722 G1ParCopyClosure<G1BarrierKlass, do_mark_object> _oop_in_klass_closure;
4723 G1KlassScanClosure _klass_in_cld_closure;
4724 bool _claim;
4726 public:
4727 G1CLDClosure(G1ParCopyClosure<G1BarrierNone, do_mark_object>* oop_closure,
4728 bool only_young, bool claim)
4729 : _oop_closure(oop_closure),
4730 _oop_in_klass_closure(oop_closure->g1(),
4731 oop_closure->pss(),
4732 oop_closure->rp()),
4733 _klass_in_cld_closure(&_oop_in_klass_closure, only_young),
4734 _claim(claim) {
4736 }
4738 void do_cld(ClassLoaderData* cld) {
4739 cld->oops_do(_oop_closure, &_klass_in_cld_closure, _claim);
4740 }
4741 };
4743 class G1CodeBlobClosure: public CodeBlobClosure {
4744 OopClosure* _f;
4746 public:
4747 G1CodeBlobClosure(OopClosure* f) : _f(f) {}
4748 void do_code_blob(CodeBlob* blob) {
4749 nmethod* that = blob->as_nmethod_or_null();
4750 if (that != NULL) {
4751 if (!that->test_set_oops_do_mark()) {
4752 that->oops_do(_f);
4753 that->fix_oop_relocations();
4754 }
4755 }
4756 }
4757 };
4759 void work(uint worker_id) {
4760 if (worker_id >= _n_workers) return; // no work needed this round
4762 double start_time_ms = os::elapsedTime() * 1000.0;
4763 _g1h->g1_policy()->phase_times()->record_gc_worker_start_time(worker_id, start_time_ms);
4765 {
4766 ResourceMark rm;
4767 HandleMark hm;
4769 ReferenceProcessor* rp = _g1h->ref_processor_stw();
4771 G1ParScanThreadState pss(_g1h, worker_id, rp);
4772 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, rp);
4774 pss.set_evac_failure_closure(&evac_failure_cl);
4776 bool only_young = _g1h->g1_policy()->gcs_are_young();
4778 // Non-IM young GC.
4779 G1ParCopyClosure<G1BarrierNone, G1MarkNone> scan_only_root_cl(_g1h, &pss, rp);
4780 G1CLDClosure<G1MarkNone> scan_only_cld_cl(&scan_only_root_cl,
4781 only_young, // Only process dirty klasses.
4782 false); // No need to claim CLDs.
4783 // IM young GC.
4784 // Strong roots closures.
4785 G1ParCopyClosure<G1BarrierNone, G1MarkFromRoot> scan_mark_root_cl(_g1h, &pss, rp);
4786 G1CLDClosure<G1MarkFromRoot> scan_mark_cld_cl(&scan_mark_root_cl,
4787 false, // Process all klasses.
4788 true); // Need to claim CLDs.
4789 // Weak roots closures.
4790 G1ParCopyClosure<G1BarrierNone, G1MarkPromotedFromRoot> scan_mark_weak_root_cl(_g1h, &pss, rp);
4791 G1CLDClosure<G1MarkPromotedFromRoot> scan_mark_weak_cld_cl(&scan_mark_weak_root_cl,
4792 false, // Process all klasses.
4793 true); // Need to claim CLDs.
4795 G1CodeBlobClosure scan_only_code_cl(&scan_only_root_cl);
4796 G1CodeBlobClosure scan_mark_code_cl(&scan_mark_root_cl);
4797 // IM Weak code roots are handled later.
4799 OopClosure* strong_root_cl;
4800 OopClosure* weak_root_cl;
4801 CLDClosure* strong_cld_cl;
4802 CLDClosure* weak_cld_cl;
4803 CodeBlobClosure* strong_code_cl;
4805 if (_g1h->g1_policy()->during_initial_mark_pause()) {
4806 // We also need to mark copied objects.
4807 strong_root_cl = &scan_mark_root_cl;
4808 strong_cld_cl = &scan_mark_cld_cl;
4809 strong_code_cl = &scan_mark_code_cl;
4810 if (ClassUnloadingWithConcurrentMark) {
4811 weak_root_cl = &scan_mark_weak_root_cl;
4812 weak_cld_cl = &scan_mark_weak_cld_cl;
4813 } else {
4814 weak_root_cl = &scan_mark_root_cl;
4815 weak_cld_cl = &scan_mark_cld_cl;
4816 }
4817 } else {
4818 strong_root_cl = &scan_only_root_cl;
4819 weak_root_cl = &scan_only_root_cl;
4820 strong_cld_cl = &scan_only_cld_cl;
4821 weak_cld_cl = &scan_only_cld_cl;
4822 strong_code_cl = &scan_only_code_cl;
4823 }
4826 G1ParPushHeapRSClosure push_heap_rs_cl(_g1h, &pss);
4828 pss.start_strong_roots();
4829 _g1h->g1_process_roots(strong_root_cl,
4830 weak_root_cl,
4831 &push_heap_rs_cl,
4832 strong_cld_cl,
4833 weak_cld_cl,
4834 strong_code_cl,
4835 worker_id);
4837 pss.end_strong_roots();
4839 {
4840 double start = os::elapsedTime();
4841 G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);
4842 evac.do_void();
4843 double elapsed_ms = (os::elapsedTime()-start)*1000.0;
4844 double term_ms = pss.term_time()*1000.0;
4845 _g1h->g1_policy()->phase_times()->add_obj_copy_time(worker_id, elapsed_ms-term_ms);
4846 _g1h->g1_policy()->phase_times()->record_termination(worker_id, term_ms, pss.term_attempts());
4847 }
4848 _g1h->g1_policy()->record_thread_age_table(pss.age_table());
4849 _g1h->update_surviving_young_words(pss.surviving_young_words()+1);
4851 if (ParallelGCVerbose) {
4852 MutexLocker x(stats_lock());
4853 pss.print_termination_stats(worker_id);
4854 }
4856 assert(pss.queue_is_empty(), "should be empty");
4858 // Close the inner scope so that the ResourceMark and HandleMark
4859 // destructors are executed here and are included as part of the
4860 // "GC Worker Time".
4861 }
4863 double end_time_ms = os::elapsedTime() * 1000.0;
4864 _g1h->g1_policy()->phase_times()->record_gc_worker_end_time(worker_id, end_time_ms);
4865 }
4866 };
4868 // *** Common G1 Evacuation Stuff
4870 // This method is run in a GC worker.
4872 void
4873 G1CollectedHeap::
4874 g1_process_roots(OopClosure* scan_non_heap_roots,
4875 OopClosure* scan_non_heap_weak_roots,
4876 OopsInHeapRegionClosure* scan_rs,
4877 CLDClosure* scan_strong_clds,
4878 CLDClosure* scan_weak_clds,
4879 CodeBlobClosure* scan_strong_code,
4880 uint worker_i) {
4882 // First scan the shared roots.
4883 double ext_roots_start = os::elapsedTime();
4884 double closure_app_time_sec = 0.0;
4886 bool during_im = _g1h->g1_policy()->during_initial_mark_pause();
4887 bool trace_metadata = during_im && ClassUnloadingWithConcurrentMark;
4889 BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots);
4890 BufferingOopClosure buf_scan_non_heap_weak_roots(scan_non_heap_weak_roots);
4892 process_roots(false, // no scoping; this is parallel code
4893 SharedHeap::SO_None,
4894 &buf_scan_non_heap_roots,
4895 &buf_scan_non_heap_weak_roots,
4896 scan_strong_clds,
4897 // Unloading Initial Marks handle the weak CLDs separately.
4898 (trace_metadata ? NULL : scan_weak_clds),
4899 scan_strong_code);
4901 // Now the CM ref_processor roots.
4902 if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) {
4903 // We need to treat the discovered reference lists of the
4904 // concurrent mark ref processor as roots and keep entries
4905 // (which are added by the marking threads) on them live
4906 // until they can be processed at the end of marking.
4907 ref_processor_cm()->weak_oops_do(&buf_scan_non_heap_roots);
4908 }
4910 if (trace_metadata) {
4911 // Barrier to make sure all workers passed
4912 // the strong CLD and strong nmethods phases.
4913 active_strong_roots_scope()->wait_until_all_workers_done_with_threads(n_par_threads());
4915 // Now take the complement of the strong CLDs.
4916 ClassLoaderDataGraph::roots_cld_do(NULL, scan_weak_clds);
4917 }
4919 // Finish up any enqueued closure apps (attributed as object copy time).
4920 buf_scan_non_heap_roots.done();
4921 buf_scan_non_heap_weak_roots.done();
4923 double obj_copy_time_sec = buf_scan_non_heap_roots.closure_app_seconds()
4924 + buf_scan_non_heap_weak_roots.closure_app_seconds();
4926 g1_policy()->phase_times()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0);
4928 double ext_root_time_ms =
4929 ((os::elapsedTime() - ext_roots_start) - obj_copy_time_sec) * 1000.0;
4931 g1_policy()->phase_times()->record_ext_root_scan_time(worker_i, ext_root_time_ms);
4933 // During conc marking we have to filter the per-thread SATB buffers
4934 // to make sure we remove any oops into the CSet (which will show up
4935 // as implicitly live).
4936 double satb_filtering_ms = 0.0;
4937 if (!_process_strong_tasks->is_task_claimed(G1H_PS_filter_satb_buffers)) {
4938 if (mark_in_progress()) {
4939 double satb_filter_start = os::elapsedTime();
4941 JavaThread::satb_mark_queue_set().filter_thread_buffers();
4943 satb_filtering_ms = (os::elapsedTime() - satb_filter_start) * 1000.0;
4944 }
4945 }
4946 g1_policy()->phase_times()->record_satb_filtering_time(worker_i, satb_filtering_ms);
4948 // Now scan the complement of the collection set.
4949 MarkingCodeBlobClosure scavenge_cs_nmethods(scan_non_heap_weak_roots, CodeBlobToOopClosure::FixRelocations);
4951 g1_rem_set()->oops_into_collection_set_do(scan_rs, &scavenge_cs_nmethods, worker_i);
4953 _process_strong_tasks->all_tasks_completed();
4954 }
4956 class G1StringSymbolTableUnlinkTask : public AbstractGangTask {
4957 private:
4958 BoolObjectClosure* _is_alive;
4959 int _initial_string_table_size;
4960 int _initial_symbol_table_size;
4962 bool _process_strings;
4963 int _strings_processed;
4964 int _strings_removed;
4966 bool _process_symbols;
4967 int _symbols_processed;
4968 int _symbols_removed;
4970 bool _do_in_parallel;
4971 public:
4972 G1StringSymbolTableUnlinkTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols) :
4973 AbstractGangTask("String/Symbol Unlinking"),
4974 _is_alive(is_alive),
4975 _do_in_parallel(G1CollectedHeap::use_parallel_gc_threads()),
4976 _process_strings(process_strings), _strings_processed(0), _strings_removed(0),
4977 _process_symbols(process_symbols), _symbols_processed(0), _symbols_removed(0) {
4979 _initial_string_table_size = StringTable::the_table()->table_size();
4980 _initial_symbol_table_size = SymbolTable::the_table()->table_size();
4981 if (process_strings) {
4982 StringTable::clear_parallel_claimed_index();
4983 }
4984 if (process_symbols) {
4985 SymbolTable::clear_parallel_claimed_index();
4986 }
4987 }
4989 ~G1StringSymbolTableUnlinkTask() {
4990 guarantee(!_process_strings || !_do_in_parallel || StringTable::parallel_claimed_index() >= _initial_string_table_size,
4991 err_msg("claim value "INT32_FORMAT" after unlink less than initial string table size "INT32_FORMAT,
4992 StringTable::parallel_claimed_index(), _initial_string_table_size));
4993 guarantee(!_process_symbols || !_do_in_parallel || SymbolTable::parallel_claimed_index() >= _initial_symbol_table_size,
4994 err_msg("claim value "INT32_FORMAT" after unlink less than initial symbol table size "INT32_FORMAT,
4995 SymbolTable::parallel_claimed_index(), _initial_symbol_table_size));
4997 if (G1TraceStringSymbolTableScrubbing) {
4998 gclog_or_tty->print_cr("Cleaned string and symbol table, "
4999 "strings: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed, "
5000 "symbols: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed",
5001 strings_processed(), strings_removed(),
5002 symbols_processed(), symbols_removed());
5003 }
5004 }
5006 void work(uint worker_id) {
5007 if (_do_in_parallel) {
5008 int strings_processed = 0;
5009 int strings_removed = 0;
5010 int symbols_processed = 0;
5011 int symbols_removed = 0;
5012 if (_process_strings) {
5013 StringTable::possibly_parallel_unlink(_is_alive, &strings_processed, &strings_removed);
5014 Atomic::add(strings_processed, &_strings_processed);
5015 Atomic::add(strings_removed, &_strings_removed);
5016 }
5017 if (_process_symbols) {
5018 SymbolTable::possibly_parallel_unlink(&symbols_processed, &symbols_removed);
5019 Atomic::add(symbols_processed, &_symbols_processed);
5020 Atomic::add(symbols_removed, &_symbols_removed);
5021 }
5022 } else {
5023 if (_process_strings) {
5024 StringTable::unlink(_is_alive, &_strings_processed, &_strings_removed);
5025 }
5026 if (_process_symbols) {
5027 SymbolTable::unlink(&_symbols_processed, &_symbols_removed);
5028 }
5029 }
5030 }
5032 size_t strings_processed() const { return (size_t)_strings_processed; }
5033 size_t strings_removed() const { return (size_t)_strings_removed; }
5035 size_t symbols_processed() const { return (size_t)_symbols_processed; }
5036 size_t symbols_removed() const { return (size_t)_symbols_removed; }
5037 };
5039 class G1CodeCacheUnloadingTask VALUE_OBJ_CLASS_SPEC {
5040 private:
5041 static Monitor* _lock;
5043 BoolObjectClosure* const _is_alive;
5044 const bool _unloading_occurred;
5045 const uint _num_workers;
5047 // Variables used to claim nmethods.
5048 nmethod* _first_nmethod;
5049 volatile nmethod* _claimed_nmethod;
5051 // The list of nmethods that need to be processed by the second pass.
5052 volatile nmethod* _postponed_list;
5053 volatile uint _num_entered_barrier;
5055 public:
5056 G1CodeCacheUnloadingTask(uint num_workers, BoolObjectClosure* is_alive, bool unloading_occurred) :
5057 _is_alive(is_alive),
5058 _unloading_occurred(unloading_occurred),
5059 _num_workers(num_workers),
5060 _first_nmethod(NULL),
5061 _claimed_nmethod(NULL),
5062 _postponed_list(NULL),
5063 _num_entered_barrier(0)
5064 {
5065 nmethod::increase_unloading_clock();
5066 _first_nmethod = CodeCache::alive_nmethod(CodeCache::first());
5067 _claimed_nmethod = (volatile nmethod*)_first_nmethod;
5068 }
5070 ~G1CodeCacheUnloadingTask() {
5071 CodeCache::verify_clean_inline_caches();
5073 CodeCache::set_needs_cache_clean(false);
5074 guarantee(CodeCache::scavenge_root_nmethods() == NULL, "Must be");
5076 CodeCache::verify_icholder_relocations();
5077 }
5079 private:
5080 void add_to_postponed_list(nmethod* nm) {
5081 nmethod* old;
5082 do {
5083 old = (nmethod*)_postponed_list;
5084 nm->set_unloading_next(old);
5085 } while ((nmethod*)Atomic::cmpxchg_ptr(nm, &_postponed_list, old) != old);
5086 }
5088 void clean_nmethod(nmethod* nm) {
5089 bool postponed = nm->do_unloading_parallel(_is_alive, _unloading_occurred);
5091 if (postponed) {
5092 // This nmethod referred to an nmethod that has not been cleaned/unloaded yet.
5093 add_to_postponed_list(nm);
5094 }
5096 // Mark that this thread has been cleaned/unloaded.
5097 // After this call, it will be safe to ask if this nmethod was unloaded or not.
5098 nm->set_unloading_clock(nmethod::global_unloading_clock());
5099 }
5101 void clean_nmethod_postponed(nmethod* nm) {
5102 nm->do_unloading_parallel_postponed(_is_alive, _unloading_occurred);
5103 }
5105 static const int MaxClaimNmethods = 16;
5107 void claim_nmethods(nmethod** claimed_nmethods, int *num_claimed_nmethods) {
5108 nmethod* first;
5109 nmethod* last;
5111 do {
5112 *num_claimed_nmethods = 0;
5114 first = last = (nmethod*)_claimed_nmethod;
5116 if (first != NULL) {
5117 for (int i = 0; i < MaxClaimNmethods; i++) {
5118 last = CodeCache::alive_nmethod(CodeCache::next(last));
5120 if (last == NULL) {
5121 break;
5122 }
5124 claimed_nmethods[i] = last;
5125 (*num_claimed_nmethods)++;
5126 }
5127 }
5129 } while ((nmethod*)Atomic::cmpxchg_ptr(last, &_claimed_nmethod, first) != first);
5130 }
5132 nmethod* claim_postponed_nmethod() {
5133 nmethod* claim;
5134 nmethod* next;
5136 do {
5137 claim = (nmethod*)_postponed_list;
5138 if (claim == NULL) {
5139 return NULL;
5140 }
5142 next = claim->unloading_next();
5144 } while ((nmethod*)Atomic::cmpxchg_ptr(next, &_postponed_list, claim) != claim);
5146 return claim;
5147 }
5149 public:
5150 // Mark that we're done with the first pass of nmethod cleaning.
5151 void barrier_mark(uint worker_id) {
5152 MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
5153 _num_entered_barrier++;
5154 if (_num_entered_barrier == _num_workers) {
5155 ml.notify_all();
5156 }
5157 }
5159 // See if we have to wait for the other workers to
5160 // finish their first-pass nmethod cleaning work.
5161 void barrier_wait(uint worker_id) {
5162 if (_num_entered_barrier < _num_workers) {
5163 MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag);
5164 while (_num_entered_barrier < _num_workers) {
5165 ml.wait(Mutex::_no_safepoint_check_flag, 0, false);
5166 }
5167 }
5168 }
5170 // Cleaning and unloading of nmethods. Some work has to be postponed
5171 // to the second pass, when we know which nmethods survive.
5172 void work_first_pass(uint worker_id) {
5173 // The first nmethods is claimed by the first worker.
5174 if (worker_id == 0 && _first_nmethod != NULL) {
5175 clean_nmethod(_first_nmethod);
5176 _first_nmethod = NULL;
5177 }
5179 int num_claimed_nmethods;
5180 nmethod* claimed_nmethods[MaxClaimNmethods];
5182 while (true) {
5183 claim_nmethods(claimed_nmethods, &num_claimed_nmethods);
5185 if (num_claimed_nmethods == 0) {
5186 break;
5187 }
5189 for (int i = 0; i < num_claimed_nmethods; i++) {
5190 clean_nmethod(claimed_nmethods[i]);
5191 }
5192 }
5193 }
5195 void work_second_pass(uint worker_id) {
5196 nmethod* nm;
5197 // Take care of postponed nmethods.
5198 while ((nm = claim_postponed_nmethod()) != NULL) {
5199 clean_nmethod_postponed(nm);
5200 }
5201 }
5202 };
5204 Monitor* G1CodeCacheUnloadingTask::_lock = new Monitor(Mutex::leaf, "Code Cache Unload lock");
5206 class G1KlassCleaningTask : public StackObj {
5207 BoolObjectClosure* _is_alive;
5208 volatile jint _clean_klass_tree_claimed;
5209 ClassLoaderDataGraphKlassIteratorAtomic _klass_iterator;
5211 public:
5212 G1KlassCleaningTask(BoolObjectClosure* is_alive) :
5213 _is_alive(is_alive),
5214 _clean_klass_tree_claimed(0),
5215 _klass_iterator() {
5216 }
5218 private:
5219 bool claim_clean_klass_tree_task() {
5220 if (_clean_klass_tree_claimed) {
5221 return false;
5222 }
5224 return Atomic::cmpxchg(1, (jint*)&_clean_klass_tree_claimed, 0) == 0;
5225 }
5227 InstanceKlass* claim_next_klass() {
5228 Klass* klass;
5229 do {
5230 klass =_klass_iterator.next_klass();
5231 } while (klass != NULL && !klass->oop_is_instance());
5233 return (InstanceKlass*)klass;
5234 }
5236 public:
5238 void clean_klass(InstanceKlass* ik) {
5239 ik->clean_implementors_list(_is_alive);
5240 ik->clean_method_data(_is_alive);
5242 // G1 specific cleanup work that has
5243 // been moved here to be done in parallel.
5244 ik->clean_dependent_nmethods();
5245 }
5247 void work() {
5248 ResourceMark rm;
5250 // One worker will clean the subklass/sibling klass tree.
5251 if (claim_clean_klass_tree_task()) {
5252 Klass::clean_subklass_tree(_is_alive);
5253 }
5255 // All workers will help cleaning the classes,
5256 InstanceKlass* klass;
5257 while ((klass = claim_next_klass()) != NULL) {
5258 clean_klass(klass);
5259 }
5260 }
5261 };
5263 // To minimize the remark pause times, the tasks below are done in parallel.
5264 class G1ParallelCleaningTask : public AbstractGangTask {
5265 private:
5266 G1StringSymbolTableUnlinkTask _string_symbol_task;
5267 G1CodeCacheUnloadingTask _code_cache_task;
5268 G1KlassCleaningTask _klass_cleaning_task;
5270 public:
5271 // The constructor is run in the VMThread.
5272 G1ParallelCleaningTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols, uint num_workers, bool unloading_occurred) :
5273 AbstractGangTask("Parallel Cleaning"),
5274 _string_symbol_task(is_alive, process_strings, process_symbols),
5275 _code_cache_task(num_workers, is_alive, unloading_occurred),
5276 _klass_cleaning_task(is_alive) {
5277 }
5279 // The parallel work done by all worker threads.
5280 void work(uint worker_id) {
5281 // Do first pass of code cache cleaning.
5282 _code_cache_task.work_first_pass(worker_id);
5284 // Let the threads mark that the first pass is done.
5285 _code_cache_task.barrier_mark(worker_id);
5287 // Clean the Strings and Symbols.
5288 _string_symbol_task.work(worker_id);
5290 // Wait for all workers to finish the first code cache cleaning pass.
5291 _code_cache_task.barrier_wait(worker_id);
5293 // Do the second code cache cleaning work, which realize on
5294 // the liveness information gathered during the first pass.
5295 _code_cache_task.work_second_pass(worker_id);
5297 // Clean all klasses that were not unloaded.
5298 _klass_cleaning_task.work();
5299 }
5300 };
5303 void G1CollectedHeap::parallel_cleaning(BoolObjectClosure* is_alive,
5304 bool process_strings,
5305 bool process_symbols,
5306 bool class_unloading_occurred) {
5307 uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
5308 workers()->active_workers() : 1);
5310 G1ParallelCleaningTask g1_unlink_task(is_alive, process_strings, process_symbols,
5311 n_workers, class_unloading_occurred);
5312 if (G1CollectedHeap::use_parallel_gc_threads()) {
5313 set_par_threads(n_workers);
5314 workers()->run_task(&g1_unlink_task);
5315 set_par_threads(0);
5316 } else {
5317 g1_unlink_task.work(0);
5318 }
5319 }
5321 void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive,
5322 bool process_strings, bool process_symbols) {
5323 {
5324 uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
5325 _g1h->workers()->active_workers() : 1);
5326 G1StringSymbolTableUnlinkTask g1_unlink_task(is_alive, process_strings, process_symbols);
5327 if (G1CollectedHeap::use_parallel_gc_threads()) {
5328 set_par_threads(n_workers);
5329 workers()->run_task(&g1_unlink_task);
5330 set_par_threads(0);
5331 } else {
5332 g1_unlink_task.work(0);
5333 }
5334 }
5336 if (G1StringDedup::is_enabled()) {
5337 G1StringDedup::unlink(is_alive);
5338 }
5339 }
5341 class G1RedirtyLoggedCardsTask : public AbstractGangTask {
5342 private:
5343 DirtyCardQueueSet* _queue;
5344 public:
5345 G1RedirtyLoggedCardsTask(DirtyCardQueueSet* queue) : AbstractGangTask("Redirty Cards"), _queue(queue) { }
5347 virtual void work(uint worker_id) {
5348 double start_time = os::elapsedTime();
5350 RedirtyLoggedCardTableEntryClosure cl;
5351 if (G1CollectedHeap::heap()->use_parallel_gc_threads()) {
5352 _queue->par_apply_closure_to_all_completed_buffers(&cl);
5353 } else {
5354 _queue->apply_closure_to_all_completed_buffers(&cl);
5355 }
5357 G1GCPhaseTimes* timer = G1CollectedHeap::heap()->g1_policy()->phase_times();
5358 timer->record_redirty_logged_cards_time_ms(worker_id, (os::elapsedTime() - start_time) * 1000.0);
5359 timer->record_redirty_logged_cards_processed_cards(worker_id, cl.num_processed());
5360 }
5361 };
5363 void G1CollectedHeap::redirty_logged_cards() {
5364 guarantee(G1DeferredRSUpdate, "Must only be called when using deferred RS updates.");
5365 double redirty_logged_cards_start = os::elapsedTime();
5367 uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
5368 _g1h->workers()->active_workers() : 1);
5370 G1RedirtyLoggedCardsTask redirty_task(&dirty_card_queue_set());
5371 dirty_card_queue_set().reset_for_par_iteration();
5372 if (use_parallel_gc_threads()) {
5373 set_par_threads(n_workers);
5374 workers()->run_task(&redirty_task);
5375 set_par_threads(0);
5376 } else {
5377 redirty_task.work(0);
5378 }
5380 DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set();
5381 dcq.merge_bufferlists(&dirty_card_queue_set());
5382 assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
5384 g1_policy()->phase_times()->record_redirty_logged_cards_time_ms((os::elapsedTime() - redirty_logged_cards_start) * 1000.0);
5385 }
5387 // Weak Reference Processing support
5389 // An always "is_alive" closure that is used to preserve referents.
5390 // If the object is non-null then it's alive. Used in the preservation
5391 // of referent objects that are pointed to by reference objects
5392 // discovered by the CM ref processor.
5393 class G1AlwaysAliveClosure: public BoolObjectClosure {
5394 G1CollectedHeap* _g1;
5395 public:
5396 G1AlwaysAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
5397 bool do_object_b(oop p) {
5398 if (p != NULL) {
5399 return true;
5400 }
5401 return false;
5402 }
5403 };
5405 bool G1STWIsAliveClosure::do_object_b(oop p) {
5406 // An object is reachable if it is outside the collection set,
5407 // or is inside and copied.
5408 return !_g1->obj_in_cs(p) || p->is_forwarded();
5409 }
5411 // Non Copying Keep Alive closure
5412 class G1KeepAliveClosure: public OopClosure {
5413 G1CollectedHeap* _g1;
5414 public:
5415 G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
5416 void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
5417 void do_oop(oop* p) {
5418 oop obj = *p;
5420 G1CollectedHeap::in_cset_state_t cset_state = _g1->in_cset_state(obj);
5421 if (obj == NULL || cset_state == G1CollectedHeap::InNeither) {
5422 return;
5423 }
5424 if (cset_state == G1CollectedHeap::InCSet) {
5425 assert( obj->is_forwarded(), "invariant" );
5426 *p = obj->forwardee();
5427 } else {
5428 assert(!obj->is_forwarded(), "invariant" );
5429 assert(cset_state == G1CollectedHeap::IsHumongous,
5430 err_msg("Only allowed InCSet state is IsHumongous, but is %d", cset_state));
5431 _g1->set_humongous_is_live(obj);
5432 }
5433 }
5434 };
5436 // Copying Keep Alive closure - can be called from both
5437 // serial and parallel code as long as different worker
5438 // threads utilize different G1ParScanThreadState instances
5439 // and different queues.
5441 class G1CopyingKeepAliveClosure: public OopClosure {
5442 G1CollectedHeap* _g1h;
5443 OopClosure* _copy_non_heap_obj_cl;
5444 G1ParScanThreadState* _par_scan_state;
5446 public:
5447 G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
5448 OopClosure* non_heap_obj_cl,
5449 G1ParScanThreadState* pss):
5450 _g1h(g1h),
5451 _copy_non_heap_obj_cl(non_heap_obj_cl),
5452 _par_scan_state(pss)
5453 {}
5455 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
5456 virtual void do_oop( oop* p) { do_oop_work(p); }
5458 template <class T> void do_oop_work(T* p) {
5459 oop obj = oopDesc::load_decode_heap_oop(p);
5461 if (_g1h->is_in_cset_or_humongous(obj)) {
5462 // If the referent object has been forwarded (either copied
5463 // to a new location or to itself in the event of an
5464 // evacuation failure) then we need to update the reference
5465 // field and, if both reference and referent are in the G1
5466 // heap, update the RSet for the referent.
5467 //
5468 // If the referent has not been forwarded then we have to keep
5469 // it alive by policy. Therefore we have copy the referent.
5470 //
5471 // If the reference field is in the G1 heap then we can push
5472 // on the PSS queue. When the queue is drained (after each
5473 // phase of reference processing) the object and it's followers
5474 // will be copied, the reference field set to point to the
5475 // new location, and the RSet updated. Otherwise we need to
5476 // use the the non-heap or metadata closures directly to copy
5477 // the referent object and update the pointer, while avoiding
5478 // updating the RSet.
5480 if (_g1h->is_in_g1_reserved(p)) {
5481 _par_scan_state->push_on_queue(p);
5482 } else {
5483 assert(!Metaspace::contains((const void*)p),
5484 err_msg("Unexpectedly found a pointer from metadata: "
5485 PTR_FORMAT, p));
5486 _copy_non_heap_obj_cl->do_oop(p);
5487 }
5488 }
5489 }
5490 };
5492 // Serial drain queue closure. Called as the 'complete_gc'
5493 // closure for each discovered list in some of the
5494 // reference processing phases.
5496 class G1STWDrainQueueClosure: public VoidClosure {
5497 protected:
5498 G1CollectedHeap* _g1h;
5499 G1ParScanThreadState* _par_scan_state;
5501 G1ParScanThreadState* par_scan_state() { return _par_scan_state; }
5503 public:
5504 G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :
5505 _g1h(g1h),
5506 _par_scan_state(pss)
5507 { }
5509 void do_void() {
5510 G1ParScanThreadState* const pss = par_scan_state();
5511 pss->trim_queue();
5512 }
5513 };
5515 // Parallel Reference Processing closures
5517 // Implementation of AbstractRefProcTaskExecutor for parallel reference
5518 // processing during G1 evacuation pauses.
5520 class G1STWRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
5521 private:
5522 G1CollectedHeap* _g1h;
5523 RefToScanQueueSet* _queues;
5524 FlexibleWorkGang* _workers;
5525 int _active_workers;
5527 public:
5528 G1STWRefProcTaskExecutor(G1CollectedHeap* g1h,
5529 FlexibleWorkGang* workers,
5530 RefToScanQueueSet *task_queues,
5531 int n_workers) :
5532 _g1h(g1h),
5533 _queues(task_queues),
5534 _workers(workers),
5535 _active_workers(n_workers)
5536 {
5537 assert(n_workers > 0, "shouldn't call this otherwise");
5538 }
5540 // Executes the given task using concurrent marking worker threads.
5541 virtual void execute(ProcessTask& task);
5542 virtual void execute(EnqueueTask& task);
5543 };
5545 // Gang task for possibly parallel reference processing
5547 class G1STWRefProcTaskProxy: public AbstractGangTask {
5548 typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
5549 ProcessTask& _proc_task;
5550 G1CollectedHeap* _g1h;
5551 RefToScanQueueSet *_task_queues;
5552 ParallelTaskTerminator* _terminator;
5554 public:
5555 G1STWRefProcTaskProxy(ProcessTask& proc_task,
5556 G1CollectedHeap* g1h,
5557 RefToScanQueueSet *task_queues,
5558 ParallelTaskTerminator* terminator) :
5559 AbstractGangTask("Process reference objects in parallel"),
5560 _proc_task(proc_task),
5561 _g1h(g1h),
5562 _task_queues(task_queues),
5563 _terminator(terminator)
5564 {}
5566 virtual void work(uint worker_id) {
5567 // The reference processing task executed by a single worker.
5568 ResourceMark rm;
5569 HandleMark hm;
5571 G1STWIsAliveClosure is_alive(_g1h);
5573 G1ParScanThreadState pss(_g1h, worker_id, NULL);
5574 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);
5576 pss.set_evac_failure_closure(&evac_failure_cl);
5578 G1ParScanExtRootClosure only_copy_non_heap_cl(_g1h, &pss, NULL);
5580 G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
5582 OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl;
5584 if (_g1h->g1_policy()->during_initial_mark_pause()) {
5585 // We also need to mark copied objects.
5586 copy_non_heap_cl = ©_mark_non_heap_cl;
5587 }
5589 // Keep alive closure.
5590 G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss);
5592 // Complete GC closure
5593 G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _task_queues, _terminator);
5595 // Call the reference processing task's work routine.
5596 _proc_task.work(worker_id, is_alive, keep_alive, drain_queue);
5598 // Note we cannot assert that the refs array is empty here as not all
5599 // of the processing tasks (specifically phase2 - pp2_work) execute
5600 // the complete_gc closure (which ordinarily would drain the queue) so
5601 // the queue may not be empty.
5602 }
5603 };
5605 // Driver routine for parallel reference processing.
5606 // Creates an instance of the ref processing gang
5607 // task and has the worker threads execute it.
5608 void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task) {
5609 assert(_workers != NULL, "Need parallel worker threads.");
5611 ParallelTaskTerminator terminator(_active_workers, _queues);
5612 G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _queues, &terminator);
5614 _g1h->set_par_threads(_active_workers);
5615 _workers->run_task(&proc_task_proxy);
5616 _g1h->set_par_threads(0);
5617 }
5619 // Gang task for parallel reference enqueueing.
5621 class G1STWRefEnqueueTaskProxy: public AbstractGangTask {
5622 typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
5623 EnqueueTask& _enq_task;
5625 public:
5626 G1STWRefEnqueueTaskProxy(EnqueueTask& enq_task) :
5627 AbstractGangTask("Enqueue reference objects in parallel"),
5628 _enq_task(enq_task)
5629 { }
5631 virtual void work(uint worker_id) {
5632 _enq_task.work(worker_id);
5633 }
5634 };
5636 // Driver routine for parallel reference enqueueing.
5637 // Creates an instance of the ref enqueueing gang
5638 // task and has the worker threads execute it.
5640 void G1STWRefProcTaskExecutor::execute(EnqueueTask& enq_task) {
5641 assert(_workers != NULL, "Need parallel worker threads.");
5643 G1STWRefEnqueueTaskProxy enq_task_proxy(enq_task);
5645 _g1h->set_par_threads(_active_workers);
5646 _workers->run_task(&enq_task_proxy);
5647 _g1h->set_par_threads(0);
5648 }
5650 // End of weak reference support closures
5652 // Abstract task used to preserve (i.e. copy) any referent objects
5653 // that are in the collection set and are pointed to by reference
5654 // objects discovered by the CM ref processor.
5656 class G1ParPreserveCMReferentsTask: public AbstractGangTask {
5657 protected:
5658 G1CollectedHeap* _g1h;
5659 RefToScanQueueSet *_queues;
5660 ParallelTaskTerminator _terminator;
5661 uint _n_workers;
5663 public:
5664 G1ParPreserveCMReferentsTask(G1CollectedHeap* g1h,int workers, RefToScanQueueSet *task_queues) :
5665 AbstractGangTask("ParPreserveCMReferents"),
5666 _g1h(g1h),
5667 _queues(task_queues),
5668 _terminator(workers, _queues),
5669 _n_workers(workers)
5670 { }
5672 void work(uint worker_id) {
5673 ResourceMark rm;
5674 HandleMark hm;
5676 G1ParScanThreadState pss(_g1h, worker_id, NULL);
5677 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);
5679 pss.set_evac_failure_closure(&evac_failure_cl);
5681 assert(pss.queue_is_empty(), "both queue and overflow should be empty");
5683 G1ParScanExtRootClosure only_copy_non_heap_cl(_g1h, &pss, NULL);
5685 G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
5687 OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl;
5689 if (_g1h->g1_policy()->during_initial_mark_pause()) {
5690 // We also need to mark copied objects.
5691 copy_non_heap_cl = ©_mark_non_heap_cl;
5692 }
5694 // Is alive closure
5695 G1AlwaysAliveClosure always_alive(_g1h);
5697 // Copying keep alive closure. Applied to referent objects that need
5698 // to be copied.
5699 G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss);
5701 ReferenceProcessor* rp = _g1h->ref_processor_cm();
5703 uint limit = ReferenceProcessor::number_of_subclasses_of_ref() * rp->max_num_q();
5704 uint stride = MIN2(MAX2(_n_workers, 1U), limit);
5706 // limit is set using max_num_q() - which was set using ParallelGCThreads.
5707 // So this must be true - but assert just in case someone decides to
5708 // change the worker ids.
5709 assert(0 <= worker_id && worker_id < limit, "sanity");
5710 assert(!rp->discovery_is_atomic(), "check this code");
5712 // Select discovered lists [i, i+stride, i+2*stride,...,limit)
5713 for (uint idx = worker_id; idx < limit; idx += stride) {
5714 DiscoveredList& ref_list = rp->discovered_refs()[idx];
5716 DiscoveredListIterator iter(ref_list, &keep_alive, &always_alive);
5717 while (iter.has_next()) {
5718 // Since discovery is not atomic for the CM ref processor, we
5719 // can see some null referent objects.
5720 iter.load_ptrs(DEBUG_ONLY(true));
5721 oop ref = iter.obj();
5723 // This will filter nulls.
5724 if (iter.is_referent_alive()) {
5725 iter.make_referent_alive();
5726 }
5727 iter.move_to_next();
5728 }
5729 }
5731 // Drain the queue - which may cause stealing
5732 G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _queues, &_terminator);
5733 drain_queue.do_void();
5734 // Allocation buffers were retired at the end of G1ParEvacuateFollowersClosure
5735 assert(pss.queue_is_empty(), "should be");
5736 }
5737 };
5739 // Weak Reference processing during an evacuation pause (part 1).
5740 void G1CollectedHeap::process_discovered_references(uint no_of_gc_workers) {
5741 double ref_proc_start = os::elapsedTime();
5743 ReferenceProcessor* rp = _ref_processor_stw;
5744 assert(rp->discovery_enabled(), "should have been enabled");
5746 // Any reference objects, in the collection set, that were 'discovered'
5747 // by the CM ref processor should have already been copied (either by
5748 // applying the external root copy closure to the discovered lists, or
5749 // by following an RSet entry).
5750 //
5751 // But some of the referents, that are in the collection set, that these
5752 // reference objects point to may not have been copied: the STW ref
5753 // processor would have seen that the reference object had already
5754 // been 'discovered' and would have skipped discovering the reference,
5755 // but would not have treated the reference object as a regular oop.
5756 // As a result the copy closure would not have been applied to the
5757 // referent object.
5758 //
5759 // We need to explicitly copy these referent objects - the references
5760 // will be processed at the end of remarking.
5761 //
5762 // We also need to do this copying before we process the reference
5763 // objects discovered by the STW ref processor in case one of these
5764 // referents points to another object which is also referenced by an
5765 // object discovered by the STW ref processor.
5767 assert(!G1CollectedHeap::use_parallel_gc_threads() ||
5768 no_of_gc_workers == workers()->active_workers(),
5769 "Need to reset active GC workers");
5771 set_par_threads(no_of_gc_workers);
5772 G1ParPreserveCMReferentsTask keep_cm_referents(this,
5773 no_of_gc_workers,
5774 _task_queues);
5776 if (G1CollectedHeap::use_parallel_gc_threads()) {
5777 workers()->run_task(&keep_cm_referents);
5778 } else {
5779 keep_cm_referents.work(0);
5780 }
5782 set_par_threads(0);
5784 // Closure to test whether a referent is alive.
5785 G1STWIsAliveClosure is_alive(this);
5787 // Even when parallel reference processing is enabled, the processing
5788 // of JNI refs is serial and performed serially by the current thread
5789 // rather than by a worker. The following PSS will be used for processing
5790 // JNI refs.
5792 // Use only a single queue for this PSS.
5793 G1ParScanThreadState pss(this, 0, NULL);
5795 // We do not embed a reference processor in the copying/scanning
5796 // closures while we're actually processing the discovered
5797 // reference objects.
5798 G1ParScanHeapEvacFailureClosure evac_failure_cl(this, &pss, NULL);
5800 pss.set_evac_failure_closure(&evac_failure_cl);
5802 assert(pss.queue_is_empty(), "pre-condition");
5804 G1ParScanExtRootClosure only_copy_non_heap_cl(this, &pss, NULL);
5806 G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(this, &pss, NULL);
5808 OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl;
5810 if (_g1h->g1_policy()->during_initial_mark_pause()) {
5811 // We also need to mark copied objects.
5812 copy_non_heap_cl = ©_mark_non_heap_cl;
5813 }
5815 // Keep alive closure.
5816 G1CopyingKeepAliveClosure keep_alive(this, copy_non_heap_cl, &pss);
5818 // Serial Complete GC closure
5819 G1STWDrainQueueClosure drain_queue(this, &pss);
5821 // Setup the soft refs policy...
5822 rp->setup_policy(false);
5824 ReferenceProcessorStats stats;
5825 if (!rp->processing_is_mt()) {
5826 // Serial reference processing...
5827 stats = rp->process_discovered_references(&is_alive,
5828 &keep_alive,
5829 &drain_queue,
5830 NULL,
5831 _gc_timer_stw,
5832 _gc_tracer_stw->gc_id());
5833 } else {
5834 // Parallel reference processing
5835 assert(rp->num_q() == no_of_gc_workers, "sanity");
5836 assert(no_of_gc_workers <= rp->max_num_q(), "sanity");
5838 G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);
5839 stats = rp->process_discovered_references(&is_alive,
5840 &keep_alive,
5841 &drain_queue,
5842 &par_task_executor,
5843 _gc_timer_stw,
5844 _gc_tracer_stw->gc_id());
5845 }
5847 _gc_tracer_stw->report_gc_reference_stats(stats);
5849 // We have completed copying any necessary live referent objects.
5850 assert(pss.queue_is_empty(), "both queue and overflow should be empty");
5852 double ref_proc_time = os::elapsedTime() - ref_proc_start;
5853 g1_policy()->phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);
5854 }
5856 // Weak Reference processing during an evacuation pause (part 2).
5857 void G1CollectedHeap::enqueue_discovered_references(uint no_of_gc_workers) {
5858 double ref_enq_start = os::elapsedTime();
5860 ReferenceProcessor* rp = _ref_processor_stw;
5861 assert(!rp->discovery_enabled(), "should have been disabled as part of processing");
5863 // Now enqueue any remaining on the discovered lists on to
5864 // the pending list.
5865 if (!rp->processing_is_mt()) {
5866 // Serial reference processing...
5867 rp->enqueue_discovered_references();
5868 } else {
5869 // Parallel reference enqueueing
5871 assert(no_of_gc_workers == workers()->active_workers(),
5872 "Need to reset active workers");
5873 assert(rp->num_q() == no_of_gc_workers, "sanity");
5874 assert(no_of_gc_workers <= rp->max_num_q(), "sanity");
5876 G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);
5877 rp->enqueue_discovered_references(&par_task_executor);
5878 }
5880 rp->verify_no_references_recorded();
5881 assert(!rp->discovery_enabled(), "should have been disabled");
5883 // FIXME
5884 // CM's reference processing also cleans up the string and symbol tables.
5885 // Should we do that here also? We could, but it is a serial operation
5886 // and could significantly increase the pause time.
5888 double ref_enq_time = os::elapsedTime() - ref_enq_start;
5889 g1_policy()->phase_times()->record_ref_enq_time(ref_enq_time * 1000.0);
5890 }
5892 void G1CollectedHeap::evacuate_collection_set(EvacuationInfo& evacuation_info) {
5893 _expand_heap_after_alloc_failure = true;
5894 _evacuation_failed = false;
5896 // Should G1EvacuationFailureALot be in effect for this GC?
5897 NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)
5899 g1_rem_set()->prepare_for_oops_into_collection_set_do();
5901 // Disable the hot card cache.
5902 G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
5903 hot_card_cache->reset_hot_cache_claimed_index();
5904 hot_card_cache->set_use_cache(false);
5906 uint n_workers;
5907 if (G1CollectedHeap::use_parallel_gc_threads()) {
5908 n_workers =
5909 AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
5910 workers()->active_workers(),
5911 Threads::number_of_non_daemon_threads());
5912 assert(UseDynamicNumberOfGCThreads ||
5913 n_workers == workers()->total_workers(),
5914 "If not dynamic should be using all the workers");
5915 workers()->set_active_workers(n_workers);
5916 set_par_threads(n_workers);
5917 } else {
5918 assert(n_par_threads() == 0,
5919 "Should be the original non-parallel value");
5920 n_workers = 1;
5921 }
5923 G1ParTask g1_par_task(this, _task_queues);
5925 init_for_evac_failure(NULL);
5927 rem_set()->prepare_for_younger_refs_iterate(true);
5929 assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty");
5930 double start_par_time_sec = os::elapsedTime();
5931 double end_par_time_sec;
5933 {
5934 StrongRootsScope srs(this);
5935 // InitialMark needs claim bits to keep track of the marked-through CLDs.
5936 if (g1_policy()->during_initial_mark_pause()) {
5937 ClassLoaderDataGraph::clear_claimed_marks();
5938 }
5940 if (G1CollectedHeap::use_parallel_gc_threads()) {
5941 // The individual threads will set their evac-failure closures.
5942 if (ParallelGCVerbose) G1ParScanThreadState::print_termination_stats_hdr();
5943 // These tasks use ShareHeap::_process_strong_tasks
5944 assert(UseDynamicNumberOfGCThreads ||
5945 workers()->active_workers() == workers()->total_workers(),
5946 "If not dynamic should be using all the workers");
5947 workers()->run_task(&g1_par_task);
5948 } else {
5949 g1_par_task.set_for_termination(n_workers);
5950 g1_par_task.work(0);
5951 }
5952 end_par_time_sec = os::elapsedTime();
5954 // Closing the inner scope will execute the destructor
5955 // for the StrongRootsScope object. We record the current
5956 // elapsed time before closing the scope so that time
5957 // taken for the SRS destructor is NOT included in the
5958 // reported parallel time.
5959 }
5961 double par_time_ms = (end_par_time_sec - start_par_time_sec) * 1000.0;
5962 g1_policy()->phase_times()->record_par_time(par_time_ms);
5964 double code_root_fixup_time_ms =
5965 (os::elapsedTime() - end_par_time_sec) * 1000.0;
5966 g1_policy()->phase_times()->record_code_root_fixup_time(code_root_fixup_time_ms);
5968 set_par_threads(0);
5970 // Process any discovered reference objects - we have
5971 // to do this _before_ we retire the GC alloc regions
5972 // as we may have to copy some 'reachable' referent
5973 // objects (and their reachable sub-graphs) that were
5974 // not copied during the pause.
5975 process_discovered_references(n_workers);
5977 // Weak root processing.
5978 {
5979 G1STWIsAliveClosure is_alive(this);
5980 G1KeepAliveClosure keep_alive(this);
5981 JNIHandles::weak_oops_do(&is_alive, &keep_alive);
5982 if (G1StringDedup::is_enabled()) {
5983 G1StringDedup::unlink_or_oops_do(&is_alive, &keep_alive);
5984 }
5985 }
5987 release_gc_alloc_regions(n_workers, evacuation_info);
5988 g1_rem_set()->cleanup_after_oops_into_collection_set_do();
5990 // Reset and re-enable the hot card cache.
5991 // Note the counts for the cards in the regions in the
5992 // collection set are reset when the collection set is freed.
5993 hot_card_cache->reset_hot_cache();
5994 hot_card_cache->set_use_cache(true);
5996 // Migrate the strong code roots attached to each region in
5997 // the collection set. Ideally we would like to do this
5998 // after we have finished the scanning/evacuation of the
5999 // strong code roots for a particular heap region.
6000 migrate_strong_code_roots();
6002 purge_code_root_memory();
6004 if (g1_policy()->during_initial_mark_pause()) {
6005 // Reset the claim values set during marking the strong code roots
6006 reset_heap_region_claim_values();
6007 }
6009 finalize_for_evac_failure();
6011 if (evacuation_failed()) {
6012 remove_self_forwarding_pointers();
6014 // Reset the G1EvacuationFailureALot counters and flags
6015 // Note: the values are reset only when an actual
6016 // evacuation failure occurs.
6017 NOT_PRODUCT(reset_evacuation_should_fail();)
6018 }
6020 // Enqueue any remaining references remaining on the STW
6021 // reference processor's discovered lists. We need to do
6022 // this after the card table is cleaned (and verified) as
6023 // the act of enqueueing entries on to the pending list
6024 // will log these updates (and dirty their associated
6025 // cards). We need these updates logged to update any
6026 // RSets.
6027 enqueue_discovered_references(n_workers);
6029 if (G1DeferredRSUpdate) {
6030 redirty_logged_cards();
6031 }
6032 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
6033 }
6035 void G1CollectedHeap::free_region(HeapRegion* hr,
6036 FreeRegionList* free_list,
6037 bool par,
6038 bool locked) {
6039 assert(!hr->isHumongous(), "this is only for non-humongous regions");
6040 assert(!hr->is_empty(), "the region should not be empty");
6041 assert(_hrs.is_available(hr->hrs_index()), "region should be committed");
6042 assert(free_list != NULL, "pre-condition");
6044 if (G1VerifyBitmaps) {
6045 MemRegion mr(hr->bottom(), hr->end());
6046 concurrent_mark()->clearRangePrevBitmap(mr);
6047 }
6049 // Clear the card counts for this region.
6050 // Note: we only need to do this if the region is not young
6051 // (since we don't refine cards in young regions).
6052 if (!hr->is_young()) {
6053 _cg1r->hot_card_cache()->reset_card_counts(hr);
6054 }
6055 hr->hr_clear(par, true /* clear_space */, locked /* locked */);
6056 free_list->add_ordered(hr);
6057 }
6059 void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
6060 FreeRegionList* free_list,
6061 bool par) {
6062 assert(hr->startsHumongous(), "this is only for starts humongous regions");
6063 assert(free_list != NULL, "pre-condition");
6065 size_t hr_capacity = hr->capacity();
6066 // We need to read this before we make the region non-humongous,
6067 // otherwise the information will be gone.
6068 uint last_index = hr->last_hc_index();
6069 hr->set_notHumongous();
6070 free_region(hr, free_list, par);
6072 uint i = hr->hrs_index() + 1;
6073 while (i < last_index) {
6074 HeapRegion* curr_hr = region_at(i);
6075 assert(curr_hr->continuesHumongous(), "invariant");
6076 curr_hr->set_notHumongous();
6077 free_region(curr_hr, free_list, par);
6078 i += 1;
6079 }
6080 }
6082 void G1CollectedHeap::remove_from_old_sets(const HeapRegionSetCount& old_regions_removed,
6083 const HeapRegionSetCount& humongous_regions_removed) {
6084 if (old_regions_removed.length() > 0 || humongous_regions_removed.length() > 0) {
6085 MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag);
6086 _old_set.bulk_remove(old_regions_removed);
6087 _humongous_set.bulk_remove(humongous_regions_removed);
6088 }
6090 }
6092 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {
6093 assert(list != NULL, "list can't be null");
6094 if (!list->is_empty()) {
6095 MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag);
6096 _hrs.insert_list_into_free_list(list);
6097 }
6098 }
6100 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {
6101 assert(_summary_bytes_used >= bytes,
6102 err_msg("invariant: _summary_bytes_used: "SIZE_FORMAT" should be >= bytes: "SIZE_FORMAT,
6103 _summary_bytes_used, bytes));
6104 _summary_bytes_used -= bytes;
6105 }
6107 class G1ParCleanupCTTask : public AbstractGangTask {
6108 G1SATBCardTableModRefBS* _ct_bs;
6109 G1CollectedHeap* _g1h;
6110 HeapRegion* volatile _su_head;
6111 public:
6112 G1ParCleanupCTTask(G1SATBCardTableModRefBS* ct_bs,
6113 G1CollectedHeap* g1h) :
6114 AbstractGangTask("G1 Par Cleanup CT Task"),
6115 _ct_bs(ct_bs), _g1h(g1h) { }
6117 void work(uint worker_id) {
6118 HeapRegion* r;
6119 while (r = _g1h->pop_dirty_cards_region()) {
6120 clear_cards(r);
6121 }
6122 }
6124 void clear_cards(HeapRegion* r) {
6125 // Cards of the survivors should have already been dirtied.
6126 if (!r->is_survivor()) {
6127 _ct_bs->clear(MemRegion(r->bottom(), r->end()));
6128 }
6129 }
6130 };
6132 #ifndef PRODUCT
6133 class G1VerifyCardTableCleanup: public HeapRegionClosure {
6134 G1CollectedHeap* _g1h;
6135 G1SATBCardTableModRefBS* _ct_bs;
6136 public:
6137 G1VerifyCardTableCleanup(G1CollectedHeap* g1h, G1SATBCardTableModRefBS* ct_bs)
6138 : _g1h(g1h), _ct_bs(ct_bs) { }
6139 virtual bool doHeapRegion(HeapRegion* r) {
6140 if (r->is_survivor()) {
6141 _g1h->verify_dirty_region(r);
6142 } else {
6143 _g1h->verify_not_dirty_region(r);
6144 }
6145 return false;
6146 }
6147 };
6149 void G1CollectedHeap::verify_not_dirty_region(HeapRegion* hr) {
6150 // All of the region should be clean.
6151 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6152 MemRegion mr(hr->bottom(), hr->end());
6153 ct_bs->verify_not_dirty_region(mr);
6154 }
6156 void G1CollectedHeap::verify_dirty_region(HeapRegion* hr) {
6157 // We cannot guarantee that [bottom(),end()] is dirty. Threads
6158 // dirty allocated blocks as they allocate them. The thread that
6159 // retires each region and replaces it with a new one will do a
6160 // maximal allocation to fill in [pre_dummy_top(),end()] but will
6161 // not dirty that area (one less thing to have to do while holding
6162 // a lock). So we can only verify that [bottom(),pre_dummy_top()]
6163 // is dirty.
6164 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6165 MemRegion mr(hr->bottom(), hr->pre_dummy_top());
6166 if (hr->is_young()) {
6167 ct_bs->verify_g1_young_region(mr);
6168 } else {
6169 ct_bs->verify_dirty_region(mr);
6170 }
6171 }
6173 void G1CollectedHeap::verify_dirty_young_list(HeapRegion* head) {
6174 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6175 for (HeapRegion* hr = head; hr != NULL; hr = hr->get_next_young_region()) {
6176 verify_dirty_region(hr);
6177 }
6178 }
6180 void G1CollectedHeap::verify_dirty_young_regions() {
6181 verify_dirty_young_list(_young_list->first_region());
6182 }
6184 bool G1CollectedHeap::verify_no_bits_over_tams(const char* bitmap_name, CMBitMapRO* bitmap,
6185 HeapWord* tams, HeapWord* end) {
6186 guarantee(tams <= end,
6187 err_msg("tams: "PTR_FORMAT" end: "PTR_FORMAT, tams, end));
6188 HeapWord* result = bitmap->getNextMarkedWordAddress(tams, end);
6189 if (result < end) {
6190 gclog_or_tty->cr();
6191 gclog_or_tty->print_cr("## wrong marked address on %s bitmap: "PTR_FORMAT,
6192 bitmap_name, result);
6193 gclog_or_tty->print_cr("## %s tams: "PTR_FORMAT" end: "PTR_FORMAT,
6194 bitmap_name, tams, end);
6195 return false;
6196 }
6197 return true;
6198 }
6200 bool G1CollectedHeap::verify_bitmaps(const char* caller, HeapRegion* hr) {
6201 CMBitMapRO* prev_bitmap = concurrent_mark()->prevMarkBitMap();
6202 CMBitMapRO* next_bitmap = (CMBitMapRO*) concurrent_mark()->nextMarkBitMap();
6204 HeapWord* bottom = hr->bottom();
6205 HeapWord* ptams = hr->prev_top_at_mark_start();
6206 HeapWord* ntams = hr->next_top_at_mark_start();
6207 HeapWord* end = hr->end();
6209 bool res_p = verify_no_bits_over_tams("prev", prev_bitmap, ptams, end);
6211 bool res_n = true;
6212 // We reset mark_in_progress() before we reset _cmThread->in_progress() and in this window
6213 // we do the clearing of the next bitmap concurrently. Thus, we can not verify the bitmap
6214 // if we happen to be in that state.
6215 if (mark_in_progress() || !_cmThread->in_progress()) {
6216 res_n = verify_no_bits_over_tams("next", next_bitmap, ntams, end);
6217 }
6218 if (!res_p || !res_n) {
6219 gclog_or_tty->print_cr("#### Bitmap verification failed for "HR_FORMAT,
6220 HR_FORMAT_PARAMS(hr));
6221 gclog_or_tty->print_cr("#### Caller: %s", caller);
6222 return false;
6223 }
6224 return true;
6225 }
6227 void G1CollectedHeap::check_bitmaps(const char* caller, HeapRegion* hr) {
6228 if (!G1VerifyBitmaps) return;
6230 guarantee(verify_bitmaps(caller, hr), "bitmap verification");
6231 }
6233 class G1VerifyBitmapClosure : public HeapRegionClosure {
6234 private:
6235 const char* _caller;
6236 G1CollectedHeap* _g1h;
6237 bool _failures;
6239 public:
6240 G1VerifyBitmapClosure(const char* caller, G1CollectedHeap* g1h) :
6241 _caller(caller), _g1h(g1h), _failures(false) { }
6243 bool failures() { return _failures; }
6245 virtual bool doHeapRegion(HeapRegion* hr) {
6246 if (hr->continuesHumongous()) return false;
6248 bool result = _g1h->verify_bitmaps(_caller, hr);
6249 if (!result) {
6250 _failures = true;
6251 }
6252 return false;
6253 }
6254 };
6256 void G1CollectedHeap::check_bitmaps(const char* caller) {
6257 if (!G1VerifyBitmaps) return;
6259 G1VerifyBitmapClosure cl(caller, this);
6260 heap_region_iterate(&cl);
6261 guarantee(!cl.failures(), "bitmap verification");
6262 }
6263 #endif // PRODUCT
6265 void G1CollectedHeap::cleanUpCardTable() {
6266 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6267 double start = os::elapsedTime();
6269 {
6270 // Iterate over the dirty cards region list.
6271 G1ParCleanupCTTask cleanup_task(ct_bs, this);
6273 if (G1CollectedHeap::use_parallel_gc_threads()) {
6274 set_par_threads();
6275 workers()->run_task(&cleanup_task);
6276 set_par_threads(0);
6277 } else {
6278 while (_dirty_cards_region_list) {
6279 HeapRegion* r = _dirty_cards_region_list;
6280 cleanup_task.clear_cards(r);
6281 _dirty_cards_region_list = r->get_next_dirty_cards_region();
6282 if (_dirty_cards_region_list == r) {
6283 // The last region.
6284 _dirty_cards_region_list = NULL;
6285 }
6286 r->set_next_dirty_cards_region(NULL);
6287 }
6288 }
6289 #ifndef PRODUCT
6290 if (G1VerifyCTCleanup || VerifyAfterGC) {
6291 G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs);
6292 heap_region_iterate(&cleanup_verifier);
6293 }
6294 #endif
6295 }
6297 double elapsed = os::elapsedTime() - start;
6298 g1_policy()->phase_times()->record_clear_ct_time(elapsed * 1000.0);
6299 }
6301 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head, EvacuationInfo& evacuation_info) {
6302 size_t pre_used = 0;
6303 FreeRegionList local_free_list("Local List for CSet Freeing");
6305 double young_time_ms = 0.0;
6306 double non_young_time_ms = 0.0;
6308 // Since the collection set is a superset of the the young list,
6309 // all we need to do to clear the young list is clear its
6310 // head and length, and unlink any young regions in the code below
6311 _young_list->clear();
6313 G1CollectorPolicy* policy = g1_policy();
6315 double start_sec = os::elapsedTime();
6316 bool non_young = true;
6318 HeapRegion* cur = cs_head;
6319 int age_bound = -1;
6320 size_t rs_lengths = 0;
6322 while (cur != NULL) {
6323 assert(!is_on_master_free_list(cur), "sanity");
6324 if (non_young) {
6325 if (cur->is_young()) {
6326 double end_sec = os::elapsedTime();
6327 double elapsed_ms = (end_sec - start_sec) * 1000.0;
6328 non_young_time_ms += elapsed_ms;
6330 start_sec = os::elapsedTime();
6331 non_young = false;
6332 }
6333 } else {
6334 if (!cur->is_young()) {
6335 double end_sec = os::elapsedTime();
6336 double elapsed_ms = (end_sec - start_sec) * 1000.0;
6337 young_time_ms += elapsed_ms;
6339 start_sec = os::elapsedTime();
6340 non_young = true;
6341 }
6342 }
6344 rs_lengths += cur->rem_set()->occupied_locked();
6346 HeapRegion* next = cur->next_in_collection_set();
6347 assert(cur->in_collection_set(), "bad CS");
6348 cur->set_next_in_collection_set(NULL);
6349 cur->set_in_collection_set(false);
6351 if (cur->is_young()) {
6352 int index = cur->young_index_in_cset();
6353 assert(index != -1, "invariant");
6354 assert((uint) index < policy->young_cset_region_length(), "invariant");
6355 size_t words_survived = _surviving_young_words[index];
6356 cur->record_surv_words_in_group(words_survived);
6358 // At this point the we have 'popped' cur from the collection set
6359 // (linked via next_in_collection_set()) but it is still in the
6360 // young list (linked via next_young_region()). Clear the
6361 // _next_young_region field.
6362 cur->set_next_young_region(NULL);
6363 } else {
6364 int index = cur->young_index_in_cset();
6365 assert(index == -1, "invariant");
6366 }
6368 assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||
6369 (!cur->is_young() && cur->young_index_in_cset() == -1),
6370 "invariant" );
6372 if (!cur->evacuation_failed()) {
6373 MemRegion used_mr = cur->used_region();
6375 // And the region is empty.
6376 assert(!used_mr.is_empty(), "Should not have empty regions in a CS.");
6377 pre_used += cur->used();
6378 free_region(cur, &local_free_list, false /* par */, true /* locked */);
6379 } else {
6380 cur->uninstall_surv_rate_group();
6381 if (cur->is_young()) {
6382 cur->set_young_index_in_cset(-1);
6383 }
6384 cur->set_not_young();
6385 cur->set_evacuation_failed(false);
6386 // The region is now considered to be old.
6387 _old_set.add(cur);
6388 evacuation_info.increment_collectionset_used_after(cur->used());
6389 }
6390 cur = next;
6391 }
6393 evacuation_info.set_regions_freed(local_free_list.length());
6394 policy->record_max_rs_lengths(rs_lengths);
6395 policy->cset_regions_freed();
6397 double end_sec = os::elapsedTime();
6398 double elapsed_ms = (end_sec - start_sec) * 1000.0;
6400 if (non_young) {
6401 non_young_time_ms += elapsed_ms;
6402 } else {
6403 young_time_ms += elapsed_ms;
6404 }
6406 prepend_to_freelist(&local_free_list);
6407 decrement_summary_bytes(pre_used);
6408 policy->phase_times()->record_young_free_cset_time_ms(young_time_ms);
6409 policy->phase_times()->record_non_young_free_cset_time_ms(non_young_time_ms);
6410 }
6412 class G1FreeHumongousRegionClosure : public HeapRegionClosure {
6413 private:
6414 FreeRegionList* _free_region_list;
6415 HeapRegionSet* _proxy_set;
6416 HeapRegionSetCount _humongous_regions_removed;
6417 size_t _freed_bytes;
6418 public:
6420 G1FreeHumongousRegionClosure(FreeRegionList* free_region_list) :
6421 _free_region_list(free_region_list), _humongous_regions_removed(), _freed_bytes(0) {
6422 }
6424 virtual bool doHeapRegion(HeapRegion* r) {
6425 if (!r->startsHumongous()) {
6426 return false;
6427 }
6429 G1CollectedHeap* g1h = G1CollectedHeap::heap();
6431 oop obj = (oop)r->bottom();
6432 CMBitMap* next_bitmap = g1h->concurrent_mark()->nextMarkBitMap();
6434 // The following checks whether the humongous object is live are sufficient.
6435 // The main additional check (in addition to having a reference from the roots
6436 // or the young gen) is whether the humongous object has a remembered set entry.
6437 //
6438 // A humongous object cannot be live if there is no remembered set for it
6439 // because:
6440 // - there can be no references from within humongous starts regions referencing
6441 // the object because we never allocate other objects into them.
6442 // (I.e. there are no intra-region references that may be missed by the
6443 // remembered set)
6444 // - as soon there is a remembered set entry to the humongous starts region
6445 // (i.e. it has "escaped" to an old object) this remembered set entry will stay
6446 // until the end of a concurrent mark.
6447 //
6448 // It is not required to check whether the object has been found dead by marking
6449 // or not, in fact it would prevent reclamation within a concurrent cycle, as
6450 // all objects allocated during that time are considered live.
6451 // SATB marking is even more conservative than the remembered set.
6452 // So if at this point in the collection there is no remembered set entry,
6453 // nobody has a reference to it.
6454 // At the start of collection we flush all refinement logs, and remembered sets
6455 // are completely up-to-date wrt to references to the humongous object.
6456 //
6457 // Other implementation considerations:
6458 // - never consider object arrays: while they are a valid target, they have not
6459 // been observed to be used as temporary objects.
6460 // - they would also pose considerable effort for cleaning up the the remembered
6461 // sets.
6462 // While this cleanup is not strictly necessary to be done (or done instantly),
6463 // given that their occurrence is very low, this saves us this additional
6464 // complexity.
6465 uint region_idx = r->hrs_index();
6466 if (g1h->humongous_is_live(region_idx) ||
6467 g1h->humongous_region_is_always_live(region_idx)) {
6469 if (G1TraceReclaimDeadHumongousObjectsAtYoungGC) {
6470 gclog_or_tty->print_cr("Live humongous %d region %d with remset "SIZE_FORMAT" code roots "SIZE_FORMAT" is marked %d live-other %d obj array %d",
6471 r->isHumongous(),
6472 region_idx,
6473 r->rem_set()->occupied(),
6474 r->rem_set()->strong_code_roots_list_length(),
6475 next_bitmap->isMarked(r->bottom()),
6476 g1h->humongous_is_live(region_idx),
6477 obj->is_objArray()
6478 );
6479 }
6481 return false;
6482 }
6484 guarantee(!obj->is_objArray(),
6485 err_msg("Eagerly reclaiming object arrays is not supported, but the object "PTR_FORMAT" is.",
6486 r->bottom()));
6488 if (G1TraceReclaimDeadHumongousObjectsAtYoungGC) {
6489 gclog_or_tty->print_cr("Reclaim humongous region %d start "PTR_FORMAT" region %d length "UINT32_FORMAT" with remset "SIZE_FORMAT" code roots "SIZE_FORMAT" is marked %d live-other %d obj array %d",
6490 r->isHumongous(),
6491 r->bottom(),
6492 region_idx,
6493 r->region_num(),
6494 r->rem_set()->occupied(),
6495 r->rem_set()->strong_code_roots_list_length(),
6496 next_bitmap->isMarked(r->bottom()),
6497 g1h->humongous_is_live(region_idx),
6498 obj->is_objArray()
6499 );
6500 }
6501 // Need to clear mark bit of the humongous object if already set.
6502 if (next_bitmap->isMarked(r->bottom())) {
6503 next_bitmap->clear(r->bottom());
6504 }
6505 _freed_bytes += r->used();
6506 r->set_containing_set(NULL);
6507 _humongous_regions_removed.increment(1u, r->capacity());
6508 g1h->free_humongous_region(r, _free_region_list, false);
6510 return false;
6511 }
6513 HeapRegionSetCount& humongous_free_count() {
6514 return _humongous_regions_removed;
6515 }
6517 size_t bytes_freed() const {
6518 return _freed_bytes;
6519 }
6521 size_t humongous_reclaimed() const {
6522 return _humongous_regions_removed.length();
6523 }
6524 };
6526 void G1CollectedHeap::eagerly_reclaim_humongous_regions() {
6527 assert_at_safepoint(true);
6529 if (!G1ReclaimDeadHumongousObjectsAtYoungGC || !_has_humongous_reclaim_candidates) {
6530 g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms(0.0, 0);
6531 return;
6532 }
6534 double start_time = os::elapsedTime();
6536 FreeRegionList local_cleanup_list("Local Humongous Cleanup List");
6538 G1FreeHumongousRegionClosure cl(&local_cleanup_list);
6539 heap_region_iterate(&cl);
6541 HeapRegionSetCount empty_set;
6542 remove_from_old_sets(empty_set, cl.humongous_free_count());
6544 G1HRPrinter* hr_printer = _g1h->hr_printer();
6545 if (hr_printer->is_active()) {
6546 FreeRegionListIterator iter(&local_cleanup_list);
6547 while (iter.more_available()) {
6548 HeapRegion* hr = iter.get_next();
6549 hr_printer->cleanup(hr);
6550 }
6551 }
6553 prepend_to_freelist(&local_cleanup_list);
6554 decrement_summary_bytes(cl.bytes_freed());
6556 g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms((os::elapsedTime() - start_time) * 1000.0,
6557 cl.humongous_reclaimed());
6558 }
6560 // This routine is similar to the above but does not record
6561 // any policy statistics or update free lists; we are abandoning
6562 // the current incremental collection set in preparation of a
6563 // full collection. After the full GC we will start to build up
6564 // the incremental collection set again.
6565 // This is only called when we're doing a full collection
6566 // and is immediately followed by the tearing down of the young list.
6568 void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) {
6569 HeapRegion* cur = cs_head;
6571 while (cur != NULL) {
6572 HeapRegion* next = cur->next_in_collection_set();
6573 assert(cur->in_collection_set(), "bad CS");
6574 cur->set_next_in_collection_set(NULL);
6575 cur->set_in_collection_set(false);
6576 cur->set_young_index_in_cset(-1);
6577 cur = next;
6578 }
6579 }
6581 void G1CollectedHeap::set_free_regions_coming() {
6582 if (G1ConcRegionFreeingVerbose) {
6583 gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
6584 "setting free regions coming");
6585 }
6587 assert(!free_regions_coming(), "pre-condition");
6588 _free_regions_coming = true;
6589 }
6591 void G1CollectedHeap::reset_free_regions_coming() {
6592 assert(free_regions_coming(), "pre-condition");
6594 {
6595 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6596 _free_regions_coming = false;
6597 SecondaryFreeList_lock->notify_all();
6598 }
6600 if (G1ConcRegionFreeingVerbose) {
6601 gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
6602 "reset free regions coming");
6603 }
6604 }
6606 void G1CollectedHeap::wait_while_free_regions_coming() {
6607 // Most of the time we won't have to wait, so let's do a quick test
6608 // first before we take the lock.
6609 if (!free_regions_coming()) {
6610 return;
6611 }
6613 if (G1ConcRegionFreeingVerbose) {
6614 gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
6615 "waiting for free regions");
6616 }
6618 {
6619 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6620 while (free_regions_coming()) {
6621 SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
6622 }
6623 }
6625 if (G1ConcRegionFreeingVerbose) {
6626 gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
6627 "done waiting for free regions");
6628 }
6629 }
6631 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
6632 assert(heap_lock_held_for_gc(),
6633 "the heap lock should already be held by or for this thread");
6634 _young_list->push_region(hr);
6635 }
6637 class NoYoungRegionsClosure: public HeapRegionClosure {
6638 private:
6639 bool _success;
6640 public:
6641 NoYoungRegionsClosure() : _success(true) { }
6642 bool doHeapRegion(HeapRegion* r) {
6643 if (r->is_young()) {
6644 gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young",
6645 r->bottom(), r->end());
6646 _success = false;
6647 }
6648 return false;
6649 }
6650 bool success() { return _success; }
6651 };
6653 bool G1CollectedHeap::check_young_list_empty(bool check_heap, bool check_sample) {
6654 bool ret = _young_list->check_list_empty(check_sample);
6656 if (check_heap) {
6657 NoYoungRegionsClosure closure;
6658 heap_region_iterate(&closure);
6659 ret = ret && closure.success();
6660 }
6662 return ret;
6663 }
6665 class TearDownRegionSetsClosure : public HeapRegionClosure {
6666 private:
6667 HeapRegionSet *_old_set;
6669 public:
6670 TearDownRegionSetsClosure(HeapRegionSet* old_set) : _old_set(old_set) { }
6672 bool doHeapRegion(HeapRegion* r) {
6673 if (r->is_empty()) {
6674 // We ignore empty regions, we'll empty the free list afterwards
6675 } else if (r->is_young()) {
6676 // We ignore young regions, we'll empty the young list afterwards
6677 } else if (r->isHumongous()) {
6678 // We ignore humongous regions, we're not tearing down the
6679 // humongous region set
6680 } else {
6681 // The rest should be old
6682 _old_set->remove(r);
6683 }
6684 return false;
6685 }
6687 ~TearDownRegionSetsClosure() {
6688 assert(_old_set->is_empty(), "post-condition");
6689 }
6690 };
6692 void G1CollectedHeap::tear_down_region_sets(bool free_list_only) {
6693 assert_at_safepoint(true /* should_be_vm_thread */);
6695 if (!free_list_only) {
6696 TearDownRegionSetsClosure cl(&_old_set);
6697 heap_region_iterate(&cl);
6699 // Note that emptying the _young_list is postponed and instead done as
6700 // the first step when rebuilding the regions sets again. The reason for
6701 // this is that during a full GC string deduplication needs to know if
6702 // a collected region was young or old when the full GC was initiated.
6703 }
6704 _hrs.remove_all_free_regions();
6705 }
6707 class RebuildRegionSetsClosure : public HeapRegionClosure {
6708 private:
6709 bool _free_list_only;
6710 HeapRegionSet* _old_set;
6711 HeapRegionSeq* _hrs;
6712 size_t _total_used;
6714 public:
6715 RebuildRegionSetsClosure(bool free_list_only,
6716 HeapRegionSet* old_set, HeapRegionSeq* hrs) :
6717 _free_list_only(free_list_only),
6718 _old_set(old_set), _hrs(hrs), _total_used(0) {
6719 assert(_hrs->num_free_regions() == 0, "pre-condition");
6720 if (!free_list_only) {
6721 assert(_old_set->is_empty(), "pre-condition");
6722 }
6723 }
6725 bool doHeapRegion(HeapRegion* r) {
6726 if (r->continuesHumongous()) {
6727 return false;
6728 }
6730 if (r->is_empty()) {
6731 // Add free regions to the free list
6732 _hrs->insert_into_free_list(r);
6733 } else if (!_free_list_only) {
6734 assert(!r->is_young(), "we should not come across young regions");
6736 if (r->isHumongous()) {
6737 // We ignore humongous regions, we left the humongous set unchanged
6738 } else {
6739 // The rest should be old, add them to the old set
6740 _old_set->add(r);
6741 }
6742 _total_used += r->used();
6743 }
6745 return false;
6746 }
6748 size_t total_used() {
6749 return _total_used;
6750 }
6751 };
6753 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
6754 assert_at_safepoint(true /* should_be_vm_thread */);
6756 if (!free_list_only) {
6757 _young_list->empty_list();
6758 }
6760 RebuildRegionSetsClosure cl(free_list_only, &_old_set, &_hrs);
6761 heap_region_iterate(&cl);
6763 if (!free_list_only) {
6764 _summary_bytes_used = cl.total_used();
6765 }
6766 assert(_summary_bytes_used == recalculate_used(),
6767 err_msg("inconsistent _summary_bytes_used, "
6768 "value: "SIZE_FORMAT" recalculated: "SIZE_FORMAT,
6769 _summary_bytes_used, recalculate_used()));
6770 }
6772 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
6773 _refine_cte_cl->set_concurrent(concurrent);
6774 }
6776 bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
6777 HeapRegion* hr = heap_region_containing(p);
6778 return hr->is_in(p);
6779 }
6781 // Methods for the mutator alloc region
6783 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
6784 bool force) {
6785 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6786 assert(!force || g1_policy()->can_expand_young_list(),
6787 "if force is true we should be able to expand the young list");
6788 bool young_list_full = g1_policy()->is_young_list_full();
6789 if (force || !young_list_full) {
6790 HeapRegion* new_alloc_region = new_region(word_size,
6791 false /* is_old */,
6792 false /* do_expand */);
6793 if (new_alloc_region != NULL) {
6794 set_region_short_lived_locked(new_alloc_region);
6795 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Eden, young_list_full);
6796 check_bitmaps("Mutator Region Allocation", new_alloc_region);
6797 return new_alloc_region;
6798 }
6799 }
6800 return NULL;
6801 }
6803 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
6804 size_t allocated_bytes) {
6805 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6806 assert(alloc_region->is_young(), "all mutator alloc regions should be young");
6808 g1_policy()->add_region_to_incremental_cset_lhs(alloc_region);
6809 _summary_bytes_used += allocated_bytes;
6810 _hr_printer.retire(alloc_region);
6811 // We update the eden sizes here, when the region is retired,
6812 // instead of when it's allocated, since this is the point that its
6813 // used space has been recored in _summary_bytes_used.
6814 g1mm()->update_eden_size();
6815 }
6817 HeapRegion* MutatorAllocRegion::allocate_new_region(size_t word_size,
6818 bool force) {
6819 return _g1h->new_mutator_alloc_region(word_size, force);
6820 }
6822 void G1CollectedHeap::set_par_threads() {
6823 // Don't change the number of workers. Use the value previously set
6824 // in the workgroup.
6825 assert(G1CollectedHeap::use_parallel_gc_threads(), "shouldn't be here otherwise");
6826 uint n_workers = workers()->active_workers();
6827 assert(UseDynamicNumberOfGCThreads ||
6828 n_workers == workers()->total_workers(),
6829 "Otherwise should be using the total number of workers");
6830 if (n_workers == 0) {
6831 assert(false, "Should have been set in prior evacuation pause.");
6832 n_workers = ParallelGCThreads;
6833 workers()->set_active_workers(n_workers);
6834 }
6835 set_par_threads(n_workers);
6836 }
6838 void MutatorAllocRegion::retire_region(HeapRegion* alloc_region,
6839 size_t allocated_bytes) {
6840 _g1h->retire_mutator_alloc_region(alloc_region, allocated_bytes);
6841 }
6843 // Methods for the GC alloc regions
6845 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size,
6846 uint count,
6847 GCAllocPurpose ap) {
6848 assert(FreeList_lock->owned_by_self(), "pre-condition");
6850 if (count < g1_policy()->max_regions(ap)) {
6851 bool survivor = (ap == GCAllocForSurvived);
6852 HeapRegion* new_alloc_region = new_region(word_size,
6853 !survivor,
6854 true /* do_expand */);
6855 if (new_alloc_region != NULL) {
6856 // We really only need to do this for old regions given that we
6857 // should never scan survivors. But it doesn't hurt to do it
6858 // for survivors too.
6859 new_alloc_region->record_top_and_timestamp();
6860 if (survivor) {
6861 new_alloc_region->set_survivor();
6862 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor);
6863 check_bitmaps("Survivor Region Allocation", new_alloc_region);
6864 } else {
6865 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Old);
6866 check_bitmaps("Old Region Allocation", new_alloc_region);
6867 }
6868 bool during_im = g1_policy()->during_initial_mark_pause();
6869 new_alloc_region->note_start_of_copying(during_im);
6870 return new_alloc_region;
6871 } else {
6872 g1_policy()->note_alloc_region_limit_reached(ap);
6873 }
6874 }
6875 return NULL;
6876 }
6878 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
6879 size_t allocated_bytes,
6880 GCAllocPurpose ap) {
6881 bool during_im = g1_policy()->during_initial_mark_pause();
6882 alloc_region->note_end_of_copying(during_im);
6883 g1_policy()->record_bytes_copied_during_gc(allocated_bytes);
6884 if (ap == GCAllocForSurvived) {
6885 young_list()->add_survivor_region(alloc_region);
6886 } else {
6887 _old_set.add(alloc_region);
6888 }
6889 _hr_printer.retire(alloc_region);
6890 }
6892 HeapRegion* SurvivorGCAllocRegion::allocate_new_region(size_t word_size,
6893 bool force) {
6894 assert(!force, "not supported for GC alloc regions");
6895 return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForSurvived);
6896 }
6898 void SurvivorGCAllocRegion::retire_region(HeapRegion* alloc_region,
6899 size_t allocated_bytes) {
6900 _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
6901 GCAllocForSurvived);
6902 }
6904 HeapRegion* OldGCAllocRegion::allocate_new_region(size_t word_size,
6905 bool force) {
6906 assert(!force, "not supported for GC alloc regions");
6907 return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForTenured);
6908 }
6910 void OldGCAllocRegion::retire_region(HeapRegion* alloc_region,
6911 size_t allocated_bytes) {
6912 _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
6913 GCAllocForTenured);
6914 }
6916 HeapRegion* OldGCAllocRegion::release() {
6917 HeapRegion* cur = get();
6918 if (cur != NULL) {
6919 // Determine how far we are from the next card boundary. If it is smaller than
6920 // the minimum object size we can allocate into, expand into the next card.
6921 HeapWord* top = cur->top();
6922 HeapWord* aligned_top = (HeapWord*)align_ptr_up(top, G1BlockOffsetSharedArray::N_bytes);
6924 size_t to_allocate_words = pointer_delta(aligned_top, top, HeapWordSize);
6926 if (to_allocate_words != 0) {
6927 // We are not at a card boundary. Fill up, possibly into the next, taking the
6928 // end of the region and the minimum object size into account.
6929 to_allocate_words = MIN2(pointer_delta(cur->end(), cur->top(), HeapWordSize),
6930 MAX2(to_allocate_words, G1CollectedHeap::min_fill_size()));
6932 // Skip allocation if there is not enough space to allocate even the smallest
6933 // possible object. In this case this region will not be retained, so the
6934 // original problem cannot occur.
6935 if (to_allocate_words >= G1CollectedHeap::min_fill_size()) {
6936 HeapWord* dummy = attempt_allocation(to_allocate_words, true /* bot_updates */);
6937 CollectedHeap::fill_with_object(dummy, to_allocate_words);
6938 }
6939 }
6940 }
6941 return G1AllocRegion::release();
6942 }
6944 // Heap region set verification
6946 class VerifyRegionListsClosure : public HeapRegionClosure {
6947 private:
6948 HeapRegionSet* _old_set;
6949 HeapRegionSet* _humongous_set;
6950 HeapRegionSeq* _hrs;
6952 public:
6953 HeapRegionSetCount _old_count;
6954 HeapRegionSetCount _humongous_count;
6955 HeapRegionSetCount _free_count;
6957 VerifyRegionListsClosure(HeapRegionSet* old_set,
6958 HeapRegionSet* humongous_set,
6959 HeapRegionSeq* hrs) :
6960 _old_set(old_set), _humongous_set(humongous_set), _hrs(hrs),
6961 _old_count(), _humongous_count(), _free_count(){ }
6963 bool doHeapRegion(HeapRegion* hr) {
6964 if (hr->continuesHumongous()) {
6965 return false;
6966 }
6968 if (hr->is_young()) {
6969 // TODO
6970 } else if (hr->startsHumongous()) {
6971 assert(hr->containing_set() == _humongous_set, err_msg("Heap region %u is starts humongous but not in humongous set.", hr->hrs_index()));
6972 _humongous_count.increment(1u, hr->capacity());
6973 } else if (hr->is_empty()) {
6974 assert(_hrs->is_free(hr), err_msg("Heap region %u is empty but not on the free list.", hr->hrs_index()));
6975 _free_count.increment(1u, hr->capacity());
6976 } else {
6977 assert(hr->containing_set() == _old_set, err_msg("Heap region %u is old but not in the old set.", hr->hrs_index()));
6978 _old_count.increment(1u, hr->capacity());
6979 }
6980 return false;
6981 }
6983 void verify_counts(HeapRegionSet* old_set, HeapRegionSet* humongous_set, HeapRegionSeq* free_list) {
6984 guarantee(old_set->length() == _old_count.length(), err_msg("Old set count mismatch. Expected %u, actual %u.", old_set->length(), _old_count.length()));
6985 guarantee(old_set->total_capacity_bytes() == _old_count.capacity(), err_msg("Old set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6986 old_set->total_capacity_bytes(), _old_count.capacity()));
6988 guarantee(humongous_set->length() == _humongous_count.length(), err_msg("Hum set count mismatch. Expected %u, actual %u.", humongous_set->length(), _humongous_count.length()));
6989 guarantee(humongous_set->total_capacity_bytes() == _humongous_count.capacity(), err_msg("Hum set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6990 humongous_set->total_capacity_bytes(), _humongous_count.capacity()));
6992 guarantee(free_list->num_free_regions() == _free_count.length(), err_msg("Free list count mismatch. Expected %u, actual %u.", free_list->num_free_regions(), _free_count.length()));
6993 guarantee(free_list->total_capacity_bytes() == _free_count.capacity(), err_msg("Free list capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6994 free_list->total_capacity_bytes(), _free_count.capacity()));
6995 }
6996 };
6998 void G1CollectedHeap::verify_region_sets() {
6999 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
7001 // First, check the explicit lists.
7002 _hrs.verify();
7003 {
7004 // Given that a concurrent operation might be adding regions to
7005 // the secondary free list we have to take the lock before
7006 // verifying it.
7007 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
7008 _secondary_free_list.verify_list();
7009 }
7011 // If a concurrent region freeing operation is in progress it will
7012 // be difficult to correctly attributed any free regions we come
7013 // across to the correct free list given that they might belong to
7014 // one of several (free_list, secondary_free_list, any local lists,
7015 // etc.). So, if that's the case we will skip the rest of the
7016 // verification operation. Alternatively, waiting for the concurrent
7017 // operation to complete will have a non-trivial effect on the GC's
7018 // operation (no concurrent operation will last longer than the
7019 // interval between two calls to verification) and it might hide
7020 // any issues that we would like to catch during testing.
7021 if (free_regions_coming()) {
7022 return;
7023 }
7025 // Make sure we append the secondary_free_list on the free_list so
7026 // that all free regions we will come across can be safely
7027 // attributed to the free_list.
7028 append_secondary_free_list_if_not_empty_with_lock();
7030 // Finally, make sure that the region accounting in the lists is
7031 // consistent with what we see in the heap.
7033 VerifyRegionListsClosure cl(&_old_set, &_humongous_set, &_hrs);
7034 heap_region_iterate(&cl);
7035 cl.verify_counts(&_old_set, &_humongous_set, &_hrs);
7036 }
7038 // Optimized nmethod scanning
7040 class RegisterNMethodOopClosure: public OopClosure {
7041 G1CollectedHeap* _g1h;
7042 nmethod* _nm;
7044 template <class T> void do_oop_work(T* p) {
7045 T heap_oop = oopDesc::load_heap_oop(p);
7046 if (!oopDesc::is_null(heap_oop)) {
7047 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
7048 HeapRegion* hr = _g1h->heap_region_containing(obj);
7049 assert(!hr->continuesHumongous(),
7050 err_msg("trying to add code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
7051 " starting at "HR_FORMAT,
7052 _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
7054 // HeapRegion::add_strong_code_root() avoids adding duplicate
7055 // entries but having duplicates is OK since we "mark" nmethods
7056 // as visited when we scan the strong code root lists during the GC.
7057 hr->add_strong_code_root(_nm);
7058 assert(hr->rem_set()->strong_code_roots_list_contains(_nm),
7059 err_msg("failed to add code root "PTR_FORMAT" to remembered set of region "HR_FORMAT,
7060 _nm, HR_FORMAT_PARAMS(hr)));
7061 }
7062 }
7064 public:
7065 RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
7066 _g1h(g1h), _nm(nm) {}
7068 void do_oop(oop* p) { do_oop_work(p); }
7069 void do_oop(narrowOop* p) { do_oop_work(p); }
7070 };
7072 class UnregisterNMethodOopClosure: public OopClosure {
7073 G1CollectedHeap* _g1h;
7074 nmethod* _nm;
7076 template <class T> void do_oop_work(T* p) {
7077 T heap_oop = oopDesc::load_heap_oop(p);
7078 if (!oopDesc::is_null(heap_oop)) {
7079 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
7080 HeapRegion* hr = _g1h->heap_region_containing(obj);
7081 assert(!hr->continuesHumongous(),
7082 err_msg("trying to remove code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
7083 " starting at "HR_FORMAT,
7084 _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
7086 hr->remove_strong_code_root(_nm);
7087 assert(!hr->rem_set()->strong_code_roots_list_contains(_nm),
7088 err_msg("failed to remove code root "PTR_FORMAT" of region "HR_FORMAT,
7089 _nm, HR_FORMAT_PARAMS(hr)));
7090 }
7091 }
7093 public:
7094 UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
7095 _g1h(g1h), _nm(nm) {}
7097 void do_oop(oop* p) { do_oop_work(p); }
7098 void do_oop(narrowOop* p) { do_oop_work(p); }
7099 };
7101 void G1CollectedHeap::register_nmethod(nmethod* nm) {
7102 CollectedHeap::register_nmethod(nm);
7104 guarantee(nm != NULL, "sanity");
7105 RegisterNMethodOopClosure reg_cl(this, nm);
7106 nm->oops_do(®_cl);
7107 }
7109 void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
7110 CollectedHeap::unregister_nmethod(nm);
7112 guarantee(nm != NULL, "sanity");
7113 UnregisterNMethodOopClosure reg_cl(this, nm);
7114 nm->oops_do(®_cl, true);
7115 }
7117 class MigrateCodeRootsHeapRegionClosure: public HeapRegionClosure {
7118 public:
7119 bool doHeapRegion(HeapRegion *hr) {
7120 assert(!hr->isHumongous(),
7121 err_msg("humongous region "HR_FORMAT" should not have been added to collection set",
7122 HR_FORMAT_PARAMS(hr)));
7123 hr->migrate_strong_code_roots();
7124 return false;
7125 }
7126 };
7128 void G1CollectedHeap::migrate_strong_code_roots() {
7129 MigrateCodeRootsHeapRegionClosure cl;
7130 double migrate_start = os::elapsedTime();
7131 collection_set_iterate(&cl);
7132 double migration_time_ms = (os::elapsedTime() - migrate_start) * 1000.0;
7133 g1_policy()->phase_times()->record_strong_code_root_migration_time(migration_time_ms);
7134 }
7136 void G1CollectedHeap::purge_code_root_memory() {
7137 double purge_start = os::elapsedTime();
7138 G1CodeRootSet::purge_chunks(G1CodeRootsChunkCacheKeepPercent);
7139 double purge_time_ms = (os::elapsedTime() - purge_start) * 1000.0;
7140 g1_policy()->phase_times()->record_strong_code_root_purge_time(purge_time_ms);
7141 }
7143 class RebuildStrongCodeRootClosure: public CodeBlobClosure {
7144 G1CollectedHeap* _g1h;
7146 public:
7147 RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :
7148 _g1h(g1h) {}
7150 void do_code_blob(CodeBlob* cb) {
7151 nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
7152 if (nm == NULL) {
7153 return;
7154 }
7156 if (ScavengeRootsInCode) {
7157 _g1h->register_nmethod(nm);
7158 }
7159 }
7160 };
7162 void G1CollectedHeap::rebuild_strong_code_roots() {
7163 RebuildStrongCodeRootClosure blob_cl(this);
7164 CodeCache::blobs_do(&blob_cl);
7165 }