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