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