Fri, 01 Oct 2010 18:23:16 -0700
6983311: G1: LoopTest hangs when run with -XX:+ExplicitInvokesConcurrent
Summary: Clear the concurrent marking "in progress" flag while the FullGCCount_lock is held. This avoids a race that can cause back to back System.gc() calls, when ExplicitGCInvokesConcurrent is enabled, to fail to initiate a marking cycle causing the requesting thread to hang.
Reviewed-by: tonyp, ysr
1 /*
2 * Copyright (c) 2001, 2010, 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 "incls/_precompiled.incl"
26 #include "incls/_g1CollectedHeap.cpp.incl"
28 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
30 // turn it on so that the contents of the young list (scan-only /
31 // to-be-collected) are printed at "strategic" points before / during
32 // / after the collection --- this is useful for debugging
33 #define YOUNG_LIST_VERBOSE 0
34 // CURRENT STATUS
35 // This file is under construction. Search for "FIXME".
37 // INVARIANTS/NOTES
38 //
39 // All allocation activity covered by the G1CollectedHeap interface is
40 // serialized by acquiring the HeapLock. This happens in
41 // mem_allocate_work, which all such allocation functions call.
42 // (Note that this does not apply to TLAB allocation, which is not part
43 // of this interface: it is done by clients of this interface.)
45 // Local to this file.
47 class RefineCardTableEntryClosure: public CardTableEntryClosure {
48 SuspendibleThreadSet* _sts;
49 G1RemSet* _g1rs;
50 ConcurrentG1Refine* _cg1r;
51 bool _concurrent;
52 public:
53 RefineCardTableEntryClosure(SuspendibleThreadSet* sts,
54 G1RemSet* g1rs,
55 ConcurrentG1Refine* cg1r) :
56 _sts(sts), _g1rs(g1rs), _cg1r(cg1r), _concurrent(true)
57 {}
58 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
59 bool oops_into_cset = _g1rs->concurrentRefineOneCard(card_ptr, worker_i, false);
60 // This path is executed by the concurrent refine or mutator threads,
61 // concurrently, and so we do not care if card_ptr contains references
62 // that point into the collection set.
63 assert(!oops_into_cset, "should be");
65 if (_concurrent && _sts->should_yield()) {
66 // Caller will actually yield.
67 return false;
68 }
69 // Otherwise, we finished successfully; return true.
70 return true;
71 }
72 void set_concurrent(bool b) { _concurrent = b; }
73 };
76 class ClearLoggedCardTableEntryClosure: public CardTableEntryClosure {
77 int _calls;
78 G1CollectedHeap* _g1h;
79 CardTableModRefBS* _ctbs;
80 int _histo[256];
81 public:
82 ClearLoggedCardTableEntryClosure() :
83 _calls(0)
84 {
85 _g1h = G1CollectedHeap::heap();
86 _ctbs = (CardTableModRefBS*)_g1h->barrier_set();
87 for (int i = 0; i < 256; i++) _histo[i] = 0;
88 }
89 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
90 if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
91 _calls++;
92 unsigned char* ujb = (unsigned char*)card_ptr;
93 int ind = (int)(*ujb);
94 _histo[ind]++;
95 *card_ptr = -1;
96 }
97 return true;
98 }
99 int calls() { return _calls; }
100 void print_histo() {
101 gclog_or_tty->print_cr("Card table value histogram:");
102 for (int i = 0; i < 256; i++) {
103 if (_histo[i] != 0) {
104 gclog_or_tty->print_cr(" %d: %d", i, _histo[i]);
105 }
106 }
107 }
108 };
110 class RedirtyLoggedCardTableEntryClosure: public CardTableEntryClosure {
111 int _calls;
112 G1CollectedHeap* _g1h;
113 CardTableModRefBS* _ctbs;
114 public:
115 RedirtyLoggedCardTableEntryClosure() :
116 _calls(0)
117 {
118 _g1h = G1CollectedHeap::heap();
119 _ctbs = (CardTableModRefBS*)_g1h->barrier_set();
120 }
121 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
122 if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
123 _calls++;
124 *card_ptr = 0;
125 }
126 return true;
127 }
128 int calls() { return _calls; }
129 };
131 class RedirtyLoggedCardTableEntryFastClosure : public CardTableEntryClosure {
132 public:
133 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
134 *card_ptr = CardTableModRefBS::dirty_card_val();
135 return true;
136 }
137 };
139 YoungList::YoungList(G1CollectedHeap* g1h)
140 : _g1h(g1h), _head(NULL),
141 _length(0),
142 _last_sampled_rs_lengths(0),
143 _survivor_head(NULL), _survivor_tail(NULL), _survivor_length(0)
144 {
145 guarantee( check_list_empty(false), "just making sure..." );
146 }
148 void YoungList::push_region(HeapRegion *hr) {
149 assert(!hr->is_young(), "should not already be young");
150 assert(hr->get_next_young_region() == NULL, "cause it should!");
152 hr->set_next_young_region(_head);
153 _head = hr;
155 hr->set_young();
156 double yg_surv_rate = _g1h->g1_policy()->predict_yg_surv_rate((int)_length);
157 ++_length;
158 }
160 void YoungList::add_survivor_region(HeapRegion* hr) {
161 assert(hr->is_survivor(), "should be flagged as survivor region");
162 assert(hr->get_next_young_region() == NULL, "cause it should!");
164 hr->set_next_young_region(_survivor_head);
165 if (_survivor_head == NULL) {
166 _survivor_tail = hr;
167 }
168 _survivor_head = hr;
170 ++_survivor_length;
171 }
173 void YoungList::empty_list(HeapRegion* list) {
174 while (list != NULL) {
175 HeapRegion* next = list->get_next_young_region();
176 list->set_next_young_region(NULL);
177 list->uninstall_surv_rate_group();
178 list->set_not_young();
179 list = next;
180 }
181 }
183 void YoungList::empty_list() {
184 assert(check_list_well_formed(), "young list should be well formed");
186 empty_list(_head);
187 _head = NULL;
188 _length = 0;
190 empty_list(_survivor_head);
191 _survivor_head = NULL;
192 _survivor_tail = NULL;
193 _survivor_length = 0;
195 _last_sampled_rs_lengths = 0;
197 assert(check_list_empty(false), "just making sure...");
198 }
200 bool YoungList::check_list_well_formed() {
201 bool ret = true;
203 size_t length = 0;
204 HeapRegion* curr = _head;
205 HeapRegion* last = NULL;
206 while (curr != NULL) {
207 if (!curr->is_young()) {
208 gclog_or_tty->print_cr("### YOUNG REGION "PTR_FORMAT"-"PTR_FORMAT" "
209 "incorrectly tagged (y: %d, surv: %d)",
210 curr->bottom(), curr->end(),
211 curr->is_young(), curr->is_survivor());
212 ret = false;
213 }
214 ++length;
215 last = curr;
216 curr = curr->get_next_young_region();
217 }
218 ret = ret && (length == _length);
220 if (!ret) {
221 gclog_or_tty->print_cr("### YOUNG LIST seems not well formed!");
222 gclog_or_tty->print_cr("### list has %d entries, _length is %d",
223 length, _length);
224 }
226 return ret;
227 }
229 bool YoungList::check_list_empty(bool check_sample) {
230 bool ret = true;
232 if (_length != 0) {
233 gclog_or_tty->print_cr("### YOUNG LIST should have 0 length, not %d",
234 _length);
235 ret = false;
236 }
237 if (check_sample && _last_sampled_rs_lengths != 0) {
238 gclog_or_tty->print_cr("### YOUNG LIST has non-zero last sampled RS lengths");
239 ret = false;
240 }
241 if (_head != NULL) {
242 gclog_or_tty->print_cr("### YOUNG LIST does not have a NULL head");
243 ret = false;
244 }
245 if (!ret) {
246 gclog_or_tty->print_cr("### YOUNG LIST does not seem empty");
247 }
249 return ret;
250 }
252 void
253 YoungList::rs_length_sampling_init() {
254 _sampled_rs_lengths = 0;
255 _curr = _head;
256 }
258 bool
259 YoungList::rs_length_sampling_more() {
260 return _curr != NULL;
261 }
263 void
264 YoungList::rs_length_sampling_next() {
265 assert( _curr != NULL, "invariant" );
266 size_t rs_length = _curr->rem_set()->occupied();
268 _sampled_rs_lengths += rs_length;
270 // The current region may not yet have been added to the
271 // incremental collection set (it gets added when it is
272 // retired as the current allocation region).
273 if (_curr->in_collection_set()) {
274 // Update the collection set policy information for this region
275 _g1h->g1_policy()->update_incremental_cset_info(_curr, rs_length);
276 }
278 _curr = _curr->get_next_young_region();
279 if (_curr == NULL) {
280 _last_sampled_rs_lengths = _sampled_rs_lengths;
281 // gclog_or_tty->print_cr("last sampled RS lengths = %d", _last_sampled_rs_lengths);
282 }
283 }
285 void
286 YoungList::reset_auxilary_lists() {
287 guarantee( is_empty(), "young list should be empty" );
288 assert(check_list_well_formed(), "young list should be well formed");
290 // Add survivor regions to SurvRateGroup.
291 _g1h->g1_policy()->note_start_adding_survivor_regions();
292 _g1h->g1_policy()->finished_recalculating_age_indexes(true /* is_survivors */);
294 for (HeapRegion* curr = _survivor_head;
295 curr != NULL;
296 curr = curr->get_next_young_region()) {
297 _g1h->g1_policy()->set_region_survivors(curr);
299 // The region is a non-empty survivor so let's add it to
300 // the incremental collection set for the next evacuation
301 // pause.
302 _g1h->g1_policy()->add_region_to_incremental_cset_rhs(curr);
303 }
304 _g1h->g1_policy()->note_stop_adding_survivor_regions();
306 _head = _survivor_head;
307 _length = _survivor_length;
308 if (_survivor_head != NULL) {
309 assert(_survivor_tail != NULL, "cause it shouldn't be");
310 assert(_survivor_length > 0, "invariant");
311 _survivor_tail->set_next_young_region(NULL);
312 }
314 // Don't clear the survivor list handles until the start of
315 // the next evacuation pause - we need it in order to re-tag
316 // the survivor regions from this evacuation pause as 'young'
317 // at the start of the next.
319 _g1h->g1_policy()->finished_recalculating_age_indexes(false /* is_survivors */);
321 assert(check_list_well_formed(), "young list should be well formed");
322 }
324 void YoungList::print() {
325 HeapRegion* lists[] = {_head, _survivor_head};
326 const char* names[] = {"YOUNG", "SURVIVOR"};
328 for (unsigned int list = 0; list < ARRAY_SIZE(lists); ++list) {
329 gclog_or_tty->print_cr("%s LIST CONTENTS", names[list]);
330 HeapRegion *curr = lists[list];
331 if (curr == NULL)
332 gclog_or_tty->print_cr(" empty");
333 while (curr != NULL) {
334 gclog_or_tty->print_cr(" [%08x-%08x], t: %08x, P: %08x, N: %08x, C: %08x, "
335 "age: %4d, y: %d, surv: %d",
336 curr->bottom(), curr->end(),
337 curr->top(),
338 curr->prev_top_at_mark_start(),
339 curr->next_top_at_mark_start(),
340 curr->top_at_conc_mark_count(),
341 curr->age_in_surv_rate_group_cond(),
342 curr->is_young(),
343 curr->is_survivor());
344 curr = curr->get_next_young_region();
345 }
346 }
348 gclog_or_tty->print_cr("");
349 }
351 void G1CollectedHeap::push_dirty_cards_region(HeapRegion* hr)
352 {
353 // Claim the right to put the region on the dirty cards region list
354 // by installing a self pointer.
355 HeapRegion* next = hr->get_next_dirty_cards_region();
356 if (next == NULL) {
357 HeapRegion* res = (HeapRegion*)
358 Atomic::cmpxchg_ptr(hr, hr->next_dirty_cards_region_addr(),
359 NULL);
360 if (res == NULL) {
361 HeapRegion* head;
362 do {
363 // Put the region to the dirty cards region list.
364 head = _dirty_cards_region_list;
365 next = (HeapRegion*)
366 Atomic::cmpxchg_ptr(hr, &_dirty_cards_region_list, head);
367 if (next == head) {
368 assert(hr->get_next_dirty_cards_region() == hr,
369 "hr->get_next_dirty_cards_region() != hr");
370 if (next == NULL) {
371 // The last region in the list points to itself.
372 hr->set_next_dirty_cards_region(hr);
373 } else {
374 hr->set_next_dirty_cards_region(next);
375 }
376 }
377 } while (next != head);
378 }
379 }
380 }
382 HeapRegion* G1CollectedHeap::pop_dirty_cards_region()
383 {
384 HeapRegion* head;
385 HeapRegion* hr;
386 do {
387 head = _dirty_cards_region_list;
388 if (head == NULL) {
389 return NULL;
390 }
391 HeapRegion* new_head = head->get_next_dirty_cards_region();
392 if (head == new_head) {
393 // The last region.
394 new_head = NULL;
395 }
396 hr = (HeapRegion*)Atomic::cmpxchg_ptr(new_head, &_dirty_cards_region_list,
397 head);
398 } while (hr != head);
399 assert(hr != NULL, "invariant");
400 hr->set_next_dirty_cards_region(NULL);
401 return hr;
402 }
404 void G1CollectedHeap::stop_conc_gc_threads() {
405 _cg1r->stop();
406 _czft->stop();
407 _cmThread->stop();
408 }
411 void G1CollectedHeap::check_ct_logs_at_safepoint() {
412 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
413 CardTableModRefBS* ct_bs = (CardTableModRefBS*)barrier_set();
415 // Count the dirty cards at the start.
416 CountNonCleanMemRegionClosure count1(this);
417 ct_bs->mod_card_iterate(&count1);
418 int orig_count = count1.n();
420 // First clear the logged cards.
421 ClearLoggedCardTableEntryClosure clear;
422 dcqs.set_closure(&clear);
423 dcqs.apply_closure_to_all_completed_buffers();
424 dcqs.iterate_closure_all_threads(false);
425 clear.print_histo();
427 // Now ensure that there's no dirty cards.
428 CountNonCleanMemRegionClosure count2(this);
429 ct_bs->mod_card_iterate(&count2);
430 if (count2.n() != 0) {
431 gclog_or_tty->print_cr("Card table has %d entries; %d originally",
432 count2.n(), orig_count);
433 }
434 guarantee(count2.n() == 0, "Card table should be clean.");
436 RedirtyLoggedCardTableEntryClosure redirty;
437 JavaThread::dirty_card_queue_set().set_closure(&redirty);
438 dcqs.apply_closure_to_all_completed_buffers();
439 dcqs.iterate_closure_all_threads(false);
440 gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",
441 clear.calls(), orig_count);
442 guarantee(redirty.calls() == clear.calls(),
443 "Or else mechanism is broken.");
445 CountNonCleanMemRegionClosure count3(this);
446 ct_bs->mod_card_iterate(&count3);
447 if (count3.n() != orig_count) {
448 gclog_or_tty->print_cr("Should have restored them all: orig = %d, final = %d.",
449 orig_count, count3.n());
450 guarantee(count3.n() >= orig_count, "Should have restored them all.");
451 }
453 JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
454 }
456 // Private class members.
458 G1CollectedHeap* G1CollectedHeap::_g1h;
460 // Private methods.
462 // Finds a HeapRegion that can be used to allocate a given size of block.
465 HeapRegion* G1CollectedHeap::newAllocRegion_work(size_t word_size,
466 bool do_expand,
467 bool zero_filled) {
468 ConcurrentZFThread::note_region_alloc();
469 HeapRegion* res = alloc_free_region_from_lists(zero_filled);
470 if (res == NULL && do_expand) {
471 expand(word_size * HeapWordSize);
472 res = alloc_free_region_from_lists(zero_filled);
473 assert(res == NULL ||
474 (!res->isHumongous() &&
475 (!zero_filled ||
476 res->zero_fill_state() == HeapRegion::Allocated)),
477 "Alloc Regions must be zero filled (and non-H)");
478 }
479 if (res != NULL) {
480 if (res->is_empty()) {
481 _free_regions--;
482 }
483 assert(!res->isHumongous() &&
484 (!zero_filled || res->zero_fill_state() == HeapRegion::Allocated),
485 err_msg("Non-young alloc Regions must be zero filled (and non-H):"
486 " res->isHumongous()=%d, zero_filled=%d, res->zero_fill_state()=%d",
487 res->isHumongous(), zero_filled, res->zero_fill_state()));
488 assert(!res->is_on_unclean_list(),
489 "Alloc Regions must not be on the unclean list");
490 if (G1PrintHeapRegions) {
491 gclog_or_tty->print_cr("new alloc region %d:["PTR_FORMAT", "PTR_FORMAT"], "
492 "top "PTR_FORMAT,
493 res->hrs_index(), res->bottom(), res->end(), res->top());
494 }
495 }
496 return res;
497 }
499 HeapRegion* G1CollectedHeap::newAllocRegionWithExpansion(int purpose,
500 size_t word_size,
501 bool zero_filled) {
502 HeapRegion* alloc_region = NULL;
503 if (_gc_alloc_region_counts[purpose] < g1_policy()->max_regions(purpose)) {
504 alloc_region = newAllocRegion_work(word_size, true, zero_filled);
505 if (purpose == GCAllocForSurvived && alloc_region != NULL) {
506 alloc_region->set_survivor();
507 }
508 ++_gc_alloc_region_counts[purpose];
509 } else {
510 g1_policy()->note_alloc_region_limit_reached(purpose);
511 }
512 return alloc_region;
513 }
515 // If could fit into free regions w/o expansion, try.
516 // Otherwise, if can expand, do so.
517 // Otherwise, if using ex regions might help, try with ex given back.
518 HeapWord* G1CollectedHeap::humongousObjAllocate(size_t word_size) {
519 assert(regions_accounted_for(), "Region leakage!");
521 // We can't allocate H regions while cleanupComplete is running, since
522 // some of the regions we find to be empty might not yet be added to the
523 // unclean list. (If we're already at a safepoint, this call is
524 // unnecessary, not to mention wrong.)
525 if (!SafepointSynchronize::is_at_safepoint())
526 wait_for_cleanup_complete();
528 size_t num_regions =
529 round_to(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords;
531 // Special case if < one region???
533 // Remember the ft size.
534 size_t x_size = expansion_regions();
536 HeapWord* res = NULL;
537 bool eliminated_allocated_from_lists = false;
539 // Can the allocation potentially fit in the free regions?
540 if (free_regions() >= num_regions) {
541 res = _hrs->obj_allocate(word_size);
542 }
543 if (res == NULL) {
544 // Try expansion.
545 size_t fs = _hrs->free_suffix();
546 if (fs + x_size >= num_regions) {
547 expand((num_regions - fs) * HeapRegion::GrainBytes);
548 res = _hrs->obj_allocate(word_size);
549 assert(res != NULL, "This should have worked.");
550 } else {
551 // Expansion won't help. Are there enough free regions if we get rid
552 // of reservations?
553 size_t avail = free_regions();
554 if (avail >= num_regions) {
555 res = _hrs->obj_allocate(word_size);
556 if (res != NULL) {
557 remove_allocated_regions_from_lists();
558 eliminated_allocated_from_lists = true;
559 }
560 }
561 }
562 }
563 if (res != NULL) {
564 // Increment by the number of regions allocated.
565 // FIXME: Assumes regions all of size GrainBytes.
566 #ifndef PRODUCT
567 mr_bs()->verify_clean_region(MemRegion(res, res + num_regions *
568 HeapRegion::GrainWords));
569 #endif
570 if (!eliminated_allocated_from_lists)
571 remove_allocated_regions_from_lists();
572 _summary_bytes_used += word_size * HeapWordSize;
573 _free_regions -= num_regions;
574 _num_humongous_regions += (int) num_regions;
575 }
576 assert(regions_accounted_for(), "Region Leakage");
577 return res;
578 }
580 HeapWord*
581 G1CollectedHeap::attempt_allocation_slow(size_t word_size,
582 bool permit_collection_pause) {
583 HeapWord* res = NULL;
584 HeapRegion* allocated_young_region = NULL;
586 assert( SafepointSynchronize::is_at_safepoint() ||
587 Heap_lock->owned_by_self(), "pre condition of the call" );
589 if (isHumongous(word_size)) {
590 // Allocation of a humongous object can, in a sense, complete a
591 // partial region, if the previous alloc was also humongous, and
592 // caused the test below to succeed.
593 if (permit_collection_pause)
594 do_collection_pause_if_appropriate(word_size);
595 res = humongousObjAllocate(word_size);
596 assert(_cur_alloc_region == NULL
597 || !_cur_alloc_region->isHumongous(),
598 "Prevent a regression of this bug.");
600 } else {
601 // We may have concurrent cleanup working at the time. Wait for it
602 // to complete. In the future we would probably want to make the
603 // concurrent cleanup truly concurrent by decoupling it from the
604 // allocation.
605 if (!SafepointSynchronize::is_at_safepoint())
606 wait_for_cleanup_complete();
607 // If we do a collection pause, this will be reset to a non-NULL
608 // value. If we don't, nulling here ensures that we allocate a new
609 // region below.
610 if (_cur_alloc_region != NULL) {
611 // We're finished with the _cur_alloc_region.
612 // As we're builing (at least the young portion) of the collection
613 // set incrementally we'll add the current allocation region to
614 // the collection set here.
615 if (_cur_alloc_region->is_young()) {
616 g1_policy()->add_region_to_incremental_cset_lhs(_cur_alloc_region);
617 }
618 _summary_bytes_used += _cur_alloc_region->used();
619 _cur_alloc_region = NULL;
620 }
621 assert(_cur_alloc_region == NULL, "Invariant.");
622 // Completion of a heap region is perhaps a good point at which to do
623 // a collection pause.
624 if (permit_collection_pause)
625 do_collection_pause_if_appropriate(word_size);
626 // Make sure we have an allocation region available.
627 if (_cur_alloc_region == NULL) {
628 if (!SafepointSynchronize::is_at_safepoint())
629 wait_for_cleanup_complete();
630 bool next_is_young = should_set_young_locked();
631 // If the next region is not young, make sure it's zero-filled.
632 _cur_alloc_region = newAllocRegion(word_size, !next_is_young);
633 if (_cur_alloc_region != NULL) {
634 _summary_bytes_used -= _cur_alloc_region->used();
635 if (next_is_young) {
636 set_region_short_lived_locked(_cur_alloc_region);
637 allocated_young_region = _cur_alloc_region;
638 }
639 }
640 }
641 assert(_cur_alloc_region == NULL || !_cur_alloc_region->isHumongous(),
642 "Prevent a regression of this bug.");
644 // Now retry the allocation.
645 if (_cur_alloc_region != NULL) {
646 if (allocated_young_region != NULL) {
647 // We need to ensure that the store to top does not
648 // float above the setting of the young type.
649 OrderAccess::storestore();
650 }
651 res = _cur_alloc_region->allocate(word_size);
652 }
653 }
655 // NOTE: fails frequently in PRT
656 assert(regions_accounted_for(), "Region leakage!");
658 if (res != NULL) {
659 if (!SafepointSynchronize::is_at_safepoint()) {
660 assert( permit_collection_pause, "invariant" );
661 assert( Heap_lock->owned_by_self(), "invariant" );
662 Heap_lock->unlock();
663 }
665 if (allocated_young_region != NULL) {
666 HeapRegion* hr = allocated_young_region;
667 HeapWord* bottom = hr->bottom();
668 HeapWord* end = hr->end();
669 MemRegion mr(bottom, end);
670 ((CardTableModRefBS*)_g1h->barrier_set())->dirty(mr);
671 }
672 }
674 assert( SafepointSynchronize::is_at_safepoint() ||
675 (res == NULL && Heap_lock->owned_by_self()) ||
676 (res != NULL && !Heap_lock->owned_by_self()),
677 "post condition of the call" );
679 return res;
680 }
682 HeapWord*
683 G1CollectedHeap::mem_allocate(size_t word_size,
684 bool is_noref,
685 bool is_tlab,
686 bool* gc_overhead_limit_was_exceeded) {
687 debug_only(check_for_valid_allocation_state());
688 assert(no_gc_in_progress(), "Allocation during gc not allowed");
689 HeapWord* result = NULL;
691 // Loop until the allocation is satisified,
692 // or unsatisfied after GC.
693 for (int try_count = 1; /* return or throw */; try_count += 1) {
694 int gc_count_before;
695 {
696 Heap_lock->lock();
697 result = attempt_allocation(word_size);
698 if (result != NULL) {
699 // attempt_allocation should have unlocked the heap lock
700 assert(is_in(result), "result not in heap");
701 return result;
702 }
703 // Read the gc count while the heap lock is held.
704 gc_count_before = SharedHeap::heap()->total_collections();
705 Heap_lock->unlock();
706 }
708 // Create the garbage collection operation...
709 VM_G1CollectForAllocation op(word_size,
710 gc_count_before);
712 // ...and get the VM thread to execute it.
713 VMThread::execute(&op);
714 if (op.prologue_succeeded()) {
715 result = op.result();
716 assert(result == NULL || is_in(result), "result not in heap");
717 return result;
718 }
720 // Give a warning if we seem to be looping forever.
721 if ((QueuedAllocationWarningCount > 0) &&
722 (try_count % QueuedAllocationWarningCount == 0)) {
723 warning("G1CollectedHeap::mem_allocate_work retries %d times",
724 try_count);
725 }
726 }
727 }
729 void G1CollectedHeap::abandon_cur_alloc_region() {
730 if (_cur_alloc_region != NULL) {
731 // We're finished with the _cur_alloc_region.
732 if (_cur_alloc_region->is_empty()) {
733 _free_regions++;
734 free_region(_cur_alloc_region);
735 } else {
736 // As we're builing (at least the young portion) of the collection
737 // set incrementally we'll add the current allocation region to
738 // the collection set here.
739 if (_cur_alloc_region->is_young()) {
740 g1_policy()->add_region_to_incremental_cset_lhs(_cur_alloc_region);
741 }
742 _summary_bytes_used += _cur_alloc_region->used();
743 }
744 _cur_alloc_region = NULL;
745 }
746 }
748 void G1CollectedHeap::abandon_gc_alloc_regions() {
749 // first, make sure that the GC alloc region list is empty (it should!)
750 assert(_gc_alloc_region_list == NULL, "invariant");
751 release_gc_alloc_regions(true /* totally */);
752 }
754 class PostMCRemSetClearClosure: public HeapRegionClosure {
755 ModRefBarrierSet* _mr_bs;
756 public:
757 PostMCRemSetClearClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {}
758 bool doHeapRegion(HeapRegion* r) {
759 r->reset_gc_time_stamp();
760 if (r->continuesHumongous())
761 return false;
762 HeapRegionRemSet* hrrs = r->rem_set();
763 if (hrrs != NULL) hrrs->clear();
764 // You might think here that we could clear just the cards
765 // corresponding to the used region. But no: if we leave a dirty card
766 // in a region we might allocate into, then it would prevent that card
767 // from being enqueued, and cause it to be missed.
768 // Re: the performance cost: we shouldn't be doing full GC anyway!
769 _mr_bs->clear(MemRegion(r->bottom(), r->end()));
770 return false;
771 }
772 };
775 class PostMCRemSetInvalidateClosure: public HeapRegionClosure {
776 ModRefBarrierSet* _mr_bs;
777 public:
778 PostMCRemSetInvalidateClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {}
779 bool doHeapRegion(HeapRegion* r) {
780 if (r->continuesHumongous()) return false;
781 if (r->used_region().word_size() != 0) {
782 _mr_bs->invalidate(r->used_region(), true /*whole heap*/);
783 }
784 return false;
785 }
786 };
788 class RebuildRSOutOfRegionClosure: public HeapRegionClosure {
789 G1CollectedHeap* _g1h;
790 UpdateRSOopClosure _cl;
791 int _worker_i;
792 public:
793 RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, int worker_i = 0) :
794 _cl(g1->g1_rem_set()->as_HRInto_G1RemSet(), worker_i),
795 _worker_i(worker_i),
796 _g1h(g1)
797 { }
798 bool doHeapRegion(HeapRegion* r) {
799 if (!r->continuesHumongous()) {
800 _cl.set_from(r);
801 r->oop_iterate(&_cl);
802 }
803 return false;
804 }
805 };
807 class ParRebuildRSTask: public AbstractGangTask {
808 G1CollectedHeap* _g1;
809 public:
810 ParRebuildRSTask(G1CollectedHeap* g1)
811 : AbstractGangTask("ParRebuildRSTask"),
812 _g1(g1)
813 { }
815 void work(int i) {
816 RebuildRSOutOfRegionClosure rebuild_rs(_g1, i);
817 _g1->heap_region_par_iterate_chunked(&rebuild_rs, i,
818 HeapRegion::RebuildRSClaimValue);
819 }
820 };
822 void G1CollectedHeap::do_collection(bool explicit_gc,
823 bool clear_all_soft_refs,
824 size_t word_size) {
825 if (GC_locker::check_active_before_gc()) {
826 return; // GC is disabled (e.g. JNI GetXXXCritical operation)
827 }
829 ResourceMark rm;
831 if (PrintHeapAtGC) {
832 Universe::print_heap_before_gc();
833 }
835 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
836 assert(Thread::current() == VMThread::vm_thread(), "should be in vm thread");
838 const bool do_clear_all_soft_refs = clear_all_soft_refs ||
839 collector_policy()->should_clear_all_soft_refs();
841 ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());
843 {
844 IsGCActiveMark x;
846 // Timing
847 bool system_gc = (gc_cause() == GCCause::_java_lang_system_gc);
848 assert(!system_gc || explicit_gc, "invariant");
849 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
850 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
851 TraceTime t(system_gc ? "Full GC (System.gc())" : "Full GC",
852 PrintGC, true, gclog_or_tty);
854 TraceMemoryManagerStats tms(true /* fullGC */);
856 double start = os::elapsedTime();
857 g1_policy()->record_full_collection_start();
859 gc_prologue(true);
860 increment_total_collections(true /* full gc */);
862 size_t g1h_prev_used = used();
863 assert(used() == recalculate_used(), "Should be equal");
865 if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) {
866 HandleMark hm; // Discard invalid handles created during verification
867 prepare_for_verify();
868 gclog_or_tty->print(" VerifyBeforeGC:");
869 Universe::verify(true);
870 }
871 assert(regions_accounted_for(), "Region leakage!");
873 COMPILER2_PRESENT(DerivedPointerTable::clear());
875 // We want to discover references, but not process them yet.
876 // This mode is disabled in
877 // instanceRefKlass::process_discovered_references if the
878 // generation does some collection work, or
879 // instanceRefKlass::enqueue_discovered_references if the
880 // generation returns without doing any work.
881 ref_processor()->disable_discovery();
882 ref_processor()->abandon_partial_discovery();
883 ref_processor()->verify_no_references_recorded();
885 // Abandon current iterations of concurrent marking and concurrent
886 // refinement, if any are in progress.
887 concurrent_mark()->abort();
889 // Make sure we'll choose a new allocation region afterwards.
890 abandon_cur_alloc_region();
891 abandon_gc_alloc_regions();
892 assert(_cur_alloc_region == NULL, "Invariant.");
893 g1_rem_set()->as_HRInto_G1RemSet()->cleanupHRRS();
894 tear_down_region_lists();
895 set_used_regions_to_need_zero_fill();
897 // We may have added regions to the current incremental collection
898 // set between the last GC or pause and now. We need to clear the
899 // incremental collection set and then start rebuilding it afresh
900 // after this full GC.
901 abandon_collection_set(g1_policy()->inc_cset_head());
902 g1_policy()->clear_incremental_cset();
903 g1_policy()->stop_incremental_cset_building();
905 if (g1_policy()->in_young_gc_mode()) {
906 empty_young_list();
907 g1_policy()->set_full_young_gcs(true);
908 }
910 // Temporarily make reference _discovery_ single threaded (non-MT).
911 ReferenceProcessorMTMutator rp_disc_ser(ref_processor(), false);
913 // Temporarily make refs discovery atomic
914 ReferenceProcessorAtomicMutator rp_disc_atomic(ref_processor(), true);
916 // Temporarily clear _is_alive_non_header
917 ReferenceProcessorIsAliveMutator rp_is_alive_null(ref_processor(), NULL);
919 ref_processor()->enable_discovery();
920 ref_processor()->setup_policy(do_clear_all_soft_refs);
922 // Do collection work
923 {
924 HandleMark hm; // Discard invalid handles created during gc
925 G1MarkSweep::invoke_at_safepoint(ref_processor(), do_clear_all_soft_refs);
926 }
927 // Because freeing humongous regions may have added some unclean
928 // regions, it is necessary to tear down again before rebuilding.
929 tear_down_region_lists();
930 rebuild_region_lists();
932 _summary_bytes_used = recalculate_used();
934 ref_processor()->enqueue_discovered_references();
936 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
938 MemoryService::track_memory_usage();
940 if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
941 HandleMark hm; // Discard invalid handles created during verification
942 gclog_or_tty->print(" VerifyAfterGC:");
943 prepare_for_verify();
944 Universe::verify(false);
945 }
946 NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
948 reset_gc_time_stamp();
949 // Since everything potentially moved, we will clear all remembered
950 // sets, and clear all cards. Later we will rebuild remebered
951 // sets. We will also reset the GC time stamps of the regions.
952 PostMCRemSetClearClosure rs_clear(mr_bs());
953 heap_region_iterate(&rs_clear);
955 // Resize the heap if necessary.
956 resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size);
958 if (_cg1r->use_cache()) {
959 _cg1r->clear_and_record_card_counts();
960 _cg1r->clear_hot_cache();
961 }
963 // Rebuild remembered sets of all regions.
965 if (G1CollectedHeap::use_parallel_gc_threads()) {
966 ParRebuildRSTask rebuild_rs_task(this);
967 assert(check_heap_region_claim_values(
968 HeapRegion::InitialClaimValue), "sanity check");
969 set_par_threads(workers()->total_workers());
970 workers()->run_task(&rebuild_rs_task);
971 set_par_threads(0);
972 assert(check_heap_region_claim_values(
973 HeapRegion::RebuildRSClaimValue), "sanity check");
974 reset_heap_region_claim_values();
975 } else {
976 RebuildRSOutOfRegionClosure rebuild_rs(this);
977 heap_region_iterate(&rebuild_rs);
978 }
980 if (PrintGC) {
981 print_size_transition(gclog_or_tty, g1h_prev_used, used(), capacity());
982 }
984 if (true) { // FIXME
985 // Ask the permanent generation to adjust size for full collections
986 perm()->compute_new_size();
987 }
989 // Start a new incremental collection set for the next pause
990 assert(g1_policy()->collection_set() == NULL, "must be");
991 g1_policy()->start_incremental_cset_building();
993 // Clear the _cset_fast_test bitmap in anticipation of adding
994 // regions to the incremental collection set for the next
995 // evacuation pause.
996 clear_cset_fast_test();
998 double end = os::elapsedTime();
999 g1_policy()->record_full_collection_end();
1001 #ifdef TRACESPINNING
1002 ParallelTaskTerminator::print_termination_counts();
1003 #endif
1005 gc_epilogue(true);
1007 // Discard all rset updates
1008 JavaThread::dirty_card_queue_set().abandon_logs();
1009 assert(!G1DeferredRSUpdate
1010 || (G1DeferredRSUpdate && (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any");
1011 assert(regions_accounted_for(), "Region leakage!");
1012 }
1014 if (g1_policy()->in_young_gc_mode()) {
1015 _young_list->reset_sampled_info();
1016 // At this point there should be no regions in the
1017 // entire heap tagged as young.
1018 assert( check_young_list_empty(true /* check_heap */),
1019 "young list should be empty at this point");
1020 }
1022 // Update the number of full collections that have been completed.
1023 increment_full_collections_completed(false /* outer */);
1025 if (PrintHeapAtGC) {
1026 Universe::print_heap_after_gc();
1027 }
1028 }
1030 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1031 do_collection(true, /* explicit_gc */
1032 clear_all_soft_refs,
1033 0 /* word_size */);
1034 }
1036 // This code is mostly copied from TenuredGeneration.
1037 void
1038 G1CollectedHeap::
1039 resize_if_necessary_after_full_collection(size_t word_size) {
1040 assert(MinHeapFreeRatio <= MaxHeapFreeRatio, "sanity check");
1042 // Include the current allocation, if any, and bytes that will be
1043 // pre-allocated to support collections, as "used".
1044 const size_t used_after_gc = used();
1045 const size_t capacity_after_gc = capacity();
1046 const size_t free_after_gc = capacity_after_gc - used_after_gc;
1048 // This is enforced in arguments.cpp.
1049 assert(MinHeapFreeRatio <= MaxHeapFreeRatio,
1050 "otherwise the code below doesn't make sense");
1052 // We don't have floating point command-line arguments
1053 const double minimum_free_percentage = (double) MinHeapFreeRatio / 100.0;
1054 const double maximum_used_percentage = 1.0 - minimum_free_percentage;
1055 const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100.0;
1056 const double minimum_used_percentage = 1.0 - maximum_free_percentage;
1058 const size_t min_heap_size = collector_policy()->min_heap_byte_size();
1059 const size_t max_heap_size = collector_policy()->max_heap_byte_size();
1061 // We have to be careful here as these two calculations can overflow
1062 // 32-bit size_t's.
1063 double used_after_gc_d = (double) used_after_gc;
1064 double minimum_desired_capacity_d = used_after_gc_d / maximum_used_percentage;
1065 double maximum_desired_capacity_d = used_after_gc_d / minimum_used_percentage;
1067 // Let's make sure that they are both under the max heap size, which
1068 // by default will make them fit into a size_t.
1069 double desired_capacity_upper_bound = (double) max_heap_size;
1070 minimum_desired_capacity_d = MIN2(minimum_desired_capacity_d,
1071 desired_capacity_upper_bound);
1072 maximum_desired_capacity_d = MIN2(maximum_desired_capacity_d,
1073 desired_capacity_upper_bound);
1075 // We can now safely turn them into size_t's.
1076 size_t minimum_desired_capacity = (size_t) minimum_desired_capacity_d;
1077 size_t maximum_desired_capacity = (size_t) maximum_desired_capacity_d;
1079 // This assert only makes sense here, before we adjust them
1080 // with respect to the min and max heap size.
1081 assert(minimum_desired_capacity <= maximum_desired_capacity,
1082 err_msg("minimum_desired_capacity = "SIZE_FORMAT", "
1083 "maximum_desired_capacity = "SIZE_FORMAT,
1084 minimum_desired_capacity, maximum_desired_capacity));
1086 // Should not be greater than the heap max size. No need to adjust
1087 // it with respect to the heap min size as it's a lower bound (i.e.,
1088 // we'll try to make the capacity larger than it, not smaller).
1089 minimum_desired_capacity = MIN2(minimum_desired_capacity, max_heap_size);
1090 // Should not be less than the heap min size. No need to adjust it
1091 // with respect to the heap max size as it's an upper bound (i.e.,
1092 // we'll try to make the capacity smaller than it, not greater).
1093 maximum_desired_capacity = MAX2(maximum_desired_capacity, min_heap_size);
1095 if (PrintGC && Verbose) {
1096 const double free_percentage =
1097 (double) free_after_gc / (double) capacity_after_gc;
1098 gclog_or_tty->print_cr("Computing new size after full GC ");
1099 gclog_or_tty->print_cr(" "
1100 " minimum_free_percentage: %6.2f",
1101 minimum_free_percentage);
1102 gclog_or_tty->print_cr(" "
1103 " maximum_free_percentage: %6.2f",
1104 maximum_free_percentage);
1105 gclog_or_tty->print_cr(" "
1106 " capacity: %6.1fK"
1107 " minimum_desired_capacity: %6.1fK"
1108 " maximum_desired_capacity: %6.1fK",
1109 (double) capacity_after_gc / (double) K,
1110 (double) minimum_desired_capacity / (double) K,
1111 (double) maximum_desired_capacity / (double) K);
1112 gclog_or_tty->print_cr(" "
1113 " free_after_gc: %6.1fK"
1114 " used_after_gc: %6.1fK",
1115 (double) free_after_gc / (double) K,
1116 (double) used_after_gc / (double) K);
1117 gclog_or_tty->print_cr(" "
1118 " free_percentage: %6.2f",
1119 free_percentage);
1120 }
1121 if (capacity_after_gc < minimum_desired_capacity) {
1122 // Don't expand unless it's significant
1123 size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
1124 expand(expand_bytes);
1125 if (PrintGC && Verbose) {
1126 gclog_or_tty->print_cr(" "
1127 " expanding:"
1128 " max_heap_size: %6.1fK"
1129 " minimum_desired_capacity: %6.1fK"
1130 " expand_bytes: %6.1fK",
1131 (double) max_heap_size / (double) K,
1132 (double) minimum_desired_capacity / (double) K,
1133 (double) expand_bytes / (double) K);
1134 }
1136 // No expansion, now see if we want to shrink
1137 } else if (capacity_after_gc > maximum_desired_capacity) {
1138 // Capacity too large, compute shrinking size
1139 size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;
1140 shrink(shrink_bytes);
1141 if (PrintGC && Verbose) {
1142 gclog_or_tty->print_cr(" "
1143 " shrinking:"
1144 " min_heap_size: %6.1fK"
1145 " maximum_desired_capacity: %6.1fK"
1146 " shrink_bytes: %6.1fK",
1147 (double) min_heap_size / (double) K,
1148 (double) maximum_desired_capacity / (double) K,
1149 (double) shrink_bytes / (double) K);
1150 }
1151 }
1152 }
1155 HeapWord*
1156 G1CollectedHeap::satisfy_failed_allocation(size_t word_size) {
1157 HeapWord* result = NULL;
1159 // In a G1 heap, we're supposed to keep allocation from failing by
1160 // incremental pauses. Therefore, at least for now, we'll favor
1161 // expansion over collection. (This might change in the future if we can
1162 // do something smarter than full collection to satisfy a failed alloc.)
1164 result = expand_and_allocate(word_size);
1165 if (result != NULL) {
1166 assert(is_in(result), "result not in heap");
1167 return result;
1168 }
1170 // OK, I guess we have to try collection.
1172 do_collection(false, false, word_size);
1174 result = attempt_allocation(word_size, /*permit_collection_pause*/false);
1176 if (result != NULL) {
1177 assert(is_in(result), "result not in heap");
1178 return result;
1179 }
1181 // Try collecting soft references.
1182 do_collection(false, true, word_size);
1183 result = attempt_allocation(word_size, /*permit_collection_pause*/false);
1184 if (result != NULL) {
1185 assert(is_in(result), "result not in heap");
1186 return result;
1187 }
1189 assert(!collector_policy()->should_clear_all_soft_refs(),
1190 "Flag should have been handled and cleared prior to this point");
1192 // What else? We might try synchronous finalization later. If the total
1193 // space available is large enough for the allocation, then a more
1194 // complete compaction phase than we've tried so far might be
1195 // appropriate.
1196 return NULL;
1197 }
1199 // Attempting to expand the heap sufficiently
1200 // to support an allocation of the given "word_size". If
1201 // successful, perform the allocation and return the address of the
1202 // allocated block, or else "NULL".
1204 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1205 size_t expand_bytes = word_size * HeapWordSize;
1206 if (expand_bytes < MinHeapDeltaBytes) {
1207 expand_bytes = MinHeapDeltaBytes;
1208 }
1209 expand(expand_bytes);
1210 assert(regions_accounted_for(), "Region leakage!");
1211 HeapWord* result = attempt_allocation(word_size, false /* permit_collection_pause */);
1212 return result;
1213 }
1215 size_t G1CollectedHeap::free_region_if_totally_empty(HeapRegion* hr) {
1216 size_t pre_used = 0;
1217 size_t cleared_h_regions = 0;
1218 size_t freed_regions = 0;
1219 UncleanRegionList local_list;
1220 free_region_if_totally_empty_work(hr, pre_used, cleared_h_regions,
1221 freed_regions, &local_list);
1223 finish_free_region_work(pre_used, cleared_h_regions, freed_regions,
1224 &local_list);
1225 return pre_used;
1226 }
1228 void
1229 G1CollectedHeap::free_region_if_totally_empty_work(HeapRegion* hr,
1230 size_t& pre_used,
1231 size_t& cleared_h,
1232 size_t& freed_regions,
1233 UncleanRegionList* list,
1234 bool par) {
1235 assert(!hr->continuesHumongous(), "should have filtered these out");
1236 size_t res = 0;
1237 if (hr->used() > 0 && hr->garbage_bytes() == hr->used() &&
1238 !hr->is_young()) {
1239 if (G1PolicyVerbose > 0)
1240 gclog_or_tty->print_cr("Freeing empty region "PTR_FORMAT "(" SIZE_FORMAT " bytes)"
1241 " during cleanup", hr, hr->used());
1242 free_region_work(hr, pre_used, cleared_h, freed_regions, list, par);
1243 }
1244 }
1246 // FIXME: both this and shrink could probably be more efficient by
1247 // doing one "VirtualSpace::expand_by" call rather than several.
1248 void G1CollectedHeap::expand(size_t expand_bytes) {
1249 size_t old_mem_size = _g1_storage.committed_size();
1250 // We expand by a minimum of 1K.
1251 expand_bytes = MAX2(expand_bytes, (size_t)K);
1252 size_t aligned_expand_bytes =
1253 ReservedSpace::page_align_size_up(expand_bytes);
1254 aligned_expand_bytes = align_size_up(aligned_expand_bytes,
1255 HeapRegion::GrainBytes);
1256 expand_bytes = aligned_expand_bytes;
1257 while (expand_bytes > 0) {
1258 HeapWord* base = (HeapWord*)_g1_storage.high();
1259 // Commit more storage.
1260 bool successful = _g1_storage.expand_by(HeapRegion::GrainBytes);
1261 if (!successful) {
1262 expand_bytes = 0;
1263 } else {
1264 expand_bytes -= HeapRegion::GrainBytes;
1265 // Expand the committed region.
1266 HeapWord* high = (HeapWord*) _g1_storage.high();
1267 _g1_committed.set_end(high);
1268 // Create a new HeapRegion.
1269 MemRegion mr(base, high);
1270 bool is_zeroed = !_g1_max_committed.contains(base);
1271 HeapRegion* hr = new HeapRegion(_bot_shared, mr, is_zeroed);
1273 // Now update max_committed if necessary.
1274 _g1_max_committed.set_end(MAX2(_g1_max_committed.end(), high));
1276 // Add it to the HeapRegionSeq.
1277 _hrs->insert(hr);
1278 // Set the zero-fill state, according to whether it's already
1279 // zeroed.
1280 {
1281 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
1282 if (is_zeroed) {
1283 hr->set_zero_fill_complete();
1284 put_free_region_on_list_locked(hr);
1285 } else {
1286 hr->set_zero_fill_needed();
1287 put_region_on_unclean_list_locked(hr);
1288 }
1289 }
1290 _free_regions++;
1291 // And we used up an expansion region to create it.
1292 _expansion_regions--;
1293 // Tell the cardtable about it.
1294 Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
1295 // And the offset table as well.
1296 _bot_shared->resize(_g1_committed.word_size());
1297 }
1298 }
1299 if (Verbose && PrintGC) {
1300 size_t new_mem_size = _g1_storage.committed_size();
1301 gclog_or_tty->print_cr("Expanding garbage-first heap from %ldK by %ldK to %ldK",
1302 old_mem_size/K, aligned_expand_bytes/K,
1303 new_mem_size/K);
1304 }
1305 }
1307 void G1CollectedHeap::shrink_helper(size_t shrink_bytes)
1308 {
1309 size_t old_mem_size = _g1_storage.committed_size();
1310 size_t aligned_shrink_bytes =
1311 ReservedSpace::page_align_size_down(shrink_bytes);
1312 aligned_shrink_bytes = align_size_down(aligned_shrink_bytes,
1313 HeapRegion::GrainBytes);
1314 size_t num_regions_deleted = 0;
1315 MemRegion mr = _hrs->shrink_by(aligned_shrink_bytes, num_regions_deleted);
1317 assert(mr.end() == (HeapWord*)_g1_storage.high(), "Bad shrink!");
1318 if (mr.byte_size() > 0)
1319 _g1_storage.shrink_by(mr.byte_size());
1320 assert(mr.start() == (HeapWord*)_g1_storage.high(), "Bad shrink!");
1322 _g1_committed.set_end(mr.start());
1323 _free_regions -= num_regions_deleted;
1324 _expansion_regions += num_regions_deleted;
1326 // Tell the cardtable about it.
1327 Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
1329 // And the offset table as well.
1330 _bot_shared->resize(_g1_committed.word_size());
1332 HeapRegionRemSet::shrink_heap(n_regions());
1334 if (Verbose && PrintGC) {
1335 size_t new_mem_size = _g1_storage.committed_size();
1336 gclog_or_tty->print_cr("Shrinking garbage-first heap from %ldK by %ldK to %ldK",
1337 old_mem_size/K, aligned_shrink_bytes/K,
1338 new_mem_size/K);
1339 }
1340 }
1342 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1343 release_gc_alloc_regions(true /* totally */);
1344 tear_down_region_lists(); // We will rebuild them in a moment.
1345 shrink_helper(shrink_bytes);
1346 rebuild_region_lists();
1347 }
1349 // Public methods.
1351 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
1352 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
1353 #endif // _MSC_VER
1356 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :
1357 SharedHeap(policy_),
1358 _g1_policy(policy_),
1359 _dirty_card_queue_set(false),
1360 _into_cset_dirty_card_queue_set(false),
1361 _ref_processor(NULL),
1362 _process_strong_tasks(new SubTasksDone(G1H_PS_NumElements)),
1363 _bot_shared(NULL),
1364 _par_alloc_during_gc_lock(Mutex::leaf, "par alloc during GC lock"),
1365 _objs_with_preserved_marks(NULL), _preserved_marks_of_objs(NULL),
1366 _evac_failure_scan_stack(NULL) ,
1367 _mark_in_progress(false),
1368 _cg1r(NULL), _czft(NULL), _summary_bytes_used(0),
1369 _cur_alloc_region(NULL),
1370 _refine_cte_cl(NULL),
1371 _free_region_list(NULL), _free_region_list_size(0),
1372 _free_regions(0),
1373 _full_collection(false),
1374 _unclean_region_list(),
1375 _unclean_regions_coming(false),
1376 _young_list(new YoungList(this)),
1377 _gc_time_stamp(0),
1378 _surviving_young_words(NULL),
1379 _full_collections_completed(0),
1380 _in_cset_fast_test(NULL),
1381 _in_cset_fast_test_base(NULL),
1382 _dirty_cards_region_list(NULL) {
1383 _g1h = this; // To catch bugs.
1384 if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) {
1385 vm_exit_during_initialization("Failed necessary allocation.");
1386 }
1388 _humongous_object_threshold_in_words = HeapRegion::GrainWords / 2;
1390 int n_queues = MAX2((int)ParallelGCThreads, 1);
1391 _task_queues = new RefToScanQueueSet(n_queues);
1393 int n_rem_sets = HeapRegionRemSet::num_par_rem_sets();
1394 assert(n_rem_sets > 0, "Invariant.");
1396 HeapRegionRemSetIterator** iter_arr =
1397 NEW_C_HEAP_ARRAY(HeapRegionRemSetIterator*, n_queues);
1398 for (int i = 0; i < n_queues; i++) {
1399 iter_arr[i] = new HeapRegionRemSetIterator();
1400 }
1401 _rem_set_iterator = iter_arr;
1403 for (int i = 0; i < n_queues; i++) {
1404 RefToScanQueue* q = new RefToScanQueue();
1405 q->initialize();
1406 _task_queues->register_queue(i, q);
1407 }
1409 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
1410 _gc_alloc_regions[ap] = NULL;
1411 _gc_alloc_region_counts[ap] = 0;
1412 _retained_gc_alloc_regions[ap] = NULL;
1413 // by default, we do not retain a GC alloc region for each ap;
1414 // we'll override this, when appropriate, below
1415 _retain_gc_alloc_region[ap] = false;
1416 }
1418 // We will try to remember the last half-full tenured region we
1419 // allocated to at the end of a collection so that we can re-use it
1420 // during the next collection.
1421 _retain_gc_alloc_region[GCAllocForTenured] = true;
1423 guarantee(_task_queues != NULL, "task_queues allocation failure.");
1424 }
1426 jint G1CollectedHeap::initialize() {
1427 CollectedHeap::pre_initialize();
1428 os::enable_vtime();
1430 // Necessary to satisfy locking discipline assertions.
1432 MutexLocker x(Heap_lock);
1434 // While there are no constraints in the GC code that HeapWordSize
1435 // be any particular value, there are multiple other areas in the
1436 // system which believe this to be true (e.g. oop->object_size in some
1437 // cases incorrectly returns the size in wordSize units rather than
1438 // HeapWordSize).
1439 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1441 size_t init_byte_size = collector_policy()->initial_heap_byte_size();
1442 size_t max_byte_size = collector_policy()->max_heap_byte_size();
1444 // Ensure that the sizes are properly aligned.
1445 Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
1446 Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");
1448 _cg1r = new ConcurrentG1Refine();
1450 // Reserve the maximum.
1451 PermanentGenerationSpec* pgs = collector_policy()->permanent_generation();
1452 // Includes the perm-gen.
1454 const size_t total_reserved = max_byte_size + pgs->max_size();
1455 char* addr = Universe::preferred_heap_base(total_reserved, Universe::UnscaledNarrowOop);
1457 ReservedSpace heap_rs(max_byte_size + pgs->max_size(),
1458 HeapRegion::GrainBytes,
1459 false /*ism*/, addr);
1461 if (UseCompressedOops) {
1462 if (addr != NULL && !heap_rs.is_reserved()) {
1463 // Failed to reserve at specified address - the requested memory
1464 // region is taken already, for example, by 'java' launcher.
1465 // Try again to reserver heap higher.
1466 addr = Universe::preferred_heap_base(total_reserved, Universe::ZeroBasedNarrowOop);
1467 ReservedSpace heap_rs0(total_reserved, HeapRegion::GrainBytes,
1468 false /*ism*/, addr);
1469 if (addr != NULL && !heap_rs0.is_reserved()) {
1470 // Failed to reserve at specified address again - give up.
1471 addr = Universe::preferred_heap_base(total_reserved, Universe::HeapBasedNarrowOop);
1472 assert(addr == NULL, "");
1473 ReservedSpace heap_rs1(total_reserved, HeapRegion::GrainBytes,
1474 false /*ism*/, addr);
1475 heap_rs = heap_rs1;
1476 } else {
1477 heap_rs = heap_rs0;
1478 }
1479 }
1480 }
1482 if (!heap_rs.is_reserved()) {
1483 vm_exit_during_initialization("Could not reserve enough space for object heap");
1484 return JNI_ENOMEM;
1485 }
1487 // It is important to do this in a way such that concurrent readers can't
1488 // temporarily think somethings in the heap. (I've actually seen this
1489 // happen in asserts: DLD.)
1490 _reserved.set_word_size(0);
1491 _reserved.set_start((HeapWord*)heap_rs.base());
1492 _reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size()));
1494 _expansion_regions = max_byte_size/HeapRegion::GrainBytes;
1496 _num_humongous_regions = 0;
1498 // Create the gen rem set (and barrier set) for the entire reserved region.
1499 _rem_set = collector_policy()->create_rem_set(_reserved, 2);
1500 set_barrier_set(rem_set()->bs());
1501 if (barrier_set()->is_a(BarrierSet::ModRef)) {
1502 _mr_bs = (ModRefBarrierSet*)_barrier_set;
1503 } else {
1504 vm_exit_during_initialization("G1 requires a mod ref bs.");
1505 return JNI_ENOMEM;
1506 }
1508 // Also create a G1 rem set.
1509 if (G1UseHRIntoRS) {
1510 if (mr_bs()->is_a(BarrierSet::CardTableModRef)) {
1511 _g1_rem_set = new HRInto_G1RemSet(this, (CardTableModRefBS*)mr_bs());
1512 } else {
1513 vm_exit_during_initialization("G1 requires a cardtable mod ref bs.");
1514 return JNI_ENOMEM;
1515 }
1516 } else {
1517 _g1_rem_set = new StupidG1RemSet(this);
1518 }
1520 // Carve out the G1 part of the heap.
1522 ReservedSpace g1_rs = heap_rs.first_part(max_byte_size);
1523 _g1_reserved = MemRegion((HeapWord*)g1_rs.base(),
1524 g1_rs.size()/HeapWordSize);
1525 ReservedSpace perm_gen_rs = heap_rs.last_part(max_byte_size);
1527 _perm_gen = pgs->init(perm_gen_rs, pgs->init_size(), rem_set());
1529 _g1_storage.initialize(g1_rs, 0);
1530 _g1_committed = MemRegion((HeapWord*)_g1_storage.low(), (size_t) 0);
1531 _g1_max_committed = _g1_committed;
1532 _hrs = new HeapRegionSeq(_expansion_regions);
1533 guarantee(_hrs != NULL, "Couldn't allocate HeapRegionSeq");
1534 guarantee(_cur_alloc_region == NULL, "from constructor");
1536 // 6843694 - ensure that the maximum region index can fit
1537 // in the remembered set structures.
1538 const size_t max_region_idx = ((size_t)1 << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
1539 guarantee((max_regions() - 1) <= max_region_idx, "too many regions");
1541 size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
1542 guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
1543 guarantee((size_t) HeapRegion::CardsPerRegion < max_cards_per_region,
1544 "too many cards per region");
1546 _bot_shared = new G1BlockOffsetSharedArray(_reserved,
1547 heap_word_size(init_byte_size));
1549 _g1h = this;
1551 _in_cset_fast_test_length = max_regions();
1552 _in_cset_fast_test_base = NEW_C_HEAP_ARRAY(bool, _in_cset_fast_test_length);
1554 // We're biasing _in_cset_fast_test to avoid subtracting the
1555 // beginning of the heap every time we want to index; basically
1556 // it's the same with what we do with the card table.
1557 _in_cset_fast_test = _in_cset_fast_test_base -
1558 ((size_t) _g1_reserved.start() >> HeapRegion::LogOfHRGrainBytes);
1560 // Clear the _cset_fast_test bitmap in anticipation of adding
1561 // regions to the incremental collection set for the first
1562 // evacuation pause.
1563 clear_cset_fast_test();
1565 // Create the ConcurrentMark data structure and thread.
1566 // (Must do this late, so that "max_regions" is defined.)
1567 _cm = new ConcurrentMark(heap_rs, (int) max_regions());
1568 _cmThread = _cm->cmThread();
1570 // ...and the concurrent zero-fill thread, if necessary.
1571 if (G1ConcZeroFill) {
1572 _czft = new ConcurrentZFThread();
1573 }
1575 // Initialize the from_card cache structure of HeapRegionRemSet.
1576 HeapRegionRemSet::init_heap(max_regions());
1578 // Now expand into the initial heap size.
1579 expand(init_byte_size);
1581 // Perform any initialization actions delegated to the policy.
1582 g1_policy()->init();
1584 g1_policy()->note_start_of_mark_thread();
1586 _refine_cte_cl =
1587 new RefineCardTableEntryClosure(ConcurrentG1RefineThread::sts(),
1588 g1_rem_set(),
1589 concurrent_g1_refine());
1590 JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
1592 JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
1593 SATB_Q_FL_lock,
1594 G1SATBProcessCompletedThreshold,
1595 Shared_SATB_Q_lock);
1597 JavaThread::dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
1598 DirtyCardQ_FL_lock,
1599 concurrent_g1_refine()->yellow_zone(),
1600 concurrent_g1_refine()->red_zone(),
1601 Shared_DirtyCardQ_lock);
1603 if (G1DeferredRSUpdate) {
1604 dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
1605 DirtyCardQ_FL_lock,
1606 -1, // never trigger processing
1607 -1, // no limit on length
1608 Shared_DirtyCardQ_lock,
1609 &JavaThread::dirty_card_queue_set());
1610 }
1612 // Initialize the card queue set used to hold cards containing
1613 // references into the collection set.
1614 _into_cset_dirty_card_queue_set.initialize(DirtyCardQ_CBL_mon,
1615 DirtyCardQ_FL_lock,
1616 -1, // never trigger processing
1617 -1, // no limit on length
1618 Shared_DirtyCardQ_lock,
1619 &JavaThread::dirty_card_queue_set());
1621 // In case we're keeping closure specialization stats, initialize those
1622 // counts and that mechanism.
1623 SpecializationStats::clear();
1625 _gc_alloc_region_list = NULL;
1627 // Do later initialization work for concurrent refinement.
1628 _cg1r->init();
1630 return JNI_OK;
1631 }
1633 void G1CollectedHeap::ref_processing_init() {
1634 SharedHeap::ref_processing_init();
1635 MemRegion mr = reserved_region();
1636 _ref_processor = ReferenceProcessor::create_ref_processor(
1637 mr, // span
1638 false, // Reference discovery is not atomic
1639 // (though it shouldn't matter here.)
1640 true, // mt_discovery
1641 NULL, // is alive closure: need to fill this in for efficiency
1642 ParallelGCThreads,
1643 ParallelRefProcEnabled,
1644 true); // Setting next fields of discovered
1645 // lists requires a barrier.
1646 }
1648 size_t G1CollectedHeap::capacity() const {
1649 return _g1_committed.byte_size();
1650 }
1652 void G1CollectedHeap::iterate_dirty_card_closure(CardTableEntryClosure* cl,
1653 DirtyCardQueue* into_cset_dcq,
1654 bool concurrent,
1655 int worker_i) {
1656 // Clean cards in the hot card cache
1657 concurrent_g1_refine()->clean_up_cache(worker_i, g1_rem_set(), into_cset_dcq);
1659 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
1660 int n_completed_buffers = 0;
1661 while (dcqs.apply_closure_to_completed_buffer(cl, worker_i, 0, true)) {
1662 n_completed_buffers++;
1663 }
1664 g1_policy()->record_update_rs_processed_buffers(worker_i,
1665 (double) n_completed_buffers);
1666 dcqs.clear_n_completed_buffers();
1667 assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!");
1668 }
1671 // Computes the sum of the storage used by the various regions.
1673 size_t G1CollectedHeap::used() const {
1674 assert(Heap_lock->owner() != NULL,
1675 "Should be owned on this thread's behalf.");
1676 size_t result = _summary_bytes_used;
1677 // Read only once in case it is set to NULL concurrently
1678 HeapRegion* hr = _cur_alloc_region;
1679 if (hr != NULL)
1680 result += hr->used();
1681 return result;
1682 }
1684 size_t G1CollectedHeap::used_unlocked() const {
1685 size_t result = _summary_bytes_used;
1686 return result;
1687 }
1689 class SumUsedClosure: public HeapRegionClosure {
1690 size_t _used;
1691 public:
1692 SumUsedClosure() : _used(0) {}
1693 bool doHeapRegion(HeapRegion* r) {
1694 if (!r->continuesHumongous()) {
1695 _used += r->used();
1696 }
1697 return false;
1698 }
1699 size_t result() { return _used; }
1700 };
1702 size_t G1CollectedHeap::recalculate_used() const {
1703 SumUsedClosure blk;
1704 _hrs->iterate(&blk);
1705 return blk.result();
1706 }
1708 #ifndef PRODUCT
1709 class SumUsedRegionsClosure: public HeapRegionClosure {
1710 size_t _num;
1711 public:
1712 SumUsedRegionsClosure() : _num(0) {}
1713 bool doHeapRegion(HeapRegion* r) {
1714 if (r->continuesHumongous() || r->used() > 0 || r->is_gc_alloc_region()) {
1715 _num += 1;
1716 }
1717 return false;
1718 }
1719 size_t result() { return _num; }
1720 };
1722 size_t G1CollectedHeap::recalculate_used_regions() const {
1723 SumUsedRegionsClosure blk;
1724 _hrs->iterate(&blk);
1725 return blk.result();
1726 }
1727 #endif // PRODUCT
1729 size_t G1CollectedHeap::unsafe_max_alloc() {
1730 if (_free_regions > 0) return HeapRegion::GrainBytes;
1731 // otherwise, is there space in the current allocation region?
1733 // We need to store the current allocation region in a local variable
1734 // here. The problem is that this method doesn't take any locks and
1735 // there may be other threads which overwrite the current allocation
1736 // region field. attempt_allocation(), for example, sets it to NULL
1737 // and this can happen *after* the NULL check here but before the call
1738 // to free(), resulting in a SIGSEGV. Note that this doesn't appear
1739 // to be a problem in the optimized build, since the two loads of the
1740 // current allocation region field are optimized away.
1741 HeapRegion* car = _cur_alloc_region;
1743 // FIXME: should iterate over all regions?
1744 if (car == NULL) {
1745 return 0;
1746 }
1747 return car->free();
1748 }
1750 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
1751 return
1752 ((cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) ||
1753 (cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent));
1754 }
1756 void G1CollectedHeap::increment_full_collections_completed(bool outer) {
1757 MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
1759 // We have already incremented _total_full_collections at the start
1760 // of the GC, so total_full_collections() represents how many full
1761 // collections have been started.
1762 unsigned int full_collections_started = total_full_collections();
1764 // Given that this method is called at the end of a Full GC or of a
1765 // concurrent cycle, and those can be nested (i.e., a Full GC can
1766 // interrupt a concurrent cycle), the number of full collections
1767 // completed should be either one (in the case where there was no
1768 // nesting) or two (when a Full GC interrupted a concurrent cycle)
1769 // behind the number of full collections started.
1771 // This is the case for the inner caller, i.e. a Full GC.
1772 assert(outer ||
1773 (full_collections_started == _full_collections_completed + 1) ||
1774 (full_collections_started == _full_collections_completed + 2),
1775 err_msg("for inner caller: full_collections_started = %u "
1776 "is inconsistent with _full_collections_completed = %u",
1777 full_collections_started, _full_collections_completed));
1779 // This is the case for the outer caller, i.e. the concurrent cycle.
1780 assert(!outer ||
1781 (full_collections_started == _full_collections_completed + 1),
1782 err_msg("for outer caller: full_collections_started = %u "
1783 "is inconsistent with _full_collections_completed = %u",
1784 full_collections_started, _full_collections_completed));
1786 _full_collections_completed += 1;
1788 // We need to clear the "in_progress" flag in the CM thread before
1789 // we wake up any waiters (especially when ExplicitInvokesConcurrent
1790 // is set) so that if a waiter requests another System.gc() it doesn't
1791 // incorrectly see that a marking cyle is still in progress.
1792 if (outer) {
1793 _cmThread->clear_in_progress();
1794 }
1796 // This notify_all() will ensure that a thread that called
1797 // System.gc() with (with ExplicitGCInvokesConcurrent set or not)
1798 // and it's waiting for a full GC to finish will be woken up. It is
1799 // waiting in VM_G1IncCollectionPause::doit_epilogue().
1800 FullGCCount_lock->notify_all();
1801 }
1803 void G1CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) {
1804 assert(Thread::current()->is_VM_thread(), "Precondition#1");
1805 assert(Heap_lock->is_locked(), "Precondition#2");
1806 GCCauseSetter gcs(this, cause);
1807 switch (cause) {
1808 case GCCause::_heap_inspection:
1809 case GCCause::_heap_dump: {
1810 HandleMark hm;
1811 do_full_collection(false); // don't clear all soft refs
1812 break;
1813 }
1814 default: // XXX FIX ME
1815 ShouldNotReachHere(); // Unexpected use of this function
1816 }
1817 }
1819 void G1CollectedHeap::collect(GCCause::Cause cause) {
1820 // The caller doesn't have the Heap_lock
1821 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
1823 unsigned int gc_count_before;
1824 unsigned int full_gc_count_before;
1825 {
1826 MutexLocker ml(Heap_lock);
1827 // Read the GC count while holding the Heap_lock
1828 gc_count_before = SharedHeap::heap()->total_collections();
1829 full_gc_count_before = SharedHeap::heap()->total_full_collections();
1831 // Don't want to do a GC until cleanup is completed.
1832 wait_for_cleanup_complete();
1834 // We give up heap lock; VMThread::execute gets it back below
1835 }
1837 if (should_do_concurrent_full_gc(cause)) {
1838 // Schedule an initial-mark evacuation pause that will start a
1839 // concurrent cycle.
1840 VM_G1IncCollectionPause op(gc_count_before,
1841 true, /* should_initiate_conc_mark */
1842 g1_policy()->max_pause_time_ms(),
1843 cause);
1844 VMThread::execute(&op);
1845 } else {
1846 if (cause == GCCause::_gc_locker
1847 DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
1849 // Schedule a standard evacuation pause.
1850 VM_G1IncCollectionPause op(gc_count_before,
1851 false, /* should_initiate_conc_mark */
1852 g1_policy()->max_pause_time_ms(),
1853 cause);
1854 VMThread::execute(&op);
1855 } else {
1856 // Schedule a Full GC.
1857 VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause);
1858 VMThread::execute(&op);
1859 }
1860 }
1861 }
1863 bool G1CollectedHeap::is_in(const void* p) const {
1864 if (_g1_committed.contains(p)) {
1865 HeapRegion* hr = _hrs->addr_to_region(p);
1866 return hr->is_in(p);
1867 } else {
1868 return _perm_gen->as_gen()->is_in(p);
1869 }
1870 }
1872 // Iteration functions.
1874 // Iterates an OopClosure over all ref-containing fields of objects
1875 // within a HeapRegion.
1877 class IterateOopClosureRegionClosure: public HeapRegionClosure {
1878 MemRegion _mr;
1879 OopClosure* _cl;
1880 public:
1881 IterateOopClosureRegionClosure(MemRegion mr, OopClosure* cl)
1882 : _mr(mr), _cl(cl) {}
1883 bool doHeapRegion(HeapRegion* r) {
1884 if (! r->continuesHumongous()) {
1885 r->oop_iterate(_cl);
1886 }
1887 return false;
1888 }
1889 };
1891 void G1CollectedHeap::oop_iterate(OopClosure* cl, bool do_perm) {
1892 IterateOopClosureRegionClosure blk(_g1_committed, cl);
1893 _hrs->iterate(&blk);
1894 if (do_perm) {
1895 perm_gen()->oop_iterate(cl);
1896 }
1897 }
1899 void G1CollectedHeap::oop_iterate(MemRegion mr, OopClosure* cl, bool do_perm) {
1900 IterateOopClosureRegionClosure blk(mr, cl);
1901 _hrs->iterate(&blk);
1902 if (do_perm) {
1903 perm_gen()->oop_iterate(cl);
1904 }
1905 }
1907 // Iterates an ObjectClosure over all objects within a HeapRegion.
1909 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
1910 ObjectClosure* _cl;
1911 public:
1912 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
1913 bool doHeapRegion(HeapRegion* r) {
1914 if (! r->continuesHumongous()) {
1915 r->object_iterate(_cl);
1916 }
1917 return false;
1918 }
1919 };
1921 void G1CollectedHeap::object_iterate(ObjectClosure* cl, bool do_perm) {
1922 IterateObjectClosureRegionClosure blk(cl);
1923 _hrs->iterate(&blk);
1924 if (do_perm) {
1925 perm_gen()->object_iterate(cl);
1926 }
1927 }
1929 void G1CollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) {
1930 // FIXME: is this right?
1931 guarantee(false, "object_iterate_since_last_GC not supported by G1 heap");
1932 }
1934 // Calls a SpaceClosure on a HeapRegion.
1936 class SpaceClosureRegionClosure: public HeapRegionClosure {
1937 SpaceClosure* _cl;
1938 public:
1939 SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {}
1940 bool doHeapRegion(HeapRegion* r) {
1941 _cl->do_space(r);
1942 return false;
1943 }
1944 };
1946 void G1CollectedHeap::space_iterate(SpaceClosure* cl) {
1947 SpaceClosureRegionClosure blk(cl);
1948 _hrs->iterate(&blk);
1949 }
1951 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) {
1952 _hrs->iterate(cl);
1953 }
1955 void G1CollectedHeap::heap_region_iterate_from(HeapRegion* r,
1956 HeapRegionClosure* cl) {
1957 _hrs->iterate_from(r, cl);
1958 }
1960 void
1961 G1CollectedHeap::heap_region_iterate_from(int idx, HeapRegionClosure* cl) {
1962 _hrs->iterate_from(idx, cl);
1963 }
1965 HeapRegion* G1CollectedHeap::region_at(size_t idx) { return _hrs->at(idx); }
1967 void
1968 G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,
1969 int worker,
1970 jint claim_value) {
1971 const size_t regions = n_regions();
1972 const size_t worker_num = (G1CollectedHeap::use_parallel_gc_threads() ? ParallelGCThreads : 1);
1973 // try to spread out the starting points of the workers
1974 const size_t start_index = regions / worker_num * (size_t) worker;
1976 // each worker will actually look at all regions
1977 for (size_t count = 0; count < regions; ++count) {
1978 const size_t index = (start_index + count) % regions;
1979 assert(0 <= index && index < regions, "sanity");
1980 HeapRegion* r = region_at(index);
1981 // we'll ignore "continues humongous" regions (we'll process them
1982 // when we come across their corresponding "start humongous"
1983 // region) and regions already claimed
1984 if (r->claim_value() == claim_value || r->continuesHumongous()) {
1985 continue;
1986 }
1987 // OK, try to claim it
1988 if (r->claimHeapRegion(claim_value)) {
1989 // success!
1990 assert(!r->continuesHumongous(), "sanity");
1991 if (r->startsHumongous()) {
1992 // If the region is "starts humongous" we'll iterate over its
1993 // "continues humongous" first; in fact we'll do them
1994 // first. The order is important. In on case, calling the
1995 // closure on the "starts humongous" region might de-allocate
1996 // and clear all its "continues humongous" regions and, as a
1997 // result, we might end up processing them twice. So, we'll do
1998 // them first (notice: most closures will ignore them anyway) and
1999 // then we'll do the "starts humongous" region.
2000 for (size_t ch_index = index + 1; ch_index < regions; ++ch_index) {
2001 HeapRegion* chr = region_at(ch_index);
2003 // if the region has already been claimed or it's not
2004 // "continues humongous" we're done
2005 if (chr->claim_value() == claim_value ||
2006 !chr->continuesHumongous()) {
2007 break;
2008 }
2010 // Noone should have claimed it directly. We can given
2011 // that we claimed its "starts humongous" region.
2012 assert(chr->claim_value() != claim_value, "sanity");
2013 assert(chr->humongous_start_region() == r, "sanity");
2015 if (chr->claimHeapRegion(claim_value)) {
2016 // we should always be able to claim it; noone else should
2017 // be trying to claim this region
2019 bool res2 = cl->doHeapRegion(chr);
2020 assert(!res2, "Should not abort");
2022 // Right now, this holds (i.e., no closure that actually
2023 // does something with "continues humongous" regions
2024 // clears them). We might have to weaken it in the future,
2025 // but let's leave these two asserts here for extra safety.
2026 assert(chr->continuesHumongous(), "should still be the case");
2027 assert(chr->humongous_start_region() == r, "sanity");
2028 } else {
2029 guarantee(false, "we should not reach here");
2030 }
2031 }
2032 }
2034 assert(!r->continuesHumongous(), "sanity");
2035 bool res = cl->doHeapRegion(r);
2036 assert(!res, "Should not abort");
2037 }
2038 }
2039 }
2041 class ResetClaimValuesClosure: public HeapRegionClosure {
2042 public:
2043 bool doHeapRegion(HeapRegion* r) {
2044 r->set_claim_value(HeapRegion::InitialClaimValue);
2045 return false;
2046 }
2047 };
2049 void
2050 G1CollectedHeap::reset_heap_region_claim_values() {
2051 ResetClaimValuesClosure blk;
2052 heap_region_iterate(&blk);
2053 }
2055 #ifdef ASSERT
2056 // This checks whether all regions in the heap have the correct claim
2057 // value. I also piggy-backed on this a check to ensure that the
2058 // humongous_start_region() information on "continues humongous"
2059 // regions is correct.
2061 class CheckClaimValuesClosure : public HeapRegionClosure {
2062 private:
2063 jint _claim_value;
2064 size_t _failures;
2065 HeapRegion* _sh_region;
2066 public:
2067 CheckClaimValuesClosure(jint claim_value) :
2068 _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
2069 bool doHeapRegion(HeapRegion* r) {
2070 if (r->claim_value() != _claim_value) {
2071 gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), "
2072 "claim value = %d, should be %d",
2073 r->bottom(), r->end(), r->claim_value(),
2074 _claim_value);
2075 ++_failures;
2076 }
2077 if (!r->isHumongous()) {
2078 _sh_region = NULL;
2079 } else if (r->startsHumongous()) {
2080 _sh_region = r;
2081 } else if (r->continuesHumongous()) {
2082 if (r->humongous_start_region() != _sh_region) {
2083 gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), "
2084 "HS = "PTR_FORMAT", should be "PTR_FORMAT,
2085 r->bottom(), r->end(),
2086 r->humongous_start_region(),
2087 _sh_region);
2088 ++_failures;
2089 }
2090 }
2091 return false;
2092 }
2093 size_t failures() {
2094 return _failures;
2095 }
2096 };
2098 bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
2099 CheckClaimValuesClosure cl(claim_value);
2100 heap_region_iterate(&cl);
2101 return cl.failures() == 0;
2102 }
2103 #endif // ASSERT
2105 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {
2106 HeapRegion* r = g1_policy()->collection_set();
2107 while (r != NULL) {
2108 HeapRegion* next = r->next_in_collection_set();
2109 if (cl->doHeapRegion(r)) {
2110 cl->incomplete();
2111 return;
2112 }
2113 r = next;
2114 }
2115 }
2117 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,
2118 HeapRegionClosure *cl) {
2119 if (r == NULL) {
2120 // The CSet is empty so there's nothing to do.
2121 return;
2122 }
2124 assert(r->in_collection_set(),
2125 "Start region must be a member of the collection set.");
2126 HeapRegion* cur = r;
2127 while (cur != NULL) {
2128 HeapRegion* next = cur->next_in_collection_set();
2129 if (cl->doHeapRegion(cur) && false) {
2130 cl->incomplete();
2131 return;
2132 }
2133 cur = next;
2134 }
2135 cur = g1_policy()->collection_set();
2136 while (cur != r) {
2137 HeapRegion* next = cur->next_in_collection_set();
2138 if (cl->doHeapRegion(cur) && false) {
2139 cl->incomplete();
2140 return;
2141 }
2142 cur = next;
2143 }
2144 }
2146 CompactibleSpace* G1CollectedHeap::first_compactible_space() {
2147 return _hrs->length() > 0 ? _hrs->at(0) : NULL;
2148 }
2151 Space* G1CollectedHeap::space_containing(const void* addr) const {
2152 Space* res = heap_region_containing(addr);
2153 if (res == NULL)
2154 res = perm_gen()->space_containing(addr);
2155 return res;
2156 }
2158 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
2159 Space* sp = space_containing(addr);
2160 if (sp != NULL) {
2161 return sp->block_start(addr);
2162 }
2163 return NULL;
2164 }
2166 size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
2167 Space* sp = space_containing(addr);
2168 assert(sp != NULL, "block_size of address outside of heap");
2169 return sp->block_size(addr);
2170 }
2172 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
2173 Space* sp = space_containing(addr);
2174 return sp->block_is_obj(addr);
2175 }
2177 bool G1CollectedHeap::supports_tlab_allocation() const {
2178 return true;
2179 }
2181 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
2182 return HeapRegion::GrainBytes;
2183 }
2185 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
2186 // Return the remaining space in the cur alloc region, but not less than
2187 // the min TLAB size.
2189 // Also, this value can be at most the humongous object threshold,
2190 // since we can't allow tlabs to grow big enough to accomodate
2191 // humongous objects.
2193 // We need to store the cur alloc region locally, since it might change
2194 // between when we test for NULL and when we use it later.
2195 ContiguousSpace* cur_alloc_space = _cur_alloc_region;
2196 size_t max_tlab_size = _humongous_object_threshold_in_words * wordSize;
2198 if (cur_alloc_space == NULL) {
2199 return max_tlab_size;
2200 } else {
2201 return MIN2(MAX2(cur_alloc_space->free(), (size_t)MinTLABSize),
2202 max_tlab_size);
2203 }
2204 }
2206 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t word_size) {
2207 assert(!isHumongous(word_size),
2208 err_msg("a TLAB should not be of humongous size, "
2209 "word_size = "SIZE_FORMAT, word_size));
2210 bool dummy;
2211 return G1CollectedHeap::mem_allocate(word_size, false, true, &dummy);
2212 }
2214 bool G1CollectedHeap::allocs_are_zero_filled() {
2215 return false;
2216 }
2218 size_t G1CollectedHeap::large_typearray_limit() {
2219 // FIXME
2220 return HeapRegion::GrainBytes/HeapWordSize;
2221 }
2223 size_t G1CollectedHeap::max_capacity() const {
2224 return g1_reserved_obj_bytes();
2225 }
2227 jlong G1CollectedHeap::millis_since_last_gc() {
2228 // assert(false, "NYI");
2229 return 0;
2230 }
2233 void G1CollectedHeap::prepare_for_verify() {
2234 if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
2235 ensure_parsability(false);
2236 }
2237 g1_rem_set()->prepare_for_verify();
2238 }
2240 class VerifyLivenessOopClosure: public OopClosure {
2241 G1CollectedHeap* g1h;
2242 public:
2243 VerifyLivenessOopClosure(G1CollectedHeap* _g1h) {
2244 g1h = _g1h;
2245 }
2246 void do_oop(narrowOop *p) { do_oop_work(p); }
2247 void do_oop( oop *p) { do_oop_work(p); }
2249 template <class T> void do_oop_work(T *p) {
2250 oop obj = oopDesc::load_decode_heap_oop(p);
2251 guarantee(obj == NULL || !g1h->is_obj_dead(obj),
2252 "Dead object referenced by a not dead object");
2253 }
2254 };
2256 class VerifyObjsInRegionClosure: public ObjectClosure {
2257 private:
2258 G1CollectedHeap* _g1h;
2259 size_t _live_bytes;
2260 HeapRegion *_hr;
2261 bool _use_prev_marking;
2262 public:
2263 // use_prev_marking == true -> use "prev" marking information,
2264 // use_prev_marking == false -> use "next" marking information
2265 VerifyObjsInRegionClosure(HeapRegion *hr, bool use_prev_marking)
2266 : _live_bytes(0), _hr(hr), _use_prev_marking(use_prev_marking) {
2267 _g1h = G1CollectedHeap::heap();
2268 }
2269 void do_object(oop o) {
2270 VerifyLivenessOopClosure isLive(_g1h);
2271 assert(o != NULL, "Huh?");
2272 if (!_g1h->is_obj_dead_cond(o, _use_prev_marking)) {
2273 o->oop_iterate(&isLive);
2274 if (!_hr->obj_allocated_since_prev_marking(o)) {
2275 size_t obj_size = o->size(); // Make sure we don't overflow
2276 _live_bytes += (obj_size * HeapWordSize);
2277 }
2278 }
2279 }
2280 size_t live_bytes() { return _live_bytes; }
2281 };
2283 class PrintObjsInRegionClosure : public ObjectClosure {
2284 HeapRegion *_hr;
2285 G1CollectedHeap *_g1;
2286 public:
2287 PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) {
2288 _g1 = G1CollectedHeap::heap();
2289 };
2291 void do_object(oop o) {
2292 if (o != NULL) {
2293 HeapWord *start = (HeapWord *) o;
2294 size_t word_sz = o->size();
2295 gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT
2296 " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",
2297 (void*) o, word_sz,
2298 _g1->isMarkedPrev(o),
2299 _g1->isMarkedNext(o),
2300 _hr->obj_allocated_since_prev_marking(o));
2301 HeapWord *end = start + word_sz;
2302 HeapWord *cur;
2303 int *val;
2304 for (cur = start; cur < end; cur++) {
2305 val = (int *) cur;
2306 gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val);
2307 }
2308 }
2309 }
2310 };
2312 class VerifyRegionClosure: public HeapRegionClosure {
2313 private:
2314 bool _allow_dirty;
2315 bool _par;
2316 bool _use_prev_marking;
2317 bool _failures;
2318 public:
2319 // use_prev_marking == true -> use "prev" marking information,
2320 // use_prev_marking == false -> use "next" marking information
2321 VerifyRegionClosure(bool allow_dirty, bool par, bool use_prev_marking)
2322 : _allow_dirty(allow_dirty),
2323 _par(par),
2324 _use_prev_marking(use_prev_marking),
2325 _failures(false) {}
2327 bool failures() {
2328 return _failures;
2329 }
2331 bool doHeapRegion(HeapRegion* r) {
2332 guarantee(_par || r->claim_value() == HeapRegion::InitialClaimValue,
2333 "Should be unclaimed at verify points.");
2334 if (!r->continuesHumongous()) {
2335 bool failures = false;
2336 r->verify(_allow_dirty, _use_prev_marking, &failures);
2337 if (failures) {
2338 _failures = true;
2339 } else {
2340 VerifyObjsInRegionClosure not_dead_yet_cl(r, _use_prev_marking);
2341 r->object_iterate(¬_dead_yet_cl);
2342 if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) {
2343 gclog_or_tty->print_cr("["PTR_FORMAT","PTR_FORMAT"] "
2344 "max_live_bytes "SIZE_FORMAT" "
2345 "< calculated "SIZE_FORMAT,
2346 r->bottom(), r->end(),
2347 r->max_live_bytes(),
2348 not_dead_yet_cl.live_bytes());
2349 _failures = true;
2350 }
2351 }
2352 }
2353 return false; // stop the region iteration if we hit a failure
2354 }
2355 };
2357 class VerifyRootsClosure: public OopsInGenClosure {
2358 private:
2359 G1CollectedHeap* _g1h;
2360 bool _use_prev_marking;
2361 bool _failures;
2362 public:
2363 // use_prev_marking == true -> use "prev" marking information,
2364 // use_prev_marking == false -> use "next" marking information
2365 VerifyRootsClosure(bool use_prev_marking) :
2366 _g1h(G1CollectedHeap::heap()),
2367 _use_prev_marking(use_prev_marking),
2368 _failures(false) { }
2370 bool failures() { return _failures; }
2372 template <class T> void do_oop_nv(T* p) {
2373 T heap_oop = oopDesc::load_heap_oop(p);
2374 if (!oopDesc::is_null(heap_oop)) {
2375 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
2376 if (_g1h->is_obj_dead_cond(obj, _use_prev_marking)) {
2377 gclog_or_tty->print_cr("Root location "PTR_FORMAT" "
2378 "points to dead obj "PTR_FORMAT, p, (void*) obj);
2379 obj->print_on(gclog_or_tty);
2380 _failures = true;
2381 }
2382 }
2383 }
2385 void do_oop(oop* p) { do_oop_nv(p); }
2386 void do_oop(narrowOop* p) { do_oop_nv(p); }
2387 };
2389 // This is the task used for parallel heap verification.
2391 class G1ParVerifyTask: public AbstractGangTask {
2392 private:
2393 G1CollectedHeap* _g1h;
2394 bool _allow_dirty;
2395 bool _use_prev_marking;
2396 bool _failures;
2398 public:
2399 // use_prev_marking == true -> use "prev" marking information,
2400 // use_prev_marking == false -> use "next" marking information
2401 G1ParVerifyTask(G1CollectedHeap* g1h, bool allow_dirty,
2402 bool use_prev_marking) :
2403 AbstractGangTask("Parallel verify task"),
2404 _g1h(g1h),
2405 _allow_dirty(allow_dirty),
2406 _use_prev_marking(use_prev_marking),
2407 _failures(false) { }
2409 bool failures() {
2410 return _failures;
2411 }
2413 void work(int worker_i) {
2414 HandleMark hm;
2415 VerifyRegionClosure blk(_allow_dirty, true, _use_prev_marking);
2416 _g1h->heap_region_par_iterate_chunked(&blk, worker_i,
2417 HeapRegion::ParVerifyClaimValue);
2418 if (blk.failures()) {
2419 _failures = true;
2420 }
2421 }
2422 };
2424 void G1CollectedHeap::verify(bool allow_dirty, bool silent) {
2425 verify(allow_dirty, silent, /* use_prev_marking */ true);
2426 }
2428 void G1CollectedHeap::verify(bool allow_dirty,
2429 bool silent,
2430 bool use_prev_marking) {
2431 if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
2432 if (!silent) { gclog_or_tty->print("roots "); }
2433 VerifyRootsClosure rootsCl(use_prev_marking);
2434 CodeBlobToOopClosure blobsCl(&rootsCl, /*do_marking=*/ false);
2435 process_strong_roots(true, // activate StrongRootsScope
2436 false,
2437 SharedHeap::SO_AllClasses,
2438 &rootsCl,
2439 &blobsCl,
2440 &rootsCl);
2441 bool failures = rootsCl.failures();
2442 rem_set()->invalidate(perm_gen()->used_region(), false);
2443 if (!silent) { gclog_or_tty->print("heapRegions "); }
2444 if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
2445 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
2446 "sanity check");
2448 G1ParVerifyTask task(this, allow_dirty, use_prev_marking);
2449 int n_workers = workers()->total_workers();
2450 set_par_threads(n_workers);
2451 workers()->run_task(&task);
2452 set_par_threads(0);
2453 if (task.failures()) {
2454 failures = true;
2455 }
2457 assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),
2458 "sanity check");
2460 reset_heap_region_claim_values();
2462 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
2463 "sanity check");
2464 } else {
2465 VerifyRegionClosure blk(allow_dirty, false, use_prev_marking);
2466 _hrs->iterate(&blk);
2467 if (blk.failures()) {
2468 failures = true;
2469 }
2470 }
2471 if (!silent) gclog_or_tty->print("remset ");
2472 rem_set()->verify();
2474 if (failures) {
2475 gclog_or_tty->print_cr("Heap:");
2476 print_on(gclog_or_tty, true /* extended */);
2477 gclog_or_tty->print_cr("");
2478 #ifndef PRODUCT
2479 if (VerifyDuringGC && G1VerifyDuringGCPrintReachable) {
2480 concurrent_mark()->print_reachable("at-verification-failure",
2481 use_prev_marking, false /* all */);
2482 }
2483 #endif
2484 gclog_or_tty->flush();
2485 }
2486 guarantee(!failures, "there should not have been any failures");
2487 } else {
2488 if (!silent) gclog_or_tty->print("(SKIPPING roots, heapRegions, remset) ");
2489 }
2490 }
2492 class PrintRegionClosure: public HeapRegionClosure {
2493 outputStream* _st;
2494 public:
2495 PrintRegionClosure(outputStream* st) : _st(st) {}
2496 bool doHeapRegion(HeapRegion* r) {
2497 r->print_on(_st);
2498 return false;
2499 }
2500 };
2502 void G1CollectedHeap::print() const { print_on(tty); }
2504 void G1CollectedHeap::print_on(outputStream* st) const {
2505 print_on(st, PrintHeapAtGCExtended);
2506 }
2508 void G1CollectedHeap::print_on(outputStream* st, bool extended) const {
2509 st->print(" %-20s", "garbage-first heap");
2510 st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
2511 capacity()/K, used_unlocked()/K);
2512 st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")",
2513 _g1_storage.low_boundary(),
2514 _g1_storage.high(),
2515 _g1_storage.high_boundary());
2516 st->cr();
2517 st->print(" region size " SIZE_FORMAT "K, ",
2518 HeapRegion::GrainBytes/K);
2519 size_t young_regions = _young_list->length();
2520 st->print(SIZE_FORMAT " young (" SIZE_FORMAT "K), ",
2521 young_regions, young_regions * HeapRegion::GrainBytes / K);
2522 size_t survivor_regions = g1_policy()->recorded_survivor_regions();
2523 st->print(SIZE_FORMAT " survivors (" SIZE_FORMAT "K)",
2524 survivor_regions, survivor_regions * HeapRegion::GrainBytes / K);
2525 st->cr();
2526 perm()->as_gen()->print_on(st);
2527 if (extended) {
2528 st->cr();
2529 print_on_extended(st);
2530 }
2531 }
2533 void G1CollectedHeap::print_on_extended(outputStream* st) const {
2534 PrintRegionClosure blk(st);
2535 _hrs->iterate(&blk);
2536 }
2538 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
2539 if (G1CollectedHeap::use_parallel_gc_threads()) {
2540 workers()->print_worker_threads_on(st);
2541 }
2543 _cmThread->print_on(st);
2544 st->cr();
2546 _cm->print_worker_threads_on(st);
2548 _cg1r->print_worker_threads_on(st);
2550 _czft->print_on(st);
2551 st->cr();
2552 }
2554 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
2555 if (G1CollectedHeap::use_parallel_gc_threads()) {
2556 workers()->threads_do(tc);
2557 }
2558 tc->do_thread(_cmThread);
2559 _cg1r->threads_do(tc);
2560 tc->do_thread(_czft);
2561 }
2563 void G1CollectedHeap::print_tracing_info() const {
2564 // We'll overload this to mean "trace GC pause statistics."
2565 if (TraceGen0Time || TraceGen1Time) {
2566 // The "G1CollectorPolicy" is keeping track of these stats, so delegate
2567 // to that.
2568 g1_policy()->print_tracing_info();
2569 }
2570 if (G1SummarizeRSetStats) {
2571 g1_rem_set()->print_summary_info();
2572 }
2573 if (G1SummarizeConcMark) {
2574 concurrent_mark()->print_summary_info();
2575 }
2576 if (G1SummarizeZFStats) {
2577 ConcurrentZFThread::print_summary_info();
2578 }
2579 g1_policy()->print_yg_surv_rate_info();
2581 SpecializationStats::print();
2582 }
2585 int G1CollectedHeap::addr_to_arena_id(void* addr) const {
2586 HeapRegion* hr = heap_region_containing(addr);
2587 if (hr == NULL) {
2588 return 0;
2589 } else {
2590 return 1;
2591 }
2592 }
2594 G1CollectedHeap* G1CollectedHeap::heap() {
2595 assert(_sh->kind() == CollectedHeap::G1CollectedHeap,
2596 "not a garbage-first heap");
2597 return _g1h;
2598 }
2600 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {
2601 // always_do_update_barrier = false;
2602 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
2603 // Call allocation profiler
2604 AllocationProfiler::iterate_since_last_gc();
2605 // Fill TLAB's and such
2606 ensure_parsability(true);
2607 }
2609 void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) {
2610 // FIXME: what is this about?
2611 // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
2612 // is set.
2613 COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),
2614 "derived pointer present"));
2615 // always_do_update_barrier = true;
2616 }
2618 void G1CollectedHeap::do_collection_pause() {
2619 assert(Heap_lock->owned_by_self(), "we assume we'reholding the Heap_lock");
2621 // Read the GC count while holding the Heap_lock
2622 // we need to do this _before_ wait_for_cleanup_complete(), to
2623 // ensure that we do not give up the heap lock and potentially
2624 // pick up the wrong count
2625 unsigned int gc_count_before = SharedHeap::heap()->total_collections();
2627 // Don't want to do a GC pause while cleanup is being completed!
2628 wait_for_cleanup_complete();
2630 g1_policy()->record_stop_world_start();
2631 {
2632 MutexUnlocker mu(Heap_lock); // give up heap lock, execute gets it back
2633 VM_G1IncCollectionPause op(gc_count_before,
2634 false, /* should_initiate_conc_mark */
2635 g1_policy()->max_pause_time_ms(),
2636 GCCause::_g1_inc_collection_pause);
2637 VMThread::execute(&op);
2638 }
2639 }
2641 void
2642 G1CollectedHeap::doConcurrentMark() {
2643 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
2644 if (!_cmThread->in_progress()) {
2645 _cmThread->set_started();
2646 CGC_lock->notify();
2647 }
2648 }
2650 class VerifyMarkedObjsClosure: public ObjectClosure {
2651 G1CollectedHeap* _g1h;
2652 public:
2653 VerifyMarkedObjsClosure(G1CollectedHeap* g1h) : _g1h(g1h) {}
2654 void do_object(oop obj) {
2655 assert(obj->mark()->is_marked() ? !_g1h->is_obj_dead(obj) : true,
2656 "markandsweep mark should agree with concurrent deadness");
2657 }
2658 };
2660 void
2661 G1CollectedHeap::checkConcurrentMark() {
2662 VerifyMarkedObjsClosure verifycl(this);
2663 // MutexLockerEx x(getMarkBitMapLock(),
2664 // Mutex::_no_safepoint_check_flag);
2665 object_iterate(&verifycl, false);
2666 }
2668 void G1CollectedHeap::do_sync_mark() {
2669 _cm->checkpointRootsInitial();
2670 _cm->markFromRoots();
2671 _cm->checkpointRootsFinal(false);
2672 }
2674 // <NEW PREDICTION>
2676 double G1CollectedHeap::predict_region_elapsed_time_ms(HeapRegion *hr,
2677 bool young) {
2678 return _g1_policy->predict_region_elapsed_time_ms(hr, young);
2679 }
2681 void G1CollectedHeap::check_if_region_is_too_expensive(double
2682 predicted_time_ms) {
2683 _g1_policy->check_if_region_is_too_expensive(predicted_time_ms);
2684 }
2686 size_t G1CollectedHeap::pending_card_num() {
2687 size_t extra_cards = 0;
2688 JavaThread *curr = Threads::first();
2689 while (curr != NULL) {
2690 DirtyCardQueue& dcq = curr->dirty_card_queue();
2691 extra_cards += dcq.size();
2692 curr = curr->next();
2693 }
2694 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
2695 size_t buffer_size = dcqs.buffer_size();
2696 size_t buffer_num = dcqs.completed_buffers_num();
2697 return buffer_size * buffer_num + extra_cards;
2698 }
2700 size_t G1CollectedHeap::max_pending_card_num() {
2701 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
2702 size_t buffer_size = dcqs.buffer_size();
2703 size_t buffer_num = dcqs.completed_buffers_num();
2704 int thread_num = Threads::number_of_threads();
2705 return (buffer_num + thread_num) * buffer_size;
2706 }
2708 size_t G1CollectedHeap::cards_scanned() {
2709 HRInto_G1RemSet* g1_rset = (HRInto_G1RemSet*) g1_rem_set();
2710 return g1_rset->cardsScanned();
2711 }
2713 void
2714 G1CollectedHeap::setup_surviving_young_words() {
2715 guarantee( _surviving_young_words == NULL, "pre-condition" );
2716 size_t array_length = g1_policy()->young_cset_length();
2717 _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, array_length);
2718 if (_surviving_young_words == NULL) {
2719 vm_exit_out_of_memory(sizeof(size_t) * array_length,
2720 "Not enough space for young surv words summary.");
2721 }
2722 memset(_surviving_young_words, 0, array_length * sizeof(size_t));
2723 #ifdef ASSERT
2724 for (size_t i = 0; i < array_length; ++i) {
2725 assert( _surviving_young_words[i] == 0, "memset above" );
2726 }
2727 #endif // !ASSERT
2728 }
2730 void
2731 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {
2732 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
2733 size_t array_length = g1_policy()->young_cset_length();
2734 for (size_t i = 0; i < array_length; ++i)
2735 _surviving_young_words[i] += surv_young_words[i];
2736 }
2738 void
2739 G1CollectedHeap::cleanup_surviving_young_words() {
2740 guarantee( _surviving_young_words != NULL, "pre-condition" );
2741 FREE_C_HEAP_ARRAY(size_t, _surviving_young_words);
2742 _surviving_young_words = NULL;
2743 }
2745 // </NEW PREDICTION>
2747 struct PrepareForRSScanningClosure : public HeapRegionClosure {
2748 bool doHeapRegion(HeapRegion *r) {
2749 r->rem_set()->set_iter_claimed(0);
2750 return false;
2751 }
2752 };
2754 #if TASKQUEUE_STATS
2755 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
2756 st->print_raw_cr("GC Task Stats");
2757 st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
2758 st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
2759 }
2761 void G1CollectedHeap::print_taskqueue_stats(outputStream* const st) const {
2762 print_taskqueue_stats_hdr(st);
2764 TaskQueueStats totals;
2765 const int n = workers() != NULL ? workers()->total_workers() : 1;
2766 for (int i = 0; i < n; ++i) {
2767 st->print("%3d ", i); task_queue(i)->stats.print(st); st->cr();
2768 totals += task_queue(i)->stats;
2769 }
2770 st->print_raw("tot "); totals.print(st); st->cr();
2772 DEBUG_ONLY(totals.verify());
2773 }
2775 void G1CollectedHeap::reset_taskqueue_stats() {
2776 const int n = workers() != NULL ? workers()->total_workers() : 1;
2777 for (int i = 0; i < n; ++i) {
2778 task_queue(i)->stats.reset();
2779 }
2780 }
2781 #endif // TASKQUEUE_STATS
2783 void
2784 G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
2785 if (GC_locker::check_active_before_gc()) {
2786 return; // GC is disabled (e.g. JNI GetXXXCritical operation)
2787 }
2789 if (PrintHeapAtGC) {
2790 Universe::print_heap_before_gc();
2791 }
2793 {
2794 ResourceMark rm;
2796 // This call will decide whether this pause is an initial-mark
2797 // pause. If it is, during_initial_mark_pause() will return true
2798 // for the duration of this pause.
2799 g1_policy()->decide_on_conc_mark_initiation();
2801 char verbose_str[128];
2802 sprintf(verbose_str, "GC pause ");
2803 if (g1_policy()->in_young_gc_mode()) {
2804 if (g1_policy()->full_young_gcs())
2805 strcat(verbose_str, "(young)");
2806 else
2807 strcat(verbose_str, "(partial)");
2808 }
2809 if (g1_policy()->during_initial_mark_pause()) {
2810 strcat(verbose_str, " (initial-mark)");
2811 // We are about to start a marking cycle, so we increment the
2812 // full collection counter.
2813 increment_total_full_collections();
2814 }
2816 // if PrintGCDetails is on, we'll print long statistics information
2817 // in the collector policy code, so let's not print this as the output
2818 // is messy if we do.
2819 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
2820 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
2821 TraceTime t(verbose_str, PrintGC && !PrintGCDetails, true, gclog_or_tty);
2823 TraceMemoryManagerStats tms(false /* fullGC */);
2825 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
2826 assert(Thread::current() == VMThread::vm_thread(), "should be in vm thread");
2827 guarantee(!is_gc_active(), "collection is not reentrant");
2828 assert(regions_accounted_for(), "Region leakage!");
2830 increment_gc_time_stamp();
2832 if (g1_policy()->in_young_gc_mode()) {
2833 assert(check_young_list_well_formed(),
2834 "young list should be well formed");
2835 }
2837 { // Call to jvmpi::post_class_unload_events must occur outside of active GC
2838 IsGCActiveMark x;
2840 gc_prologue(false);
2841 increment_total_collections(false /* full gc */);
2843 #if G1_REM_SET_LOGGING
2844 gclog_or_tty->print_cr("\nJust chose CS, heap:");
2845 print();
2846 #endif
2848 if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) {
2849 HandleMark hm; // Discard invalid handles created during verification
2850 prepare_for_verify();
2851 gclog_or_tty->print(" VerifyBeforeGC:");
2852 Universe::verify(false);
2853 }
2855 COMPILER2_PRESENT(DerivedPointerTable::clear());
2857 // We want to turn off ref discovery, if necessary, and turn it back on
2858 // on again later if we do. XXX Dubious: why is discovery disabled?
2859 bool was_enabled = ref_processor()->discovery_enabled();
2860 if (was_enabled) ref_processor()->disable_discovery();
2862 // Forget the current alloc region (we might even choose it to be part
2863 // of the collection set!).
2864 abandon_cur_alloc_region();
2866 // The elapsed time induced by the start time below deliberately elides
2867 // the possible verification above.
2868 double start_time_sec = os::elapsedTime();
2869 size_t start_used_bytes = used();
2871 #if YOUNG_LIST_VERBOSE
2872 gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:");
2873 _young_list->print();
2874 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
2875 #endif // YOUNG_LIST_VERBOSE
2877 g1_policy()->record_collection_pause_start(start_time_sec,
2878 start_used_bytes);
2880 #if YOUNG_LIST_VERBOSE
2881 gclog_or_tty->print_cr("\nAfter recording pause start.\nYoung_list:");
2882 _young_list->print();
2883 #endif // YOUNG_LIST_VERBOSE
2885 if (g1_policy()->during_initial_mark_pause()) {
2886 concurrent_mark()->checkpointRootsInitialPre();
2887 }
2888 save_marks();
2890 // We must do this before any possible evacuation that should propagate
2891 // marks.
2892 if (mark_in_progress()) {
2893 double start_time_sec = os::elapsedTime();
2895 _cm->drainAllSATBBuffers();
2896 double finish_mark_ms = (os::elapsedTime() - start_time_sec) * 1000.0;
2897 g1_policy()->record_satb_drain_time(finish_mark_ms);
2898 }
2899 // Record the number of elements currently on the mark stack, so we
2900 // only iterate over these. (Since evacuation may add to the mark
2901 // stack, doing more exposes race conditions.) If no mark is in
2902 // progress, this will be zero.
2903 _cm->set_oops_do_bound();
2905 assert(regions_accounted_for(), "Region leakage.");
2907 if (mark_in_progress())
2908 concurrent_mark()->newCSet();
2910 #if YOUNG_LIST_VERBOSE
2911 gclog_or_tty->print_cr("\nBefore choosing collection set.\nYoung_list:");
2912 _young_list->print();
2913 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
2914 #endif // YOUNG_LIST_VERBOSE
2916 g1_policy()->choose_collection_set(target_pause_time_ms);
2918 // Nothing to do if we were unable to choose a collection set.
2919 #if G1_REM_SET_LOGGING
2920 gclog_or_tty->print_cr("\nAfter pause, heap:");
2921 print();
2922 #endif
2923 PrepareForRSScanningClosure prepare_for_rs_scan;
2924 collection_set_iterate(&prepare_for_rs_scan);
2926 setup_surviving_young_words();
2928 // Set up the gc allocation regions.
2929 get_gc_alloc_regions();
2931 // Actually do the work...
2932 evacuate_collection_set();
2934 free_collection_set(g1_policy()->collection_set());
2935 g1_policy()->clear_collection_set();
2937 cleanup_surviving_young_words();
2939 // Start a new incremental collection set for the next pause.
2940 g1_policy()->start_incremental_cset_building();
2942 // Clear the _cset_fast_test bitmap in anticipation of adding
2943 // regions to the incremental collection set for the next
2944 // evacuation pause.
2945 clear_cset_fast_test();
2947 if (g1_policy()->in_young_gc_mode()) {
2948 _young_list->reset_sampled_info();
2950 // Don't check the whole heap at this point as the
2951 // GC alloc regions from this pause have been tagged
2952 // as survivors and moved on to the survivor list.
2953 // Survivor regions will fail the !is_young() check.
2954 assert(check_young_list_empty(false /* check_heap */),
2955 "young list should be empty");
2957 #if YOUNG_LIST_VERBOSE
2958 gclog_or_tty->print_cr("Before recording survivors.\nYoung List:");
2959 _young_list->print();
2960 #endif // YOUNG_LIST_VERBOSE
2962 g1_policy()->record_survivor_regions(_young_list->survivor_length(),
2963 _young_list->first_survivor_region(),
2964 _young_list->last_survivor_region());
2966 _young_list->reset_auxilary_lists();
2967 }
2969 if (evacuation_failed()) {
2970 _summary_bytes_used = recalculate_used();
2971 } else {
2972 // The "used" of the the collection set have already been subtracted
2973 // when they were freed. Add in the bytes evacuated.
2974 _summary_bytes_used += g1_policy()->bytes_in_to_space();
2975 }
2977 if (g1_policy()->in_young_gc_mode() &&
2978 g1_policy()->during_initial_mark_pause()) {
2979 concurrent_mark()->checkpointRootsInitialPost();
2980 set_marking_started();
2981 // CAUTION: after the doConcurrentMark() call below,
2982 // the concurrent marking thread(s) could be running
2983 // concurrently with us. Make sure that anything after
2984 // this point does not assume that we are the only GC thread
2985 // running. Note: of course, the actual marking work will
2986 // not start until the safepoint itself is released in
2987 // ConcurrentGCThread::safepoint_desynchronize().
2988 doConcurrentMark();
2989 }
2991 #if YOUNG_LIST_VERBOSE
2992 gclog_or_tty->print_cr("\nEnd of the pause.\nYoung_list:");
2993 _young_list->print();
2994 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
2995 #endif // YOUNG_LIST_VERBOSE
2997 double end_time_sec = os::elapsedTime();
2998 double pause_time_ms = (end_time_sec - start_time_sec) * MILLIUNITS;
2999 g1_policy()->record_pause_time_ms(pause_time_ms);
3000 g1_policy()->record_collection_pause_end();
3002 assert(regions_accounted_for(), "Region leakage.");
3004 MemoryService::track_memory_usage();
3006 if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
3007 HandleMark hm; // Discard invalid handles created during verification
3008 gclog_or_tty->print(" VerifyAfterGC:");
3009 prepare_for_verify();
3010 Universe::verify(false);
3011 }
3013 if (was_enabled) ref_processor()->enable_discovery();
3015 {
3016 size_t expand_bytes = g1_policy()->expansion_amount();
3017 if (expand_bytes > 0) {
3018 size_t bytes_before = capacity();
3019 expand(expand_bytes);
3020 }
3021 }
3023 if (mark_in_progress()) {
3024 concurrent_mark()->update_g1_committed();
3025 }
3027 #ifdef TRACESPINNING
3028 ParallelTaskTerminator::print_termination_counts();
3029 #endif
3031 gc_epilogue(false);
3032 }
3034 assert(verify_region_lists(), "Bad region lists.");
3036 if (ExitAfterGCNum > 0 && total_collections() == ExitAfterGCNum) {
3037 gclog_or_tty->print_cr("Stopping after GC #%d", ExitAfterGCNum);
3038 print_tracing_info();
3039 vm_exit(-1);
3040 }
3041 }
3043 TASKQUEUE_STATS_ONLY(if (ParallelGCVerbose) print_taskqueue_stats());
3044 TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
3046 if (PrintHeapAtGC) {
3047 Universe::print_heap_after_gc();
3048 }
3049 if (G1SummarizeRSetStats &&
3050 (G1SummarizeRSetStatsPeriod > 0) &&
3051 (total_collections() % G1SummarizeRSetStatsPeriod == 0)) {
3052 g1_rem_set()->print_summary_info();
3053 }
3054 }
3056 size_t G1CollectedHeap::desired_plab_sz(GCAllocPurpose purpose)
3057 {
3058 size_t gclab_word_size;
3059 switch (purpose) {
3060 case GCAllocForSurvived:
3061 gclab_word_size = YoungPLABSize;
3062 break;
3063 case GCAllocForTenured:
3064 gclab_word_size = OldPLABSize;
3065 break;
3066 default:
3067 assert(false, "unknown GCAllocPurpose");
3068 gclab_word_size = OldPLABSize;
3069 break;
3070 }
3071 return gclab_word_size;
3072 }
3075 void G1CollectedHeap::set_gc_alloc_region(int purpose, HeapRegion* r) {
3076 assert(purpose >= 0 && purpose < GCAllocPurposeCount, "invalid purpose");
3077 // make sure we don't call set_gc_alloc_region() multiple times on
3078 // the same region
3079 assert(r == NULL || !r->is_gc_alloc_region(),
3080 "shouldn't already be a GC alloc region");
3081 assert(r == NULL || !r->isHumongous(),
3082 "humongous regions shouldn't be used as GC alloc regions");
3084 HeapWord* original_top = NULL;
3085 if (r != NULL)
3086 original_top = r->top();
3088 // We will want to record the used space in r as being there before gc.
3089 // One we install it as a GC alloc region it's eligible for allocation.
3090 // So record it now and use it later.
3091 size_t r_used = 0;
3092 if (r != NULL) {
3093 r_used = r->used();
3095 if (G1CollectedHeap::use_parallel_gc_threads()) {
3096 // need to take the lock to guard against two threads calling
3097 // get_gc_alloc_region concurrently (very unlikely but...)
3098 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
3099 r->save_marks();
3100 }
3101 }
3102 HeapRegion* old_alloc_region = _gc_alloc_regions[purpose];
3103 _gc_alloc_regions[purpose] = r;
3104 if (old_alloc_region != NULL) {
3105 // Replace aliases too.
3106 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
3107 if (_gc_alloc_regions[ap] == old_alloc_region) {
3108 _gc_alloc_regions[ap] = r;
3109 }
3110 }
3111 }
3112 if (r != NULL) {
3113 push_gc_alloc_region(r);
3114 if (mark_in_progress() && original_top != r->next_top_at_mark_start()) {
3115 // We are using a region as a GC alloc region after it has been used
3116 // as a mutator allocation region during the current marking cycle.
3117 // The mutator-allocated objects are currently implicitly marked, but
3118 // when we move hr->next_top_at_mark_start() forward at the the end
3119 // of the GC pause, they won't be. We therefore mark all objects in
3120 // the "gap". We do this object-by-object, since marking densely
3121 // does not currently work right with marking bitmap iteration. This
3122 // means we rely on TLAB filling at the start of pauses, and no
3123 // "resuscitation" of filled TLAB's. If we want to do this, we need
3124 // to fix the marking bitmap iteration.
3125 HeapWord* curhw = r->next_top_at_mark_start();
3126 HeapWord* t = original_top;
3128 while (curhw < t) {
3129 oop cur = (oop)curhw;
3130 // We'll assume parallel for generality. This is rare code.
3131 concurrent_mark()->markAndGrayObjectIfNecessary(cur); // can't we just mark them?
3132 curhw = curhw + cur->size();
3133 }
3134 assert(curhw == t, "Should have parsed correctly.");
3135 }
3136 if (G1PolicyVerbose > 1) {
3137 gclog_or_tty->print("New alloc region ["PTR_FORMAT", "PTR_FORMAT", " PTR_FORMAT") "
3138 "for survivors:", r->bottom(), original_top, r->end());
3139 r->print();
3140 }
3141 g1_policy()->record_before_bytes(r_used);
3142 }
3143 }
3145 void G1CollectedHeap::push_gc_alloc_region(HeapRegion* hr) {
3146 assert(Thread::current()->is_VM_thread() ||
3147 par_alloc_during_gc_lock()->owned_by_self(), "Precondition");
3148 assert(!hr->is_gc_alloc_region() && !hr->in_collection_set(),
3149 "Precondition.");
3150 hr->set_is_gc_alloc_region(true);
3151 hr->set_next_gc_alloc_region(_gc_alloc_region_list);
3152 _gc_alloc_region_list = hr;
3153 }
3155 #ifdef G1_DEBUG
3156 class FindGCAllocRegion: public HeapRegionClosure {
3157 public:
3158 bool doHeapRegion(HeapRegion* r) {
3159 if (r->is_gc_alloc_region()) {
3160 gclog_or_tty->print_cr("Region %d ["PTR_FORMAT"...] is still a gc_alloc_region.",
3161 r->hrs_index(), r->bottom());
3162 }
3163 return false;
3164 }
3165 };
3166 #endif // G1_DEBUG
3168 void G1CollectedHeap::forget_alloc_region_list() {
3169 assert(Thread::current()->is_VM_thread(), "Precondition");
3170 while (_gc_alloc_region_list != NULL) {
3171 HeapRegion* r = _gc_alloc_region_list;
3172 assert(r->is_gc_alloc_region(), "Invariant.");
3173 // We need HeapRegion::oops_on_card_seq_iterate_careful() to work on
3174 // newly allocated data in order to be able to apply deferred updates
3175 // before the GC is done for verification purposes (i.e to allow
3176 // G1HRRSFlushLogBuffersOnVerify). It's safe thing to do after the
3177 // collection.
3178 r->ContiguousSpace::set_saved_mark();
3179 _gc_alloc_region_list = r->next_gc_alloc_region();
3180 r->set_next_gc_alloc_region(NULL);
3181 r->set_is_gc_alloc_region(false);
3182 if (r->is_survivor()) {
3183 if (r->is_empty()) {
3184 r->set_not_young();
3185 } else {
3186 _young_list->add_survivor_region(r);
3187 }
3188 }
3189 if (r->is_empty()) {
3190 ++_free_regions;
3191 }
3192 }
3193 #ifdef G1_DEBUG
3194 FindGCAllocRegion fa;
3195 heap_region_iterate(&fa);
3196 #endif // G1_DEBUG
3197 }
3200 bool G1CollectedHeap::check_gc_alloc_regions() {
3201 // TODO: allocation regions check
3202 return true;
3203 }
3205 void G1CollectedHeap::get_gc_alloc_regions() {
3206 // First, let's check that the GC alloc region list is empty (it should)
3207 assert(_gc_alloc_region_list == NULL, "invariant");
3209 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
3210 assert(_gc_alloc_regions[ap] == NULL, "invariant");
3211 assert(_gc_alloc_region_counts[ap] == 0, "invariant");
3213 // Create new GC alloc regions.
3214 HeapRegion* alloc_region = _retained_gc_alloc_regions[ap];
3215 _retained_gc_alloc_regions[ap] = NULL;
3217 if (alloc_region != NULL) {
3218 assert(_retain_gc_alloc_region[ap], "only way to retain a GC region");
3220 // let's make sure that the GC alloc region is not tagged as such
3221 // outside a GC operation
3222 assert(!alloc_region->is_gc_alloc_region(), "sanity");
3224 if (alloc_region->in_collection_set() ||
3225 alloc_region->top() == alloc_region->end() ||
3226 alloc_region->top() == alloc_region->bottom() ||
3227 alloc_region->isHumongous()) {
3228 // we will discard the current GC alloc region if
3229 // * it's in the collection set (it can happen!),
3230 // * it's already full (no point in using it),
3231 // * it's empty (this means that it was emptied during
3232 // a cleanup and it should be on the free list now), or
3233 // * it's humongous (this means that it was emptied
3234 // during a cleanup and was added to the free list, but
3235 // has been subseqently used to allocate a humongous
3236 // object that may be less than the region size).
3238 alloc_region = NULL;
3239 }
3240 }
3242 if (alloc_region == NULL) {
3243 // we will get a new GC alloc region
3244 alloc_region = newAllocRegionWithExpansion(ap, 0);
3245 } else {
3246 // the region was retained from the last collection
3247 ++_gc_alloc_region_counts[ap];
3248 if (G1PrintHeapRegions) {
3249 gclog_or_tty->print_cr("new alloc region %d:["PTR_FORMAT", "PTR_FORMAT"], "
3250 "top "PTR_FORMAT,
3251 alloc_region->hrs_index(), alloc_region->bottom(), alloc_region->end(), alloc_region->top());
3252 }
3253 }
3255 if (alloc_region != NULL) {
3256 assert(_gc_alloc_regions[ap] == NULL, "pre-condition");
3257 set_gc_alloc_region(ap, alloc_region);
3258 }
3260 assert(_gc_alloc_regions[ap] == NULL ||
3261 _gc_alloc_regions[ap]->is_gc_alloc_region(),
3262 "the GC alloc region should be tagged as such");
3263 assert(_gc_alloc_regions[ap] == NULL ||
3264 _gc_alloc_regions[ap] == _gc_alloc_region_list,
3265 "the GC alloc region should be the same as the GC alloc list head");
3266 }
3267 // Set alternative regions for allocation purposes that have reached
3268 // their limit.
3269 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
3270 GCAllocPurpose alt_purpose = g1_policy()->alternative_purpose(ap);
3271 if (_gc_alloc_regions[ap] == NULL && alt_purpose != ap) {
3272 _gc_alloc_regions[ap] = _gc_alloc_regions[alt_purpose];
3273 }
3274 }
3275 assert(check_gc_alloc_regions(), "alloc regions messed up");
3276 }
3278 void G1CollectedHeap::release_gc_alloc_regions(bool totally) {
3279 // We keep a separate list of all regions that have been alloc regions in
3280 // the current collection pause. Forget that now. This method will
3281 // untag the GC alloc regions and tear down the GC alloc region
3282 // list. It's desirable that no regions are tagged as GC alloc
3283 // outside GCs.
3284 forget_alloc_region_list();
3286 // The current alloc regions contain objs that have survived
3287 // collection. Make them no longer GC alloc regions.
3288 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
3289 HeapRegion* r = _gc_alloc_regions[ap];
3290 _retained_gc_alloc_regions[ap] = NULL;
3291 _gc_alloc_region_counts[ap] = 0;
3293 if (r != NULL) {
3294 // we retain nothing on _gc_alloc_regions between GCs
3295 set_gc_alloc_region(ap, NULL);
3297 if (r->is_empty()) {
3298 // we didn't actually allocate anything in it; let's just put
3299 // it on the free list
3300 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
3301 r->set_zero_fill_complete();
3302 put_free_region_on_list_locked(r);
3303 } else if (_retain_gc_alloc_region[ap] && !totally) {
3304 // retain it so that we can use it at the beginning of the next GC
3305 _retained_gc_alloc_regions[ap] = r;
3306 }
3307 }
3308 }
3309 }
3311 #ifndef PRODUCT
3312 // Useful for debugging
3314 void G1CollectedHeap::print_gc_alloc_regions() {
3315 gclog_or_tty->print_cr("GC alloc regions");
3316 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
3317 HeapRegion* r = _gc_alloc_regions[ap];
3318 if (r == NULL) {
3319 gclog_or_tty->print_cr(" %2d : "PTR_FORMAT, ap, NULL);
3320 } else {
3321 gclog_or_tty->print_cr(" %2d : "PTR_FORMAT" "SIZE_FORMAT,
3322 ap, r->bottom(), r->used());
3323 }
3324 }
3325 }
3326 #endif // PRODUCT
3328 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {
3329 _drain_in_progress = false;
3330 set_evac_failure_closure(cl);
3331 _evac_failure_scan_stack = new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true);
3332 }
3334 void G1CollectedHeap::finalize_for_evac_failure() {
3335 assert(_evac_failure_scan_stack != NULL &&
3336 _evac_failure_scan_stack->length() == 0,
3337 "Postcondition");
3338 assert(!_drain_in_progress, "Postcondition");
3339 delete _evac_failure_scan_stack;
3340 _evac_failure_scan_stack = NULL;
3341 }
3345 // *** Sequential G1 Evacuation
3347 HeapWord* G1CollectedHeap::allocate_during_gc(GCAllocPurpose purpose, size_t word_size) {
3348 HeapRegion* alloc_region = _gc_alloc_regions[purpose];
3349 // let the caller handle alloc failure
3350 if (alloc_region == NULL) return NULL;
3351 assert(isHumongous(word_size) || !alloc_region->isHumongous(),
3352 "Either the object is humongous or the region isn't");
3353 HeapWord* block = alloc_region->allocate(word_size);
3354 if (block == NULL) {
3355 block = allocate_during_gc_slow(purpose, alloc_region, false, word_size);
3356 }
3357 return block;
3358 }
3360 class G1IsAliveClosure: public BoolObjectClosure {
3361 G1CollectedHeap* _g1;
3362 public:
3363 G1IsAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
3364 void do_object(oop p) { assert(false, "Do not call."); }
3365 bool do_object_b(oop p) {
3366 // It is reachable if it is outside the collection set, or is inside
3367 // and forwarded.
3369 #ifdef G1_DEBUG
3370 gclog_or_tty->print_cr("is alive "PTR_FORMAT" in CS %d forwarded %d overall %d",
3371 (void*) p, _g1->obj_in_cs(p), p->is_forwarded(),
3372 !_g1->obj_in_cs(p) || p->is_forwarded());
3373 #endif // G1_DEBUG
3375 return !_g1->obj_in_cs(p) || p->is_forwarded();
3376 }
3377 };
3379 class G1KeepAliveClosure: public OopClosure {
3380 G1CollectedHeap* _g1;
3381 public:
3382 G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
3383 void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
3384 void do_oop( oop* p) {
3385 oop obj = *p;
3386 #ifdef G1_DEBUG
3387 if (PrintGC && Verbose) {
3388 gclog_or_tty->print_cr("keep alive *"PTR_FORMAT" = "PTR_FORMAT" "PTR_FORMAT,
3389 p, (void*) obj, (void*) *p);
3390 }
3391 #endif // G1_DEBUG
3393 if (_g1->obj_in_cs(obj)) {
3394 assert( obj->is_forwarded(), "invariant" );
3395 *p = obj->forwardee();
3396 #ifdef G1_DEBUG
3397 gclog_or_tty->print_cr(" in CSet: moved "PTR_FORMAT" -> "PTR_FORMAT,
3398 (void*) obj, (void*) *p);
3399 #endif // G1_DEBUG
3400 }
3401 }
3402 };
3404 class UpdateRSetDeferred : public OopsInHeapRegionClosure {
3405 private:
3406 G1CollectedHeap* _g1;
3407 DirtyCardQueue *_dcq;
3408 CardTableModRefBS* _ct_bs;
3410 public:
3411 UpdateRSetDeferred(G1CollectedHeap* g1, DirtyCardQueue* dcq) :
3412 _g1(g1), _ct_bs((CardTableModRefBS*)_g1->barrier_set()), _dcq(dcq) {}
3414 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
3415 virtual void do_oop( oop* p) { do_oop_work(p); }
3416 template <class T> void do_oop_work(T* p) {
3417 assert(_from->is_in_reserved(p), "paranoia");
3418 if (!_from->is_in_reserved(oopDesc::load_decode_heap_oop(p)) &&
3419 !_from->is_survivor()) {
3420 size_t card_index = _ct_bs->index_for(p);
3421 if (_ct_bs->mark_card_deferred(card_index)) {
3422 _dcq->enqueue((jbyte*)_ct_bs->byte_for_index(card_index));
3423 }
3424 }
3425 }
3426 };
3428 class RemoveSelfPointerClosure: public ObjectClosure {
3429 private:
3430 G1CollectedHeap* _g1;
3431 ConcurrentMark* _cm;
3432 HeapRegion* _hr;
3433 size_t _prev_marked_bytes;
3434 size_t _next_marked_bytes;
3435 OopsInHeapRegionClosure *_cl;
3436 public:
3437 RemoveSelfPointerClosure(G1CollectedHeap* g1, OopsInHeapRegionClosure* cl) :
3438 _g1(g1), _cm(_g1->concurrent_mark()), _prev_marked_bytes(0),
3439 _next_marked_bytes(0), _cl(cl) {}
3441 size_t prev_marked_bytes() { return _prev_marked_bytes; }
3442 size_t next_marked_bytes() { return _next_marked_bytes; }
3444 // The original idea here was to coalesce evacuated and dead objects.
3445 // However that caused complications with the block offset table (BOT).
3446 // In particular if there were two TLABs, one of them partially refined.
3447 // |----- TLAB_1--------|----TLAB_2-~~~(partially refined part)~~~|
3448 // The BOT entries of the unrefined part of TLAB_2 point to the start
3449 // of TLAB_2. If the last object of the TLAB_1 and the first object
3450 // of TLAB_2 are coalesced, then the cards of the unrefined part
3451 // would point into middle of the filler object.
3452 //
3453 // The current approach is to not coalesce and leave the BOT contents intact.
3454 void do_object(oop obj) {
3455 if (obj->is_forwarded() && obj->forwardee() == obj) {
3456 // The object failed to move.
3457 assert(!_g1->is_obj_dead(obj), "We should not be preserving dead objs.");
3458 _cm->markPrev(obj);
3459 assert(_cm->isPrevMarked(obj), "Should be marked!");
3460 _prev_marked_bytes += (obj->size() * HeapWordSize);
3461 if (_g1->mark_in_progress() && !_g1->is_obj_ill(obj)) {
3462 _cm->markAndGrayObjectIfNecessary(obj);
3463 }
3464 obj->set_mark(markOopDesc::prototype());
3465 // While we were processing RSet buffers during the
3466 // collection, we actually didn't scan any cards on the
3467 // collection set, since we didn't want to update remebered
3468 // sets with entries that point into the collection set, given
3469 // that live objects fromthe collection set are about to move
3470 // and such entries will be stale very soon. This change also
3471 // dealt with a reliability issue which involved scanning a
3472 // card in the collection set and coming across an array that
3473 // was being chunked and looking malformed. The problem is
3474 // that, if evacuation fails, we might have remembered set
3475 // entries missing given that we skipped cards on the
3476 // collection set. So, we'll recreate such entries now.
3477 obj->oop_iterate(_cl);
3478 assert(_cm->isPrevMarked(obj), "Should be marked!");
3479 } else {
3480 // The object has been either evacuated or is dead. Fill it with a
3481 // dummy object.
3482 MemRegion mr((HeapWord*)obj, obj->size());
3483 CollectedHeap::fill_with_object(mr);
3484 _cm->clearRangeBothMaps(mr);
3485 }
3486 }
3487 };
3489 void G1CollectedHeap::remove_self_forwarding_pointers() {
3490 UpdateRSetImmediate immediate_update(_g1h->g1_rem_set());
3491 DirtyCardQueue dcq(&_g1h->dirty_card_queue_set());
3492 UpdateRSetDeferred deferred_update(_g1h, &dcq);
3493 OopsInHeapRegionClosure *cl;
3494 if (G1DeferredRSUpdate) {
3495 cl = &deferred_update;
3496 } else {
3497 cl = &immediate_update;
3498 }
3499 HeapRegion* cur = g1_policy()->collection_set();
3500 while (cur != NULL) {
3501 assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!");
3503 RemoveSelfPointerClosure rspc(_g1h, cl);
3504 if (cur->evacuation_failed()) {
3505 assert(cur->in_collection_set(), "bad CS");
3506 cl->set_region(cur);
3507 cur->object_iterate(&rspc);
3509 // A number of manipulations to make the TAMS be the current top,
3510 // and the marked bytes be the ones observed in the iteration.
3511 if (_g1h->concurrent_mark()->at_least_one_mark_complete()) {
3512 // The comments below are the postconditions achieved by the
3513 // calls. Note especially the last such condition, which says that
3514 // the count of marked bytes has been properly restored.
3515 cur->note_start_of_marking(false);
3516 // _next_top_at_mark_start == top, _next_marked_bytes == 0
3517 cur->add_to_marked_bytes(rspc.prev_marked_bytes());
3518 // _next_marked_bytes == prev_marked_bytes.
3519 cur->note_end_of_marking();
3520 // _prev_top_at_mark_start == top(),
3521 // _prev_marked_bytes == prev_marked_bytes
3522 }
3523 // If there is no mark in progress, we modified the _next variables
3524 // above needlessly, but harmlessly.
3525 if (_g1h->mark_in_progress()) {
3526 cur->note_start_of_marking(false);
3527 // _next_top_at_mark_start == top, _next_marked_bytes == 0
3528 // _next_marked_bytes == next_marked_bytes.
3529 }
3531 // Now make sure the region has the right index in the sorted array.
3532 g1_policy()->note_change_in_marked_bytes(cur);
3533 }
3534 cur = cur->next_in_collection_set();
3535 }
3536 assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!");
3538 // Now restore saved marks, if any.
3539 if (_objs_with_preserved_marks != NULL) {
3540 assert(_preserved_marks_of_objs != NULL, "Both or none.");
3541 assert(_objs_with_preserved_marks->length() ==
3542 _preserved_marks_of_objs->length(), "Both or none.");
3543 guarantee(_objs_with_preserved_marks->length() ==
3544 _preserved_marks_of_objs->length(), "Both or none.");
3545 for (int i = 0; i < _objs_with_preserved_marks->length(); i++) {
3546 oop obj = _objs_with_preserved_marks->at(i);
3547 markOop m = _preserved_marks_of_objs->at(i);
3548 obj->set_mark(m);
3549 }
3550 // Delete the preserved marks growable arrays (allocated on the C heap).
3551 delete _objs_with_preserved_marks;
3552 delete _preserved_marks_of_objs;
3553 _objs_with_preserved_marks = NULL;
3554 _preserved_marks_of_objs = NULL;
3555 }
3556 }
3558 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {
3559 _evac_failure_scan_stack->push(obj);
3560 }
3562 void G1CollectedHeap::drain_evac_failure_scan_stack() {
3563 assert(_evac_failure_scan_stack != NULL, "precondition");
3565 while (_evac_failure_scan_stack->length() > 0) {
3566 oop obj = _evac_failure_scan_stack->pop();
3567 _evac_failure_closure->set_region(heap_region_containing(obj));
3568 obj->oop_iterate_backwards(_evac_failure_closure);
3569 }
3570 }
3572 void G1CollectedHeap::handle_evacuation_failure(oop old) {
3573 markOop m = old->mark();
3574 // forward to self
3575 assert(!old->is_forwarded(), "precondition");
3577 old->forward_to(old);
3578 handle_evacuation_failure_common(old, m);
3579 }
3581 oop
3582 G1CollectedHeap::handle_evacuation_failure_par(OopsInHeapRegionClosure* cl,
3583 oop old) {
3584 markOop m = old->mark();
3585 oop forward_ptr = old->forward_to_atomic(old);
3586 if (forward_ptr == NULL) {
3587 // Forward-to-self succeeded.
3588 if (_evac_failure_closure != cl) {
3589 MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag);
3590 assert(!_drain_in_progress,
3591 "Should only be true while someone holds the lock.");
3592 // Set the global evac-failure closure to the current thread's.
3593 assert(_evac_failure_closure == NULL, "Or locking has failed.");
3594 set_evac_failure_closure(cl);
3595 // Now do the common part.
3596 handle_evacuation_failure_common(old, m);
3597 // Reset to NULL.
3598 set_evac_failure_closure(NULL);
3599 } else {
3600 // The lock is already held, and this is recursive.
3601 assert(_drain_in_progress, "This should only be the recursive case.");
3602 handle_evacuation_failure_common(old, m);
3603 }
3604 return old;
3605 } else {
3606 // Someone else had a place to copy it.
3607 return forward_ptr;
3608 }
3609 }
3611 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) {
3612 set_evacuation_failed(true);
3614 preserve_mark_if_necessary(old, m);
3616 HeapRegion* r = heap_region_containing(old);
3617 if (!r->evacuation_failed()) {
3618 r->set_evacuation_failed(true);
3619 if (G1PrintHeapRegions) {
3620 gclog_or_tty->print("overflow in heap region "PTR_FORMAT" "
3621 "["PTR_FORMAT","PTR_FORMAT")\n",
3622 r, r->bottom(), r->end());
3623 }
3624 }
3626 push_on_evac_failure_scan_stack(old);
3628 if (!_drain_in_progress) {
3629 // prevent recursion in copy_to_survivor_space()
3630 _drain_in_progress = true;
3631 drain_evac_failure_scan_stack();
3632 _drain_in_progress = false;
3633 }
3634 }
3636 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) {
3637 if (m != markOopDesc::prototype()) {
3638 if (_objs_with_preserved_marks == NULL) {
3639 assert(_preserved_marks_of_objs == NULL, "Both or none.");
3640 _objs_with_preserved_marks =
3641 new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true);
3642 _preserved_marks_of_objs =
3643 new (ResourceObj::C_HEAP) GrowableArray<markOop>(40, true);
3644 }
3645 _objs_with_preserved_marks->push(obj);
3646 _preserved_marks_of_objs->push(m);
3647 }
3648 }
3650 // *** Parallel G1 Evacuation
3652 HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose,
3653 size_t word_size) {
3654 assert(!isHumongous(word_size),
3655 err_msg("we should not be seeing humongous allocation requests "
3656 "during GC, word_size = "SIZE_FORMAT, word_size));
3658 HeapRegion* alloc_region = _gc_alloc_regions[purpose];
3659 // let the caller handle alloc failure
3660 if (alloc_region == NULL) return NULL;
3662 HeapWord* block = alloc_region->par_allocate(word_size);
3663 if (block == NULL) {
3664 MutexLockerEx x(par_alloc_during_gc_lock(),
3665 Mutex::_no_safepoint_check_flag);
3666 block = allocate_during_gc_slow(purpose, alloc_region, true, word_size);
3667 }
3668 return block;
3669 }
3671 void G1CollectedHeap::retire_alloc_region(HeapRegion* alloc_region,
3672 bool par) {
3673 // Another thread might have obtained alloc_region for the given
3674 // purpose, and might be attempting to allocate in it, and might
3675 // succeed. Therefore, we can't do the "finalization" stuff on the
3676 // region below until we're sure the last allocation has happened.
3677 // We ensure this by allocating the remaining space with a garbage
3678 // object.
3679 if (par) par_allocate_remaining_space(alloc_region);
3680 // Now we can do the post-GC stuff on the region.
3681 alloc_region->note_end_of_copying();
3682 g1_policy()->record_after_bytes(alloc_region->used());
3683 }
3685 HeapWord*
3686 G1CollectedHeap::allocate_during_gc_slow(GCAllocPurpose purpose,
3687 HeapRegion* alloc_region,
3688 bool par,
3689 size_t word_size) {
3690 assert(!isHumongous(word_size),
3691 err_msg("we should not be seeing humongous allocation requests "
3692 "during GC, word_size = "SIZE_FORMAT, word_size));
3694 HeapWord* block = NULL;
3695 // In the parallel case, a previous thread to obtain the lock may have
3696 // already assigned a new gc_alloc_region.
3697 if (alloc_region != _gc_alloc_regions[purpose]) {
3698 assert(par, "But should only happen in parallel case.");
3699 alloc_region = _gc_alloc_regions[purpose];
3700 if (alloc_region == NULL) return NULL;
3701 block = alloc_region->par_allocate(word_size);
3702 if (block != NULL) return block;
3703 // Otherwise, continue; this new region is empty, too.
3704 }
3705 assert(alloc_region != NULL, "We better have an allocation region");
3706 retire_alloc_region(alloc_region, par);
3708 if (_gc_alloc_region_counts[purpose] >= g1_policy()->max_regions(purpose)) {
3709 // Cannot allocate more regions for the given purpose.
3710 GCAllocPurpose alt_purpose = g1_policy()->alternative_purpose(purpose);
3711 // Is there an alternative?
3712 if (purpose != alt_purpose) {
3713 HeapRegion* alt_region = _gc_alloc_regions[alt_purpose];
3714 // Has not the alternative region been aliased?
3715 if (alloc_region != alt_region && alt_region != NULL) {
3716 // Try to allocate in the alternative region.
3717 if (par) {
3718 block = alt_region->par_allocate(word_size);
3719 } else {
3720 block = alt_region->allocate(word_size);
3721 }
3722 // Make an alias.
3723 _gc_alloc_regions[purpose] = _gc_alloc_regions[alt_purpose];
3724 if (block != NULL) {
3725 return block;
3726 }
3727 retire_alloc_region(alt_region, par);
3728 }
3729 // Both the allocation region and the alternative one are full
3730 // and aliased, replace them with a new allocation region.
3731 purpose = alt_purpose;
3732 } else {
3733 set_gc_alloc_region(purpose, NULL);
3734 return NULL;
3735 }
3736 }
3738 // Now allocate a new region for allocation.
3739 alloc_region = newAllocRegionWithExpansion(purpose, word_size, false /*zero_filled*/);
3741 // let the caller handle alloc failure
3742 if (alloc_region != NULL) {
3744 assert(check_gc_alloc_regions(), "alloc regions messed up");
3745 assert(alloc_region->saved_mark_at_top(),
3746 "Mark should have been saved already.");
3747 // We used to assert that the region was zero-filled here, but no
3748 // longer.
3750 // This must be done last: once it's installed, other regions may
3751 // allocate in it (without holding the lock.)
3752 set_gc_alloc_region(purpose, alloc_region);
3754 if (par) {
3755 block = alloc_region->par_allocate(word_size);
3756 } else {
3757 block = alloc_region->allocate(word_size);
3758 }
3759 // Caller handles alloc failure.
3760 } else {
3761 // This sets other apis using the same old alloc region to NULL, also.
3762 set_gc_alloc_region(purpose, NULL);
3763 }
3764 return block; // May be NULL.
3765 }
3767 void G1CollectedHeap::par_allocate_remaining_space(HeapRegion* r) {
3768 HeapWord* block = NULL;
3769 size_t free_words;
3770 do {
3771 free_words = r->free()/HeapWordSize;
3772 // If there's too little space, no one can allocate, so we're done.
3773 if (free_words < CollectedHeap::min_fill_size()) return;
3774 // Otherwise, try to claim it.
3775 block = r->par_allocate(free_words);
3776 } while (block == NULL);
3777 fill_with_object(block, free_words);
3778 }
3780 #ifndef PRODUCT
3781 bool GCLabBitMapClosure::do_bit(size_t offset) {
3782 HeapWord* addr = _bitmap->offsetToHeapWord(offset);
3783 guarantee(_cm->isMarked(oop(addr)), "it should be!");
3784 return true;
3785 }
3786 #endif // PRODUCT
3788 G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h, int queue_num)
3789 : _g1h(g1h),
3790 _refs(g1h->task_queue(queue_num)),
3791 _dcq(&g1h->dirty_card_queue_set()),
3792 _ct_bs((CardTableModRefBS*)_g1h->barrier_set()),
3793 _g1_rem(g1h->g1_rem_set()),
3794 _hash_seed(17), _queue_num(queue_num),
3795 _term_attempts(0),
3796 _surviving_alloc_buffer(g1h->desired_plab_sz(GCAllocForSurvived)),
3797 _tenured_alloc_buffer(g1h->desired_plab_sz(GCAllocForTenured)),
3798 _age_table(false),
3799 _strong_roots_time(0), _term_time(0),
3800 _alloc_buffer_waste(0), _undo_waste(0)
3801 {
3802 // we allocate G1YoungSurvRateNumRegions plus one entries, since
3803 // we "sacrifice" entry 0 to keep track of surviving bytes for
3804 // non-young regions (where the age is -1)
3805 // We also add a few elements at the beginning and at the end in
3806 // an attempt to eliminate cache contention
3807 size_t real_length = 1 + _g1h->g1_policy()->young_cset_length();
3808 size_t array_length = PADDING_ELEM_NUM +
3809 real_length +
3810 PADDING_ELEM_NUM;
3811 _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length);
3812 if (_surviving_young_words_base == NULL)
3813 vm_exit_out_of_memory(array_length * sizeof(size_t),
3814 "Not enough space for young surv histo.");
3815 _surviving_young_words = _surviving_young_words_base + PADDING_ELEM_NUM;
3816 memset(_surviving_young_words, 0, real_length * sizeof(size_t));
3818 _alloc_buffers[GCAllocForSurvived] = &_surviving_alloc_buffer;
3819 _alloc_buffers[GCAllocForTenured] = &_tenured_alloc_buffer;
3821 _start = os::elapsedTime();
3822 }
3824 void
3825 G1ParScanThreadState::print_termination_stats_hdr(outputStream* const st)
3826 {
3827 st->print_raw_cr("GC Termination Stats");
3828 st->print_raw_cr(" elapsed --strong roots-- -------termination-------"
3829 " ------waste (KiB)------");
3830 st->print_raw_cr("thr ms ms % ms % attempts"
3831 " total alloc undo");
3832 st->print_raw_cr("--- --------- --------- ------ --------- ------ --------"
3833 " ------- ------- -------");
3834 }
3836 void
3837 G1ParScanThreadState::print_termination_stats(int i,
3838 outputStream* const st) const
3839 {
3840 const double elapsed_ms = elapsed_time() * 1000.0;
3841 const double s_roots_ms = strong_roots_time() * 1000.0;
3842 const double term_ms = term_time() * 1000.0;
3843 st->print_cr("%3d %9.2f %9.2f %6.2f "
3844 "%9.2f %6.2f " SIZE_FORMAT_W(8) " "
3845 SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7),
3846 i, elapsed_ms, s_roots_ms, s_roots_ms * 100 / elapsed_ms,
3847 term_ms, term_ms * 100 / elapsed_ms, term_attempts(),
3848 (alloc_buffer_waste() + undo_waste()) * HeapWordSize / K,
3849 alloc_buffer_waste() * HeapWordSize / K,
3850 undo_waste() * HeapWordSize / K);
3851 }
3853 G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state) :
3854 _g1(g1), _g1_rem(_g1->g1_rem_set()), _cm(_g1->concurrent_mark()),
3855 _par_scan_state(par_scan_state) { }
3857 template <class T> void G1ParCopyHelper::mark_forwardee(T* p) {
3858 // This is called _after_ do_oop_work has been called, hence after
3859 // the object has been relocated to its new location and *p points
3860 // to its new location.
3862 T heap_oop = oopDesc::load_heap_oop(p);
3863 if (!oopDesc::is_null(heap_oop)) {
3864 oop obj = oopDesc::decode_heap_oop(heap_oop);
3865 assert((_g1->evacuation_failed()) || (!_g1->obj_in_cs(obj)),
3866 "shouldn't still be in the CSet if evacuation didn't fail.");
3867 HeapWord* addr = (HeapWord*)obj;
3868 if (_g1->is_in_g1_reserved(addr))
3869 _cm->grayRoot(oop(addr));
3870 }
3871 }
3873 oop G1ParCopyHelper::copy_to_survivor_space(oop old) {
3874 size_t word_sz = old->size();
3875 HeapRegion* from_region = _g1->heap_region_containing_raw(old);
3876 // +1 to make the -1 indexes valid...
3877 int young_index = from_region->young_index_in_cset()+1;
3878 assert( (from_region->is_young() && young_index > 0) ||
3879 (!from_region->is_young() && young_index == 0), "invariant" );
3880 G1CollectorPolicy* g1p = _g1->g1_policy();
3881 markOop m = old->mark();
3882 int age = m->has_displaced_mark_helper() ? m->displaced_mark_helper()->age()
3883 : m->age();
3884 GCAllocPurpose alloc_purpose = g1p->evacuation_destination(from_region, age,
3885 word_sz);
3886 HeapWord* obj_ptr = _par_scan_state->allocate(alloc_purpose, word_sz);
3887 oop obj = oop(obj_ptr);
3889 if (obj_ptr == NULL) {
3890 // This will either forward-to-self, or detect that someone else has
3891 // installed a forwarding pointer.
3892 OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure();
3893 return _g1->handle_evacuation_failure_par(cl, old);
3894 }
3896 // We're going to allocate linearly, so might as well prefetch ahead.
3897 Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
3899 oop forward_ptr = old->forward_to_atomic(obj);
3900 if (forward_ptr == NULL) {
3901 Copy::aligned_disjoint_words((HeapWord*) old, obj_ptr, word_sz);
3902 if (g1p->track_object_age(alloc_purpose)) {
3903 // We could simply do obj->incr_age(). However, this causes a
3904 // performance issue. obj->incr_age() will first check whether
3905 // the object has a displaced mark by checking its mark word;
3906 // getting the mark word from the new location of the object
3907 // stalls. So, given that we already have the mark word and we
3908 // are about to install it anyway, it's better to increase the
3909 // age on the mark word, when the object does not have a
3910 // displaced mark word. We're not expecting many objects to have
3911 // a displaced marked word, so that case is not optimized
3912 // further (it could be...) and we simply call obj->incr_age().
3914 if (m->has_displaced_mark_helper()) {
3915 // in this case, we have to install the mark word first,
3916 // otherwise obj looks to be forwarded (the old mark word,
3917 // which contains the forward pointer, was copied)
3918 obj->set_mark(m);
3919 obj->incr_age();
3920 } else {
3921 m = m->incr_age();
3922 obj->set_mark(m);
3923 }
3924 _par_scan_state->age_table()->add(obj, word_sz);
3925 } else {
3926 obj->set_mark(m);
3927 }
3929 // preserve "next" mark bit
3930 if (_g1->mark_in_progress() && !_g1->is_obj_ill(old)) {
3931 if (!use_local_bitmaps ||
3932 !_par_scan_state->alloc_buffer(alloc_purpose)->mark(obj_ptr)) {
3933 // if we couldn't mark it on the local bitmap (this happens when
3934 // the object was not allocated in the GCLab), we have to bite
3935 // the bullet and do the standard parallel mark
3936 _cm->markAndGrayObjectIfNecessary(obj);
3937 }
3938 #if 1
3939 if (_g1->isMarkedNext(old)) {
3940 _cm->nextMarkBitMap()->parClear((HeapWord*)old);
3941 }
3942 #endif
3943 }
3945 size_t* surv_young_words = _par_scan_state->surviving_young_words();
3946 surv_young_words[young_index] += word_sz;
3948 if (obj->is_objArray() && arrayOop(obj)->length() >= ParGCArrayScanChunk) {
3949 arrayOop(old)->set_length(0);
3950 oop* old_p = set_partial_array_mask(old);
3951 _par_scan_state->push_on_queue(old_p);
3952 } else {
3953 // No point in using the slower heap_region_containing() method,
3954 // given that we know obj is in the heap.
3955 _scanner->set_region(_g1->heap_region_containing_raw(obj));
3956 obj->oop_iterate_backwards(_scanner);
3957 }
3958 } else {
3959 _par_scan_state->undo_allocation(alloc_purpose, obj_ptr, word_sz);
3960 obj = forward_ptr;
3961 }
3962 return obj;
3963 }
3965 template <bool do_gen_barrier, G1Barrier barrier, bool do_mark_forwardee>
3966 template <class T>
3967 void G1ParCopyClosure <do_gen_barrier, barrier, do_mark_forwardee>
3968 ::do_oop_work(T* p) {
3969 oop obj = oopDesc::load_decode_heap_oop(p);
3970 assert(barrier != G1BarrierRS || obj != NULL,
3971 "Precondition: G1BarrierRS implies obj is nonNull");
3973 // here the null check is implicit in the cset_fast_test() test
3974 if (_g1->in_cset_fast_test(obj)) {
3975 #if G1_REM_SET_LOGGING
3976 gclog_or_tty->print_cr("Loc "PTR_FORMAT" contains pointer "PTR_FORMAT" "
3977 "into CS.", p, (void*) obj);
3978 #endif
3979 if (obj->is_forwarded()) {
3980 oopDesc::encode_store_heap_oop(p, obj->forwardee());
3981 } else {
3982 oop copy_oop = copy_to_survivor_space(obj);
3983 oopDesc::encode_store_heap_oop(p, copy_oop);
3984 }
3985 // When scanning the RS, we only care about objs in CS.
3986 if (barrier == G1BarrierRS) {
3987 _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num());
3988 }
3989 }
3991 if (barrier == G1BarrierEvac && obj != NULL) {
3992 _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num());
3993 }
3995 if (do_gen_barrier && obj != NULL) {
3996 par_do_barrier(p);
3997 }
3998 }
4000 template void G1ParCopyClosure<false, G1BarrierEvac, false>::do_oop_work(oop* p);
4001 template void G1ParCopyClosure<false, G1BarrierEvac, false>::do_oop_work(narrowOop* p);
4003 template <class T> void G1ParScanPartialArrayClosure::do_oop_nv(T* p) {
4004 assert(has_partial_array_mask(p), "invariant");
4005 oop old = clear_partial_array_mask(p);
4006 assert(old->is_objArray(), "must be obj array");
4007 assert(old->is_forwarded(), "must be forwarded");
4008 assert(Universe::heap()->is_in_reserved(old), "must be in heap.");
4010 objArrayOop obj = objArrayOop(old->forwardee());
4011 assert((void*)old != (void*)old->forwardee(), "self forwarding here?");
4012 // Process ParGCArrayScanChunk elements now
4013 // and push the remainder back onto queue
4014 int start = arrayOop(old)->length();
4015 int end = obj->length();
4016 int remainder = end - start;
4017 assert(start <= end, "just checking");
4018 if (remainder > 2 * ParGCArrayScanChunk) {
4019 // Test above combines last partial chunk with a full chunk
4020 end = start + ParGCArrayScanChunk;
4021 arrayOop(old)->set_length(end);
4022 // Push remainder.
4023 oop* old_p = set_partial_array_mask(old);
4024 assert(arrayOop(old)->length() < obj->length(), "Empty push?");
4025 _par_scan_state->push_on_queue(old_p);
4026 } else {
4027 // Restore length so that the heap remains parsable in
4028 // case of evacuation failure.
4029 arrayOop(old)->set_length(end);
4030 }
4031 _scanner.set_region(_g1->heap_region_containing_raw(obj));
4032 // process our set of indices (include header in first chunk)
4033 obj->oop_iterate_range(&_scanner, start, end);
4034 }
4036 class G1ParEvacuateFollowersClosure : public VoidClosure {
4037 protected:
4038 G1CollectedHeap* _g1h;
4039 G1ParScanThreadState* _par_scan_state;
4040 RefToScanQueueSet* _queues;
4041 ParallelTaskTerminator* _terminator;
4043 G1ParScanThreadState* par_scan_state() { return _par_scan_state; }
4044 RefToScanQueueSet* queues() { return _queues; }
4045 ParallelTaskTerminator* terminator() { return _terminator; }
4047 public:
4048 G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
4049 G1ParScanThreadState* par_scan_state,
4050 RefToScanQueueSet* queues,
4051 ParallelTaskTerminator* terminator)
4052 : _g1h(g1h), _par_scan_state(par_scan_state),
4053 _queues(queues), _terminator(terminator) {}
4055 void do_void() {
4056 G1ParScanThreadState* pss = par_scan_state();
4057 while (true) {
4058 pss->trim_queue();
4060 StarTask stolen_task;
4061 if (queues()->steal(pss->queue_num(), pss->hash_seed(), stolen_task)) {
4062 // slightly paranoid tests; I'm trying to catch potential
4063 // problems before we go into push_on_queue to know where the
4064 // problem is coming from
4065 assert((oop*)stolen_task != NULL, "Error");
4066 if (stolen_task.is_narrow()) {
4067 assert(UseCompressedOops, "Error");
4068 narrowOop* p = (narrowOop*) stolen_task;
4069 assert(has_partial_array_mask(p) ||
4070 _g1h->is_in_g1_reserved(oopDesc::load_decode_heap_oop(p)), "Error");
4071 pss->push_on_queue(p);
4072 } else {
4073 oop* p = (oop*) stolen_task;
4074 assert(has_partial_array_mask(p) || _g1h->is_in_g1_reserved(*p), "Error");
4075 pss->push_on_queue(p);
4076 }
4077 continue;
4078 }
4079 pss->start_term_time();
4080 if (terminator()->offer_termination()) break;
4081 pss->end_term_time();
4082 }
4083 pss->end_term_time();
4084 pss->retire_alloc_buffers();
4085 }
4086 };
4088 class G1ParTask : public AbstractGangTask {
4089 protected:
4090 G1CollectedHeap* _g1h;
4091 RefToScanQueueSet *_queues;
4092 ParallelTaskTerminator _terminator;
4093 int _n_workers;
4095 Mutex _stats_lock;
4096 Mutex* stats_lock() { return &_stats_lock; }
4098 size_t getNCards() {
4099 return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
4100 / G1BlockOffsetSharedArray::N_bytes;
4101 }
4103 public:
4104 G1ParTask(G1CollectedHeap* g1h, int workers, RefToScanQueueSet *task_queues)
4105 : AbstractGangTask("G1 collection"),
4106 _g1h(g1h),
4107 _queues(task_queues),
4108 _terminator(workers, _queues),
4109 _stats_lock(Mutex::leaf, "parallel G1 stats lock", true),
4110 _n_workers(workers)
4111 {}
4113 RefToScanQueueSet* queues() { return _queues; }
4115 RefToScanQueue *work_queue(int i) {
4116 return queues()->queue(i);
4117 }
4119 void work(int i) {
4120 if (i >= _n_workers) return; // no work needed this round
4122 double start_time_ms = os::elapsedTime() * 1000.0;
4123 _g1h->g1_policy()->record_gc_worker_start_time(i, start_time_ms);
4125 ResourceMark rm;
4126 HandleMark hm;
4128 G1ParScanThreadState pss(_g1h, i);
4129 G1ParScanHeapEvacClosure scan_evac_cl(_g1h, &pss);
4130 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss);
4131 G1ParScanPartialArrayClosure partial_scan_cl(_g1h, &pss);
4133 pss.set_evac_closure(&scan_evac_cl);
4134 pss.set_evac_failure_closure(&evac_failure_cl);
4135 pss.set_partial_scan_closure(&partial_scan_cl);
4137 G1ParScanExtRootClosure only_scan_root_cl(_g1h, &pss);
4138 G1ParScanPermClosure only_scan_perm_cl(_g1h, &pss);
4139 G1ParScanHeapRSClosure only_scan_heap_rs_cl(_g1h, &pss);
4140 G1ParPushHeapRSClosure push_heap_rs_cl(_g1h, &pss);
4142 G1ParScanAndMarkExtRootClosure scan_mark_root_cl(_g1h, &pss);
4143 G1ParScanAndMarkPermClosure scan_mark_perm_cl(_g1h, &pss);
4144 G1ParScanAndMarkHeapRSClosure scan_mark_heap_rs_cl(_g1h, &pss);
4146 OopsInHeapRegionClosure *scan_root_cl;
4147 OopsInHeapRegionClosure *scan_perm_cl;
4149 if (_g1h->g1_policy()->during_initial_mark_pause()) {
4150 scan_root_cl = &scan_mark_root_cl;
4151 scan_perm_cl = &scan_mark_perm_cl;
4152 } else {
4153 scan_root_cl = &only_scan_root_cl;
4154 scan_perm_cl = &only_scan_perm_cl;
4155 }
4157 pss.start_strong_roots();
4158 _g1h->g1_process_strong_roots(/* not collecting perm */ false,
4159 SharedHeap::SO_AllClasses,
4160 scan_root_cl,
4161 &push_heap_rs_cl,
4162 scan_perm_cl,
4163 i);
4164 pss.end_strong_roots();
4165 {
4166 double start = os::elapsedTime();
4167 G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);
4168 evac.do_void();
4169 double elapsed_ms = (os::elapsedTime()-start)*1000.0;
4170 double term_ms = pss.term_time()*1000.0;
4171 _g1h->g1_policy()->record_obj_copy_time(i, elapsed_ms-term_ms);
4172 _g1h->g1_policy()->record_termination(i, term_ms, pss.term_attempts());
4173 }
4174 _g1h->g1_policy()->record_thread_age_table(pss.age_table());
4175 _g1h->update_surviving_young_words(pss.surviving_young_words()+1);
4177 // Clean up any par-expanded rem sets.
4178 HeapRegionRemSet::par_cleanup();
4180 if (ParallelGCVerbose) {
4181 MutexLocker x(stats_lock());
4182 pss.print_termination_stats(i);
4183 }
4185 assert(pss.refs_to_scan() == 0, "Task queue should be empty");
4186 assert(pss.overflowed_refs_to_scan() == 0, "Overflow queue should be empty");
4187 double end_time_ms = os::elapsedTime() * 1000.0;
4188 _g1h->g1_policy()->record_gc_worker_end_time(i, end_time_ms);
4189 }
4190 };
4192 // *** Common G1 Evacuation Stuff
4194 // This method is run in a GC worker.
4196 void
4197 G1CollectedHeap::
4198 g1_process_strong_roots(bool collecting_perm_gen,
4199 SharedHeap::ScanningOption so,
4200 OopClosure* scan_non_heap_roots,
4201 OopsInHeapRegionClosure* scan_rs,
4202 OopsInGenClosure* scan_perm,
4203 int worker_i) {
4204 // First scan the strong roots, including the perm gen.
4205 double ext_roots_start = os::elapsedTime();
4206 double closure_app_time_sec = 0.0;
4208 BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots);
4209 BufferingOopsInGenClosure buf_scan_perm(scan_perm);
4210 buf_scan_perm.set_generation(perm_gen());
4212 // Walk the code cache w/o buffering, because StarTask cannot handle
4213 // unaligned oop locations.
4214 CodeBlobToOopClosure eager_scan_code_roots(scan_non_heap_roots, /*do_marking=*/ true);
4216 process_strong_roots(false, // no scoping; this is parallel code
4217 collecting_perm_gen, so,
4218 &buf_scan_non_heap_roots,
4219 &eager_scan_code_roots,
4220 &buf_scan_perm);
4222 // Finish up any enqueued closure apps.
4223 buf_scan_non_heap_roots.done();
4224 buf_scan_perm.done();
4225 double ext_roots_end = os::elapsedTime();
4226 g1_policy()->reset_obj_copy_time(worker_i);
4227 double obj_copy_time_sec =
4228 buf_scan_non_heap_roots.closure_app_seconds() +
4229 buf_scan_perm.closure_app_seconds();
4230 g1_policy()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0);
4231 double ext_root_time_ms =
4232 ((ext_roots_end - ext_roots_start) - obj_copy_time_sec) * 1000.0;
4233 g1_policy()->record_ext_root_scan_time(worker_i, ext_root_time_ms);
4235 // Scan strong roots in mark stack.
4236 if (!_process_strong_tasks->is_task_claimed(G1H_PS_mark_stack_oops_do)) {
4237 concurrent_mark()->oops_do(scan_non_heap_roots);
4238 }
4239 double mark_stack_scan_ms = (os::elapsedTime() - ext_roots_end) * 1000.0;
4240 g1_policy()->record_mark_stack_scan_time(worker_i, mark_stack_scan_ms);
4242 // XXX What should this be doing in the parallel case?
4243 g1_policy()->record_collection_pause_end_CH_strong_roots();
4244 // Now scan the complement of the collection set.
4245 if (scan_rs != NULL) {
4246 g1_rem_set()->oops_into_collection_set_do(scan_rs, worker_i);
4247 }
4248 // Finish with the ref_processor roots.
4249 if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) {
4250 ref_processor()->oops_do(scan_non_heap_roots);
4251 }
4252 g1_policy()->record_collection_pause_end_G1_strong_roots();
4253 _process_strong_tasks->all_tasks_completed();
4254 }
4256 void
4257 G1CollectedHeap::g1_process_weak_roots(OopClosure* root_closure,
4258 OopClosure* non_root_closure) {
4259 CodeBlobToOopClosure roots_in_blobs(root_closure, /*do_marking=*/ false);
4260 SharedHeap::process_weak_roots(root_closure, &roots_in_blobs, non_root_closure);
4261 }
4264 class SaveMarksClosure: public HeapRegionClosure {
4265 public:
4266 bool doHeapRegion(HeapRegion* r) {
4267 r->save_marks();
4268 return false;
4269 }
4270 };
4272 void G1CollectedHeap::save_marks() {
4273 if (!CollectedHeap::use_parallel_gc_threads()) {
4274 SaveMarksClosure sm;
4275 heap_region_iterate(&sm);
4276 }
4277 // We do this even in the parallel case
4278 perm_gen()->save_marks();
4279 }
4281 void G1CollectedHeap::evacuate_collection_set() {
4282 set_evacuation_failed(false);
4284 g1_rem_set()->prepare_for_oops_into_collection_set_do();
4285 concurrent_g1_refine()->set_use_cache(false);
4286 concurrent_g1_refine()->clear_hot_cache_claimed_index();
4288 int n_workers = (ParallelGCThreads > 0 ? workers()->total_workers() : 1);
4289 set_par_threads(n_workers);
4290 G1ParTask g1_par_task(this, n_workers, _task_queues);
4292 init_for_evac_failure(NULL);
4294 rem_set()->prepare_for_younger_refs_iterate(true);
4296 assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty");
4297 double start_par = os::elapsedTime();
4298 if (G1CollectedHeap::use_parallel_gc_threads()) {
4299 // The individual threads will set their evac-failure closures.
4300 StrongRootsScope srs(this);
4301 if (ParallelGCVerbose) G1ParScanThreadState::print_termination_stats_hdr();
4302 workers()->run_task(&g1_par_task);
4303 } else {
4304 StrongRootsScope srs(this);
4305 g1_par_task.work(0);
4306 }
4308 double par_time = (os::elapsedTime() - start_par) * 1000.0;
4309 g1_policy()->record_par_time(par_time);
4310 set_par_threads(0);
4311 // Is this the right thing to do here? We don't save marks
4312 // on individual heap regions when we allocate from
4313 // them in parallel, so this seems like the correct place for this.
4314 retire_all_alloc_regions();
4315 {
4316 G1IsAliveClosure is_alive(this);
4317 G1KeepAliveClosure keep_alive(this);
4318 JNIHandles::weak_oops_do(&is_alive, &keep_alive);
4319 }
4320 release_gc_alloc_regions(false /* totally */);
4321 g1_rem_set()->cleanup_after_oops_into_collection_set_do();
4323 concurrent_g1_refine()->clear_hot_cache();
4324 concurrent_g1_refine()->set_use_cache(true);
4326 finalize_for_evac_failure();
4328 // Must do this before removing self-forwarding pointers, which clears
4329 // the per-region evac-failure flags.
4330 concurrent_mark()->complete_marking_in_collection_set();
4332 if (evacuation_failed()) {
4333 remove_self_forwarding_pointers();
4334 if (PrintGCDetails) {
4335 gclog_or_tty->print(" (to-space overflow)");
4336 } else if (PrintGC) {
4337 gclog_or_tty->print("--");
4338 }
4339 }
4341 if (G1DeferredRSUpdate) {
4342 RedirtyLoggedCardTableEntryFastClosure redirty;
4343 dirty_card_queue_set().set_closure(&redirty);
4344 dirty_card_queue_set().apply_closure_to_all_completed_buffers();
4346 DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set();
4347 dcq.merge_bufferlists(&dirty_card_queue_set());
4348 assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
4349 }
4350 COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
4351 }
4353 void G1CollectedHeap::free_region(HeapRegion* hr) {
4354 size_t pre_used = 0;
4355 size_t cleared_h_regions = 0;
4356 size_t freed_regions = 0;
4357 UncleanRegionList local_list;
4359 HeapWord* start = hr->bottom();
4360 HeapWord* end = hr->prev_top_at_mark_start();
4361 size_t used_bytes = hr->used();
4362 size_t live_bytes = hr->max_live_bytes();
4363 if (used_bytes > 0) {
4364 guarantee( live_bytes <= used_bytes, "invariant" );
4365 } else {
4366 guarantee( live_bytes == 0, "invariant" );
4367 }
4369 size_t garbage_bytes = used_bytes - live_bytes;
4370 if (garbage_bytes > 0)
4371 g1_policy()->decrease_known_garbage_bytes(garbage_bytes);
4373 free_region_work(hr, pre_used, cleared_h_regions, freed_regions,
4374 &local_list);
4375 finish_free_region_work(pre_used, cleared_h_regions, freed_regions,
4376 &local_list);
4377 }
4379 void
4380 G1CollectedHeap::free_region_work(HeapRegion* hr,
4381 size_t& pre_used,
4382 size_t& cleared_h_regions,
4383 size_t& freed_regions,
4384 UncleanRegionList* list,
4385 bool par) {
4386 pre_used += hr->used();
4387 if (hr->isHumongous()) {
4388 assert(hr->startsHumongous(),
4389 "Only the start of a humongous region should be freed.");
4390 int ind = _hrs->find(hr);
4391 assert(ind != -1, "Should have an index.");
4392 // Clear the start region.
4393 hr->hr_clear(par, true /*clear_space*/);
4394 list->insert_before_head(hr);
4395 cleared_h_regions++;
4396 freed_regions++;
4397 // Clear any continued regions.
4398 ind++;
4399 while ((size_t)ind < n_regions()) {
4400 HeapRegion* hrc = _hrs->at(ind);
4401 if (!hrc->continuesHumongous()) break;
4402 // Otherwise, does continue the H region.
4403 assert(hrc->humongous_start_region() == hr, "Huh?");
4404 hrc->hr_clear(par, true /*clear_space*/);
4405 cleared_h_regions++;
4406 freed_regions++;
4407 list->insert_before_head(hrc);
4408 ind++;
4409 }
4410 } else {
4411 hr->hr_clear(par, true /*clear_space*/);
4412 list->insert_before_head(hr);
4413 freed_regions++;
4414 // If we're using clear2, this should not be enabled.
4415 // assert(!hr->in_cohort(), "Can't be both free and in a cohort.");
4416 }
4417 }
4419 void G1CollectedHeap::finish_free_region_work(size_t pre_used,
4420 size_t cleared_h_regions,
4421 size_t freed_regions,
4422 UncleanRegionList* list) {
4423 if (list != NULL && list->sz() > 0) {
4424 prepend_region_list_on_unclean_list(list);
4425 }
4426 // Acquire a lock, if we're parallel, to update possibly-shared
4427 // variables.
4428 Mutex* lock = (n_par_threads() > 0) ? ParGCRareEvent_lock : NULL;
4429 {
4430 MutexLockerEx x(lock, Mutex::_no_safepoint_check_flag);
4431 _summary_bytes_used -= pre_used;
4432 _num_humongous_regions -= (int) cleared_h_regions;
4433 _free_regions += freed_regions;
4434 }
4435 }
4438 void G1CollectedHeap::dirtyCardsForYoungRegions(CardTableModRefBS* ct_bs, HeapRegion* list) {
4439 while (list != NULL) {
4440 guarantee( list->is_young(), "invariant" );
4442 HeapWord* bottom = list->bottom();
4443 HeapWord* end = list->end();
4444 MemRegion mr(bottom, end);
4445 ct_bs->dirty(mr);
4447 list = list->get_next_young_region();
4448 }
4449 }
4452 class G1ParCleanupCTTask : public AbstractGangTask {
4453 CardTableModRefBS* _ct_bs;
4454 G1CollectedHeap* _g1h;
4455 HeapRegion* volatile _su_head;
4456 public:
4457 G1ParCleanupCTTask(CardTableModRefBS* ct_bs,
4458 G1CollectedHeap* g1h,
4459 HeapRegion* survivor_list) :
4460 AbstractGangTask("G1 Par Cleanup CT Task"),
4461 _ct_bs(ct_bs),
4462 _g1h(g1h),
4463 _su_head(survivor_list)
4464 { }
4466 void work(int i) {
4467 HeapRegion* r;
4468 while (r = _g1h->pop_dirty_cards_region()) {
4469 clear_cards(r);
4470 }
4471 // Redirty the cards of the survivor regions.
4472 dirty_list(&this->_su_head);
4473 }
4475 void clear_cards(HeapRegion* r) {
4476 // Cards for Survivor regions will be dirtied later.
4477 if (!r->is_survivor()) {
4478 _ct_bs->clear(MemRegion(r->bottom(), r->end()));
4479 }
4480 }
4482 void dirty_list(HeapRegion* volatile * head_ptr) {
4483 HeapRegion* head;
4484 do {
4485 // Pop region off the list.
4486 head = *head_ptr;
4487 if (head != NULL) {
4488 HeapRegion* r = (HeapRegion*)
4489 Atomic::cmpxchg_ptr(head->get_next_young_region(), head_ptr, head);
4490 if (r == head) {
4491 assert(!r->isHumongous(), "Humongous regions shouldn't be on survivor list");
4492 _ct_bs->dirty(MemRegion(r->bottom(), r->end()));
4493 }
4494 }
4495 } while (*head_ptr != NULL);
4496 }
4497 };
4500 #ifndef PRODUCT
4501 class G1VerifyCardTableCleanup: public HeapRegionClosure {
4502 CardTableModRefBS* _ct_bs;
4503 public:
4504 G1VerifyCardTableCleanup(CardTableModRefBS* ct_bs)
4505 : _ct_bs(ct_bs)
4506 { }
4507 virtual bool doHeapRegion(HeapRegion* r)
4508 {
4509 MemRegion mr(r->bottom(), r->end());
4510 if (r->is_survivor()) {
4511 _ct_bs->verify_dirty_region(mr);
4512 } else {
4513 _ct_bs->verify_clean_region(mr);
4514 }
4515 return false;
4516 }
4517 };
4518 #endif
4520 void G1CollectedHeap::cleanUpCardTable() {
4521 CardTableModRefBS* ct_bs = (CardTableModRefBS*) (barrier_set());
4522 double start = os::elapsedTime();
4524 // Iterate over the dirty cards region list.
4525 G1ParCleanupCTTask cleanup_task(ct_bs, this,
4526 _young_list->first_survivor_region());
4528 if (ParallelGCThreads > 0) {
4529 set_par_threads(workers()->total_workers());
4530 workers()->run_task(&cleanup_task);
4531 set_par_threads(0);
4532 } else {
4533 while (_dirty_cards_region_list) {
4534 HeapRegion* r = _dirty_cards_region_list;
4535 cleanup_task.clear_cards(r);
4536 _dirty_cards_region_list = r->get_next_dirty_cards_region();
4537 if (_dirty_cards_region_list == r) {
4538 // The last region.
4539 _dirty_cards_region_list = NULL;
4540 }
4541 r->set_next_dirty_cards_region(NULL);
4542 }
4543 // now, redirty the cards of the survivor regions
4544 // (it seemed faster to do it this way, instead of iterating over
4545 // all regions and then clearing / dirtying as appropriate)
4546 dirtyCardsForYoungRegions(ct_bs, _young_list->first_survivor_region());
4547 }
4549 double elapsed = os::elapsedTime() - start;
4550 g1_policy()->record_clear_ct_time( elapsed * 1000.0);
4551 #ifndef PRODUCT
4552 if (G1VerifyCTCleanup || VerifyAfterGC) {
4553 G1VerifyCardTableCleanup cleanup_verifier(ct_bs);
4554 heap_region_iterate(&cleanup_verifier);
4555 }
4556 #endif
4557 }
4559 void G1CollectedHeap::do_collection_pause_if_appropriate(size_t word_size) {
4560 if (g1_policy()->should_do_collection_pause(word_size)) {
4561 do_collection_pause();
4562 }
4563 }
4565 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head) {
4566 double young_time_ms = 0.0;
4567 double non_young_time_ms = 0.0;
4569 // Since the collection set is a superset of the the young list,
4570 // all we need to do to clear the young list is clear its
4571 // head and length, and unlink any young regions in the code below
4572 _young_list->clear();
4574 G1CollectorPolicy* policy = g1_policy();
4576 double start_sec = os::elapsedTime();
4577 bool non_young = true;
4579 HeapRegion* cur = cs_head;
4580 int age_bound = -1;
4581 size_t rs_lengths = 0;
4583 while (cur != NULL) {
4584 if (non_young) {
4585 if (cur->is_young()) {
4586 double end_sec = os::elapsedTime();
4587 double elapsed_ms = (end_sec - start_sec) * 1000.0;
4588 non_young_time_ms += elapsed_ms;
4590 start_sec = os::elapsedTime();
4591 non_young = false;
4592 }
4593 } else {
4594 if (!cur->is_on_free_list()) {
4595 double end_sec = os::elapsedTime();
4596 double elapsed_ms = (end_sec - start_sec) * 1000.0;
4597 young_time_ms += elapsed_ms;
4599 start_sec = os::elapsedTime();
4600 non_young = true;
4601 }
4602 }
4604 rs_lengths += cur->rem_set()->occupied();
4606 HeapRegion* next = cur->next_in_collection_set();
4607 assert(cur->in_collection_set(), "bad CS");
4608 cur->set_next_in_collection_set(NULL);
4609 cur->set_in_collection_set(false);
4611 if (cur->is_young()) {
4612 int index = cur->young_index_in_cset();
4613 guarantee( index != -1, "invariant" );
4614 guarantee( (size_t)index < policy->young_cset_length(), "invariant" );
4615 size_t words_survived = _surviving_young_words[index];
4616 cur->record_surv_words_in_group(words_survived);
4618 // At this point the we have 'popped' cur from the collection set
4619 // (linked via next_in_collection_set()) but it is still in the
4620 // young list (linked via next_young_region()). Clear the
4621 // _next_young_region field.
4622 cur->set_next_young_region(NULL);
4623 } else {
4624 int index = cur->young_index_in_cset();
4625 guarantee( index == -1, "invariant" );
4626 }
4628 assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||
4629 (!cur->is_young() && cur->young_index_in_cset() == -1),
4630 "invariant" );
4632 if (!cur->evacuation_failed()) {
4633 // And the region is empty.
4634 assert(!cur->is_empty(),
4635 "Should not have empty regions in a CS.");
4636 free_region(cur);
4637 } else {
4638 cur->uninstall_surv_rate_group();
4639 if (cur->is_young())
4640 cur->set_young_index_in_cset(-1);
4641 cur->set_not_young();
4642 cur->set_evacuation_failed(false);
4643 }
4644 cur = next;
4645 }
4647 policy->record_max_rs_lengths(rs_lengths);
4648 policy->cset_regions_freed();
4650 double end_sec = os::elapsedTime();
4651 double elapsed_ms = (end_sec - start_sec) * 1000.0;
4652 if (non_young)
4653 non_young_time_ms += elapsed_ms;
4654 else
4655 young_time_ms += elapsed_ms;
4657 policy->record_young_free_cset_time_ms(young_time_ms);
4658 policy->record_non_young_free_cset_time_ms(non_young_time_ms);
4659 }
4661 // This routine is similar to the above but does not record
4662 // any policy statistics or update free lists; we are abandoning
4663 // the current incremental collection set in preparation of a
4664 // full collection. After the full GC we will start to build up
4665 // the incremental collection set again.
4666 // This is only called when we're doing a full collection
4667 // and is immediately followed by the tearing down of the young list.
4669 void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) {
4670 HeapRegion* cur = cs_head;
4672 while (cur != NULL) {
4673 HeapRegion* next = cur->next_in_collection_set();
4674 assert(cur->in_collection_set(), "bad CS");
4675 cur->set_next_in_collection_set(NULL);
4676 cur->set_in_collection_set(false);
4677 cur->set_young_index_in_cset(-1);
4678 cur = next;
4679 }
4680 }
4682 HeapRegion*
4683 G1CollectedHeap::alloc_region_from_unclean_list_locked(bool zero_filled) {
4684 assert(ZF_mon->owned_by_self(), "Precondition");
4685 HeapRegion* res = pop_unclean_region_list_locked();
4686 if (res != NULL) {
4687 assert(!res->continuesHumongous() &&
4688 res->zero_fill_state() != HeapRegion::Allocated,
4689 "Only free regions on unclean list.");
4690 if (zero_filled) {
4691 res->ensure_zero_filled_locked();
4692 res->set_zero_fill_allocated();
4693 }
4694 }
4695 return res;
4696 }
4698 HeapRegion* G1CollectedHeap::alloc_region_from_unclean_list(bool zero_filled) {
4699 MutexLockerEx zx(ZF_mon, Mutex::_no_safepoint_check_flag);
4700 return alloc_region_from_unclean_list_locked(zero_filled);
4701 }
4703 void G1CollectedHeap::put_region_on_unclean_list(HeapRegion* r) {
4704 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4705 put_region_on_unclean_list_locked(r);
4706 if (should_zf()) ZF_mon->notify_all(); // Wake up ZF thread.
4707 }
4709 void G1CollectedHeap::set_unclean_regions_coming(bool b) {
4710 MutexLockerEx x(Cleanup_mon);
4711 set_unclean_regions_coming_locked(b);
4712 }
4714 void G1CollectedHeap::set_unclean_regions_coming_locked(bool b) {
4715 assert(Cleanup_mon->owned_by_self(), "Precondition");
4716 _unclean_regions_coming = b;
4717 // Wake up mutator threads that might be waiting for completeCleanup to
4718 // finish.
4719 if (!b) Cleanup_mon->notify_all();
4720 }
4722 void G1CollectedHeap::wait_for_cleanup_complete() {
4723 MutexLockerEx x(Cleanup_mon);
4724 wait_for_cleanup_complete_locked();
4725 }
4727 void G1CollectedHeap::wait_for_cleanup_complete_locked() {
4728 assert(Cleanup_mon->owned_by_self(), "precondition");
4729 while (_unclean_regions_coming) {
4730 Cleanup_mon->wait();
4731 }
4732 }
4734 void
4735 G1CollectedHeap::put_region_on_unclean_list_locked(HeapRegion* r) {
4736 assert(ZF_mon->owned_by_self(), "precondition.");
4737 #ifdef ASSERT
4738 if (r->is_gc_alloc_region()) {
4739 ResourceMark rm;
4740 stringStream region_str;
4741 print_on(®ion_str);
4742 assert(!r->is_gc_alloc_region(), err_msg("Unexpected GC allocation region: %s",
4743 region_str.as_string()));
4744 }
4745 #endif
4746 _unclean_region_list.insert_before_head(r);
4747 }
4749 void
4750 G1CollectedHeap::prepend_region_list_on_unclean_list(UncleanRegionList* list) {
4751 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4752 prepend_region_list_on_unclean_list_locked(list);
4753 if (should_zf()) ZF_mon->notify_all(); // Wake up ZF thread.
4754 }
4756 void
4757 G1CollectedHeap::
4758 prepend_region_list_on_unclean_list_locked(UncleanRegionList* list) {
4759 assert(ZF_mon->owned_by_self(), "precondition.");
4760 _unclean_region_list.prepend_list(list);
4761 }
4763 HeapRegion* G1CollectedHeap::pop_unclean_region_list_locked() {
4764 assert(ZF_mon->owned_by_self(), "precondition.");
4765 HeapRegion* res = _unclean_region_list.pop();
4766 if (res != NULL) {
4767 // Inform ZF thread that there's a new unclean head.
4768 if (_unclean_region_list.hd() != NULL && should_zf())
4769 ZF_mon->notify_all();
4770 }
4771 return res;
4772 }
4774 HeapRegion* G1CollectedHeap::peek_unclean_region_list_locked() {
4775 assert(ZF_mon->owned_by_self(), "precondition.");
4776 return _unclean_region_list.hd();
4777 }
4780 bool G1CollectedHeap::move_cleaned_region_to_free_list_locked() {
4781 assert(ZF_mon->owned_by_self(), "Precondition");
4782 HeapRegion* r = peek_unclean_region_list_locked();
4783 if (r != NULL && r->zero_fill_state() == HeapRegion::ZeroFilled) {
4784 // Result of below must be equal to "r", since we hold the lock.
4785 (void)pop_unclean_region_list_locked();
4786 put_free_region_on_list_locked(r);
4787 return true;
4788 } else {
4789 return false;
4790 }
4791 }
4793 bool G1CollectedHeap::move_cleaned_region_to_free_list() {
4794 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4795 return move_cleaned_region_to_free_list_locked();
4796 }
4799 void G1CollectedHeap::put_free_region_on_list_locked(HeapRegion* r) {
4800 assert(ZF_mon->owned_by_self(), "precondition.");
4801 assert(_free_region_list_size == free_region_list_length(), "Inv");
4802 assert(r->zero_fill_state() == HeapRegion::ZeroFilled,
4803 "Regions on free list must be zero filled");
4804 assert(!r->isHumongous(), "Must not be humongous.");
4805 assert(r->is_empty(), "Better be empty");
4806 assert(!r->is_on_free_list(),
4807 "Better not already be on free list");
4808 assert(!r->is_on_unclean_list(),
4809 "Better not already be on unclean list");
4810 r->set_on_free_list(true);
4811 r->set_next_on_free_list(_free_region_list);
4812 _free_region_list = r;
4813 _free_region_list_size++;
4814 assert(_free_region_list_size == free_region_list_length(), "Inv");
4815 }
4817 void G1CollectedHeap::put_free_region_on_list(HeapRegion* r) {
4818 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4819 put_free_region_on_list_locked(r);
4820 }
4822 HeapRegion* G1CollectedHeap::pop_free_region_list_locked() {
4823 assert(ZF_mon->owned_by_self(), "precondition.");
4824 assert(_free_region_list_size == free_region_list_length(), "Inv");
4825 HeapRegion* res = _free_region_list;
4826 if (res != NULL) {
4827 _free_region_list = res->next_from_free_list();
4828 _free_region_list_size--;
4829 res->set_on_free_list(false);
4830 res->set_next_on_free_list(NULL);
4831 assert(_free_region_list_size == free_region_list_length(), "Inv");
4832 }
4833 return res;
4834 }
4837 HeapRegion* G1CollectedHeap::alloc_free_region_from_lists(bool zero_filled) {
4838 // By self, or on behalf of self.
4839 assert(Heap_lock->is_locked(), "Precondition");
4840 HeapRegion* res = NULL;
4841 bool first = true;
4842 while (res == NULL) {
4843 if (zero_filled || !first) {
4844 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4845 res = pop_free_region_list_locked();
4846 if (res != NULL) {
4847 assert(!res->zero_fill_is_allocated(),
4848 "No allocated regions on free list.");
4849 res->set_zero_fill_allocated();
4850 } else if (!first) {
4851 break; // We tried both, time to return NULL.
4852 }
4853 }
4855 if (res == NULL) {
4856 res = alloc_region_from_unclean_list(zero_filled);
4857 }
4858 assert(res == NULL ||
4859 !zero_filled ||
4860 res->zero_fill_is_allocated(),
4861 "We must have allocated the region we're returning");
4862 first = false;
4863 }
4864 return res;
4865 }
4867 void G1CollectedHeap::remove_allocated_regions_from_lists() {
4868 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4869 {
4870 HeapRegion* prev = NULL;
4871 HeapRegion* cur = _unclean_region_list.hd();
4872 while (cur != NULL) {
4873 HeapRegion* next = cur->next_from_unclean_list();
4874 if (cur->zero_fill_is_allocated()) {
4875 // Remove from the list.
4876 if (prev == NULL) {
4877 (void)_unclean_region_list.pop();
4878 } else {
4879 _unclean_region_list.delete_after(prev);
4880 }
4881 cur->set_on_unclean_list(false);
4882 cur->set_next_on_unclean_list(NULL);
4883 } else {
4884 prev = cur;
4885 }
4886 cur = next;
4887 }
4888 assert(_unclean_region_list.sz() == unclean_region_list_length(),
4889 "Inv");
4890 }
4892 {
4893 HeapRegion* prev = NULL;
4894 HeapRegion* cur = _free_region_list;
4895 while (cur != NULL) {
4896 HeapRegion* next = cur->next_from_free_list();
4897 if (cur->zero_fill_is_allocated()) {
4898 // Remove from the list.
4899 if (prev == NULL) {
4900 _free_region_list = cur->next_from_free_list();
4901 } else {
4902 prev->set_next_on_free_list(cur->next_from_free_list());
4903 }
4904 cur->set_on_free_list(false);
4905 cur->set_next_on_free_list(NULL);
4906 _free_region_list_size--;
4907 } else {
4908 prev = cur;
4909 }
4910 cur = next;
4911 }
4912 assert(_free_region_list_size == free_region_list_length(), "Inv");
4913 }
4914 }
4916 bool G1CollectedHeap::verify_region_lists() {
4917 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4918 return verify_region_lists_locked();
4919 }
4921 bool G1CollectedHeap::verify_region_lists_locked() {
4922 HeapRegion* unclean = _unclean_region_list.hd();
4923 while (unclean != NULL) {
4924 guarantee(unclean->is_on_unclean_list(), "Well, it is!");
4925 guarantee(!unclean->is_on_free_list(), "Well, it shouldn't be!");
4926 guarantee(unclean->zero_fill_state() != HeapRegion::Allocated,
4927 "Everything else is possible.");
4928 unclean = unclean->next_from_unclean_list();
4929 }
4930 guarantee(_unclean_region_list.sz() == unclean_region_list_length(), "Inv");
4932 HeapRegion* free_r = _free_region_list;
4933 while (free_r != NULL) {
4934 assert(free_r->is_on_free_list(), "Well, it is!");
4935 assert(!free_r->is_on_unclean_list(), "Well, it shouldn't be!");
4936 switch (free_r->zero_fill_state()) {
4937 case HeapRegion::NotZeroFilled:
4938 case HeapRegion::ZeroFilling:
4939 guarantee(false, "Should not be on free list.");
4940 break;
4941 default:
4942 // Everything else is possible.
4943 break;
4944 }
4945 free_r = free_r->next_from_free_list();
4946 }
4947 guarantee(_free_region_list_size == free_region_list_length(), "Inv");
4948 // If we didn't do an assertion...
4949 return true;
4950 }
4952 size_t G1CollectedHeap::free_region_list_length() {
4953 assert(ZF_mon->owned_by_self(), "precondition.");
4954 size_t len = 0;
4955 HeapRegion* cur = _free_region_list;
4956 while (cur != NULL) {
4957 len++;
4958 cur = cur->next_from_free_list();
4959 }
4960 return len;
4961 }
4963 size_t G1CollectedHeap::unclean_region_list_length() {
4964 assert(ZF_mon->owned_by_self(), "precondition.");
4965 return _unclean_region_list.length();
4966 }
4968 size_t G1CollectedHeap::n_regions() {
4969 return _hrs->length();
4970 }
4972 size_t G1CollectedHeap::max_regions() {
4973 return
4974 (size_t)align_size_up(g1_reserved_obj_bytes(), HeapRegion::GrainBytes) /
4975 HeapRegion::GrainBytes;
4976 }
4978 size_t G1CollectedHeap::free_regions() {
4979 /* Possibly-expensive assert.
4980 assert(_free_regions == count_free_regions(),
4981 "_free_regions is off.");
4982 */
4983 return _free_regions;
4984 }
4986 bool G1CollectedHeap::should_zf() {
4987 return _free_region_list_size < (size_t) G1ConcZFMaxRegions;
4988 }
4990 class RegionCounter: public HeapRegionClosure {
4991 size_t _n;
4992 public:
4993 RegionCounter() : _n(0) {}
4994 bool doHeapRegion(HeapRegion* r) {
4995 if (r->is_empty()) {
4996 assert(!r->isHumongous(), "H regions should not be empty.");
4997 _n++;
4998 }
4999 return false;
5000 }
5001 int res() { return (int) _n; }
5002 };
5004 size_t G1CollectedHeap::count_free_regions() {
5005 RegionCounter rc;
5006 heap_region_iterate(&rc);
5007 size_t n = rc.res();
5008 if (_cur_alloc_region != NULL && _cur_alloc_region->is_empty())
5009 n--;
5010 return n;
5011 }
5013 size_t G1CollectedHeap::count_free_regions_list() {
5014 size_t n = 0;
5015 size_t o = 0;
5016 ZF_mon->lock_without_safepoint_check();
5017 HeapRegion* cur = _free_region_list;
5018 while (cur != NULL) {
5019 cur = cur->next_from_free_list();
5020 n++;
5021 }
5022 size_t m = unclean_region_list_length();
5023 ZF_mon->unlock();
5024 return n + m;
5025 }
5027 bool G1CollectedHeap::should_set_young_locked() {
5028 assert(heap_lock_held_for_gc(),
5029 "the heap lock should already be held by or for this thread");
5030 return (g1_policy()->in_young_gc_mode() &&
5031 g1_policy()->should_add_next_region_to_young_list());
5032 }
5034 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
5035 assert(heap_lock_held_for_gc(),
5036 "the heap lock should already be held by or for this thread");
5037 _young_list->push_region(hr);
5038 g1_policy()->set_region_short_lived(hr);
5039 }
5041 class NoYoungRegionsClosure: public HeapRegionClosure {
5042 private:
5043 bool _success;
5044 public:
5045 NoYoungRegionsClosure() : _success(true) { }
5046 bool doHeapRegion(HeapRegion* r) {
5047 if (r->is_young()) {
5048 gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young",
5049 r->bottom(), r->end());
5050 _success = false;
5051 }
5052 return false;
5053 }
5054 bool success() { return _success; }
5055 };
5057 bool G1CollectedHeap::check_young_list_empty(bool check_heap, bool check_sample) {
5058 bool ret = _young_list->check_list_empty(check_sample);
5060 if (check_heap) {
5061 NoYoungRegionsClosure closure;
5062 heap_region_iterate(&closure);
5063 ret = ret && closure.success();
5064 }
5066 return ret;
5067 }
5069 void G1CollectedHeap::empty_young_list() {
5070 assert(heap_lock_held_for_gc(),
5071 "the heap lock should already be held by or for this thread");
5072 assert(g1_policy()->in_young_gc_mode(), "should be in young GC mode");
5074 _young_list->empty_list();
5075 }
5077 bool G1CollectedHeap::all_alloc_regions_no_allocs_since_save_marks() {
5078 bool no_allocs = true;
5079 for (int ap = 0; ap < GCAllocPurposeCount && no_allocs; ++ap) {
5080 HeapRegion* r = _gc_alloc_regions[ap];
5081 no_allocs = r == NULL || r->saved_mark_at_top();
5082 }
5083 return no_allocs;
5084 }
5086 void G1CollectedHeap::retire_all_alloc_regions() {
5087 for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
5088 HeapRegion* r = _gc_alloc_regions[ap];
5089 if (r != NULL) {
5090 // Check for aliases.
5091 bool has_processed_alias = false;
5092 for (int i = 0; i < ap; ++i) {
5093 if (_gc_alloc_regions[i] == r) {
5094 has_processed_alias = true;
5095 break;
5096 }
5097 }
5098 if (!has_processed_alias) {
5099 retire_alloc_region(r, false /* par */);
5100 }
5101 }
5102 }
5103 }
5106 // Done at the start of full GC.
5107 void G1CollectedHeap::tear_down_region_lists() {
5108 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
5109 while (pop_unclean_region_list_locked() != NULL) ;
5110 assert(_unclean_region_list.hd() == NULL && _unclean_region_list.sz() == 0,
5111 "Postconditions of loop.");
5112 while (pop_free_region_list_locked() != NULL) ;
5113 assert(_free_region_list == NULL, "Postcondition of loop.");
5114 if (_free_region_list_size != 0) {
5115 gclog_or_tty->print_cr("Size is %d.", _free_region_list_size);
5116 print_on(gclog_or_tty, true /* extended */);
5117 }
5118 assert(_free_region_list_size == 0, "Postconditions of loop.");
5119 }
5122 class RegionResetter: public HeapRegionClosure {
5123 G1CollectedHeap* _g1;
5124 int _n;
5125 public:
5126 RegionResetter() : _g1(G1CollectedHeap::heap()), _n(0) {}
5127 bool doHeapRegion(HeapRegion* r) {
5128 if (r->continuesHumongous()) return false;
5129 if (r->top() > r->bottom()) {
5130 if (r->top() < r->end()) {
5131 Copy::fill_to_words(r->top(),
5132 pointer_delta(r->end(), r->top()));
5133 }
5134 r->set_zero_fill_allocated();
5135 } else {
5136 assert(r->is_empty(), "tautology");
5137 _n++;
5138 switch (r->zero_fill_state()) {
5139 case HeapRegion::NotZeroFilled:
5140 case HeapRegion::ZeroFilling:
5141 _g1->put_region_on_unclean_list_locked(r);
5142 break;
5143 case HeapRegion::Allocated:
5144 r->set_zero_fill_complete();
5145 // no break; go on to put on free list.
5146 case HeapRegion::ZeroFilled:
5147 _g1->put_free_region_on_list_locked(r);
5148 break;
5149 }
5150 }
5151 return false;
5152 }
5154 int getFreeRegionCount() {return _n;}
5155 };
5157 // Done at the end of full GC.
5158 void G1CollectedHeap::rebuild_region_lists() {
5159 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
5160 // This needs to go at the end of the full GC.
5161 RegionResetter rs;
5162 heap_region_iterate(&rs);
5163 _free_regions = rs.getFreeRegionCount();
5164 // Tell the ZF thread it may have work to do.
5165 if (should_zf()) ZF_mon->notify_all();
5166 }
5168 class UsedRegionsNeedZeroFillSetter: public HeapRegionClosure {
5169 G1CollectedHeap* _g1;
5170 int _n;
5171 public:
5172 UsedRegionsNeedZeroFillSetter() : _g1(G1CollectedHeap::heap()), _n(0) {}
5173 bool doHeapRegion(HeapRegion* r) {
5174 if (r->continuesHumongous()) return false;
5175 if (r->top() > r->bottom()) {
5176 // There are assertions in "set_zero_fill_needed()" below that
5177 // require top() == bottom(), so this is technically illegal.
5178 // We'll skirt the law here, by making that true temporarily.
5179 DEBUG_ONLY(HeapWord* save_top = r->top();
5180 r->set_top(r->bottom()));
5181 r->set_zero_fill_needed();
5182 DEBUG_ONLY(r->set_top(save_top));
5183 }
5184 return false;
5185 }
5186 };
5188 // Done at the start of full GC.
5189 void G1CollectedHeap::set_used_regions_to_need_zero_fill() {
5190 MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
5191 // This needs to go at the end of the full GC.
5192 UsedRegionsNeedZeroFillSetter rs;
5193 heap_region_iterate(&rs);
5194 }
5196 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
5197 _refine_cte_cl->set_concurrent(concurrent);
5198 }
5200 #ifndef PRODUCT
5202 class PrintHeapRegionClosure: public HeapRegionClosure {
5203 public:
5204 bool doHeapRegion(HeapRegion *r) {
5205 gclog_or_tty->print("Region: "PTR_FORMAT":", r);
5206 if (r != NULL) {
5207 if (r->is_on_free_list())
5208 gclog_or_tty->print("Free ");
5209 if (r->is_young())
5210 gclog_or_tty->print("Young ");
5211 if (r->isHumongous())
5212 gclog_or_tty->print("Is Humongous ");
5213 r->print();
5214 }
5215 return false;
5216 }
5217 };
5219 class SortHeapRegionClosure : public HeapRegionClosure {
5220 size_t young_regions,free_regions, unclean_regions;
5221 size_t hum_regions, count;
5222 size_t unaccounted, cur_unclean, cur_alloc;
5223 size_t total_free;
5224 HeapRegion* cur;
5225 public:
5226 SortHeapRegionClosure(HeapRegion *_cur) : cur(_cur), young_regions(0),
5227 free_regions(0), unclean_regions(0),
5228 hum_regions(0),
5229 count(0), unaccounted(0),
5230 cur_alloc(0), total_free(0)
5231 {}
5232 bool doHeapRegion(HeapRegion *r) {
5233 count++;
5234 if (r->is_on_free_list()) free_regions++;
5235 else if (r->is_on_unclean_list()) unclean_regions++;
5236 else if (r->isHumongous()) hum_regions++;
5237 else if (r->is_young()) young_regions++;
5238 else if (r == cur) cur_alloc++;
5239 else unaccounted++;
5240 return false;
5241 }
5242 void print() {
5243 total_free = free_regions + unclean_regions;
5244 gclog_or_tty->print("%d regions\n", count);
5245 gclog_or_tty->print("%d free: free_list = %d unclean = %d\n",
5246 total_free, free_regions, unclean_regions);
5247 gclog_or_tty->print("%d humongous %d young\n",
5248 hum_regions, young_regions);
5249 gclog_or_tty->print("%d cur_alloc\n", cur_alloc);
5250 gclog_or_tty->print("UHOH unaccounted = %d\n", unaccounted);
5251 }
5252 };
5254 void G1CollectedHeap::print_region_counts() {
5255 SortHeapRegionClosure sc(_cur_alloc_region);
5256 PrintHeapRegionClosure cl;
5257 heap_region_iterate(&cl);
5258 heap_region_iterate(&sc);
5259 sc.print();
5260 print_region_accounting_info();
5261 };
5263 bool G1CollectedHeap::regions_accounted_for() {
5264 // TODO: regions accounting for young/survivor/tenured
5265 return true;
5266 }
5268 bool G1CollectedHeap::print_region_accounting_info() {
5269 gclog_or_tty->print_cr("Free regions: %d (count: %d count list %d) (clean: %d unclean: %d).",
5270 free_regions(),
5271 count_free_regions(), count_free_regions_list(),
5272 _free_region_list_size, _unclean_region_list.sz());
5273 gclog_or_tty->print_cr("cur_alloc: %d.",
5274 (_cur_alloc_region == NULL ? 0 : 1));
5275 gclog_or_tty->print_cr("H regions: %d.", _num_humongous_regions);
5277 // TODO: check regions accounting for young/survivor/tenured
5278 return true;
5279 }
5281 bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
5282 HeapRegion* hr = heap_region_containing(p);
5283 if (hr == NULL) {
5284 return is_in_permanent(p);
5285 } else {
5286 return hr->is_in(p);
5287 }
5288 }
5289 #endif // !PRODUCT
5291 void G1CollectedHeap::g1_unimplemented() {
5292 // Unimplemented();
5293 }