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