Fri, 19 Aug 2011 09:30:59 +0200
6814390: G1: remove the concept of non-generational G1
Summary: Removed the possibility to turn off generational mode for G1.
Reviewed-by: johnc, ysr, tonyp
1 /*
2 * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
25 #include "precompiled.hpp"
26 #include "code/icBuffer.hpp"
27 #include "gc_implementation/g1/bufferingOopClosure.hpp"
28 #include "gc_implementation/g1/concurrentG1Refine.hpp"
29 #include "gc_implementation/g1/concurrentG1RefineThread.hpp"
30 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
31 #include "gc_implementation/g1/g1AllocRegion.inline.hpp"
32 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
33 #include "gc_implementation/g1/g1CollectorPolicy.hpp"
34 #include "gc_implementation/g1/g1MarkSweep.hpp"
35 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
36 #include "gc_implementation/g1/g1RemSet.inline.hpp"
37 #include "gc_implementation/g1/heapRegionRemSet.hpp"
38 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
39 #include "gc_implementation/g1/vm_operations_g1.hpp"
40 #include "gc_implementation/shared/isGCActiveMark.hpp"
41 #include "memory/gcLocker.inline.hpp"
42 #include "memory/genOopClosures.inline.hpp"
43 #include "memory/generationSpec.hpp"
44 #include "oops/oop.inline.hpp"
45 #include "oops/oop.pcgc.inline.hpp"
46 #include "runtime/aprofiler.hpp"
47 #include "runtime/vmThread.hpp"
49 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
51 // turn it on so that the contents of the young list (scan-only /
52 // to-be-collected) are printed at "strategic" points before / during
53 // / after the collection --- this is useful for debugging
54 #define YOUNG_LIST_VERBOSE 0
55 // CURRENT STATUS
56 // This file is under construction. Search for "FIXME".
58 // INVARIANTS/NOTES
59 //
60 // All allocation activity covered by the G1CollectedHeap interface is
61 // serialized by acquiring the HeapLock. This happens in mem_allocate
62 // and allocate_new_tlab, which are the "entry" points to the
63 // allocation code from the rest of the JVM. (Note that this does not
64 // apply to TLAB allocation, which is not part of this interface: it
65 // is done by clients of this interface.)
67 // Local to this file.
69 class RefineCardTableEntryClosure: public CardTableEntryClosure {
70 SuspendibleThreadSet* _sts;
71 G1RemSet* _g1rs;
72 ConcurrentG1Refine* _cg1r;
73 bool _concurrent;
74 public:
75 RefineCardTableEntryClosure(SuspendibleThreadSet* sts,
76 G1RemSet* g1rs,
77 ConcurrentG1Refine* cg1r) :
78 _sts(sts), _g1rs(g1rs), _cg1r(cg1r), _concurrent(true)
79 {}
80 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
81 bool oops_into_cset = _g1rs->concurrentRefineOneCard(card_ptr, worker_i, false);
82 // This path is executed by the concurrent refine or mutator threads,
83 // concurrently, and so we do not care if card_ptr contains references
84 // that point into the collection set.
85 assert(!oops_into_cset, "should be");
87 if (_concurrent && _sts->should_yield()) {
88 // Caller will actually yield.
89 return false;
90 }
91 // Otherwise, we finished successfully; return true.
92 return true;
93 }
94 void set_concurrent(bool b) { _concurrent = b; }
95 };
98 class ClearLoggedCardTableEntryClosure: public CardTableEntryClosure {
99 int _calls;
100 G1CollectedHeap* _g1h;
101 CardTableModRefBS* _ctbs;
102 int _histo[256];
103 public:
104 ClearLoggedCardTableEntryClosure() :
105 _calls(0)
106 {
107 _g1h = G1CollectedHeap::heap();
108 _ctbs = (CardTableModRefBS*)_g1h->barrier_set();
109 for (int i = 0; i < 256; i++) _histo[i] = 0;
110 }
111 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
112 if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
113 _calls++;
114 unsigned char* ujb = (unsigned char*)card_ptr;
115 int ind = (int)(*ujb);
116 _histo[ind]++;
117 *card_ptr = -1;
118 }
119 return true;
120 }
121 int calls() { return _calls; }
122 void print_histo() {
123 gclog_or_tty->print_cr("Card table value histogram:");
124 for (int i = 0; i < 256; i++) {
125 if (_histo[i] != 0) {
126 gclog_or_tty->print_cr(" %d: %d", i, _histo[i]);
127 }
128 }
129 }
130 };
132 class RedirtyLoggedCardTableEntryClosure: public CardTableEntryClosure {
133 int _calls;
134 G1CollectedHeap* _g1h;
135 CardTableModRefBS* _ctbs;
136 public:
137 RedirtyLoggedCardTableEntryClosure() :
138 _calls(0)
139 {
140 _g1h = G1CollectedHeap::heap();
141 _ctbs = (CardTableModRefBS*)_g1h->barrier_set();
142 }
143 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
144 if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
145 _calls++;
146 *card_ptr = 0;
147 }
148 return true;
149 }
150 int calls() { return _calls; }
151 };
153 class RedirtyLoggedCardTableEntryFastClosure : public CardTableEntryClosure {
154 public:
155 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
156 *card_ptr = CardTableModRefBS::dirty_card_val();
157 return true;
158 }
159 };
161 YoungList::YoungList(G1CollectedHeap* g1h)
162 : _g1h(g1h), _head(NULL),
163 _length(0),
164 _last_sampled_rs_lengths(0),
165 _survivor_head(NULL), _survivor_tail(NULL), _survivor_length(0)
166 {
167 guarantee( check_list_empty(false), "just making sure..." );
168 }
170 void YoungList::push_region(HeapRegion *hr) {
171 assert(!hr->is_young(), "should not already be young");
172 assert(hr->get_next_young_region() == NULL, "cause it should!");
174 hr->set_next_young_region(_head);
175 _head = hr;
177 hr->set_young();
178 double yg_surv_rate = _g1h->g1_policy()->predict_yg_surv_rate((int)_length);
179 ++_length;
180 }
182 void YoungList::add_survivor_region(HeapRegion* hr) {
183 assert(hr->is_survivor(), "should be flagged as survivor region");
184 assert(hr->get_next_young_region() == NULL, "cause it should!");
186 hr->set_next_young_region(_survivor_head);
187 if (_survivor_head == NULL) {
188 _survivor_tail = hr;
189 }
190 _survivor_head = hr;
192 ++_survivor_length;
193 }
195 void YoungList::empty_list(HeapRegion* list) {
196 while (list != NULL) {
197 HeapRegion* next = list->get_next_young_region();
198 list->set_next_young_region(NULL);
199 list->uninstall_surv_rate_group();
200 list->set_not_young();
201 list = next;
202 }
203 }
205 void YoungList::empty_list() {
206 assert(check_list_well_formed(), "young list should be well formed");
208 empty_list(_head);
209 _head = NULL;
210 _length = 0;
212 empty_list(_survivor_head);
213 _survivor_head = NULL;
214 _survivor_tail = NULL;
215 _survivor_length = 0;
217 _last_sampled_rs_lengths = 0;
219 assert(check_list_empty(false), "just making sure...");
220 }
222 bool YoungList::check_list_well_formed() {
223 bool ret = true;
225 size_t length = 0;
226 HeapRegion* curr = _head;
227 HeapRegion* last = NULL;
228 while (curr != NULL) {
229 if (!curr->is_young()) {
230 gclog_or_tty->print_cr("### YOUNG REGION "PTR_FORMAT"-"PTR_FORMAT" "
231 "incorrectly tagged (y: %d, surv: %d)",
232 curr->bottom(), curr->end(),
233 curr->is_young(), curr->is_survivor());
234 ret = false;
235 }
236 ++length;
237 last = curr;
238 curr = curr->get_next_young_region();
239 }
240 ret = ret && (length == _length);
242 if (!ret) {
243 gclog_or_tty->print_cr("### YOUNG LIST seems not well formed!");
244 gclog_or_tty->print_cr("### list has %d entries, _length is %d",
245 length, _length);
246 }
248 return ret;
249 }
251 bool YoungList::check_list_empty(bool check_sample) {
252 bool ret = true;
254 if (_length != 0) {
255 gclog_or_tty->print_cr("### YOUNG LIST should have 0 length, not %d",
256 _length);
257 ret = false;
258 }
259 if (check_sample && _last_sampled_rs_lengths != 0) {
260 gclog_or_tty->print_cr("### YOUNG LIST has non-zero last sampled RS lengths");
261 ret = false;
262 }
263 if (_head != NULL) {
264 gclog_or_tty->print_cr("### YOUNG LIST does not have a NULL head");
265 ret = false;
266 }
267 if (!ret) {
268 gclog_or_tty->print_cr("### YOUNG LIST does not seem empty");
269 }
271 return ret;
272 }
274 void
275 YoungList::rs_length_sampling_init() {
276 _sampled_rs_lengths = 0;
277 _curr = _head;
278 }
280 bool
281 YoungList::rs_length_sampling_more() {
282 return _curr != NULL;
283 }
285 void
286 YoungList::rs_length_sampling_next() {
287 assert( _curr != NULL, "invariant" );
288 size_t rs_length = _curr->rem_set()->occupied();
290 _sampled_rs_lengths += rs_length;
292 // The current region may not yet have been added to the
293 // incremental collection set (it gets added when it is
294 // retired as the current allocation region).
295 if (_curr->in_collection_set()) {
296 // Update the collection set policy information for this region
297 _g1h->g1_policy()->update_incremental_cset_info(_curr, rs_length);
298 }
300 _curr = _curr->get_next_young_region();
301 if (_curr == NULL) {
302 _last_sampled_rs_lengths = _sampled_rs_lengths;
303 // gclog_or_tty->print_cr("last sampled RS lengths = %d", _last_sampled_rs_lengths);
304 }
305 }
307 void
308 YoungList::reset_auxilary_lists() {
309 guarantee( is_empty(), "young list should be empty" );
310 assert(check_list_well_formed(), "young list should be well formed");
312 // Add survivor regions to SurvRateGroup.
313 _g1h->g1_policy()->note_start_adding_survivor_regions();
314 _g1h->g1_policy()->finished_recalculating_age_indexes(true /* is_survivors */);
316 for (HeapRegion* curr = _survivor_head;
317 curr != NULL;
318 curr = curr->get_next_young_region()) {
319 _g1h->g1_policy()->set_region_survivors(curr);
321 // The region is a non-empty survivor so let's add it to
322 // the incremental collection set for the next evacuation
323 // pause.
324 _g1h->g1_policy()->add_region_to_incremental_cset_rhs(curr);
325 }
326 _g1h->g1_policy()->note_stop_adding_survivor_regions();
328 _head = _survivor_head;
329 _length = _survivor_length;
330 if (_survivor_head != NULL) {
331 assert(_survivor_tail != NULL, "cause it shouldn't be");
332 assert(_survivor_length > 0, "invariant");
333 _survivor_tail->set_next_young_region(NULL);
334 }
336 // Don't clear the survivor list handles until the start of
337 // the next evacuation pause - we need it in order to re-tag
338 // the survivor regions from this evacuation pause as 'young'
339 // at the start of the next.
341 _g1h->g1_policy()->finished_recalculating_age_indexes(false /* is_survivors */);
343 assert(check_list_well_formed(), "young list should be well formed");
344 }
346 void YoungList::print() {
347 HeapRegion* lists[] = {_head, _survivor_head};
348 const char* names[] = {"YOUNG", "SURVIVOR"};
350 for (unsigned int list = 0; list < ARRAY_SIZE(lists); ++list) {
351 gclog_or_tty->print_cr("%s LIST CONTENTS", names[list]);
352 HeapRegion *curr = lists[list];
353 if (curr == NULL)
354 gclog_or_tty->print_cr(" empty");
355 while (curr != NULL) {
356 gclog_or_tty->print_cr(" [%08x-%08x], t: %08x, P: %08x, N: %08x, C: %08x, "
357 "age: %4d, y: %d, surv: %d",
358 curr->bottom(), curr->end(),
359 curr->top(),
360 curr->prev_top_at_mark_start(),
361 curr->next_top_at_mark_start(),
362 curr->top_at_conc_mark_count(),
363 curr->age_in_surv_rate_group_cond(),
364 curr->is_young(),
365 curr->is_survivor());
366 curr = curr->get_next_young_region();
367 }
368 }
370 gclog_or_tty->print_cr("");
371 }
373 void G1CollectedHeap::push_dirty_cards_region(HeapRegion* hr)
374 {
375 // Claim the right to put the region on the dirty cards region list
376 // by installing a self pointer.
377 HeapRegion* next = hr->get_next_dirty_cards_region();
378 if (next == NULL) {
379 HeapRegion* res = (HeapRegion*)
380 Atomic::cmpxchg_ptr(hr, hr->next_dirty_cards_region_addr(),
381 NULL);
382 if (res == NULL) {
383 HeapRegion* head;
384 do {
385 // Put the region to the dirty cards region list.
386 head = _dirty_cards_region_list;
387 next = (HeapRegion*)
388 Atomic::cmpxchg_ptr(hr, &_dirty_cards_region_list, head);
389 if (next == head) {
390 assert(hr->get_next_dirty_cards_region() == hr,
391 "hr->get_next_dirty_cards_region() != hr");
392 if (next == NULL) {
393 // The last region in the list points to itself.
394 hr->set_next_dirty_cards_region(hr);
395 } else {
396 hr->set_next_dirty_cards_region(next);
397 }
398 }
399 } while (next != head);
400 }
401 }
402 }
404 HeapRegion* G1CollectedHeap::pop_dirty_cards_region()
405 {
406 HeapRegion* head;
407 HeapRegion* hr;
408 do {
409 head = _dirty_cards_region_list;
410 if (head == NULL) {
411 return NULL;
412 }
413 HeapRegion* new_head = head->get_next_dirty_cards_region();
414 if (head == new_head) {
415 // The last region.
416 new_head = NULL;
417 }
418 hr = (HeapRegion*)Atomic::cmpxchg_ptr(new_head, &_dirty_cards_region_list,
419 head);
420 } while (hr != head);
421 assert(hr != NULL, "invariant");
422 hr->set_next_dirty_cards_region(NULL);
423 return hr;
424 }
426 void G1CollectedHeap::stop_conc_gc_threads() {
427 _cg1r->stop();
428 _cmThread->stop();
429 }
431 #ifdef ASSERT
432 // A region is added to the collection set as it is retired
433 // so an address p can point to a region which will be in the
434 // collection set but has not yet been retired. This method
435 // therefore is only accurate during a GC pause after all
436 // regions have been retired. It is used for debugging
437 // to check if an nmethod has references to objects that can
438 // be move during a partial collection. Though it can be
439 // inaccurate, it is sufficient for G1 because the conservative
440 // implementation of is_scavengable() for G1 will indicate that
441 // all nmethods must be scanned during a partial collection.
442 bool G1CollectedHeap::is_in_partial_collection(const void* p) {
443 HeapRegion* hr = heap_region_containing(p);
444 return hr != NULL && hr->in_collection_set();
445 }
446 #endif
448 // Returns true if the reference points to an object that
449 // can move in an incremental collecction.
450 bool G1CollectedHeap::is_scavengable(const void* p) {
451 G1CollectedHeap* g1h = G1CollectedHeap::heap();
452 G1CollectorPolicy* g1p = g1h->g1_policy();
453 HeapRegion* hr = heap_region_containing(p);
454 if (hr == NULL) {
455 // perm gen (or null)
456 return false;
457 } else {
458 return !hr->isHumongous();
459 }
460 }
462 void G1CollectedHeap::check_ct_logs_at_safepoint() {
463 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
464 CardTableModRefBS* ct_bs = (CardTableModRefBS*)barrier_set();
466 // Count the dirty cards at the start.
467 CountNonCleanMemRegionClosure count1(this);
468 ct_bs->mod_card_iterate(&count1);
469 int orig_count = count1.n();
471 // First clear the logged cards.
472 ClearLoggedCardTableEntryClosure clear;
473 dcqs.set_closure(&clear);
474 dcqs.apply_closure_to_all_completed_buffers();
475 dcqs.iterate_closure_all_threads(false);
476 clear.print_histo();
478 // Now ensure that there's no dirty cards.
479 CountNonCleanMemRegionClosure count2(this);
480 ct_bs->mod_card_iterate(&count2);
481 if (count2.n() != 0) {
482 gclog_or_tty->print_cr("Card table has %d entries; %d originally",
483 count2.n(), orig_count);
484 }
485 guarantee(count2.n() == 0, "Card table should be clean.");
487 RedirtyLoggedCardTableEntryClosure redirty;
488 JavaThread::dirty_card_queue_set().set_closure(&redirty);
489 dcqs.apply_closure_to_all_completed_buffers();
490 dcqs.iterate_closure_all_threads(false);
491 gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",
492 clear.calls(), orig_count);
493 guarantee(redirty.calls() == clear.calls(),
494 "Or else mechanism is broken.");
496 CountNonCleanMemRegionClosure count3(this);
497 ct_bs->mod_card_iterate(&count3);
498 if (count3.n() != orig_count) {
499 gclog_or_tty->print_cr("Should have restored them all: orig = %d, final = %d.",
500 orig_count, count3.n());
501 guarantee(count3.n() >= orig_count, "Should have restored them all.");
502 }
504 JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
505 }
507 // Private class members.
509 G1CollectedHeap* G1CollectedHeap::_g1h;
511 // Private methods.
513 HeapRegion*
514 G1CollectedHeap::new_region_try_secondary_free_list() {
515 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
516 while (!_secondary_free_list.is_empty() || free_regions_coming()) {
517 if (!_secondary_free_list.is_empty()) {
518 if (G1ConcRegionFreeingVerbose) {
519 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
520 "secondary_free_list has "SIZE_FORMAT" entries",
521 _secondary_free_list.length());
522 }
523 // It looks as if there are free regions available on the
524 // secondary_free_list. Let's move them to the free_list and try
525 // again to allocate from it.
526 append_secondary_free_list();
528 assert(!_free_list.is_empty(), "if the secondary_free_list was not "
529 "empty we should have moved at least one entry to the free_list");
530 HeapRegion* res = _free_list.remove_head();
531 if (G1ConcRegionFreeingVerbose) {
532 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
533 "allocated "HR_FORMAT" from secondary_free_list",
534 HR_FORMAT_PARAMS(res));
535 }
536 return res;
537 }
539 // Wait here until we get notifed either when (a) there are no
540 // more free regions coming or (b) some regions have been moved on
541 // the secondary_free_list.
542 SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
543 }
545 if (G1ConcRegionFreeingVerbose) {
546 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
547 "could not allocate from secondary_free_list");
548 }
549 return NULL;
550 }
552 HeapRegion* G1CollectedHeap::new_region(size_t word_size, bool do_expand) {
553 assert(!isHumongous(word_size) ||
554 word_size <= (size_t) HeapRegion::GrainWords,
555 "the only time we use this to allocate a humongous region is "
556 "when we are allocating a single humongous region");
558 HeapRegion* res;
559 if (G1StressConcRegionFreeing) {
560 if (!_secondary_free_list.is_empty()) {
561 if (G1ConcRegionFreeingVerbose) {
562 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
563 "forced to look at the secondary_free_list");
564 }
565 res = new_region_try_secondary_free_list();
566 if (res != NULL) {
567 return res;
568 }
569 }
570 }
571 res = _free_list.remove_head_or_null();
572 if (res == NULL) {
573 if (G1ConcRegionFreeingVerbose) {
574 gclog_or_tty->print_cr("G1ConcRegionFreeing [region alloc] : "
575 "res == NULL, trying the secondary_free_list");
576 }
577 res = new_region_try_secondary_free_list();
578 }
579 if (res == NULL && do_expand) {
580 if (expand(word_size * HeapWordSize)) {
581 // Even though the heap was expanded, it might not have reached
582 // the desired size. So, we cannot assume that the allocation
583 // will succeed.
584 res = _free_list.remove_head_or_null();
585 }
586 }
587 return res;
588 }
590 size_t G1CollectedHeap::humongous_obj_allocate_find_first(size_t num_regions,
591 size_t word_size) {
592 assert(isHumongous(word_size), "word_size should be humongous");
593 assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
595 size_t first = G1_NULL_HRS_INDEX;
596 if (num_regions == 1) {
597 // Only one region to allocate, no need to go through the slower
598 // path. The caller will attempt the expasion if this fails, so
599 // let's not try to expand here too.
600 HeapRegion* hr = new_region(word_size, false /* do_expand */);
601 if (hr != NULL) {
602 first = hr->hrs_index();
603 } else {
604 first = G1_NULL_HRS_INDEX;
605 }
606 } else {
607 // We can't allocate humongous regions while cleanupComplete() is
608 // running, since some of the regions we find to be empty might not
609 // yet be added to the free list and it is not straightforward to
610 // know which list they are on so that we can remove them. Note
611 // that we only need to do this if we need to allocate more than
612 // one region to satisfy the current humongous allocation
613 // request. If we are only allocating one region we use the common
614 // region allocation code (see above).
615 wait_while_free_regions_coming();
616 append_secondary_free_list_if_not_empty_with_lock();
618 if (free_regions() >= num_regions) {
619 first = _hrs.find_contiguous(num_regions);
620 if (first != G1_NULL_HRS_INDEX) {
621 for (size_t i = first; i < first + num_regions; ++i) {
622 HeapRegion* hr = region_at(i);
623 assert(hr->is_empty(), "sanity");
624 assert(is_on_master_free_list(hr), "sanity");
625 hr->set_pending_removal(true);
626 }
627 _free_list.remove_all_pending(num_regions);
628 }
629 }
630 }
631 return first;
632 }
634 HeapWord*
635 G1CollectedHeap::humongous_obj_allocate_initialize_regions(size_t first,
636 size_t num_regions,
637 size_t word_size) {
638 assert(first != G1_NULL_HRS_INDEX, "pre-condition");
639 assert(isHumongous(word_size), "word_size should be humongous");
640 assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
642 // Index of last region in the series + 1.
643 size_t last = first + num_regions;
645 // We need to initialize the region(s) we just discovered. This is
646 // a bit tricky given that it can happen concurrently with
647 // refinement threads refining cards on these regions and
648 // potentially wanting to refine the BOT as they are scanning
649 // those cards (this can happen shortly after a cleanup; see CR
650 // 6991377). So we have to set up the region(s) carefully and in
651 // a specific order.
653 // The word size sum of all the regions we will allocate.
654 size_t word_size_sum = num_regions * HeapRegion::GrainWords;
655 assert(word_size <= word_size_sum, "sanity");
657 // This will be the "starts humongous" region.
658 HeapRegion* first_hr = region_at(first);
659 // The header of the new object will be placed at the bottom of
660 // the first region.
661 HeapWord* new_obj = first_hr->bottom();
662 // This will be the new end of the first region in the series that
663 // should also match the end of the last region in the seriers.
664 HeapWord* new_end = new_obj + word_size_sum;
665 // This will be the new top of the first region that will reflect
666 // this allocation.
667 HeapWord* new_top = new_obj + word_size;
669 // First, we need to zero the header of the space that we will be
670 // allocating. When we update top further down, some refinement
671 // threads might try to scan the region. By zeroing the header we
672 // ensure that any thread that will try to scan the region will
673 // come across the zero klass word and bail out.
674 //
675 // NOTE: It would not have been correct to have used
676 // CollectedHeap::fill_with_object() and make the space look like
677 // an int array. The thread that is doing the allocation will
678 // later update the object header to a potentially different array
679 // type and, for a very short period of time, the klass and length
680 // fields will be inconsistent. This could cause a refinement
681 // thread to calculate the object size incorrectly.
682 Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
684 // We will set up the first region as "starts humongous". This
685 // will also update the BOT covering all the regions to reflect
686 // that there is a single object that starts at the bottom of the
687 // first region.
688 first_hr->set_startsHumongous(new_top, new_end);
690 // Then, if there are any, we will set up the "continues
691 // humongous" regions.
692 HeapRegion* hr = NULL;
693 for (size_t i = first + 1; i < last; ++i) {
694 hr = region_at(i);
695 hr->set_continuesHumongous(first_hr);
696 }
697 // If we have "continues humongous" regions (hr != NULL), then the
698 // end of the last one should match new_end.
699 assert(hr == NULL || hr->end() == new_end, "sanity");
701 // Up to this point no concurrent thread would have been able to
702 // do any scanning on any region in this series. All the top
703 // fields still point to bottom, so the intersection between
704 // [bottom,top] and [card_start,card_end] will be empty. Before we
705 // update the top fields, we'll do a storestore to make sure that
706 // no thread sees the update to top before the zeroing of the
707 // object header and the BOT initialization.
708 OrderAccess::storestore();
710 // Now that the BOT and the object header have been initialized,
711 // we can update top of the "starts humongous" region.
712 assert(first_hr->bottom() < new_top && new_top <= first_hr->end(),
713 "new_top should be in this region");
714 first_hr->set_top(new_top);
715 if (_hr_printer.is_active()) {
716 HeapWord* bottom = first_hr->bottom();
717 HeapWord* end = first_hr->orig_end();
718 if ((first + 1) == last) {
719 // the series has a single humongous region
720 _hr_printer.alloc(G1HRPrinter::SingleHumongous, first_hr, new_top);
721 } else {
722 // the series has more than one humongous regions
723 _hr_printer.alloc(G1HRPrinter::StartsHumongous, first_hr, end);
724 }
725 }
727 // Now, we will update the top fields of the "continues humongous"
728 // regions. The reason we need to do this is that, otherwise,
729 // these regions would look empty and this will confuse parts of
730 // G1. For example, the code that looks for a consecutive number
731 // of empty regions will consider them empty and try to
732 // re-allocate them. We can extend is_empty() to also include
733 // !continuesHumongous(), but it is easier to just update the top
734 // fields here. The way we set top for all regions (i.e., top ==
735 // end for all regions but the last one, top == new_top for the
736 // last one) is actually used when we will free up the humongous
737 // region in free_humongous_region().
738 hr = NULL;
739 for (size_t i = first + 1; i < last; ++i) {
740 hr = region_at(i);
741 if ((i + 1) == last) {
742 // last continues humongous region
743 assert(hr->bottom() < new_top && new_top <= hr->end(),
744 "new_top should fall on this region");
745 hr->set_top(new_top);
746 _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, new_top);
747 } else {
748 // not last one
749 assert(new_top > hr->end(), "new_top should be above this region");
750 hr->set_top(hr->end());
751 _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, hr->end());
752 }
753 }
754 // If we have continues humongous regions (hr != NULL), then the
755 // end of the last one should match new_end and its top should
756 // match new_top.
757 assert(hr == NULL ||
758 (hr->end() == new_end && hr->top() == new_top), "sanity");
760 assert(first_hr->used() == word_size * HeapWordSize, "invariant");
761 _summary_bytes_used += first_hr->used();
762 _humongous_set.add(first_hr);
764 return new_obj;
765 }
767 // If could fit into free regions w/o expansion, try.
768 // Otherwise, if can expand, do so.
769 // Otherwise, if using ex regions might help, try with ex given back.
770 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {
771 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
773 verify_region_sets_optional();
775 size_t num_regions =
776 round_to(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords;
777 size_t x_size = expansion_regions();
778 size_t fs = _hrs.free_suffix();
779 size_t first = humongous_obj_allocate_find_first(num_regions, word_size);
780 if (first == G1_NULL_HRS_INDEX) {
781 // The only thing we can do now is attempt expansion.
782 if (fs + x_size >= num_regions) {
783 // If the number of regions we're trying to allocate for this
784 // object is at most the number of regions in the free suffix,
785 // then the call to humongous_obj_allocate_find_first() above
786 // should have succeeded and we wouldn't be here.
787 //
788 // We should only be trying to expand when the free suffix is
789 // not sufficient for the object _and_ we have some expansion
790 // room available.
791 assert(num_regions > fs, "earlier allocation should have succeeded");
793 if (expand((num_regions - fs) * HeapRegion::GrainBytes)) {
794 // Even though the heap was expanded, it might not have
795 // reached the desired size. So, we cannot assume that the
796 // allocation will succeed.
797 first = humongous_obj_allocate_find_first(num_regions, word_size);
798 }
799 }
800 }
802 HeapWord* result = NULL;
803 if (first != G1_NULL_HRS_INDEX) {
804 result =
805 humongous_obj_allocate_initialize_regions(first, num_regions, word_size);
806 assert(result != NULL, "it should always return a valid result");
807 }
809 verify_region_sets_optional();
811 return result;
812 }
814 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t word_size) {
815 assert_heap_not_locked_and_not_at_safepoint();
816 assert(!isHumongous(word_size), "we do not allow humongous TLABs");
818 unsigned int dummy_gc_count_before;
819 return attempt_allocation(word_size, &dummy_gc_count_before);
820 }
822 HeapWord*
823 G1CollectedHeap::mem_allocate(size_t word_size,
824 bool* gc_overhead_limit_was_exceeded) {
825 assert_heap_not_locked_and_not_at_safepoint();
827 // Loop until the allocation is satisified, or unsatisfied after GC.
828 for (int try_count = 1; /* we'll return */; try_count += 1) {
829 unsigned int gc_count_before;
831 HeapWord* result = NULL;
832 if (!isHumongous(word_size)) {
833 result = attempt_allocation(word_size, &gc_count_before);
834 } else {
835 result = attempt_allocation_humongous(word_size, &gc_count_before);
836 }
837 if (result != NULL) {
838 return result;
839 }
841 // Create the garbage collection operation...
842 VM_G1CollectForAllocation op(gc_count_before, word_size);
843 // ...and get the VM thread to execute it.
844 VMThread::execute(&op);
846 if (op.prologue_succeeded() && op.pause_succeeded()) {
847 // If the operation was successful we'll return the result even
848 // if it is NULL. If the allocation attempt failed immediately
849 // after a Full GC, it's unlikely we'll be able to allocate now.
850 HeapWord* result = op.result();
851 if (result != NULL && !isHumongous(word_size)) {
852 // Allocations that take place on VM operations do not do any
853 // card dirtying and we have to do it here. We only have to do
854 // this for non-humongous allocations, though.
855 dirty_young_block(result, word_size);
856 }
857 return result;
858 } else {
859 assert(op.result() == NULL,
860 "the result should be NULL if the VM op did not succeed");
861 }
863 // Give a warning if we seem to be looping forever.
864 if ((QueuedAllocationWarningCount > 0) &&
865 (try_count % QueuedAllocationWarningCount == 0)) {
866 warning("G1CollectedHeap::mem_allocate retries %d times", try_count);
867 }
868 }
870 ShouldNotReachHere();
871 return NULL;
872 }
874 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size,
875 unsigned int *gc_count_before_ret) {
876 // Make sure you read the note in attempt_allocation_humongous().
878 assert_heap_not_locked_and_not_at_safepoint();
879 assert(!isHumongous(word_size), "attempt_allocation_slow() should not "
880 "be called for humongous allocation requests");
882 // We should only get here after the first-level allocation attempt
883 // (attempt_allocation()) failed to allocate.
885 // We will loop until a) we manage to successfully perform the
886 // allocation or b) we successfully schedule a collection which
887 // fails to perform the allocation. b) is the only case when we'll
888 // return NULL.
889 HeapWord* result = NULL;
890 for (int try_count = 1; /* we'll return */; try_count += 1) {
891 bool should_try_gc;
892 unsigned int gc_count_before;
894 {
895 MutexLockerEx x(Heap_lock);
897 result = _mutator_alloc_region.attempt_allocation_locked(word_size,
898 false /* bot_updates */);
899 if (result != NULL) {
900 return result;
901 }
903 // If we reach here, attempt_allocation_locked() above failed to
904 // allocate a new region. So the mutator alloc region should be NULL.
905 assert(_mutator_alloc_region.get() == NULL, "only way to get here");
907 if (GC_locker::is_active_and_needs_gc()) {
908 if (g1_policy()->can_expand_young_list()) {
909 result = _mutator_alloc_region.attempt_allocation_force(word_size,
910 false /* bot_updates */);
911 if (result != NULL) {
912 return result;
913 }
914 }
915 should_try_gc = false;
916 } else {
917 // Read the GC count while still holding the Heap_lock.
918 gc_count_before = SharedHeap::heap()->total_collections();
919 should_try_gc = true;
920 }
921 }
923 if (should_try_gc) {
924 bool succeeded;
925 result = do_collection_pause(word_size, gc_count_before, &succeeded);
926 if (result != NULL) {
927 assert(succeeded, "only way to get back a non-NULL result");
928 return result;
929 }
931 if (succeeded) {
932 // If we get here we successfully scheduled a collection which
933 // failed to allocate. No point in trying to allocate
934 // further. We'll just return NULL.
935 MutexLockerEx x(Heap_lock);
936 *gc_count_before_ret = SharedHeap::heap()->total_collections();
937 return NULL;
938 }
939 } else {
940 GC_locker::stall_until_clear();
941 }
943 // We can reach here if we were unsuccessul in scheduling a
944 // collection (because another thread beat us to it) or if we were
945 // stalled due to the GC locker. In either can we should retry the
946 // allocation attempt in case another thread successfully
947 // performed a collection and reclaimed enough space. We do the
948 // first attempt (without holding the Heap_lock) here and the
949 // follow-on attempt will be at the start of the next loop
950 // iteration (after taking the Heap_lock).
951 result = _mutator_alloc_region.attempt_allocation(word_size,
952 false /* bot_updates */);
953 if (result != NULL ){
954 return result;
955 }
957 // Give a warning if we seem to be looping forever.
958 if ((QueuedAllocationWarningCount > 0) &&
959 (try_count % QueuedAllocationWarningCount == 0)) {
960 warning("G1CollectedHeap::attempt_allocation_slow() "
961 "retries %d times", try_count);
962 }
963 }
965 ShouldNotReachHere();
966 return NULL;
967 }
969 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size,
970 unsigned int * gc_count_before_ret) {
971 // The structure of this method has a lot of similarities to
972 // attempt_allocation_slow(). The reason these two were not merged
973 // into a single one is that such a method would require several "if
974 // allocation is not humongous do this, otherwise do that"
975 // conditional paths which would obscure its flow. In fact, an early
976 // version of this code did use a unified method which was harder to
977 // follow and, as a result, it had subtle bugs that were hard to
978 // track down. So keeping these two methods separate allows each to
979 // be more readable. It will be good to keep these two in sync as
980 // much as possible.
982 assert_heap_not_locked_and_not_at_safepoint();
983 assert(isHumongous(word_size), "attempt_allocation_humongous() "
984 "should only be called for humongous allocations");
986 // We will loop until a) we manage to successfully perform the
987 // allocation or b) we successfully schedule a collection which
988 // fails to perform the allocation. b) is the only case when we'll
989 // return NULL.
990 HeapWord* result = NULL;
991 for (int try_count = 1; /* we'll return */; try_count += 1) {
992 bool should_try_gc;
993 unsigned int gc_count_before;
995 {
996 MutexLockerEx x(Heap_lock);
998 // Given that humongous objects are not allocated in young
999 // regions, we'll first try to do the allocation without doing a
1000 // collection hoping that there's enough space in the heap.
1001 result = humongous_obj_allocate(word_size);
1002 if (result != NULL) {
1003 return result;
1004 }
1006 if (GC_locker::is_active_and_needs_gc()) {
1007 should_try_gc = false;
1008 } else {
1009 // Read the GC count while still holding the Heap_lock.
1010 gc_count_before = SharedHeap::heap()->total_collections();
1011 should_try_gc = true;
1012 }
1013 }
1015 if (should_try_gc) {
1016 // If we failed to allocate the humongous object, we should try to
1017 // do a collection pause (if we're allowed) in case it reclaims
1018 // enough space for the allocation to succeed after the pause.
1020 bool succeeded;
1021 result = do_collection_pause(word_size, gc_count_before, &succeeded);
1022 if (result != NULL) {
1023 assert(succeeded, "only way to get back a non-NULL result");
1024 return result;
1025 }
1027 if (succeeded) {
1028 // If we get here we successfully scheduled a collection which
1029 // failed to allocate. No point in trying to allocate
1030 // further. We'll just return NULL.
1031 MutexLockerEx x(Heap_lock);
1032 *gc_count_before_ret = SharedHeap::heap()->total_collections();
1033 return NULL;
1034 }
1035 } else {
1036 GC_locker::stall_until_clear();
1037 }
1039 // We can reach here if we were unsuccessul in scheduling a
1040 // collection (because another thread beat us to it) or if we were
1041 // stalled due to the GC locker. In either can we should retry the
1042 // allocation attempt in case another thread successfully
1043 // performed a collection and reclaimed enough space. Give a
1044 // warning if we seem to be looping forever.
1046 if ((QueuedAllocationWarningCount > 0) &&
1047 (try_count % QueuedAllocationWarningCount == 0)) {
1048 warning("G1CollectedHeap::attempt_allocation_humongous() "
1049 "retries %d times", try_count);
1050 }
1051 }
1053 ShouldNotReachHere();
1054 return NULL;
1055 }
1057 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
1058 bool expect_null_mutator_alloc_region) {
1059 assert_at_safepoint(true /* should_be_vm_thread */);
1060 assert(_mutator_alloc_region.get() == NULL ||
1061 !expect_null_mutator_alloc_region,
1062 "the current alloc region was unexpectedly found to be non-NULL");
1064 if (!isHumongous(word_size)) {
1065 return _mutator_alloc_region.attempt_allocation_locked(word_size,
1066 false /* bot_updates */);
1067 } else {
1068 return humongous_obj_allocate(word_size);
1069 }
1071 ShouldNotReachHere();
1072 }
1074 class PostMCRemSetClearClosure: public HeapRegionClosure {
1075 ModRefBarrierSet* _mr_bs;
1076 public:
1077 PostMCRemSetClearClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {}
1078 bool doHeapRegion(HeapRegion* r) {
1079 r->reset_gc_time_stamp();
1080 if (r->continuesHumongous())
1081 return false;
1082 HeapRegionRemSet* hrrs = r->rem_set();
1083 if (hrrs != NULL) hrrs->clear();
1084 // You might think here that we could clear just the cards
1085 // corresponding to the used region. But no: if we leave a dirty card
1086 // in a region we might allocate into, then it would prevent that card
1087 // from being enqueued, and cause it to be missed.
1088 // Re: the performance cost: we shouldn't be doing full GC anyway!
1089 _mr_bs->clear(MemRegion(r->bottom(), r->end()));
1090 return false;
1091 }
1092 };
1095 class PostMCRemSetInvalidateClosure: public HeapRegionClosure {
1096 ModRefBarrierSet* _mr_bs;
1097 public:
1098 PostMCRemSetInvalidateClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {}
1099 bool doHeapRegion(HeapRegion* r) {
1100 if (r->continuesHumongous()) return false;
1101 if (r->used_region().word_size() != 0) {
1102 _mr_bs->invalidate(r->used_region(), true /*whole heap*/);
1103 }
1104 return false;
1105 }
1106 };
1108 class RebuildRSOutOfRegionClosure: public HeapRegionClosure {
1109 G1CollectedHeap* _g1h;
1110 UpdateRSOopClosure _cl;
1111 int _worker_i;
1112 public:
1113 RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, int worker_i = 0) :
1114 _cl(g1->g1_rem_set(), worker_i),
1115 _worker_i(worker_i),
1116 _g1h(g1)
1117 { }
1119 bool doHeapRegion(HeapRegion* r) {
1120 if (!r->continuesHumongous()) {
1121 _cl.set_from(r);
1122 r->oop_iterate(&_cl);
1123 }
1124 return false;
1125 }
1126 };
1128 class ParRebuildRSTask: public AbstractGangTask {
1129 G1CollectedHeap* _g1;
1130 public:
1131 ParRebuildRSTask(G1CollectedHeap* g1)
1132 : AbstractGangTask("ParRebuildRSTask"),
1133 _g1(g1)
1134 { }
1136 void work(int i) {
1137 RebuildRSOutOfRegionClosure rebuild_rs(_g1, i);
1138 _g1->heap_region_par_iterate_chunked(&rebuild_rs, i,
1139 HeapRegion::RebuildRSClaimValue);
1140 }
1141 };
1143 class PostCompactionPrinterClosure: public HeapRegionClosure {
1144 private:
1145 G1HRPrinter* _hr_printer;
1146 public:
1147 bool doHeapRegion(HeapRegion* hr) {
1148 assert(!hr->is_young(), "not expecting to find young regions");
1149 // We only generate output for non-empty regions.
1150 if (!hr->is_empty()) {
1151 if (!hr->isHumongous()) {
1152 _hr_printer->post_compaction(hr, G1HRPrinter::Old);
1153 } else if (hr->startsHumongous()) {
1154 if (hr->capacity() == (size_t) HeapRegion::GrainBytes) {
1155 // single humongous region
1156 _hr_printer->post_compaction(hr, G1HRPrinter::SingleHumongous);
1157 } else {
1158 _hr_printer->post_compaction(hr, G1HRPrinter::StartsHumongous);
1159 }
1160 } else {
1161 assert(hr->continuesHumongous(), "only way to get here");
1162 _hr_printer->post_compaction(hr, G1HRPrinter::ContinuesHumongous);
1163 }
1164 }
1165 return false;
1166 }
1168 PostCompactionPrinterClosure(G1HRPrinter* hr_printer)
1169 : _hr_printer(hr_printer) { }
1170 };
1172 bool G1CollectedHeap::do_collection(bool explicit_gc,
1173 bool clear_all_soft_refs,
1174 size_t word_size) {
1175 assert_at_safepoint(true /* should_be_vm_thread */);
1177 if (GC_locker::check_active_before_gc()) {
1178 return false;
1179 }
1181 SvcGCMarker sgcm(SvcGCMarker::FULL);
1182 ResourceMark rm;
1184 if (PrintHeapAtGC) {
1185 Universe::print_heap_before_gc();
1186 }
1188 verify_region_sets_optional();
1190 const bool do_clear_all_soft_refs = clear_all_soft_refs ||
1191 collector_policy()->should_clear_all_soft_refs();
1193 ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());
1195 {
1196 IsGCActiveMark x;
1198 // Timing
1199 bool system_gc = (gc_cause() == GCCause::_java_lang_system_gc);
1200 assert(!system_gc || explicit_gc, "invariant");
1201 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
1202 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
1203 TraceTime t(system_gc ? "Full GC (System.gc())" : "Full GC",
1204 PrintGC, true, gclog_or_tty);
1206 TraceCollectorStats tcs(g1mm()->full_collection_counters());
1207 TraceMemoryManagerStats tms(true /* fullGC */, gc_cause());
1209 double start = os::elapsedTime();
1210 g1_policy()->record_full_collection_start();
1212 wait_while_free_regions_coming();
1213 append_secondary_free_list_if_not_empty_with_lock();
1215 gc_prologue(true);
1216 increment_total_collections(true /* full gc */);
1218 size_t g1h_prev_used = used();
1219 assert(used() == recalculate_used(), "Should be equal");
1221 if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) {
1222 HandleMark hm; // Discard invalid handles created during verification
1223 gclog_or_tty->print(" VerifyBeforeGC:");
1224 prepare_for_verify();
1225 Universe::verify(/* allow dirty */ true,
1226 /* silent */ false,
1227 /* option */ VerifyOption_G1UsePrevMarking);
1229 }
1231 COMPILER2_PRESENT(DerivedPointerTable::clear());
1233 // We want to discover references, but not process them yet.
1234 // This mode is disabled in
1235 // instanceRefKlass::process_discovered_references if the
1236 // generation does some collection work, or
1237 // instanceRefKlass::enqueue_discovered_references if the
1238 // generation returns without doing any work.
1239 ref_processor()->disable_discovery();
1240 ref_processor()->abandon_partial_discovery();
1241 ref_processor()->verify_no_references_recorded();
1243 // Abandon current iterations of concurrent marking and concurrent
1244 // refinement, if any are in progress.
1245 concurrent_mark()->abort();
1247 // Make sure we'll choose a new allocation region afterwards.
1248 release_mutator_alloc_region();
1249 abandon_gc_alloc_regions();
1250 g1_rem_set()->cleanupHRRS();
1251 tear_down_region_lists();
1253 // We should call this after we retire any currently active alloc
1254 // regions so that all the ALLOC / RETIRE events are generated
1255 // before the start GC event.
1256 _hr_printer.start_gc(true /* full */, (size_t) total_collections());
1258 // We may have added regions to the current incremental collection
1259 // set between the last GC or pause and now. We need to clear the
1260 // incremental collection set and then start rebuilding it afresh
1261 // after this full GC.
1262 abandon_collection_set(g1_policy()->inc_cset_head());
1263 g1_policy()->clear_incremental_cset();
1264 g1_policy()->stop_incremental_cset_building();
1266 empty_young_list();
1267 g1_policy()->set_full_young_gcs(true);
1269 // See the comment in G1CollectedHeap::ref_processing_init() about
1270 // how reference processing currently works in G1.
1272 // Temporarily make reference _discovery_ single threaded (non-MT).
1273 ReferenceProcessorMTDiscoveryMutator rp_disc_ser(ref_processor(), false);
1275 // Temporarily make refs discovery atomic
1276 ReferenceProcessorAtomicMutator rp_disc_atomic(ref_processor(), true);
1278 // Temporarily clear _is_alive_non_header
1279 ReferenceProcessorIsAliveMutator rp_is_alive_null(ref_processor(), NULL);
1281 ref_processor()->enable_discovery();
1282 ref_processor()->setup_policy(do_clear_all_soft_refs);
1283 // Do collection work
1284 {
1285 HandleMark hm; // Discard invalid handles created during gc
1286 G1MarkSweep::invoke_at_safepoint(ref_processor(), do_clear_all_soft_refs);
1287 }
1288 assert(free_regions() == 0, "we should not have added any free regions");
1289 rebuild_region_lists();
1291 _summary_bytes_used = recalculate_used();
1293 ref_processor()->enqueue_discovered_references();
1295 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
1297 MemoryService::track_memory_usage();
1299 if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
1300 HandleMark hm; // Discard invalid handles created during verification
1301 gclog_or_tty->print(" VerifyAfterGC:");
1302 prepare_for_verify();
1303 Universe::verify(/* allow dirty */ false,
1304 /* silent */ false,
1305 /* option */ VerifyOption_G1UsePrevMarking);
1307 }
1308 NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
1310 reset_gc_time_stamp();
1311 // Since everything potentially moved, we will clear all remembered
1312 // sets, and clear all cards. Later we will rebuild remebered
1313 // sets. We will also reset the GC time stamps of the regions.
1314 PostMCRemSetClearClosure rs_clear(mr_bs());
1315 heap_region_iterate(&rs_clear);
1317 // Resize the heap if necessary.
1318 resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size);
1320 if (_hr_printer.is_active()) {
1321 // We should do this after we potentially resize the heap so
1322 // that all the COMMIT / UNCOMMIT events are generated before
1323 // the end GC event.
1325 PostCompactionPrinterClosure cl(hr_printer());
1326 heap_region_iterate(&cl);
1328 _hr_printer.end_gc(true /* full */, (size_t) total_collections());
1329 }
1331 if (_cg1r->use_cache()) {
1332 _cg1r->clear_and_record_card_counts();
1333 _cg1r->clear_hot_cache();
1334 }
1336 // Rebuild remembered sets of all regions.
1338 if (G1CollectedHeap::use_parallel_gc_threads()) {
1339 ParRebuildRSTask rebuild_rs_task(this);
1340 assert(check_heap_region_claim_values(
1341 HeapRegion::InitialClaimValue), "sanity check");
1342 set_par_threads(workers()->total_workers());
1343 workers()->run_task(&rebuild_rs_task);
1344 set_par_threads(0);
1345 assert(check_heap_region_claim_values(
1346 HeapRegion::RebuildRSClaimValue), "sanity check");
1347 reset_heap_region_claim_values();
1348 } else {
1349 RebuildRSOutOfRegionClosure rebuild_rs(this);
1350 heap_region_iterate(&rebuild_rs);
1351 }
1353 if (PrintGC) {
1354 print_size_transition(gclog_or_tty, g1h_prev_used, used(), capacity());
1355 }
1357 if (true) { // FIXME
1358 // Ask the permanent generation to adjust size for full collections
1359 perm()->compute_new_size();
1360 }
1362 // Start a new incremental collection set for the next pause
1363 assert(g1_policy()->collection_set() == NULL, "must be");
1364 g1_policy()->start_incremental_cset_building();
1366 // Clear the _cset_fast_test bitmap in anticipation of adding
1367 // regions to the incremental collection set for the next
1368 // evacuation pause.
1369 clear_cset_fast_test();
1371 init_mutator_alloc_region();
1373 double end = os::elapsedTime();
1374 g1_policy()->record_full_collection_end();
1376 #ifdef TRACESPINNING
1377 ParallelTaskTerminator::print_termination_counts();
1378 #endif
1380 gc_epilogue(true);
1382 // Discard all rset updates
1383 JavaThread::dirty_card_queue_set().abandon_logs();
1384 assert(!G1DeferredRSUpdate
1385 || (G1DeferredRSUpdate && (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any");
1386 }
1388 _young_list->reset_sampled_info();
1389 // At this point there should be no regions in the
1390 // entire heap tagged as young.
1391 assert( check_young_list_empty(true /* check_heap */),
1392 "young list should be empty at this point");
1394 // Update the number of full collections that have been completed.
1395 increment_full_collections_completed(false /* concurrent */);
1397 _hrs.verify_optional();
1398 verify_region_sets_optional();
1400 if (PrintHeapAtGC) {
1401 Universe::print_heap_after_gc();
1402 }
1403 g1mm()->update_counters();
1405 return true;
1406 }
1408 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1409 // do_collection() will return whether it succeeded in performing
1410 // the GC. Currently, there is no facility on the
1411 // do_full_collection() API to notify the caller than the collection
1412 // did not succeed (e.g., because it was locked out by the GC
1413 // locker). So, right now, we'll ignore the return value.
1414 bool dummy = do_collection(true, /* explicit_gc */
1415 clear_all_soft_refs,
1416 0 /* word_size */);
1417 }
1419 // This code is mostly copied from TenuredGeneration.
1420 void
1421 G1CollectedHeap::
1422 resize_if_necessary_after_full_collection(size_t word_size) {
1423 assert(MinHeapFreeRatio <= MaxHeapFreeRatio, "sanity check");
1425 // Include the current allocation, if any, and bytes that will be
1426 // pre-allocated to support collections, as "used".
1427 const size_t used_after_gc = used();
1428 const size_t capacity_after_gc = capacity();
1429 const size_t free_after_gc = capacity_after_gc - used_after_gc;
1431 // This is enforced in arguments.cpp.
1432 assert(MinHeapFreeRatio <= MaxHeapFreeRatio,
1433 "otherwise the code below doesn't make sense");
1435 // We don't have floating point command-line arguments
1436 const double minimum_free_percentage = (double) MinHeapFreeRatio / 100.0;
1437 const double maximum_used_percentage = 1.0 - minimum_free_percentage;
1438 const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100.0;
1439 const double minimum_used_percentage = 1.0 - maximum_free_percentage;
1441 const size_t min_heap_size = collector_policy()->min_heap_byte_size();
1442 const size_t max_heap_size = collector_policy()->max_heap_byte_size();
1444 // We have to be careful here as these two calculations can overflow
1445 // 32-bit size_t's.
1446 double used_after_gc_d = (double) used_after_gc;
1447 double minimum_desired_capacity_d = used_after_gc_d / maximum_used_percentage;
1448 double maximum_desired_capacity_d = used_after_gc_d / minimum_used_percentage;
1450 // Let's make sure that they are both under the max heap size, which
1451 // by default will make them fit into a size_t.
1452 double desired_capacity_upper_bound = (double) max_heap_size;
1453 minimum_desired_capacity_d = MIN2(minimum_desired_capacity_d,
1454 desired_capacity_upper_bound);
1455 maximum_desired_capacity_d = MIN2(maximum_desired_capacity_d,
1456 desired_capacity_upper_bound);
1458 // We can now safely turn them into size_t's.
1459 size_t minimum_desired_capacity = (size_t) minimum_desired_capacity_d;
1460 size_t maximum_desired_capacity = (size_t) maximum_desired_capacity_d;
1462 // This assert only makes sense here, before we adjust them
1463 // with respect to the min and max heap size.
1464 assert(minimum_desired_capacity <= maximum_desired_capacity,
1465 err_msg("minimum_desired_capacity = "SIZE_FORMAT", "
1466 "maximum_desired_capacity = "SIZE_FORMAT,
1467 minimum_desired_capacity, maximum_desired_capacity));
1469 // Should not be greater than the heap max size. No need to adjust
1470 // it with respect to the heap min size as it's a lower bound (i.e.,
1471 // we'll try to make the capacity larger than it, not smaller).
1472 minimum_desired_capacity = MIN2(minimum_desired_capacity, max_heap_size);
1473 // Should not be less than the heap min size. No need to adjust it
1474 // with respect to the heap max size as it's an upper bound (i.e.,
1475 // we'll try to make the capacity smaller than it, not greater).
1476 maximum_desired_capacity = MAX2(maximum_desired_capacity, min_heap_size);
1478 if (PrintGC && Verbose) {
1479 const double free_percentage =
1480 (double) free_after_gc / (double) capacity_after_gc;
1481 gclog_or_tty->print_cr("Computing new size after full GC ");
1482 gclog_or_tty->print_cr(" "
1483 " minimum_free_percentage: %6.2f",
1484 minimum_free_percentage);
1485 gclog_or_tty->print_cr(" "
1486 " maximum_free_percentage: %6.2f",
1487 maximum_free_percentage);
1488 gclog_or_tty->print_cr(" "
1489 " capacity: %6.1fK"
1490 " minimum_desired_capacity: %6.1fK"
1491 " maximum_desired_capacity: %6.1fK",
1492 (double) capacity_after_gc / (double) K,
1493 (double) minimum_desired_capacity / (double) K,
1494 (double) maximum_desired_capacity / (double) K);
1495 gclog_or_tty->print_cr(" "
1496 " free_after_gc: %6.1fK"
1497 " used_after_gc: %6.1fK",
1498 (double) free_after_gc / (double) K,
1499 (double) used_after_gc / (double) K);
1500 gclog_or_tty->print_cr(" "
1501 " free_percentage: %6.2f",
1502 free_percentage);
1503 }
1504 if (capacity_after_gc < minimum_desired_capacity) {
1505 // Don't expand unless it's significant
1506 size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
1507 if (expand(expand_bytes)) {
1508 if (PrintGC && Verbose) {
1509 gclog_or_tty->print_cr(" "
1510 " expanding:"
1511 " max_heap_size: %6.1fK"
1512 " minimum_desired_capacity: %6.1fK"
1513 " expand_bytes: %6.1fK",
1514 (double) max_heap_size / (double) K,
1515 (double) minimum_desired_capacity / (double) K,
1516 (double) expand_bytes / (double) K);
1517 }
1518 }
1520 // No expansion, now see if we want to shrink
1521 } else if (capacity_after_gc > maximum_desired_capacity) {
1522 // Capacity too large, compute shrinking size
1523 size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;
1524 shrink(shrink_bytes);
1525 if (PrintGC && Verbose) {
1526 gclog_or_tty->print_cr(" "
1527 " shrinking:"
1528 " min_heap_size: %6.1fK"
1529 " maximum_desired_capacity: %6.1fK"
1530 " shrink_bytes: %6.1fK",
1531 (double) min_heap_size / (double) K,
1532 (double) maximum_desired_capacity / (double) K,
1533 (double) shrink_bytes / (double) K);
1534 }
1535 }
1536 }
1539 HeapWord*
1540 G1CollectedHeap::satisfy_failed_allocation(size_t word_size,
1541 bool* succeeded) {
1542 assert_at_safepoint(true /* should_be_vm_thread */);
1544 *succeeded = true;
1545 // Let's attempt the allocation first.
1546 HeapWord* result =
1547 attempt_allocation_at_safepoint(word_size,
1548 false /* expect_null_mutator_alloc_region */);
1549 if (result != NULL) {
1550 assert(*succeeded, "sanity");
1551 return result;
1552 }
1554 // In a G1 heap, we're supposed to keep allocation from failing by
1555 // incremental pauses. Therefore, at least for now, we'll favor
1556 // expansion over collection. (This might change in the future if we can
1557 // do something smarter than full collection to satisfy a failed alloc.)
1558 result = expand_and_allocate(word_size);
1559 if (result != NULL) {
1560 assert(*succeeded, "sanity");
1561 return result;
1562 }
1564 // Expansion didn't work, we'll try to do a Full GC.
1565 bool gc_succeeded = do_collection(false, /* explicit_gc */
1566 false, /* clear_all_soft_refs */
1567 word_size);
1568 if (!gc_succeeded) {
1569 *succeeded = false;
1570 return NULL;
1571 }
1573 // Retry the allocation
1574 result = attempt_allocation_at_safepoint(word_size,
1575 true /* expect_null_mutator_alloc_region */);
1576 if (result != NULL) {
1577 assert(*succeeded, "sanity");
1578 return result;
1579 }
1581 // Then, try a Full GC that will collect all soft references.
1582 gc_succeeded = do_collection(false, /* explicit_gc */
1583 true, /* clear_all_soft_refs */
1584 word_size);
1585 if (!gc_succeeded) {
1586 *succeeded = false;
1587 return NULL;
1588 }
1590 // Retry the allocation once more
1591 result = attempt_allocation_at_safepoint(word_size,
1592 true /* expect_null_mutator_alloc_region */);
1593 if (result != NULL) {
1594 assert(*succeeded, "sanity");
1595 return result;
1596 }
1598 assert(!collector_policy()->should_clear_all_soft_refs(),
1599 "Flag should have been handled and cleared prior to this point");
1601 // What else? We might try synchronous finalization later. If the total
1602 // space available is large enough for the allocation, then a more
1603 // complete compaction phase than we've tried so far might be
1604 // appropriate.
1605 assert(*succeeded, "sanity");
1606 return NULL;
1607 }
1609 // Attempting to expand the heap sufficiently
1610 // to support an allocation of the given "word_size". If
1611 // successful, perform the allocation and return the address of the
1612 // allocated block, or else "NULL".
1614 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1615 assert_at_safepoint(true /* should_be_vm_thread */);
1617 verify_region_sets_optional();
1619 size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
1620 if (expand(expand_bytes)) {
1621 _hrs.verify_optional();
1622 verify_region_sets_optional();
1623 return attempt_allocation_at_safepoint(word_size,
1624 false /* expect_null_mutator_alloc_region */);
1625 }
1626 return NULL;
1627 }
1629 void G1CollectedHeap::update_committed_space(HeapWord* old_end,
1630 HeapWord* new_end) {
1631 assert(old_end != new_end, "don't call this otherwise");
1632 assert((HeapWord*) _g1_storage.high() == new_end, "invariant");
1634 // Update the committed mem region.
1635 _g1_committed.set_end(new_end);
1636 // Tell the card table about the update.
1637 Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
1638 // Tell the BOT about the update.
1639 _bot_shared->resize(_g1_committed.word_size());
1640 }
1642 bool G1CollectedHeap::expand(size_t expand_bytes) {
1643 size_t old_mem_size = _g1_storage.committed_size();
1644 size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);
1645 aligned_expand_bytes = align_size_up(aligned_expand_bytes,
1646 HeapRegion::GrainBytes);
1648 if (Verbose && PrintGC) {
1649 gclog_or_tty->print("Expanding garbage-first heap from %ldK by %ldK",
1650 old_mem_size/K, aligned_expand_bytes/K);
1651 }
1653 // First commit the memory.
1654 HeapWord* old_end = (HeapWord*) _g1_storage.high();
1655 bool successful = _g1_storage.expand_by(aligned_expand_bytes);
1656 if (successful) {
1657 // Then propagate this update to the necessary data structures.
1658 HeapWord* new_end = (HeapWord*) _g1_storage.high();
1659 update_committed_space(old_end, new_end);
1661 FreeRegionList expansion_list("Local Expansion List");
1662 MemRegion mr = _hrs.expand_by(old_end, new_end, &expansion_list);
1663 assert(mr.start() == old_end, "post-condition");
1664 // mr might be a smaller region than what was requested if
1665 // expand_by() was unable to allocate the HeapRegion instances
1666 assert(mr.end() <= new_end, "post-condition");
1668 size_t actual_expand_bytes = mr.byte_size();
1669 assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
1670 assert(actual_expand_bytes == expansion_list.total_capacity_bytes(),
1671 "post-condition");
1672 if (actual_expand_bytes < aligned_expand_bytes) {
1673 // We could not expand _hrs to the desired size. In this case we
1674 // need to shrink the committed space accordingly.
1675 assert(mr.end() < new_end, "invariant");
1677 size_t diff_bytes = aligned_expand_bytes - actual_expand_bytes;
1678 // First uncommit the memory.
1679 _g1_storage.shrink_by(diff_bytes);
1680 // Then propagate this update to the necessary data structures.
1681 update_committed_space(new_end, mr.end());
1682 }
1683 _free_list.add_as_tail(&expansion_list);
1685 if (_hr_printer.is_active()) {
1686 HeapWord* curr = mr.start();
1687 while (curr < mr.end()) {
1688 HeapWord* curr_end = curr + HeapRegion::GrainWords;
1689 _hr_printer.commit(curr, curr_end);
1690 curr = curr_end;
1691 }
1692 assert(curr == mr.end(), "post-condition");
1693 }
1694 } else {
1695 // The expansion of the virtual storage space was unsuccessful.
1696 // Let's see if it was because we ran out of swap.
1697 if (G1ExitOnExpansionFailure &&
1698 _g1_storage.uncommitted_size() >= aligned_expand_bytes) {
1699 // We had head room...
1700 vm_exit_out_of_memory(aligned_expand_bytes, "G1 heap expansion");
1701 }
1702 }
1704 if (Verbose && PrintGC) {
1705 size_t new_mem_size = _g1_storage.committed_size();
1706 gclog_or_tty->print_cr("...%s, expanded to %ldK",
1707 (successful ? "Successful" : "Failed"),
1708 new_mem_size/K);
1709 }
1710 return successful;
1711 }
1713 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
1714 size_t old_mem_size = _g1_storage.committed_size();
1715 size_t aligned_shrink_bytes =
1716 ReservedSpace::page_align_size_down(shrink_bytes);
1717 aligned_shrink_bytes = align_size_down(aligned_shrink_bytes,
1718 HeapRegion::GrainBytes);
1719 size_t num_regions_deleted = 0;
1720 MemRegion mr = _hrs.shrink_by(aligned_shrink_bytes, &num_regions_deleted);
1721 HeapWord* old_end = (HeapWord*) _g1_storage.high();
1722 assert(mr.end() == old_end, "post-condition");
1723 if (mr.byte_size() > 0) {
1724 if (_hr_printer.is_active()) {
1725 HeapWord* curr = mr.end();
1726 while (curr > mr.start()) {
1727 HeapWord* curr_end = curr;
1728 curr -= HeapRegion::GrainWords;
1729 _hr_printer.uncommit(curr, curr_end);
1730 }
1731 assert(curr == mr.start(), "post-condition");
1732 }
1734 _g1_storage.shrink_by(mr.byte_size());
1735 HeapWord* new_end = (HeapWord*) _g1_storage.high();
1736 assert(mr.start() == new_end, "post-condition");
1738 _expansion_regions += num_regions_deleted;
1739 update_committed_space(old_end, new_end);
1740 HeapRegionRemSet::shrink_heap(n_regions());
1742 if (Verbose && PrintGC) {
1743 size_t new_mem_size = _g1_storage.committed_size();
1744 gclog_or_tty->print_cr("Shrinking garbage-first heap from %ldK by %ldK to %ldK",
1745 old_mem_size/K, aligned_shrink_bytes/K,
1746 new_mem_size/K);
1747 }
1748 }
1749 }
1751 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1752 verify_region_sets_optional();
1754 // We should only reach here at the end of a Full GC which means we
1755 // should not not be holding to any GC alloc regions. The method
1756 // below will make sure of that and do any remaining clean up.
1757 abandon_gc_alloc_regions();
1759 // Instead of tearing down / rebuilding the free lists here, we
1760 // could instead use the remove_all_pending() method on free_list to
1761 // remove only the ones that we need to remove.
1762 tear_down_region_lists(); // We will rebuild them in a moment.
1763 shrink_helper(shrink_bytes);
1764 rebuild_region_lists();
1766 _hrs.verify_optional();
1767 verify_region_sets_optional();
1768 }
1770 // Public methods.
1772 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
1773 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
1774 #endif // _MSC_VER
1777 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :
1778 SharedHeap(policy_),
1779 _g1_policy(policy_),
1780 _dirty_card_queue_set(false),
1781 _into_cset_dirty_card_queue_set(false),
1782 _is_alive_closure(this),
1783 _ref_processor(NULL),
1784 _process_strong_tasks(new SubTasksDone(G1H_PS_NumElements)),
1785 _bot_shared(NULL),
1786 _objs_with_preserved_marks(NULL), _preserved_marks_of_objs(NULL),
1787 _evac_failure_scan_stack(NULL) ,
1788 _mark_in_progress(false),
1789 _cg1r(NULL), _summary_bytes_used(0),
1790 _refine_cte_cl(NULL),
1791 _full_collection(false),
1792 _free_list("Master Free List"),
1793 _secondary_free_list("Secondary Free List"),
1794 _humongous_set("Master Humongous Set"),
1795 _free_regions_coming(false),
1796 _young_list(new YoungList(this)),
1797 _gc_time_stamp(0),
1798 _retained_old_gc_alloc_region(NULL),
1799 _surviving_young_words(NULL),
1800 _full_collections_completed(0),
1801 _in_cset_fast_test(NULL),
1802 _in_cset_fast_test_base(NULL),
1803 _dirty_cards_region_list(NULL) {
1804 _g1h = this; // To catch bugs.
1805 if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) {
1806 vm_exit_during_initialization("Failed necessary allocation.");
1807 }
1809 _humongous_object_threshold_in_words = HeapRegion::GrainWords / 2;
1811 int n_queues = MAX2((int)ParallelGCThreads, 1);
1812 _task_queues = new RefToScanQueueSet(n_queues);
1814 int n_rem_sets = HeapRegionRemSet::num_par_rem_sets();
1815 assert(n_rem_sets > 0, "Invariant.");
1817 HeapRegionRemSetIterator** iter_arr =
1818 NEW_C_HEAP_ARRAY(HeapRegionRemSetIterator*, n_queues);
1819 for (int i = 0; i < n_queues; i++) {
1820 iter_arr[i] = new HeapRegionRemSetIterator();
1821 }
1822 _rem_set_iterator = iter_arr;
1824 for (int i = 0; i < n_queues; i++) {
1825 RefToScanQueue* q = new RefToScanQueue();
1826 q->initialize();
1827 _task_queues->register_queue(i, q);
1828 }
1830 guarantee(_task_queues != NULL, "task_queues allocation failure.");
1831 }
1833 jint G1CollectedHeap::initialize() {
1834 CollectedHeap::pre_initialize();
1835 os::enable_vtime();
1837 // Necessary to satisfy locking discipline assertions.
1839 MutexLocker x(Heap_lock);
1841 // We have to initialize the printer before committing the heap, as
1842 // it will be used then.
1843 _hr_printer.set_active(G1PrintHeapRegions);
1845 // While there are no constraints in the GC code that HeapWordSize
1846 // be any particular value, there are multiple other areas in the
1847 // system which believe this to be true (e.g. oop->object_size in some
1848 // cases incorrectly returns the size in wordSize units rather than
1849 // HeapWordSize).
1850 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1852 size_t init_byte_size = collector_policy()->initial_heap_byte_size();
1853 size_t max_byte_size = collector_policy()->max_heap_byte_size();
1855 // Ensure that the sizes are properly aligned.
1856 Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
1857 Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");
1859 _cg1r = new ConcurrentG1Refine();
1861 // Reserve the maximum.
1862 PermanentGenerationSpec* pgs = collector_policy()->permanent_generation();
1863 // Includes the perm-gen.
1865 // When compressed oops are enabled, the preferred heap base
1866 // is calculated by subtracting the requested size from the
1867 // 32Gb boundary and using the result as the base address for
1868 // heap reservation. If the requested size is not aligned to
1869 // HeapRegion::GrainBytes (i.e. the alignment that is passed
1870 // into the ReservedHeapSpace constructor) then the actual
1871 // base of the reserved heap may end up differing from the
1872 // address that was requested (i.e. the preferred heap base).
1873 // If this happens then we could end up using a non-optimal
1874 // compressed oops mode.
1876 // Since max_byte_size is aligned to the size of a heap region (checked
1877 // above), we also need to align the perm gen size as it might not be.
1878 const size_t total_reserved = max_byte_size +
1879 align_size_up(pgs->max_size(), HeapRegion::GrainBytes);
1880 Universe::check_alignment(total_reserved, HeapRegion::GrainBytes, "g1 heap and perm");
1882 char* addr = Universe::preferred_heap_base(total_reserved, Universe::UnscaledNarrowOop);
1884 ReservedHeapSpace heap_rs(total_reserved, HeapRegion::GrainBytes,
1885 UseLargePages, addr);
1887 if (UseCompressedOops) {
1888 if (addr != NULL && !heap_rs.is_reserved()) {
1889 // Failed to reserve at specified address - the requested memory
1890 // region is taken already, for example, by 'java' launcher.
1891 // Try again to reserver heap higher.
1892 addr = Universe::preferred_heap_base(total_reserved, Universe::ZeroBasedNarrowOop);
1894 ReservedHeapSpace heap_rs0(total_reserved, HeapRegion::GrainBytes,
1895 UseLargePages, addr);
1897 if (addr != NULL && !heap_rs0.is_reserved()) {
1898 // Failed to reserve at specified address again - give up.
1899 addr = Universe::preferred_heap_base(total_reserved, Universe::HeapBasedNarrowOop);
1900 assert(addr == NULL, "");
1902 ReservedHeapSpace heap_rs1(total_reserved, HeapRegion::GrainBytes,
1903 UseLargePages, addr);
1904 heap_rs = heap_rs1;
1905 } else {
1906 heap_rs = heap_rs0;
1907 }
1908 }
1909 }
1911 if (!heap_rs.is_reserved()) {
1912 vm_exit_during_initialization("Could not reserve enough space for object heap");
1913 return JNI_ENOMEM;
1914 }
1916 // It is important to do this in a way such that concurrent readers can't
1917 // temporarily think somethings in the heap. (I've actually seen this
1918 // happen in asserts: DLD.)
1919 _reserved.set_word_size(0);
1920 _reserved.set_start((HeapWord*)heap_rs.base());
1921 _reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size()));
1923 _expansion_regions = max_byte_size/HeapRegion::GrainBytes;
1925 // Create the gen rem set (and barrier set) for the entire reserved region.
1926 _rem_set = collector_policy()->create_rem_set(_reserved, 2);
1927 set_barrier_set(rem_set()->bs());
1928 if (barrier_set()->is_a(BarrierSet::ModRef)) {
1929 _mr_bs = (ModRefBarrierSet*)_barrier_set;
1930 } else {
1931 vm_exit_during_initialization("G1 requires a mod ref bs.");
1932 return JNI_ENOMEM;
1933 }
1935 // Also create a G1 rem set.
1936 if (mr_bs()->is_a(BarrierSet::CardTableModRef)) {
1937 _g1_rem_set = new G1RemSet(this, (CardTableModRefBS*)mr_bs());
1938 } else {
1939 vm_exit_during_initialization("G1 requires a cardtable mod ref bs.");
1940 return JNI_ENOMEM;
1941 }
1943 // Carve out the G1 part of the heap.
1945 ReservedSpace g1_rs = heap_rs.first_part(max_byte_size);
1946 _g1_reserved = MemRegion((HeapWord*)g1_rs.base(),
1947 g1_rs.size()/HeapWordSize);
1948 ReservedSpace perm_gen_rs = heap_rs.last_part(max_byte_size);
1950 _perm_gen = pgs->init(perm_gen_rs, pgs->init_size(), rem_set());
1952 _g1_storage.initialize(g1_rs, 0);
1953 _g1_committed = MemRegion((HeapWord*)_g1_storage.low(), (size_t) 0);
1954 _hrs.initialize((HeapWord*) _g1_reserved.start(),
1955 (HeapWord*) _g1_reserved.end(),
1956 _expansion_regions);
1958 // 6843694 - ensure that the maximum region index can fit
1959 // in the remembered set structures.
1960 const size_t max_region_idx = ((size_t)1 << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
1961 guarantee((max_regions() - 1) <= max_region_idx, "too many regions");
1963 size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
1964 guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
1965 guarantee((size_t) HeapRegion::CardsPerRegion < max_cards_per_region,
1966 "too many cards per region");
1968 HeapRegionSet::set_unrealistically_long_length(max_regions() + 1);
1970 _bot_shared = new G1BlockOffsetSharedArray(_reserved,
1971 heap_word_size(init_byte_size));
1973 _g1h = this;
1975 _in_cset_fast_test_length = max_regions();
1976 _in_cset_fast_test_base = NEW_C_HEAP_ARRAY(bool, _in_cset_fast_test_length);
1978 // We're biasing _in_cset_fast_test to avoid subtracting the
1979 // beginning of the heap every time we want to index; basically
1980 // it's the same with what we do with the card table.
1981 _in_cset_fast_test = _in_cset_fast_test_base -
1982 ((size_t) _g1_reserved.start() >> HeapRegion::LogOfHRGrainBytes);
1984 // Clear the _cset_fast_test bitmap in anticipation of adding
1985 // regions to the incremental collection set for the first
1986 // evacuation pause.
1987 clear_cset_fast_test();
1989 // Create the ConcurrentMark data structure and thread.
1990 // (Must do this late, so that "max_regions" is defined.)
1991 _cm = new ConcurrentMark(heap_rs, (int) max_regions());
1992 _cmThread = _cm->cmThread();
1994 // Initialize the from_card cache structure of HeapRegionRemSet.
1995 HeapRegionRemSet::init_heap(max_regions());
1997 // Now expand into the initial heap size.
1998 if (!expand(init_byte_size)) {
1999 vm_exit_during_initialization("Failed to allocate initial heap.");
2000 return JNI_ENOMEM;
2001 }
2003 // Perform any initialization actions delegated to the policy.
2004 g1_policy()->init();
2006 g1_policy()->note_start_of_mark_thread();
2008 _refine_cte_cl =
2009 new RefineCardTableEntryClosure(ConcurrentG1RefineThread::sts(),
2010 g1_rem_set(),
2011 concurrent_g1_refine());
2012 JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
2014 JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
2015 SATB_Q_FL_lock,
2016 G1SATBProcessCompletedThreshold,
2017 Shared_SATB_Q_lock);
2019 JavaThread::dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
2020 DirtyCardQ_FL_lock,
2021 concurrent_g1_refine()->yellow_zone(),
2022 concurrent_g1_refine()->red_zone(),
2023 Shared_DirtyCardQ_lock);
2025 if (G1DeferredRSUpdate) {
2026 dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
2027 DirtyCardQ_FL_lock,
2028 -1, // never trigger processing
2029 -1, // no limit on length
2030 Shared_DirtyCardQ_lock,
2031 &JavaThread::dirty_card_queue_set());
2032 }
2034 // Initialize the card queue set used to hold cards containing
2035 // references into the collection set.
2036 _into_cset_dirty_card_queue_set.initialize(DirtyCardQ_CBL_mon,
2037 DirtyCardQ_FL_lock,
2038 -1, // never trigger processing
2039 -1, // no limit on length
2040 Shared_DirtyCardQ_lock,
2041 &JavaThread::dirty_card_queue_set());
2043 // In case we're keeping closure specialization stats, initialize those
2044 // counts and that mechanism.
2045 SpecializationStats::clear();
2047 // Do later initialization work for concurrent refinement.
2048 _cg1r->init();
2050 // Here we allocate the dummy full region that is required by the
2051 // G1AllocRegion class. If we don't pass an address in the reserved
2052 // space here, lots of asserts fire.
2054 HeapRegion* dummy_region = new_heap_region(0 /* index of bottom region */,
2055 _g1_reserved.start());
2056 // We'll re-use the same region whether the alloc region will
2057 // require BOT updates or not and, if it doesn't, then a non-young
2058 // region will complain that it cannot support allocations without
2059 // BOT updates. So we'll tag the dummy region as young to avoid that.
2060 dummy_region->set_young();
2061 // Make sure it's full.
2062 dummy_region->set_top(dummy_region->end());
2063 G1AllocRegion::setup(this, dummy_region);
2065 init_mutator_alloc_region();
2067 // Do create of the monitoring and management support so that
2068 // values in the heap have been properly initialized.
2069 _g1mm = new G1MonitoringSupport(this, &_g1_storage);
2071 return JNI_OK;
2072 }
2074 void G1CollectedHeap::ref_processing_init() {
2075 // Reference processing in G1 currently works as follows:
2076 //
2077 // * There is only one reference processor instance that
2078 // 'spans' the entire heap. It is created by the code
2079 // below.
2080 // * Reference discovery is not enabled during an incremental
2081 // pause (see 6484982).
2082 // * Discoverered refs are not enqueued nor are they processed
2083 // during an incremental pause (see 6484982).
2084 // * Reference discovery is enabled at initial marking.
2085 // * Reference discovery is disabled and the discovered
2086 // references processed etc during remarking.
2087 // * Reference discovery is MT (see below).
2088 // * Reference discovery requires a barrier (see below).
2089 // * Reference processing is currently not MT (see 6608385).
2090 // * A full GC enables (non-MT) reference discovery and
2091 // processes any discovered references.
2093 SharedHeap::ref_processing_init();
2094 MemRegion mr = reserved_region();
2095 _ref_processor =
2096 new ReferenceProcessor(mr, // span
2097 ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing
2098 (int) ParallelGCThreads, // degree of mt processing
2099 ParallelGCThreads > 1 || ConcGCThreads > 1, // mt discovery
2100 (int) MAX2(ParallelGCThreads, ConcGCThreads), // degree of mt discovery
2101 false, // Reference discovery is not atomic
2102 &_is_alive_closure, // is alive closure for efficiency
2103 true); // Setting next fields of discovered
2104 // lists requires a barrier.
2105 }
2107 size_t G1CollectedHeap::capacity() const {
2108 return _g1_committed.byte_size();
2109 }
2111 void G1CollectedHeap::iterate_dirty_card_closure(CardTableEntryClosure* cl,
2112 DirtyCardQueue* into_cset_dcq,
2113 bool concurrent,
2114 int worker_i) {
2115 // Clean cards in the hot card cache
2116 concurrent_g1_refine()->clean_up_cache(worker_i, g1_rem_set(), into_cset_dcq);
2118 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
2119 int n_completed_buffers = 0;
2120 while (dcqs.apply_closure_to_completed_buffer(cl, worker_i, 0, true)) {
2121 n_completed_buffers++;
2122 }
2123 g1_policy()->record_update_rs_processed_buffers(worker_i,
2124 (double) n_completed_buffers);
2125 dcqs.clear_n_completed_buffers();
2126 assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!");
2127 }
2130 // Computes the sum of the storage used by the various regions.
2132 size_t G1CollectedHeap::used() const {
2133 assert(Heap_lock->owner() != NULL,
2134 "Should be owned on this thread's behalf.");
2135 size_t result = _summary_bytes_used;
2136 // Read only once in case it is set to NULL concurrently
2137 HeapRegion* hr = _mutator_alloc_region.get();
2138 if (hr != NULL)
2139 result += hr->used();
2140 return result;
2141 }
2143 size_t G1CollectedHeap::used_unlocked() const {
2144 size_t result = _summary_bytes_used;
2145 return result;
2146 }
2148 class SumUsedClosure: public HeapRegionClosure {
2149 size_t _used;
2150 public:
2151 SumUsedClosure() : _used(0) {}
2152 bool doHeapRegion(HeapRegion* r) {
2153 if (!r->continuesHumongous()) {
2154 _used += r->used();
2155 }
2156 return false;
2157 }
2158 size_t result() { return _used; }
2159 };
2161 size_t G1CollectedHeap::recalculate_used() const {
2162 SumUsedClosure blk;
2163 heap_region_iterate(&blk);
2164 return blk.result();
2165 }
2167 size_t G1CollectedHeap::unsafe_max_alloc() {
2168 if (free_regions() > 0) return HeapRegion::GrainBytes;
2169 // otherwise, is there space in the current allocation region?
2171 // We need to store the current allocation region in a local variable
2172 // here. The problem is that this method doesn't take any locks and
2173 // there may be other threads which overwrite the current allocation
2174 // region field. attempt_allocation(), for example, sets it to NULL
2175 // and this can happen *after* the NULL check here but before the call
2176 // to free(), resulting in a SIGSEGV. Note that this doesn't appear
2177 // to be a problem in the optimized build, since the two loads of the
2178 // current allocation region field are optimized away.
2179 HeapRegion* hr = _mutator_alloc_region.get();
2180 if (hr == NULL) {
2181 return 0;
2182 }
2183 return hr->free();
2184 }
2186 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
2187 return
2188 ((cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) ||
2189 (cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent));
2190 }
2192 #ifndef PRODUCT
2193 void G1CollectedHeap::allocate_dummy_regions() {
2194 // Let's fill up most of the region
2195 size_t word_size = HeapRegion::GrainWords - 1024;
2196 // And as a result the region we'll allocate will be humongous.
2197 guarantee(isHumongous(word_size), "sanity");
2199 for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {
2200 // Let's use the existing mechanism for the allocation
2201 HeapWord* dummy_obj = humongous_obj_allocate(word_size);
2202 if (dummy_obj != NULL) {
2203 MemRegion mr(dummy_obj, word_size);
2204 CollectedHeap::fill_with_object(mr);
2205 } else {
2206 // If we can't allocate once, we probably cannot allocate
2207 // again. Let's get out of the loop.
2208 break;
2209 }
2210 }
2211 }
2212 #endif // !PRODUCT
2214 void G1CollectedHeap::increment_full_collections_completed(bool concurrent) {
2215 MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
2217 // We assume that if concurrent == true, then the caller is a
2218 // concurrent thread that was joined the Suspendible Thread
2219 // Set. If there's ever a cheap way to check this, we should add an
2220 // assert here.
2222 // We have already incremented _total_full_collections at the start
2223 // of the GC, so total_full_collections() represents how many full
2224 // collections have been started.
2225 unsigned int full_collections_started = total_full_collections();
2227 // Given that this method is called at the end of a Full GC or of a
2228 // concurrent cycle, and those can be nested (i.e., a Full GC can
2229 // interrupt a concurrent cycle), the number of full collections
2230 // completed should be either one (in the case where there was no
2231 // nesting) or two (when a Full GC interrupted a concurrent cycle)
2232 // behind the number of full collections started.
2234 // This is the case for the inner caller, i.e. a Full GC.
2235 assert(concurrent ||
2236 (full_collections_started == _full_collections_completed + 1) ||
2237 (full_collections_started == _full_collections_completed + 2),
2238 err_msg("for inner caller (Full GC): full_collections_started = %u "
2239 "is inconsistent with _full_collections_completed = %u",
2240 full_collections_started, _full_collections_completed));
2242 // This is the case for the outer caller, i.e. the concurrent cycle.
2243 assert(!concurrent ||
2244 (full_collections_started == _full_collections_completed + 1),
2245 err_msg("for outer caller (concurrent cycle): "
2246 "full_collections_started = %u "
2247 "is inconsistent with _full_collections_completed = %u",
2248 full_collections_started, _full_collections_completed));
2250 _full_collections_completed += 1;
2252 // We need to clear the "in_progress" flag in the CM thread before
2253 // we wake up any waiters (especially when ExplicitInvokesConcurrent
2254 // is set) so that if a waiter requests another System.gc() it doesn't
2255 // incorrectly see that a marking cyle is still in progress.
2256 if (concurrent) {
2257 _cmThread->clear_in_progress();
2258 }
2260 // This notify_all() will ensure that a thread that called
2261 // System.gc() with (with ExplicitGCInvokesConcurrent set or not)
2262 // and it's waiting for a full GC to finish will be woken up. It is
2263 // waiting in VM_G1IncCollectionPause::doit_epilogue().
2264 FullGCCount_lock->notify_all();
2265 }
2267 void G1CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) {
2268 assert_at_safepoint(true /* should_be_vm_thread */);
2269 GCCauseSetter gcs(this, cause);
2270 switch (cause) {
2271 case GCCause::_heap_inspection:
2272 case GCCause::_heap_dump: {
2273 HandleMark hm;
2274 do_full_collection(false); // don't clear all soft refs
2275 break;
2276 }
2277 default: // XXX FIX ME
2278 ShouldNotReachHere(); // Unexpected use of this function
2279 }
2280 }
2282 void G1CollectedHeap::collect(GCCause::Cause cause) {
2283 // The caller doesn't have the Heap_lock
2284 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
2286 unsigned int gc_count_before;
2287 unsigned int full_gc_count_before;
2288 {
2289 MutexLocker ml(Heap_lock);
2291 // Read the GC count while holding the Heap_lock
2292 gc_count_before = SharedHeap::heap()->total_collections();
2293 full_gc_count_before = SharedHeap::heap()->total_full_collections();
2294 }
2296 if (should_do_concurrent_full_gc(cause)) {
2297 // Schedule an initial-mark evacuation pause that will start a
2298 // concurrent cycle. We're setting word_size to 0 which means that
2299 // we are not requesting a post-GC allocation.
2300 VM_G1IncCollectionPause op(gc_count_before,
2301 0, /* word_size */
2302 true, /* should_initiate_conc_mark */
2303 g1_policy()->max_pause_time_ms(),
2304 cause);
2305 VMThread::execute(&op);
2306 } else {
2307 if (cause == GCCause::_gc_locker
2308 DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
2310 // Schedule a standard evacuation pause. We're setting word_size
2311 // to 0 which means that we are not requesting a post-GC allocation.
2312 VM_G1IncCollectionPause op(gc_count_before,
2313 0, /* word_size */
2314 false, /* should_initiate_conc_mark */
2315 g1_policy()->max_pause_time_ms(),
2316 cause);
2317 VMThread::execute(&op);
2318 } else {
2319 // Schedule a Full GC.
2320 VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause);
2321 VMThread::execute(&op);
2322 }
2323 }
2324 }
2326 bool G1CollectedHeap::is_in(const void* p) const {
2327 HeapRegion* hr = _hrs.addr_to_region((HeapWord*) p);
2328 if (hr != NULL) {
2329 return hr->is_in(p);
2330 } else {
2331 return _perm_gen->as_gen()->is_in(p);
2332 }
2333 }
2335 // Iteration functions.
2337 // Iterates an OopClosure over all ref-containing fields of objects
2338 // within a HeapRegion.
2340 class IterateOopClosureRegionClosure: public HeapRegionClosure {
2341 MemRegion _mr;
2342 OopClosure* _cl;
2343 public:
2344 IterateOopClosureRegionClosure(MemRegion mr, OopClosure* cl)
2345 : _mr(mr), _cl(cl) {}
2346 bool doHeapRegion(HeapRegion* r) {
2347 if (! r->continuesHumongous()) {
2348 r->oop_iterate(_cl);
2349 }
2350 return false;
2351 }
2352 };
2354 void G1CollectedHeap::oop_iterate(OopClosure* cl, bool do_perm) {
2355 IterateOopClosureRegionClosure blk(_g1_committed, cl);
2356 heap_region_iterate(&blk);
2357 if (do_perm) {
2358 perm_gen()->oop_iterate(cl);
2359 }
2360 }
2362 void G1CollectedHeap::oop_iterate(MemRegion mr, OopClosure* cl, bool do_perm) {
2363 IterateOopClosureRegionClosure blk(mr, cl);
2364 heap_region_iterate(&blk);
2365 if (do_perm) {
2366 perm_gen()->oop_iterate(cl);
2367 }
2368 }
2370 // Iterates an ObjectClosure over all objects within a HeapRegion.
2372 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
2373 ObjectClosure* _cl;
2374 public:
2375 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
2376 bool doHeapRegion(HeapRegion* r) {
2377 if (! r->continuesHumongous()) {
2378 r->object_iterate(_cl);
2379 }
2380 return false;
2381 }
2382 };
2384 void G1CollectedHeap::object_iterate(ObjectClosure* cl, bool do_perm) {
2385 IterateObjectClosureRegionClosure blk(cl);
2386 heap_region_iterate(&blk);
2387 if (do_perm) {
2388 perm_gen()->object_iterate(cl);
2389 }
2390 }
2392 void G1CollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) {
2393 // FIXME: is this right?
2394 guarantee(false, "object_iterate_since_last_GC not supported by G1 heap");
2395 }
2397 // Calls a SpaceClosure on a HeapRegion.
2399 class SpaceClosureRegionClosure: public HeapRegionClosure {
2400 SpaceClosure* _cl;
2401 public:
2402 SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {}
2403 bool doHeapRegion(HeapRegion* r) {
2404 _cl->do_space(r);
2405 return false;
2406 }
2407 };
2409 void G1CollectedHeap::space_iterate(SpaceClosure* cl) {
2410 SpaceClosureRegionClosure blk(cl);
2411 heap_region_iterate(&blk);
2412 }
2414 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
2415 _hrs.iterate(cl);
2416 }
2418 void G1CollectedHeap::heap_region_iterate_from(HeapRegion* r,
2419 HeapRegionClosure* cl) const {
2420 _hrs.iterate_from(r, cl);
2421 }
2423 void
2424 G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,
2425 int worker,
2426 jint claim_value) {
2427 const size_t regions = n_regions();
2428 const size_t worker_num = (G1CollectedHeap::use_parallel_gc_threads() ? ParallelGCThreads : 1);
2429 // try to spread out the starting points of the workers
2430 const size_t start_index = regions / worker_num * (size_t) worker;
2432 // each worker will actually look at all regions
2433 for (size_t count = 0; count < regions; ++count) {
2434 const size_t index = (start_index + count) % regions;
2435 assert(0 <= index && index < regions, "sanity");
2436 HeapRegion* r = region_at(index);
2437 // we'll ignore "continues humongous" regions (we'll process them
2438 // when we come across their corresponding "start humongous"
2439 // region) and regions already claimed
2440 if (r->claim_value() == claim_value || r->continuesHumongous()) {
2441 continue;
2442 }
2443 // OK, try to claim it
2444 if (r->claimHeapRegion(claim_value)) {
2445 // success!
2446 assert(!r->continuesHumongous(), "sanity");
2447 if (r->startsHumongous()) {
2448 // If the region is "starts humongous" we'll iterate over its
2449 // "continues humongous" first; in fact we'll do them
2450 // first. The order is important. In on case, calling the
2451 // closure on the "starts humongous" region might de-allocate
2452 // and clear all its "continues humongous" regions and, as a
2453 // result, we might end up processing them twice. So, we'll do
2454 // them first (notice: most closures will ignore them anyway) and
2455 // then we'll do the "starts humongous" region.
2456 for (size_t ch_index = index + 1; ch_index < regions; ++ch_index) {
2457 HeapRegion* chr = region_at(ch_index);
2459 // if the region has already been claimed or it's not
2460 // "continues humongous" we're done
2461 if (chr->claim_value() == claim_value ||
2462 !chr->continuesHumongous()) {
2463 break;
2464 }
2466 // Noone should have claimed it directly. We can given
2467 // that we claimed its "starts humongous" region.
2468 assert(chr->claim_value() != claim_value, "sanity");
2469 assert(chr->humongous_start_region() == r, "sanity");
2471 if (chr->claimHeapRegion(claim_value)) {
2472 // we should always be able to claim it; noone else should
2473 // be trying to claim this region
2475 bool res2 = cl->doHeapRegion(chr);
2476 assert(!res2, "Should not abort");
2478 // Right now, this holds (i.e., no closure that actually
2479 // does something with "continues humongous" regions
2480 // clears them). We might have to weaken it in the future,
2481 // but let's leave these two asserts here for extra safety.
2482 assert(chr->continuesHumongous(), "should still be the case");
2483 assert(chr->humongous_start_region() == r, "sanity");
2484 } else {
2485 guarantee(false, "we should not reach here");
2486 }
2487 }
2488 }
2490 assert(!r->continuesHumongous(), "sanity");
2491 bool res = cl->doHeapRegion(r);
2492 assert(!res, "Should not abort");
2493 }
2494 }
2495 }
2497 class ResetClaimValuesClosure: public HeapRegionClosure {
2498 public:
2499 bool doHeapRegion(HeapRegion* r) {
2500 r->set_claim_value(HeapRegion::InitialClaimValue);
2501 return false;
2502 }
2503 };
2505 void
2506 G1CollectedHeap::reset_heap_region_claim_values() {
2507 ResetClaimValuesClosure blk;
2508 heap_region_iterate(&blk);
2509 }
2511 #ifdef ASSERT
2512 // This checks whether all regions in the heap have the correct claim
2513 // value. I also piggy-backed on this a check to ensure that the
2514 // humongous_start_region() information on "continues humongous"
2515 // regions is correct.
2517 class CheckClaimValuesClosure : public HeapRegionClosure {
2518 private:
2519 jint _claim_value;
2520 size_t _failures;
2521 HeapRegion* _sh_region;
2522 public:
2523 CheckClaimValuesClosure(jint claim_value) :
2524 _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
2525 bool doHeapRegion(HeapRegion* r) {
2526 if (r->claim_value() != _claim_value) {
2527 gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), "
2528 "claim value = %d, should be %d",
2529 r->bottom(), r->end(), r->claim_value(),
2530 _claim_value);
2531 ++_failures;
2532 }
2533 if (!r->isHumongous()) {
2534 _sh_region = NULL;
2535 } else if (r->startsHumongous()) {
2536 _sh_region = r;
2537 } else if (r->continuesHumongous()) {
2538 if (r->humongous_start_region() != _sh_region) {
2539 gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), "
2540 "HS = "PTR_FORMAT", should be "PTR_FORMAT,
2541 r->bottom(), r->end(),
2542 r->humongous_start_region(),
2543 _sh_region);
2544 ++_failures;
2545 }
2546 }
2547 return false;
2548 }
2549 size_t failures() {
2550 return _failures;
2551 }
2552 };
2554 bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
2555 CheckClaimValuesClosure cl(claim_value);
2556 heap_region_iterate(&cl);
2557 return cl.failures() == 0;
2558 }
2559 #endif // ASSERT
2561 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {
2562 HeapRegion* r = g1_policy()->collection_set();
2563 while (r != NULL) {
2564 HeapRegion* next = r->next_in_collection_set();
2565 if (cl->doHeapRegion(r)) {
2566 cl->incomplete();
2567 return;
2568 }
2569 r = next;
2570 }
2571 }
2573 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,
2574 HeapRegionClosure *cl) {
2575 if (r == NULL) {
2576 // The CSet is empty so there's nothing to do.
2577 return;
2578 }
2580 assert(r->in_collection_set(),
2581 "Start region must be a member of the collection set.");
2582 HeapRegion* cur = r;
2583 while (cur != NULL) {
2584 HeapRegion* next = cur->next_in_collection_set();
2585 if (cl->doHeapRegion(cur) && false) {
2586 cl->incomplete();
2587 return;
2588 }
2589 cur = next;
2590 }
2591 cur = g1_policy()->collection_set();
2592 while (cur != r) {
2593 HeapRegion* next = cur->next_in_collection_set();
2594 if (cl->doHeapRegion(cur) && false) {
2595 cl->incomplete();
2596 return;
2597 }
2598 cur = next;
2599 }
2600 }
2602 CompactibleSpace* G1CollectedHeap::first_compactible_space() {
2603 return n_regions() > 0 ? region_at(0) : NULL;
2604 }
2607 Space* G1CollectedHeap::space_containing(const void* addr) const {
2608 Space* res = heap_region_containing(addr);
2609 if (res == NULL)
2610 res = perm_gen()->space_containing(addr);
2611 return res;
2612 }
2614 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
2615 Space* sp = space_containing(addr);
2616 if (sp != NULL) {
2617 return sp->block_start(addr);
2618 }
2619 return NULL;
2620 }
2622 size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
2623 Space* sp = space_containing(addr);
2624 assert(sp != NULL, "block_size of address outside of heap");
2625 return sp->block_size(addr);
2626 }
2628 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
2629 Space* sp = space_containing(addr);
2630 return sp->block_is_obj(addr);
2631 }
2633 bool G1CollectedHeap::supports_tlab_allocation() const {
2634 return true;
2635 }
2637 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
2638 return HeapRegion::GrainBytes;
2639 }
2641 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
2642 // Return the remaining space in the cur alloc region, but not less than
2643 // the min TLAB size.
2645 // Also, this value can be at most the humongous object threshold,
2646 // since we can't allow tlabs to grow big enough to accomodate
2647 // humongous objects.
2649 HeapRegion* hr = _mutator_alloc_region.get();
2650 size_t max_tlab_size = _humongous_object_threshold_in_words * wordSize;
2651 if (hr == NULL) {
2652 return max_tlab_size;
2653 } else {
2654 return MIN2(MAX2(hr->free(), (size_t) MinTLABSize), max_tlab_size);
2655 }
2656 }
2658 size_t G1CollectedHeap::max_capacity() const {
2659 return _g1_reserved.byte_size();
2660 }
2662 jlong G1CollectedHeap::millis_since_last_gc() {
2663 // assert(false, "NYI");
2664 return 0;
2665 }
2667 void G1CollectedHeap::prepare_for_verify() {
2668 if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
2669 ensure_parsability(false);
2670 }
2671 g1_rem_set()->prepare_for_verify();
2672 }
2674 class VerifyLivenessOopClosure: public OopClosure {
2675 G1CollectedHeap* _g1h;
2676 VerifyOption _vo;
2677 public:
2678 VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo):
2679 _g1h(g1h), _vo(vo)
2680 { }
2681 void do_oop(narrowOop *p) { do_oop_work(p); }
2682 void do_oop( oop *p) { do_oop_work(p); }
2684 template <class T> void do_oop_work(T *p) {
2685 oop obj = oopDesc::load_decode_heap_oop(p);
2686 guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo),
2687 "Dead object referenced by a not dead object");
2688 }
2689 };
2691 class VerifyObjsInRegionClosure: public ObjectClosure {
2692 private:
2693 G1CollectedHeap* _g1h;
2694 size_t _live_bytes;
2695 HeapRegion *_hr;
2696 VerifyOption _vo;
2697 public:
2698 // _vo == UsePrevMarking -> use "prev" marking information,
2699 // _vo == UseNextMarking -> use "next" marking information,
2700 // _vo == UseMarkWord -> use mark word from object header.
2701 VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo)
2702 : _live_bytes(0), _hr(hr), _vo(vo) {
2703 _g1h = G1CollectedHeap::heap();
2704 }
2705 void do_object(oop o) {
2706 VerifyLivenessOopClosure isLive(_g1h, _vo);
2707 assert(o != NULL, "Huh?");
2708 if (!_g1h->is_obj_dead_cond(o, _vo)) {
2709 // If the object is alive according to the mark word,
2710 // then verify that the marking information agrees.
2711 // Note we can't verify the contra-positive of the
2712 // above: if the object is dead (according to the mark
2713 // word), it may not be marked, or may have been marked
2714 // but has since became dead, or may have been allocated
2715 // since the last marking.
2716 if (_vo == VerifyOption_G1UseMarkWord) {
2717 guarantee(!_g1h->is_obj_dead(o), "mark word and concurrent mark mismatch");
2718 }
2720 o->oop_iterate(&isLive);
2721 if (!_hr->obj_allocated_since_prev_marking(o)) {
2722 size_t obj_size = o->size(); // Make sure we don't overflow
2723 _live_bytes += (obj_size * HeapWordSize);
2724 }
2725 }
2726 }
2727 size_t live_bytes() { return _live_bytes; }
2728 };
2730 class PrintObjsInRegionClosure : public ObjectClosure {
2731 HeapRegion *_hr;
2732 G1CollectedHeap *_g1;
2733 public:
2734 PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) {
2735 _g1 = G1CollectedHeap::heap();
2736 };
2738 void do_object(oop o) {
2739 if (o != NULL) {
2740 HeapWord *start = (HeapWord *) o;
2741 size_t word_sz = o->size();
2742 gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT
2743 " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",
2744 (void*) o, word_sz,
2745 _g1->isMarkedPrev(o),
2746 _g1->isMarkedNext(o),
2747 _hr->obj_allocated_since_prev_marking(o));
2748 HeapWord *end = start + word_sz;
2749 HeapWord *cur;
2750 int *val;
2751 for (cur = start; cur < end; cur++) {
2752 val = (int *) cur;
2753 gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val);
2754 }
2755 }
2756 }
2757 };
2759 class VerifyRegionClosure: public HeapRegionClosure {
2760 private:
2761 bool _allow_dirty;
2762 bool _par;
2763 VerifyOption _vo;
2764 bool _failures;
2765 public:
2766 // _vo == UsePrevMarking -> use "prev" marking information,
2767 // _vo == UseNextMarking -> use "next" marking information,
2768 // _vo == UseMarkWord -> use mark word from object header.
2769 VerifyRegionClosure(bool allow_dirty, bool par, VerifyOption vo)
2770 : _allow_dirty(allow_dirty),
2771 _par(par),
2772 _vo(vo),
2773 _failures(false) {}
2775 bool failures() {
2776 return _failures;
2777 }
2779 bool doHeapRegion(HeapRegion* r) {
2780 guarantee(_par || r->claim_value() == HeapRegion::InitialClaimValue,
2781 "Should be unclaimed at verify points.");
2782 if (!r->continuesHumongous()) {
2783 bool failures = false;
2784 r->verify(_allow_dirty, _vo, &failures);
2785 if (failures) {
2786 _failures = true;
2787 } else {
2788 VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo);
2789 r->object_iterate(¬_dead_yet_cl);
2790 if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
2791 gclog_or_tty->print_cr("["PTR_FORMAT","PTR_FORMAT"] "
2792 "max_live_bytes "SIZE_FORMAT" "
2793 "< calculated "SIZE_FORMAT,
2794 r->bottom(), r->end(),
2795 r->max_live_bytes(),
2796 not_dead_yet_cl.live_bytes());
2797 _failures = true;
2798 }
2799 }
2800 }
2801 return false; // stop the region iteration if we hit a failure
2802 }
2803 };
2805 class VerifyRootsClosure: public OopsInGenClosure {
2806 private:
2807 G1CollectedHeap* _g1h;
2808 VerifyOption _vo;
2809 bool _failures;
2810 public:
2811 // _vo == UsePrevMarking -> use "prev" marking information,
2812 // _vo == UseNextMarking -> use "next" marking information,
2813 // _vo == UseMarkWord -> use mark word from object header.
2814 VerifyRootsClosure(VerifyOption vo) :
2815 _g1h(G1CollectedHeap::heap()),
2816 _vo(vo),
2817 _failures(false) { }
2819 bool failures() { return _failures; }
2821 template <class T> void do_oop_nv(T* p) {
2822 T heap_oop = oopDesc::load_heap_oop(p);
2823 if (!oopDesc::is_null(heap_oop)) {
2824 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
2825 if (_g1h->is_obj_dead_cond(obj, _vo)) {
2826 gclog_or_tty->print_cr("Root location "PTR_FORMAT" "
2827 "points to dead obj "PTR_FORMAT, p, (void*) obj);
2828 if (_vo == VerifyOption_G1UseMarkWord) {
2829 gclog_or_tty->print_cr(" Mark word: "PTR_FORMAT, (void*)(obj->mark()));
2830 }
2831 obj->print_on(gclog_or_tty);
2832 _failures = true;
2833 }
2834 }
2835 }
2837 void do_oop(oop* p) { do_oop_nv(p); }
2838 void do_oop(narrowOop* p) { do_oop_nv(p); }
2839 };
2841 // This is the task used for parallel heap verification.
2843 class G1ParVerifyTask: public AbstractGangTask {
2844 private:
2845 G1CollectedHeap* _g1h;
2846 bool _allow_dirty;
2847 VerifyOption _vo;
2848 bool _failures;
2850 public:
2851 // _vo == UsePrevMarking -> use "prev" marking information,
2852 // _vo == UseNextMarking -> use "next" marking information,
2853 // _vo == UseMarkWord -> use mark word from object header.
2854 G1ParVerifyTask(G1CollectedHeap* g1h, bool allow_dirty, VerifyOption vo) :
2855 AbstractGangTask("Parallel verify task"),
2856 _g1h(g1h),
2857 _allow_dirty(allow_dirty),
2858 _vo(vo),
2859 _failures(false) { }
2861 bool failures() {
2862 return _failures;
2863 }
2865 void work(int worker_i) {
2866 HandleMark hm;
2867 VerifyRegionClosure blk(_allow_dirty, true, _vo);
2868 _g1h->heap_region_par_iterate_chunked(&blk, worker_i,
2869 HeapRegion::ParVerifyClaimValue);
2870 if (blk.failures()) {
2871 _failures = true;
2872 }
2873 }
2874 };
2876 void G1CollectedHeap::verify(bool allow_dirty, bool silent) {
2877 verify(allow_dirty, silent, VerifyOption_G1UsePrevMarking);
2878 }
2880 void G1CollectedHeap::verify(bool allow_dirty,
2881 bool silent,
2882 VerifyOption vo) {
2883 if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
2884 if (!silent) { gclog_or_tty->print("Roots (excluding permgen) "); }
2885 VerifyRootsClosure rootsCl(vo);
2886 CodeBlobToOopClosure blobsCl(&rootsCl, /*do_marking=*/ false);
2888 // We apply the relevant closures to all the oops in the
2889 // system dictionary, the string table and the code cache.
2890 const int so = SharedHeap::SO_AllClasses | SharedHeap::SO_Strings | SharedHeap::SO_CodeCache;
2892 process_strong_roots(true, // activate StrongRootsScope
2893 true, // we set "collecting perm gen" to true,
2894 // so we don't reset the dirty cards in the perm gen.
2895 SharedHeap::ScanningOption(so), // roots scanning options
2896 &rootsCl,
2897 &blobsCl,
2898 &rootsCl);
2900 // If we're verifying after the marking phase of a Full GC then we can't
2901 // treat the perm gen as roots into the G1 heap. Some of the objects in
2902 // the perm gen may be dead and hence not marked. If one of these dead
2903 // objects is considered to be a root then we may end up with a false
2904 // "Root location <x> points to dead ob <y>" failure.
2905 if (vo != VerifyOption_G1UseMarkWord) {
2906 // Since we used "collecting_perm_gen" == true above, we will not have
2907 // checked the refs from perm into the G1-collected heap. We check those
2908 // references explicitly below. Whether the relevant cards are dirty
2909 // is checked further below in the rem set verification.
2910 if (!silent) { gclog_or_tty->print("Permgen roots "); }
2911 perm_gen()->oop_iterate(&rootsCl);
2912 }
2913 bool failures = rootsCl.failures();
2915 if (vo != VerifyOption_G1UseMarkWord) {
2916 // If we're verifying during a full GC then the region sets
2917 // will have been torn down at the start of the GC. Therefore
2918 // verifying the region sets will fail. So we only verify
2919 // the region sets when not in a full GC.
2920 if (!silent) { gclog_or_tty->print("HeapRegionSets "); }
2921 verify_region_sets();
2922 }
2924 if (!silent) { gclog_or_tty->print("HeapRegions "); }
2925 if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
2926 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
2927 "sanity check");
2929 G1ParVerifyTask task(this, allow_dirty, vo);
2930 int n_workers = workers()->total_workers();
2931 set_par_threads(n_workers);
2932 workers()->run_task(&task);
2933 set_par_threads(0);
2934 if (task.failures()) {
2935 failures = true;
2936 }
2938 assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),
2939 "sanity check");
2941 reset_heap_region_claim_values();
2943 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
2944 "sanity check");
2945 } else {
2946 VerifyRegionClosure blk(allow_dirty, false, vo);
2947 heap_region_iterate(&blk);
2948 if (blk.failures()) {
2949 failures = true;
2950 }
2951 }
2952 if (!silent) gclog_or_tty->print("RemSet ");
2953 rem_set()->verify();
2955 if (failures) {
2956 gclog_or_tty->print_cr("Heap:");
2957 print_on(gclog_or_tty, true /* extended */);
2958 gclog_or_tty->print_cr("");
2959 #ifndef PRODUCT
2960 if (VerifyDuringGC && G1VerifyDuringGCPrintReachable) {
2961 concurrent_mark()->print_reachable("at-verification-failure",
2962 vo, false /* all */);
2963 }
2964 #endif
2965 gclog_or_tty->flush();
2966 }
2967 guarantee(!failures, "there should not have been any failures");
2968 } else {
2969 if (!silent) gclog_or_tty->print("(SKIPPING roots, heapRegions, remset) ");
2970 }
2971 }
2973 class PrintRegionClosure: public HeapRegionClosure {
2974 outputStream* _st;
2975 public:
2976 PrintRegionClosure(outputStream* st) : _st(st) {}
2977 bool doHeapRegion(HeapRegion* r) {
2978 r->print_on(_st);
2979 return false;
2980 }
2981 };
2983 void G1CollectedHeap::print() const { print_on(tty); }
2985 void G1CollectedHeap::print_on(outputStream* st) const {
2986 print_on(st, PrintHeapAtGCExtended);
2987 }
2989 void G1CollectedHeap::print_on(outputStream* st, bool extended) const {
2990 st->print(" %-20s", "garbage-first heap");
2991 st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
2992 capacity()/K, used_unlocked()/K);
2993 st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")",
2994 _g1_storage.low_boundary(),
2995 _g1_storage.high(),
2996 _g1_storage.high_boundary());
2997 st->cr();
2998 st->print(" region size " SIZE_FORMAT "K, ",
2999 HeapRegion::GrainBytes/K);
3000 size_t young_regions = _young_list->length();
3001 st->print(SIZE_FORMAT " young (" SIZE_FORMAT "K), ",
3002 young_regions, young_regions * HeapRegion::GrainBytes / K);
3003 size_t survivor_regions = g1_policy()->recorded_survivor_regions();
3004 st->print(SIZE_FORMAT " survivors (" SIZE_FORMAT "K)",
3005 survivor_regions, survivor_regions * HeapRegion::GrainBytes / K);
3006 st->cr();
3007 perm()->as_gen()->print_on(st);
3008 if (extended) {
3009 st->cr();
3010 print_on_extended(st);
3011 }
3012 }
3014 void G1CollectedHeap::print_on_extended(outputStream* st) const {
3015 PrintRegionClosure blk(st);
3016 heap_region_iterate(&blk);
3017 }
3019 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
3020 if (G1CollectedHeap::use_parallel_gc_threads()) {
3021 workers()->print_worker_threads_on(st);
3022 }
3023 _cmThread->print_on(st);
3024 st->cr();
3025 _cm->print_worker_threads_on(st);
3026 _cg1r->print_worker_threads_on(st);
3027 st->cr();
3028 }
3030 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
3031 if (G1CollectedHeap::use_parallel_gc_threads()) {
3032 workers()->threads_do(tc);
3033 }
3034 tc->do_thread(_cmThread);
3035 _cg1r->threads_do(tc);
3036 }
3038 void G1CollectedHeap::print_tracing_info() const {
3039 // We'll overload this to mean "trace GC pause statistics."
3040 if (TraceGen0Time || TraceGen1Time) {
3041 // The "G1CollectorPolicy" is keeping track of these stats, so delegate
3042 // to that.
3043 g1_policy()->print_tracing_info();
3044 }
3045 if (G1SummarizeRSetStats) {
3046 g1_rem_set()->print_summary_info();
3047 }
3048 if (G1SummarizeConcMark) {
3049 concurrent_mark()->print_summary_info();
3050 }
3051 g1_policy()->print_yg_surv_rate_info();
3052 SpecializationStats::print();
3053 }
3055 #ifndef PRODUCT
3056 // Helpful for debugging RSet issues.
3058 class PrintRSetsClosure : public HeapRegionClosure {
3059 private:
3060 const char* _msg;
3061 size_t _occupied_sum;
3063 public:
3064 bool doHeapRegion(HeapRegion* r) {
3065 HeapRegionRemSet* hrrs = r->rem_set();
3066 size_t occupied = hrrs->occupied();
3067 _occupied_sum += occupied;
3069 gclog_or_tty->print_cr("Printing RSet for region "HR_FORMAT,
3070 HR_FORMAT_PARAMS(r));
3071 if (occupied == 0) {
3072 gclog_or_tty->print_cr(" RSet is empty");
3073 } else {
3074 hrrs->print();
3075 }
3076 gclog_or_tty->print_cr("----------");
3077 return false;
3078 }
3080 PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
3081 gclog_or_tty->cr();
3082 gclog_or_tty->print_cr("========================================");
3083 gclog_or_tty->print_cr(msg);
3084 gclog_or_tty->cr();
3085 }
3087 ~PrintRSetsClosure() {
3088 gclog_or_tty->print_cr("Occupied Sum: "SIZE_FORMAT, _occupied_sum);
3089 gclog_or_tty->print_cr("========================================");
3090 gclog_or_tty->cr();
3091 }
3092 };
3094 void G1CollectedHeap::print_cset_rsets() {
3095 PrintRSetsClosure cl("Printing CSet RSets");
3096 collection_set_iterate(&cl);
3097 }
3099 void G1CollectedHeap::print_all_rsets() {
3100 PrintRSetsClosure cl("Printing All RSets");;
3101 heap_region_iterate(&cl);
3102 }
3103 #endif // PRODUCT
3105 G1CollectedHeap* G1CollectedHeap::heap() {
3106 assert(_sh->kind() == CollectedHeap::G1CollectedHeap,
3107 "not a garbage-first heap");
3108 return _g1h;
3109 }
3111 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {
3112 // always_do_update_barrier = false;
3113 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
3114 // Call allocation profiler
3115 AllocationProfiler::iterate_since_last_gc();
3116 // Fill TLAB's and such
3117 ensure_parsability(true);
3118 }
3120 void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) {
3121 // FIXME: what is this about?
3122 // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
3123 // is set.
3124 COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),
3125 "derived pointer present"));
3126 // always_do_update_barrier = true;
3127 }
3129 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
3130 unsigned int gc_count_before,
3131 bool* succeeded) {
3132 assert_heap_not_locked_and_not_at_safepoint();
3133 g1_policy()->record_stop_world_start();
3134 VM_G1IncCollectionPause op(gc_count_before,
3135 word_size,
3136 false, /* should_initiate_conc_mark */
3137 g1_policy()->max_pause_time_ms(),
3138 GCCause::_g1_inc_collection_pause);
3139 VMThread::execute(&op);
3141 HeapWord* result = op.result();
3142 bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded();
3143 assert(result == NULL || ret_succeeded,
3144 "the result should be NULL if the VM did not succeed");
3145 *succeeded = ret_succeeded;
3147 assert_heap_not_locked();
3148 return result;
3149 }
3151 void
3152 G1CollectedHeap::doConcurrentMark() {
3153 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
3154 if (!_cmThread->in_progress()) {
3155 _cmThread->set_started();
3156 CGC_lock->notify();
3157 }
3158 }
3160 // <NEW PREDICTION>
3162 double G1CollectedHeap::predict_region_elapsed_time_ms(HeapRegion *hr,
3163 bool young) {
3164 return _g1_policy->predict_region_elapsed_time_ms(hr, young);
3165 }
3167 void G1CollectedHeap::check_if_region_is_too_expensive(double
3168 predicted_time_ms) {
3169 _g1_policy->check_if_region_is_too_expensive(predicted_time_ms);
3170 }
3172 size_t G1CollectedHeap::pending_card_num() {
3173 size_t extra_cards = 0;
3174 JavaThread *curr = Threads::first();
3175 while (curr != NULL) {
3176 DirtyCardQueue& dcq = curr->dirty_card_queue();
3177 extra_cards += dcq.size();
3178 curr = curr->next();
3179 }
3180 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
3181 size_t buffer_size = dcqs.buffer_size();
3182 size_t buffer_num = dcqs.completed_buffers_num();
3183 return buffer_size * buffer_num + extra_cards;
3184 }
3186 size_t G1CollectedHeap::max_pending_card_num() {
3187 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
3188 size_t buffer_size = dcqs.buffer_size();
3189 size_t buffer_num = dcqs.completed_buffers_num();
3190 int thread_num = Threads::number_of_threads();
3191 return (buffer_num + thread_num) * buffer_size;
3192 }
3194 size_t G1CollectedHeap::cards_scanned() {
3195 return g1_rem_set()->cardsScanned();
3196 }
3198 void
3199 G1CollectedHeap::setup_surviving_young_words() {
3200 guarantee( _surviving_young_words == NULL, "pre-condition" );
3201 size_t array_length = g1_policy()->young_cset_length();
3202 _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, array_length);
3203 if (_surviving_young_words == NULL) {
3204 vm_exit_out_of_memory(sizeof(size_t) * array_length,
3205 "Not enough space for young surv words summary.");
3206 }
3207 memset(_surviving_young_words, 0, array_length * sizeof(size_t));
3208 #ifdef ASSERT
3209 for (size_t i = 0; i < array_length; ++i) {
3210 assert( _surviving_young_words[i] == 0, "memset above" );
3211 }
3212 #endif // !ASSERT
3213 }
3215 void
3216 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {
3217 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
3218 size_t array_length = g1_policy()->young_cset_length();
3219 for (size_t i = 0; i < array_length; ++i)
3220 _surviving_young_words[i] += surv_young_words[i];
3221 }
3223 void
3224 G1CollectedHeap::cleanup_surviving_young_words() {
3225 guarantee( _surviving_young_words != NULL, "pre-condition" );
3226 FREE_C_HEAP_ARRAY(size_t, _surviving_young_words);
3227 _surviving_young_words = NULL;
3228 }
3230 // </NEW PREDICTION>
3232 #ifdef ASSERT
3233 class VerifyCSetClosure: public HeapRegionClosure {
3234 public:
3235 bool doHeapRegion(HeapRegion* hr) {
3236 // Here we check that the CSet region's RSet is ready for parallel
3237 // iteration. The fields that we'll verify are only manipulated
3238 // when the region is part of a CSet and is collected. Afterwards,
3239 // we reset these fields when we clear the region's RSet (when the
3240 // region is freed) so they are ready when the region is
3241 // re-allocated. The only exception to this is if there's an
3242 // evacuation failure and instead of freeing the region we leave
3243 // it in the heap. In that case, we reset these fields during
3244 // evacuation failure handling.
3245 guarantee(hr->rem_set()->verify_ready_for_par_iteration(), "verification");
3247 // Here's a good place to add any other checks we'd like to
3248 // perform on CSet regions.
3249 return false;
3250 }
3251 };
3252 #endif // ASSERT
3254 #if TASKQUEUE_STATS
3255 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
3256 st->print_raw_cr("GC Task Stats");
3257 st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
3258 st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
3259 }
3261 void G1CollectedHeap::print_taskqueue_stats(outputStream* const st) const {
3262 print_taskqueue_stats_hdr(st);
3264 TaskQueueStats totals;
3265 const int n = workers() != NULL ? workers()->total_workers() : 1;
3266 for (int i = 0; i < n; ++i) {
3267 st->print("%3d ", i); task_queue(i)->stats.print(st); st->cr();
3268 totals += task_queue(i)->stats;
3269 }
3270 st->print_raw("tot "); totals.print(st); st->cr();
3272 DEBUG_ONLY(totals.verify());
3273 }
3275 void G1CollectedHeap::reset_taskqueue_stats() {
3276 const int n = workers() != NULL ? workers()->total_workers() : 1;
3277 for (int i = 0; i < n; ++i) {
3278 task_queue(i)->stats.reset();
3279 }
3280 }
3281 #endif // TASKQUEUE_STATS
3283 bool
3284 G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
3285 assert_at_safepoint(true /* should_be_vm_thread */);
3286 guarantee(!is_gc_active(), "collection is not reentrant");
3288 if (GC_locker::check_active_before_gc()) {
3289 return false;
3290 }
3292 SvcGCMarker sgcm(SvcGCMarker::MINOR);
3293 ResourceMark rm;
3295 if (PrintHeapAtGC) {
3296 Universe::print_heap_before_gc();
3297 }
3299 verify_region_sets_optional();
3300 verify_dirty_young_regions();
3302 {
3303 // This call will decide whether this pause is an initial-mark
3304 // pause. If it is, during_initial_mark_pause() will return true
3305 // for the duration of this pause.
3306 g1_policy()->decide_on_conc_mark_initiation();
3308 char verbose_str[128];
3309 sprintf(verbose_str, "GC pause ");
3310 if (g1_policy()->full_young_gcs()) {
3311 strcat(verbose_str, "(young)");
3312 } else {
3313 strcat(verbose_str, "(partial)");
3314 }
3315 if (g1_policy()->during_initial_mark_pause()) {
3316 strcat(verbose_str, " (initial-mark)");
3317 // We are about to start a marking cycle, so we increment the
3318 // full collection counter.
3319 increment_total_full_collections();
3320 }
3322 // if PrintGCDetails is on, we'll print long statistics information
3323 // in the collector policy code, so let's not print this as the output
3324 // is messy if we do.
3325 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
3326 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
3327 TraceTime t(verbose_str, PrintGC && !PrintGCDetails, true, gclog_or_tty);
3329 TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
3330 TraceMemoryManagerStats tms(false /* fullGC */, gc_cause());
3332 // If the secondary_free_list is not empty, append it to the
3333 // free_list. No need to wait for the cleanup operation to finish;
3334 // the region allocation code will check the secondary_free_list
3335 // and wait if necessary. If the G1StressConcRegionFreeing flag is
3336 // set, skip this step so that the region allocation code has to
3337 // get entries from the secondary_free_list.
3338 if (!G1StressConcRegionFreeing) {
3339 append_secondary_free_list_if_not_empty_with_lock();
3340 }
3342 assert(check_young_list_well_formed(),
3343 "young list should be well formed");
3345 { // Call to jvmpi::post_class_unload_events must occur outside of active GC
3346 IsGCActiveMark x;
3348 gc_prologue(false);
3349 increment_total_collections(false /* full gc */);
3350 increment_gc_time_stamp();
3352 if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) {
3353 HandleMark hm; // Discard invalid handles created during verification
3354 gclog_or_tty->print(" VerifyBeforeGC:");
3355 prepare_for_verify();
3356 Universe::verify(/* allow dirty */ false,
3357 /* silent */ false,
3358 /* option */ VerifyOption_G1UsePrevMarking);
3360 }
3362 COMPILER2_PRESENT(DerivedPointerTable::clear());
3364 // Please see comment in G1CollectedHeap::ref_processing_init()
3365 // to see how reference processing currently works in G1.
3366 //
3367 // We want to turn off ref discovery, if necessary, and turn it back on
3368 // on again later if we do. XXX Dubious: why is discovery disabled?
3369 bool was_enabled = ref_processor()->discovery_enabled();
3370 if (was_enabled) ref_processor()->disable_discovery();
3372 // Forget the current alloc region (we might even choose it to be part
3373 // of the collection set!).
3374 release_mutator_alloc_region();
3376 // We should call this after we retire the mutator alloc
3377 // region(s) so that all the ALLOC / RETIRE events are generated
3378 // before the start GC event.
3379 _hr_printer.start_gc(false /* full */, (size_t) total_collections());
3381 // The elapsed time induced by the start time below deliberately elides
3382 // the possible verification above.
3383 double start_time_sec = os::elapsedTime();
3384 size_t start_used_bytes = used();
3386 #if YOUNG_LIST_VERBOSE
3387 gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:");
3388 _young_list->print();
3389 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
3390 #endif // YOUNG_LIST_VERBOSE
3392 g1_policy()->record_collection_pause_start(start_time_sec,
3393 start_used_bytes);
3395 #if YOUNG_LIST_VERBOSE
3396 gclog_or_tty->print_cr("\nAfter recording pause start.\nYoung_list:");
3397 _young_list->print();
3398 #endif // YOUNG_LIST_VERBOSE
3400 if (g1_policy()->during_initial_mark_pause()) {
3401 concurrent_mark()->checkpointRootsInitialPre();
3402 }
3403 perm_gen()->save_marks();
3405 // We must do this before any possible evacuation that should propagate
3406 // marks.
3407 if (mark_in_progress()) {
3408 double start_time_sec = os::elapsedTime();
3410 _cm->drainAllSATBBuffers();
3411 double finish_mark_ms = (os::elapsedTime() - start_time_sec) * 1000.0;
3412 g1_policy()->record_satb_drain_time(finish_mark_ms);
3413 }
3414 // Record the number of elements currently on the mark stack, so we
3415 // only iterate over these. (Since evacuation may add to the mark
3416 // stack, doing more exposes race conditions.) If no mark is in
3417 // progress, this will be zero.
3418 _cm->set_oops_do_bound();
3420 if (mark_in_progress()) {
3421 concurrent_mark()->newCSet();
3422 }
3424 #if YOUNG_LIST_VERBOSE
3425 gclog_or_tty->print_cr("\nBefore choosing collection set.\nYoung_list:");
3426 _young_list->print();
3427 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
3428 #endif // YOUNG_LIST_VERBOSE
3430 g1_policy()->choose_collection_set(target_pause_time_ms);
3432 if (_hr_printer.is_active()) {
3433 HeapRegion* hr = g1_policy()->collection_set();
3434 while (hr != NULL) {
3435 G1HRPrinter::RegionType type;
3436 if (!hr->is_young()) {
3437 type = G1HRPrinter::Old;
3438 } else if (hr->is_survivor()) {
3439 type = G1HRPrinter::Survivor;
3440 } else {
3441 type = G1HRPrinter::Eden;
3442 }
3443 _hr_printer.cset(hr);
3444 hr = hr->next_in_collection_set();
3445 }
3446 }
3448 // We have chosen the complete collection set. If marking is
3449 // active then, we clear the region fields of any of the
3450 // concurrent marking tasks whose region fields point into
3451 // the collection set as these values will become stale. This
3452 // will cause the owning marking threads to claim a new region
3453 // when marking restarts.
3454 if (mark_in_progress()) {
3455 concurrent_mark()->reset_active_task_region_fields_in_cset();
3456 }
3458 #ifdef ASSERT
3459 VerifyCSetClosure cl;
3460 collection_set_iterate(&cl);
3461 #endif // ASSERT
3463 setup_surviving_young_words();
3465 // Initialize the GC alloc regions.
3466 init_gc_alloc_regions();
3468 // Actually do the work...
3469 evacuate_collection_set();
3471 free_collection_set(g1_policy()->collection_set());
3472 g1_policy()->clear_collection_set();
3474 cleanup_surviving_young_words();
3476 // Start a new incremental collection set for the next pause.
3477 g1_policy()->start_incremental_cset_building();
3479 // Clear the _cset_fast_test bitmap in anticipation of adding
3480 // regions to the incremental collection set for the next
3481 // evacuation pause.
3482 clear_cset_fast_test();
3484 _young_list->reset_sampled_info();
3486 // Don't check the whole heap at this point as the
3487 // GC alloc regions from this pause have been tagged
3488 // as survivors and moved on to the survivor list.
3489 // Survivor regions will fail the !is_young() check.
3490 assert(check_young_list_empty(false /* check_heap */),
3491 "young list should be empty");
3493 #if YOUNG_LIST_VERBOSE
3494 gclog_or_tty->print_cr("Before recording survivors.\nYoung List:");
3495 _young_list->print();
3496 #endif // YOUNG_LIST_VERBOSE
3498 g1_policy()->record_survivor_regions(_young_list->survivor_length(),
3499 _young_list->first_survivor_region(),
3500 _young_list->last_survivor_region());
3502 _young_list->reset_auxilary_lists();
3504 if (evacuation_failed()) {
3505 _summary_bytes_used = recalculate_used();
3506 } else {
3507 // The "used" of the the collection set have already been subtracted
3508 // when they were freed. Add in the bytes evacuated.
3509 _summary_bytes_used += g1_policy()->bytes_copied_during_gc();
3510 }
3512 if (g1_policy()->during_initial_mark_pause()) {
3513 concurrent_mark()->checkpointRootsInitialPost();
3514 set_marking_started();
3515 // CAUTION: after the doConcurrentMark() call below,
3516 // the concurrent marking thread(s) could be running
3517 // concurrently with us. Make sure that anything after
3518 // this point does not assume that we are the only GC thread
3519 // running. Note: of course, the actual marking work will
3520 // not start until the safepoint itself is released in
3521 // ConcurrentGCThread::safepoint_desynchronize().
3522 doConcurrentMark();
3523 }
3525 allocate_dummy_regions();
3527 #if YOUNG_LIST_VERBOSE
3528 gclog_or_tty->print_cr("\nEnd of the pause.\nYoung_list:");
3529 _young_list->print();
3530 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
3531 #endif // YOUNG_LIST_VERBOSE
3533 init_mutator_alloc_region();
3535 double end_time_sec = os::elapsedTime();
3536 double pause_time_ms = (end_time_sec - start_time_sec) * MILLIUNITS;
3537 g1_policy()->record_pause_time_ms(pause_time_ms);
3538 g1_policy()->record_collection_pause_end();
3540 MemoryService::track_memory_usage();
3542 // In prepare_for_verify() below we'll need to scan the deferred
3543 // update buffers to bring the RSets up-to-date if
3544 // G1HRRSFlushLogBuffersOnVerify has been set. While scanning
3545 // the update buffers we'll probably need to scan cards on the
3546 // regions we just allocated to (i.e., the GC alloc
3547 // regions). However, during the last GC we called
3548 // set_saved_mark() on all the GC alloc regions, so card
3549 // scanning might skip the [saved_mark_word()...top()] area of
3550 // those regions (i.e., the area we allocated objects into
3551 // during the last GC). But it shouldn't. Given that
3552 // saved_mark_word() is conditional on whether the GC time stamp
3553 // on the region is current or not, by incrementing the GC time
3554 // stamp here we invalidate all the GC time stamps on all the
3555 // regions and saved_mark_word() will simply return top() for
3556 // all the regions. This is a nicer way of ensuring this rather
3557 // than iterating over the regions and fixing them. In fact, the
3558 // GC time stamp increment here also ensures that
3559 // saved_mark_word() will return top() between pauses, i.e.,
3560 // during concurrent refinement. So we don't need the
3561 // is_gc_active() check to decided which top to use when
3562 // scanning cards (see CR 7039627).
3563 increment_gc_time_stamp();
3565 if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
3566 HandleMark hm; // Discard invalid handles created during verification
3567 gclog_or_tty->print(" VerifyAfterGC:");
3568 prepare_for_verify();
3569 Universe::verify(/* allow dirty */ true,
3570 /* silent */ false,
3571 /* option */ VerifyOption_G1UsePrevMarking);
3572 }
3574 if (was_enabled) ref_processor()->enable_discovery();
3576 {
3577 size_t expand_bytes = g1_policy()->expansion_amount();
3578 if (expand_bytes > 0) {
3579 size_t bytes_before = capacity();
3580 if (!expand(expand_bytes)) {
3581 // We failed to expand the heap so let's verify that
3582 // committed/uncommitted amount match the backing store
3583 assert(capacity() == _g1_storage.committed_size(), "committed size mismatch");
3584 assert(max_capacity() == _g1_storage.reserved_size(), "reserved size mismatch");
3585 }
3586 }
3587 }
3589 // We should do this after we potentially expand the heap so
3590 // that all the COMMIT events are generated before the end GC
3591 // event, and after we retire the GC alloc regions so that all
3592 // RETIRE events are generated before the end GC event.
3593 _hr_printer.end_gc(false /* full */, (size_t) total_collections());
3595 // We have to do this after we decide whether to expand the heap or not.
3596 g1_policy()->print_heap_transition();
3598 if (mark_in_progress()) {
3599 concurrent_mark()->update_g1_committed();
3600 }
3602 #ifdef TRACESPINNING
3603 ParallelTaskTerminator::print_termination_counts();
3604 #endif
3606 gc_epilogue(false);
3607 }
3609 if (ExitAfterGCNum > 0 && total_collections() == ExitAfterGCNum) {
3610 gclog_or_tty->print_cr("Stopping after GC #%d", ExitAfterGCNum);
3611 print_tracing_info();
3612 vm_exit(-1);
3613 }
3614 }
3616 _hrs.verify_optional();
3617 verify_region_sets_optional();
3619 TASKQUEUE_STATS_ONLY(if (ParallelGCVerbose) print_taskqueue_stats());
3620 TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
3622 if (PrintHeapAtGC) {
3623 Universe::print_heap_after_gc();
3624 }
3625 g1mm()->update_counters();
3627 if (G1SummarizeRSetStats &&
3628 (G1SummarizeRSetStatsPeriod > 0) &&
3629 (total_collections() % G1SummarizeRSetStatsPeriod == 0)) {
3630 g1_rem_set()->print_summary_info();
3631 }
3633 return true;
3634 }
3636 size_t G1CollectedHeap::desired_plab_sz(GCAllocPurpose purpose)
3637 {
3638 size_t gclab_word_size;
3639 switch (purpose) {
3640 case GCAllocForSurvived:
3641 gclab_word_size = YoungPLABSize;
3642 break;
3643 case GCAllocForTenured:
3644 gclab_word_size = OldPLABSize;
3645 break;
3646 default:
3647 assert(false, "unknown GCAllocPurpose");
3648 gclab_word_size = OldPLABSize;
3649 break;
3650 }
3651 return gclab_word_size;
3652 }
3654 void G1CollectedHeap::init_mutator_alloc_region() {
3655 assert(_mutator_alloc_region.get() == NULL, "pre-condition");
3656 _mutator_alloc_region.init();
3657 }
3659 void G1CollectedHeap::release_mutator_alloc_region() {
3660 _mutator_alloc_region.release();
3661 assert(_mutator_alloc_region.get() == NULL, "post-condition");
3662 }
3664 void G1CollectedHeap::init_gc_alloc_regions() {
3665 assert_at_safepoint(true /* should_be_vm_thread */);
3667 _survivor_gc_alloc_region.init();
3668 _old_gc_alloc_region.init();
3669 HeapRegion* retained_region = _retained_old_gc_alloc_region;
3670 _retained_old_gc_alloc_region = NULL;
3672 // We will discard the current GC alloc region if:
3673 // a) it's in the collection set (it can happen!),
3674 // b) it's already full (no point in using it),
3675 // c) it's empty (this means that it was emptied during
3676 // a cleanup and it should be on the free list now), or
3677 // d) it's humongous (this means that it was emptied
3678 // during a cleanup and was added to the free list, but
3679 // has been subseqently used to allocate a humongous
3680 // object that may be less than the region size).
3681 if (retained_region != NULL &&
3682 !retained_region->in_collection_set() &&
3683 !(retained_region->top() == retained_region->end()) &&
3684 !retained_region->is_empty() &&
3685 !retained_region->isHumongous()) {
3686 retained_region->set_saved_mark();
3687 _old_gc_alloc_region.set(retained_region);
3688 _hr_printer.reuse(retained_region);
3689 }
3690 }
3692 void G1CollectedHeap::release_gc_alloc_regions() {
3693 _survivor_gc_alloc_region.release();
3694 // If we have an old GC alloc region to release, we'll save it in
3695 // _retained_old_gc_alloc_region. If we don't
3696 // _retained_old_gc_alloc_region will become NULL. This is what we
3697 // want either way so no reason to check explicitly for either
3698 // condition.
3699 _retained_old_gc_alloc_region = _old_gc_alloc_region.release();
3700 }
3702 void G1CollectedHeap::abandon_gc_alloc_regions() {
3703 assert(_survivor_gc_alloc_region.get() == NULL, "pre-condition");
3704 assert(_old_gc_alloc_region.get() == NULL, "pre-condition");
3705 _retained_old_gc_alloc_region = NULL;
3706 }
3708 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {
3709 _drain_in_progress = false;
3710 set_evac_failure_closure(cl);
3711 _evac_failure_scan_stack = new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true);
3712 }
3714 void G1CollectedHeap::finalize_for_evac_failure() {
3715 assert(_evac_failure_scan_stack != NULL &&
3716 _evac_failure_scan_stack->length() == 0,
3717 "Postcondition");
3718 assert(!_drain_in_progress, "Postcondition");
3719 delete _evac_failure_scan_stack;
3720 _evac_failure_scan_stack = NULL;
3721 }
3723 // *** Sequential G1 Evacuation
3725 class G1IsAliveClosure: public BoolObjectClosure {
3726 G1CollectedHeap* _g1;
3727 public:
3728 G1IsAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
3729 void do_object(oop p) { assert(false, "Do not call."); }
3730 bool do_object_b(oop p) {
3731 // It is reachable if it is outside the collection set, or is inside
3732 // and forwarded.
3734 #ifdef G1_DEBUG
3735 gclog_or_tty->print_cr("is alive "PTR_FORMAT" in CS %d forwarded %d overall %d",
3736 (void*) p, _g1->obj_in_cs(p), p->is_forwarded(),
3737 !_g1->obj_in_cs(p) || p->is_forwarded());
3738 #endif // G1_DEBUG
3740 return !_g1->obj_in_cs(p) || p->is_forwarded();
3741 }
3742 };
3744 class G1KeepAliveClosure: public OopClosure {
3745 G1CollectedHeap* _g1;
3746 public:
3747 G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
3748 void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
3749 void do_oop( oop* p) {
3750 oop obj = *p;
3751 #ifdef G1_DEBUG
3752 if (PrintGC && Verbose) {
3753 gclog_or_tty->print_cr("keep alive *"PTR_FORMAT" = "PTR_FORMAT" "PTR_FORMAT,
3754 p, (void*) obj, (void*) *p);
3755 }
3756 #endif // G1_DEBUG
3758 if (_g1->obj_in_cs(obj)) {
3759 assert( obj->is_forwarded(), "invariant" );
3760 *p = obj->forwardee();
3761 #ifdef G1_DEBUG
3762 gclog_or_tty->print_cr(" in CSet: moved "PTR_FORMAT" -> "PTR_FORMAT,
3763 (void*) obj, (void*) *p);
3764 #endif // G1_DEBUG
3765 }
3766 }
3767 };
3769 class UpdateRSetDeferred : public OopsInHeapRegionClosure {
3770 private:
3771 G1CollectedHeap* _g1;
3772 DirtyCardQueue *_dcq;
3773 CardTableModRefBS* _ct_bs;
3775 public:
3776 UpdateRSetDeferred(G1CollectedHeap* g1, DirtyCardQueue* dcq) :
3777 _g1(g1), _ct_bs((CardTableModRefBS*)_g1->barrier_set()), _dcq(dcq) {}
3779 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
3780 virtual void do_oop( oop* p) { do_oop_work(p); }
3781 template <class T> void do_oop_work(T* p) {
3782 assert(_from->is_in_reserved(p), "paranoia");
3783 if (!_from->is_in_reserved(oopDesc::load_decode_heap_oop(p)) &&
3784 !_from->is_survivor()) {
3785 size_t card_index = _ct_bs->index_for(p);
3786 if (_ct_bs->mark_card_deferred(card_index)) {
3787 _dcq->enqueue((jbyte*)_ct_bs->byte_for_index(card_index));
3788 }
3789 }
3790 }
3791 };
3793 class RemoveSelfPointerClosure: public ObjectClosure {
3794 private:
3795 G1CollectedHeap* _g1;
3796 ConcurrentMark* _cm;
3797 HeapRegion* _hr;
3798 size_t _prev_marked_bytes;
3799 size_t _next_marked_bytes;
3800 OopsInHeapRegionClosure *_cl;
3801 public:
3802 RemoveSelfPointerClosure(G1CollectedHeap* g1, HeapRegion* hr,
3803 OopsInHeapRegionClosure* cl) :
3804 _g1(g1), _hr(hr), _cm(_g1->concurrent_mark()), _prev_marked_bytes(0),
3805 _next_marked_bytes(0), _cl(cl) {}
3807 size_t prev_marked_bytes() { return _prev_marked_bytes; }
3808 size_t next_marked_bytes() { return _next_marked_bytes; }
3810 // <original comment>
3811 // The original idea here was to coalesce evacuated and dead objects.
3812 // However that caused complications with the block offset table (BOT).
3813 // In particular if there were two TLABs, one of them partially refined.
3814 // |----- TLAB_1--------|----TLAB_2-~~~(partially refined part)~~~|
3815 // The BOT entries of the unrefined part of TLAB_2 point to the start
3816 // of TLAB_2. If the last object of the TLAB_1 and the first object
3817 // of TLAB_2 are coalesced, then the cards of the unrefined part
3818 // would point into middle of the filler object.
3819 // The current approach is to not coalesce and leave the BOT contents intact.
3820 // </original comment>
3821 //
3822 // We now reset the BOT when we start the object iteration over the
3823 // region and refine its entries for every object we come across. So
3824 // the above comment is not really relevant and we should be able
3825 // to coalesce dead objects if we want to.
3826 void do_object(oop obj) {
3827 HeapWord* obj_addr = (HeapWord*) obj;
3828 assert(_hr->is_in(obj_addr), "sanity");
3829 size_t obj_size = obj->size();
3830 _hr->update_bot_for_object(obj_addr, obj_size);
3831 if (obj->is_forwarded() && obj->forwardee() == obj) {
3832 // The object failed to move.
3833 assert(!_g1->is_obj_dead(obj), "We should not be preserving dead objs.");
3834 _cm->markPrev(obj);
3835 assert(_cm->isPrevMarked(obj), "Should be marked!");
3836 _prev_marked_bytes += (obj_size * HeapWordSize);
3837 if (_g1->mark_in_progress() && !_g1->is_obj_ill(obj)) {
3838 _cm->markAndGrayObjectIfNecessary(obj);
3839 }
3840 obj->set_mark(markOopDesc::prototype());
3841 // While we were processing RSet buffers during the
3842 // collection, we actually didn't scan any cards on the
3843 // collection set, since we didn't want to update remebered
3844 // sets with entries that point into the collection set, given
3845 // that live objects fromthe collection set are about to move
3846 // and such entries will be stale very soon. This change also
3847 // dealt with a reliability issue which involved scanning a
3848 // card in the collection set and coming across an array that
3849 // was being chunked and looking malformed. The problem is
3850 // that, if evacuation fails, we might have remembered set
3851 // entries missing given that we skipped cards on the
3852 // collection set. So, we'll recreate such entries now.
3853 obj->oop_iterate(_cl);
3854 assert(_cm->isPrevMarked(obj), "Should be marked!");
3855 } else {
3856 // The object has been either evacuated or is dead. Fill it with a
3857 // dummy object.
3858 MemRegion mr((HeapWord*)obj, obj_size);
3859 CollectedHeap::fill_with_object(mr);
3860 _cm->clearRangeBothMaps(mr);
3861 }
3862 }
3863 };
3865 void G1CollectedHeap::remove_self_forwarding_pointers() {
3866 UpdateRSetImmediate immediate_update(_g1h->g1_rem_set());
3867 DirtyCardQueue dcq(&_g1h->dirty_card_queue_set());
3868 UpdateRSetDeferred deferred_update(_g1h, &dcq);
3869 OopsInHeapRegionClosure *cl;
3870 if (G1DeferredRSUpdate) {
3871 cl = &deferred_update;
3872 } else {
3873 cl = &immediate_update;
3874 }
3875 HeapRegion* cur = g1_policy()->collection_set();
3876 while (cur != NULL) {
3877 assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!");
3878 assert(!cur->isHumongous(), "sanity");
3880 if (cur->evacuation_failed()) {
3881 assert(cur->in_collection_set(), "bad CS");
3882 RemoveSelfPointerClosure rspc(_g1h, cur, cl);
3884 // In the common case we make sure that this is done when the
3885 // region is freed so that it is "ready-to-go" when it's
3886 // re-allocated. However, when evacuation failure happens, a
3887 // region will remain in the heap and might ultimately be added
3888 // to a CSet in the future. So we have to be careful here and
3889 // make sure the region's RSet is ready for parallel iteration
3890 // whenever this might be required in the future.
3891 cur->rem_set()->reset_for_par_iteration();
3892 cur->reset_bot();
3893 cl->set_region(cur);
3894 cur->object_iterate(&rspc);
3896 // A number of manipulations to make the TAMS be the current top,
3897 // and the marked bytes be the ones observed in the iteration.
3898 if (_g1h->concurrent_mark()->at_least_one_mark_complete()) {
3899 // The comments below are the postconditions achieved by the
3900 // calls. Note especially the last such condition, which says that
3901 // the count of marked bytes has been properly restored.
3902 cur->note_start_of_marking(false);
3903 // _next_top_at_mark_start == top, _next_marked_bytes == 0
3904 cur->add_to_marked_bytes(rspc.prev_marked_bytes());
3905 // _next_marked_bytes == prev_marked_bytes.
3906 cur->note_end_of_marking();
3907 // _prev_top_at_mark_start == top(),
3908 // _prev_marked_bytes == prev_marked_bytes
3909 }
3910 // If there is no mark in progress, we modified the _next variables
3911 // above needlessly, but harmlessly.
3912 if (_g1h->mark_in_progress()) {
3913 cur->note_start_of_marking(false);
3914 // _next_top_at_mark_start == top, _next_marked_bytes == 0
3915 // _next_marked_bytes == next_marked_bytes.
3916 }
3918 // Now make sure the region has the right index in the sorted array.
3919 g1_policy()->note_change_in_marked_bytes(cur);
3920 }
3921 cur = cur->next_in_collection_set();
3922 }
3923 assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!");
3925 // Now restore saved marks, if any.
3926 if (_objs_with_preserved_marks != NULL) {
3927 assert(_preserved_marks_of_objs != NULL, "Both or none.");
3928 guarantee(_objs_with_preserved_marks->length() ==
3929 _preserved_marks_of_objs->length(), "Both or none.");
3930 for (int i = 0; i < _objs_with_preserved_marks->length(); i++) {
3931 oop obj = _objs_with_preserved_marks->at(i);
3932 markOop m = _preserved_marks_of_objs->at(i);
3933 obj->set_mark(m);
3934 }
3935 // Delete the preserved marks growable arrays (allocated on the C heap).
3936 delete _objs_with_preserved_marks;
3937 delete _preserved_marks_of_objs;
3938 _objs_with_preserved_marks = NULL;
3939 _preserved_marks_of_objs = NULL;
3940 }
3941 }
3943 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {
3944 _evac_failure_scan_stack->push(obj);
3945 }
3947 void G1CollectedHeap::drain_evac_failure_scan_stack() {
3948 assert(_evac_failure_scan_stack != NULL, "precondition");
3950 while (_evac_failure_scan_stack->length() > 0) {
3951 oop obj = _evac_failure_scan_stack->pop();
3952 _evac_failure_closure->set_region(heap_region_containing(obj));
3953 obj->oop_iterate_backwards(_evac_failure_closure);
3954 }
3955 }
3957 oop
3958 G1CollectedHeap::handle_evacuation_failure_par(OopsInHeapRegionClosure* cl,
3959 oop old) {
3960 assert(obj_in_cs(old),
3961 err_msg("obj: "PTR_FORMAT" should still be in the CSet",
3962 (HeapWord*) old));
3963 markOop m = old->mark();
3964 oop forward_ptr = old->forward_to_atomic(old);
3965 if (forward_ptr == NULL) {
3966 // Forward-to-self succeeded.
3967 if (_evac_failure_closure != cl) {
3968 MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag);
3969 assert(!_drain_in_progress,
3970 "Should only be true while someone holds the lock.");
3971 // Set the global evac-failure closure to the current thread's.
3972 assert(_evac_failure_closure == NULL, "Or locking has failed.");
3973 set_evac_failure_closure(cl);
3974 // Now do the common part.
3975 handle_evacuation_failure_common(old, m);
3976 // Reset to NULL.
3977 set_evac_failure_closure(NULL);
3978 } else {
3979 // The lock is already held, and this is recursive.
3980 assert(_drain_in_progress, "This should only be the recursive case.");
3981 handle_evacuation_failure_common(old, m);
3982 }
3983 return old;
3984 } else {
3985 // Forward-to-self failed. Either someone else managed to allocate
3986 // space for this object (old != forward_ptr) or they beat us in
3987 // self-forwarding it (old == forward_ptr).
3988 assert(old == forward_ptr || !obj_in_cs(forward_ptr),
3989 err_msg("obj: "PTR_FORMAT" forwarded to: "PTR_FORMAT" "
3990 "should not be in the CSet",
3991 (HeapWord*) old, (HeapWord*) forward_ptr));
3992 return forward_ptr;
3993 }
3994 }
3996 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) {
3997 set_evacuation_failed(true);
3999 preserve_mark_if_necessary(old, m);
4001 HeapRegion* r = heap_region_containing(old);
4002 if (!r->evacuation_failed()) {
4003 r->set_evacuation_failed(true);
4004 _hr_printer.evac_failure(r);
4005 }
4007 push_on_evac_failure_scan_stack(old);
4009 if (!_drain_in_progress) {
4010 // prevent recursion in copy_to_survivor_space()
4011 _drain_in_progress = true;
4012 drain_evac_failure_scan_stack();
4013 _drain_in_progress = false;
4014 }
4015 }
4017 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) {
4018 assert(evacuation_failed(), "Oversaving!");
4019 // We want to call the "for_promotion_failure" version only in the
4020 // case of a promotion failure.
4021 if (m->must_be_preserved_for_promotion_failure(obj)) {
4022 if (_objs_with_preserved_marks == NULL) {
4023 assert(_preserved_marks_of_objs == NULL, "Both or none.");
4024 _objs_with_preserved_marks =
4025 new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true);
4026 _preserved_marks_of_objs =
4027 new (ResourceObj::C_HEAP) GrowableArray<markOop>(40, true);
4028 }
4029 _objs_with_preserved_marks->push(obj);
4030 _preserved_marks_of_objs->push(m);
4031 }
4032 }
4034 HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose,
4035 size_t word_size) {
4036 if (purpose == GCAllocForSurvived) {
4037 HeapWord* result = survivor_attempt_allocation(word_size);
4038 if (result != NULL) {
4039 return result;
4040 } else {
4041 // Let's try to allocate in the old gen in case we can fit the
4042 // object there.
4043 return old_attempt_allocation(word_size);
4044 }
4045 } else {
4046 assert(purpose == GCAllocForTenured, "sanity");
4047 HeapWord* result = old_attempt_allocation(word_size);
4048 if (result != NULL) {
4049 return result;
4050 } else {
4051 // Let's try to allocate in the survivors in case we can fit the
4052 // object there.
4053 return survivor_attempt_allocation(word_size);
4054 }
4055 }
4057 ShouldNotReachHere();
4058 // Trying to keep some compilers happy.
4059 return NULL;
4060 }
4062 #ifndef PRODUCT
4063 bool GCLabBitMapClosure::do_bit(size_t offset) {
4064 HeapWord* addr = _bitmap->offsetToHeapWord(offset);
4065 guarantee(_cm->isMarked(oop(addr)), "it should be!");
4066 return true;
4067 }
4068 #endif // PRODUCT
4070 G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h, int queue_num)
4071 : _g1h(g1h),
4072 _refs(g1h->task_queue(queue_num)),
4073 _dcq(&g1h->dirty_card_queue_set()),
4074 _ct_bs((CardTableModRefBS*)_g1h->barrier_set()),
4075 _g1_rem(g1h->g1_rem_set()),
4076 _hash_seed(17), _queue_num(queue_num),
4077 _term_attempts(0),
4078 _surviving_alloc_buffer(g1h->desired_plab_sz(GCAllocForSurvived)),
4079 _tenured_alloc_buffer(g1h->desired_plab_sz(GCAllocForTenured)),
4080 _age_table(false),
4081 _strong_roots_time(0), _term_time(0),
4082 _alloc_buffer_waste(0), _undo_waste(0)
4083 {
4084 // we allocate G1YoungSurvRateNumRegions plus one entries, since
4085 // we "sacrifice" entry 0 to keep track of surviving bytes for
4086 // non-young regions (where the age is -1)
4087 // We also add a few elements at the beginning and at the end in
4088 // an attempt to eliminate cache contention
4089 size_t real_length = 1 + _g1h->g1_policy()->young_cset_length();
4090 size_t array_length = PADDING_ELEM_NUM +
4091 real_length +
4092 PADDING_ELEM_NUM;
4093 _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length);
4094 if (_surviving_young_words_base == NULL)
4095 vm_exit_out_of_memory(array_length * sizeof(size_t),
4096 "Not enough space for young surv histo.");
4097 _surviving_young_words = _surviving_young_words_base + PADDING_ELEM_NUM;
4098 memset(_surviving_young_words, 0, real_length * sizeof(size_t));
4100 _alloc_buffers[GCAllocForSurvived] = &_surviving_alloc_buffer;
4101 _alloc_buffers[GCAllocForTenured] = &_tenured_alloc_buffer;
4103 _start = os::elapsedTime();
4104 }
4106 void
4107 G1ParScanThreadState::print_termination_stats_hdr(outputStream* const st)
4108 {
4109 st->print_raw_cr("GC Termination Stats");
4110 st->print_raw_cr(" elapsed --strong roots-- -------termination-------"
4111 " ------waste (KiB)------");
4112 st->print_raw_cr("thr ms ms % ms % attempts"
4113 " total alloc undo");
4114 st->print_raw_cr("--- --------- --------- ------ --------- ------ --------"
4115 " ------- ------- -------");
4116 }
4118 void
4119 G1ParScanThreadState::print_termination_stats(int i,
4120 outputStream* const st) const
4121 {
4122 const double elapsed_ms = elapsed_time() * 1000.0;
4123 const double s_roots_ms = strong_roots_time() * 1000.0;
4124 const double term_ms = term_time() * 1000.0;
4125 st->print_cr("%3d %9.2f %9.2f %6.2f "
4126 "%9.2f %6.2f " SIZE_FORMAT_W(8) " "
4127 SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7),
4128 i, elapsed_ms, s_roots_ms, s_roots_ms * 100 / elapsed_ms,
4129 term_ms, term_ms * 100 / elapsed_ms, term_attempts(),
4130 (alloc_buffer_waste() + undo_waste()) * HeapWordSize / K,
4131 alloc_buffer_waste() * HeapWordSize / K,
4132 undo_waste() * HeapWordSize / K);
4133 }
4135 #ifdef ASSERT
4136 bool G1ParScanThreadState::verify_ref(narrowOop* ref) const {
4137 assert(ref != NULL, "invariant");
4138 assert(UseCompressedOops, "sanity");
4139 assert(!has_partial_array_mask(ref), err_msg("ref=" PTR_FORMAT, ref));
4140 oop p = oopDesc::load_decode_heap_oop(ref);
4141 assert(_g1h->is_in_g1_reserved(p),
4142 err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, intptr_t(p)));
4143 return true;
4144 }
4146 bool G1ParScanThreadState::verify_ref(oop* ref) const {
4147 assert(ref != NULL, "invariant");
4148 if (has_partial_array_mask(ref)) {
4149 // Must be in the collection set--it's already been copied.
4150 oop p = clear_partial_array_mask(ref);
4151 assert(_g1h->obj_in_cs(p),
4152 err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, intptr_t(p)));
4153 } else {
4154 oop p = oopDesc::load_decode_heap_oop(ref);
4155 assert(_g1h->is_in_g1_reserved(p),
4156 err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, intptr_t(p)));
4157 }
4158 return true;
4159 }
4161 bool G1ParScanThreadState::verify_task(StarTask ref) const {
4162 if (ref.is_narrow()) {
4163 return verify_ref((narrowOop*) ref);
4164 } else {
4165 return verify_ref((oop*) ref);
4166 }
4167 }
4168 #endif // ASSERT
4170 void G1ParScanThreadState::trim_queue() {
4171 StarTask ref;
4172 do {
4173 // Drain the overflow stack first, so other threads can steal.
4174 while (refs()->pop_overflow(ref)) {
4175 deal_with_reference(ref);
4176 }
4177 while (refs()->pop_local(ref)) {
4178 deal_with_reference(ref);
4179 }
4180 } while (!refs()->is_empty());
4181 }
4183 G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state) :
4184 _g1(g1), _g1_rem(_g1->g1_rem_set()), _cm(_g1->concurrent_mark()),
4185 _par_scan_state(par_scan_state) { }
4187 template <class T> void G1ParCopyHelper::mark_forwardee(T* p) {
4188 // This is called _after_ do_oop_work has been called, hence after
4189 // the object has been relocated to its new location and *p points
4190 // to its new location.
4192 T heap_oop = oopDesc::load_heap_oop(p);
4193 if (!oopDesc::is_null(heap_oop)) {
4194 oop obj = oopDesc::decode_heap_oop(heap_oop);
4195 HeapWord* addr = (HeapWord*)obj;
4196 if (_g1->is_in_g1_reserved(addr)) {
4197 _cm->grayRoot(oop(addr));
4198 }
4199 }
4200 }
4202 oop G1ParCopyHelper::copy_to_survivor_space(oop old) {
4203 size_t word_sz = old->size();
4204 HeapRegion* from_region = _g1->heap_region_containing_raw(old);
4205 // +1 to make the -1 indexes valid...
4206 int young_index = from_region->young_index_in_cset()+1;
4207 assert( (from_region->is_young() && young_index > 0) ||
4208 (!from_region->is_young() && young_index == 0), "invariant" );
4209 G1CollectorPolicy* g1p = _g1->g1_policy();
4210 markOop m = old->mark();
4211 int age = m->has_displaced_mark_helper() ? m->displaced_mark_helper()->age()
4212 : m->age();
4213 GCAllocPurpose alloc_purpose = g1p->evacuation_destination(from_region, age,
4214 word_sz);
4215 HeapWord* obj_ptr = _par_scan_state->allocate(alloc_purpose, word_sz);
4216 oop obj = oop(obj_ptr);
4218 if (obj_ptr == NULL) {
4219 // This will either forward-to-self, or detect that someone else has
4220 // installed a forwarding pointer.
4221 OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure();
4222 return _g1->handle_evacuation_failure_par(cl, old);
4223 }
4225 // We're going to allocate linearly, so might as well prefetch ahead.
4226 Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
4228 oop forward_ptr = old->forward_to_atomic(obj);
4229 if (forward_ptr == NULL) {
4230 Copy::aligned_disjoint_words((HeapWord*) old, obj_ptr, word_sz);
4231 if (g1p->track_object_age(alloc_purpose)) {
4232 // We could simply do obj->incr_age(). However, this causes a
4233 // performance issue. obj->incr_age() will first check whether
4234 // the object has a displaced mark by checking its mark word;
4235 // getting the mark word from the new location of the object
4236 // stalls. So, given that we already have the mark word and we
4237 // are about to install it anyway, it's better to increase the
4238 // age on the mark word, when the object does not have a
4239 // displaced mark word. We're not expecting many objects to have
4240 // a displaced marked word, so that case is not optimized
4241 // further (it could be...) and we simply call obj->incr_age().
4243 if (m->has_displaced_mark_helper()) {
4244 // in this case, we have to install the mark word first,
4245 // otherwise obj looks to be forwarded (the old mark word,
4246 // which contains the forward pointer, was copied)
4247 obj->set_mark(m);
4248 obj->incr_age();
4249 } else {
4250 m = m->incr_age();
4251 obj->set_mark(m);
4252 }
4253 _par_scan_state->age_table()->add(obj, word_sz);
4254 } else {
4255 obj->set_mark(m);
4256 }
4258 // preserve "next" mark bit
4259 if (_g1->mark_in_progress() && !_g1->is_obj_ill(old)) {
4260 if (!use_local_bitmaps ||
4261 !_par_scan_state->alloc_buffer(alloc_purpose)->mark(obj_ptr)) {
4262 // if we couldn't mark it on the local bitmap (this happens when
4263 // the object was not allocated in the GCLab), we have to bite
4264 // the bullet and do the standard parallel mark
4265 _cm->markAndGrayObjectIfNecessary(obj);
4266 }
4267 #if 1
4268 if (_g1->isMarkedNext(old)) {
4269 _cm->nextMarkBitMap()->parClear((HeapWord*)old);
4270 }
4271 #endif
4272 }
4274 size_t* surv_young_words = _par_scan_state->surviving_young_words();
4275 surv_young_words[young_index] += word_sz;
4277 if (obj->is_objArray() && arrayOop(obj)->length() >= ParGCArrayScanChunk) {
4278 arrayOop(old)->set_length(0);
4279 oop* old_p = set_partial_array_mask(old);
4280 _par_scan_state->push_on_queue(old_p);
4281 } else {
4282 // No point in using the slower heap_region_containing() method,
4283 // given that we know obj is in the heap.
4284 _scanner->set_region(_g1->heap_region_containing_raw(obj));
4285 obj->oop_iterate_backwards(_scanner);
4286 }
4287 } else {
4288 _par_scan_state->undo_allocation(alloc_purpose, obj_ptr, word_sz);
4289 obj = forward_ptr;
4290 }
4291 return obj;
4292 }
4294 template <bool do_gen_barrier, G1Barrier barrier, bool do_mark_forwardee>
4295 template <class T>
4296 void G1ParCopyClosure <do_gen_barrier, barrier, do_mark_forwardee>
4297 ::do_oop_work(T* p) {
4298 oop obj = oopDesc::load_decode_heap_oop(p);
4299 assert(barrier != G1BarrierRS || obj != NULL,
4300 "Precondition: G1BarrierRS implies obj is nonNull");
4302 // here the null check is implicit in the cset_fast_test() test
4303 if (_g1->in_cset_fast_test(obj)) {
4304 if (obj->is_forwarded()) {
4305 oopDesc::encode_store_heap_oop(p, obj->forwardee());
4306 } else {
4307 oop copy_oop = copy_to_survivor_space(obj);
4308 oopDesc::encode_store_heap_oop(p, copy_oop);
4309 }
4310 // When scanning the RS, we only care about objs in CS.
4311 if (barrier == G1BarrierRS) {
4312 _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num());
4313 }
4314 }
4316 if (barrier == G1BarrierEvac && obj != NULL) {
4317 _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num());
4318 }
4320 if (do_gen_barrier && obj != NULL) {
4321 par_do_barrier(p);
4322 }
4323 }
4325 template void G1ParCopyClosure<false, G1BarrierEvac, false>::do_oop_work(oop* p);
4326 template void G1ParCopyClosure<false, G1BarrierEvac, false>::do_oop_work(narrowOop* p);
4328 template <class T> void G1ParScanPartialArrayClosure::do_oop_nv(T* p) {
4329 assert(has_partial_array_mask(p), "invariant");
4330 oop old = clear_partial_array_mask(p);
4331 assert(old->is_objArray(), "must be obj array");
4332 assert(old->is_forwarded(), "must be forwarded");
4333 assert(Universe::heap()->is_in_reserved(old), "must be in heap.");
4335 objArrayOop obj = objArrayOop(old->forwardee());
4336 assert((void*)old != (void*)old->forwardee(), "self forwarding here?");
4337 // Process ParGCArrayScanChunk elements now
4338 // and push the remainder back onto queue
4339 int start = arrayOop(old)->length();
4340 int end = obj->length();
4341 int remainder = end - start;
4342 assert(start <= end, "just checking");
4343 if (remainder > 2 * ParGCArrayScanChunk) {
4344 // Test above combines last partial chunk with a full chunk
4345 end = start + ParGCArrayScanChunk;
4346 arrayOop(old)->set_length(end);
4347 // Push remainder.
4348 oop* old_p = set_partial_array_mask(old);
4349 assert(arrayOop(old)->length() < obj->length(), "Empty push?");
4350 _par_scan_state->push_on_queue(old_p);
4351 } else {
4352 // Restore length so that the heap remains parsable in
4353 // case of evacuation failure.
4354 arrayOop(old)->set_length(end);
4355 }
4356 _scanner.set_region(_g1->heap_region_containing_raw(obj));
4357 // process our set of indices (include header in first chunk)
4358 obj->oop_iterate_range(&_scanner, start, end);
4359 }
4361 class G1ParEvacuateFollowersClosure : public VoidClosure {
4362 protected:
4363 G1CollectedHeap* _g1h;
4364 G1ParScanThreadState* _par_scan_state;
4365 RefToScanQueueSet* _queues;
4366 ParallelTaskTerminator* _terminator;
4368 G1ParScanThreadState* par_scan_state() { return _par_scan_state; }
4369 RefToScanQueueSet* queues() { return _queues; }
4370 ParallelTaskTerminator* terminator() { return _terminator; }
4372 public:
4373 G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
4374 G1ParScanThreadState* par_scan_state,
4375 RefToScanQueueSet* queues,
4376 ParallelTaskTerminator* terminator)
4377 : _g1h(g1h), _par_scan_state(par_scan_state),
4378 _queues(queues), _terminator(terminator) {}
4380 void do_void();
4382 private:
4383 inline bool offer_termination();
4384 };
4386 bool G1ParEvacuateFollowersClosure::offer_termination() {
4387 G1ParScanThreadState* const pss = par_scan_state();
4388 pss->start_term_time();
4389 const bool res = terminator()->offer_termination();
4390 pss->end_term_time();
4391 return res;
4392 }
4394 void G1ParEvacuateFollowersClosure::do_void() {
4395 StarTask stolen_task;
4396 G1ParScanThreadState* const pss = par_scan_state();
4397 pss->trim_queue();
4399 do {
4400 while (queues()->steal(pss->queue_num(), pss->hash_seed(), stolen_task)) {
4401 assert(pss->verify_task(stolen_task), "sanity");
4402 if (stolen_task.is_narrow()) {
4403 pss->deal_with_reference((narrowOop*) stolen_task);
4404 } else {
4405 pss->deal_with_reference((oop*) stolen_task);
4406 }
4408 // We've just processed a reference and we might have made
4409 // available new entries on the queues. So we have to make sure
4410 // we drain the queues as necessary.
4411 pss->trim_queue();
4412 }
4413 } while (!offer_termination());
4415 pss->retire_alloc_buffers();
4416 }
4418 class G1ParTask : public AbstractGangTask {
4419 protected:
4420 G1CollectedHeap* _g1h;
4421 RefToScanQueueSet *_queues;
4422 ParallelTaskTerminator _terminator;
4423 int _n_workers;
4425 Mutex _stats_lock;
4426 Mutex* stats_lock() { return &_stats_lock; }
4428 size_t getNCards() {
4429 return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
4430 / G1BlockOffsetSharedArray::N_bytes;
4431 }
4433 public:
4434 G1ParTask(G1CollectedHeap* g1h, int workers, RefToScanQueueSet *task_queues)
4435 : AbstractGangTask("G1 collection"),
4436 _g1h(g1h),
4437 _queues(task_queues),
4438 _terminator(workers, _queues),
4439 _stats_lock(Mutex::leaf, "parallel G1 stats lock", true),
4440 _n_workers(workers)
4441 {}
4443 RefToScanQueueSet* queues() { return _queues; }
4445 RefToScanQueue *work_queue(int i) {
4446 return queues()->queue(i);
4447 }
4449 void work(int i) {
4450 if (i >= _n_workers) return; // no work needed this round
4452 double start_time_ms = os::elapsedTime() * 1000.0;
4453 _g1h->g1_policy()->record_gc_worker_start_time(i, start_time_ms);
4455 ResourceMark rm;
4456 HandleMark hm;
4458 G1ParScanThreadState pss(_g1h, i);
4459 G1ParScanHeapEvacClosure scan_evac_cl(_g1h, &pss);
4460 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss);
4461 G1ParScanPartialArrayClosure partial_scan_cl(_g1h, &pss);
4463 pss.set_evac_closure(&scan_evac_cl);
4464 pss.set_evac_failure_closure(&evac_failure_cl);
4465 pss.set_partial_scan_closure(&partial_scan_cl);
4467 G1ParScanExtRootClosure only_scan_root_cl(_g1h, &pss);
4468 G1ParScanPermClosure only_scan_perm_cl(_g1h, &pss);
4469 G1ParScanHeapRSClosure only_scan_heap_rs_cl(_g1h, &pss);
4470 G1ParPushHeapRSClosure push_heap_rs_cl(_g1h, &pss);
4472 G1ParScanAndMarkExtRootClosure scan_mark_root_cl(_g1h, &pss);
4473 G1ParScanAndMarkPermClosure scan_mark_perm_cl(_g1h, &pss);
4474 G1ParScanAndMarkHeapRSClosure scan_mark_heap_rs_cl(_g1h, &pss);
4476 OopsInHeapRegionClosure *scan_root_cl;
4477 OopsInHeapRegionClosure *scan_perm_cl;
4479 if (_g1h->g1_policy()->during_initial_mark_pause()) {
4480 scan_root_cl = &scan_mark_root_cl;
4481 scan_perm_cl = &scan_mark_perm_cl;
4482 } else {
4483 scan_root_cl = &only_scan_root_cl;
4484 scan_perm_cl = &only_scan_perm_cl;
4485 }
4487 pss.start_strong_roots();
4488 _g1h->g1_process_strong_roots(/* not collecting perm */ false,
4489 SharedHeap::SO_AllClasses,
4490 scan_root_cl,
4491 &push_heap_rs_cl,
4492 scan_perm_cl,
4493 i);
4494 pss.end_strong_roots();
4496 {
4497 double start = os::elapsedTime();
4498 G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);
4499 evac.do_void();
4500 double elapsed_ms = (os::elapsedTime()-start)*1000.0;
4501 double term_ms = pss.term_time()*1000.0;
4502 _g1h->g1_policy()->record_obj_copy_time(i, elapsed_ms-term_ms);
4503 _g1h->g1_policy()->record_termination(i, term_ms, pss.term_attempts());
4504 }
4505 _g1h->g1_policy()->record_thread_age_table(pss.age_table());
4506 _g1h->update_surviving_young_words(pss.surviving_young_words()+1);
4508 // Clean up any par-expanded rem sets.
4509 HeapRegionRemSet::par_cleanup();
4511 if (ParallelGCVerbose) {
4512 MutexLocker x(stats_lock());
4513 pss.print_termination_stats(i);
4514 }
4516 assert(pss.refs()->is_empty(), "should be empty");
4517 double end_time_ms = os::elapsedTime() * 1000.0;
4518 _g1h->g1_policy()->record_gc_worker_end_time(i, end_time_ms);
4519 }
4520 };
4522 // *** Common G1 Evacuation Stuff
4524 // This method is run in a GC worker.
4526 void
4527 G1CollectedHeap::
4528 g1_process_strong_roots(bool collecting_perm_gen,
4529 SharedHeap::ScanningOption so,
4530 OopClosure* scan_non_heap_roots,
4531 OopsInHeapRegionClosure* scan_rs,
4532 OopsInGenClosure* scan_perm,
4533 int worker_i) {
4534 // First scan the strong roots, including the perm gen.
4535 double ext_roots_start = os::elapsedTime();
4536 double closure_app_time_sec = 0.0;
4538 BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots);
4539 BufferingOopsInGenClosure buf_scan_perm(scan_perm);
4540 buf_scan_perm.set_generation(perm_gen());
4542 // Walk the code cache w/o buffering, because StarTask cannot handle
4543 // unaligned oop locations.
4544 CodeBlobToOopClosure eager_scan_code_roots(scan_non_heap_roots, /*do_marking=*/ true);
4546 process_strong_roots(false, // no scoping; this is parallel code
4547 collecting_perm_gen, so,
4548 &buf_scan_non_heap_roots,
4549 &eager_scan_code_roots,
4550 &buf_scan_perm);
4552 // Now the ref_processor roots.
4553 if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) {
4554 // We need to treat the discovered reference lists as roots and
4555 // keep entries (which are added by the marking threads) on them
4556 // live until they can be processed at the end of marking.
4557 ref_processor()->weak_oops_do(&buf_scan_non_heap_roots);
4558 ref_processor()->oops_do(&buf_scan_non_heap_roots);
4559 }
4561 // Finish up any enqueued closure apps (attributed as object copy time).
4562 buf_scan_non_heap_roots.done();
4563 buf_scan_perm.done();
4565 double ext_roots_end = os::elapsedTime();
4567 g1_policy()->reset_obj_copy_time(worker_i);
4568 double obj_copy_time_sec = buf_scan_perm.closure_app_seconds() +
4569 buf_scan_non_heap_roots.closure_app_seconds();
4570 g1_policy()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0);
4572 double ext_root_time_ms =
4573 ((ext_roots_end - ext_roots_start) - obj_copy_time_sec) * 1000.0;
4575 g1_policy()->record_ext_root_scan_time(worker_i, ext_root_time_ms);
4577 // Scan strong roots in mark stack.
4578 if (!_process_strong_tasks->is_task_claimed(G1H_PS_mark_stack_oops_do)) {
4579 concurrent_mark()->oops_do(scan_non_heap_roots);
4580 }
4581 double mark_stack_scan_ms = (os::elapsedTime() - ext_roots_end) * 1000.0;
4582 g1_policy()->record_mark_stack_scan_time(worker_i, mark_stack_scan_ms);
4584 // Now scan the complement of the collection set.
4585 if (scan_rs != NULL) {
4586 g1_rem_set()->oops_into_collection_set_do(scan_rs, worker_i);
4587 }
4589 _process_strong_tasks->all_tasks_completed();
4590 }
4592 void
4593 G1CollectedHeap::g1_process_weak_roots(OopClosure* root_closure,
4594 OopClosure* non_root_closure) {
4595 CodeBlobToOopClosure roots_in_blobs(root_closure, /*do_marking=*/ false);
4596 SharedHeap::process_weak_roots(root_closure, &roots_in_blobs, non_root_closure);
4597 }
4599 void G1CollectedHeap::evacuate_collection_set() {
4600 set_evacuation_failed(false);
4602 g1_rem_set()->prepare_for_oops_into_collection_set_do();
4603 concurrent_g1_refine()->set_use_cache(false);
4604 concurrent_g1_refine()->clear_hot_cache_claimed_index();
4606 int n_workers = (ParallelGCThreads > 0 ? workers()->total_workers() : 1);
4607 set_par_threads(n_workers);
4608 G1ParTask g1_par_task(this, n_workers, _task_queues);
4610 init_for_evac_failure(NULL);
4612 rem_set()->prepare_for_younger_refs_iterate(true);
4614 assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty");
4615 double start_par = os::elapsedTime();
4616 if (G1CollectedHeap::use_parallel_gc_threads()) {
4617 // The individual threads will set their evac-failure closures.
4618 StrongRootsScope srs(this);
4619 if (ParallelGCVerbose) G1ParScanThreadState::print_termination_stats_hdr();
4620 workers()->run_task(&g1_par_task);
4621 } else {
4622 StrongRootsScope srs(this);
4623 g1_par_task.work(0);
4624 }
4626 double par_time = (os::elapsedTime() - start_par) * 1000.0;
4627 g1_policy()->record_par_time(par_time);
4628 set_par_threads(0);
4630 // Weak root processing.
4631 // Note: when JSR 292 is enabled and code blobs can contain
4632 // non-perm oops then we will need to process the code blobs
4633 // here too.
4634 {
4635 G1IsAliveClosure is_alive(this);
4636 G1KeepAliveClosure keep_alive(this);
4637 JNIHandles::weak_oops_do(&is_alive, &keep_alive);
4638 }
4639 release_gc_alloc_regions();
4640 g1_rem_set()->cleanup_after_oops_into_collection_set_do();
4642 concurrent_g1_refine()->clear_hot_cache();
4643 concurrent_g1_refine()->set_use_cache(true);
4645 finalize_for_evac_failure();
4647 // Must do this before removing self-forwarding pointers, which clears
4648 // the per-region evac-failure flags.
4649 concurrent_mark()->complete_marking_in_collection_set();
4651 if (evacuation_failed()) {
4652 remove_self_forwarding_pointers();
4653 if (PrintGCDetails) {
4654 gclog_or_tty->print(" (to-space overflow)");
4655 } else if (PrintGC) {
4656 gclog_or_tty->print("--");
4657 }
4658 }
4660 if (G1DeferredRSUpdate) {
4661 RedirtyLoggedCardTableEntryFastClosure redirty;
4662 dirty_card_queue_set().set_closure(&redirty);
4663 dirty_card_queue_set().apply_closure_to_all_completed_buffers();
4665 DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set();
4666 dcq.merge_bufferlists(&dirty_card_queue_set());
4667 assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
4668 }
4669 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
4670 }
4672 void G1CollectedHeap::free_region_if_empty(HeapRegion* hr,
4673 size_t* pre_used,
4674 FreeRegionList* free_list,
4675 HumongousRegionSet* humongous_proxy_set,
4676 HRRSCleanupTask* hrrs_cleanup_task,
4677 bool par) {
4678 if (hr->used() > 0 && hr->max_live_bytes() == 0 && !hr->is_young()) {
4679 if (hr->isHumongous()) {
4680 assert(hr->startsHumongous(), "we should only see starts humongous");
4681 free_humongous_region(hr, pre_used, free_list, humongous_proxy_set, par);
4682 } else {
4683 free_region(hr, pre_used, free_list, par);
4684 }
4685 } else {
4686 hr->rem_set()->do_cleanup_work(hrrs_cleanup_task);
4687 }
4688 }
4690 void G1CollectedHeap::free_region(HeapRegion* hr,
4691 size_t* pre_used,
4692 FreeRegionList* free_list,
4693 bool par) {
4694 assert(!hr->isHumongous(), "this is only for non-humongous regions");
4695 assert(!hr->is_empty(), "the region should not be empty");
4696 assert(free_list != NULL, "pre-condition");
4698 *pre_used += hr->used();
4699 hr->hr_clear(par, true /* clear_space */);
4700 free_list->add_as_head(hr);
4701 }
4703 void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
4704 size_t* pre_used,
4705 FreeRegionList* free_list,
4706 HumongousRegionSet* humongous_proxy_set,
4707 bool par) {
4708 assert(hr->startsHumongous(), "this is only for starts humongous regions");
4709 assert(free_list != NULL, "pre-condition");
4710 assert(humongous_proxy_set != NULL, "pre-condition");
4712 size_t hr_used = hr->used();
4713 size_t hr_capacity = hr->capacity();
4714 size_t hr_pre_used = 0;
4715 _humongous_set.remove_with_proxy(hr, humongous_proxy_set);
4716 hr->set_notHumongous();
4717 free_region(hr, &hr_pre_used, free_list, par);
4719 size_t i = hr->hrs_index() + 1;
4720 size_t num = 1;
4721 while (i < n_regions()) {
4722 HeapRegion* curr_hr = region_at(i);
4723 if (!curr_hr->continuesHumongous()) {
4724 break;
4725 }
4726 curr_hr->set_notHumongous();
4727 free_region(curr_hr, &hr_pre_used, free_list, par);
4728 num += 1;
4729 i += 1;
4730 }
4731 assert(hr_pre_used == hr_used,
4732 err_msg("hr_pre_used: "SIZE_FORMAT" and hr_used: "SIZE_FORMAT" "
4733 "should be the same", hr_pre_used, hr_used));
4734 *pre_used += hr_pre_used;
4735 }
4737 void G1CollectedHeap::update_sets_after_freeing_regions(size_t pre_used,
4738 FreeRegionList* free_list,
4739 HumongousRegionSet* humongous_proxy_set,
4740 bool par) {
4741 if (pre_used > 0) {
4742 Mutex* lock = (par) ? ParGCRareEvent_lock : NULL;
4743 MutexLockerEx x(lock, Mutex::_no_safepoint_check_flag);
4744 assert(_summary_bytes_used >= pre_used,
4745 err_msg("invariant: _summary_bytes_used: "SIZE_FORMAT" "
4746 "should be >= pre_used: "SIZE_FORMAT,
4747 _summary_bytes_used, pre_used));
4748 _summary_bytes_used -= pre_used;
4749 }
4750 if (free_list != NULL && !free_list->is_empty()) {
4751 MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag);
4752 _free_list.add_as_head(free_list);
4753 }
4754 if (humongous_proxy_set != NULL && !humongous_proxy_set->is_empty()) {
4755 MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag);
4756 _humongous_set.update_from_proxy(humongous_proxy_set);
4757 }
4758 }
4760 class G1ParCleanupCTTask : public AbstractGangTask {
4761 CardTableModRefBS* _ct_bs;
4762 G1CollectedHeap* _g1h;
4763 HeapRegion* volatile _su_head;
4764 public:
4765 G1ParCleanupCTTask(CardTableModRefBS* ct_bs,
4766 G1CollectedHeap* g1h) :
4767 AbstractGangTask("G1 Par Cleanup CT Task"),
4768 _ct_bs(ct_bs), _g1h(g1h) { }
4770 void work(int i) {
4771 HeapRegion* r;
4772 while (r = _g1h->pop_dirty_cards_region()) {
4773 clear_cards(r);
4774 }
4775 }
4777 void clear_cards(HeapRegion* r) {
4778 // Cards of the survivors should have already been dirtied.
4779 if (!r->is_survivor()) {
4780 _ct_bs->clear(MemRegion(r->bottom(), r->end()));
4781 }
4782 }
4783 };
4785 #ifndef PRODUCT
4786 class G1VerifyCardTableCleanup: public HeapRegionClosure {
4787 G1CollectedHeap* _g1h;
4788 CardTableModRefBS* _ct_bs;
4789 public:
4790 G1VerifyCardTableCleanup(G1CollectedHeap* g1h, CardTableModRefBS* ct_bs)
4791 : _g1h(g1h), _ct_bs(ct_bs) { }
4792 virtual bool doHeapRegion(HeapRegion* r) {
4793 if (r->is_survivor()) {
4794 _g1h->verify_dirty_region(r);
4795 } else {
4796 _g1h->verify_not_dirty_region(r);
4797 }
4798 return false;
4799 }
4800 };
4802 void G1CollectedHeap::verify_not_dirty_region(HeapRegion* hr) {
4803 // All of the region should be clean.
4804 CardTableModRefBS* ct_bs = (CardTableModRefBS*)barrier_set();
4805 MemRegion mr(hr->bottom(), hr->end());
4806 ct_bs->verify_not_dirty_region(mr);
4807 }
4809 void G1CollectedHeap::verify_dirty_region(HeapRegion* hr) {
4810 // We cannot guarantee that [bottom(),end()] is dirty. Threads
4811 // dirty allocated blocks as they allocate them. The thread that
4812 // retires each region and replaces it with a new one will do a
4813 // maximal allocation to fill in [pre_dummy_top(),end()] but will
4814 // not dirty that area (one less thing to have to do while holding
4815 // a lock). So we can only verify that [bottom(),pre_dummy_top()]
4816 // is dirty.
4817 CardTableModRefBS* ct_bs = (CardTableModRefBS*) barrier_set();
4818 MemRegion mr(hr->bottom(), hr->pre_dummy_top());
4819 ct_bs->verify_dirty_region(mr);
4820 }
4822 void G1CollectedHeap::verify_dirty_young_list(HeapRegion* head) {
4823 CardTableModRefBS* ct_bs = (CardTableModRefBS*) barrier_set();
4824 for (HeapRegion* hr = head; hr != NULL; hr = hr->get_next_young_region()) {
4825 verify_dirty_region(hr);
4826 }
4827 }
4829 void G1CollectedHeap::verify_dirty_young_regions() {
4830 verify_dirty_young_list(_young_list->first_region());
4831 verify_dirty_young_list(_young_list->first_survivor_region());
4832 }
4833 #endif
4835 void G1CollectedHeap::cleanUpCardTable() {
4836 CardTableModRefBS* ct_bs = (CardTableModRefBS*) (barrier_set());
4837 double start = os::elapsedTime();
4839 // Iterate over the dirty cards region list.
4840 G1ParCleanupCTTask cleanup_task(ct_bs, this);
4842 if (ParallelGCThreads > 0) {
4843 set_par_threads(workers()->total_workers());
4844 workers()->run_task(&cleanup_task);
4845 set_par_threads(0);
4846 } else {
4847 while (_dirty_cards_region_list) {
4848 HeapRegion* r = _dirty_cards_region_list;
4849 cleanup_task.clear_cards(r);
4850 _dirty_cards_region_list = r->get_next_dirty_cards_region();
4851 if (_dirty_cards_region_list == r) {
4852 // The last region.
4853 _dirty_cards_region_list = NULL;
4854 }
4855 r->set_next_dirty_cards_region(NULL);
4856 }
4857 }
4859 double elapsed = os::elapsedTime() - start;
4860 g1_policy()->record_clear_ct_time( elapsed * 1000.0);
4861 #ifndef PRODUCT
4862 if (G1VerifyCTCleanup || VerifyAfterGC) {
4863 G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs);
4864 heap_region_iterate(&cleanup_verifier);
4865 }
4866 #endif
4867 }
4869 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head) {
4870 size_t pre_used = 0;
4871 FreeRegionList local_free_list("Local List for CSet Freeing");
4873 double young_time_ms = 0.0;
4874 double non_young_time_ms = 0.0;
4876 // Since the collection set is a superset of the the young list,
4877 // all we need to do to clear the young list is clear its
4878 // head and length, and unlink any young regions in the code below
4879 _young_list->clear();
4881 G1CollectorPolicy* policy = g1_policy();
4883 double start_sec = os::elapsedTime();
4884 bool non_young = true;
4886 HeapRegion* cur = cs_head;
4887 int age_bound = -1;
4888 size_t rs_lengths = 0;
4890 while (cur != NULL) {
4891 assert(!is_on_master_free_list(cur), "sanity");
4893 if (non_young) {
4894 if (cur->is_young()) {
4895 double end_sec = os::elapsedTime();
4896 double elapsed_ms = (end_sec - start_sec) * 1000.0;
4897 non_young_time_ms += elapsed_ms;
4899 start_sec = os::elapsedTime();
4900 non_young = false;
4901 }
4902 } else {
4903 double end_sec = os::elapsedTime();
4904 double elapsed_ms = (end_sec - start_sec) * 1000.0;
4905 young_time_ms += elapsed_ms;
4907 start_sec = os::elapsedTime();
4908 non_young = true;
4909 }
4911 rs_lengths += cur->rem_set()->occupied();
4913 HeapRegion* next = cur->next_in_collection_set();
4914 assert(cur->in_collection_set(), "bad CS");
4915 cur->set_next_in_collection_set(NULL);
4916 cur->set_in_collection_set(false);
4918 if (cur->is_young()) {
4919 int index = cur->young_index_in_cset();
4920 guarantee( index != -1, "invariant" );
4921 guarantee( (size_t)index < policy->young_cset_length(), "invariant" );
4922 size_t words_survived = _surviving_young_words[index];
4923 cur->record_surv_words_in_group(words_survived);
4925 // At this point the we have 'popped' cur from the collection set
4926 // (linked via next_in_collection_set()) but it is still in the
4927 // young list (linked via next_young_region()). Clear the
4928 // _next_young_region field.
4929 cur->set_next_young_region(NULL);
4930 } else {
4931 int index = cur->young_index_in_cset();
4932 guarantee( index == -1, "invariant" );
4933 }
4935 assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||
4936 (!cur->is_young() && cur->young_index_in_cset() == -1),
4937 "invariant" );
4939 if (!cur->evacuation_failed()) {
4940 // And the region is empty.
4941 assert(!cur->is_empty(), "Should not have empty regions in a CS.");
4942 free_region(cur, &pre_used, &local_free_list, false /* par */);
4943 } else {
4944 cur->uninstall_surv_rate_group();
4945 if (cur->is_young())
4946 cur->set_young_index_in_cset(-1);
4947 cur->set_not_young();
4948 cur->set_evacuation_failed(false);
4949 }
4950 cur = next;
4951 }
4953 policy->record_max_rs_lengths(rs_lengths);
4954 policy->cset_regions_freed();
4956 double end_sec = os::elapsedTime();
4957 double elapsed_ms = (end_sec - start_sec) * 1000.0;
4958 if (non_young)
4959 non_young_time_ms += elapsed_ms;
4960 else
4961 young_time_ms += elapsed_ms;
4963 update_sets_after_freeing_regions(pre_used, &local_free_list,
4964 NULL /* humongous_proxy_set */,
4965 false /* par */);
4966 policy->record_young_free_cset_time_ms(young_time_ms);
4967 policy->record_non_young_free_cset_time_ms(non_young_time_ms);
4968 }
4970 // This routine is similar to the above but does not record
4971 // any policy statistics or update free lists; we are abandoning
4972 // the current incremental collection set in preparation of a
4973 // full collection. After the full GC we will start to build up
4974 // the incremental collection set again.
4975 // This is only called when we're doing a full collection
4976 // and is immediately followed by the tearing down of the young list.
4978 void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) {
4979 HeapRegion* cur = cs_head;
4981 while (cur != NULL) {
4982 HeapRegion* next = cur->next_in_collection_set();
4983 assert(cur->in_collection_set(), "bad CS");
4984 cur->set_next_in_collection_set(NULL);
4985 cur->set_in_collection_set(false);
4986 cur->set_young_index_in_cset(-1);
4987 cur = next;
4988 }
4989 }
4991 void G1CollectedHeap::set_free_regions_coming() {
4992 if (G1ConcRegionFreeingVerbose) {
4993 gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
4994 "setting free regions coming");
4995 }
4997 assert(!free_regions_coming(), "pre-condition");
4998 _free_regions_coming = true;
4999 }
5001 void G1CollectedHeap::reset_free_regions_coming() {
5002 {
5003 assert(free_regions_coming(), "pre-condition");
5004 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
5005 _free_regions_coming = false;
5006 SecondaryFreeList_lock->notify_all();
5007 }
5009 if (G1ConcRegionFreeingVerbose) {
5010 gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : "
5011 "reset free regions coming");
5012 }
5013 }
5015 void G1CollectedHeap::wait_while_free_regions_coming() {
5016 // Most of the time we won't have to wait, so let's do a quick test
5017 // first before we take the lock.
5018 if (!free_regions_coming()) {
5019 return;
5020 }
5022 if (G1ConcRegionFreeingVerbose) {
5023 gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
5024 "waiting for free regions");
5025 }
5027 {
5028 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
5029 while (free_regions_coming()) {
5030 SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag);
5031 }
5032 }
5034 if (G1ConcRegionFreeingVerbose) {
5035 gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : "
5036 "done waiting for free regions");
5037 }
5038 }
5040 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
5041 assert(heap_lock_held_for_gc(),
5042 "the heap lock should already be held by or for this thread");
5043 _young_list->push_region(hr);
5044 g1_policy()->set_region_short_lived(hr);
5045 }
5047 class NoYoungRegionsClosure: public HeapRegionClosure {
5048 private:
5049 bool _success;
5050 public:
5051 NoYoungRegionsClosure() : _success(true) { }
5052 bool doHeapRegion(HeapRegion* r) {
5053 if (r->is_young()) {
5054 gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young",
5055 r->bottom(), r->end());
5056 _success = false;
5057 }
5058 return false;
5059 }
5060 bool success() { return _success; }
5061 };
5063 bool G1CollectedHeap::check_young_list_empty(bool check_heap, bool check_sample) {
5064 bool ret = _young_list->check_list_empty(check_sample);
5066 if (check_heap) {
5067 NoYoungRegionsClosure closure;
5068 heap_region_iterate(&closure);
5069 ret = ret && closure.success();
5070 }
5072 return ret;
5073 }
5075 void G1CollectedHeap::empty_young_list() {
5076 assert(heap_lock_held_for_gc(),
5077 "the heap lock should already be held by or for this thread");
5079 _young_list->empty_list();
5080 }
5082 // Done at the start of full GC.
5083 void G1CollectedHeap::tear_down_region_lists() {
5084 _free_list.remove_all();
5085 }
5087 class RegionResetter: public HeapRegionClosure {
5088 G1CollectedHeap* _g1h;
5089 FreeRegionList _local_free_list;
5091 public:
5092 RegionResetter() : _g1h(G1CollectedHeap::heap()),
5093 _local_free_list("Local Free List for RegionResetter") { }
5095 bool doHeapRegion(HeapRegion* r) {
5096 if (r->continuesHumongous()) return false;
5097 if (r->top() > r->bottom()) {
5098 if (r->top() < r->end()) {
5099 Copy::fill_to_words(r->top(),
5100 pointer_delta(r->end(), r->top()));
5101 }
5102 } else {
5103 assert(r->is_empty(), "tautology");
5104 _local_free_list.add_as_tail(r);
5105 }
5106 return false;
5107 }
5109 void update_free_lists() {
5110 _g1h->update_sets_after_freeing_regions(0, &_local_free_list, NULL,
5111 false /* par */);
5112 }
5113 };
5115 // Done at the end of full GC.
5116 void G1CollectedHeap::rebuild_region_lists() {
5117 // This needs to go at the end of the full GC.
5118 RegionResetter rs;
5119 heap_region_iterate(&rs);
5120 rs.update_free_lists();
5121 }
5123 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
5124 _refine_cte_cl->set_concurrent(concurrent);
5125 }
5127 bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
5128 HeapRegion* hr = heap_region_containing(p);
5129 if (hr == NULL) {
5130 return is_in_permanent(p);
5131 } else {
5132 return hr->is_in(p);
5133 }
5134 }
5136 // Methods for the mutator alloc region
5138 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
5139 bool force) {
5140 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
5141 assert(!force || g1_policy()->can_expand_young_list(),
5142 "if force is true we should be able to expand the young list");
5143 bool young_list_full = g1_policy()->is_young_list_full();
5144 if (force || !young_list_full) {
5145 HeapRegion* new_alloc_region = new_region(word_size,
5146 false /* do_expand */);
5147 if (new_alloc_region != NULL) {
5148 g1_policy()->update_region_num(true /* next_is_young */);
5149 set_region_short_lived_locked(new_alloc_region);
5150 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Eden, young_list_full);
5151 g1mm()->update_eden_counters();
5152 return new_alloc_region;
5153 }
5154 }
5155 return NULL;
5156 }
5158 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
5159 size_t allocated_bytes) {
5160 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
5161 assert(alloc_region->is_young(), "all mutator alloc regions should be young");
5163 g1_policy()->add_region_to_incremental_cset_lhs(alloc_region);
5164 _summary_bytes_used += allocated_bytes;
5165 _hr_printer.retire(alloc_region);
5166 }
5168 HeapRegion* MutatorAllocRegion::allocate_new_region(size_t word_size,
5169 bool force) {
5170 return _g1h->new_mutator_alloc_region(word_size, force);
5171 }
5173 void MutatorAllocRegion::retire_region(HeapRegion* alloc_region,
5174 size_t allocated_bytes) {
5175 _g1h->retire_mutator_alloc_region(alloc_region, allocated_bytes);
5176 }
5178 // Methods for the GC alloc regions
5180 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size,
5181 size_t count,
5182 GCAllocPurpose ap) {
5183 assert(FreeList_lock->owned_by_self(), "pre-condition");
5185 if (count < g1_policy()->max_regions(ap)) {
5186 HeapRegion* new_alloc_region = new_region(word_size,
5187 true /* do_expand */);
5188 if (new_alloc_region != NULL) {
5189 // We really only need to do this for old regions given that we
5190 // should never scan survivors. But it doesn't hurt to do it
5191 // for survivors too.
5192 new_alloc_region->set_saved_mark();
5193 if (ap == GCAllocForSurvived) {
5194 new_alloc_region->set_survivor();
5195 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor);
5196 } else {
5197 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Old);
5198 }
5199 return new_alloc_region;
5200 } else {
5201 g1_policy()->note_alloc_region_limit_reached(ap);
5202 }
5203 }
5204 return NULL;
5205 }
5207 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
5208 size_t allocated_bytes,
5209 GCAllocPurpose ap) {
5210 alloc_region->note_end_of_copying();
5211 g1_policy()->record_bytes_copied_during_gc(allocated_bytes);
5212 if (ap == GCAllocForSurvived) {
5213 young_list()->add_survivor_region(alloc_region);
5214 }
5215 _hr_printer.retire(alloc_region);
5216 }
5218 HeapRegion* SurvivorGCAllocRegion::allocate_new_region(size_t word_size,
5219 bool force) {
5220 assert(!force, "not supported for GC alloc regions");
5221 return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForSurvived);
5222 }
5224 void SurvivorGCAllocRegion::retire_region(HeapRegion* alloc_region,
5225 size_t allocated_bytes) {
5226 _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
5227 GCAllocForSurvived);
5228 }
5230 HeapRegion* OldGCAllocRegion::allocate_new_region(size_t word_size,
5231 bool force) {
5232 assert(!force, "not supported for GC alloc regions");
5233 return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForTenured);
5234 }
5236 void OldGCAllocRegion::retire_region(HeapRegion* alloc_region,
5237 size_t allocated_bytes) {
5238 _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes,
5239 GCAllocForTenured);
5240 }
5241 // Heap region set verification
5243 class VerifyRegionListsClosure : public HeapRegionClosure {
5244 private:
5245 HumongousRegionSet* _humongous_set;
5246 FreeRegionList* _free_list;
5247 size_t _region_count;
5249 public:
5250 VerifyRegionListsClosure(HumongousRegionSet* humongous_set,
5251 FreeRegionList* free_list) :
5252 _humongous_set(humongous_set), _free_list(free_list),
5253 _region_count(0) { }
5255 size_t region_count() { return _region_count; }
5257 bool doHeapRegion(HeapRegion* hr) {
5258 _region_count += 1;
5260 if (hr->continuesHumongous()) {
5261 return false;
5262 }
5264 if (hr->is_young()) {
5265 // TODO
5266 } else if (hr->startsHumongous()) {
5267 _humongous_set->verify_next_region(hr);
5268 } else if (hr->is_empty()) {
5269 _free_list->verify_next_region(hr);
5270 }
5271 return false;
5272 }
5273 };
5275 HeapRegion* G1CollectedHeap::new_heap_region(size_t hrs_index,
5276 HeapWord* bottom) {
5277 HeapWord* end = bottom + HeapRegion::GrainWords;
5278 MemRegion mr(bottom, end);
5279 assert(_g1_reserved.contains(mr), "invariant");
5280 // This might return NULL if the allocation fails
5281 return new HeapRegion(hrs_index, _bot_shared, mr, true /* is_zeroed */);
5282 }
5284 void G1CollectedHeap::verify_region_sets() {
5285 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
5287 // First, check the explicit lists.
5288 _free_list.verify();
5289 {
5290 // Given that a concurrent operation might be adding regions to
5291 // the secondary free list we have to take the lock before
5292 // verifying it.
5293 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
5294 _secondary_free_list.verify();
5295 }
5296 _humongous_set.verify();
5298 // If a concurrent region freeing operation is in progress it will
5299 // be difficult to correctly attributed any free regions we come
5300 // across to the correct free list given that they might belong to
5301 // one of several (free_list, secondary_free_list, any local lists,
5302 // etc.). So, if that's the case we will skip the rest of the
5303 // verification operation. Alternatively, waiting for the concurrent
5304 // operation to complete will have a non-trivial effect on the GC's
5305 // operation (no concurrent operation will last longer than the
5306 // interval between two calls to verification) and it might hide
5307 // any issues that we would like to catch during testing.
5308 if (free_regions_coming()) {
5309 return;
5310 }
5312 // Make sure we append the secondary_free_list on the free_list so
5313 // that all free regions we will come across can be safely
5314 // attributed to the free_list.
5315 append_secondary_free_list_if_not_empty_with_lock();
5317 // Finally, make sure that the region accounting in the lists is
5318 // consistent with what we see in the heap.
5319 _humongous_set.verify_start();
5320 _free_list.verify_start();
5322 VerifyRegionListsClosure cl(&_humongous_set, &_free_list);
5323 heap_region_iterate(&cl);
5325 _humongous_set.verify_end();
5326 _free_list.verify_end();
5327 }