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