Tue, 18 Mar 2014 19:07:22 +0100
8029075: String deduplication in G1
Summary: Implementation of JEP 192, http://openjdk.java.net/jeps/192
Reviewed-by: brutisso, tschatzl, coleenp
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 #include "precompiled.hpp"
26 #include "code/codeCache.hpp"
27 #include "code/icBuffer.hpp"
28 #include "gc_implementation/g1/bufferingOopClosure.hpp"
29 #include "gc_implementation/g1/concurrentG1Refine.hpp"
30 #include "gc_implementation/g1/concurrentG1RefineThread.hpp"
31 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
32 #include "gc_implementation/g1/g1AllocRegion.inline.hpp"
33 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
34 #include "gc_implementation/g1/g1CollectorPolicy.hpp"
35 #include "gc_implementation/g1/g1ErgoVerbose.hpp"
36 #include "gc_implementation/g1/g1EvacFailure.hpp"
37 #include "gc_implementation/g1/g1GCPhaseTimes.hpp"
38 #include "gc_implementation/g1/g1Log.hpp"
39 #include "gc_implementation/g1/g1MarkSweep.hpp"
40 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
41 #include "gc_implementation/g1/g1RemSet.inline.hpp"
42 #include "gc_implementation/g1/g1StringDedup.hpp"
43 #include "gc_implementation/g1/g1YCTypes.hpp"
44 #include "gc_implementation/g1/heapRegion.inline.hpp"
45 #include "gc_implementation/g1/heapRegionRemSet.hpp"
46 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
47 #include "gc_implementation/g1/vm_operations_g1.hpp"
48 #include "gc_implementation/shared/gcHeapSummary.hpp"
49 #include "gc_implementation/shared/gcTimer.hpp"
50 #include "gc_implementation/shared/gcTrace.hpp"
51 #include "gc_implementation/shared/gcTraceTime.hpp"
52 #include "gc_implementation/shared/isGCActiveMark.hpp"
53 #include "memory/gcLocker.inline.hpp"
54 #include "memory/generationSpec.hpp"
55 #include "memory/iterator.hpp"
56 #include "memory/referenceProcessor.hpp"
57 #include "oops/oop.inline.hpp"
58 #include "oops/oop.pcgc.inline.hpp"
59 #include "runtime/vmThread.hpp"
60 #include "utilities/ticks.hpp"
62 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
64 // turn it on so that the contents of the young list (scan-only /
65 // to-be-collected) are printed at "strategic" points before / during
66 // / after the collection --- this is useful for debugging
67 #define YOUNG_LIST_VERBOSE 0
68 // CURRENT STATUS
69 // This file is under construction. Search for "FIXME".
71 // INVARIANTS/NOTES
72 //
73 // All allocation activity covered by the G1CollectedHeap interface is
74 // serialized by acquiring the HeapLock. This happens in mem_allocate
75 // and allocate_new_tlab, which are the "entry" points to the
76 // allocation code from the rest of the JVM. (Note that this does not
77 // apply to TLAB allocation, which is not part of this interface: it
78 // is done by clients of this interface.)
80 // Notes on implementation of parallelism in different tasks.
81 //
82 // G1ParVerifyTask uses heap_region_par_iterate_chunked() for parallelism.
83 // The number of GC workers is passed to heap_region_par_iterate_chunked().
84 // It does use run_task() which sets _n_workers in the task.
85 // G1ParTask executes g1_process_strong_roots() ->
86 // SharedHeap::process_strong_roots() which calls eventually to
87 // CardTableModRefBS::par_non_clean_card_iterate_work() which uses
88 // SequentialSubTasksDone. SharedHeap::process_strong_roots() also
89 // directly uses SubTasksDone (_process_strong_tasks field in SharedHeap).
90 //
92 // Local to this file.
94 class RefineCardTableEntryClosure: public CardTableEntryClosure {
95 SuspendibleThreadSet* _sts;
96 G1RemSet* _g1rs;
97 ConcurrentG1Refine* _cg1r;
98 bool _concurrent;
99 public:
100 RefineCardTableEntryClosure(SuspendibleThreadSet* sts,
101 G1RemSet* g1rs,
102 ConcurrentG1Refine* cg1r) :
103 _sts(sts), _g1rs(g1rs), _cg1r(cg1r), _concurrent(true)
104 {}
105 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
106 bool oops_into_cset = _g1rs->refine_card(card_ptr, worker_i, false);
107 // This path is executed by the concurrent refine or mutator threads,
108 // concurrently, and so we do not care if card_ptr contains references
109 // that point into the collection set.
110 assert(!oops_into_cset, "should be");
112 if (_concurrent && _sts->should_yield()) {
113 // Caller will actually yield.
114 return false;
115 }
116 // Otherwise, we finished successfully; return true.
117 return true;
118 }
119 void set_concurrent(bool b) { _concurrent = b; }
120 };
123 class ClearLoggedCardTableEntryClosure: public CardTableEntryClosure {
124 int _calls;
125 G1CollectedHeap* _g1h;
126 CardTableModRefBS* _ctbs;
127 int _histo[256];
128 public:
129 ClearLoggedCardTableEntryClosure() :
130 _calls(0), _g1h(G1CollectedHeap::heap()), _ctbs(_g1h->g1_barrier_set())
131 {
132 for (int i = 0; i < 256; i++) _histo[i] = 0;
133 }
134 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
135 if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
136 _calls++;
137 unsigned char* ujb = (unsigned char*)card_ptr;
138 int ind = (int)(*ujb);
139 _histo[ind]++;
140 *card_ptr = -1;
141 }
142 return true;
143 }
144 int calls() { return _calls; }
145 void print_histo() {
146 gclog_or_tty->print_cr("Card table value histogram:");
147 for (int i = 0; i < 256; i++) {
148 if (_histo[i] != 0) {
149 gclog_or_tty->print_cr(" %d: %d", i, _histo[i]);
150 }
151 }
152 }
153 };
155 class RedirtyLoggedCardTableEntryClosure: public CardTableEntryClosure {
156 int _calls;
157 G1CollectedHeap* _g1h;
158 CardTableModRefBS* _ctbs;
159 public:
160 RedirtyLoggedCardTableEntryClosure() :
161 _calls(0), _g1h(G1CollectedHeap::heap()), _ctbs(_g1h->g1_barrier_set()) {}
163 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
164 if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
165 _calls++;
166 *card_ptr = 0;
167 }
168 return true;
169 }
170 int calls() { return _calls; }
171 };
173 YoungList::YoungList(G1CollectedHeap* g1h) :
174 _g1h(g1h), _head(NULL), _length(0), _last_sampled_rs_lengths(0),
175 _survivor_head(NULL), _survivor_tail(NULL), _survivor_length(0) {
176 guarantee(check_list_empty(false), "just making sure...");
177 }
179 void YoungList::push_region(HeapRegion *hr) {
180 assert(!hr->is_young(), "should not already be young");
181 assert(hr->get_next_young_region() == NULL, "cause it should!");
183 hr->set_next_young_region(_head);
184 _head = hr;
186 _g1h->g1_policy()->set_region_eden(hr, (int) _length);
187 ++_length;
188 }
190 void YoungList::add_survivor_region(HeapRegion* hr) {
191 assert(hr->is_survivor(), "should be flagged as survivor region");
192 assert(hr->get_next_young_region() == NULL, "cause it should!");
194 hr->set_next_young_region(_survivor_head);
195 if (_survivor_head == NULL) {
196 _survivor_tail = hr;
197 }
198 _survivor_head = hr;
199 ++_survivor_length;
200 }
202 void YoungList::empty_list(HeapRegion* list) {
203 while (list != NULL) {
204 HeapRegion* next = list->get_next_young_region();
205 list->set_next_young_region(NULL);
206 list->uninstall_surv_rate_group();
207 list->set_not_young();
208 list = next;
209 }
210 }
212 void YoungList::empty_list() {
213 assert(check_list_well_formed(), "young list should be well formed");
215 empty_list(_head);
216 _head = NULL;
217 _length = 0;
219 empty_list(_survivor_head);
220 _survivor_head = NULL;
221 _survivor_tail = NULL;
222 _survivor_length = 0;
224 _last_sampled_rs_lengths = 0;
226 assert(check_list_empty(false), "just making sure...");
227 }
229 bool YoungList::check_list_well_formed() {
230 bool ret = true;
232 uint length = 0;
233 HeapRegion* curr = _head;
234 HeapRegion* last = NULL;
235 while (curr != NULL) {
236 if (!curr->is_young()) {
237 gclog_or_tty->print_cr("### YOUNG REGION "PTR_FORMAT"-"PTR_FORMAT" "
238 "incorrectly tagged (y: %d, surv: %d)",
239 curr->bottom(), curr->end(),
240 curr->is_young(), curr->is_survivor());
241 ret = false;
242 }
243 ++length;
244 last = curr;
245 curr = curr->get_next_young_region();
246 }
247 ret = ret && (length == _length);
249 if (!ret) {
250 gclog_or_tty->print_cr("### YOUNG LIST seems not well formed!");
251 gclog_or_tty->print_cr("### list has %u entries, _length is %u",
252 length, _length);
253 }
255 return ret;
256 }
258 bool YoungList::check_list_empty(bool check_sample) {
259 bool ret = true;
261 if (_length != 0) {
262 gclog_or_tty->print_cr("### YOUNG LIST should have 0 length, not %u",
263 _length);
264 ret = false;
265 }
266 if (check_sample && _last_sampled_rs_lengths != 0) {
267 gclog_or_tty->print_cr("### YOUNG LIST has non-zero last sampled RS lengths");
268 ret = false;
269 }
270 if (_head != NULL) {
271 gclog_or_tty->print_cr("### YOUNG LIST does not have a NULL head");
272 ret = false;
273 }
274 if (!ret) {
275 gclog_or_tty->print_cr("### YOUNG LIST does not seem empty");
276 }
278 return ret;
279 }
281 void
282 YoungList::rs_length_sampling_init() {
283 _sampled_rs_lengths = 0;
284 _curr = _head;
285 }
287 bool
288 YoungList::rs_length_sampling_more() {
289 return _curr != NULL;
290 }
292 void
293 YoungList::rs_length_sampling_next() {
294 assert( _curr != NULL, "invariant" );
295 size_t rs_length = _curr->rem_set()->occupied();
297 _sampled_rs_lengths += rs_length;
299 // The current region may not yet have been added to the
300 // incremental collection set (it gets added when it is
301 // retired as the current allocation region).
302 if (_curr->in_collection_set()) {
303 // Update the collection set policy information for this region
304 _g1h->g1_policy()->update_incremental_cset_info(_curr, rs_length);
305 }
307 _curr = _curr->get_next_young_region();
308 if (_curr == NULL) {
309 _last_sampled_rs_lengths = _sampled_rs_lengths;
310 // gclog_or_tty->print_cr("last sampled RS lengths = %d", _last_sampled_rs_lengths);
311 }
312 }
314 void
315 YoungList::reset_auxilary_lists() {
316 guarantee( is_empty(), "young list should be empty" );
317 assert(check_list_well_formed(), "young list should be well formed");
319 // Add survivor regions to SurvRateGroup.
320 _g1h->g1_policy()->note_start_adding_survivor_regions();
321 _g1h->g1_policy()->finished_recalculating_age_indexes(true /* is_survivors */);
323 int young_index_in_cset = 0;
324 for (HeapRegion* curr = _survivor_head;
325 curr != NULL;
326 curr = curr->get_next_young_region()) {
327 _g1h->g1_policy()->set_region_survivor(curr, young_index_in_cset);
329 // The region is a non-empty survivor so let's add it to
330 // the incremental collection set for the next evacuation
331 // pause.
332 _g1h->g1_policy()->add_region_to_incremental_cset_rhs(curr);
333 young_index_in_cset += 1;
334 }
335 assert((uint) young_index_in_cset == _survivor_length, "post-condition");
336 _g1h->g1_policy()->note_stop_adding_survivor_regions();
338 _head = _survivor_head;
339 _length = _survivor_length;
340 if (_survivor_head != NULL) {
341 assert(_survivor_tail != NULL, "cause it shouldn't be");
342 assert(_survivor_length > 0, "invariant");
343 _survivor_tail->set_next_young_region(NULL);
344 }
346 // Don't clear the survivor list handles until the start of
347 // the next evacuation pause - we need it in order to re-tag
348 // the survivor regions from this evacuation pause as 'young'
349 // at the start of the next.
351 _g1h->g1_policy()->finished_recalculating_age_indexes(false /* is_survivors */);
353 assert(check_list_well_formed(), "young list should be well formed");
354 }
356 void YoungList::print() {
357 HeapRegion* lists[] = {_head, _survivor_head};
358 const char* names[] = {"YOUNG", "SURVIVOR"};
360 for (unsigned int list = 0; list < ARRAY_SIZE(lists); ++list) {
361 gclog_or_tty->print_cr("%s LIST CONTENTS", names[list]);
362 HeapRegion *curr = lists[list];
363 if (curr == NULL)
364 gclog_or_tty->print_cr(" empty");
365 while (curr != NULL) {
366 gclog_or_tty->print_cr(" "HR_FORMAT", P: "PTR_FORMAT "N: "PTR_FORMAT", age: %4d",
367 HR_FORMAT_PARAMS(curr),
368 curr->prev_top_at_mark_start(),
369 curr->next_top_at_mark_start(),
370 curr->age_in_surv_rate_group_cond());
371 curr = curr->get_next_young_region();
372 }
373 }
375 gclog_or_tty->print_cr("");
376 }
378 void G1CollectedHeap::push_dirty_cards_region(HeapRegion* hr)
379 {
380 // Claim the right to put the region on the dirty cards region list
381 // by installing a self pointer.
382 HeapRegion* next = hr->get_next_dirty_cards_region();
383 if (next == NULL) {
384 HeapRegion* res = (HeapRegion*)
385 Atomic::cmpxchg_ptr(hr, hr->next_dirty_cards_region_addr(),
386 NULL);
387 if (res == NULL) {
388 HeapRegion* head;
389 do {
390 // Put the region to the dirty cards region list.
391 head = _dirty_cards_region_list;
392 next = (HeapRegion*)
393 Atomic::cmpxchg_ptr(hr, &_dirty_cards_region_list, head);
394 if (next == head) {
395 assert(hr->get_next_dirty_cards_region() == hr,
396 "hr->get_next_dirty_cards_region() != hr");
397 if (next == NULL) {
398 // The last region in the list points to itself.
399 hr->set_next_dirty_cards_region(hr);
400 } else {
401 hr->set_next_dirty_cards_region(next);
402 }
403 }
404 } while (next != head);
405 }
406 }
407 }
409 HeapRegion* G1CollectedHeap::pop_dirty_cards_region()
410 {
411 HeapRegion* head;
412 HeapRegion* hr;
413 do {
414 head = _dirty_cards_region_list;
415 if (head == NULL) {
416 return NULL;
417 }
418 HeapRegion* new_head = head->get_next_dirty_cards_region();
419 if (head == new_head) {
420 // The last region.
421 new_head = NULL;
422 }
423 hr = (HeapRegion*)Atomic::cmpxchg_ptr(new_head, &_dirty_cards_region_list,
424 head);
425 } while (hr != head);
426 assert(hr != NULL, "invariant");
427 hr->set_next_dirty_cards_region(NULL);
428 return hr;
429 }
431 void G1CollectedHeap::stop_conc_gc_threads() {
432 _cg1r->stop();
433 _cmThread->stop();
434 }
436 #ifdef ASSERT
437 // A region is added to the collection set as it is retired
438 // so an address p can point to a region which will be in the
439 // collection set but has not yet been retired. This method
440 // therefore is only accurate during a GC pause after all
441 // regions have been retired. It is used for debugging
442 // to check if an nmethod has references to objects that can
443 // be move during a partial collection. Though it can be
444 // inaccurate, it is sufficient for G1 because the conservative
445 // implementation of is_scavengable() for G1 will indicate that
446 // all nmethods must be scanned during a partial collection.
447 bool G1CollectedHeap::is_in_partial_collection(const void* p) {
448 HeapRegion* hr = heap_region_containing(p);
449 return hr != NULL && hr->in_collection_set();
450 }
451 #endif
453 // Returns true if the reference points to an object that
454 // can move in an incremental collection.
455 bool G1CollectedHeap::is_scavengable(const void* p) {
456 G1CollectedHeap* g1h = G1CollectedHeap::heap();
457 G1CollectorPolicy* g1p = g1h->g1_policy();
458 HeapRegion* hr = heap_region_containing(p);
459 if (hr == NULL) {
460 // null
461 assert(p == NULL, err_msg("Not NULL " PTR_FORMAT ,p));
462 return false;
463 } else {
464 return !hr->isHumongous();
465 }
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.set_closure(&clear);
480 dcqs.apply_closure_to_all_completed_buffers();
481 dcqs.iterate_closure_all_threads(false);
482 clear.print_histo();
484 // Now ensure that there's no dirty cards.
485 CountNonCleanMemRegionClosure count2(this);
486 ct_bs->mod_card_iterate(&count2);
487 if (count2.n() != 0) {
488 gclog_or_tty->print_cr("Card table has %d entries; %d originally",
489 count2.n(), orig_count);
490 }
491 guarantee(count2.n() == 0, "Card table should be clean.");
493 RedirtyLoggedCardTableEntryClosure redirty;
494 JavaThread::dirty_card_queue_set().set_closure(&redirty);
495 dcqs.apply_closure_to_all_completed_buffers();
496 dcqs.iterate_closure_all_threads(false);
497 gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",
498 clear.calls(), orig_count);
499 guarantee(redirty.calls() == clear.calls(),
500 "Or else mechanism is broken.");
502 CountNonCleanMemRegionClosure count3(this);
503 ct_bs->mod_card_iterate(&count3);
504 if (count3.n() != orig_count) {
505 gclog_or_tty->print_cr("Should have restored them all: orig = %d, final = %d.",
506 orig_count, count3.n());
507 guarantee(count3.n() >= orig_count, "Should have restored them all.");
508 }
510 JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
511 }
513 // Private class members.
515 G1CollectedHeap* G1CollectedHeap::_g1h;
517 // Private methods.
519 HeapRegion*
520 G1CollectedHeap::new_region_try_secondary_free_list() {
521 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
522 while (!_secondary_free_list.is_empty() || free_regions_coming()) {
523 if (!_secondary_free_list.is_empty()) {
524 if (G1ConcRegionFreeingVerbose) {
525 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
526 "secondary_free_list has %u entries",
527 _secondary_free_list.length());
528 }
529 // It looks as if there are free regions available on the
530 // secondary_free_list. Let's move them to the free_list and try
531 // again to allocate from it.
532 append_secondary_free_list();
534 assert(!_free_list.is_empty(), "if the secondary_free_list was not "
535 "empty we should have moved at least one entry to the free_list");
536 HeapRegion* res = _free_list.remove_head();
537 if (G1ConcRegionFreeingVerbose) {
538 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
539 "allocated "HR_FORMAT" from secondary_free_list",
540 HR_FORMAT_PARAMS(res));
541 }
542 return res;
543 }
545 // Wait here until we get notified either when (a) there are no
546 // more free regions coming or (b) some regions have been moved on
547 // the secondary_free_list.
548 SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
549 }
551 if (G1ConcRegionFreeingVerbose) {
552 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
553 "could not allocate from secondary_free_list");
554 }
555 return NULL;
556 }
558 HeapRegion* G1CollectedHeap::new_region(size_t word_size, bool do_expand) {
559 assert(!isHumongous(word_size) || word_size <= HeapRegion::GrainWords,
560 "the only time we use this to allocate a humongous region is "
561 "when we are allocating a single humongous region");
563 HeapRegion* res;
564 if (G1StressConcRegionFreeing) {
565 if (!_secondary_free_list.is_empty()) {
566 if (G1ConcRegionFreeingVerbose) {
567 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
568 "forced to look at the secondary_free_list");
569 }
570 res = new_region_try_secondary_free_list();
571 if (res != NULL) {
572 return res;
573 }
574 }
575 }
576 res = _free_list.remove_head_or_null();
577 if (res == NULL) {
578 if (G1ConcRegionFreeingVerbose) {
579 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
580 "res == NULL, trying the secondary_free_list");
581 }
582 res = new_region_try_secondary_free_list();
583 }
584 if (res == NULL && do_expand && _expand_heap_after_alloc_failure) {
585 // Currently, only attempts to allocate GC alloc regions set
586 // do_expand to true. So, we should only reach here during a
587 // safepoint. If this assumption changes we might have to
588 // reconsider the use of _expand_heap_after_alloc_failure.
589 assert(SafepointSynchronize::is_at_safepoint(), "invariant");
591 ergo_verbose1(ErgoHeapSizing,
592 "attempt heap expansion",
593 ergo_format_reason("region allocation request failed")
594 ergo_format_byte("allocation request"),
595 word_size * HeapWordSize);
596 if (expand(word_size * HeapWordSize)) {
597 // Given that expand() succeeded in expanding the heap, and we
598 // always expand the heap by an amount aligned to the heap
599 // region size, the free list should in theory not be empty. So
600 // it would probably be OK to use remove_head(). But the extra
601 // check for NULL is unlikely to be a performance issue here (we
602 // just expanded the heap!) so let's just be conservative and
603 // use remove_head_or_null().
604 res = _free_list.remove_head_or_null();
605 } else {
606 _expand_heap_after_alloc_failure = false;
607 }
608 }
609 return res;
610 }
612 uint G1CollectedHeap::humongous_obj_allocate_find_first(uint num_regions,
613 size_t word_size) {
614 assert(isHumongous(word_size), "word_size should be humongous");
615 assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
617 uint first = G1_NULL_HRS_INDEX;
618 if (num_regions == 1) {
619 // Only one region to allocate, no need to go through the slower
620 // path. The caller will attempt the expansion if this fails, so
621 // let's not try to expand here too.
622 HeapRegion* hr = new_region(word_size, false /* do_expand */);
623 if (hr != NULL) {
624 first = hr->hrs_index();
625 } else {
626 first = G1_NULL_HRS_INDEX;
627 }
628 } else {
629 // We can't allocate humongous regions while cleanupComplete() is
630 // running, since some of the regions we find to be empty might not
631 // yet be added to the free list and it is not straightforward to
632 // know which list they are on so that we can remove them. Note
633 // that we only need to do this if we need to allocate more than
634 // one region to satisfy the current humongous allocation
635 // request. If we are only allocating one region we use the common
636 // region allocation code (see above).
637 wait_while_free_regions_coming();
638 append_secondary_free_list_if_not_empty_with_lock();
640 if (free_regions() >= num_regions) {
641 first = _hrs.find_contiguous(num_regions);
642 if (first != G1_NULL_HRS_INDEX) {
643 for (uint i = first; i < first + num_regions; ++i) {
644 HeapRegion* hr = region_at(i);
645 assert(hr->is_empty(), "sanity");
646 assert(is_on_master_free_list(hr), "sanity");
647 hr->set_pending_removal(true);
648 }
649 _free_list.remove_all_pending(num_regions);
650 }
651 }
652 }
653 return first;
654 }
656 HeapWord*
657 G1CollectedHeap::humongous_obj_allocate_initialize_regions(uint first,
658 uint num_regions,
659 size_t word_size) {
660 assert(first != G1_NULL_HRS_INDEX, "pre-condition");
661 assert(isHumongous(word_size), "word_size should be humongous");
662 assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
664 // Index of last region in the series + 1.
665 uint last = first + num_regions;
667 // We need to initialize the region(s) we just discovered. This is
668 // a bit tricky given that it can happen concurrently with
669 // refinement threads refining cards on these regions and
670 // potentially wanting to refine the BOT as they are scanning
671 // those cards (this can happen shortly after a cleanup; see CR
672 // 6991377). So we have to set up the region(s) carefully and in
673 // a specific order.
675 // The word size sum of all the regions we will allocate.
676 size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;
677 assert(word_size <= word_size_sum, "sanity");
679 // This will be the "starts humongous" region.
680 HeapRegion* first_hr = region_at(first);
681 // The header of the new object will be placed at the bottom of
682 // the first region.
683 HeapWord* new_obj = first_hr->bottom();
684 // This will be the new end of the first region in the series that
685 // should also match the end of the last region in the series.
686 HeapWord* new_end = new_obj + word_size_sum;
687 // This will be the new top of the first region that will reflect
688 // this allocation.
689 HeapWord* new_top = new_obj + word_size;
691 // First, we need to zero the header of the space that we will be
692 // allocating. When we update top further down, some refinement
693 // threads might try to scan the region. By zeroing the header we
694 // ensure that any thread that will try to scan the region will
695 // come across the zero klass word and bail out.
696 //
697 // NOTE: It would not have been correct to have used
698 // CollectedHeap::fill_with_object() and make the space look like
699 // an int array. The thread that is doing the allocation will
700 // later update the object header to a potentially different array
701 // type and, for a very short period of time, the klass and length
702 // fields will be inconsistent. This could cause a refinement
703 // thread to calculate the object size incorrectly.
704 Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
706 // We will set up the first region as "starts humongous". This
707 // will also update the BOT covering all the regions to reflect
708 // that there is a single object that starts at the bottom of the
709 // first region.
710 first_hr->set_startsHumongous(new_top, new_end);
712 // Then, if there are any, we will set up the "continues
713 // humongous" regions.
714 HeapRegion* hr = NULL;
715 for (uint i = first + 1; i < last; ++i) {
716 hr = region_at(i);
717 hr->set_continuesHumongous(first_hr);
718 }
719 // If we have "continues humongous" regions (hr != NULL), then the
720 // end of the last one should match new_end.
721 assert(hr == NULL || hr->end() == new_end, "sanity");
723 // Up to this point no concurrent thread would have been able to
724 // do any scanning on any region in this series. All the top
725 // fields still point to bottom, so the intersection between
726 // [bottom,top] and [card_start,card_end] will be empty. Before we
727 // update the top fields, we'll do a storestore to make sure that
728 // no thread sees the update to top before the zeroing of the
729 // object header and the BOT initialization.
730 OrderAccess::storestore();
732 // Now that the BOT and the object header have been initialized,
733 // we can update top of the "starts humongous" region.
734 assert(first_hr->bottom() < new_top && new_top <= first_hr->end(),
735 "new_top should be in this region");
736 first_hr->set_top(new_top);
737 if (_hr_printer.is_active()) {
738 HeapWord* bottom = first_hr->bottom();
739 HeapWord* end = first_hr->orig_end();
740 if ((first + 1) == last) {
741 // the series has a single humongous region
742 _hr_printer.alloc(G1HRPrinter::SingleHumongous, first_hr, new_top);
743 } else {
744 // the series has more than one humongous regions
745 _hr_printer.alloc(G1HRPrinter::StartsHumongous, first_hr, end);
746 }
747 }
749 // Now, we will update the top fields of the "continues humongous"
750 // regions. The reason we need to do this is that, otherwise,
751 // these regions would look empty and this will confuse parts of
752 // G1. For example, the code that looks for a consecutive number
753 // of empty regions will consider them empty and try to
754 // re-allocate them. We can extend is_empty() to also include
755 // !continuesHumongous(), but it is easier to just update the top
756 // fields here. The way we set top for all regions (i.e., top ==
757 // end for all regions but the last one, top == new_top for the
758 // last one) is actually used when we will free up the humongous
759 // region in free_humongous_region().
760 hr = NULL;
761 for (uint i = first + 1; i < last; ++i) {
762 hr = region_at(i);
763 if ((i + 1) == last) {
764 // last continues humongous region
765 assert(hr->bottom() < new_top && new_top <= hr->end(),
766 "new_top should fall on this region");
767 hr->set_top(new_top);
768 _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, new_top);
769 } else {
770 // not last one
771 assert(new_top > hr->end(), "new_top should be above this region");
772 hr->set_top(hr->end());
773 _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, hr->end());
774 }
775 }
776 // If we have continues humongous regions (hr != NULL), then the
777 // end of the last one should match new_end and its top should
778 // match new_top.
779 assert(hr == NULL ||
780 (hr->end() == new_end && hr->top() == new_top), "sanity");
782 assert(first_hr->used() == word_size * HeapWordSize, "invariant");
783 _summary_bytes_used += first_hr->used();
784 _humongous_set.add(first_hr);
786 return new_obj;
787 }
789 // If could fit into free regions w/o expansion, try.
790 // Otherwise, if can expand, do so.
791 // Otherwise, if using ex regions might help, try with ex given back.
792 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {
793 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
795 verify_region_sets_optional();
797 size_t word_size_rounded = round_to(word_size, HeapRegion::GrainWords);
798 uint num_regions = (uint) (word_size_rounded / HeapRegion::GrainWords);
799 uint x_num = expansion_regions();
800 uint fs = _hrs.free_suffix();
801 uint first = humongous_obj_allocate_find_first(num_regions, word_size);
802 if (first == G1_NULL_HRS_INDEX) {
803 // The only thing we can do now is attempt expansion.
804 if (fs + x_num >= num_regions) {
805 // If the number of regions we're trying to allocate for this
806 // object is at most the number of regions in the free suffix,
807 // then the call to humongous_obj_allocate_find_first() above
808 // should have succeeded and we wouldn't be here.
809 //
810 // We should only be trying to expand when the free suffix is
811 // not sufficient for the object _and_ we have some expansion
812 // room available.
813 assert(num_regions > fs, "earlier allocation should have succeeded");
815 ergo_verbose1(ErgoHeapSizing,
816 "attempt heap expansion",
817 ergo_format_reason("humongous allocation request failed")
818 ergo_format_byte("allocation request"),
819 word_size * HeapWordSize);
820 if (expand((num_regions - fs) * HeapRegion::GrainBytes)) {
821 // Even though the heap was expanded, it might not have
822 // reached the desired size. So, we cannot assume that the
823 // allocation will succeed.
824 first = humongous_obj_allocate_find_first(num_regions, word_size);
825 }
826 }
827 }
829 HeapWord* result = NULL;
830 if (first != G1_NULL_HRS_INDEX) {
831 result =
832 humongous_obj_allocate_initialize_regions(first, num_regions, word_size);
833 assert(result != NULL, "it should always return a valid result");
835 // A successful humongous object allocation changes the used space
836 // information of the old generation so we need to recalculate the
837 // sizes and update the jstat counters here.
838 g1mm()->update_sizes();
839 }
841 verify_region_sets_optional();
843 return result;
844 }
846 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t word_size) {
847 assert_heap_not_locked_and_not_at_safepoint();
848 assert(!isHumongous(word_size), "we do not allow humongous TLABs");
850 unsigned int dummy_gc_count_before;
851 int dummy_gclocker_retry_count = 0;
852 return attempt_allocation(word_size, &dummy_gc_count_before, &dummy_gclocker_retry_count);
853 }
855 HeapWord*
856 G1CollectedHeap::mem_allocate(size_t word_size,
857 bool* gc_overhead_limit_was_exceeded) {
858 assert_heap_not_locked_and_not_at_safepoint();
860 // Loop until the allocation is satisfied, or unsatisfied after GC.
861 for (int try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
862 unsigned int gc_count_before;
864 HeapWord* result = NULL;
865 if (!isHumongous(word_size)) {
866 result = attempt_allocation(word_size, &gc_count_before, &gclocker_retry_count);
867 } else {
868 result = attempt_allocation_humongous(word_size, &gc_count_before, &gclocker_retry_count);
869 }
870 if (result != NULL) {
871 return result;
872 }
874 // Create the garbage collection operation...
875 VM_G1CollectForAllocation op(gc_count_before, word_size);
876 // ...and get the VM thread to execute it.
877 VMThread::execute(&op);
879 if (op.prologue_succeeded() && op.pause_succeeded()) {
880 // If the operation was successful we'll return the result even
881 // if it is NULL. If the allocation attempt failed immediately
882 // after a Full GC, it's unlikely we'll be able to allocate now.
883 HeapWord* result = op.result();
884 if (result != NULL && !isHumongous(word_size)) {
885 // Allocations that take place on VM operations do not do any
886 // card dirtying and we have to do it here. We only have to do
887 // this for non-humongous allocations, though.
888 dirty_young_block(result, word_size);
889 }
890 return result;
891 } else {
892 if (gclocker_retry_count > GCLockerRetryAllocationCount) {
893 return NULL;
894 }
895 assert(op.result() == NULL,
896 "the result should be NULL if the VM op did not succeed");
897 }
899 // Give a warning if we seem to be looping forever.
900 if ((QueuedAllocationWarningCount > 0) &&
901 (try_count % QueuedAllocationWarningCount == 0)) {
902 warning("G1CollectedHeap::mem_allocate retries %d times", try_count);
903 }
904 }
906 ShouldNotReachHere();
907 return NULL;
908 }
910 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size,
911 unsigned int *gc_count_before_ret,
912 int* gclocker_retry_count_ret) {
913 // Make sure you read the note in attempt_allocation_humongous().
915 assert_heap_not_locked_and_not_at_safepoint();
916 assert(!isHumongous(word_size), "attempt_allocation_slow() should not "
917 "be called for humongous allocation requests");
919 // We should only get here after the first-level allocation attempt
920 // (attempt_allocation()) failed to allocate.
922 // We will loop until a) we manage to successfully perform the
923 // allocation or b) we successfully schedule a collection which
924 // fails to perform the allocation. b) is the only case when we'll
925 // return NULL.
926 HeapWord* result = NULL;
927 for (int try_count = 1; /* we'll return */; try_count += 1) {
928 bool should_try_gc;
929 unsigned int gc_count_before;
931 {
932 MutexLockerEx x(Heap_lock);
934 result = _mutator_alloc_region.attempt_allocation_locked(word_size,
935 false /* bot_updates */);
936 if (result != NULL) {
937 return result;
938 }
940 // If we reach here, attempt_allocation_locked() above failed to
941 // allocate a new region. So the mutator alloc region should be NULL.
942 assert(_mutator_alloc_region.get() == NULL, "only way to get here");
944 if (GC_locker::is_active_and_needs_gc()) {
945 if (g1_policy()->can_expand_young_list()) {
946 // No need for an ergo verbose message here,
947 // can_expand_young_list() does this when it returns true.
948 result = _mutator_alloc_region.attempt_allocation_force(word_size,
949 false /* bot_updates */);
950 if (result != NULL) {
951 return result;
952 }
953 }
954 should_try_gc = false;
955 } else {
956 // The GCLocker may not be active but the GCLocker initiated
957 // GC may not yet have been performed (GCLocker::needs_gc()
958 // returns true). In this case we do not try this GC and
959 // wait until the GCLocker initiated GC is performed, and
960 // then retry the allocation.
961 if (GC_locker::needs_gc()) {
962 should_try_gc = false;
963 } else {
964 // Read the GC count while still holding the Heap_lock.
965 gc_count_before = total_collections();
966 should_try_gc = true;
967 }
968 }
969 }
971 if (should_try_gc) {
972 bool succeeded;
973 result = do_collection_pause(word_size, gc_count_before, &succeeded,
974 GCCause::_g1_inc_collection_pause);
975 if (result != NULL) {
976 assert(succeeded, "only way to get back a non-NULL result");
977 return result;
978 }
980 if (succeeded) {
981 // If we get here we successfully scheduled a collection which
982 // failed to allocate. No point in trying to allocate
983 // further. We'll just return NULL.
984 MutexLockerEx x(Heap_lock);
985 *gc_count_before_ret = total_collections();
986 return NULL;
987 }
988 } else {
989 if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
990 MutexLockerEx x(Heap_lock);
991 *gc_count_before_ret = total_collections();
992 return NULL;
993 }
994 // The GCLocker is either active or the GCLocker initiated
995 // GC has not yet been performed. Stall until it is and
996 // then retry the allocation.
997 GC_locker::stall_until_clear();
998 (*gclocker_retry_count_ret) += 1;
999 }
1001 // We can reach here if we were unsuccessful in scheduling a
1002 // collection (because another thread beat us to it) or if we were
1003 // stalled due to the GC locker. In either can we should retry the
1004 // allocation attempt in case another thread successfully
1005 // performed a collection and reclaimed enough space. We do the
1006 // first attempt (without holding the Heap_lock) here and the
1007 // follow-on attempt will be at the start of the next loop
1008 // iteration (after taking the Heap_lock).
1009 result = _mutator_alloc_region.attempt_allocation(word_size,
1010 false /* bot_updates */);
1011 if (result != NULL) {
1012 return result;
1013 }
1015 // Give a warning if we seem to be looping forever.
1016 if ((QueuedAllocationWarningCount > 0) &&
1017 (try_count % QueuedAllocationWarningCount == 0)) {
1018 warning("G1CollectedHeap::attempt_allocation_slow() "
1019 "retries %d times", try_count);
1020 }
1021 }
1023 ShouldNotReachHere();
1024 return NULL;
1025 }
1027 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size,
1028 unsigned int * gc_count_before_ret,
1029 int* gclocker_retry_count_ret) {
1030 // The structure of this method has a lot of similarities to
1031 // attempt_allocation_slow(). The reason these two were not merged
1032 // into a single one is that such a method would require several "if
1033 // allocation is not humongous do this, otherwise do that"
1034 // conditional paths which would obscure its flow. In fact, an early
1035 // version of this code did use a unified method which was harder to
1036 // follow and, as a result, it had subtle bugs that were hard to
1037 // track down. So keeping these two methods separate allows each to
1038 // be more readable. It will be good to keep these two in sync as
1039 // much as possible.
1041 assert_heap_not_locked_and_not_at_safepoint();
1042 assert(isHumongous(word_size), "attempt_allocation_humongous() "
1043 "should only be called for humongous allocations");
1045 // Humongous objects can exhaust the heap quickly, so we should check if we
1046 // need to start a marking cycle at each humongous object allocation. We do
1047 // the check before we do the actual allocation. The reason for doing it
1048 // before the allocation is that we avoid having to keep track of the newly
1049 // allocated memory while we do a GC.
1050 if (g1_policy()->need_to_start_conc_mark("concurrent humongous allocation",
1051 word_size)) {
1052 collect(GCCause::_g1_humongous_allocation);
1053 }
1055 // We will loop until a) we manage to successfully perform the
1056 // allocation or b) we successfully schedule a collection which
1057 // fails to perform the allocation. b) is the only case when we'll
1058 // return NULL.
1059 HeapWord* result = NULL;
1060 for (int try_count = 1; /* we'll return */; try_count += 1) {
1061 bool should_try_gc;
1062 unsigned int gc_count_before;
1064 {
1065 MutexLockerEx x(Heap_lock);
1067 // Given that humongous objects are not allocated in young
1068 // regions, we'll first try to do the allocation without doing a
1069 // collection hoping that there's enough space in the heap.
1070 result = humongous_obj_allocate(word_size);
1071 if (result != NULL) {
1072 return result;
1073 }
1075 if (GC_locker::is_active_and_needs_gc()) {
1076 should_try_gc = false;
1077 } else {
1078 // The GCLocker may not be active but the GCLocker initiated
1079 // GC may not yet have been performed (GCLocker::needs_gc()
1080 // returns true). In this case we do not try this GC and
1081 // wait until the GCLocker initiated GC is performed, and
1082 // then retry the allocation.
1083 if (GC_locker::needs_gc()) {
1084 should_try_gc = false;
1085 } else {
1086 // Read the GC count while still holding the Heap_lock.
1087 gc_count_before = total_collections();
1088 should_try_gc = true;
1089 }
1090 }
1091 }
1093 if (should_try_gc) {
1094 // If we failed to allocate the humongous object, we should try to
1095 // do a collection pause (if we're allowed) in case it reclaims
1096 // enough space for the allocation to succeed after the pause.
1098 bool succeeded;
1099 result = do_collection_pause(word_size, gc_count_before, &succeeded,
1100 GCCause::_g1_humongous_allocation);
1101 if (result != NULL) {
1102 assert(succeeded, "only way to get back a non-NULL result");
1103 return result;
1104 }
1106 if (succeeded) {
1107 // If we get here we successfully scheduled a collection which
1108 // failed to allocate. No point in trying to allocate
1109 // further. We'll just return NULL.
1110 MutexLockerEx x(Heap_lock);
1111 *gc_count_before_ret = total_collections();
1112 return NULL;
1113 }
1114 } else {
1115 if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
1116 MutexLockerEx x(Heap_lock);
1117 *gc_count_before_ret = total_collections();
1118 return NULL;
1119 }
1120 // The GCLocker is either active or the GCLocker initiated
1121 // GC has not yet been performed. Stall until it is and
1122 // then retry the allocation.
1123 GC_locker::stall_until_clear();
1124 (*gclocker_retry_count_ret) += 1;
1125 }
1127 // We can reach here if we were unsuccessful in scheduling a
1128 // collection (because another thread beat us to it) or if we were
1129 // stalled due to the GC locker. In either can we should retry the
1130 // allocation attempt in case another thread successfully
1131 // performed a collection and reclaimed enough space. Give a
1132 // warning if we seem to be looping forever.
1134 if ((QueuedAllocationWarningCount > 0) &&
1135 (try_count % QueuedAllocationWarningCount == 0)) {
1136 warning("G1CollectedHeap::attempt_allocation_humongous() "
1137 "retries %d times", try_count);
1138 }
1139 }
1141 ShouldNotReachHere();
1142 return NULL;
1143 }
1145 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
1146 bool expect_null_mutator_alloc_region) {
1147 assert_at_safepoint(true /* should_be_vm_thread */);
1148 assert(_mutator_alloc_region.get() == NULL ||
1149 !expect_null_mutator_alloc_region,
1150 "the current alloc region was unexpectedly found to be non-NULL");
1152 if (!isHumongous(word_size)) {
1153 return _mutator_alloc_region.attempt_allocation_locked(word_size,
1154 false /* bot_updates */);
1155 } else {
1156 HeapWord* result = humongous_obj_allocate(word_size);
1157 if (result != NULL && g1_policy()->need_to_start_conc_mark("STW humongous allocation")) {
1158 g1_policy()->set_initiate_conc_mark_if_possible();
1159 }
1160 return result;
1161 }
1163 ShouldNotReachHere();
1164 }
1166 class PostMCRemSetClearClosure: public HeapRegionClosure {
1167 G1CollectedHeap* _g1h;
1168 ModRefBarrierSet* _mr_bs;
1169 public:
1170 PostMCRemSetClearClosure(G1CollectedHeap* g1h, ModRefBarrierSet* mr_bs) :
1171 _g1h(g1h), _mr_bs(mr_bs) {}
1173 bool doHeapRegion(HeapRegion* r) {
1174 HeapRegionRemSet* hrrs = r->rem_set();
1176 if (r->continuesHumongous()) {
1177 // We'll assert that the strong code root list and RSet is empty
1178 assert(hrrs->strong_code_roots_list_length() == 0, "sanity");
1179 assert(hrrs->occupied() == 0, "RSet should be empty");
1180 return false;
1181 }
1183 _g1h->reset_gc_time_stamps(r);
1184 hrrs->clear();
1185 // You might think here that we could clear just the cards
1186 // corresponding to the used region. But no: if we leave a dirty card
1187 // in a region we might allocate into, then it would prevent that card
1188 // from being enqueued, and cause it to be missed.
1189 // Re: the performance cost: we shouldn't be doing full GC anyway!
1190 _mr_bs->clear(MemRegion(r->bottom(), r->end()));
1192 return false;
1193 }
1194 };
1196 void G1CollectedHeap::clear_rsets_post_compaction() {
1197 PostMCRemSetClearClosure rs_clear(this, g1_barrier_set());
1198 heap_region_iterate(&rs_clear);
1199 }
1201 class RebuildRSOutOfRegionClosure: public HeapRegionClosure {
1202 G1CollectedHeap* _g1h;
1203 UpdateRSOopClosure _cl;
1204 int _worker_i;
1205 public:
1206 RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, int worker_i = 0) :
1207 _cl(g1->g1_rem_set(), worker_i),
1208 _worker_i(worker_i),
1209 _g1h(g1)
1210 { }
1212 bool doHeapRegion(HeapRegion* r) {
1213 if (!r->continuesHumongous()) {
1214 _cl.set_from(r);
1215 r->oop_iterate(&_cl);
1216 }
1217 return false;
1218 }
1219 };
1221 class ParRebuildRSTask: public AbstractGangTask {
1222 G1CollectedHeap* _g1;
1223 public:
1224 ParRebuildRSTask(G1CollectedHeap* g1)
1225 : AbstractGangTask("ParRebuildRSTask"),
1226 _g1(g1)
1227 { }
1229 void work(uint worker_id) {
1230 RebuildRSOutOfRegionClosure rebuild_rs(_g1, worker_id);
1231 _g1->heap_region_par_iterate_chunked(&rebuild_rs, worker_id,
1232 _g1->workers()->active_workers(),
1233 HeapRegion::RebuildRSClaimValue);
1234 }
1235 };
1237 class PostCompactionPrinterClosure: public HeapRegionClosure {
1238 private:
1239 G1HRPrinter* _hr_printer;
1240 public:
1241 bool doHeapRegion(HeapRegion* hr) {
1242 assert(!hr->is_young(), "not expecting to find young regions");
1243 // We only generate output for non-empty regions.
1244 if (!hr->is_empty()) {
1245 if (!hr->isHumongous()) {
1246 _hr_printer->post_compaction(hr, G1HRPrinter::Old);
1247 } else if (hr->startsHumongous()) {
1248 if (hr->region_num() == 1) {
1249 // single humongous region
1250 _hr_printer->post_compaction(hr, G1HRPrinter::SingleHumongous);
1251 } else {
1252 _hr_printer->post_compaction(hr, G1HRPrinter::StartsHumongous);
1253 }
1254 } else {
1255 assert(hr->continuesHumongous(), "only way to get here");
1256 _hr_printer->post_compaction(hr, G1HRPrinter::ContinuesHumongous);
1257 }
1258 }
1259 return false;
1260 }
1262 PostCompactionPrinterClosure(G1HRPrinter* hr_printer)
1263 : _hr_printer(hr_printer) { }
1264 };
1266 void G1CollectedHeap::print_hrs_post_compaction() {
1267 PostCompactionPrinterClosure cl(hr_printer());
1268 heap_region_iterate(&cl);
1269 }
1271 bool G1CollectedHeap::do_collection(bool explicit_gc,
1272 bool clear_all_soft_refs,
1273 size_t word_size) {
1274 assert_at_safepoint(true /* should_be_vm_thread */);
1276 if (GC_locker::check_active_before_gc()) {
1277 return false;
1278 }
1280 STWGCTimer* gc_timer = G1MarkSweep::gc_timer();
1281 gc_timer->register_gc_start();
1283 SerialOldTracer* gc_tracer = G1MarkSweep::gc_tracer();
1284 gc_tracer->report_gc_start(gc_cause(), gc_timer->gc_start());
1286 SvcGCMarker sgcm(SvcGCMarker::FULL);
1287 ResourceMark rm;
1289 print_heap_before_gc();
1290 trace_heap_before_gc(gc_tracer);
1292 size_t metadata_prev_used = MetaspaceAux::allocated_used_bytes();
1294 verify_region_sets_optional();
1296 const bool do_clear_all_soft_refs = clear_all_soft_refs ||
1297 collector_policy()->should_clear_all_soft_refs();
1299 ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());
1301 {
1302 IsGCActiveMark x;
1304 // Timing
1305 assert(gc_cause() != GCCause::_java_lang_system_gc || explicit_gc, "invariant");
1306 gclog_or_tty->date_stamp(G1Log::fine() && PrintGCDateStamps);
1307 TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
1309 {
1310 GCTraceTime t(GCCauseString("Full GC", gc_cause()), G1Log::fine(), true, NULL);
1311 TraceCollectorStats tcs(g1mm()->full_collection_counters());
1312 TraceMemoryManagerStats tms(true /* fullGC */, gc_cause());
1314 double start = os::elapsedTime();
1315 g1_policy()->record_full_collection_start();
1317 // Note: When we have a more flexible GC logging framework that
1318 // allows us to add optional attributes to a GC log record we
1319 // could consider timing and reporting how long we wait in the
1320 // following two methods.
1321 wait_while_free_regions_coming();
1322 // If we start the compaction before the CM threads finish
1323 // scanning the root regions we might trip them over as we'll
1324 // be moving objects / updating references. So let's wait until
1325 // they are done. By telling them to abort, they should complete
1326 // early.
1327 _cm->root_regions()->abort();
1328 _cm->root_regions()->wait_until_scan_finished();
1329 append_secondary_free_list_if_not_empty_with_lock();
1331 gc_prologue(true);
1332 increment_total_collections(true /* full gc */);
1333 increment_old_marking_cycles_started();
1335 assert(used() == recalculate_used(), "Should be equal");
1337 verify_before_gc();
1339 pre_full_gc_dump(gc_timer);
1341 COMPILER2_PRESENT(DerivedPointerTable::clear());
1343 // Disable discovery and empty the discovered lists
1344 // for the CM ref processor.
1345 ref_processor_cm()->disable_discovery();
1346 ref_processor_cm()->abandon_partial_discovery();
1347 ref_processor_cm()->verify_no_references_recorded();
1349 // Abandon current iterations of concurrent marking and concurrent
1350 // refinement, if any are in progress. We have to do this before
1351 // wait_until_scan_finished() below.
1352 concurrent_mark()->abort();
1354 // Make sure we'll choose a new allocation region afterwards.
1355 release_mutator_alloc_region();
1356 abandon_gc_alloc_regions();
1357 g1_rem_set()->cleanupHRRS();
1359 // We should call this after we retire any currently active alloc
1360 // regions so that all the ALLOC / RETIRE events are generated
1361 // before the start GC event.
1362 _hr_printer.start_gc(true /* full */, (size_t) total_collections());
1364 // We may have added regions to the current incremental collection
1365 // set between the last GC or pause and now. We need to clear the
1366 // incremental collection set and then start rebuilding it afresh
1367 // after this full GC.
1368 abandon_collection_set(g1_policy()->inc_cset_head());
1369 g1_policy()->clear_incremental_cset();
1370 g1_policy()->stop_incremental_cset_building();
1372 tear_down_region_sets(false /* free_list_only */);
1373 g1_policy()->set_gcs_are_young(true);
1375 // See the comments in g1CollectedHeap.hpp and
1376 // G1CollectedHeap::ref_processing_init() about
1377 // how reference processing currently works in G1.
1379 // Temporarily make discovery by the STW ref processor single threaded (non-MT).
1380 ReferenceProcessorMTDiscoveryMutator stw_rp_disc_ser(ref_processor_stw(), false);
1382 // Temporarily clear the STW ref processor's _is_alive_non_header field.
1383 ReferenceProcessorIsAliveMutator stw_rp_is_alive_null(ref_processor_stw(), NULL);
1385 ref_processor_stw()->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
1386 ref_processor_stw()->setup_policy(do_clear_all_soft_refs);
1388 // Do collection work
1389 {
1390 HandleMark hm; // Discard invalid handles created during gc
1391 G1MarkSweep::invoke_at_safepoint(ref_processor_stw(), do_clear_all_soft_refs);
1392 }
1394 assert(free_regions() == 0, "we should not have added any free regions");
1395 rebuild_region_sets(false /* free_list_only */);
1397 // Enqueue any discovered reference objects that have
1398 // not been removed from the discovered lists.
1399 ref_processor_stw()->enqueue_discovered_references();
1401 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
1403 MemoryService::track_memory_usage();
1405 assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
1406 ref_processor_stw()->verify_no_references_recorded();
1408 // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1409 ClassLoaderDataGraph::purge();
1410 MetaspaceAux::verify_metrics();
1412 // Note: since we've just done a full GC, concurrent
1413 // marking is no longer active. Therefore we need not
1414 // re-enable reference discovery for the CM ref processor.
1415 // That will be done at the start of the next marking cycle.
1416 assert(!ref_processor_cm()->discovery_enabled(), "Postcondition");
1417 ref_processor_cm()->verify_no_references_recorded();
1419 reset_gc_time_stamp();
1420 // Since everything potentially moved, we will clear all remembered
1421 // sets, and clear all cards. Later we will rebuild remembered
1422 // sets. We will also reset the GC time stamps of the regions.
1423 clear_rsets_post_compaction();
1424 check_gc_time_stamps();
1426 // Resize the heap if necessary.
1427 resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size);
1429 if (_hr_printer.is_active()) {
1430 // We should do this after we potentially resize the heap so
1431 // that all the COMMIT / UNCOMMIT events are generated before
1432 // the end GC event.
1434 print_hrs_post_compaction();
1435 _hr_printer.end_gc(true /* full */, (size_t) total_collections());
1436 }
1438 G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
1439 if (hot_card_cache->use_cache()) {
1440 hot_card_cache->reset_card_counts();
1441 hot_card_cache->reset_hot_cache();
1442 }
1444 // Rebuild remembered sets of all regions.
1445 if (G1CollectedHeap::use_parallel_gc_threads()) {
1446 uint n_workers =
1447 AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
1448 workers()->active_workers(),
1449 Threads::number_of_non_daemon_threads());
1450 assert(UseDynamicNumberOfGCThreads ||
1451 n_workers == workers()->total_workers(),
1452 "If not dynamic should be using all the workers");
1453 workers()->set_active_workers(n_workers);
1454 // Set parallel threads in the heap (_n_par_threads) only
1455 // before a parallel phase and always reset it to 0 after
1456 // the phase so that the number of parallel threads does
1457 // no get carried forward to a serial phase where there
1458 // may be code that is "possibly_parallel".
1459 set_par_threads(n_workers);
1461 ParRebuildRSTask rebuild_rs_task(this);
1462 assert(check_heap_region_claim_values(
1463 HeapRegion::InitialClaimValue), "sanity check");
1464 assert(UseDynamicNumberOfGCThreads ||
1465 workers()->active_workers() == workers()->total_workers(),
1466 "Unless dynamic should use total workers");
1467 // Use the most recent number of active workers
1468 assert(workers()->active_workers() > 0,
1469 "Active workers not properly set");
1470 set_par_threads(workers()->active_workers());
1471 workers()->run_task(&rebuild_rs_task);
1472 set_par_threads(0);
1473 assert(check_heap_region_claim_values(
1474 HeapRegion::RebuildRSClaimValue), "sanity check");
1475 reset_heap_region_claim_values();
1476 } else {
1477 RebuildRSOutOfRegionClosure rebuild_rs(this);
1478 heap_region_iterate(&rebuild_rs);
1479 }
1481 // Rebuild the strong code root lists for each region
1482 rebuild_strong_code_roots();
1484 if (true) { // FIXME
1485 MetaspaceGC::compute_new_size();
1486 }
1488 #ifdef TRACESPINNING
1489 ParallelTaskTerminator::print_termination_counts();
1490 #endif
1492 // Discard all rset updates
1493 JavaThread::dirty_card_queue_set().abandon_logs();
1494 assert(!G1DeferredRSUpdate
1495 || (G1DeferredRSUpdate &&
1496 (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any");
1498 _young_list->reset_sampled_info();
1499 // At this point there should be no regions in the
1500 // entire heap tagged as young.
1501 assert(check_young_list_empty(true /* check_heap */),
1502 "young list should be empty at this point");
1504 // Update the number of full collections that have been completed.
1505 increment_old_marking_cycles_completed(false /* concurrent */);
1507 _hrs.verify_optional();
1508 verify_region_sets_optional();
1510 verify_after_gc();
1512 // Start a new incremental collection set for the next pause
1513 assert(g1_policy()->collection_set() == NULL, "must be");
1514 g1_policy()->start_incremental_cset_building();
1516 // Clear the _cset_fast_test bitmap in anticipation of adding
1517 // regions to the incremental collection set for the next
1518 // evacuation pause.
1519 clear_cset_fast_test();
1521 init_mutator_alloc_region();
1523 double end = os::elapsedTime();
1524 g1_policy()->record_full_collection_end();
1526 if (G1Log::fine()) {
1527 g1_policy()->print_heap_transition();
1528 }
1530 // We must call G1MonitoringSupport::update_sizes() in the same scoping level
1531 // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
1532 // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
1533 // before any GC notifications are raised.
1534 g1mm()->update_sizes();
1536 gc_epilogue(true);
1537 }
1539 if (G1Log::finer()) {
1540 g1_policy()->print_detailed_heap_transition(true /* full */);
1541 }
1543 print_heap_after_gc();
1544 trace_heap_after_gc(gc_tracer);
1546 post_full_gc_dump(gc_timer);
1548 gc_timer->register_gc_end();
1549 gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions());
1550 }
1552 return true;
1553 }
1555 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1556 // do_collection() will return whether it succeeded in performing
1557 // the GC. Currently, there is no facility on the
1558 // do_full_collection() API to notify the caller than the collection
1559 // did not succeed (e.g., because it was locked out by the GC
1560 // locker). So, right now, we'll ignore the return value.
1561 bool dummy = do_collection(true, /* explicit_gc */
1562 clear_all_soft_refs,
1563 0 /* word_size */);
1564 }
1566 // This code is mostly copied from TenuredGeneration.
1567 void
1568 G1CollectedHeap::
1569 resize_if_necessary_after_full_collection(size_t word_size) {
1570 // Include the current allocation, if any, and bytes that will be
1571 // pre-allocated to support collections, as "used".
1572 const size_t used_after_gc = used();
1573 const size_t capacity_after_gc = capacity();
1574 const size_t free_after_gc = capacity_after_gc - used_after_gc;
1576 // This is enforced in arguments.cpp.
1577 assert(MinHeapFreeRatio <= MaxHeapFreeRatio,
1578 "otherwise the code below doesn't make sense");
1580 // We don't have floating point command-line arguments
1581 const double minimum_free_percentage = (double) MinHeapFreeRatio / 100.0;
1582 const double maximum_used_percentage = 1.0 - minimum_free_percentage;
1583 const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100.0;
1584 const double minimum_used_percentage = 1.0 - maximum_free_percentage;
1586 const size_t min_heap_size = collector_policy()->min_heap_byte_size();
1587 const size_t max_heap_size = collector_policy()->max_heap_byte_size();
1589 // We have to be careful here as these two calculations can overflow
1590 // 32-bit size_t's.
1591 double used_after_gc_d = (double) used_after_gc;
1592 double minimum_desired_capacity_d = used_after_gc_d / maximum_used_percentage;
1593 double maximum_desired_capacity_d = used_after_gc_d / minimum_used_percentage;
1595 // Let's make sure that they are both under the max heap size, which
1596 // by default will make them fit into a size_t.
1597 double desired_capacity_upper_bound = (double) max_heap_size;
1598 minimum_desired_capacity_d = MIN2(minimum_desired_capacity_d,
1599 desired_capacity_upper_bound);
1600 maximum_desired_capacity_d = MIN2(maximum_desired_capacity_d,
1601 desired_capacity_upper_bound);
1603 // We can now safely turn them into size_t's.
1604 size_t minimum_desired_capacity = (size_t) minimum_desired_capacity_d;
1605 size_t maximum_desired_capacity = (size_t) maximum_desired_capacity_d;
1607 // This assert only makes sense here, before we adjust them
1608 // with respect to the min and max heap size.
1609 assert(minimum_desired_capacity <= maximum_desired_capacity,
1610 err_msg("minimum_desired_capacity = "SIZE_FORMAT", "
1611 "maximum_desired_capacity = "SIZE_FORMAT,
1612 minimum_desired_capacity, maximum_desired_capacity));
1614 // Should not be greater than the heap max size. No need to adjust
1615 // it with respect to the heap min size as it's a lower bound (i.e.,
1616 // we'll try to make the capacity larger than it, not smaller).
1617 minimum_desired_capacity = MIN2(minimum_desired_capacity, max_heap_size);
1618 // Should not be less than the heap min size. No need to adjust it
1619 // with respect to the heap max size as it's an upper bound (i.e.,
1620 // we'll try to make the capacity smaller than it, not greater).
1621 maximum_desired_capacity = MAX2(maximum_desired_capacity, min_heap_size);
1623 if (capacity_after_gc < minimum_desired_capacity) {
1624 // Don't expand unless it's significant
1625 size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
1626 ergo_verbose4(ErgoHeapSizing,
1627 "attempt heap expansion",
1628 ergo_format_reason("capacity lower than "
1629 "min desired capacity after Full GC")
1630 ergo_format_byte("capacity")
1631 ergo_format_byte("occupancy")
1632 ergo_format_byte_perc("min desired capacity"),
1633 capacity_after_gc, used_after_gc,
1634 minimum_desired_capacity, (double) MinHeapFreeRatio);
1635 expand(expand_bytes);
1637 // No expansion, now see if we want to shrink
1638 } else if (capacity_after_gc > maximum_desired_capacity) {
1639 // Capacity too large, compute shrinking size
1640 size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;
1641 ergo_verbose4(ErgoHeapSizing,
1642 "attempt heap shrinking",
1643 ergo_format_reason("capacity higher than "
1644 "max desired capacity after Full GC")
1645 ergo_format_byte("capacity")
1646 ergo_format_byte("occupancy")
1647 ergo_format_byte_perc("max desired capacity"),
1648 capacity_after_gc, used_after_gc,
1649 maximum_desired_capacity, (double) MaxHeapFreeRatio);
1650 shrink(shrink_bytes);
1651 }
1652 }
1655 HeapWord*
1656 G1CollectedHeap::satisfy_failed_allocation(size_t word_size,
1657 bool* succeeded) {
1658 assert_at_safepoint(true /* should_be_vm_thread */);
1660 *succeeded = true;
1661 // Let's attempt the allocation first.
1662 HeapWord* result =
1663 attempt_allocation_at_safepoint(word_size,
1664 false /* expect_null_mutator_alloc_region */);
1665 if (result != NULL) {
1666 assert(*succeeded, "sanity");
1667 return result;
1668 }
1670 // In a G1 heap, we're supposed to keep allocation from failing by
1671 // incremental pauses. Therefore, at least for now, we'll favor
1672 // expansion over collection. (This might change in the future if we can
1673 // do something smarter than full collection to satisfy a failed alloc.)
1674 result = expand_and_allocate(word_size);
1675 if (result != NULL) {
1676 assert(*succeeded, "sanity");
1677 return result;
1678 }
1680 // Expansion didn't work, we'll try to do a Full GC.
1681 bool gc_succeeded = do_collection(false, /* explicit_gc */
1682 false, /* clear_all_soft_refs */
1683 word_size);
1684 if (!gc_succeeded) {
1685 *succeeded = false;
1686 return NULL;
1687 }
1689 // Retry the allocation
1690 result = attempt_allocation_at_safepoint(word_size,
1691 true /* expect_null_mutator_alloc_region */);
1692 if (result != NULL) {
1693 assert(*succeeded, "sanity");
1694 return result;
1695 }
1697 // Then, try a Full GC that will collect all soft references.
1698 gc_succeeded = do_collection(false, /* explicit_gc */
1699 true, /* clear_all_soft_refs */
1700 word_size);
1701 if (!gc_succeeded) {
1702 *succeeded = false;
1703 return NULL;
1704 }
1706 // Retry the allocation once more
1707 result = attempt_allocation_at_safepoint(word_size,
1708 true /* expect_null_mutator_alloc_region */);
1709 if (result != NULL) {
1710 assert(*succeeded, "sanity");
1711 return result;
1712 }
1714 assert(!collector_policy()->should_clear_all_soft_refs(),
1715 "Flag should have been handled and cleared prior to this point");
1717 // What else? We might try synchronous finalization later. If the total
1718 // space available is large enough for the allocation, then a more
1719 // complete compaction phase than we've tried so far might be
1720 // appropriate.
1721 assert(*succeeded, "sanity");
1722 return NULL;
1723 }
1725 // Attempting to expand the heap sufficiently
1726 // to support an allocation of the given "word_size". If
1727 // successful, perform the allocation and return the address of the
1728 // allocated block, or else "NULL".
1730 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1731 assert_at_safepoint(true /* should_be_vm_thread */);
1733 verify_region_sets_optional();
1735 size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
1736 ergo_verbose1(ErgoHeapSizing,
1737 "attempt heap expansion",
1738 ergo_format_reason("allocation request failed")
1739 ergo_format_byte("allocation request"),
1740 word_size * HeapWordSize);
1741 if (expand(expand_bytes)) {
1742 _hrs.verify_optional();
1743 verify_region_sets_optional();
1744 return attempt_allocation_at_safepoint(word_size,
1745 false /* expect_null_mutator_alloc_region */);
1746 }
1747 return NULL;
1748 }
1750 void G1CollectedHeap::update_committed_space(HeapWord* old_end,
1751 HeapWord* new_end) {
1752 assert(old_end != new_end, "don't call this otherwise");
1753 assert((HeapWord*) _g1_storage.high() == new_end, "invariant");
1755 // Update the committed mem region.
1756 _g1_committed.set_end(new_end);
1757 // Tell the card table about the update.
1758 Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
1759 // Tell the BOT about the update.
1760 _bot_shared->resize(_g1_committed.word_size());
1761 // Tell the hot card cache about the update
1762 _cg1r->hot_card_cache()->resize_card_counts(capacity());
1763 }
1765 bool G1CollectedHeap::expand(size_t expand_bytes) {
1766 size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);
1767 aligned_expand_bytes = align_size_up(aligned_expand_bytes,
1768 HeapRegion::GrainBytes);
1769 ergo_verbose2(ErgoHeapSizing,
1770 "expand the heap",
1771 ergo_format_byte("requested expansion amount")
1772 ergo_format_byte("attempted expansion amount"),
1773 expand_bytes, aligned_expand_bytes);
1775 if (_g1_storage.uncommitted_size() == 0) {
1776 ergo_verbose0(ErgoHeapSizing,
1777 "did not expand the heap",
1778 ergo_format_reason("heap already fully expanded"));
1779 return false;
1780 }
1782 // First commit the memory.
1783 HeapWord* old_end = (HeapWord*) _g1_storage.high();
1784 bool successful = _g1_storage.expand_by(aligned_expand_bytes);
1785 if (successful) {
1786 // Then propagate this update to the necessary data structures.
1787 HeapWord* new_end = (HeapWord*) _g1_storage.high();
1788 update_committed_space(old_end, new_end);
1790 FreeRegionList expansion_list("Local Expansion List");
1791 MemRegion mr = _hrs.expand_by(old_end, new_end, &expansion_list);
1792 assert(mr.start() == old_end, "post-condition");
1793 // mr might be a smaller region than what was requested if
1794 // expand_by() was unable to allocate the HeapRegion instances
1795 assert(mr.end() <= new_end, "post-condition");
1797 size_t actual_expand_bytes = mr.byte_size();
1798 assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
1799 assert(actual_expand_bytes == expansion_list.total_capacity_bytes(),
1800 "post-condition");
1801 if (actual_expand_bytes < aligned_expand_bytes) {
1802 // We could not expand _hrs to the desired size. In this case we
1803 // need to shrink the committed space accordingly.
1804 assert(mr.end() < new_end, "invariant");
1806 size_t diff_bytes = aligned_expand_bytes - actual_expand_bytes;
1807 // First uncommit the memory.
1808 _g1_storage.shrink_by(diff_bytes);
1809 // Then propagate this update to the necessary data structures.
1810 update_committed_space(new_end, mr.end());
1811 }
1812 _free_list.add_as_tail(&expansion_list);
1814 if (_hr_printer.is_active()) {
1815 HeapWord* curr = mr.start();
1816 while (curr < mr.end()) {
1817 HeapWord* curr_end = curr + HeapRegion::GrainWords;
1818 _hr_printer.commit(curr, curr_end);
1819 curr = curr_end;
1820 }
1821 assert(curr == mr.end(), "post-condition");
1822 }
1823 g1_policy()->record_new_heap_size(n_regions());
1824 } else {
1825 ergo_verbose0(ErgoHeapSizing,
1826 "did not expand the heap",
1827 ergo_format_reason("heap expansion operation failed"));
1828 // The expansion of the virtual storage space was unsuccessful.
1829 // Let's see if it was because we ran out of swap.
1830 if (G1ExitOnExpansionFailure &&
1831 _g1_storage.uncommitted_size() >= aligned_expand_bytes) {
1832 // We had head room...
1833 vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");
1834 }
1835 }
1836 return successful;
1837 }
1839 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
1840 size_t aligned_shrink_bytes =
1841 ReservedSpace::page_align_size_down(shrink_bytes);
1842 aligned_shrink_bytes = align_size_down(aligned_shrink_bytes,
1843 HeapRegion::GrainBytes);
1844 uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);
1846 uint num_regions_removed = _hrs.shrink_by(num_regions_to_remove);
1847 HeapWord* old_end = (HeapWord*) _g1_storage.high();
1848 size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;
1850 ergo_verbose3(ErgoHeapSizing,
1851 "shrink the heap",
1852 ergo_format_byte("requested shrinking amount")
1853 ergo_format_byte("aligned shrinking amount")
1854 ergo_format_byte("attempted shrinking amount"),
1855 shrink_bytes, aligned_shrink_bytes, shrunk_bytes);
1856 if (num_regions_removed > 0) {
1857 _g1_storage.shrink_by(shrunk_bytes);
1858 HeapWord* new_end = (HeapWord*) _g1_storage.high();
1860 if (_hr_printer.is_active()) {
1861 HeapWord* curr = old_end;
1862 while (curr > new_end) {
1863 HeapWord* curr_end = curr;
1864 curr -= HeapRegion::GrainWords;
1865 _hr_printer.uncommit(curr, curr_end);
1866 }
1867 }
1869 _expansion_regions += num_regions_removed;
1870 update_committed_space(old_end, new_end);
1871 HeapRegionRemSet::shrink_heap(n_regions());
1872 g1_policy()->record_new_heap_size(n_regions());
1873 } else {
1874 ergo_verbose0(ErgoHeapSizing,
1875 "did not shrink the heap",
1876 ergo_format_reason("heap shrinking operation failed"));
1877 }
1878 }
1880 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1881 verify_region_sets_optional();
1883 // We should only reach here at the end of a Full GC which means we
1884 // should not not be holding to any GC alloc regions. The method
1885 // below will make sure of that and do any remaining clean up.
1886 abandon_gc_alloc_regions();
1888 // Instead of tearing down / rebuilding the free lists here, we
1889 // could instead use the remove_all_pending() method on free_list to
1890 // remove only the ones that we need to remove.
1891 tear_down_region_sets(true /* free_list_only */);
1892 shrink_helper(shrink_bytes);
1893 rebuild_region_sets(true /* free_list_only */);
1895 _hrs.verify_optional();
1896 verify_region_sets_optional();
1897 }
1899 // Public methods.
1901 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
1902 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
1903 #endif // _MSC_VER
1906 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :
1907 SharedHeap(policy_),
1908 _g1_policy(policy_),
1909 _dirty_card_queue_set(false),
1910 _into_cset_dirty_card_queue_set(false),
1911 _is_alive_closure_cm(this),
1912 _is_alive_closure_stw(this),
1913 _ref_processor_cm(NULL),
1914 _ref_processor_stw(NULL),
1915 _process_strong_tasks(new SubTasksDone(G1H_PS_NumElements)),
1916 _bot_shared(NULL),
1917 _evac_failure_scan_stack(NULL),
1918 _mark_in_progress(false),
1919 _cg1r(NULL), _summary_bytes_used(0),
1920 _g1mm(NULL),
1921 _refine_cte_cl(NULL),
1922 _full_collection(false),
1923 _free_list("Master Free List", new MasterFreeRegionListMtSafeChecker()),
1924 _secondary_free_list("Secondary Free List", new SecondaryFreeRegionListMtSafeChecker()),
1925 _old_set("Old Set", false /* humongous */, new OldRegionSetMtSafeChecker()),
1926 _humongous_set("Master Humongous Set", true /* humongous */, new HumongousRegionSetMtSafeChecker()),
1927 _free_regions_coming(false),
1928 _young_list(new YoungList(this)),
1929 _gc_time_stamp(0),
1930 _retained_old_gc_alloc_region(NULL),
1931 _survivor_plab_stats(YoungPLABSize, PLABWeight),
1932 _old_plab_stats(OldPLABSize, PLABWeight),
1933 _expand_heap_after_alloc_failure(true),
1934 _surviving_young_words(NULL),
1935 _old_marking_cycles_started(0),
1936 _old_marking_cycles_completed(0),
1937 _concurrent_cycle_started(false),
1938 _in_cset_fast_test(NULL),
1939 _in_cset_fast_test_base(NULL),
1940 _dirty_cards_region_list(NULL),
1941 _worker_cset_start_region(NULL),
1942 _worker_cset_start_region_time_stamp(NULL),
1943 _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),
1944 _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
1945 _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),
1946 _gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) G1OldTracer()) {
1948 _g1h = this;
1949 if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) {
1950 vm_exit_during_initialization("Failed necessary allocation.");
1951 }
1953 _humongous_object_threshold_in_words = HeapRegion::GrainWords / 2;
1955 int n_queues = MAX2((int)ParallelGCThreads, 1);
1956 _task_queues = new RefToScanQueueSet(n_queues);
1958 uint n_rem_sets = HeapRegionRemSet::num_par_rem_sets();
1959 assert(n_rem_sets > 0, "Invariant.");
1961 _worker_cset_start_region = NEW_C_HEAP_ARRAY(HeapRegion*, n_queues, mtGC);
1962 _worker_cset_start_region_time_stamp = NEW_C_HEAP_ARRAY(unsigned int, n_queues, mtGC);
1963 _evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);
1965 for (int i = 0; i < n_queues; i++) {
1966 RefToScanQueue* q = new RefToScanQueue();
1967 q->initialize();
1968 _task_queues->register_queue(i, q);
1969 ::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();
1970 }
1971 clear_cset_start_regions();
1973 // Initialize the G1EvacuationFailureALot counters and flags.
1974 NOT_PRODUCT(reset_evacuation_should_fail();)
1976 guarantee(_task_queues != NULL, "task_queues allocation failure.");
1977 }
1979 jint G1CollectedHeap::initialize() {
1980 CollectedHeap::pre_initialize();
1981 os::enable_vtime();
1983 G1Log::init();
1985 // Necessary to satisfy locking discipline assertions.
1987 MutexLocker x(Heap_lock);
1989 // We have to initialize the printer before committing the heap, as
1990 // it will be used then.
1991 _hr_printer.set_active(G1PrintHeapRegions);
1993 // While there are no constraints in the GC code that HeapWordSize
1994 // be any particular value, there are multiple other areas in the
1995 // system which believe this to be true (e.g. oop->object_size in some
1996 // cases incorrectly returns the size in wordSize units rather than
1997 // HeapWordSize).
1998 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
2000 size_t init_byte_size = collector_policy()->initial_heap_byte_size();
2001 size_t max_byte_size = collector_policy()->max_heap_byte_size();
2002 size_t heap_alignment = collector_policy()->heap_alignment();
2004 // Ensure that the sizes are properly aligned.
2005 Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
2006 Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");
2007 Universe::check_alignment(max_byte_size, heap_alignment, "g1 heap");
2009 _cg1r = new ConcurrentG1Refine(this);
2011 // Reserve the maximum.
2013 // When compressed oops are enabled, the preferred heap base
2014 // is calculated by subtracting the requested size from the
2015 // 32Gb boundary and using the result as the base address for
2016 // heap reservation. If the requested size is not aligned to
2017 // HeapRegion::GrainBytes (i.e. the alignment that is passed
2018 // into the ReservedHeapSpace constructor) then the actual
2019 // base of the reserved heap may end up differing from the
2020 // address that was requested (i.e. the preferred heap base).
2021 // If this happens then we could end up using a non-optimal
2022 // compressed oops mode.
2024 ReservedSpace heap_rs = Universe::reserve_heap(max_byte_size,
2025 heap_alignment);
2027 // It is important to do this in a way such that concurrent readers can't
2028 // temporarily think something is in the heap. (I've actually seen this
2029 // happen in asserts: DLD.)
2030 _reserved.set_word_size(0);
2031 _reserved.set_start((HeapWord*)heap_rs.base());
2032 _reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size()));
2034 _expansion_regions = (uint) (max_byte_size / HeapRegion::GrainBytes);
2036 // Create the gen rem set (and barrier set) for the entire reserved region.
2037 _rem_set = collector_policy()->create_rem_set(_reserved, 2);
2038 set_barrier_set(rem_set()->bs());
2039 if (!barrier_set()->is_a(BarrierSet::G1SATBCTLogging)) {
2040 vm_exit_during_initialization("G1 requires a G1SATBLoggingCardTableModRefBS");
2041 return JNI_ENOMEM;
2042 }
2044 // Also create a G1 rem set.
2045 _g1_rem_set = new G1RemSet(this, g1_barrier_set());
2047 // Carve out the G1 part of the heap.
2049 ReservedSpace g1_rs = heap_rs.first_part(max_byte_size);
2050 _g1_reserved = MemRegion((HeapWord*)g1_rs.base(),
2051 g1_rs.size()/HeapWordSize);
2053 _g1_storage.initialize(g1_rs, 0);
2054 _g1_committed = MemRegion((HeapWord*)_g1_storage.low(), (size_t) 0);
2055 _hrs.initialize((HeapWord*) _g1_reserved.start(),
2056 (HeapWord*) _g1_reserved.end());
2057 assert(_hrs.max_length() == _expansion_regions,
2058 err_msg("max length: %u expansion regions: %u",
2059 _hrs.max_length(), _expansion_regions));
2061 // Do later initialization work for concurrent refinement.
2062 _cg1r->init();
2064 // 6843694 - ensure that the maximum region index can fit
2065 // in the remembered set structures.
2066 const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
2067 guarantee((max_regions() - 1) <= max_region_idx, "too many regions");
2069 size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
2070 guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
2071 guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,
2072 "too many cards per region");
2074 FreeRegionList::set_unrealistically_long_length(max_regions() + 1);
2076 _bot_shared = new G1BlockOffsetSharedArray(_reserved,
2077 heap_word_size(init_byte_size));
2079 _g1h = this;
2081 _in_cset_fast_test_length = max_regions();
2082 _in_cset_fast_test_base =
2083 NEW_C_HEAP_ARRAY(bool, (size_t) _in_cset_fast_test_length, mtGC);
2085 // We're biasing _in_cset_fast_test to avoid subtracting the
2086 // beginning of the heap every time we want to index; basically
2087 // it's the same with what we do with the card table.
2088 _in_cset_fast_test = _in_cset_fast_test_base -
2089 ((uintx) _g1_reserved.start() >> HeapRegion::LogOfHRGrainBytes);
2091 // Clear the _cset_fast_test bitmap in anticipation of adding
2092 // regions to the incremental collection set for the first
2093 // evacuation pause.
2094 clear_cset_fast_test();
2096 // Create the ConcurrentMark data structure and thread.
2097 // (Must do this late, so that "max_regions" is defined.)
2098 _cm = new ConcurrentMark(this, heap_rs);
2099 if (_cm == NULL || !_cm->completed_initialization()) {
2100 vm_shutdown_during_initialization("Could not create/initialize ConcurrentMark");
2101 return JNI_ENOMEM;
2102 }
2103 _cmThread = _cm->cmThread();
2105 // Initialize the from_card cache structure of HeapRegionRemSet.
2106 HeapRegionRemSet::init_heap(max_regions());
2108 // Now expand into the initial heap size.
2109 if (!expand(init_byte_size)) {
2110 vm_shutdown_during_initialization("Failed to allocate initial heap.");
2111 return JNI_ENOMEM;
2112 }
2114 // Perform any initialization actions delegated to the policy.
2115 g1_policy()->init();
2117 _refine_cte_cl =
2118 new RefineCardTableEntryClosure(ConcurrentG1RefineThread::sts(),
2119 g1_rem_set(),
2120 concurrent_g1_refine());
2121 JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
2123 JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
2124 SATB_Q_FL_lock,
2125 G1SATBProcessCompletedThreshold,
2126 Shared_SATB_Q_lock);
2128 JavaThread::dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
2129 DirtyCardQ_FL_lock,
2130 concurrent_g1_refine()->yellow_zone(),
2131 concurrent_g1_refine()->red_zone(),
2132 Shared_DirtyCardQ_lock);
2134 if (G1DeferredRSUpdate) {
2135 dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
2136 DirtyCardQ_FL_lock,
2137 -1, // never trigger processing
2138 -1, // no limit on length
2139 Shared_DirtyCardQ_lock,
2140 &JavaThread::dirty_card_queue_set());
2141 }
2143 // Initialize the card queue set used to hold cards containing
2144 // references into the collection set.
2145 _into_cset_dirty_card_queue_set.initialize(DirtyCardQ_CBL_mon,
2146 DirtyCardQ_FL_lock,
2147 -1, // never trigger processing
2148 -1, // no limit on length
2149 Shared_DirtyCardQ_lock,
2150 &JavaThread::dirty_card_queue_set());
2152 // In case we're keeping closure specialization stats, initialize those
2153 // counts and that mechanism.
2154 SpecializationStats::clear();
2156 // Here we allocate the dummy full region that is required by the
2157 // G1AllocRegion class. If we don't pass an address in the reserved
2158 // space here, lots of asserts fire.
2160 HeapRegion* dummy_region = new_heap_region(0 /* index of bottom region */,
2161 _g1_reserved.start());
2162 // We'll re-use the same region whether the alloc region will
2163 // require BOT updates or not and, if it doesn't, then a non-young
2164 // region will complain that it cannot support allocations without
2165 // BOT updates. So we'll tag the dummy region as young to avoid that.
2166 dummy_region->set_young();
2167 // Make sure it's full.
2168 dummy_region->set_top(dummy_region->end());
2169 G1AllocRegion::setup(this, dummy_region);
2171 init_mutator_alloc_region();
2173 // Do create of the monitoring and management support so that
2174 // values in the heap have been properly initialized.
2175 _g1mm = new G1MonitoringSupport(this);
2177 G1StringDedup::initialize();
2179 return JNI_OK;
2180 }
2182 size_t G1CollectedHeap::conservative_max_heap_alignment() {
2183 return HeapRegion::max_region_size();
2184 }
2186 void G1CollectedHeap::ref_processing_init() {
2187 // Reference processing in G1 currently works as follows:
2188 //
2189 // * There are two reference processor instances. One is
2190 // used to record and process discovered references
2191 // during concurrent marking; the other is used to
2192 // record and process references during STW pauses
2193 // (both full and incremental).
2194 // * Both ref processors need to 'span' the entire heap as
2195 // the regions in the collection set may be dotted around.
2196 //
2197 // * For the concurrent marking ref processor:
2198 // * Reference discovery is enabled at initial marking.
2199 // * Reference discovery is disabled and the discovered
2200 // references processed etc during remarking.
2201 // * Reference discovery is MT (see below).
2202 // * Reference discovery requires a barrier (see below).
2203 // * Reference processing may or may not be MT
2204 // (depending on the value of ParallelRefProcEnabled
2205 // and ParallelGCThreads).
2206 // * A full GC disables reference discovery by the CM
2207 // ref processor and abandons any entries on it's
2208 // discovered lists.
2209 //
2210 // * For the STW processor:
2211 // * Non MT discovery is enabled at the start of a full GC.
2212 // * Processing and enqueueing during a full GC is non-MT.
2213 // * During a full GC, references are processed after marking.
2214 //
2215 // * Discovery (may or may not be MT) is enabled at the start
2216 // of an incremental evacuation pause.
2217 // * References are processed near the end of a STW evacuation pause.
2218 // * For both types of GC:
2219 // * Discovery is atomic - i.e. not concurrent.
2220 // * Reference discovery will not need a barrier.
2222 SharedHeap::ref_processing_init();
2223 MemRegion mr = reserved_region();
2225 // Concurrent Mark ref processor
2226 _ref_processor_cm =
2227 new ReferenceProcessor(mr, // span
2228 ParallelRefProcEnabled && (ParallelGCThreads > 1),
2229 // mt processing
2230 (int) ParallelGCThreads,
2231 // degree of mt processing
2232 (ParallelGCThreads > 1) || (ConcGCThreads > 1),
2233 // mt discovery
2234 (int) MAX2(ParallelGCThreads, ConcGCThreads),
2235 // degree of mt discovery
2236 false,
2237 // Reference discovery is not atomic
2238 &_is_alive_closure_cm,
2239 // is alive closure
2240 // (for efficiency/performance)
2241 true);
2242 // Setting next fields of discovered
2243 // lists requires a barrier.
2245 // STW ref processor
2246 _ref_processor_stw =
2247 new ReferenceProcessor(mr, // span
2248 ParallelRefProcEnabled && (ParallelGCThreads > 1),
2249 // mt processing
2250 MAX2((int)ParallelGCThreads, 1),
2251 // degree of mt processing
2252 (ParallelGCThreads > 1),
2253 // mt discovery
2254 MAX2((int)ParallelGCThreads, 1),
2255 // degree of mt discovery
2256 true,
2257 // Reference discovery is atomic
2258 &_is_alive_closure_stw,
2259 // is alive closure
2260 // (for efficiency/performance)
2261 false);
2262 // Setting next fields of discovered
2263 // lists does not require a barrier.
2264 }
2266 size_t G1CollectedHeap::capacity() const {
2267 return _g1_committed.byte_size();
2268 }
2270 void G1CollectedHeap::reset_gc_time_stamps(HeapRegion* hr) {
2271 assert(!hr->continuesHumongous(), "pre-condition");
2272 hr->reset_gc_time_stamp();
2273 if (hr->startsHumongous()) {
2274 uint first_index = hr->hrs_index() + 1;
2275 uint last_index = hr->last_hc_index();
2276 for (uint i = first_index; i < last_index; i += 1) {
2277 HeapRegion* chr = region_at(i);
2278 assert(chr->continuesHumongous(), "sanity");
2279 chr->reset_gc_time_stamp();
2280 }
2281 }
2282 }
2284 #ifndef PRODUCT
2285 class CheckGCTimeStampsHRClosure : public HeapRegionClosure {
2286 private:
2287 unsigned _gc_time_stamp;
2288 bool _failures;
2290 public:
2291 CheckGCTimeStampsHRClosure(unsigned gc_time_stamp) :
2292 _gc_time_stamp(gc_time_stamp), _failures(false) { }
2294 virtual bool doHeapRegion(HeapRegion* hr) {
2295 unsigned region_gc_time_stamp = hr->get_gc_time_stamp();
2296 if (_gc_time_stamp != region_gc_time_stamp) {
2297 gclog_or_tty->print_cr("Region "HR_FORMAT" has GC time stamp = %d, "
2298 "expected %d", HR_FORMAT_PARAMS(hr),
2299 region_gc_time_stamp, _gc_time_stamp);
2300 _failures = true;
2301 }
2302 return false;
2303 }
2305 bool failures() { return _failures; }
2306 };
2308 void G1CollectedHeap::check_gc_time_stamps() {
2309 CheckGCTimeStampsHRClosure cl(_gc_time_stamp);
2310 heap_region_iterate(&cl);
2311 guarantee(!cl.failures(), "all GC time stamps should have been reset");
2312 }
2313 #endif // PRODUCT
2315 void G1CollectedHeap::iterate_dirty_card_closure(CardTableEntryClosure* cl,
2316 DirtyCardQueue* into_cset_dcq,
2317 bool concurrent,
2318 int worker_i) {
2319 // Clean cards in the hot card cache
2320 G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
2321 hot_card_cache->drain(worker_i, g1_rem_set(), into_cset_dcq);
2323 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
2324 int n_completed_buffers = 0;
2325 while (dcqs.apply_closure_to_completed_buffer(cl, worker_i, 0, true)) {
2326 n_completed_buffers++;
2327 }
2328 g1_policy()->phase_times()->record_update_rs_processed_buffers(worker_i, n_completed_buffers);
2329 dcqs.clear_n_completed_buffers();
2330 assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!");
2331 }
2334 // Computes the sum of the storage used by the various regions.
2336 size_t G1CollectedHeap::used() const {
2337 assert(Heap_lock->owner() != NULL,
2338 "Should be owned on this thread's behalf.");
2339 size_t result = _summary_bytes_used;
2340 // Read only once in case it is set to NULL concurrently
2341 HeapRegion* hr = _mutator_alloc_region.get();
2342 if (hr != NULL)
2343 result += hr->used();
2344 return result;
2345 }
2347 size_t G1CollectedHeap::used_unlocked() const {
2348 size_t result = _summary_bytes_used;
2349 return result;
2350 }
2352 class SumUsedClosure: public HeapRegionClosure {
2353 size_t _used;
2354 public:
2355 SumUsedClosure() : _used(0) {}
2356 bool doHeapRegion(HeapRegion* r) {
2357 if (!r->continuesHumongous()) {
2358 _used += r->used();
2359 }
2360 return false;
2361 }
2362 size_t result() { return _used; }
2363 };
2365 size_t G1CollectedHeap::recalculate_used() const {
2366 double recalculate_used_start = os::elapsedTime();
2368 SumUsedClosure blk;
2369 heap_region_iterate(&blk);
2371 g1_policy()->phase_times()->record_evac_fail_recalc_used_time((os::elapsedTime() - recalculate_used_start) * 1000.0);
2372 return blk.result();
2373 }
2375 size_t G1CollectedHeap::unsafe_max_alloc() {
2376 if (free_regions() > 0) return HeapRegion::GrainBytes;
2377 // otherwise, is there space in the current allocation region?
2379 // We need to store the current allocation region in a local variable
2380 // here. The problem is that this method doesn't take any locks and
2381 // there may be other threads which overwrite the current allocation
2382 // region field. attempt_allocation(), for example, sets it to NULL
2383 // and this can happen *after* the NULL check here but before the call
2384 // to free(), resulting in a SIGSEGV. Note that this doesn't appear
2385 // to be a problem in the optimized build, since the two loads of the
2386 // current allocation region field are optimized away.
2387 HeapRegion* hr = _mutator_alloc_region.get();
2388 if (hr == NULL) {
2389 return 0;
2390 }
2391 return hr->free();
2392 }
2394 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
2395 switch (cause) {
2396 case GCCause::_gc_locker: return GCLockerInvokesConcurrent;
2397 case GCCause::_java_lang_system_gc: return ExplicitGCInvokesConcurrent;
2398 case GCCause::_g1_humongous_allocation: return true;
2399 default: return false;
2400 }
2401 }
2403 #ifndef PRODUCT
2404 void G1CollectedHeap::allocate_dummy_regions() {
2405 // Let's fill up most of the region
2406 size_t word_size = HeapRegion::GrainWords - 1024;
2407 // And as a result the region we'll allocate will be humongous.
2408 guarantee(isHumongous(word_size), "sanity");
2410 for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {
2411 // Let's use the existing mechanism for the allocation
2412 HeapWord* dummy_obj = humongous_obj_allocate(word_size);
2413 if (dummy_obj != NULL) {
2414 MemRegion mr(dummy_obj, word_size);
2415 CollectedHeap::fill_with_object(mr);
2416 } else {
2417 // If we can't allocate once, we probably cannot allocate
2418 // again. Let's get out of the loop.
2419 break;
2420 }
2421 }
2422 }
2423 #endif // !PRODUCT
2425 void G1CollectedHeap::increment_old_marking_cycles_started() {
2426 assert(_old_marking_cycles_started == _old_marking_cycles_completed ||
2427 _old_marking_cycles_started == _old_marking_cycles_completed + 1,
2428 err_msg("Wrong marking cycle count (started: %d, completed: %d)",
2429 _old_marking_cycles_started, _old_marking_cycles_completed));
2431 _old_marking_cycles_started++;
2432 }
2434 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent) {
2435 MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
2437 // We assume that if concurrent == true, then the caller is a
2438 // concurrent thread that was joined the Suspendible Thread
2439 // Set. If there's ever a cheap way to check this, we should add an
2440 // assert here.
2442 // Given that this method is called at the end of a Full GC or of a
2443 // concurrent cycle, and those can be nested (i.e., a Full GC can
2444 // interrupt a concurrent cycle), the number of full collections
2445 // completed should be either one (in the case where there was no
2446 // nesting) or two (when a Full GC interrupted a concurrent cycle)
2447 // behind the number of full collections started.
2449 // This is the case for the inner caller, i.e. a Full GC.
2450 assert(concurrent ||
2451 (_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||
2452 (_old_marking_cycles_started == _old_marking_cycles_completed + 2),
2453 err_msg("for inner caller (Full GC): _old_marking_cycles_started = %u "
2454 "is inconsistent with _old_marking_cycles_completed = %u",
2455 _old_marking_cycles_started, _old_marking_cycles_completed));
2457 // This is the case for the outer caller, i.e. the concurrent cycle.
2458 assert(!concurrent ||
2459 (_old_marking_cycles_started == _old_marking_cycles_completed + 1),
2460 err_msg("for outer caller (concurrent cycle): "
2461 "_old_marking_cycles_started = %u "
2462 "is inconsistent with _old_marking_cycles_completed = %u",
2463 _old_marking_cycles_started, _old_marking_cycles_completed));
2465 _old_marking_cycles_completed += 1;
2467 // We need to clear the "in_progress" flag in the CM thread before
2468 // we wake up any waiters (especially when ExplicitInvokesConcurrent
2469 // is set) so that if a waiter requests another System.gc() it doesn't
2470 // incorrectly see that a marking cycle is still in progress.
2471 if (concurrent) {
2472 _cmThread->clear_in_progress();
2473 }
2475 // This notify_all() will ensure that a thread that called
2476 // System.gc() with (with ExplicitGCInvokesConcurrent set or not)
2477 // and it's waiting for a full GC to finish will be woken up. It is
2478 // waiting in VM_G1IncCollectionPause::doit_epilogue().
2479 FullGCCount_lock->notify_all();
2480 }
2482 void G1CollectedHeap::register_concurrent_cycle_start(const Ticks& start_time) {
2483 _concurrent_cycle_started = true;
2484 _gc_timer_cm->register_gc_start(start_time);
2486 _gc_tracer_cm->report_gc_start(gc_cause(), _gc_timer_cm->gc_start());
2487 trace_heap_before_gc(_gc_tracer_cm);
2488 }
2490 void G1CollectedHeap::register_concurrent_cycle_end() {
2491 if (_concurrent_cycle_started) {
2492 if (_cm->has_aborted()) {
2493 _gc_tracer_cm->report_concurrent_mode_failure();
2494 }
2496 _gc_timer_cm->register_gc_end();
2497 _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions());
2499 _concurrent_cycle_started = false;
2500 }
2501 }
2503 void G1CollectedHeap::trace_heap_after_concurrent_cycle() {
2504 if (_concurrent_cycle_started) {
2505 trace_heap_after_gc(_gc_tracer_cm);
2506 }
2507 }
2509 G1YCType G1CollectedHeap::yc_type() {
2510 bool is_young = g1_policy()->gcs_are_young();
2511 bool is_initial_mark = g1_policy()->during_initial_mark_pause();
2512 bool is_during_mark = mark_in_progress();
2514 if (is_initial_mark) {
2515 return InitialMark;
2516 } else if (is_during_mark) {
2517 return DuringMark;
2518 } else if (is_young) {
2519 return Normal;
2520 } else {
2521 return Mixed;
2522 }
2523 }
2525 void G1CollectedHeap::collect(GCCause::Cause cause) {
2526 assert_heap_not_locked();
2528 unsigned int gc_count_before;
2529 unsigned int old_marking_count_before;
2530 bool retry_gc;
2532 do {
2533 retry_gc = false;
2535 {
2536 MutexLocker ml(Heap_lock);
2538 // Read the GC count while holding the Heap_lock
2539 gc_count_before = total_collections();
2540 old_marking_count_before = _old_marking_cycles_started;
2541 }
2543 if (should_do_concurrent_full_gc(cause)) {
2544 // Schedule an initial-mark evacuation pause that will start a
2545 // concurrent cycle. We're setting word_size to 0 which means that
2546 // we are not requesting a post-GC allocation.
2547 VM_G1IncCollectionPause op(gc_count_before,
2548 0, /* word_size */
2549 true, /* should_initiate_conc_mark */
2550 g1_policy()->max_pause_time_ms(),
2551 cause);
2553 VMThread::execute(&op);
2554 if (!op.pause_succeeded()) {
2555 if (old_marking_count_before == _old_marking_cycles_started) {
2556 retry_gc = op.should_retry_gc();
2557 } else {
2558 // A Full GC happened while we were trying to schedule the
2559 // initial-mark GC. No point in starting a new cycle given
2560 // that the whole heap was collected anyway.
2561 }
2563 if (retry_gc) {
2564 if (GC_locker::is_active_and_needs_gc()) {
2565 GC_locker::stall_until_clear();
2566 }
2567 }
2568 }
2569 } else {
2570 if (cause == GCCause::_gc_locker
2571 DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
2573 // Schedule a standard evacuation pause. We're setting word_size
2574 // to 0 which means that we are not requesting a post-GC allocation.
2575 VM_G1IncCollectionPause op(gc_count_before,
2576 0, /* word_size */
2577 false, /* should_initiate_conc_mark */
2578 g1_policy()->max_pause_time_ms(),
2579 cause);
2580 VMThread::execute(&op);
2581 } else {
2582 // Schedule a Full GC.
2583 VM_G1CollectFull op(gc_count_before, old_marking_count_before, cause);
2584 VMThread::execute(&op);
2585 }
2586 }
2587 } while (retry_gc);
2588 }
2590 bool G1CollectedHeap::is_in(const void* p) const {
2591 if (_g1_committed.contains(p)) {
2592 // Given that we know that p is in the committed space,
2593 // heap_region_containing_raw() should successfully
2594 // return the containing region.
2595 HeapRegion* hr = heap_region_containing_raw(p);
2596 return hr->is_in(p);
2597 } else {
2598 return false;
2599 }
2600 }
2602 // Iteration functions.
2604 // Iterates an OopClosure over all ref-containing fields of objects
2605 // within a HeapRegion.
2607 class IterateOopClosureRegionClosure: public HeapRegionClosure {
2608 MemRegion _mr;
2609 ExtendedOopClosure* _cl;
2610 public:
2611 IterateOopClosureRegionClosure(MemRegion mr, ExtendedOopClosure* cl)
2612 : _mr(mr), _cl(cl) {}
2613 bool doHeapRegion(HeapRegion* r) {
2614 if (!r->continuesHumongous()) {
2615 r->oop_iterate(_cl);
2616 }
2617 return false;
2618 }
2619 };
2621 void G1CollectedHeap::oop_iterate(ExtendedOopClosure* cl) {
2622 IterateOopClosureRegionClosure blk(_g1_committed, cl);
2623 heap_region_iterate(&blk);
2624 }
2626 void G1CollectedHeap::oop_iterate(MemRegion mr, ExtendedOopClosure* cl) {
2627 IterateOopClosureRegionClosure blk(mr, cl);
2628 heap_region_iterate(&blk);
2629 }
2631 // Iterates an ObjectClosure over all objects within a HeapRegion.
2633 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
2634 ObjectClosure* _cl;
2635 public:
2636 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
2637 bool doHeapRegion(HeapRegion* r) {
2638 if (! r->continuesHumongous()) {
2639 r->object_iterate(_cl);
2640 }
2641 return false;
2642 }
2643 };
2645 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
2646 IterateObjectClosureRegionClosure blk(cl);
2647 heap_region_iterate(&blk);
2648 }
2650 // Calls a SpaceClosure on a HeapRegion.
2652 class SpaceClosureRegionClosure: public HeapRegionClosure {
2653 SpaceClosure* _cl;
2654 public:
2655 SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {}
2656 bool doHeapRegion(HeapRegion* r) {
2657 _cl->do_space(r);
2658 return false;
2659 }
2660 };
2662 void G1CollectedHeap::space_iterate(SpaceClosure* cl) {
2663 SpaceClosureRegionClosure blk(cl);
2664 heap_region_iterate(&blk);
2665 }
2667 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
2668 _hrs.iterate(cl);
2669 }
2671 void
2672 G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,
2673 uint worker_id,
2674 uint no_of_par_workers,
2675 jint claim_value) {
2676 const uint regions = n_regions();
2677 const uint max_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
2678 no_of_par_workers :
2679 1);
2680 assert(UseDynamicNumberOfGCThreads ||
2681 no_of_par_workers == workers()->total_workers(),
2682 "Non dynamic should use fixed number of workers");
2683 // try to spread out the starting points of the workers
2684 const HeapRegion* start_hr =
2685 start_region_for_worker(worker_id, no_of_par_workers);
2686 const uint start_index = start_hr->hrs_index();
2688 // each worker will actually look at all regions
2689 for (uint count = 0; count < regions; ++count) {
2690 const uint index = (start_index + count) % regions;
2691 assert(0 <= index && index < regions, "sanity");
2692 HeapRegion* r = region_at(index);
2693 // we'll ignore "continues humongous" regions (we'll process them
2694 // when we come across their corresponding "start humongous"
2695 // region) and regions already claimed
2696 if (r->claim_value() == claim_value || r->continuesHumongous()) {
2697 continue;
2698 }
2699 // OK, try to claim it
2700 if (r->claimHeapRegion(claim_value)) {
2701 // success!
2702 assert(!r->continuesHumongous(), "sanity");
2703 if (r->startsHumongous()) {
2704 // If the region is "starts humongous" we'll iterate over its
2705 // "continues humongous" first; in fact we'll do them
2706 // first. The order is important. In on case, calling the
2707 // closure on the "starts humongous" region might de-allocate
2708 // and clear all its "continues humongous" regions and, as a
2709 // result, we might end up processing them twice. So, we'll do
2710 // them first (notice: most closures will ignore them anyway) and
2711 // then we'll do the "starts humongous" region.
2712 for (uint ch_index = index + 1; ch_index < regions; ++ch_index) {
2713 HeapRegion* chr = region_at(ch_index);
2715 // if the region has already been claimed or it's not
2716 // "continues humongous" we're done
2717 if (chr->claim_value() == claim_value ||
2718 !chr->continuesHumongous()) {
2719 break;
2720 }
2722 // No one should have claimed it directly. We can given
2723 // that we claimed its "starts humongous" region.
2724 assert(chr->claim_value() != claim_value, "sanity");
2725 assert(chr->humongous_start_region() == r, "sanity");
2727 if (chr->claimHeapRegion(claim_value)) {
2728 // we should always be able to claim it; no one else should
2729 // be trying to claim this region
2731 bool res2 = cl->doHeapRegion(chr);
2732 assert(!res2, "Should not abort");
2734 // Right now, this holds (i.e., no closure that actually
2735 // does something with "continues humongous" regions
2736 // clears them). We might have to weaken it in the future,
2737 // but let's leave these two asserts here for extra safety.
2738 assert(chr->continuesHumongous(), "should still be the case");
2739 assert(chr->humongous_start_region() == r, "sanity");
2740 } else {
2741 guarantee(false, "we should not reach here");
2742 }
2743 }
2744 }
2746 assert(!r->continuesHumongous(), "sanity");
2747 bool res = cl->doHeapRegion(r);
2748 assert(!res, "Should not abort");
2749 }
2750 }
2751 }
2753 class ResetClaimValuesClosure: public HeapRegionClosure {
2754 public:
2755 bool doHeapRegion(HeapRegion* r) {
2756 r->set_claim_value(HeapRegion::InitialClaimValue);
2757 return false;
2758 }
2759 };
2761 void G1CollectedHeap::reset_heap_region_claim_values() {
2762 ResetClaimValuesClosure blk;
2763 heap_region_iterate(&blk);
2764 }
2766 void G1CollectedHeap::reset_cset_heap_region_claim_values() {
2767 ResetClaimValuesClosure blk;
2768 collection_set_iterate(&blk);
2769 }
2771 #ifdef ASSERT
2772 // This checks whether all regions in the heap have the correct claim
2773 // value. I also piggy-backed on this a check to ensure that the
2774 // humongous_start_region() information on "continues humongous"
2775 // regions is correct.
2777 class CheckClaimValuesClosure : public HeapRegionClosure {
2778 private:
2779 jint _claim_value;
2780 uint _failures;
2781 HeapRegion* _sh_region;
2783 public:
2784 CheckClaimValuesClosure(jint claim_value) :
2785 _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
2786 bool doHeapRegion(HeapRegion* r) {
2787 if (r->claim_value() != _claim_value) {
2788 gclog_or_tty->print_cr("Region " HR_FORMAT ", "
2789 "claim value = %d, should be %d",
2790 HR_FORMAT_PARAMS(r),
2791 r->claim_value(), _claim_value);
2792 ++_failures;
2793 }
2794 if (!r->isHumongous()) {
2795 _sh_region = NULL;
2796 } else if (r->startsHumongous()) {
2797 _sh_region = r;
2798 } else if (r->continuesHumongous()) {
2799 if (r->humongous_start_region() != _sh_region) {
2800 gclog_or_tty->print_cr("Region " HR_FORMAT ", "
2801 "HS = "PTR_FORMAT", should be "PTR_FORMAT,
2802 HR_FORMAT_PARAMS(r),
2803 r->humongous_start_region(),
2804 _sh_region);
2805 ++_failures;
2806 }
2807 }
2808 return false;
2809 }
2810 uint failures() { return _failures; }
2811 };
2813 bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
2814 CheckClaimValuesClosure cl(claim_value);
2815 heap_region_iterate(&cl);
2816 return cl.failures() == 0;
2817 }
2819 class CheckClaimValuesInCSetHRClosure: public HeapRegionClosure {
2820 private:
2821 jint _claim_value;
2822 uint _failures;
2824 public:
2825 CheckClaimValuesInCSetHRClosure(jint claim_value) :
2826 _claim_value(claim_value), _failures(0) { }
2828 uint failures() { return _failures; }
2830 bool doHeapRegion(HeapRegion* hr) {
2831 assert(hr->in_collection_set(), "how?");
2832 assert(!hr->isHumongous(), "H-region in CSet");
2833 if (hr->claim_value() != _claim_value) {
2834 gclog_or_tty->print_cr("CSet Region " HR_FORMAT ", "
2835 "claim value = %d, should be %d",
2836 HR_FORMAT_PARAMS(hr),
2837 hr->claim_value(), _claim_value);
2838 _failures += 1;
2839 }
2840 return false;
2841 }
2842 };
2844 bool G1CollectedHeap::check_cset_heap_region_claim_values(jint claim_value) {
2845 CheckClaimValuesInCSetHRClosure cl(claim_value);
2846 collection_set_iterate(&cl);
2847 return cl.failures() == 0;
2848 }
2849 #endif // ASSERT
2851 // Clear the cached CSet starting regions and (more importantly)
2852 // the time stamps. Called when we reset the GC time stamp.
2853 void G1CollectedHeap::clear_cset_start_regions() {
2854 assert(_worker_cset_start_region != NULL, "sanity");
2855 assert(_worker_cset_start_region_time_stamp != NULL, "sanity");
2857 int n_queues = MAX2((int)ParallelGCThreads, 1);
2858 for (int i = 0; i < n_queues; i++) {
2859 _worker_cset_start_region[i] = NULL;
2860 _worker_cset_start_region_time_stamp[i] = 0;
2861 }
2862 }
2864 // Given the id of a worker, obtain or calculate a suitable
2865 // starting region for iterating over the current collection set.
2866 HeapRegion* G1CollectedHeap::start_cset_region_for_worker(int worker_i) {
2867 assert(get_gc_time_stamp() > 0, "should have been updated by now");
2869 HeapRegion* result = NULL;
2870 unsigned gc_time_stamp = get_gc_time_stamp();
2872 if (_worker_cset_start_region_time_stamp[worker_i] == gc_time_stamp) {
2873 // Cached starting region for current worker was set
2874 // during the current pause - so it's valid.
2875 // Note: the cached starting heap region may be NULL
2876 // (when the collection set is empty).
2877 result = _worker_cset_start_region[worker_i];
2878 assert(result == NULL || result->in_collection_set(), "sanity");
2879 return result;
2880 }
2882 // The cached entry was not valid so let's calculate
2883 // a suitable starting heap region for this worker.
2885 // We want the parallel threads to start their collection
2886 // set iteration at different collection set regions to
2887 // avoid contention.
2888 // If we have:
2889 // n collection set regions
2890 // p threads
2891 // Then thread t will start at region floor ((t * n) / p)
2893 result = g1_policy()->collection_set();
2894 if (G1CollectedHeap::use_parallel_gc_threads()) {
2895 uint cs_size = g1_policy()->cset_region_length();
2896 uint active_workers = workers()->active_workers();
2897 assert(UseDynamicNumberOfGCThreads ||
2898 active_workers == workers()->total_workers(),
2899 "Unless dynamic should use total workers");
2901 uint end_ind = (cs_size * worker_i) / active_workers;
2902 uint start_ind = 0;
2904 if (worker_i > 0 &&
2905 _worker_cset_start_region_time_stamp[worker_i - 1] == gc_time_stamp) {
2906 // Previous workers starting region is valid
2907 // so let's iterate from there
2908 start_ind = (cs_size * (worker_i - 1)) / active_workers;
2909 result = _worker_cset_start_region[worker_i - 1];
2910 }
2912 for (uint i = start_ind; i < end_ind; i++) {
2913 result = result->next_in_collection_set();
2914 }
2915 }
2917 // Note: the calculated starting heap region may be NULL
2918 // (when the collection set is empty).
2919 assert(result == NULL || result->in_collection_set(), "sanity");
2920 assert(_worker_cset_start_region_time_stamp[worker_i] != gc_time_stamp,
2921 "should be updated only once per pause");
2922 _worker_cset_start_region[worker_i] = result;
2923 OrderAccess::storestore();
2924 _worker_cset_start_region_time_stamp[worker_i] = gc_time_stamp;
2925 return result;
2926 }
2928 HeapRegion* G1CollectedHeap::start_region_for_worker(uint worker_i,
2929 uint no_of_par_workers) {
2930 uint worker_num =
2931 G1CollectedHeap::use_parallel_gc_threads() ? no_of_par_workers : 1U;
2932 assert(UseDynamicNumberOfGCThreads ||
2933 no_of_par_workers == workers()->total_workers(),
2934 "Non dynamic should use fixed number of workers");
2935 const uint start_index = n_regions() * worker_i / worker_num;
2936 return region_at(start_index);
2937 }
2939 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {
2940 HeapRegion* r = g1_policy()->collection_set();
2941 while (r != NULL) {
2942 HeapRegion* next = r->next_in_collection_set();
2943 if (cl->doHeapRegion(r)) {
2944 cl->incomplete();
2945 return;
2946 }
2947 r = next;
2948 }
2949 }
2951 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,
2952 HeapRegionClosure *cl) {
2953 if (r == NULL) {
2954 // The CSet is empty so there's nothing to do.
2955 return;
2956 }
2958 assert(r->in_collection_set(),
2959 "Start region must be a member of the collection set.");
2960 HeapRegion* cur = r;
2961 while (cur != NULL) {
2962 HeapRegion* next = cur->next_in_collection_set();
2963 if (cl->doHeapRegion(cur) && false) {
2964 cl->incomplete();
2965 return;
2966 }
2967 cur = next;
2968 }
2969 cur = g1_policy()->collection_set();
2970 while (cur != r) {
2971 HeapRegion* next = cur->next_in_collection_set();
2972 if (cl->doHeapRegion(cur) && false) {
2973 cl->incomplete();
2974 return;
2975 }
2976 cur = next;
2977 }
2978 }
2980 CompactibleSpace* G1CollectedHeap::first_compactible_space() {
2981 return n_regions() > 0 ? region_at(0) : NULL;
2982 }
2985 Space* G1CollectedHeap::space_containing(const void* addr) const {
2986 Space* res = heap_region_containing(addr);
2987 return res;
2988 }
2990 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
2991 Space* sp = space_containing(addr);
2992 if (sp != NULL) {
2993 return sp->block_start(addr);
2994 }
2995 return NULL;
2996 }
2998 size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
2999 Space* sp = space_containing(addr);
3000 assert(sp != NULL, "block_size of address outside of heap");
3001 return sp->block_size(addr);
3002 }
3004 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
3005 Space* sp = space_containing(addr);
3006 return sp->block_is_obj(addr);
3007 }
3009 bool G1CollectedHeap::supports_tlab_allocation() const {
3010 return true;
3011 }
3013 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
3014 return (_g1_policy->young_list_target_length() - young_list()->survivor_length()) * HeapRegion::GrainBytes;
3015 }
3017 size_t G1CollectedHeap::tlab_used(Thread* ignored) const {
3018 return young_list()->eden_used_bytes();
3019 }
3021 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size
3022 // must be smaller than the humongous object limit.
3023 size_t G1CollectedHeap::max_tlab_size() const {
3024 return align_size_down(_humongous_object_threshold_in_words - 1, MinObjAlignment);
3025 }
3027 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
3028 // Return the remaining space in the cur alloc region, but not less than
3029 // the min TLAB size.
3031 // Also, this value can be at most the humongous object threshold,
3032 // since we can't allow tlabs to grow big enough to accommodate
3033 // humongous objects.
3035 HeapRegion* hr = _mutator_alloc_region.get();
3036 size_t max_tlab = max_tlab_size() * wordSize;
3037 if (hr == NULL) {
3038 return max_tlab;
3039 } else {
3040 return MIN2(MAX2(hr->free(), (size_t) MinTLABSize), max_tlab);
3041 }
3042 }
3044 size_t G1CollectedHeap::max_capacity() const {
3045 return _g1_reserved.byte_size();
3046 }
3048 jlong G1CollectedHeap::millis_since_last_gc() {
3049 // assert(false, "NYI");
3050 return 0;
3051 }
3053 void G1CollectedHeap::prepare_for_verify() {
3054 if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
3055 ensure_parsability(false);
3056 }
3057 g1_rem_set()->prepare_for_verify();
3058 }
3060 bool G1CollectedHeap::allocated_since_marking(oop obj, HeapRegion* hr,
3061 VerifyOption vo) {
3062 switch (vo) {
3063 case VerifyOption_G1UsePrevMarking:
3064 return hr->obj_allocated_since_prev_marking(obj);
3065 case VerifyOption_G1UseNextMarking:
3066 return hr->obj_allocated_since_next_marking(obj);
3067 case VerifyOption_G1UseMarkWord:
3068 return false;
3069 default:
3070 ShouldNotReachHere();
3071 }
3072 return false; // keep some compilers happy
3073 }
3075 HeapWord* G1CollectedHeap::top_at_mark_start(HeapRegion* hr, VerifyOption vo) {
3076 switch (vo) {
3077 case VerifyOption_G1UsePrevMarking: return hr->prev_top_at_mark_start();
3078 case VerifyOption_G1UseNextMarking: return hr->next_top_at_mark_start();
3079 case VerifyOption_G1UseMarkWord: return NULL;
3080 default: ShouldNotReachHere();
3081 }
3082 return NULL; // keep some compilers happy
3083 }
3085 bool G1CollectedHeap::is_marked(oop obj, VerifyOption vo) {
3086 switch (vo) {
3087 case VerifyOption_G1UsePrevMarking: return isMarkedPrev(obj);
3088 case VerifyOption_G1UseNextMarking: return isMarkedNext(obj);
3089 case VerifyOption_G1UseMarkWord: return obj->is_gc_marked();
3090 default: ShouldNotReachHere();
3091 }
3092 return false; // keep some compilers happy
3093 }
3095 const char* G1CollectedHeap::top_at_mark_start_str(VerifyOption vo) {
3096 switch (vo) {
3097 case VerifyOption_G1UsePrevMarking: return "PTAMS";
3098 case VerifyOption_G1UseNextMarking: return "NTAMS";
3099 case VerifyOption_G1UseMarkWord: return "NONE";
3100 default: ShouldNotReachHere();
3101 }
3102 return NULL; // keep some compilers happy
3103 }
3105 class VerifyRootsClosure: public OopClosure {
3106 private:
3107 G1CollectedHeap* _g1h;
3108 VerifyOption _vo;
3109 bool _failures;
3110 public:
3111 // _vo == UsePrevMarking -> use "prev" marking information,
3112 // _vo == UseNextMarking -> use "next" marking information,
3113 // _vo == UseMarkWord -> use mark word from object header.
3114 VerifyRootsClosure(VerifyOption vo) :
3115 _g1h(G1CollectedHeap::heap()),
3116 _vo(vo),
3117 _failures(false) { }
3119 bool failures() { return _failures; }
3121 template <class T> void do_oop_nv(T* p) {
3122 T heap_oop = oopDesc::load_heap_oop(p);
3123 if (!oopDesc::is_null(heap_oop)) {
3124 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
3125 if (_g1h->is_obj_dead_cond(obj, _vo)) {
3126 gclog_or_tty->print_cr("Root location "PTR_FORMAT" "
3127 "points to dead obj "PTR_FORMAT, p, (void*) obj);
3128 if (_vo == VerifyOption_G1UseMarkWord) {
3129 gclog_or_tty->print_cr(" Mark word: "PTR_FORMAT, (void*)(obj->mark()));
3130 }
3131 obj->print_on(gclog_or_tty);
3132 _failures = true;
3133 }
3134 }
3135 }
3137 void do_oop(oop* p) { do_oop_nv(p); }
3138 void do_oop(narrowOop* p) { do_oop_nv(p); }
3139 };
3141 class G1VerifyCodeRootOopClosure: public OopClosure {
3142 G1CollectedHeap* _g1h;
3143 OopClosure* _root_cl;
3144 nmethod* _nm;
3145 VerifyOption _vo;
3146 bool _failures;
3148 template <class T> void do_oop_work(T* p) {
3149 // First verify that this root is live
3150 _root_cl->do_oop(p);
3152 if (!G1VerifyHeapRegionCodeRoots) {
3153 // We're not verifying the code roots attached to heap region.
3154 return;
3155 }
3157 // Don't check the code roots during marking verification in a full GC
3158 if (_vo == VerifyOption_G1UseMarkWord) {
3159 return;
3160 }
3162 // Now verify that the current nmethod (which contains p) is
3163 // in the code root list of the heap region containing the
3164 // object referenced by p.
3166 T heap_oop = oopDesc::load_heap_oop(p);
3167 if (!oopDesc::is_null(heap_oop)) {
3168 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
3170 // Now fetch the region containing the object
3171 HeapRegion* hr = _g1h->heap_region_containing(obj);
3172 HeapRegionRemSet* hrrs = hr->rem_set();
3173 // Verify that the strong code root list for this region
3174 // contains the nmethod
3175 if (!hrrs->strong_code_roots_list_contains(_nm)) {
3176 gclog_or_tty->print_cr("Code root location "PTR_FORMAT" "
3177 "from nmethod "PTR_FORMAT" not in strong "
3178 "code roots for region ["PTR_FORMAT","PTR_FORMAT")",
3179 p, _nm, hr->bottom(), hr->end());
3180 _failures = true;
3181 }
3182 }
3183 }
3185 public:
3186 G1VerifyCodeRootOopClosure(G1CollectedHeap* g1h, OopClosure* root_cl, VerifyOption vo):
3187 _g1h(g1h), _root_cl(root_cl), _vo(vo), _nm(NULL), _failures(false) {}
3189 void do_oop(oop* p) { do_oop_work(p); }
3190 void do_oop(narrowOop* p) { do_oop_work(p); }
3192 void set_nmethod(nmethod* nm) { _nm = nm; }
3193 bool failures() { return _failures; }
3194 };
3196 class G1VerifyCodeRootBlobClosure: public CodeBlobClosure {
3197 G1VerifyCodeRootOopClosure* _oop_cl;
3199 public:
3200 G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure* oop_cl):
3201 _oop_cl(oop_cl) {}
3203 void do_code_blob(CodeBlob* cb) {
3204 nmethod* nm = cb->as_nmethod_or_null();
3205 if (nm != NULL) {
3206 _oop_cl->set_nmethod(nm);
3207 nm->oops_do(_oop_cl);
3208 }
3209 }
3210 };
3212 class YoungRefCounterClosure : public OopClosure {
3213 G1CollectedHeap* _g1h;
3214 int _count;
3215 public:
3216 YoungRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {}
3217 void do_oop(oop* p) { if (_g1h->is_in_young(*p)) { _count++; } }
3218 void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3220 int count() { return _count; }
3221 void reset_count() { _count = 0; };
3222 };
3224 class VerifyKlassClosure: public KlassClosure {
3225 YoungRefCounterClosure _young_ref_counter_closure;
3226 OopClosure *_oop_closure;
3227 public:
3228 VerifyKlassClosure(G1CollectedHeap* g1h, OopClosure* cl) : _young_ref_counter_closure(g1h), _oop_closure(cl) {}
3229 void do_klass(Klass* k) {
3230 k->oops_do(_oop_closure);
3232 _young_ref_counter_closure.reset_count();
3233 k->oops_do(&_young_ref_counter_closure);
3234 if (_young_ref_counter_closure.count() > 0) {
3235 guarantee(k->has_modified_oops(), err_msg("Klass %p, has young refs but is not dirty.", k));
3236 }
3237 }
3238 };
3240 class VerifyLivenessOopClosure: public OopClosure {
3241 G1CollectedHeap* _g1h;
3242 VerifyOption _vo;
3243 public:
3244 VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo):
3245 _g1h(g1h), _vo(vo)
3246 { }
3247 void do_oop(narrowOop *p) { do_oop_work(p); }
3248 void do_oop( oop *p) { do_oop_work(p); }
3250 template <class T> void do_oop_work(T *p) {
3251 oop obj = oopDesc::load_decode_heap_oop(p);
3252 guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo),
3253 "Dead object referenced by a not dead object");
3254 }
3255 };
3257 class VerifyObjsInRegionClosure: public ObjectClosure {
3258 private:
3259 G1CollectedHeap* _g1h;
3260 size_t _live_bytes;
3261 HeapRegion *_hr;
3262 VerifyOption _vo;
3263 public:
3264 // _vo == UsePrevMarking -> use "prev" marking information,
3265 // _vo == UseNextMarking -> use "next" marking information,
3266 // _vo == UseMarkWord -> use mark word from object header.
3267 VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo)
3268 : _live_bytes(0), _hr(hr), _vo(vo) {
3269 _g1h = G1CollectedHeap::heap();
3270 }
3271 void do_object(oop o) {
3272 VerifyLivenessOopClosure isLive(_g1h, _vo);
3273 assert(o != NULL, "Huh?");
3274 if (!_g1h->is_obj_dead_cond(o, _vo)) {
3275 // If the object is alive according to the mark word,
3276 // then verify that the marking information agrees.
3277 // Note we can't verify the contra-positive of the
3278 // above: if the object is dead (according to the mark
3279 // word), it may not be marked, or may have been marked
3280 // but has since became dead, or may have been allocated
3281 // since the last marking.
3282 if (_vo == VerifyOption_G1UseMarkWord) {
3283 guarantee(!_g1h->is_obj_dead(o), "mark word and concurrent mark mismatch");
3284 }
3286 o->oop_iterate_no_header(&isLive);
3287 if (!_hr->obj_allocated_since_prev_marking(o)) {
3288 size_t obj_size = o->size(); // Make sure we don't overflow
3289 _live_bytes += (obj_size * HeapWordSize);
3290 }
3291 }
3292 }
3293 size_t live_bytes() { return _live_bytes; }
3294 };
3296 class PrintObjsInRegionClosure : public ObjectClosure {
3297 HeapRegion *_hr;
3298 G1CollectedHeap *_g1;
3299 public:
3300 PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) {
3301 _g1 = G1CollectedHeap::heap();
3302 };
3304 void do_object(oop o) {
3305 if (o != NULL) {
3306 HeapWord *start = (HeapWord *) o;
3307 size_t word_sz = o->size();
3308 gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT
3309 " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",
3310 (void*) o, word_sz,
3311 _g1->isMarkedPrev(o),
3312 _g1->isMarkedNext(o),
3313 _hr->obj_allocated_since_prev_marking(o));
3314 HeapWord *end = start + word_sz;
3315 HeapWord *cur;
3316 int *val;
3317 for (cur = start; cur < end; cur++) {
3318 val = (int *) cur;
3319 gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val);
3320 }
3321 }
3322 }
3323 };
3325 class VerifyRegionClosure: public HeapRegionClosure {
3326 private:
3327 bool _par;
3328 VerifyOption _vo;
3329 bool _failures;
3330 public:
3331 // _vo == UsePrevMarking -> use "prev" marking information,
3332 // _vo == UseNextMarking -> use "next" marking information,
3333 // _vo == UseMarkWord -> use mark word from object header.
3334 VerifyRegionClosure(bool par, VerifyOption vo)
3335 : _par(par),
3336 _vo(vo),
3337 _failures(false) {}
3339 bool failures() {
3340 return _failures;
3341 }
3343 bool doHeapRegion(HeapRegion* r) {
3344 if (!r->continuesHumongous()) {
3345 bool failures = false;
3346 r->verify(_vo, &failures);
3347 if (failures) {
3348 _failures = true;
3349 } else {
3350 VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo);
3351 r->object_iterate(¬_dead_yet_cl);
3352 if (_vo != VerifyOption_G1UseNextMarking) {
3353 if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
3354 gclog_or_tty->print_cr("["PTR_FORMAT","PTR_FORMAT"] "
3355 "max_live_bytes "SIZE_FORMAT" "
3356 "< calculated "SIZE_FORMAT,
3357 r->bottom(), r->end(),
3358 r->max_live_bytes(),
3359 not_dead_yet_cl.live_bytes());
3360 _failures = true;
3361 }
3362 } else {
3363 // When vo == UseNextMarking we cannot currently do a sanity
3364 // check on the live bytes as the calculation has not been
3365 // finalized yet.
3366 }
3367 }
3368 }
3369 return false; // stop the region iteration if we hit a failure
3370 }
3371 };
3373 // This is the task used for parallel verification of the heap regions
3375 class G1ParVerifyTask: public AbstractGangTask {
3376 private:
3377 G1CollectedHeap* _g1h;
3378 VerifyOption _vo;
3379 bool _failures;
3381 public:
3382 // _vo == UsePrevMarking -> use "prev" marking information,
3383 // _vo == UseNextMarking -> use "next" marking information,
3384 // _vo == UseMarkWord -> use mark word from object header.
3385 G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) :
3386 AbstractGangTask("Parallel verify task"),
3387 _g1h(g1h),
3388 _vo(vo),
3389 _failures(false) { }
3391 bool failures() {
3392 return _failures;
3393 }
3395 void work(uint worker_id) {
3396 HandleMark hm;
3397 VerifyRegionClosure blk(true, _vo);
3398 _g1h->heap_region_par_iterate_chunked(&blk, worker_id,
3399 _g1h->workers()->active_workers(),
3400 HeapRegion::ParVerifyClaimValue);
3401 if (blk.failures()) {
3402 _failures = true;
3403 }
3404 }
3405 };
3407 void G1CollectedHeap::verify(bool silent, VerifyOption vo) {
3408 if (SafepointSynchronize::is_at_safepoint()) {
3409 assert(Thread::current()->is_VM_thread(),
3410 "Expected to be executed serially by the VM thread at this point");
3412 if (!silent) { gclog_or_tty->print("Roots "); }
3413 VerifyRootsClosure rootsCl(vo);
3414 G1VerifyCodeRootOopClosure codeRootsCl(this, &rootsCl, vo);
3415 G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl);
3416 VerifyKlassClosure klassCl(this, &rootsCl);
3418 // We apply the relevant closures to all the oops in the
3419 // system dictionary, the string table and the code cache.
3420 const int so = SO_AllClasses | SO_Strings | SO_CodeCache;
3422 // Need cleared claim bits for the strong roots processing
3423 ClassLoaderDataGraph::clear_claimed_marks();
3425 process_strong_roots(true, // activate StrongRootsScope
3426 false, // we set "is scavenging" to false,
3427 // so we don't reset the dirty cards.
3428 ScanningOption(so), // roots scanning options
3429 &rootsCl,
3430 &blobsCl,
3431 &klassCl
3432 );
3434 bool failures = rootsCl.failures() || codeRootsCl.failures();
3436 if (vo != VerifyOption_G1UseMarkWord) {
3437 // If we're verifying during a full GC then the region sets
3438 // will have been torn down at the start of the GC. Therefore
3439 // verifying the region sets will fail. So we only verify
3440 // the region sets when not in a full GC.
3441 if (!silent) { gclog_or_tty->print("HeapRegionSets "); }
3442 verify_region_sets();
3443 }
3445 if (!silent) { gclog_or_tty->print("HeapRegions "); }
3446 if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
3447 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3448 "sanity check");
3450 G1ParVerifyTask task(this, vo);
3451 assert(UseDynamicNumberOfGCThreads ||
3452 workers()->active_workers() == workers()->total_workers(),
3453 "If not dynamic should be using all the workers");
3454 int n_workers = workers()->active_workers();
3455 set_par_threads(n_workers);
3456 workers()->run_task(&task);
3457 set_par_threads(0);
3458 if (task.failures()) {
3459 failures = true;
3460 }
3462 // Checks that the expected amount of parallel work was done.
3463 // The implication is that n_workers is > 0.
3464 assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),
3465 "sanity check");
3467 reset_heap_region_claim_values();
3469 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3470 "sanity check");
3471 } else {
3472 VerifyRegionClosure blk(false, vo);
3473 heap_region_iterate(&blk);
3474 if (blk.failures()) {
3475 failures = true;
3476 }
3477 }
3478 if (!silent) gclog_or_tty->print("RemSet ");
3479 rem_set()->verify();
3481 if (G1StringDedup::is_enabled()) {
3482 if (!silent) gclog_or_tty->print("StrDedup ");
3483 G1StringDedup::verify();
3484 }
3486 if (failures) {
3487 gclog_or_tty->print_cr("Heap:");
3488 // It helps to have the per-region information in the output to
3489 // help us track down what went wrong. This is why we call
3490 // print_extended_on() instead of print_on().
3491 print_extended_on(gclog_or_tty);
3492 gclog_or_tty->print_cr("");
3493 #ifndef PRODUCT
3494 if (VerifyDuringGC && G1VerifyDuringGCPrintReachable) {
3495 concurrent_mark()->print_reachable("at-verification-failure",
3496 vo, false /* all */);
3497 }
3498 #endif
3499 gclog_or_tty->flush();
3500 }
3501 guarantee(!failures, "there should not have been any failures");
3502 } else {
3503 if (!silent) {
3504 gclog_or_tty->print("(SKIPPING Roots, HeapRegionSets, HeapRegions, RemSet");
3505 if (G1StringDedup::is_enabled()) {
3506 gclog_or_tty->print(", StrDedup");
3507 }
3508 gclog_or_tty->print(") ");
3509 }
3510 }
3511 }
3513 void G1CollectedHeap::verify(bool silent) {
3514 verify(silent, VerifyOption_G1UsePrevMarking);
3515 }
3517 double G1CollectedHeap::verify(bool guard, const char* msg) {
3518 double verify_time_ms = 0.0;
3520 if (guard && total_collections() >= VerifyGCStartAt) {
3521 double verify_start = os::elapsedTime();
3522 HandleMark hm; // Discard invalid handles created during verification
3523 prepare_for_verify();
3524 Universe::verify(VerifyOption_G1UsePrevMarking, msg);
3525 verify_time_ms = (os::elapsedTime() - verify_start) * 1000;
3526 }
3528 return verify_time_ms;
3529 }
3531 void G1CollectedHeap::verify_before_gc() {
3532 double verify_time_ms = verify(VerifyBeforeGC, " VerifyBeforeGC:");
3533 g1_policy()->phase_times()->record_verify_before_time_ms(verify_time_ms);
3534 }
3536 void G1CollectedHeap::verify_after_gc() {
3537 double verify_time_ms = verify(VerifyAfterGC, " VerifyAfterGC:");
3538 g1_policy()->phase_times()->record_verify_after_time_ms(verify_time_ms);
3539 }
3541 class PrintRegionClosure: public HeapRegionClosure {
3542 outputStream* _st;
3543 public:
3544 PrintRegionClosure(outputStream* st) : _st(st) {}
3545 bool doHeapRegion(HeapRegion* r) {
3546 r->print_on(_st);
3547 return false;
3548 }
3549 };
3551 void G1CollectedHeap::print_on(outputStream* st) const {
3552 st->print(" %-20s", "garbage-first heap");
3553 st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
3554 capacity()/K, used_unlocked()/K);
3555 st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")",
3556 _g1_storage.low_boundary(),
3557 _g1_storage.high(),
3558 _g1_storage.high_boundary());
3559 st->cr();
3560 st->print(" region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);
3561 uint young_regions = _young_list->length();
3562 st->print("%u young (" SIZE_FORMAT "K), ", young_regions,
3563 (size_t) young_regions * HeapRegion::GrainBytes / K);
3564 uint survivor_regions = g1_policy()->recorded_survivor_regions();
3565 st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,
3566 (size_t) survivor_regions * HeapRegion::GrainBytes / K);
3567 st->cr();
3568 MetaspaceAux::print_on(st);
3569 }
3571 void G1CollectedHeap::print_extended_on(outputStream* st) const {
3572 print_on(st);
3574 // Print the per-region information.
3575 st->cr();
3576 st->print_cr("Heap Regions: (Y=young(eden), SU=young(survivor), "
3577 "HS=humongous(starts), HC=humongous(continues), "
3578 "CS=collection set, F=free, TS=gc time stamp, "
3579 "PTAMS=previous top-at-mark-start, "
3580 "NTAMS=next top-at-mark-start)");
3581 PrintRegionClosure blk(st);
3582 heap_region_iterate(&blk);
3583 }
3585 void G1CollectedHeap::print_on_error(outputStream* st) const {
3586 this->CollectedHeap::print_on_error(st);
3588 if (_cm != NULL) {
3589 st->cr();
3590 _cm->print_on_error(st);
3591 }
3592 }
3594 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
3595 if (G1CollectedHeap::use_parallel_gc_threads()) {
3596 workers()->print_worker_threads_on(st);
3597 }
3598 _cmThread->print_on(st);
3599 st->cr();
3600 _cm->print_worker_threads_on(st);
3601 _cg1r->print_worker_threads_on(st);
3602 if (G1StringDedup::is_enabled()) {
3603 G1StringDedup::print_worker_threads_on(st);
3604 }
3605 }
3607 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
3608 if (G1CollectedHeap::use_parallel_gc_threads()) {
3609 workers()->threads_do(tc);
3610 }
3611 tc->do_thread(_cmThread);
3612 _cg1r->threads_do(tc);
3613 if (G1StringDedup::is_enabled()) {
3614 G1StringDedup::threads_do(tc);
3615 }
3616 }
3618 void G1CollectedHeap::print_tracing_info() const {
3619 // We'll overload this to mean "trace GC pause statistics."
3620 if (TraceGen0Time || TraceGen1Time) {
3621 // The "G1CollectorPolicy" is keeping track of these stats, so delegate
3622 // to that.
3623 g1_policy()->print_tracing_info();
3624 }
3625 if (G1SummarizeRSetStats) {
3626 g1_rem_set()->print_summary_info();
3627 }
3628 if (G1SummarizeConcMark) {
3629 concurrent_mark()->print_summary_info();
3630 }
3631 g1_policy()->print_yg_surv_rate_info();
3632 SpecializationStats::print();
3633 }
3635 #ifndef PRODUCT
3636 // Helpful for debugging RSet issues.
3638 class PrintRSetsClosure : public HeapRegionClosure {
3639 private:
3640 const char* _msg;
3641 size_t _occupied_sum;
3643 public:
3644 bool doHeapRegion(HeapRegion* r) {
3645 HeapRegionRemSet* hrrs = r->rem_set();
3646 size_t occupied = hrrs->occupied();
3647 _occupied_sum += occupied;
3649 gclog_or_tty->print_cr("Printing RSet for region "HR_FORMAT,
3650 HR_FORMAT_PARAMS(r));
3651 if (occupied == 0) {
3652 gclog_or_tty->print_cr(" RSet is empty");
3653 } else {
3654 hrrs->print();
3655 }
3656 gclog_or_tty->print_cr("----------");
3657 return false;
3658 }
3660 PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
3661 gclog_or_tty->cr();
3662 gclog_or_tty->print_cr("========================================");
3663 gclog_or_tty->print_cr(msg);
3664 gclog_or_tty->cr();
3665 }
3667 ~PrintRSetsClosure() {
3668 gclog_or_tty->print_cr("Occupied Sum: "SIZE_FORMAT, _occupied_sum);
3669 gclog_or_tty->print_cr("========================================");
3670 gclog_or_tty->cr();
3671 }
3672 };
3674 void G1CollectedHeap::print_cset_rsets() {
3675 PrintRSetsClosure cl("Printing CSet RSets");
3676 collection_set_iterate(&cl);
3677 }
3679 void G1CollectedHeap::print_all_rsets() {
3680 PrintRSetsClosure cl("Printing All RSets");;
3681 heap_region_iterate(&cl);
3682 }
3683 #endif // PRODUCT
3685 G1CollectedHeap* G1CollectedHeap::heap() {
3686 assert(_sh->kind() == CollectedHeap::G1CollectedHeap,
3687 "not a garbage-first heap");
3688 return _g1h;
3689 }
3691 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {
3692 // always_do_update_barrier = false;
3693 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
3694 // Fill TLAB's and such
3695 accumulate_statistics_all_tlabs();
3696 ensure_parsability(true);
3698 if (G1SummarizeRSetStats && (G1SummarizeRSetStatsPeriod > 0) &&
3699 (total_collections() % G1SummarizeRSetStatsPeriod == 0)) {
3700 g1_rem_set()->print_periodic_summary_info("Before GC RS summary");
3701 }
3702 }
3704 void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) {
3706 if (G1SummarizeRSetStats &&
3707 (G1SummarizeRSetStatsPeriod > 0) &&
3708 // we are at the end of the GC. Total collections has already been increased.
3709 ((total_collections() - 1) % G1SummarizeRSetStatsPeriod == 0)) {
3710 g1_rem_set()->print_periodic_summary_info("After GC RS summary");
3711 }
3713 // FIXME: what is this about?
3714 // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
3715 // is set.
3716 COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),
3717 "derived pointer present"));
3718 // always_do_update_barrier = true;
3720 resize_all_tlabs();
3722 // We have just completed a GC. Update the soft reference
3723 // policy with the new heap occupancy
3724 Universe::update_heap_info_at_gc();
3725 }
3727 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
3728 unsigned int gc_count_before,
3729 bool* succeeded,
3730 GCCause::Cause gc_cause) {
3731 assert_heap_not_locked_and_not_at_safepoint();
3732 g1_policy()->record_stop_world_start();
3733 VM_G1IncCollectionPause op(gc_count_before,
3734 word_size,
3735 false, /* should_initiate_conc_mark */
3736 g1_policy()->max_pause_time_ms(),
3737 gc_cause);
3738 VMThread::execute(&op);
3740 HeapWord* result = op.result();
3741 bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded();
3742 assert(result == NULL || ret_succeeded,
3743 "the result should be NULL if the VM did not succeed");
3744 *succeeded = ret_succeeded;
3746 assert_heap_not_locked();
3747 return result;
3748 }
3750 void
3751 G1CollectedHeap::doConcurrentMark() {
3752 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
3753 if (!_cmThread->in_progress()) {
3754 _cmThread->set_started();
3755 CGC_lock->notify();
3756 }
3757 }
3759 size_t G1CollectedHeap::pending_card_num() {
3760 size_t extra_cards = 0;
3761 JavaThread *curr = Threads::first();
3762 while (curr != NULL) {
3763 DirtyCardQueue& dcq = curr->dirty_card_queue();
3764 extra_cards += dcq.size();
3765 curr = curr->next();
3766 }
3767 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
3768 size_t buffer_size = dcqs.buffer_size();
3769 size_t buffer_num = dcqs.completed_buffers_num();
3771 // PtrQueueSet::buffer_size() and PtrQueue:size() return sizes
3772 // in bytes - not the number of 'entries'. We need to convert
3773 // into a number of cards.
3774 return (buffer_size * buffer_num + extra_cards) / oopSize;
3775 }
3777 size_t G1CollectedHeap::cards_scanned() {
3778 return g1_rem_set()->cardsScanned();
3779 }
3781 void
3782 G1CollectedHeap::setup_surviving_young_words() {
3783 assert(_surviving_young_words == NULL, "pre-condition");
3784 uint array_length = g1_policy()->young_cset_region_length();
3785 _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, (size_t) array_length, mtGC);
3786 if (_surviving_young_words == NULL) {
3787 vm_exit_out_of_memory(sizeof(size_t) * array_length, OOM_MALLOC_ERROR,
3788 "Not enough space for young surv words summary.");
3789 }
3790 memset(_surviving_young_words, 0, (size_t) array_length * sizeof(size_t));
3791 #ifdef ASSERT
3792 for (uint i = 0; i < array_length; ++i) {
3793 assert( _surviving_young_words[i] == 0, "memset above" );
3794 }
3795 #endif // !ASSERT
3796 }
3798 void
3799 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {
3800 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
3801 uint array_length = g1_policy()->young_cset_region_length();
3802 for (uint i = 0; i < array_length; ++i) {
3803 _surviving_young_words[i] += surv_young_words[i];
3804 }
3805 }
3807 void
3808 G1CollectedHeap::cleanup_surviving_young_words() {
3809 guarantee( _surviving_young_words != NULL, "pre-condition" );
3810 FREE_C_HEAP_ARRAY(size_t, _surviving_young_words, mtGC);
3811 _surviving_young_words = NULL;
3812 }
3814 #ifdef ASSERT
3815 class VerifyCSetClosure: public HeapRegionClosure {
3816 public:
3817 bool doHeapRegion(HeapRegion* hr) {
3818 // Here we check that the CSet region's RSet is ready for parallel
3819 // iteration. The fields that we'll verify are only manipulated
3820 // when the region is part of a CSet and is collected. Afterwards,
3821 // we reset these fields when we clear the region's RSet (when the
3822 // region is freed) so they are ready when the region is
3823 // re-allocated. The only exception to this is if there's an
3824 // evacuation failure and instead of freeing the region we leave
3825 // it in the heap. In that case, we reset these fields during
3826 // evacuation failure handling.
3827 guarantee(hr->rem_set()->verify_ready_for_par_iteration(), "verification");
3829 // Here's a good place to add any other checks we'd like to
3830 // perform on CSet regions.
3831 return false;
3832 }
3833 };
3834 #endif // ASSERT
3836 #if TASKQUEUE_STATS
3837 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
3838 st->print_raw_cr("GC Task Stats");
3839 st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
3840 st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
3841 }
3843 void G1CollectedHeap::print_taskqueue_stats(outputStream* const st) const {
3844 print_taskqueue_stats_hdr(st);
3846 TaskQueueStats totals;
3847 const int n = workers() != NULL ? workers()->total_workers() : 1;
3848 for (int i = 0; i < n; ++i) {
3849 st->print("%3d ", i); task_queue(i)->stats.print(st); st->cr();
3850 totals += task_queue(i)->stats;
3851 }
3852 st->print_raw("tot "); totals.print(st); st->cr();
3854 DEBUG_ONLY(totals.verify());
3855 }
3857 void G1CollectedHeap::reset_taskqueue_stats() {
3858 const int n = workers() != NULL ? workers()->total_workers() : 1;
3859 for (int i = 0; i < n; ++i) {
3860 task_queue(i)->stats.reset();
3861 }
3862 }
3863 #endif // TASKQUEUE_STATS
3865 void G1CollectedHeap::log_gc_header() {
3866 if (!G1Log::fine()) {
3867 return;
3868 }
3870 gclog_or_tty->date_stamp(PrintGCDateStamps);
3871 gclog_or_tty->stamp(PrintGCTimeStamps);
3873 GCCauseString gc_cause_str = GCCauseString("GC pause", gc_cause())
3874 .append(g1_policy()->gcs_are_young() ? "(young)" : "(mixed)")
3875 .append(g1_policy()->during_initial_mark_pause() ? " (initial-mark)" : "");
3877 gclog_or_tty->print("[%s", (const char*)gc_cause_str);
3878 }
3880 void G1CollectedHeap::log_gc_footer(double pause_time_sec) {
3881 if (!G1Log::fine()) {
3882 return;
3883 }
3885 if (G1Log::finer()) {
3886 if (evacuation_failed()) {
3887 gclog_or_tty->print(" (to-space exhausted)");
3888 }
3889 gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
3890 g1_policy()->phase_times()->note_gc_end();
3891 g1_policy()->phase_times()->print(pause_time_sec);
3892 g1_policy()->print_detailed_heap_transition();
3893 } else {
3894 if (evacuation_failed()) {
3895 gclog_or_tty->print("--");
3896 }
3897 g1_policy()->print_heap_transition();
3898 gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec);
3899 }
3900 gclog_or_tty->flush();
3901 }
3903 bool
3904 G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
3905 assert_at_safepoint(true /* should_be_vm_thread */);
3906 guarantee(!is_gc_active(), "collection is not reentrant");
3908 if (GC_locker::check_active_before_gc()) {
3909 return false;
3910 }
3912 _gc_timer_stw->register_gc_start();
3914 _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
3916 SvcGCMarker sgcm(SvcGCMarker::MINOR);
3917 ResourceMark rm;
3919 print_heap_before_gc();
3920 trace_heap_before_gc(_gc_tracer_stw);
3922 verify_region_sets_optional();
3923 verify_dirty_young_regions();
3925 // This call will decide whether this pause is an initial-mark
3926 // pause. If it is, during_initial_mark_pause() will return true
3927 // for the duration of this pause.
3928 g1_policy()->decide_on_conc_mark_initiation();
3930 // We do not allow initial-mark to be piggy-backed on a mixed GC.
3931 assert(!g1_policy()->during_initial_mark_pause() ||
3932 g1_policy()->gcs_are_young(), "sanity");
3934 // We also do not allow mixed GCs during marking.
3935 assert(!mark_in_progress() || g1_policy()->gcs_are_young(), "sanity");
3937 // Record whether this pause is an initial mark. When the current
3938 // thread has completed its logging output and it's safe to signal
3939 // the CM thread, the flag's value in the policy has been reset.
3940 bool should_start_conc_mark = g1_policy()->during_initial_mark_pause();
3942 // Inner scope for scope based logging, timers, and stats collection
3943 {
3944 EvacuationInfo evacuation_info;
3946 if (g1_policy()->during_initial_mark_pause()) {
3947 // We are about to start a marking cycle, so we increment the
3948 // full collection counter.
3949 increment_old_marking_cycles_started();
3950 register_concurrent_cycle_start(_gc_timer_stw->gc_start());
3951 }
3953 _gc_tracer_stw->report_yc_type(yc_type());
3955 TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
3957 int active_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
3958 workers()->active_workers() : 1);
3959 double pause_start_sec = os::elapsedTime();
3960 g1_policy()->phase_times()->note_gc_start(active_workers);
3961 log_gc_header();
3963 TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
3964 TraceMemoryManagerStats tms(false /* fullGC */, gc_cause());
3966 // If the secondary_free_list is not empty, append it to the
3967 // free_list. No need to wait for the cleanup operation to finish;
3968 // the region allocation code will check the secondary_free_list
3969 // and wait if necessary. If the G1StressConcRegionFreeing flag is
3970 // set, skip this step so that the region allocation code has to
3971 // get entries from the secondary_free_list.
3972 if (!G1StressConcRegionFreeing) {
3973 append_secondary_free_list_if_not_empty_with_lock();
3974 }
3976 assert(check_young_list_well_formed(), "young list should be well formed");
3977 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3978 "sanity check");
3980 // Don't dynamically change the number of GC threads this early. A value of
3981 // 0 is used to indicate serial work. When parallel work is done,
3982 // it will be set.
3984 { // Call to jvmpi::post_class_unload_events must occur outside of active GC
3985 IsGCActiveMark x;
3987 gc_prologue(false);
3988 increment_total_collections(false /* full gc */);
3989 increment_gc_time_stamp();
3991 verify_before_gc();
3993 COMPILER2_PRESENT(DerivedPointerTable::clear());
3995 // Please see comment in g1CollectedHeap.hpp and
3996 // G1CollectedHeap::ref_processing_init() to see how
3997 // reference processing currently works in G1.
3999 // Enable discovery in the STW reference processor
4000 ref_processor_stw()->enable_discovery(true /*verify_disabled*/,
4001 true /*verify_no_refs*/);
4003 {
4004 // We want to temporarily turn off discovery by the
4005 // CM ref processor, if necessary, and turn it back on
4006 // on again later if we do. Using a scoped
4007 // NoRefDiscovery object will do this.
4008 NoRefDiscovery no_cm_discovery(ref_processor_cm());
4010 // Forget the current alloc region (we might even choose it to be part
4011 // of the collection set!).
4012 release_mutator_alloc_region();
4014 // We should call this after we retire the mutator alloc
4015 // region(s) so that all the ALLOC / RETIRE events are generated
4016 // before the start GC event.
4017 _hr_printer.start_gc(false /* full */, (size_t) total_collections());
4019 // This timing is only used by the ergonomics to handle our pause target.
4020 // It is unclear why this should not include the full pause. We will
4021 // investigate this in CR 7178365.
4022 //
4023 // Preserving the old comment here if that helps the investigation:
4024 //
4025 // The elapsed time induced by the start time below deliberately elides
4026 // the possible verification above.
4027 double sample_start_time_sec = os::elapsedTime();
4029 #if YOUNG_LIST_VERBOSE
4030 gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:");
4031 _young_list->print();
4032 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4033 #endif // YOUNG_LIST_VERBOSE
4035 g1_policy()->record_collection_pause_start(sample_start_time_sec);
4037 double scan_wait_start = os::elapsedTime();
4038 // We have to wait until the CM threads finish scanning the
4039 // root regions as it's the only way to ensure that all the
4040 // objects on them have been correctly scanned before we start
4041 // moving them during the GC.
4042 bool waited = _cm->root_regions()->wait_until_scan_finished();
4043 double wait_time_ms = 0.0;
4044 if (waited) {
4045 double scan_wait_end = os::elapsedTime();
4046 wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;
4047 }
4048 g1_policy()->phase_times()->record_root_region_scan_wait_time(wait_time_ms);
4050 #if YOUNG_LIST_VERBOSE
4051 gclog_or_tty->print_cr("\nAfter recording pause start.\nYoung_list:");
4052 _young_list->print();
4053 #endif // YOUNG_LIST_VERBOSE
4055 if (g1_policy()->during_initial_mark_pause()) {
4056 concurrent_mark()->checkpointRootsInitialPre();
4057 }
4059 #if YOUNG_LIST_VERBOSE
4060 gclog_or_tty->print_cr("\nBefore choosing collection set.\nYoung_list:");
4061 _young_list->print();
4062 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4063 #endif // YOUNG_LIST_VERBOSE
4065 g1_policy()->finalize_cset(target_pause_time_ms, evacuation_info);
4067 _cm->note_start_of_gc();
4068 // We should not verify the per-thread SATB buffers given that
4069 // we have not filtered them yet (we'll do so during the
4070 // GC). We also call this after finalize_cset() to
4071 // ensure that the CSet has been finalized.
4072 _cm->verify_no_cset_oops(true /* verify_stacks */,
4073 true /* verify_enqueued_buffers */,
4074 false /* verify_thread_buffers */,
4075 true /* verify_fingers */);
4077 if (_hr_printer.is_active()) {
4078 HeapRegion* hr = g1_policy()->collection_set();
4079 while (hr != NULL) {
4080 G1HRPrinter::RegionType type;
4081 if (!hr->is_young()) {
4082 type = G1HRPrinter::Old;
4083 } else if (hr->is_survivor()) {
4084 type = G1HRPrinter::Survivor;
4085 } else {
4086 type = G1HRPrinter::Eden;
4087 }
4088 _hr_printer.cset(hr);
4089 hr = hr->next_in_collection_set();
4090 }
4091 }
4093 #ifdef ASSERT
4094 VerifyCSetClosure cl;
4095 collection_set_iterate(&cl);
4096 #endif // ASSERT
4098 setup_surviving_young_words();
4100 // Initialize the GC alloc regions.
4101 init_gc_alloc_regions(evacuation_info);
4103 // Actually do the work...
4104 evacuate_collection_set(evacuation_info);
4106 // We do this to mainly verify the per-thread SATB buffers
4107 // (which have been filtered by now) since we didn't verify
4108 // them earlier. No point in re-checking the stacks / enqueued
4109 // buffers given that the CSet has not changed since last time
4110 // we checked.
4111 _cm->verify_no_cset_oops(false /* verify_stacks */,
4112 false /* verify_enqueued_buffers */,
4113 true /* verify_thread_buffers */,
4114 true /* verify_fingers */);
4116 free_collection_set(g1_policy()->collection_set(), evacuation_info);
4117 g1_policy()->clear_collection_set();
4119 cleanup_surviving_young_words();
4121 // Start a new incremental collection set for the next pause.
4122 g1_policy()->start_incremental_cset_building();
4124 // Clear the _cset_fast_test bitmap in anticipation of adding
4125 // regions to the incremental collection set for the next
4126 // evacuation pause.
4127 clear_cset_fast_test();
4129 _young_list->reset_sampled_info();
4131 // Don't check the whole heap at this point as the
4132 // GC alloc regions from this pause have been tagged
4133 // as survivors and moved on to the survivor list.
4134 // Survivor regions will fail the !is_young() check.
4135 assert(check_young_list_empty(false /* check_heap */),
4136 "young list should be empty");
4138 #if YOUNG_LIST_VERBOSE
4139 gclog_or_tty->print_cr("Before recording survivors.\nYoung List:");
4140 _young_list->print();
4141 #endif // YOUNG_LIST_VERBOSE
4143 g1_policy()->record_survivor_regions(_young_list->survivor_length(),
4144 _young_list->first_survivor_region(),
4145 _young_list->last_survivor_region());
4147 _young_list->reset_auxilary_lists();
4149 if (evacuation_failed()) {
4150 _summary_bytes_used = recalculate_used();
4151 uint n_queues = MAX2((int)ParallelGCThreads, 1);
4152 for (uint i = 0; i < n_queues; i++) {
4153 if (_evacuation_failed_info_array[i].has_failed()) {
4154 _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
4155 }
4156 }
4157 } else {
4158 // The "used" of the the collection set have already been subtracted
4159 // when they were freed. Add in the bytes evacuated.
4160 _summary_bytes_used += g1_policy()->bytes_copied_during_gc();
4161 }
4163 if (g1_policy()->during_initial_mark_pause()) {
4164 // We have to do this before we notify the CM threads that
4165 // they can start working to make sure that all the
4166 // appropriate initialization is done on the CM object.
4167 concurrent_mark()->checkpointRootsInitialPost();
4168 set_marking_started();
4169 // Note that we don't actually trigger the CM thread at
4170 // this point. We do that later when we're sure that
4171 // the current thread has completed its logging output.
4172 }
4174 allocate_dummy_regions();
4176 #if YOUNG_LIST_VERBOSE
4177 gclog_or_tty->print_cr("\nEnd of the pause.\nYoung_list:");
4178 _young_list->print();
4179 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
4180 #endif // YOUNG_LIST_VERBOSE
4182 init_mutator_alloc_region();
4184 {
4185 size_t expand_bytes = g1_policy()->expansion_amount();
4186 if (expand_bytes > 0) {
4187 size_t bytes_before = capacity();
4188 // No need for an ergo verbose message here,
4189 // expansion_amount() does this when it returns a value > 0.
4190 if (!expand(expand_bytes)) {
4191 // We failed to expand the heap so let's verify that
4192 // committed/uncommitted amount match the backing store
4193 assert(capacity() == _g1_storage.committed_size(), "committed size mismatch");
4194 assert(max_capacity() == _g1_storage.reserved_size(), "reserved size mismatch");
4195 }
4196 }
4197 }
4199 // We redo the verification but now wrt to the new CSet which
4200 // has just got initialized after the previous CSet was freed.
4201 _cm->verify_no_cset_oops(true /* verify_stacks */,
4202 true /* verify_enqueued_buffers */,
4203 true /* verify_thread_buffers */,
4204 true /* verify_fingers */);
4205 _cm->note_end_of_gc();
4207 // This timing is only used by the ergonomics to handle our pause target.
4208 // It is unclear why this should not include the full pause. We will
4209 // investigate this in CR 7178365.
4210 double sample_end_time_sec = os::elapsedTime();
4211 double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
4212 g1_policy()->record_collection_pause_end(pause_time_ms, evacuation_info);
4214 MemoryService::track_memory_usage();
4216 // In prepare_for_verify() below we'll need to scan the deferred
4217 // update buffers to bring the RSets up-to-date if
4218 // G1HRRSFlushLogBuffersOnVerify has been set. While scanning
4219 // the update buffers we'll probably need to scan cards on the
4220 // regions we just allocated to (i.e., the GC alloc
4221 // regions). However, during the last GC we called
4222 // set_saved_mark() on all the GC alloc regions, so card
4223 // scanning might skip the [saved_mark_word()...top()] area of
4224 // those regions (i.e., the area we allocated objects into
4225 // during the last GC). But it shouldn't. Given that
4226 // saved_mark_word() is conditional on whether the GC time stamp
4227 // on the region is current or not, by incrementing the GC time
4228 // stamp here we invalidate all the GC time stamps on all the
4229 // regions and saved_mark_word() will simply return top() for
4230 // all the regions. This is a nicer way of ensuring this rather
4231 // than iterating over the regions and fixing them. In fact, the
4232 // GC time stamp increment here also ensures that
4233 // saved_mark_word() will return top() between pauses, i.e.,
4234 // during concurrent refinement. So we don't need the
4235 // is_gc_active() check to decided which top to use when
4236 // scanning cards (see CR 7039627).
4237 increment_gc_time_stamp();
4239 verify_after_gc();
4241 assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
4242 ref_processor_stw()->verify_no_references_recorded();
4244 // CM reference discovery will be re-enabled if necessary.
4245 }
4247 // We should do this after we potentially expand the heap so
4248 // that all the COMMIT events are generated before the end GC
4249 // event, and after we retire the GC alloc regions so that all
4250 // RETIRE events are generated before the end GC event.
4251 _hr_printer.end_gc(false /* full */, (size_t) total_collections());
4253 if (mark_in_progress()) {
4254 concurrent_mark()->update_g1_committed();
4255 }
4257 #ifdef TRACESPINNING
4258 ParallelTaskTerminator::print_termination_counts();
4259 #endif
4261 gc_epilogue(false);
4262 }
4264 // Print the remainder of the GC log output.
4265 log_gc_footer(os::elapsedTime() - pause_start_sec);
4267 // It is not yet to safe to tell the concurrent mark to
4268 // start as we have some optional output below. We don't want the
4269 // output from the concurrent mark thread interfering with this
4270 // logging output either.
4272 _hrs.verify_optional();
4273 verify_region_sets_optional();
4275 TASKQUEUE_STATS_ONLY(if (ParallelGCVerbose) print_taskqueue_stats());
4276 TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
4278 print_heap_after_gc();
4279 trace_heap_after_gc(_gc_tracer_stw);
4281 // We must call G1MonitoringSupport::update_sizes() in the same scoping level
4282 // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
4283 // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
4284 // before any GC notifications are raised.
4285 g1mm()->update_sizes();
4287 _gc_tracer_stw->report_evacuation_info(&evacuation_info);
4288 _gc_tracer_stw->report_tenuring_threshold(_g1_policy->tenuring_threshold());
4289 _gc_timer_stw->register_gc_end();
4290 _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(), _gc_timer_stw->time_partitions());
4291 }
4292 // It should now be safe to tell the concurrent mark thread to start
4293 // without its logging output interfering with the logging output
4294 // that came from the pause.
4296 if (should_start_conc_mark) {
4297 // CAUTION: after the doConcurrentMark() call below,
4298 // the concurrent marking thread(s) could be running
4299 // concurrently with us. Make sure that anything after
4300 // this point does not assume that we are the only GC thread
4301 // running. Note: of course, the actual marking work will
4302 // not start until the safepoint itself is released in
4303 // ConcurrentGCThread::safepoint_desynchronize().
4304 doConcurrentMark();
4305 }
4307 return true;
4308 }
4310 size_t G1CollectedHeap::desired_plab_sz(GCAllocPurpose purpose)
4311 {
4312 size_t gclab_word_size;
4313 switch (purpose) {
4314 case GCAllocForSurvived:
4315 gclab_word_size = _survivor_plab_stats.desired_plab_sz();
4316 break;
4317 case GCAllocForTenured:
4318 gclab_word_size = _old_plab_stats.desired_plab_sz();
4319 break;
4320 default:
4321 assert(false, "unknown GCAllocPurpose");
4322 gclab_word_size = _old_plab_stats.desired_plab_sz();
4323 break;
4324 }
4326 // Prevent humongous PLAB sizes for two reasons:
4327 // * PLABs are allocated using a similar paths as oops, but should
4328 // never be in a humongous region
4329 // * Allowing humongous PLABs needlessly churns the region free lists
4330 return MIN2(_humongous_object_threshold_in_words, gclab_word_size);
4331 }
4333 void G1CollectedHeap::init_mutator_alloc_region() {
4334 assert(_mutator_alloc_region.get() == NULL, "pre-condition");
4335 _mutator_alloc_region.init();
4336 }
4338 void G1CollectedHeap::release_mutator_alloc_region() {
4339 _mutator_alloc_region.release();
4340 assert(_mutator_alloc_region.get() == NULL, "post-condition");
4341 }
4343 void G1CollectedHeap::init_gc_alloc_regions(EvacuationInfo& evacuation_info) {
4344 assert_at_safepoint(true /* should_be_vm_thread */);
4346 _survivor_gc_alloc_region.init();
4347 _old_gc_alloc_region.init();
4348 HeapRegion* retained_region = _retained_old_gc_alloc_region;
4349 _retained_old_gc_alloc_region = NULL;
4351 // We will discard the current GC alloc region if:
4352 // a) it's in the collection set (it can happen!),
4353 // b) it's already full (no point in using it),
4354 // c) it's empty (this means that it was emptied during
4355 // a cleanup and it should be on the free list now), or
4356 // d) it's humongous (this means that it was emptied
4357 // during a cleanup and was added to the free list, but
4358 // has been subsequently used to allocate a humongous
4359 // object that may be less than the region size).
4360 if (retained_region != NULL &&
4361 !retained_region->in_collection_set() &&
4362 !(retained_region->top() == retained_region->end()) &&
4363 !retained_region->is_empty() &&
4364 !retained_region->isHumongous()) {
4365 retained_region->set_saved_mark();
4366 // The retained region was added to the old region set when it was
4367 // retired. We have to remove it now, since we don't allow regions
4368 // we allocate to in the region sets. We'll re-add it later, when
4369 // it's retired again.
4370 _old_set.remove(retained_region);
4371 bool during_im = g1_policy()->during_initial_mark_pause();
4372 retained_region->note_start_of_copying(during_im);
4373 _old_gc_alloc_region.set(retained_region);
4374 _hr_printer.reuse(retained_region);
4375 evacuation_info.set_alloc_regions_used_before(retained_region->used());
4376 }
4377 }
4379 void G1CollectedHeap::release_gc_alloc_regions(uint no_of_gc_workers, EvacuationInfo& evacuation_info) {
4380 evacuation_info.set_allocation_regions(_survivor_gc_alloc_region.count() +
4381 _old_gc_alloc_region.count());
4382 _survivor_gc_alloc_region.release();
4383 // If we have an old GC alloc region to release, we'll save it in
4384 // _retained_old_gc_alloc_region. If we don't
4385 // _retained_old_gc_alloc_region will become NULL. This is what we
4386 // want either way so no reason to check explicitly for either
4387 // condition.
4388 _retained_old_gc_alloc_region = _old_gc_alloc_region.release();
4390 if (ResizePLAB) {
4391 _survivor_plab_stats.adjust_desired_plab_sz(no_of_gc_workers);
4392 _old_plab_stats.adjust_desired_plab_sz(no_of_gc_workers);
4393 }
4394 }
4396 void G1CollectedHeap::abandon_gc_alloc_regions() {
4397 assert(_survivor_gc_alloc_region.get() == NULL, "pre-condition");
4398 assert(_old_gc_alloc_region.get() == NULL, "pre-condition");
4399 _retained_old_gc_alloc_region = NULL;
4400 }
4402 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {
4403 _drain_in_progress = false;
4404 set_evac_failure_closure(cl);
4405 _evac_failure_scan_stack = new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(40, true);
4406 }
4408 void G1CollectedHeap::finalize_for_evac_failure() {
4409 assert(_evac_failure_scan_stack != NULL &&
4410 _evac_failure_scan_stack->length() == 0,
4411 "Postcondition");
4412 assert(!_drain_in_progress, "Postcondition");
4413 delete _evac_failure_scan_stack;
4414 _evac_failure_scan_stack = NULL;
4415 }
4417 void G1CollectedHeap::remove_self_forwarding_pointers() {
4418 assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
4420 double remove_self_forwards_start = os::elapsedTime();
4422 G1ParRemoveSelfForwardPtrsTask rsfp_task(this);
4424 if (G1CollectedHeap::use_parallel_gc_threads()) {
4425 set_par_threads();
4426 workers()->run_task(&rsfp_task);
4427 set_par_threads(0);
4428 } else {
4429 rsfp_task.work(0);
4430 }
4432 assert(check_cset_heap_region_claim_values(HeapRegion::ParEvacFailureClaimValue), "sanity");
4434 // Reset the claim values in the regions in the collection set.
4435 reset_cset_heap_region_claim_values();
4437 assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
4439 // Now restore saved marks, if any.
4440 assert(_objs_with_preserved_marks.size() ==
4441 _preserved_marks_of_objs.size(), "Both or none.");
4442 while (!_objs_with_preserved_marks.is_empty()) {
4443 oop obj = _objs_with_preserved_marks.pop();
4444 markOop m = _preserved_marks_of_objs.pop();
4445 obj->set_mark(m);
4446 }
4447 _objs_with_preserved_marks.clear(true);
4448 _preserved_marks_of_objs.clear(true);
4450 g1_policy()->phase_times()->record_evac_fail_remove_self_forwards((os::elapsedTime() - remove_self_forwards_start) * 1000.0);
4451 }
4453 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {
4454 _evac_failure_scan_stack->push(obj);
4455 }
4457 void G1CollectedHeap::drain_evac_failure_scan_stack() {
4458 assert(_evac_failure_scan_stack != NULL, "precondition");
4460 while (_evac_failure_scan_stack->length() > 0) {
4461 oop obj = _evac_failure_scan_stack->pop();
4462 _evac_failure_closure->set_region(heap_region_containing(obj));
4463 obj->oop_iterate_backwards(_evac_failure_closure);
4464 }
4465 }
4467 oop
4468 G1CollectedHeap::handle_evacuation_failure_par(G1ParScanThreadState* _par_scan_state,
4469 oop old) {
4470 assert(obj_in_cs(old),
4471 err_msg("obj: "PTR_FORMAT" should still be in the CSet",
4472 (HeapWord*) old));
4473 markOop m = old->mark();
4474 oop forward_ptr = old->forward_to_atomic(old);
4475 if (forward_ptr == NULL) {
4476 // Forward-to-self succeeded.
4477 assert(_par_scan_state != NULL, "par scan state");
4478 OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure();
4479 uint queue_num = _par_scan_state->queue_num();
4481 _evacuation_failed = true;
4482 _evacuation_failed_info_array[queue_num].register_copy_failure(old->size());
4483 if (_evac_failure_closure != cl) {
4484 MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag);
4485 assert(!_drain_in_progress,
4486 "Should only be true while someone holds the lock.");
4487 // Set the global evac-failure closure to the current thread's.
4488 assert(_evac_failure_closure == NULL, "Or locking has failed.");
4489 set_evac_failure_closure(cl);
4490 // Now do the common part.
4491 handle_evacuation_failure_common(old, m);
4492 // Reset to NULL.
4493 set_evac_failure_closure(NULL);
4494 } else {
4495 // The lock is already held, and this is recursive.
4496 assert(_drain_in_progress, "This should only be the recursive case.");
4497 handle_evacuation_failure_common(old, m);
4498 }
4499 return old;
4500 } else {
4501 // Forward-to-self failed. Either someone else managed to allocate
4502 // space for this object (old != forward_ptr) or they beat us in
4503 // self-forwarding it (old == forward_ptr).
4504 assert(old == forward_ptr || !obj_in_cs(forward_ptr),
4505 err_msg("obj: "PTR_FORMAT" forwarded to: "PTR_FORMAT" "
4506 "should not be in the CSet",
4507 (HeapWord*) old, (HeapWord*) forward_ptr));
4508 return forward_ptr;
4509 }
4510 }
4512 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) {
4513 preserve_mark_if_necessary(old, m);
4515 HeapRegion* r = heap_region_containing(old);
4516 if (!r->evacuation_failed()) {
4517 r->set_evacuation_failed(true);
4518 _hr_printer.evac_failure(r);
4519 }
4521 push_on_evac_failure_scan_stack(old);
4523 if (!_drain_in_progress) {
4524 // prevent recursion in copy_to_survivor_space()
4525 _drain_in_progress = true;
4526 drain_evac_failure_scan_stack();
4527 _drain_in_progress = false;
4528 }
4529 }
4531 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) {
4532 assert(evacuation_failed(), "Oversaving!");
4533 // We want to call the "for_promotion_failure" version only in the
4534 // case of a promotion failure.
4535 if (m->must_be_preserved_for_promotion_failure(obj)) {
4536 _objs_with_preserved_marks.push(obj);
4537 _preserved_marks_of_objs.push(m);
4538 }
4539 }
4541 HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose,
4542 size_t word_size) {
4543 if (purpose == GCAllocForSurvived) {
4544 HeapWord* result = survivor_attempt_allocation(word_size);
4545 if (result != NULL) {
4546 return result;
4547 } else {
4548 // Let's try to allocate in the old gen in case we can fit the
4549 // object there.
4550 return old_attempt_allocation(word_size);
4551 }
4552 } else {
4553 assert(purpose == GCAllocForTenured, "sanity");
4554 HeapWord* result = old_attempt_allocation(word_size);
4555 if (result != NULL) {
4556 return result;
4557 } else {
4558 // Let's try to allocate in the survivors in case we can fit the
4559 // object there.
4560 return survivor_attempt_allocation(word_size);
4561 }
4562 }
4564 ShouldNotReachHere();
4565 // Trying to keep some compilers happy.
4566 return NULL;
4567 }
4569 G1ParGCAllocBuffer::G1ParGCAllocBuffer(size_t gclab_word_size) :
4570 ParGCAllocBuffer(gclab_word_size), _retired(false) { }
4572 G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h, uint queue_num, ReferenceProcessor* rp)
4573 : _g1h(g1h),
4574 _refs(g1h->task_queue(queue_num)),
4575 _dcq(&g1h->dirty_card_queue_set()),
4576 _ct_bs(g1h->g1_barrier_set()),
4577 _g1_rem(g1h->g1_rem_set()),
4578 _hash_seed(17), _queue_num(queue_num),
4579 _term_attempts(0),
4580 _surviving_alloc_buffer(g1h->desired_plab_sz(GCAllocForSurvived)),
4581 _tenured_alloc_buffer(g1h->desired_plab_sz(GCAllocForTenured)),
4582 _age_table(false), _scanner(g1h, this, rp),
4583 _strong_roots_time(0), _term_time(0),
4584 _alloc_buffer_waste(0), _undo_waste(0) {
4585 // we allocate G1YoungSurvRateNumRegions plus one entries, since
4586 // we "sacrifice" entry 0 to keep track of surviving bytes for
4587 // non-young regions (where the age is -1)
4588 // We also add a few elements at the beginning and at the end in
4589 // an attempt to eliminate cache contention
4590 uint real_length = 1 + _g1h->g1_policy()->young_cset_region_length();
4591 uint array_length = PADDING_ELEM_NUM +
4592 real_length +
4593 PADDING_ELEM_NUM;
4594 _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length, mtGC);
4595 if (_surviving_young_words_base == NULL)
4596 vm_exit_out_of_memory(array_length * sizeof(size_t), OOM_MALLOC_ERROR,
4597 "Not enough space for young surv histo.");
4598 _surviving_young_words = _surviving_young_words_base + PADDING_ELEM_NUM;
4599 memset(_surviving_young_words, 0, (size_t) real_length * sizeof(size_t));
4601 _alloc_buffers[GCAllocForSurvived] = &_surviving_alloc_buffer;
4602 _alloc_buffers[GCAllocForTenured] = &_tenured_alloc_buffer;
4604 _start = os::elapsedTime();
4605 }
4607 void
4608 G1ParScanThreadState::print_termination_stats_hdr(outputStream* const st)
4609 {
4610 st->print_raw_cr("GC Termination Stats");
4611 st->print_raw_cr(" elapsed --strong roots-- -------termination-------"
4612 " ------waste (KiB)------");
4613 st->print_raw_cr("thr ms ms % ms % attempts"
4614 " total alloc undo");
4615 st->print_raw_cr("--- --------- --------- ------ --------- ------ --------"
4616 " ------- ------- -------");
4617 }
4619 void
4620 G1ParScanThreadState::print_termination_stats(int i,
4621 outputStream* const st) const
4622 {
4623 const double elapsed_ms = elapsed_time() * 1000.0;
4624 const double s_roots_ms = strong_roots_time() * 1000.0;
4625 const double term_ms = term_time() * 1000.0;
4626 st->print_cr("%3d %9.2f %9.2f %6.2f "
4627 "%9.2f %6.2f " SIZE_FORMAT_W(8) " "
4628 SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7),
4629 i, elapsed_ms, s_roots_ms, s_roots_ms * 100 / elapsed_ms,
4630 term_ms, term_ms * 100 / elapsed_ms, term_attempts(),
4631 (alloc_buffer_waste() + undo_waste()) * HeapWordSize / K,
4632 alloc_buffer_waste() * HeapWordSize / K,
4633 undo_waste() * HeapWordSize / K);
4634 }
4636 #ifdef ASSERT
4637 bool G1ParScanThreadState::verify_ref(narrowOop* ref) const {
4638 assert(ref != NULL, "invariant");
4639 assert(UseCompressedOops, "sanity");
4640 assert(!has_partial_array_mask(ref), err_msg("ref=" PTR_FORMAT, ref));
4641 oop p = oopDesc::load_decode_heap_oop(ref);
4642 assert(_g1h->is_in_g1_reserved(p),
4643 err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, (void *)p));
4644 return true;
4645 }
4647 bool G1ParScanThreadState::verify_ref(oop* ref) const {
4648 assert(ref != NULL, "invariant");
4649 if (has_partial_array_mask(ref)) {
4650 // Must be in the collection set--it's already been copied.
4651 oop p = clear_partial_array_mask(ref);
4652 assert(_g1h->obj_in_cs(p),
4653 err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, (void *)p));
4654 } else {
4655 oop p = oopDesc::load_decode_heap_oop(ref);
4656 assert(_g1h->is_in_g1_reserved(p),
4657 err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, (void *)p));
4658 }
4659 return true;
4660 }
4662 bool G1ParScanThreadState::verify_task(StarTask ref) const {
4663 if (ref.is_narrow()) {
4664 return verify_ref((narrowOop*) ref);
4665 } else {
4666 return verify_ref((oop*) ref);
4667 }
4668 }
4669 #endif // ASSERT
4671 void G1ParScanThreadState::trim_queue() {
4672 assert(_evac_failure_cl != NULL, "not set");
4674 StarTask ref;
4675 do {
4676 // Drain the overflow stack first, so other threads can steal.
4677 while (refs()->pop_overflow(ref)) {
4678 deal_with_reference(ref);
4679 }
4681 while (refs()->pop_local(ref)) {
4682 deal_with_reference(ref);
4683 }
4684 } while (!refs()->is_empty());
4685 }
4687 G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1,
4688 G1ParScanThreadState* par_scan_state) :
4689 _g1(g1), _par_scan_state(par_scan_state),
4690 _worker_id(par_scan_state->queue_num()) { }
4692 void G1ParCopyHelper::mark_object(oop obj) {
4693 #ifdef ASSERT
4694 HeapRegion* hr = _g1->heap_region_containing(obj);
4695 assert(hr != NULL, "sanity");
4696 assert(!hr->in_collection_set(), "should not mark objects in the CSet");
4697 #endif // ASSERT
4699 // We know that the object is not moving so it's safe to read its size.
4700 _cm->grayRoot(obj, (size_t) obj->size(), _worker_id);
4701 }
4703 void G1ParCopyHelper::mark_forwarded_object(oop from_obj, oop to_obj) {
4704 #ifdef ASSERT
4705 assert(from_obj->is_forwarded(), "from obj should be forwarded");
4706 assert(from_obj->forwardee() == to_obj, "to obj should be the forwardee");
4707 assert(from_obj != to_obj, "should not be self-forwarded");
4709 HeapRegion* from_hr = _g1->heap_region_containing(from_obj);
4710 assert(from_hr != NULL, "sanity");
4711 assert(from_hr->in_collection_set(), "from obj should be in the CSet");
4713 HeapRegion* to_hr = _g1->heap_region_containing(to_obj);
4714 assert(to_hr != NULL, "sanity");
4715 assert(!to_hr->in_collection_set(), "should not mark objects in the CSet");
4716 #endif // ASSERT
4718 // The object might be in the process of being copied by another
4719 // worker so we cannot trust that its to-space image is
4720 // well-formed. So we have to read its size from its from-space
4721 // image which we know should not be changing.
4722 _cm->grayRoot(to_obj, (size_t) from_obj->size(), _worker_id);
4723 }
4725 oop G1ParScanThreadState::copy_to_survivor_space(oop const old) {
4726 size_t word_sz = old->size();
4727 HeapRegion* from_region = _g1h->heap_region_containing_raw(old);
4728 // +1 to make the -1 indexes valid...
4729 int young_index = from_region->young_index_in_cset()+1;
4730 assert( (from_region->is_young() && young_index > 0) ||
4731 (!from_region->is_young() && young_index == 0), "invariant" );
4732 G1CollectorPolicy* g1p = _g1h->g1_policy();
4733 markOop m = old->mark();
4734 int age = m->has_displaced_mark_helper() ? m->displaced_mark_helper()->age()
4735 : m->age();
4736 GCAllocPurpose alloc_purpose = g1p->evacuation_destination(from_region, age,
4737 word_sz);
4738 HeapWord* obj_ptr = allocate(alloc_purpose, word_sz);
4739 #ifndef PRODUCT
4740 // Should this evacuation fail?
4741 if (_g1h->evacuation_should_fail()) {
4742 if (obj_ptr != NULL) {
4743 undo_allocation(alloc_purpose, obj_ptr, word_sz);
4744 obj_ptr = NULL;
4745 }
4746 }
4747 #endif // !PRODUCT
4749 if (obj_ptr == NULL) {
4750 // This will either forward-to-self, or detect that someone else has
4751 // installed a forwarding pointer.
4752 return _g1h->handle_evacuation_failure_par(this, old);
4753 }
4755 oop obj = oop(obj_ptr);
4757 // We're going to allocate linearly, so might as well prefetch ahead.
4758 Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
4760 oop forward_ptr = old->forward_to_atomic(obj);
4761 if (forward_ptr == NULL) {
4762 Copy::aligned_disjoint_words((HeapWord*) old, obj_ptr, word_sz);
4764 // alloc_purpose is just a hint to allocate() above, recheck the type of region
4765 // we actually allocated from and update alloc_purpose accordingly
4766 HeapRegion* to_region = _g1h->heap_region_containing_raw(obj_ptr);
4767 alloc_purpose = to_region->is_young() ? GCAllocForSurvived : GCAllocForTenured;
4769 if (g1p->track_object_age(alloc_purpose)) {
4770 // We could simply do obj->incr_age(). However, this causes a
4771 // performance issue. obj->incr_age() will first check whether
4772 // the object has a displaced mark by checking its mark word;
4773 // getting the mark word from the new location of the object
4774 // stalls. So, given that we already have the mark word and we
4775 // are about to install it anyway, it's better to increase the
4776 // age on the mark word, when the object does not have a
4777 // displaced mark word. We're not expecting many objects to have
4778 // a displaced marked word, so that case is not optimized
4779 // further (it could be...) and we simply call obj->incr_age().
4781 if (m->has_displaced_mark_helper()) {
4782 // in this case, we have to install the mark word first,
4783 // otherwise obj looks to be forwarded (the old mark word,
4784 // which contains the forward pointer, was copied)
4785 obj->set_mark(m);
4786 obj->incr_age();
4787 } else {
4788 m = m->incr_age();
4789 obj->set_mark(m);
4790 }
4791 age_table()->add(obj, word_sz);
4792 } else {
4793 obj->set_mark(m);
4794 }
4796 if (G1StringDedup::is_enabled()) {
4797 G1StringDedup::enqueue_from_evacuation(from_region->is_young(),
4798 to_region->is_young(),
4799 queue_num(),
4800 obj);
4801 }
4803 size_t* surv_young_words = surviving_young_words();
4804 surv_young_words[young_index] += word_sz;
4806 if (obj->is_objArray() && arrayOop(obj)->length() >= ParGCArrayScanChunk) {
4807 // We keep track of the next start index in the length field of
4808 // the to-space object. The actual length can be found in the
4809 // length field of the from-space object.
4810 arrayOop(obj)->set_length(0);
4811 oop* old_p = set_partial_array_mask(old);
4812 push_on_queue(old_p);
4813 } else {
4814 // No point in using the slower heap_region_containing() method,
4815 // given that we know obj is in the heap.
4816 _scanner.set_region(_g1h->heap_region_containing_raw(obj));
4817 obj->oop_iterate_backwards(&_scanner);
4818 }
4819 } else {
4820 undo_allocation(alloc_purpose, obj_ptr, word_sz);
4821 obj = forward_ptr;
4822 }
4823 return obj;
4824 }
4826 template <class T>
4827 void G1ParCopyHelper::do_klass_barrier(T* p, oop new_obj) {
4828 if (_g1->heap_region_containing_raw(new_obj)->is_young()) {
4829 _scanned_klass->record_modified_oops();
4830 }
4831 }
4833 template <G1Barrier barrier, bool do_mark_object>
4834 template <class T>
4835 void G1ParCopyClosure<barrier, do_mark_object>::do_oop_work(T* p) {
4836 T heap_oop = oopDesc::load_heap_oop(p);
4838 if (oopDesc::is_null(heap_oop)) {
4839 return;
4840 }
4842 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
4844 assert(_worker_id == _par_scan_state->queue_num(), "sanity");
4846 if (_g1->in_cset_fast_test(obj)) {
4847 oop forwardee;
4848 if (obj->is_forwarded()) {
4849 forwardee = obj->forwardee();
4850 } else {
4851 forwardee = _par_scan_state->copy_to_survivor_space(obj);
4852 }
4853 assert(forwardee != NULL, "forwardee should not be NULL");
4854 oopDesc::encode_store_heap_oop(p, forwardee);
4855 if (do_mark_object && forwardee != obj) {
4856 // If the object is self-forwarded we don't need to explicitly
4857 // mark it, the evacuation failure protocol will do so.
4858 mark_forwarded_object(obj, forwardee);
4859 }
4861 if (barrier == G1BarrierKlass) {
4862 do_klass_barrier(p, forwardee);
4863 }
4864 } else {
4865 // The object is not in collection set. If we're a root scanning
4866 // closure during an initial mark pause (i.e. do_mark_object will
4867 // be true) then attempt to mark the object.
4868 if (do_mark_object) {
4869 mark_object(obj);
4870 }
4871 }
4873 if (barrier == G1BarrierEvac) {
4874 _par_scan_state->update_rs(_from, p, _worker_id);
4875 }
4876 }
4878 template void G1ParCopyClosure<G1BarrierEvac, false>::do_oop_work(oop* p);
4879 template void G1ParCopyClosure<G1BarrierEvac, false>::do_oop_work(narrowOop* p);
4881 class G1ParEvacuateFollowersClosure : public VoidClosure {
4882 protected:
4883 G1CollectedHeap* _g1h;
4884 G1ParScanThreadState* _par_scan_state;
4885 RefToScanQueueSet* _queues;
4886 ParallelTaskTerminator* _terminator;
4888 G1ParScanThreadState* par_scan_state() { return _par_scan_state; }
4889 RefToScanQueueSet* queues() { return _queues; }
4890 ParallelTaskTerminator* terminator() { return _terminator; }
4892 public:
4893 G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
4894 G1ParScanThreadState* par_scan_state,
4895 RefToScanQueueSet* queues,
4896 ParallelTaskTerminator* terminator)
4897 : _g1h(g1h), _par_scan_state(par_scan_state),
4898 _queues(queues), _terminator(terminator) {}
4900 void do_void();
4902 private:
4903 inline bool offer_termination();
4904 };
4906 bool G1ParEvacuateFollowersClosure::offer_termination() {
4907 G1ParScanThreadState* const pss = par_scan_state();
4908 pss->start_term_time();
4909 const bool res = terminator()->offer_termination();
4910 pss->end_term_time();
4911 return res;
4912 }
4914 void G1ParEvacuateFollowersClosure::do_void() {
4915 StarTask stolen_task;
4916 G1ParScanThreadState* const pss = par_scan_state();
4917 pss->trim_queue();
4919 do {
4920 while (queues()->steal(pss->queue_num(), pss->hash_seed(), stolen_task)) {
4921 assert(pss->verify_task(stolen_task), "sanity");
4922 if (stolen_task.is_narrow()) {
4923 pss->deal_with_reference((narrowOop*) stolen_task);
4924 } else {
4925 pss->deal_with_reference((oop*) stolen_task);
4926 }
4928 // We've just processed a reference and we might have made
4929 // available new entries on the queues. So we have to make sure
4930 // we drain the queues as necessary.
4931 pss->trim_queue();
4932 }
4933 } while (!offer_termination());
4935 pss->retire_alloc_buffers();
4936 }
4938 class G1KlassScanClosure : public KlassClosure {
4939 G1ParCopyHelper* _closure;
4940 bool _process_only_dirty;
4941 int _count;
4942 public:
4943 G1KlassScanClosure(G1ParCopyHelper* closure, bool process_only_dirty)
4944 : _process_only_dirty(process_only_dirty), _closure(closure), _count(0) {}
4945 void do_klass(Klass* klass) {
4946 // If the klass has not been dirtied we know that there's
4947 // no references into the young gen and we can skip it.
4948 if (!_process_only_dirty || klass->has_modified_oops()) {
4949 // Clean the klass since we're going to scavenge all the metadata.
4950 klass->clear_modified_oops();
4952 // Tell the closure that this klass is the Klass to scavenge
4953 // and is the one to dirty if oops are left pointing into the young gen.
4954 _closure->set_scanned_klass(klass);
4956 klass->oops_do(_closure);
4958 _closure->set_scanned_klass(NULL);
4959 }
4960 _count++;
4961 }
4962 };
4964 class G1ParTask : public AbstractGangTask {
4965 protected:
4966 G1CollectedHeap* _g1h;
4967 RefToScanQueueSet *_queues;
4968 ParallelTaskTerminator _terminator;
4969 uint _n_workers;
4971 Mutex _stats_lock;
4972 Mutex* stats_lock() { return &_stats_lock; }
4974 size_t getNCards() {
4975 return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
4976 / G1BlockOffsetSharedArray::N_bytes;
4977 }
4979 public:
4980 G1ParTask(G1CollectedHeap* g1h,
4981 RefToScanQueueSet *task_queues)
4982 : AbstractGangTask("G1 collection"),
4983 _g1h(g1h),
4984 _queues(task_queues),
4985 _terminator(0, _queues),
4986 _stats_lock(Mutex::leaf, "parallel G1 stats lock", true)
4987 {}
4989 RefToScanQueueSet* queues() { return _queues; }
4991 RefToScanQueue *work_queue(int i) {
4992 return queues()->queue(i);
4993 }
4995 ParallelTaskTerminator* terminator() { return &_terminator; }
4997 virtual void set_for_termination(int active_workers) {
4998 // This task calls set_n_termination() in par_non_clean_card_iterate_work()
4999 // in the young space (_par_seq_tasks) in the G1 heap
5000 // for SequentialSubTasksDone.
5001 // This task also uses SubTasksDone in SharedHeap and G1CollectedHeap
5002 // both of which need setting by set_n_termination().
5003 _g1h->SharedHeap::set_n_termination(active_workers);
5004 _g1h->set_n_termination(active_workers);
5005 terminator()->reset_for_reuse(active_workers);
5006 _n_workers = active_workers;
5007 }
5009 void work(uint worker_id) {
5010 if (worker_id >= _n_workers) return; // no work needed this round
5012 double start_time_ms = os::elapsedTime() * 1000.0;
5013 _g1h->g1_policy()->phase_times()->record_gc_worker_start_time(worker_id, start_time_ms);
5015 {
5016 ResourceMark rm;
5017 HandleMark hm;
5019 ReferenceProcessor* rp = _g1h->ref_processor_stw();
5021 G1ParScanThreadState pss(_g1h, worker_id, rp);
5022 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, rp);
5024 pss.set_evac_failure_closure(&evac_failure_cl);
5026 G1ParScanExtRootClosure only_scan_root_cl(_g1h, &pss, rp);
5027 G1ParScanMetadataClosure only_scan_metadata_cl(_g1h, &pss, rp);
5029 G1ParScanAndMarkExtRootClosure scan_mark_root_cl(_g1h, &pss, rp);
5030 G1ParScanAndMarkMetadataClosure scan_mark_metadata_cl(_g1h, &pss, rp);
5032 bool only_young = _g1h->g1_policy()->gcs_are_young();
5033 G1KlassScanClosure scan_mark_klasses_cl_s(&scan_mark_metadata_cl, false);
5034 G1KlassScanClosure only_scan_klasses_cl_s(&only_scan_metadata_cl, only_young);
5036 OopClosure* scan_root_cl = &only_scan_root_cl;
5037 G1KlassScanClosure* scan_klasses_cl = &only_scan_klasses_cl_s;
5039 if (_g1h->g1_policy()->during_initial_mark_pause()) {
5040 // We also need to mark copied objects.
5041 scan_root_cl = &scan_mark_root_cl;
5042 scan_klasses_cl = &scan_mark_klasses_cl_s;
5043 }
5045 G1ParPushHeapRSClosure push_heap_rs_cl(_g1h, &pss);
5047 // Don't scan the scavengable methods in the code cache as part
5048 // of strong root scanning. The code roots that point into a
5049 // region in the collection set are scanned when we scan the
5050 // region's RSet.
5051 int so = SharedHeap::SO_AllClasses | SharedHeap::SO_Strings;
5053 pss.start_strong_roots();
5054 _g1h->g1_process_strong_roots(/* is scavenging */ true,
5055 SharedHeap::ScanningOption(so),
5056 scan_root_cl,
5057 &push_heap_rs_cl,
5058 scan_klasses_cl,
5059 worker_id);
5060 pss.end_strong_roots();
5062 {
5063 double start = os::elapsedTime();
5064 G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);
5065 evac.do_void();
5066 double elapsed_ms = (os::elapsedTime()-start)*1000.0;
5067 double term_ms = pss.term_time()*1000.0;
5068 _g1h->g1_policy()->phase_times()->add_obj_copy_time(worker_id, elapsed_ms-term_ms);
5069 _g1h->g1_policy()->phase_times()->record_termination(worker_id, term_ms, pss.term_attempts());
5070 }
5071 _g1h->g1_policy()->record_thread_age_table(pss.age_table());
5072 _g1h->update_surviving_young_words(pss.surviving_young_words()+1);
5074 if (ParallelGCVerbose) {
5075 MutexLocker x(stats_lock());
5076 pss.print_termination_stats(worker_id);
5077 }
5079 assert(pss.refs()->is_empty(), "should be empty");
5081 // Close the inner scope so that the ResourceMark and HandleMark
5082 // destructors are executed here and are included as part of the
5083 // "GC Worker Time".
5084 }
5086 double end_time_ms = os::elapsedTime() * 1000.0;
5087 _g1h->g1_policy()->phase_times()->record_gc_worker_end_time(worker_id, end_time_ms);
5088 }
5089 };
5091 // *** Common G1 Evacuation Stuff
5093 // This method is run in a GC worker.
5095 void
5096 G1CollectedHeap::
5097 g1_process_strong_roots(bool is_scavenging,
5098 ScanningOption so,
5099 OopClosure* scan_non_heap_roots,
5100 OopsInHeapRegionClosure* scan_rs,
5101 G1KlassScanClosure* scan_klasses,
5102 int worker_i) {
5104 // First scan the strong roots
5105 double ext_roots_start = os::elapsedTime();
5106 double closure_app_time_sec = 0.0;
5108 BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots);
5110 assert(so & SO_CodeCache || scan_rs != NULL, "must scan code roots somehow");
5111 // Walk the code cache/strong code roots w/o buffering, because StarTask
5112 // cannot handle unaligned oop locations.
5113 CodeBlobToOopClosure eager_scan_code_roots(scan_non_heap_roots, true /* do_marking */);
5115 process_strong_roots(false, // no scoping; this is parallel code
5116 is_scavenging, so,
5117 &buf_scan_non_heap_roots,
5118 &eager_scan_code_roots,
5119 scan_klasses
5120 );
5122 // Now the CM ref_processor roots.
5123 if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) {
5124 // We need to treat the discovered reference lists of the
5125 // concurrent mark ref processor as roots and keep entries
5126 // (which are added by the marking threads) on them live
5127 // until they can be processed at the end of marking.
5128 ref_processor_cm()->weak_oops_do(&buf_scan_non_heap_roots);
5129 }
5131 // Finish up any enqueued closure apps (attributed as object copy time).
5132 buf_scan_non_heap_roots.done();
5134 double obj_copy_time_sec = buf_scan_non_heap_roots.closure_app_seconds();
5136 g1_policy()->phase_times()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0);
5138 double ext_root_time_ms =
5139 ((os::elapsedTime() - ext_roots_start) - obj_copy_time_sec) * 1000.0;
5141 g1_policy()->phase_times()->record_ext_root_scan_time(worker_i, ext_root_time_ms);
5143 // During conc marking we have to filter the per-thread SATB buffers
5144 // to make sure we remove any oops into the CSet (which will show up
5145 // as implicitly live).
5146 double satb_filtering_ms = 0.0;
5147 if (!_process_strong_tasks->is_task_claimed(G1H_PS_filter_satb_buffers)) {
5148 if (mark_in_progress()) {
5149 double satb_filter_start = os::elapsedTime();
5151 JavaThread::satb_mark_queue_set().filter_thread_buffers();
5153 satb_filtering_ms = (os::elapsedTime() - satb_filter_start) * 1000.0;
5154 }
5155 }
5156 g1_policy()->phase_times()->record_satb_filtering_time(worker_i, satb_filtering_ms);
5158 // If this is an initial mark pause, and we're not scanning
5159 // the entire code cache, we need to mark the oops in the
5160 // strong code root lists for the regions that are not in
5161 // the collection set.
5162 // Note all threads participate in this set of root tasks.
5163 double mark_strong_code_roots_ms = 0.0;
5164 if (g1_policy()->during_initial_mark_pause() && !(so & SO_CodeCache)) {
5165 double mark_strong_roots_start = os::elapsedTime();
5166 mark_strong_code_roots(worker_i);
5167 mark_strong_code_roots_ms = (os::elapsedTime() - mark_strong_roots_start) * 1000.0;
5168 }
5169 g1_policy()->phase_times()->record_strong_code_root_mark_time(worker_i, mark_strong_code_roots_ms);
5171 // Now scan the complement of the collection set.
5172 if (scan_rs != NULL) {
5173 g1_rem_set()->oops_into_collection_set_do(scan_rs, &eager_scan_code_roots, worker_i);
5174 }
5175 _process_strong_tasks->all_tasks_completed();
5176 }
5178 void
5179 G1CollectedHeap::g1_process_weak_roots(OopClosure* root_closure) {
5180 CodeBlobToOopClosure roots_in_blobs(root_closure, /*do_marking=*/ false);
5181 SharedHeap::process_weak_roots(root_closure, &roots_in_blobs);
5182 }
5184 class G1StringSymbolTableUnlinkTask : public AbstractGangTask {
5185 private:
5186 BoolObjectClosure* _is_alive;
5187 int _initial_string_table_size;
5188 int _initial_symbol_table_size;
5190 bool _process_strings;
5191 int _strings_processed;
5192 int _strings_removed;
5194 bool _process_symbols;
5195 int _symbols_processed;
5196 int _symbols_removed;
5198 bool _do_in_parallel;
5199 public:
5200 G1StringSymbolTableUnlinkTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols) :
5201 AbstractGangTask("Par String/Symbol table unlink"), _is_alive(is_alive),
5202 _do_in_parallel(G1CollectedHeap::use_parallel_gc_threads()),
5203 _process_strings(process_strings), _strings_processed(0), _strings_removed(0),
5204 _process_symbols(process_symbols), _symbols_processed(0), _symbols_removed(0) {
5206 _initial_string_table_size = StringTable::the_table()->table_size();
5207 _initial_symbol_table_size = SymbolTable::the_table()->table_size();
5208 if (process_strings) {
5209 StringTable::clear_parallel_claimed_index();
5210 }
5211 if (process_symbols) {
5212 SymbolTable::clear_parallel_claimed_index();
5213 }
5214 }
5216 ~G1StringSymbolTableUnlinkTask() {
5217 guarantee(!_process_strings || !_do_in_parallel || StringTable::parallel_claimed_index() >= _initial_string_table_size,
5218 err_msg("claim value "INT32_FORMAT" after unlink less than initial string table size "INT32_FORMAT,
5219 StringTable::parallel_claimed_index(), _initial_string_table_size));
5220 guarantee(!_process_symbols || !_do_in_parallel || SymbolTable::parallel_claimed_index() >= _initial_symbol_table_size,
5221 err_msg("claim value "INT32_FORMAT" after unlink less than initial symbol table size "INT32_FORMAT,
5222 SymbolTable::parallel_claimed_index(), _initial_symbol_table_size));
5223 }
5225 void work(uint worker_id) {
5226 if (_do_in_parallel) {
5227 int strings_processed = 0;
5228 int strings_removed = 0;
5229 int symbols_processed = 0;
5230 int symbols_removed = 0;
5231 if (_process_strings) {
5232 StringTable::possibly_parallel_unlink(_is_alive, &strings_processed, &strings_removed);
5233 Atomic::add(strings_processed, &_strings_processed);
5234 Atomic::add(strings_removed, &_strings_removed);
5235 }
5236 if (_process_symbols) {
5237 SymbolTable::possibly_parallel_unlink(&symbols_processed, &symbols_removed);
5238 Atomic::add(symbols_processed, &_symbols_processed);
5239 Atomic::add(symbols_removed, &_symbols_removed);
5240 }
5241 } else {
5242 if (_process_strings) {
5243 StringTable::unlink(_is_alive, &_strings_processed, &_strings_removed);
5244 }
5245 if (_process_symbols) {
5246 SymbolTable::unlink(&_symbols_processed, &_symbols_removed);
5247 }
5248 }
5249 }
5251 size_t strings_processed() const { return (size_t)_strings_processed; }
5252 size_t strings_removed() const { return (size_t)_strings_removed; }
5254 size_t symbols_processed() const { return (size_t)_symbols_processed; }
5255 size_t symbols_removed() const { return (size_t)_symbols_removed; }
5256 };
5258 void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive,
5259 bool process_strings, bool process_symbols) {
5260 uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
5261 _g1h->workers()->active_workers() : 1);
5263 G1StringSymbolTableUnlinkTask g1_unlink_task(is_alive, process_strings, process_symbols);
5264 if (G1CollectedHeap::use_parallel_gc_threads()) {
5265 set_par_threads(n_workers);
5266 workers()->run_task(&g1_unlink_task);
5267 set_par_threads(0);
5268 } else {
5269 g1_unlink_task.work(0);
5270 }
5271 if (G1TraceStringSymbolTableScrubbing) {
5272 gclog_or_tty->print_cr("Cleaned string and symbol table, "
5273 "strings: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed, "
5274 "symbols: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed",
5275 g1_unlink_task.strings_processed(), g1_unlink_task.strings_removed(),
5276 g1_unlink_task.symbols_processed(), g1_unlink_task.symbols_removed());
5277 }
5279 if (G1StringDedup::is_enabled()) {
5280 G1StringDedup::unlink(is_alive);
5281 }
5282 }
5284 class RedirtyLoggedCardTableEntryFastClosure : public CardTableEntryClosure {
5285 public:
5286 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
5287 *card_ptr = CardTableModRefBS::dirty_card_val();
5288 return true;
5289 }
5290 };
5292 void G1CollectedHeap::redirty_logged_cards() {
5293 guarantee(G1DeferredRSUpdate, "Must only be called when using deferred RS updates.");
5294 double redirty_logged_cards_start = os::elapsedTime();
5296 RedirtyLoggedCardTableEntryFastClosure redirty;
5297 dirty_card_queue_set().set_closure(&redirty);
5298 dirty_card_queue_set().apply_closure_to_all_completed_buffers();
5300 DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set();
5301 dcq.merge_bufferlists(&dirty_card_queue_set());
5302 assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
5304 g1_policy()->phase_times()->record_redirty_logged_cards_time_ms((os::elapsedTime() - redirty_logged_cards_start) * 1000.0);
5305 }
5307 // Weak Reference Processing support
5309 // An always "is_alive" closure that is used to preserve referents.
5310 // If the object is non-null then it's alive. Used in the preservation
5311 // of referent objects that are pointed to by reference objects
5312 // discovered by the CM ref processor.
5313 class G1AlwaysAliveClosure: public BoolObjectClosure {
5314 G1CollectedHeap* _g1;
5315 public:
5316 G1AlwaysAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
5317 bool do_object_b(oop p) {
5318 if (p != NULL) {
5319 return true;
5320 }
5321 return false;
5322 }
5323 };
5325 bool G1STWIsAliveClosure::do_object_b(oop p) {
5326 // An object is reachable if it is outside the collection set,
5327 // or is inside and copied.
5328 return !_g1->obj_in_cs(p) || p->is_forwarded();
5329 }
5331 // Non Copying Keep Alive closure
5332 class G1KeepAliveClosure: public OopClosure {
5333 G1CollectedHeap* _g1;
5334 public:
5335 G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
5336 void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
5337 void do_oop( oop* p) {
5338 oop obj = *p;
5340 if (_g1->obj_in_cs(obj)) {
5341 assert( obj->is_forwarded(), "invariant" );
5342 *p = obj->forwardee();
5343 }
5344 }
5345 };
5347 // Copying Keep Alive closure - can be called from both
5348 // serial and parallel code as long as different worker
5349 // threads utilize different G1ParScanThreadState instances
5350 // and different queues.
5352 class G1CopyingKeepAliveClosure: public OopClosure {
5353 G1CollectedHeap* _g1h;
5354 OopClosure* _copy_non_heap_obj_cl;
5355 OopsInHeapRegionClosure* _copy_metadata_obj_cl;
5356 G1ParScanThreadState* _par_scan_state;
5358 public:
5359 G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
5360 OopClosure* non_heap_obj_cl,
5361 OopsInHeapRegionClosure* metadata_obj_cl,
5362 G1ParScanThreadState* pss):
5363 _g1h(g1h),
5364 _copy_non_heap_obj_cl(non_heap_obj_cl),
5365 _copy_metadata_obj_cl(metadata_obj_cl),
5366 _par_scan_state(pss)
5367 {}
5369 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
5370 virtual void do_oop( oop* p) { do_oop_work(p); }
5372 template <class T> void do_oop_work(T* p) {
5373 oop obj = oopDesc::load_decode_heap_oop(p);
5375 if (_g1h->obj_in_cs(obj)) {
5376 // If the referent object has been forwarded (either copied
5377 // to a new location or to itself in the event of an
5378 // evacuation failure) then we need to update the reference
5379 // field and, if both reference and referent are in the G1
5380 // heap, update the RSet for the referent.
5381 //
5382 // If the referent has not been forwarded then we have to keep
5383 // it alive by policy. Therefore we have copy the referent.
5384 //
5385 // If the reference field is in the G1 heap then we can push
5386 // on the PSS queue. When the queue is drained (after each
5387 // phase of reference processing) the object and it's followers
5388 // will be copied, the reference field set to point to the
5389 // new location, and the RSet updated. Otherwise we need to
5390 // use the the non-heap or metadata closures directly to copy
5391 // the referent object and update the pointer, while avoiding
5392 // updating the RSet.
5394 if (_g1h->is_in_g1_reserved(p)) {
5395 _par_scan_state->push_on_queue(p);
5396 } else {
5397 assert(!ClassLoaderDataGraph::contains((address)p),
5398 err_msg("Otherwise need to call _copy_metadata_obj_cl->do_oop(p) "
5399 PTR_FORMAT, p));
5400 _copy_non_heap_obj_cl->do_oop(p);
5401 }
5402 }
5403 }
5404 };
5406 // Serial drain queue closure. Called as the 'complete_gc'
5407 // closure for each discovered list in some of the
5408 // reference processing phases.
5410 class G1STWDrainQueueClosure: public VoidClosure {
5411 protected:
5412 G1CollectedHeap* _g1h;
5413 G1ParScanThreadState* _par_scan_state;
5415 G1ParScanThreadState* par_scan_state() { return _par_scan_state; }
5417 public:
5418 G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :
5419 _g1h(g1h),
5420 _par_scan_state(pss)
5421 { }
5423 void do_void() {
5424 G1ParScanThreadState* const pss = par_scan_state();
5425 pss->trim_queue();
5426 }
5427 };
5429 // Parallel Reference Processing closures
5431 // Implementation of AbstractRefProcTaskExecutor for parallel reference
5432 // processing during G1 evacuation pauses.
5434 class G1STWRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
5435 private:
5436 G1CollectedHeap* _g1h;
5437 RefToScanQueueSet* _queues;
5438 FlexibleWorkGang* _workers;
5439 int _active_workers;
5441 public:
5442 G1STWRefProcTaskExecutor(G1CollectedHeap* g1h,
5443 FlexibleWorkGang* workers,
5444 RefToScanQueueSet *task_queues,
5445 int n_workers) :
5446 _g1h(g1h),
5447 _queues(task_queues),
5448 _workers(workers),
5449 _active_workers(n_workers)
5450 {
5451 assert(n_workers > 0, "shouldn't call this otherwise");
5452 }
5454 // Executes the given task using concurrent marking worker threads.
5455 virtual void execute(ProcessTask& task);
5456 virtual void execute(EnqueueTask& task);
5457 };
5459 // Gang task for possibly parallel reference processing
5461 class G1STWRefProcTaskProxy: public AbstractGangTask {
5462 typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
5463 ProcessTask& _proc_task;
5464 G1CollectedHeap* _g1h;
5465 RefToScanQueueSet *_task_queues;
5466 ParallelTaskTerminator* _terminator;
5468 public:
5469 G1STWRefProcTaskProxy(ProcessTask& proc_task,
5470 G1CollectedHeap* g1h,
5471 RefToScanQueueSet *task_queues,
5472 ParallelTaskTerminator* terminator) :
5473 AbstractGangTask("Process reference objects in parallel"),
5474 _proc_task(proc_task),
5475 _g1h(g1h),
5476 _task_queues(task_queues),
5477 _terminator(terminator)
5478 {}
5480 virtual void work(uint worker_id) {
5481 // The reference processing task executed by a single worker.
5482 ResourceMark rm;
5483 HandleMark hm;
5485 G1STWIsAliveClosure is_alive(_g1h);
5487 G1ParScanThreadState pss(_g1h, worker_id, NULL);
5488 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);
5490 pss.set_evac_failure_closure(&evac_failure_cl);
5492 G1ParScanExtRootClosure only_copy_non_heap_cl(_g1h, &pss, NULL);
5493 G1ParScanMetadataClosure only_copy_metadata_cl(_g1h, &pss, NULL);
5495 G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
5496 G1ParScanAndMarkMetadataClosure copy_mark_metadata_cl(_g1h, &pss, NULL);
5498 OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl;
5499 OopsInHeapRegionClosure* copy_metadata_cl = &only_copy_metadata_cl;
5501 if (_g1h->g1_policy()->during_initial_mark_pause()) {
5502 // We also need to mark copied objects.
5503 copy_non_heap_cl = ©_mark_non_heap_cl;
5504 copy_metadata_cl = ©_mark_metadata_cl;
5505 }
5507 // Keep alive closure.
5508 G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, copy_metadata_cl, &pss);
5510 // Complete GC closure
5511 G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _task_queues, _terminator);
5513 // Call the reference processing task's work routine.
5514 _proc_task.work(worker_id, is_alive, keep_alive, drain_queue);
5516 // Note we cannot assert that the refs array is empty here as not all
5517 // of the processing tasks (specifically phase2 - pp2_work) execute
5518 // the complete_gc closure (which ordinarily would drain the queue) so
5519 // the queue may not be empty.
5520 }
5521 };
5523 // Driver routine for parallel reference processing.
5524 // Creates an instance of the ref processing gang
5525 // task and has the worker threads execute it.
5526 void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task) {
5527 assert(_workers != NULL, "Need parallel worker threads.");
5529 ParallelTaskTerminator terminator(_active_workers, _queues);
5530 G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _queues, &terminator);
5532 _g1h->set_par_threads(_active_workers);
5533 _workers->run_task(&proc_task_proxy);
5534 _g1h->set_par_threads(0);
5535 }
5537 // Gang task for parallel reference enqueueing.
5539 class G1STWRefEnqueueTaskProxy: public AbstractGangTask {
5540 typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
5541 EnqueueTask& _enq_task;
5543 public:
5544 G1STWRefEnqueueTaskProxy(EnqueueTask& enq_task) :
5545 AbstractGangTask("Enqueue reference objects in parallel"),
5546 _enq_task(enq_task)
5547 { }
5549 virtual void work(uint worker_id) {
5550 _enq_task.work(worker_id);
5551 }
5552 };
5554 // Driver routine for parallel reference enqueueing.
5555 // Creates an instance of the ref enqueueing gang
5556 // task and has the worker threads execute it.
5558 void G1STWRefProcTaskExecutor::execute(EnqueueTask& enq_task) {
5559 assert(_workers != NULL, "Need parallel worker threads.");
5561 G1STWRefEnqueueTaskProxy enq_task_proxy(enq_task);
5563 _g1h->set_par_threads(_active_workers);
5564 _workers->run_task(&enq_task_proxy);
5565 _g1h->set_par_threads(0);
5566 }
5568 // End of weak reference support closures
5570 // Abstract task used to preserve (i.e. copy) any referent objects
5571 // that are in the collection set and are pointed to by reference
5572 // objects discovered by the CM ref processor.
5574 class G1ParPreserveCMReferentsTask: public AbstractGangTask {
5575 protected:
5576 G1CollectedHeap* _g1h;
5577 RefToScanQueueSet *_queues;
5578 ParallelTaskTerminator _terminator;
5579 uint _n_workers;
5581 public:
5582 G1ParPreserveCMReferentsTask(G1CollectedHeap* g1h,int workers, RefToScanQueueSet *task_queues) :
5583 AbstractGangTask("ParPreserveCMReferents"),
5584 _g1h(g1h),
5585 _queues(task_queues),
5586 _terminator(workers, _queues),
5587 _n_workers(workers)
5588 { }
5590 void work(uint worker_id) {
5591 ResourceMark rm;
5592 HandleMark hm;
5594 G1ParScanThreadState pss(_g1h, worker_id, NULL);
5595 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL);
5597 pss.set_evac_failure_closure(&evac_failure_cl);
5599 assert(pss.refs()->is_empty(), "both queue and overflow should be empty");
5602 G1ParScanExtRootClosure only_copy_non_heap_cl(_g1h, &pss, NULL);
5603 G1ParScanMetadataClosure only_copy_metadata_cl(_g1h, &pss, NULL);
5605 G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL);
5606 G1ParScanAndMarkMetadataClosure copy_mark_metadata_cl(_g1h, &pss, NULL);
5608 OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl;
5609 OopsInHeapRegionClosure* copy_metadata_cl = &only_copy_metadata_cl;
5611 if (_g1h->g1_policy()->during_initial_mark_pause()) {
5612 // We also need to mark copied objects.
5613 copy_non_heap_cl = ©_mark_non_heap_cl;
5614 copy_metadata_cl = ©_mark_metadata_cl;
5615 }
5617 // Is alive closure
5618 G1AlwaysAliveClosure always_alive(_g1h);
5620 // Copying keep alive closure. Applied to referent objects that need
5621 // to be copied.
5622 G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, copy_metadata_cl, &pss);
5624 ReferenceProcessor* rp = _g1h->ref_processor_cm();
5626 uint limit = ReferenceProcessor::number_of_subclasses_of_ref() * rp->max_num_q();
5627 uint stride = MIN2(MAX2(_n_workers, 1U), limit);
5629 // limit is set using max_num_q() - which was set using ParallelGCThreads.
5630 // So this must be true - but assert just in case someone decides to
5631 // change the worker ids.
5632 assert(0 <= worker_id && worker_id < limit, "sanity");
5633 assert(!rp->discovery_is_atomic(), "check this code");
5635 // Select discovered lists [i, i+stride, i+2*stride,...,limit)
5636 for (uint idx = worker_id; idx < limit; idx += stride) {
5637 DiscoveredList& ref_list = rp->discovered_refs()[idx];
5639 DiscoveredListIterator iter(ref_list, &keep_alive, &always_alive);
5640 while (iter.has_next()) {
5641 // Since discovery is not atomic for the CM ref processor, we
5642 // can see some null referent objects.
5643 iter.load_ptrs(DEBUG_ONLY(true));
5644 oop ref = iter.obj();
5646 // This will filter nulls.
5647 if (iter.is_referent_alive()) {
5648 iter.make_referent_alive();
5649 }
5650 iter.move_to_next();
5651 }
5652 }
5654 // Drain the queue - which may cause stealing
5655 G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _queues, &_terminator);
5656 drain_queue.do_void();
5657 // Allocation buffers were retired at the end of G1ParEvacuateFollowersClosure
5658 assert(pss.refs()->is_empty(), "should be");
5659 }
5660 };
5662 // Weak Reference processing during an evacuation pause (part 1).
5663 void G1CollectedHeap::process_discovered_references(uint no_of_gc_workers) {
5664 double ref_proc_start = os::elapsedTime();
5666 ReferenceProcessor* rp = _ref_processor_stw;
5667 assert(rp->discovery_enabled(), "should have been enabled");
5669 // Any reference objects, in the collection set, that were 'discovered'
5670 // by the CM ref processor should have already been copied (either by
5671 // applying the external root copy closure to the discovered lists, or
5672 // by following an RSet entry).
5673 //
5674 // But some of the referents, that are in the collection set, that these
5675 // reference objects point to may not have been copied: the STW ref
5676 // processor would have seen that the reference object had already
5677 // been 'discovered' and would have skipped discovering the reference,
5678 // but would not have treated the reference object as a regular oop.
5679 // As a result the copy closure would not have been applied to the
5680 // referent object.
5681 //
5682 // We need to explicitly copy these referent objects - the references
5683 // will be processed at the end of remarking.
5684 //
5685 // We also need to do this copying before we process the reference
5686 // objects discovered by the STW ref processor in case one of these
5687 // referents points to another object which is also referenced by an
5688 // object discovered by the STW ref processor.
5690 assert(!G1CollectedHeap::use_parallel_gc_threads() ||
5691 no_of_gc_workers == workers()->active_workers(),
5692 "Need to reset active GC workers");
5694 set_par_threads(no_of_gc_workers);
5695 G1ParPreserveCMReferentsTask keep_cm_referents(this,
5696 no_of_gc_workers,
5697 _task_queues);
5699 if (G1CollectedHeap::use_parallel_gc_threads()) {
5700 workers()->run_task(&keep_cm_referents);
5701 } else {
5702 keep_cm_referents.work(0);
5703 }
5705 set_par_threads(0);
5707 // Closure to test whether a referent is alive.
5708 G1STWIsAliveClosure is_alive(this);
5710 // Even when parallel reference processing is enabled, the processing
5711 // of JNI refs is serial and performed serially by the current thread
5712 // rather than by a worker. The following PSS will be used for processing
5713 // JNI refs.
5715 // Use only a single queue for this PSS.
5716 G1ParScanThreadState pss(this, 0, NULL);
5718 // We do not embed a reference processor in the copying/scanning
5719 // closures while we're actually processing the discovered
5720 // reference objects.
5721 G1ParScanHeapEvacFailureClosure evac_failure_cl(this, &pss, NULL);
5723 pss.set_evac_failure_closure(&evac_failure_cl);
5725 assert(pss.refs()->is_empty(), "pre-condition");
5727 G1ParScanExtRootClosure only_copy_non_heap_cl(this, &pss, NULL);
5728 G1ParScanMetadataClosure only_copy_metadata_cl(this, &pss, NULL);
5730 G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(this, &pss, NULL);
5731 G1ParScanAndMarkMetadataClosure copy_mark_metadata_cl(this, &pss, NULL);
5733 OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl;
5734 OopsInHeapRegionClosure* copy_metadata_cl = &only_copy_metadata_cl;
5736 if (_g1h->g1_policy()->during_initial_mark_pause()) {
5737 // We also need to mark copied objects.
5738 copy_non_heap_cl = ©_mark_non_heap_cl;
5739 copy_metadata_cl = ©_mark_metadata_cl;
5740 }
5742 // Keep alive closure.
5743 G1CopyingKeepAliveClosure keep_alive(this, copy_non_heap_cl, copy_metadata_cl, &pss);
5745 // Serial Complete GC closure
5746 G1STWDrainQueueClosure drain_queue(this, &pss);
5748 // Setup the soft refs policy...
5749 rp->setup_policy(false);
5751 ReferenceProcessorStats stats;
5752 if (!rp->processing_is_mt()) {
5753 // Serial reference processing...
5754 stats = rp->process_discovered_references(&is_alive,
5755 &keep_alive,
5756 &drain_queue,
5757 NULL,
5758 _gc_timer_stw);
5759 } else {
5760 // Parallel reference processing
5761 assert(rp->num_q() == no_of_gc_workers, "sanity");
5762 assert(no_of_gc_workers <= rp->max_num_q(), "sanity");
5764 G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);
5765 stats = rp->process_discovered_references(&is_alive,
5766 &keep_alive,
5767 &drain_queue,
5768 &par_task_executor,
5769 _gc_timer_stw);
5770 }
5772 _gc_tracer_stw->report_gc_reference_stats(stats);
5773 // We have completed copying any necessary live referent objects
5774 // (that were not copied during the actual pause) so we can
5775 // retire any active alloc buffers
5776 pss.retire_alloc_buffers();
5777 assert(pss.refs()->is_empty(), "both queue and overflow should be empty");
5779 double ref_proc_time = os::elapsedTime() - ref_proc_start;
5780 g1_policy()->phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);
5781 }
5783 // Weak Reference processing during an evacuation pause (part 2).
5784 void G1CollectedHeap::enqueue_discovered_references(uint no_of_gc_workers) {
5785 double ref_enq_start = os::elapsedTime();
5787 ReferenceProcessor* rp = _ref_processor_stw;
5788 assert(!rp->discovery_enabled(), "should have been disabled as part of processing");
5790 // Now enqueue any remaining on the discovered lists on to
5791 // the pending list.
5792 if (!rp->processing_is_mt()) {
5793 // Serial reference processing...
5794 rp->enqueue_discovered_references();
5795 } else {
5796 // Parallel reference enqueueing
5798 assert(no_of_gc_workers == workers()->active_workers(),
5799 "Need to reset active workers");
5800 assert(rp->num_q() == no_of_gc_workers, "sanity");
5801 assert(no_of_gc_workers <= rp->max_num_q(), "sanity");
5803 G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers);
5804 rp->enqueue_discovered_references(&par_task_executor);
5805 }
5807 rp->verify_no_references_recorded();
5808 assert(!rp->discovery_enabled(), "should have been disabled");
5810 // FIXME
5811 // CM's reference processing also cleans up the string and symbol tables.
5812 // Should we do that here also? We could, but it is a serial operation
5813 // and could significantly increase the pause time.
5815 double ref_enq_time = os::elapsedTime() - ref_enq_start;
5816 g1_policy()->phase_times()->record_ref_enq_time(ref_enq_time * 1000.0);
5817 }
5819 void G1CollectedHeap::evacuate_collection_set(EvacuationInfo& evacuation_info) {
5820 _expand_heap_after_alloc_failure = true;
5821 _evacuation_failed = false;
5823 // Should G1EvacuationFailureALot be in effect for this GC?
5824 NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)
5826 g1_rem_set()->prepare_for_oops_into_collection_set_do();
5828 // Disable the hot card cache.
5829 G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache();
5830 hot_card_cache->reset_hot_cache_claimed_index();
5831 hot_card_cache->set_use_cache(false);
5833 uint n_workers;
5834 if (G1CollectedHeap::use_parallel_gc_threads()) {
5835 n_workers =
5836 AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
5837 workers()->active_workers(),
5838 Threads::number_of_non_daemon_threads());
5839 assert(UseDynamicNumberOfGCThreads ||
5840 n_workers == workers()->total_workers(),
5841 "If not dynamic should be using all the workers");
5842 workers()->set_active_workers(n_workers);
5843 set_par_threads(n_workers);
5844 } else {
5845 assert(n_par_threads() == 0,
5846 "Should be the original non-parallel value");
5847 n_workers = 1;
5848 }
5850 G1ParTask g1_par_task(this, _task_queues);
5852 init_for_evac_failure(NULL);
5854 rem_set()->prepare_for_younger_refs_iterate(true);
5856 assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty");
5857 double start_par_time_sec = os::elapsedTime();
5858 double end_par_time_sec;
5860 {
5861 StrongRootsScope srs(this);
5863 if (G1CollectedHeap::use_parallel_gc_threads()) {
5864 // The individual threads will set their evac-failure closures.
5865 if (ParallelGCVerbose) G1ParScanThreadState::print_termination_stats_hdr();
5866 // These tasks use ShareHeap::_process_strong_tasks
5867 assert(UseDynamicNumberOfGCThreads ||
5868 workers()->active_workers() == workers()->total_workers(),
5869 "If not dynamic should be using all the workers");
5870 workers()->run_task(&g1_par_task);
5871 } else {
5872 g1_par_task.set_for_termination(n_workers);
5873 g1_par_task.work(0);
5874 }
5875 end_par_time_sec = os::elapsedTime();
5877 // Closing the inner scope will execute the destructor
5878 // for the StrongRootsScope object. We record the current
5879 // elapsed time before closing the scope so that time
5880 // taken for the SRS destructor is NOT included in the
5881 // reported parallel time.
5882 }
5884 double par_time_ms = (end_par_time_sec - start_par_time_sec) * 1000.0;
5885 g1_policy()->phase_times()->record_par_time(par_time_ms);
5887 double code_root_fixup_time_ms =
5888 (os::elapsedTime() - end_par_time_sec) * 1000.0;
5889 g1_policy()->phase_times()->record_code_root_fixup_time(code_root_fixup_time_ms);
5891 set_par_threads(0);
5893 // Process any discovered reference objects - we have
5894 // to do this _before_ we retire the GC alloc regions
5895 // as we may have to copy some 'reachable' referent
5896 // objects (and their reachable sub-graphs) that were
5897 // not copied during the pause.
5898 process_discovered_references(n_workers);
5900 // Weak root processing.
5901 {
5902 G1STWIsAliveClosure is_alive(this);
5903 G1KeepAliveClosure keep_alive(this);
5904 JNIHandles::weak_oops_do(&is_alive, &keep_alive);
5905 if (G1StringDedup::is_enabled()) {
5906 G1StringDedup::unlink_or_oops_do(&is_alive, &keep_alive);
5907 }
5908 }
5910 release_gc_alloc_regions(n_workers, evacuation_info);
5911 g1_rem_set()->cleanup_after_oops_into_collection_set_do();
5913 // Reset and re-enable the hot card cache.
5914 // Note the counts for the cards in the regions in the
5915 // collection set are reset when the collection set is freed.
5916 hot_card_cache->reset_hot_cache();
5917 hot_card_cache->set_use_cache(true);
5919 // Migrate the strong code roots attached to each region in
5920 // the collection set. Ideally we would like to do this
5921 // after we have finished the scanning/evacuation of the
5922 // strong code roots for a particular heap region.
5923 migrate_strong_code_roots();
5925 purge_code_root_memory();
5927 if (g1_policy()->during_initial_mark_pause()) {
5928 // Reset the claim values set during marking the strong code roots
5929 reset_heap_region_claim_values();
5930 }
5932 finalize_for_evac_failure();
5934 if (evacuation_failed()) {
5935 remove_self_forwarding_pointers();
5937 // Reset the G1EvacuationFailureALot counters and flags
5938 // Note: the values are reset only when an actual
5939 // evacuation failure occurs.
5940 NOT_PRODUCT(reset_evacuation_should_fail();)
5941 }
5943 // Enqueue any remaining references remaining on the STW
5944 // reference processor's discovered lists. We need to do
5945 // this after the card table is cleaned (and verified) as
5946 // the act of enqueueing entries on to the pending list
5947 // will log these updates (and dirty their associated
5948 // cards). We need these updates logged to update any
5949 // RSets.
5950 enqueue_discovered_references(n_workers);
5952 if (G1DeferredRSUpdate) {
5953 redirty_logged_cards();
5954 }
5955 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
5956 }
5958 void G1CollectedHeap::free_region(HeapRegion* hr,
5959 FreeRegionList* free_list,
5960 bool par,
5961 bool locked) {
5962 assert(!hr->isHumongous(), "this is only for non-humongous regions");
5963 assert(!hr->is_empty(), "the region should not be empty");
5964 assert(free_list != NULL, "pre-condition");
5966 // Clear the card counts for this region.
5967 // Note: we only need to do this if the region is not young
5968 // (since we don't refine cards in young regions).
5969 if (!hr->is_young()) {
5970 _cg1r->hot_card_cache()->reset_card_counts(hr);
5971 }
5972 hr->hr_clear(par, true /* clear_space */, locked /* locked */);
5973 free_list->add_as_head(hr);
5974 }
5976 void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
5977 FreeRegionList* free_list,
5978 bool par) {
5979 assert(hr->startsHumongous(), "this is only for starts humongous regions");
5980 assert(free_list != NULL, "pre-condition");
5982 size_t hr_capacity = hr->capacity();
5983 // We need to read this before we make the region non-humongous,
5984 // otherwise the information will be gone.
5985 uint last_index = hr->last_hc_index();
5986 hr->set_notHumongous();
5987 free_region(hr, free_list, par);
5989 uint i = hr->hrs_index() + 1;
5990 while (i < last_index) {
5991 HeapRegion* curr_hr = region_at(i);
5992 assert(curr_hr->continuesHumongous(), "invariant");
5993 curr_hr->set_notHumongous();
5994 free_region(curr_hr, free_list, par);
5995 i += 1;
5996 }
5997 }
5999 void G1CollectedHeap::remove_from_old_sets(const HeapRegionSetCount& old_regions_removed,
6000 const HeapRegionSetCount& humongous_regions_removed) {
6001 if (old_regions_removed.length() > 0 || humongous_regions_removed.length() > 0) {
6002 MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag);
6003 _old_set.bulk_remove(old_regions_removed);
6004 _humongous_set.bulk_remove(humongous_regions_removed);
6005 }
6007 }
6009 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {
6010 assert(list != NULL, "list can't be null");
6011 if (!list->is_empty()) {
6012 MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag);
6013 _free_list.add_as_head(list);
6014 }
6015 }
6017 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {
6018 assert(_summary_bytes_used >= bytes,
6019 err_msg("invariant: _summary_bytes_used: "SIZE_FORMAT" should be >= bytes: "SIZE_FORMAT,
6020 _summary_bytes_used, bytes));
6021 _summary_bytes_used -= bytes;
6022 }
6024 class G1ParCleanupCTTask : public AbstractGangTask {
6025 G1SATBCardTableModRefBS* _ct_bs;
6026 G1CollectedHeap* _g1h;
6027 HeapRegion* volatile _su_head;
6028 public:
6029 G1ParCleanupCTTask(G1SATBCardTableModRefBS* ct_bs,
6030 G1CollectedHeap* g1h) :
6031 AbstractGangTask("G1 Par Cleanup CT Task"),
6032 _ct_bs(ct_bs), _g1h(g1h) { }
6034 void work(uint worker_id) {
6035 HeapRegion* r;
6036 while (r = _g1h->pop_dirty_cards_region()) {
6037 clear_cards(r);
6038 }
6039 }
6041 void clear_cards(HeapRegion* r) {
6042 // Cards of the survivors should have already been dirtied.
6043 if (!r->is_survivor()) {
6044 _ct_bs->clear(MemRegion(r->bottom(), r->end()));
6045 }
6046 }
6047 };
6049 #ifndef PRODUCT
6050 class G1VerifyCardTableCleanup: public HeapRegionClosure {
6051 G1CollectedHeap* _g1h;
6052 G1SATBCardTableModRefBS* _ct_bs;
6053 public:
6054 G1VerifyCardTableCleanup(G1CollectedHeap* g1h, G1SATBCardTableModRefBS* ct_bs)
6055 : _g1h(g1h), _ct_bs(ct_bs) { }
6056 virtual bool doHeapRegion(HeapRegion* r) {
6057 if (r->is_survivor()) {
6058 _g1h->verify_dirty_region(r);
6059 } else {
6060 _g1h->verify_not_dirty_region(r);
6061 }
6062 return false;
6063 }
6064 };
6066 void G1CollectedHeap::verify_not_dirty_region(HeapRegion* hr) {
6067 // All of the region should be clean.
6068 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6069 MemRegion mr(hr->bottom(), hr->end());
6070 ct_bs->verify_not_dirty_region(mr);
6071 }
6073 void G1CollectedHeap::verify_dirty_region(HeapRegion* hr) {
6074 // We cannot guarantee that [bottom(),end()] is dirty. Threads
6075 // dirty allocated blocks as they allocate them. The thread that
6076 // retires each region and replaces it with a new one will do a
6077 // maximal allocation to fill in [pre_dummy_top(),end()] but will
6078 // not dirty that area (one less thing to have to do while holding
6079 // a lock). So we can only verify that [bottom(),pre_dummy_top()]
6080 // is dirty.
6081 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6082 MemRegion mr(hr->bottom(), hr->pre_dummy_top());
6083 if (hr->is_young()) {
6084 ct_bs->verify_g1_young_region(mr);
6085 } else {
6086 ct_bs->verify_dirty_region(mr);
6087 }
6088 }
6090 void G1CollectedHeap::verify_dirty_young_list(HeapRegion* head) {
6091 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6092 for (HeapRegion* hr = head; hr != NULL; hr = hr->get_next_young_region()) {
6093 verify_dirty_region(hr);
6094 }
6095 }
6097 void G1CollectedHeap::verify_dirty_young_regions() {
6098 verify_dirty_young_list(_young_list->first_region());
6099 }
6100 #endif
6102 void G1CollectedHeap::cleanUpCardTable() {
6103 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set();
6104 double start = os::elapsedTime();
6106 {
6107 // Iterate over the dirty cards region list.
6108 G1ParCleanupCTTask cleanup_task(ct_bs, this);
6110 if (G1CollectedHeap::use_parallel_gc_threads()) {
6111 set_par_threads();
6112 workers()->run_task(&cleanup_task);
6113 set_par_threads(0);
6114 } else {
6115 while (_dirty_cards_region_list) {
6116 HeapRegion* r = _dirty_cards_region_list;
6117 cleanup_task.clear_cards(r);
6118 _dirty_cards_region_list = r->get_next_dirty_cards_region();
6119 if (_dirty_cards_region_list == r) {
6120 // The last region.
6121 _dirty_cards_region_list = NULL;
6122 }
6123 r->set_next_dirty_cards_region(NULL);
6124 }
6125 }
6126 #ifndef PRODUCT
6127 if (G1VerifyCTCleanup || VerifyAfterGC) {
6128 G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs);
6129 heap_region_iterate(&cleanup_verifier);
6130 }
6131 #endif
6132 }
6134 double elapsed = os::elapsedTime() - start;
6135 g1_policy()->phase_times()->record_clear_ct_time(elapsed * 1000.0);
6136 }
6138 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head, EvacuationInfo& evacuation_info) {
6139 size_t pre_used = 0;
6140 FreeRegionList local_free_list("Local List for CSet Freeing");
6142 double young_time_ms = 0.0;
6143 double non_young_time_ms = 0.0;
6145 // Since the collection set is a superset of the the young list,
6146 // all we need to do to clear the young list is clear its
6147 // head and length, and unlink any young regions in the code below
6148 _young_list->clear();
6150 G1CollectorPolicy* policy = g1_policy();
6152 double start_sec = os::elapsedTime();
6153 bool non_young = true;
6155 HeapRegion* cur = cs_head;
6156 int age_bound = -1;
6157 size_t rs_lengths = 0;
6159 while (cur != NULL) {
6160 assert(!is_on_master_free_list(cur), "sanity");
6161 if (non_young) {
6162 if (cur->is_young()) {
6163 double end_sec = os::elapsedTime();
6164 double elapsed_ms = (end_sec - start_sec) * 1000.0;
6165 non_young_time_ms += elapsed_ms;
6167 start_sec = os::elapsedTime();
6168 non_young = false;
6169 }
6170 } else {
6171 if (!cur->is_young()) {
6172 double end_sec = os::elapsedTime();
6173 double elapsed_ms = (end_sec - start_sec) * 1000.0;
6174 young_time_ms += elapsed_ms;
6176 start_sec = os::elapsedTime();
6177 non_young = true;
6178 }
6179 }
6181 rs_lengths += cur->rem_set()->occupied_locked();
6183 HeapRegion* next = cur->next_in_collection_set();
6184 assert(cur->in_collection_set(), "bad CS");
6185 cur->set_next_in_collection_set(NULL);
6186 cur->set_in_collection_set(false);
6188 if (cur->is_young()) {
6189 int index = cur->young_index_in_cset();
6190 assert(index != -1, "invariant");
6191 assert((uint) index < policy->young_cset_region_length(), "invariant");
6192 size_t words_survived = _surviving_young_words[index];
6193 cur->record_surv_words_in_group(words_survived);
6195 // At this point the we have 'popped' cur from the collection set
6196 // (linked via next_in_collection_set()) but it is still in the
6197 // young list (linked via next_young_region()). Clear the
6198 // _next_young_region field.
6199 cur->set_next_young_region(NULL);
6200 } else {
6201 int index = cur->young_index_in_cset();
6202 assert(index == -1, "invariant");
6203 }
6205 assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||
6206 (!cur->is_young() && cur->young_index_in_cset() == -1),
6207 "invariant" );
6209 if (!cur->evacuation_failed()) {
6210 MemRegion used_mr = cur->used_region();
6212 // And the region is empty.
6213 assert(!used_mr.is_empty(), "Should not have empty regions in a CS.");
6214 pre_used += cur->used();
6215 free_region(cur, &local_free_list, false /* par */, true /* locked */);
6216 } else {
6217 cur->uninstall_surv_rate_group();
6218 if (cur->is_young()) {
6219 cur->set_young_index_in_cset(-1);
6220 }
6221 cur->set_not_young();
6222 cur->set_evacuation_failed(false);
6223 // The region is now considered to be old.
6224 _old_set.add(cur);
6225 evacuation_info.increment_collectionset_used_after(cur->used());
6226 }
6227 cur = next;
6228 }
6230 evacuation_info.set_regions_freed(local_free_list.length());
6231 policy->record_max_rs_lengths(rs_lengths);
6232 policy->cset_regions_freed();
6234 double end_sec = os::elapsedTime();
6235 double elapsed_ms = (end_sec - start_sec) * 1000.0;
6237 if (non_young) {
6238 non_young_time_ms += elapsed_ms;
6239 } else {
6240 young_time_ms += elapsed_ms;
6241 }
6243 prepend_to_freelist(&local_free_list);
6244 decrement_summary_bytes(pre_used);
6245 policy->phase_times()->record_young_free_cset_time_ms(young_time_ms);
6246 policy->phase_times()->record_non_young_free_cset_time_ms(non_young_time_ms);
6247 }
6249 // This routine is similar to the above but does not record
6250 // any policy statistics or update free lists; we are abandoning
6251 // the current incremental collection set in preparation of a
6252 // full collection. After the full GC we will start to build up
6253 // the incremental collection set again.
6254 // This is only called when we're doing a full collection
6255 // and is immediately followed by the tearing down of the young list.
6257 void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) {
6258 HeapRegion* cur = cs_head;
6260 while (cur != NULL) {
6261 HeapRegion* next = cur->next_in_collection_set();
6262 assert(cur->in_collection_set(), "bad CS");
6263 cur->set_next_in_collection_set(NULL);
6264 cur->set_in_collection_set(false);
6265 cur->set_young_index_in_cset(-1);
6266 cur = next;
6267 }
6268 }
6270 void G1CollectedHeap::set_free_regions_coming() {
6271 if (G1ConcRegionFreeingVerbose) {
6272 gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
6273 "setting free regions coming");
6274 }
6276 assert(!free_regions_coming(), "pre-condition");
6277 _free_regions_coming = true;
6278 }
6280 void G1CollectedHeap::reset_free_regions_coming() {
6281 assert(free_regions_coming(), "pre-condition");
6283 {
6284 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6285 _free_regions_coming = false;
6286 SecondaryFreeList_lock->notify_all();
6287 }
6289 if (G1ConcRegionFreeingVerbose) {
6290 gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
6291 "reset free regions coming");
6292 }
6293 }
6295 void G1CollectedHeap::wait_while_free_regions_coming() {
6296 // Most of the time we won't have to wait, so let's do a quick test
6297 // first before we take the lock.
6298 if (!free_regions_coming()) {
6299 return;
6300 }
6302 if (G1ConcRegionFreeingVerbose) {
6303 gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
6304 "waiting for free regions");
6305 }
6307 {
6308 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6309 while (free_regions_coming()) {
6310 SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
6311 }
6312 }
6314 if (G1ConcRegionFreeingVerbose) {
6315 gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
6316 "done waiting for free regions");
6317 }
6318 }
6320 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
6321 assert(heap_lock_held_for_gc(),
6322 "the heap lock should already be held by or for this thread");
6323 _young_list->push_region(hr);
6324 }
6326 class NoYoungRegionsClosure: public HeapRegionClosure {
6327 private:
6328 bool _success;
6329 public:
6330 NoYoungRegionsClosure() : _success(true) { }
6331 bool doHeapRegion(HeapRegion* r) {
6332 if (r->is_young()) {
6333 gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young",
6334 r->bottom(), r->end());
6335 _success = false;
6336 }
6337 return false;
6338 }
6339 bool success() { return _success; }
6340 };
6342 bool G1CollectedHeap::check_young_list_empty(bool check_heap, bool check_sample) {
6343 bool ret = _young_list->check_list_empty(check_sample);
6345 if (check_heap) {
6346 NoYoungRegionsClosure closure;
6347 heap_region_iterate(&closure);
6348 ret = ret && closure.success();
6349 }
6351 return ret;
6352 }
6354 class TearDownRegionSetsClosure : public HeapRegionClosure {
6355 private:
6356 HeapRegionSet *_old_set;
6358 public:
6359 TearDownRegionSetsClosure(HeapRegionSet* old_set) : _old_set(old_set) { }
6361 bool doHeapRegion(HeapRegion* r) {
6362 if (r->is_empty()) {
6363 // We ignore empty regions, we'll empty the free list afterwards
6364 } else if (r->is_young()) {
6365 // We ignore young regions, we'll empty the young list afterwards
6366 } else if (r->isHumongous()) {
6367 // We ignore humongous regions, we're not tearing down the
6368 // humongous region set
6369 } else {
6370 // The rest should be old
6371 _old_set->remove(r);
6372 }
6373 return false;
6374 }
6376 ~TearDownRegionSetsClosure() {
6377 assert(_old_set->is_empty(), "post-condition");
6378 }
6379 };
6381 void G1CollectedHeap::tear_down_region_sets(bool free_list_only) {
6382 assert_at_safepoint(true /* should_be_vm_thread */);
6384 if (!free_list_only) {
6385 TearDownRegionSetsClosure cl(&_old_set);
6386 heap_region_iterate(&cl);
6388 // Note that emptying the _young_list is postponed and instead done as
6389 // the first step when rebuilding the regions sets again. The reason for
6390 // this is that during a full GC string deduplication needs to know if
6391 // a collected region was young or old when the full GC was initiated.
6392 }
6393 _free_list.remove_all();
6394 }
6396 class RebuildRegionSetsClosure : public HeapRegionClosure {
6397 private:
6398 bool _free_list_only;
6399 HeapRegionSet* _old_set;
6400 FreeRegionList* _free_list;
6401 size_t _total_used;
6403 public:
6404 RebuildRegionSetsClosure(bool free_list_only,
6405 HeapRegionSet* old_set, FreeRegionList* free_list) :
6406 _free_list_only(free_list_only),
6407 _old_set(old_set), _free_list(free_list), _total_used(0) {
6408 assert(_free_list->is_empty(), "pre-condition");
6409 if (!free_list_only) {
6410 assert(_old_set->is_empty(), "pre-condition");
6411 }
6412 }
6414 bool doHeapRegion(HeapRegion* r) {
6415 if (r->continuesHumongous()) {
6416 return false;
6417 }
6419 if (r->is_empty()) {
6420 // Add free regions to the free list
6421 _free_list->add_as_tail(r);
6422 } else if (!_free_list_only) {
6423 assert(!r->is_young(), "we should not come across young regions");
6425 if (r->isHumongous()) {
6426 // We ignore humongous regions, we left the humongous set unchanged
6427 } else {
6428 // The rest should be old, add them to the old set
6429 _old_set->add(r);
6430 }
6431 _total_used += r->used();
6432 }
6434 return false;
6435 }
6437 size_t total_used() {
6438 return _total_used;
6439 }
6440 };
6442 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
6443 assert_at_safepoint(true /* should_be_vm_thread */);
6445 if (!free_list_only) {
6446 _young_list->empty_list();
6447 }
6449 RebuildRegionSetsClosure cl(free_list_only, &_old_set, &_free_list);
6450 heap_region_iterate(&cl);
6452 if (!free_list_only) {
6453 _summary_bytes_used = cl.total_used();
6454 }
6455 assert(_summary_bytes_used == recalculate_used(),
6456 err_msg("inconsistent _summary_bytes_used, "
6457 "value: "SIZE_FORMAT" recalculated: "SIZE_FORMAT,
6458 _summary_bytes_used, recalculate_used()));
6459 }
6461 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
6462 _refine_cte_cl->set_concurrent(concurrent);
6463 }
6465 bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
6466 HeapRegion* hr = heap_region_containing(p);
6467 if (hr == NULL) {
6468 return false;
6469 } else {
6470 return hr->is_in(p);
6471 }
6472 }
6474 // Methods for the mutator alloc region
6476 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
6477 bool force) {
6478 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6479 assert(!force || g1_policy()->can_expand_young_list(),
6480 "if force is true we should be able to expand the young list");
6481 bool young_list_full = g1_policy()->is_young_list_full();
6482 if (force || !young_list_full) {
6483 HeapRegion* new_alloc_region = new_region(word_size,
6484 false /* do_expand */);
6485 if (new_alloc_region != NULL) {
6486 set_region_short_lived_locked(new_alloc_region);
6487 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Eden, young_list_full);
6488 return new_alloc_region;
6489 }
6490 }
6491 return NULL;
6492 }
6494 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
6495 size_t allocated_bytes) {
6496 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6497 assert(alloc_region->is_young(), "all mutator alloc regions should be young");
6499 g1_policy()->add_region_to_incremental_cset_lhs(alloc_region);
6500 _summary_bytes_used += allocated_bytes;
6501 _hr_printer.retire(alloc_region);
6502 // We update the eden sizes here, when the region is retired,
6503 // instead of when it's allocated, since this is the point that its
6504 // used space has been recored in _summary_bytes_used.
6505 g1mm()->update_eden_size();
6506 }
6508 HeapRegion* MutatorAllocRegion::allocate_new_region(size_t word_size,
6509 bool force) {
6510 return _g1h->new_mutator_alloc_region(word_size, force);
6511 }
6513 void G1CollectedHeap::set_par_threads() {
6514 // Don't change the number of workers. Use the value previously set
6515 // in the workgroup.
6516 assert(G1CollectedHeap::use_parallel_gc_threads(), "shouldn't be here otherwise");
6517 uint n_workers = workers()->active_workers();
6518 assert(UseDynamicNumberOfGCThreads ||
6519 n_workers == workers()->total_workers(),
6520 "Otherwise should be using the total number of workers");
6521 if (n_workers == 0) {
6522 assert(false, "Should have been set in prior evacuation pause.");
6523 n_workers = ParallelGCThreads;
6524 workers()->set_active_workers(n_workers);
6525 }
6526 set_par_threads(n_workers);
6527 }
6529 void MutatorAllocRegion::retire_region(HeapRegion* alloc_region,
6530 size_t allocated_bytes) {
6531 _g1h->retire_mutator_alloc_region(alloc_region, allocated_bytes);
6532 }
6534 // Methods for the GC alloc regions
6536 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size,
6537 uint count,
6538 GCAllocPurpose ap) {
6539 assert(FreeList_lock->owned_by_self(), "pre-condition");
6541 if (count < g1_policy()->max_regions(ap)) {
6542 HeapRegion* new_alloc_region = new_region(word_size,
6543 true /* do_expand */);
6544 if (new_alloc_region != NULL) {
6545 // We really only need to do this for old regions given that we
6546 // should never scan survivors. But it doesn't hurt to do it
6547 // for survivors too.
6548 new_alloc_region->set_saved_mark();
6549 if (ap == GCAllocForSurvived) {
6550 new_alloc_region->set_survivor();
6551 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor);
6552 } else {
6553 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Old);
6554 }
6555 bool during_im = g1_policy()->during_initial_mark_pause();
6556 new_alloc_region->note_start_of_copying(during_im);
6557 return new_alloc_region;
6558 } else {
6559 g1_policy()->note_alloc_region_limit_reached(ap);
6560 }
6561 }
6562 return NULL;
6563 }
6565 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
6566 size_t allocated_bytes,
6567 GCAllocPurpose ap) {
6568 bool during_im = g1_policy()->during_initial_mark_pause();
6569 alloc_region->note_end_of_copying(during_im);
6570 g1_policy()->record_bytes_copied_during_gc(allocated_bytes);
6571 if (ap == GCAllocForSurvived) {
6572 young_list()->add_survivor_region(alloc_region);
6573 } else {
6574 _old_set.add(alloc_region);
6575 }
6576 _hr_printer.retire(alloc_region);
6577 }
6579 HeapRegion* SurvivorGCAllocRegion::allocate_new_region(size_t word_size,
6580 bool force) {
6581 assert(!force, "not supported for GC alloc regions");
6582 return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForSurvived);
6583 }
6585 void SurvivorGCAllocRegion::retire_region(HeapRegion* alloc_region,
6586 size_t allocated_bytes) {
6587 _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
6588 GCAllocForSurvived);
6589 }
6591 HeapRegion* OldGCAllocRegion::allocate_new_region(size_t word_size,
6592 bool force) {
6593 assert(!force, "not supported for GC alloc regions");
6594 return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForTenured);
6595 }
6597 void OldGCAllocRegion::retire_region(HeapRegion* alloc_region,
6598 size_t allocated_bytes) {
6599 _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
6600 GCAllocForTenured);
6601 }
6602 // Heap region set verification
6604 class VerifyRegionListsClosure : public HeapRegionClosure {
6605 private:
6606 HeapRegionSet* _old_set;
6607 HeapRegionSet* _humongous_set;
6608 FreeRegionList* _free_list;
6610 public:
6611 HeapRegionSetCount _old_count;
6612 HeapRegionSetCount _humongous_count;
6613 HeapRegionSetCount _free_count;
6615 VerifyRegionListsClosure(HeapRegionSet* old_set,
6616 HeapRegionSet* humongous_set,
6617 FreeRegionList* free_list) :
6618 _old_set(old_set), _humongous_set(humongous_set), _free_list(free_list),
6619 _old_count(), _humongous_count(), _free_count(){ }
6621 bool doHeapRegion(HeapRegion* hr) {
6622 if (hr->continuesHumongous()) {
6623 return false;
6624 }
6626 if (hr->is_young()) {
6627 // TODO
6628 } else if (hr->startsHumongous()) {
6629 assert(hr->containing_set() == _humongous_set, err_msg("Heap region %u is starts humongous but not in humongous set.", hr->region_num()));
6630 _humongous_count.increment(1u, hr->capacity());
6631 } else if (hr->is_empty()) {
6632 assert(hr->containing_set() == _free_list, err_msg("Heap region %u is empty but not on the free list.", hr->region_num()));
6633 _free_count.increment(1u, hr->capacity());
6634 } else {
6635 assert(hr->containing_set() == _old_set, err_msg("Heap region %u is old but not in the old set.", hr->region_num()));
6636 _old_count.increment(1u, hr->capacity());
6637 }
6638 return false;
6639 }
6641 void verify_counts(HeapRegionSet* old_set, HeapRegionSet* humongous_set, FreeRegionList* free_list) {
6642 guarantee(old_set->length() == _old_count.length(), err_msg("Old set count mismatch. Expected %u, actual %u.", old_set->length(), _old_count.length()));
6643 guarantee(old_set->total_capacity_bytes() == _old_count.capacity(), err_msg("Old set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6644 old_set->total_capacity_bytes(), _old_count.capacity()));
6646 guarantee(humongous_set->length() == _humongous_count.length(), err_msg("Hum set count mismatch. Expected %u, actual %u.", humongous_set->length(), _humongous_count.length()));
6647 guarantee(humongous_set->total_capacity_bytes() == _humongous_count.capacity(), err_msg("Hum set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6648 humongous_set->total_capacity_bytes(), _humongous_count.capacity()));
6650 guarantee(free_list->length() == _free_count.length(), err_msg("Free list count mismatch. Expected %u, actual %u.", free_list->length(), _free_count.length()));
6651 guarantee(free_list->total_capacity_bytes() == _free_count.capacity(), err_msg("Free list capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT,
6652 free_list->total_capacity_bytes(), _free_count.capacity()));
6653 }
6654 };
6656 HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index,
6657 HeapWord* bottom) {
6658 HeapWord* end = bottom + HeapRegion::GrainWords;
6659 MemRegion mr(bottom, end);
6660 assert(_g1_reserved.contains(mr), "invariant");
6661 // This might return NULL if the allocation fails
6662 return new HeapRegion(hrs_index, _bot_shared, mr);
6663 }
6665 void G1CollectedHeap::verify_region_sets() {
6666 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
6668 // First, check the explicit lists.
6669 _free_list.verify_list();
6670 {
6671 // Given that a concurrent operation might be adding regions to
6672 // the secondary free list we have to take the lock before
6673 // verifying it.
6674 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
6675 _secondary_free_list.verify_list();
6676 }
6678 // If a concurrent region freeing operation is in progress it will
6679 // be difficult to correctly attributed any free regions we come
6680 // across to the correct free list given that they might belong to
6681 // one of several (free_list, secondary_free_list, any local lists,
6682 // etc.). So, if that's the case we will skip the rest of the
6683 // verification operation. Alternatively, waiting for the concurrent
6684 // operation to complete will have a non-trivial effect on the GC's
6685 // operation (no concurrent operation will last longer than the
6686 // interval between two calls to verification) and it might hide
6687 // any issues that we would like to catch during testing.
6688 if (free_regions_coming()) {
6689 return;
6690 }
6692 // Make sure we append the secondary_free_list on the free_list so
6693 // that all free regions we will come across can be safely
6694 // attributed to the free_list.
6695 append_secondary_free_list_if_not_empty_with_lock();
6697 // Finally, make sure that the region accounting in the lists is
6698 // consistent with what we see in the heap.
6700 VerifyRegionListsClosure cl(&_old_set, &_humongous_set, &_free_list);
6701 heap_region_iterate(&cl);
6702 cl.verify_counts(&_old_set, &_humongous_set, &_free_list);
6703 }
6705 // Optimized nmethod scanning
6707 class RegisterNMethodOopClosure: public OopClosure {
6708 G1CollectedHeap* _g1h;
6709 nmethod* _nm;
6711 template <class T> void do_oop_work(T* p) {
6712 T heap_oop = oopDesc::load_heap_oop(p);
6713 if (!oopDesc::is_null(heap_oop)) {
6714 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
6715 HeapRegion* hr = _g1h->heap_region_containing(obj);
6716 assert(!hr->continuesHumongous(),
6717 err_msg("trying to add code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
6718 " starting at "HR_FORMAT,
6719 _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
6721 // HeapRegion::add_strong_code_root() avoids adding duplicate
6722 // entries but having duplicates is OK since we "mark" nmethods
6723 // as visited when we scan the strong code root lists during the GC.
6724 hr->add_strong_code_root(_nm);
6725 assert(hr->rem_set()->strong_code_roots_list_contains(_nm),
6726 err_msg("failed to add code root "PTR_FORMAT" to remembered set of region "HR_FORMAT,
6727 _nm, HR_FORMAT_PARAMS(hr)));
6728 }
6729 }
6731 public:
6732 RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
6733 _g1h(g1h), _nm(nm) {}
6735 void do_oop(oop* p) { do_oop_work(p); }
6736 void do_oop(narrowOop* p) { do_oop_work(p); }
6737 };
6739 class UnregisterNMethodOopClosure: public OopClosure {
6740 G1CollectedHeap* _g1h;
6741 nmethod* _nm;
6743 template <class T> void do_oop_work(T* p) {
6744 T heap_oop = oopDesc::load_heap_oop(p);
6745 if (!oopDesc::is_null(heap_oop)) {
6746 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
6747 HeapRegion* hr = _g1h->heap_region_containing(obj);
6748 assert(!hr->continuesHumongous(),
6749 err_msg("trying to remove code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT
6750 " starting at "HR_FORMAT,
6751 _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())));
6753 hr->remove_strong_code_root(_nm);
6754 assert(!hr->rem_set()->strong_code_roots_list_contains(_nm),
6755 err_msg("failed to remove code root "PTR_FORMAT" of region "HR_FORMAT,
6756 _nm, HR_FORMAT_PARAMS(hr)));
6757 }
6758 }
6760 public:
6761 UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
6762 _g1h(g1h), _nm(nm) {}
6764 void do_oop(oop* p) { do_oop_work(p); }
6765 void do_oop(narrowOop* p) { do_oop_work(p); }
6766 };
6768 void G1CollectedHeap::register_nmethod(nmethod* nm) {
6769 CollectedHeap::register_nmethod(nm);
6771 guarantee(nm != NULL, "sanity");
6772 RegisterNMethodOopClosure reg_cl(this, nm);
6773 nm->oops_do(®_cl);
6774 }
6776 void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
6777 CollectedHeap::unregister_nmethod(nm);
6779 guarantee(nm != NULL, "sanity");
6780 UnregisterNMethodOopClosure reg_cl(this, nm);
6781 nm->oops_do(®_cl, true);
6782 }
6784 class MigrateCodeRootsHeapRegionClosure: public HeapRegionClosure {
6785 public:
6786 bool doHeapRegion(HeapRegion *hr) {
6787 assert(!hr->isHumongous(),
6788 err_msg("humongous region "HR_FORMAT" should not have been added to collection set",
6789 HR_FORMAT_PARAMS(hr)));
6790 hr->migrate_strong_code_roots();
6791 return false;
6792 }
6793 };
6795 void G1CollectedHeap::migrate_strong_code_roots() {
6796 MigrateCodeRootsHeapRegionClosure cl;
6797 double migrate_start = os::elapsedTime();
6798 collection_set_iterate(&cl);
6799 double migration_time_ms = (os::elapsedTime() - migrate_start) * 1000.0;
6800 g1_policy()->phase_times()->record_strong_code_root_migration_time(migration_time_ms);
6801 }
6803 void G1CollectedHeap::purge_code_root_memory() {
6804 double purge_start = os::elapsedTime();
6805 G1CodeRootSet::purge_chunks(G1CodeRootsChunkCacheKeepPercent);
6806 double purge_time_ms = (os::elapsedTime() - purge_start) * 1000.0;
6807 g1_policy()->phase_times()->record_strong_code_root_purge_time(purge_time_ms);
6808 }
6810 // Mark all the code roots that point into regions *not* in the
6811 // collection set.
6812 //
6813 // Note we do not want to use a "marking" CodeBlobToOopClosure while
6814 // walking the the code roots lists of regions not in the collection
6815 // set. Suppose we have an nmethod (M) that points to objects in two
6816 // separate regions - one in the collection set (R1) and one not (R2).
6817 // Using a "marking" CodeBlobToOopClosure here would result in "marking"
6818 // nmethod M when walking the code roots for R1. When we come to scan
6819 // the code roots for R2, we would see that M is already marked and it
6820 // would be skipped and the objects in R2 that are referenced from M
6821 // would not be evacuated.
6823 class MarkStrongCodeRootCodeBlobClosure: public CodeBlobClosure {
6825 class MarkStrongCodeRootOopClosure: public OopClosure {
6826 ConcurrentMark* _cm;
6827 HeapRegion* _hr;
6828 uint _worker_id;
6830 template <class T> void do_oop_work(T* p) {
6831 T heap_oop = oopDesc::load_heap_oop(p);
6832 if (!oopDesc::is_null(heap_oop)) {
6833 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
6834 // Only mark objects in the region (which is assumed
6835 // to be not in the collection set).
6836 if (_hr->is_in(obj)) {
6837 _cm->grayRoot(obj, (size_t) obj->size(), _worker_id);
6838 }
6839 }
6840 }
6842 public:
6843 MarkStrongCodeRootOopClosure(ConcurrentMark* cm, HeapRegion* hr, uint worker_id) :
6844 _cm(cm), _hr(hr), _worker_id(worker_id) {
6845 assert(!_hr->in_collection_set(), "sanity");
6846 }
6848 void do_oop(narrowOop* p) { do_oop_work(p); }
6849 void do_oop(oop* p) { do_oop_work(p); }
6850 };
6852 MarkStrongCodeRootOopClosure _oop_cl;
6854 public:
6855 MarkStrongCodeRootCodeBlobClosure(ConcurrentMark* cm, HeapRegion* hr, uint worker_id):
6856 _oop_cl(cm, hr, worker_id) {}
6858 void do_code_blob(CodeBlob* cb) {
6859 nmethod* nm = (cb == NULL) ? NULL : cb->as_nmethod_or_null();
6860 if (nm != NULL) {
6861 nm->oops_do(&_oop_cl);
6862 }
6863 }
6864 };
6866 class MarkStrongCodeRootsHRClosure: public HeapRegionClosure {
6867 G1CollectedHeap* _g1h;
6868 uint _worker_id;
6870 public:
6871 MarkStrongCodeRootsHRClosure(G1CollectedHeap* g1h, uint worker_id) :
6872 _g1h(g1h), _worker_id(worker_id) {}
6874 bool doHeapRegion(HeapRegion *hr) {
6875 HeapRegionRemSet* hrrs = hr->rem_set();
6876 if (hr->continuesHumongous()) {
6877 // Code roots should never be attached to a continuation of a humongous region
6878 assert(hrrs->strong_code_roots_list_length() == 0,
6879 err_msg("code roots should never be attached to continuations of humongous region "HR_FORMAT
6880 " starting at "HR_FORMAT", but has "SIZE_FORMAT,
6881 HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()),
6882 hrrs->strong_code_roots_list_length()));
6883 return false;
6884 }
6886 if (hr->in_collection_set()) {
6887 // Don't mark code roots into regions in the collection set here.
6888 // They will be marked when we scan them.
6889 return false;
6890 }
6892 MarkStrongCodeRootCodeBlobClosure cb_cl(_g1h->concurrent_mark(), hr, _worker_id);
6893 hr->strong_code_roots_do(&cb_cl);
6894 return false;
6895 }
6896 };
6898 void G1CollectedHeap::mark_strong_code_roots(uint worker_id) {
6899 MarkStrongCodeRootsHRClosure cl(this, worker_id);
6900 if (G1CollectedHeap::use_parallel_gc_threads()) {
6901 heap_region_par_iterate_chunked(&cl,
6902 worker_id,
6903 workers()->active_workers(),
6904 HeapRegion::ParMarkRootClaimValue);
6905 } else {
6906 heap_region_iterate(&cl);
6907 }
6908 }
6910 class RebuildStrongCodeRootClosure: public CodeBlobClosure {
6911 G1CollectedHeap* _g1h;
6913 public:
6914 RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :
6915 _g1h(g1h) {}
6917 void do_code_blob(CodeBlob* cb) {
6918 nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
6919 if (nm == NULL) {
6920 return;
6921 }
6923 if (ScavengeRootsInCode && nm->detect_scavenge_root_oops()) {
6924 _g1h->register_nmethod(nm);
6925 }
6926 }
6927 };
6929 void G1CollectedHeap::rebuild_strong_code_roots() {
6930 RebuildStrongCodeRootClosure blob_cl(this);
6931 CodeCache::blobs_do(&blob_cl);
6932 }