Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/hotspot/share/gc/g1/g1CollectedHeap.cpp
40957 views
1
/*
2
* Copyright (c) 2001, 2021, 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
#include "precompiled.hpp"
26
#include "classfile/classLoaderDataGraph.hpp"
27
#include "classfile/metadataOnStackMark.hpp"
28
#include "classfile/stringTable.hpp"
29
#include "code/codeCache.hpp"
30
#include "code/icBuffer.hpp"
31
#include "compiler/oopMap.hpp"
32
#include "gc/g1/g1Allocator.inline.hpp"
33
#include "gc/g1/g1Arguments.hpp"
34
#include "gc/g1/g1BarrierSet.hpp"
35
#include "gc/g1/g1CollectedHeap.inline.hpp"
36
#include "gc/g1/g1CollectionSet.hpp"
37
#include "gc/g1/g1CollectorState.hpp"
38
#include "gc/g1/g1ConcurrentRefine.hpp"
39
#include "gc/g1/g1ConcurrentRefineThread.hpp"
40
#include "gc/g1/g1ConcurrentMarkThread.inline.hpp"
41
#include "gc/g1/g1DirtyCardQueue.hpp"
42
#include "gc/g1/g1EvacStats.inline.hpp"
43
#include "gc/g1/g1FullCollector.hpp"
44
#include "gc/g1/g1GCParPhaseTimesTracker.hpp"
45
#include "gc/g1/g1GCPhaseTimes.hpp"
46
#include "gc/g1/g1GCPauseType.hpp"
47
#include "gc/g1/g1HeapSizingPolicy.hpp"
48
#include "gc/g1/g1HeapTransition.hpp"
49
#include "gc/g1/g1HeapVerifier.hpp"
50
#include "gc/g1/g1HotCardCache.hpp"
51
#include "gc/g1/g1InitLogger.hpp"
52
#include "gc/g1/g1MemoryPool.hpp"
53
#include "gc/g1/g1OopClosures.inline.hpp"
54
#include "gc/g1/g1ParallelCleaning.hpp"
55
#include "gc/g1/g1ParScanThreadState.inline.hpp"
56
#include "gc/g1/g1PeriodicGCTask.hpp"
57
#include "gc/g1/g1Policy.hpp"
58
#include "gc/g1/g1RedirtyCardsQueue.hpp"
59
#include "gc/g1/g1RegionToSpaceMapper.hpp"
60
#include "gc/g1/g1RemSet.hpp"
61
#include "gc/g1/g1RootClosures.hpp"
62
#include "gc/g1/g1RootProcessor.hpp"
63
#include "gc/g1/g1SATBMarkQueueSet.hpp"
64
#include "gc/g1/g1ThreadLocalData.hpp"
65
#include "gc/g1/g1Trace.hpp"
66
#include "gc/g1/g1ServiceThread.hpp"
67
#include "gc/g1/g1UncommitRegionTask.hpp"
68
#include "gc/g1/g1VMOperations.hpp"
69
#include "gc/g1/g1YoungGCPostEvacuateTasks.hpp"
70
#include "gc/g1/heapRegion.inline.hpp"
71
#include "gc/g1/heapRegionRemSet.hpp"
72
#include "gc/g1/heapRegionSet.inline.hpp"
73
#include "gc/shared/concurrentGCBreakpoints.hpp"
74
#include "gc/shared/gcBehaviours.hpp"
75
#include "gc/shared/gcHeapSummary.hpp"
76
#include "gc/shared/gcId.hpp"
77
#include "gc/shared/gcLocker.hpp"
78
#include "gc/shared/gcTimer.hpp"
79
#include "gc/shared/gcTraceTime.inline.hpp"
80
#include "gc/shared/generationSpec.hpp"
81
#include "gc/shared/isGCActiveMark.hpp"
82
#include "gc/shared/locationPrinter.inline.hpp"
83
#include "gc/shared/oopStorageParState.hpp"
84
#include "gc/shared/preservedMarks.inline.hpp"
85
#include "gc/shared/suspendibleThreadSet.hpp"
86
#include "gc/shared/referenceProcessor.inline.hpp"
87
#include "gc/shared/taskTerminator.hpp"
88
#include "gc/shared/taskqueue.inline.hpp"
89
#include "gc/shared/tlab_globals.hpp"
90
#include "gc/shared/weakProcessor.inline.hpp"
91
#include "gc/shared/workerPolicy.hpp"
92
#include "logging/log.hpp"
93
#include "memory/allocation.hpp"
94
#include "memory/iterator.hpp"
95
#include "memory/heapInspection.hpp"
96
#include "memory/metaspaceUtils.hpp"
97
#include "memory/resourceArea.hpp"
98
#include "memory/universe.hpp"
99
#include "oops/access.inline.hpp"
100
#include "oops/compressedOops.inline.hpp"
101
#include "oops/oop.inline.hpp"
102
#include "runtime/atomic.hpp"
103
#include "runtime/handles.inline.hpp"
104
#include "runtime/init.hpp"
105
#include "runtime/java.hpp"
106
#include "runtime/orderAccess.hpp"
107
#include "runtime/threadSMR.hpp"
108
#include "runtime/vmThread.hpp"
109
#include "utilities/align.hpp"
110
#include "utilities/autoRestore.hpp"
111
#include "utilities/bitMap.inline.hpp"
112
#include "utilities/globalDefinitions.hpp"
113
#include "utilities/stack.inline.hpp"
114
115
size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
116
117
// INVARIANTS/NOTES
118
//
119
// All allocation activity covered by the G1CollectedHeap interface is
120
// serialized by acquiring the HeapLock. This happens in mem_allocate
121
// and allocate_new_tlab, which are the "entry" points to the
122
// allocation code from the rest of the JVM. (Note that this does not
123
// apply to TLAB allocation, which is not part of this interface: it
124
// is done by clients of this interface.)
125
126
void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) {
127
HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions);
128
}
129
130
void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) {
131
// The from card cache is not the memory that is actually committed. So we cannot
132
// take advantage of the zero_filled parameter.
133
reset_from_card_cache(start_idx, num_regions);
134
}
135
136
Tickspan G1CollectedHeap::run_task_timed(AbstractGangTask* task) {
137
Ticks start = Ticks::now();
138
workers()->run_task(task);
139
return Ticks::now() - start;
140
}
141
142
void G1CollectedHeap::run_batch_task(G1BatchedGangTask* cl) {
143
uint num_workers = MAX2(1u, MIN2(cl->num_workers_estimate(), workers()->active_workers()));
144
cl->set_max_workers(num_workers);
145
workers()->run_task(cl, num_workers);
146
}
147
148
HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index,
149
MemRegion mr) {
150
return new HeapRegion(hrs_index, bot(), mr);
151
}
152
153
// Private methods.
154
155
HeapRegion* G1CollectedHeap::new_region(size_t word_size,
156
HeapRegionType type,
157
bool do_expand,
158
uint node_index) {
159
assert(!is_humongous(word_size) || word_size <= HeapRegion::GrainWords,
160
"the only time we use this to allocate a humongous region is "
161
"when we are allocating a single humongous region");
162
163
HeapRegion* res = _hrm.allocate_free_region(type, node_index);
164
165
if (res == NULL && do_expand && _expand_heap_after_alloc_failure) {
166
// Currently, only attempts to allocate GC alloc regions set
167
// do_expand to true. So, we should only reach here during a
168
// safepoint. If this assumption changes we might have to
169
// reconsider the use of _expand_heap_after_alloc_failure.
170
assert(SafepointSynchronize::is_at_safepoint(), "invariant");
171
172
log_debug(gc, ergo, heap)("Attempt heap expansion (region allocation request failed). Allocation request: " SIZE_FORMAT "B",
173
word_size * HeapWordSize);
174
175
assert(word_size * HeapWordSize < HeapRegion::GrainBytes,
176
"This kind of expansion should never be more than one region. Size: " SIZE_FORMAT,
177
word_size * HeapWordSize);
178
if (expand_single_region(node_index)) {
179
// Given that expand_single_region() succeeded in expanding the heap, and we
180
// always expand the heap by an amount aligned to the heap
181
// region size, the free list should in theory not be empty.
182
// In either case allocate_free_region() will check for NULL.
183
res = _hrm.allocate_free_region(type, node_index);
184
} else {
185
_expand_heap_after_alloc_failure = false;
186
}
187
}
188
return res;
189
}
190
191
HeapWord*
192
G1CollectedHeap::humongous_obj_allocate_initialize_regions(HeapRegion* first_hr,
193
uint num_regions,
194
size_t word_size) {
195
assert(first_hr != NULL, "pre-condition");
196
assert(is_humongous(word_size), "word_size should be humongous");
197
assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
198
199
// Index of last region in the series.
200
uint first = first_hr->hrm_index();
201
uint last = first + num_regions - 1;
202
203
// We need to initialize the region(s) we just discovered. This is
204
// a bit tricky given that it can happen concurrently with
205
// refinement threads refining cards on these regions and
206
// potentially wanting to refine the BOT as they are scanning
207
// those cards (this can happen shortly after a cleanup; see CR
208
// 6991377). So we have to set up the region(s) carefully and in
209
// a specific order.
210
211
// The word size sum of all the regions we will allocate.
212
size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;
213
assert(word_size <= word_size_sum, "sanity");
214
215
// The passed in hr will be the "starts humongous" region. The header
216
// of the new object will be placed at the bottom of this region.
217
HeapWord* new_obj = first_hr->bottom();
218
// This will be the new top of the new object.
219
HeapWord* obj_top = new_obj + word_size;
220
221
// First, we need to zero the header of the space that we will be
222
// allocating. When we update top further down, some refinement
223
// threads might try to scan the region. By zeroing the header we
224
// ensure that any thread that will try to scan the region will
225
// come across the zero klass word and bail out.
226
//
227
// NOTE: It would not have been correct to have used
228
// CollectedHeap::fill_with_object() and make the space look like
229
// an int array. The thread that is doing the allocation will
230
// later update the object header to a potentially different array
231
// type and, for a very short period of time, the klass and length
232
// fields will be inconsistent. This could cause a refinement
233
// thread to calculate the object size incorrectly.
234
Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
235
236
// Next, pad out the unused tail of the last region with filler
237
// objects, for improved usage accounting.
238
// How many words we use for filler objects.
239
size_t word_fill_size = word_size_sum - word_size;
240
241
// How many words memory we "waste" which cannot hold a filler object.
242
size_t words_not_fillable = 0;
243
244
if (word_fill_size >= min_fill_size()) {
245
fill_with_objects(obj_top, word_fill_size);
246
} else if (word_fill_size > 0) {
247
// We have space to fill, but we cannot fit an object there.
248
words_not_fillable = word_fill_size;
249
word_fill_size = 0;
250
}
251
252
// We will set up the first region as "starts humongous". This
253
// will also update the BOT covering all the regions to reflect
254
// that there is a single object that starts at the bottom of the
255
// first region.
256
first_hr->set_starts_humongous(obj_top, word_fill_size);
257
_policy->remset_tracker()->update_at_allocate(first_hr);
258
// Then, if there are any, we will set up the "continues
259
// humongous" regions.
260
HeapRegion* hr = NULL;
261
for (uint i = first + 1; i <= last; ++i) {
262
hr = region_at(i);
263
hr->set_continues_humongous(first_hr);
264
_policy->remset_tracker()->update_at_allocate(hr);
265
}
266
267
// Up to this point no concurrent thread would have been able to
268
// do any scanning on any region in this series. All the top
269
// fields still point to bottom, so the intersection between
270
// [bottom,top] and [card_start,card_end] will be empty. Before we
271
// update the top fields, we'll do a storestore to make sure that
272
// no thread sees the update to top before the zeroing of the
273
// object header and the BOT initialization.
274
OrderAccess::storestore();
275
276
// Now, we will update the top fields of the "continues humongous"
277
// regions except the last one.
278
for (uint i = first; i < last; ++i) {
279
hr = region_at(i);
280
hr->set_top(hr->end());
281
}
282
283
hr = region_at(last);
284
// If we cannot fit a filler object, we must set top to the end
285
// of the humongous object, otherwise we cannot iterate the heap
286
// and the BOT will not be complete.
287
hr->set_top(hr->end() - words_not_fillable);
288
289
assert(hr->bottom() < obj_top && obj_top <= hr->end(),
290
"obj_top should be in last region");
291
292
_verifier->check_bitmaps("Humongous Region Allocation", first_hr);
293
294
assert(words_not_fillable == 0 ||
295
first_hr->bottom() + word_size_sum - words_not_fillable == hr->top(),
296
"Miscalculation in humongous allocation");
297
298
increase_used((word_size_sum - words_not_fillable) * HeapWordSize);
299
300
for (uint i = first; i <= last; ++i) {
301
hr = region_at(i);
302
_humongous_set.add(hr);
303
_hr_printer.alloc(hr);
304
}
305
306
return new_obj;
307
}
308
309
size_t G1CollectedHeap::humongous_obj_size_in_regions(size_t word_size) {
310
assert(is_humongous(word_size), "Object of size " SIZE_FORMAT " must be humongous here", word_size);
311
return align_up(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords;
312
}
313
314
// If could fit into free regions w/o expansion, try.
315
// Otherwise, if can expand, do so.
316
// Otherwise, if using ex regions might help, try with ex given back.
317
HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {
318
assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
319
320
_verifier->verify_region_sets_optional();
321
322
uint obj_regions = (uint) humongous_obj_size_in_regions(word_size);
323
324
// Policy: First try to allocate a humongous object in the free list.
325
HeapRegion* humongous_start = _hrm.allocate_humongous(obj_regions);
326
if (humongous_start == NULL) {
327
// Policy: We could not find enough regions for the humongous object in the
328
// free list. Look through the heap to find a mix of free and uncommitted regions.
329
// If so, expand the heap and allocate the humongous object.
330
humongous_start = _hrm.expand_and_allocate_humongous(obj_regions);
331
if (humongous_start != NULL) {
332
// We managed to find a region by expanding the heap.
333
log_debug(gc, ergo, heap)("Heap expansion (humongous allocation request). Allocation request: " SIZE_FORMAT "B",
334
word_size * HeapWordSize);
335
policy()->record_new_heap_size(num_regions());
336
} else {
337
// Policy: Potentially trigger a defragmentation GC.
338
}
339
}
340
341
HeapWord* result = NULL;
342
if (humongous_start != NULL) {
343
result = humongous_obj_allocate_initialize_regions(humongous_start, obj_regions, word_size);
344
assert(result != NULL, "it should always return a valid result");
345
346
// A successful humongous object allocation changes the used space
347
// information of the old generation so we need to recalculate the
348
// sizes and update the jstat counters here.
349
g1mm()->update_sizes();
350
}
351
352
_verifier->verify_region_sets_optional();
353
354
return result;
355
}
356
357
HeapWord* G1CollectedHeap::allocate_new_tlab(size_t min_size,
358
size_t requested_size,
359
size_t* actual_size) {
360
assert_heap_not_locked_and_not_at_safepoint();
361
assert(!is_humongous(requested_size), "we do not allow humongous TLABs");
362
363
return attempt_allocation(min_size, requested_size, actual_size);
364
}
365
366
HeapWord*
367
G1CollectedHeap::mem_allocate(size_t word_size,
368
bool* gc_overhead_limit_was_exceeded) {
369
assert_heap_not_locked_and_not_at_safepoint();
370
371
if (is_humongous(word_size)) {
372
return attempt_allocation_humongous(word_size);
373
}
374
size_t dummy = 0;
375
return attempt_allocation(word_size, word_size, &dummy);
376
}
377
378
HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size) {
379
ResourceMark rm; // For retrieving the thread names in log messages.
380
381
// Make sure you read the note in attempt_allocation_humongous().
382
383
assert_heap_not_locked_and_not_at_safepoint();
384
assert(!is_humongous(word_size), "attempt_allocation_slow() should not "
385
"be called for humongous allocation requests");
386
387
// We should only get here after the first-level allocation attempt
388
// (attempt_allocation()) failed to allocate.
389
390
// We will loop until a) we manage to successfully perform the
391
// allocation or b) we successfully schedule a collection which
392
// fails to perform the allocation. b) is the only case when we'll
393
// return NULL.
394
HeapWord* result = NULL;
395
for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
396
bool should_try_gc;
397
uint gc_count_before;
398
399
{
400
MutexLocker x(Heap_lock);
401
result = _allocator->attempt_allocation_locked(word_size);
402
if (result != NULL) {
403
return result;
404
}
405
406
// If the GCLocker is active and we are bound for a GC, try expanding young gen.
407
// This is different to when only GCLocker::needs_gc() is set: try to avoid
408
// waiting because the GCLocker is active to not wait too long.
409
if (GCLocker::is_active_and_needs_gc() && policy()->can_expand_young_list()) {
410
// No need for an ergo message here, can_expand_young_list() does this when
411
// it returns true.
412
result = _allocator->attempt_allocation_force(word_size);
413
if (result != NULL) {
414
return result;
415
}
416
}
417
// Only try a GC if the GCLocker does not signal the need for a GC. Wait until
418
// the GCLocker initiated GC has been performed and then retry. This includes
419
// the case when the GC Locker is not active but has not been performed.
420
should_try_gc = !GCLocker::needs_gc();
421
// Read the GC count while still holding the Heap_lock.
422
gc_count_before = total_collections();
423
}
424
425
if (should_try_gc) {
426
bool succeeded;
427
result = do_collection_pause(word_size, gc_count_before, &succeeded,
428
GCCause::_g1_inc_collection_pause);
429
if (result != NULL) {
430
assert(succeeded, "only way to get back a non-NULL result");
431
log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
432
Thread::current()->name(), p2i(result));
433
return result;
434
}
435
436
if (succeeded) {
437
// We successfully scheduled a collection which failed to allocate. No
438
// point in trying to allocate further. We'll just return NULL.
439
log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
440
SIZE_FORMAT " words", Thread::current()->name(), word_size);
441
return NULL;
442
}
443
log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT " words",
444
Thread::current()->name(), word_size);
445
} else {
446
// Failed to schedule a collection.
447
if (gclocker_retry_count > GCLockerRetryAllocationCount) {
448
log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
449
SIZE_FORMAT " words", Thread::current()->name(), word_size);
450
return NULL;
451
}
452
log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
453
// The GCLocker is either active or the GCLocker initiated
454
// GC has not yet been performed. Stall until it is and
455
// then retry the allocation.
456
GCLocker::stall_until_clear();
457
gclocker_retry_count += 1;
458
}
459
460
// We can reach here if we were unsuccessful in scheduling a
461
// collection (because another thread beat us to it) or if we were
462
// stalled due to the GC locker. In either can we should retry the
463
// allocation attempt in case another thread successfully
464
// performed a collection and reclaimed enough space. We do the
465
// first attempt (without holding the Heap_lock) here and the
466
// follow-on attempt will be at the start of the next loop
467
// iteration (after taking the Heap_lock).
468
size_t dummy = 0;
469
result = _allocator->attempt_allocation(word_size, word_size, &dummy);
470
if (result != NULL) {
471
return result;
472
}
473
474
// Give a warning if we seem to be looping forever.
475
if ((QueuedAllocationWarningCount > 0) &&
476
(try_count % QueuedAllocationWarningCount == 0)) {
477
log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",
478
Thread::current()->name(), try_count, word_size);
479
}
480
}
481
482
ShouldNotReachHere();
483
return NULL;
484
}
485
486
void G1CollectedHeap::begin_archive_alloc_range(bool open) {
487
assert_at_safepoint_on_vm_thread();
488
if (_archive_allocator == NULL) {
489
_archive_allocator = G1ArchiveAllocator::create_allocator(this, open);
490
}
491
}
492
493
bool G1CollectedHeap::is_archive_alloc_too_large(size_t word_size) {
494
// Allocations in archive regions cannot be of a size that would be considered
495
// humongous even for a minimum-sized region, because G1 region sizes/boundaries
496
// may be different at archive-restore time.
497
return word_size >= humongous_threshold_for(HeapRegion::min_region_size_in_words());
498
}
499
500
HeapWord* G1CollectedHeap::archive_mem_allocate(size_t word_size) {
501
assert_at_safepoint_on_vm_thread();
502
assert(_archive_allocator != NULL, "_archive_allocator not initialized");
503
if (is_archive_alloc_too_large(word_size)) {
504
return NULL;
505
}
506
return _archive_allocator->archive_mem_allocate(word_size);
507
}
508
509
void G1CollectedHeap::end_archive_alloc_range(GrowableArray<MemRegion>* ranges,
510
size_t end_alignment_in_bytes) {
511
assert_at_safepoint_on_vm_thread();
512
assert(_archive_allocator != NULL, "_archive_allocator not initialized");
513
514
// Call complete_archive to do the real work, filling in the MemRegion
515
// array with the archive regions.
516
_archive_allocator->complete_archive(ranges, end_alignment_in_bytes);
517
delete _archive_allocator;
518
_archive_allocator = NULL;
519
}
520
521
bool G1CollectedHeap::check_archive_addresses(MemRegion* ranges, size_t count) {
522
assert(ranges != NULL, "MemRegion array NULL");
523
assert(count != 0, "No MemRegions provided");
524
MemRegion reserved = _hrm.reserved();
525
for (size_t i = 0; i < count; i++) {
526
if (!reserved.contains(ranges[i].start()) || !reserved.contains(ranges[i].last())) {
527
return false;
528
}
529
}
530
return true;
531
}
532
533
bool G1CollectedHeap::alloc_archive_regions(MemRegion* ranges,
534
size_t count,
535
bool open) {
536
assert(!is_init_completed(), "Expect to be called at JVM init time");
537
assert(ranges != NULL, "MemRegion array NULL");
538
assert(count != 0, "No MemRegions provided");
539
MutexLocker x(Heap_lock);
540
541
MemRegion reserved = _hrm.reserved();
542
HeapWord* prev_last_addr = NULL;
543
HeapRegion* prev_last_region = NULL;
544
545
// Temporarily disable pretouching of heap pages. This interface is used
546
// when mmap'ing archived heap data in, so pre-touching is wasted.
547
FlagSetting fs(AlwaysPreTouch, false);
548
549
// For each specified MemRegion range, allocate the corresponding G1
550
// regions and mark them as archive regions. We expect the ranges
551
// in ascending starting address order, without overlap.
552
for (size_t i = 0; i < count; i++) {
553
MemRegion curr_range = ranges[i];
554
HeapWord* start_address = curr_range.start();
555
size_t word_size = curr_range.word_size();
556
HeapWord* last_address = curr_range.last();
557
size_t commits = 0;
558
559
guarantee(reserved.contains(start_address) && reserved.contains(last_address),
560
"MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
561
p2i(start_address), p2i(last_address));
562
guarantee(start_address > prev_last_addr,
563
"Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
564
p2i(start_address), p2i(prev_last_addr));
565
prev_last_addr = last_address;
566
567
// Check for ranges that start in the same G1 region in which the previous
568
// range ended, and adjust the start address so we don't try to allocate
569
// the same region again. If the current range is entirely within that
570
// region, skip it, just adjusting the recorded top.
571
HeapRegion* start_region = _hrm.addr_to_region(start_address);
572
if ((prev_last_region != NULL) && (start_region == prev_last_region)) {
573
start_address = start_region->end();
574
if (start_address > last_address) {
575
increase_used(word_size * HeapWordSize);
576
start_region->set_top(last_address + 1);
577
continue;
578
}
579
start_region->set_top(start_address);
580
curr_range = MemRegion(start_address, last_address + 1);
581
start_region = _hrm.addr_to_region(start_address);
582
}
583
584
// Perform the actual region allocation, exiting if it fails.
585
// Then note how much new space we have allocated.
586
if (!_hrm.allocate_containing_regions(curr_range, &commits, workers())) {
587
return false;
588
}
589
increase_used(word_size * HeapWordSize);
590
if (commits != 0) {
591
log_debug(gc, ergo, heap)("Attempt heap expansion (allocate archive regions). Total size: " SIZE_FORMAT "B",
592
HeapRegion::GrainWords * HeapWordSize * commits);
593
594
}
595
596
// Mark each G1 region touched by the range as archive, add it to
597
// the old set, and set top.
598
HeapRegion* curr_region = _hrm.addr_to_region(start_address);
599
HeapRegion* last_region = _hrm.addr_to_region(last_address);
600
prev_last_region = last_region;
601
602
while (curr_region != NULL) {
603
assert(curr_region->is_empty() && !curr_region->is_pinned(),
604
"Region already in use (index %u)", curr_region->hrm_index());
605
if (open) {
606
curr_region->set_open_archive();
607
} else {
608
curr_region->set_closed_archive();
609
}
610
_hr_printer.alloc(curr_region);
611
_archive_set.add(curr_region);
612
HeapWord* top;
613
HeapRegion* next_region;
614
if (curr_region != last_region) {
615
top = curr_region->end();
616
next_region = _hrm.next_region_in_heap(curr_region);
617
} else {
618
top = last_address + 1;
619
next_region = NULL;
620
}
621
curr_region->set_top(top);
622
curr_region = next_region;
623
}
624
}
625
return true;
626
}
627
628
void G1CollectedHeap::fill_archive_regions(MemRegion* ranges, size_t count) {
629
assert(!is_init_completed(), "Expect to be called at JVM init time");
630
assert(ranges != NULL, "MemRegion array NULL");
631
assert(count != 0, "No MemRegions provided");
632
MemRegion reserved = _hrm.reserved();
633
HeapWord *prev_last_addr = NULL;
634
HeapRegion* prev_last_region = NULL;
635
636
// For each MemRegion, create filler objects, if needed, in the G1 regions
637
// that contain the address range. The address range actually within the
638
// MemRegion will not be modified. That is assumed to have been initialized
639
// elsewhere, probably via an mmap of archived heap data.
640
MutexLocker x(Heap_lock);
641
for (size_t i = 0; i < count; i++) {
642
HeapWord* start_address = ranges[i].start();
643
HeapWord* last_address = ranges[i].last();
644
645
assert(reserved.contains(start_address) && reserved.contains(last_address),
646
"MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
647
p2i(start_address), p2i(last_address));
648
assert(start_address > prev_last_addr,
649
"Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
650
p2i(start_address), p2i(prev_last_addr));
651
652
HeapRegion* start_region = _hrm.addr_to_region(start_address);
653
HeapRegion* last_region = _hrm.addr_to_region(last_address);
654
HeapWord* bottom_address = start_region->bottom();
655
656
// Check for a range beginning in the same region in which the
657
// previous one ended.
658
if (start_region == prev_last_region) {
659
bottom_address = prev_last_addr + 1;
660
}
661
662
// Verify that the regions were all marked as archive regions by
663
// alloc_archive_regions.
664
HeapRegion* curr_region = start_region;
665
while (curr_region != NULL) {
666
guarantee(curr_region->is_archive(),
667
"Expected archive region at index %u", curr_region->hrm_index());
668
if (curr_region != last_region) {
669
curr_region = _hrm.next_region_in_heap(curr_region);
670
} else {
671
curr_region = NULL;
672
}
673
}
674
675
prev_last_addr = last_address;
676
prev_last_region = last_region;
677
678
// Fill the memory below the allocated range with dummy object(s),
679
// if the region bottom does not match the range start, or if the previous
680
// range ended within the same G1 region, and there is a gap.
681
assert(start_address >= bottom_address, "bottom address should not be greater than start address");
682
if (start_address > bottom_address) {
683
size_t fill_size = pointer_delta(start_address, bottom_address);
684
G1CollectedHeap::fill_with_objects(bottom_address, fill_size);
685
increase_used(fill_size * HeapWordSize);
686
}
687
}
688
}
689
690
inline HeapWord* G1CollectedHeap::attempt_allocation(size_t min_word_size,
691
size_t desired_word_size,
692
size_t* actual_word_size) {
693
assert_heap_not_locked_and_not_at_safepoint();
694
assert(!is_humongous(desired_word_size), "attempt_allocation() should not "
695
"be called for humongous allocation requests");
696
697
HeapWord* result = _allocator->attempt_allocation(min_word_size, desired_word_size, actual_word_size);
698
699
if (result == NULL) {
700
*actual_word_size = desired_word_size;
701
result = attempt_allocation_slow(desired_word_size);
702
}
703
704
assert_heap_not_locked();
705
if (result != NULL) {
706
assert(*actual_word_size != 0, "Actual size must have been set here");
707
dirty_young_block(result, *actual_word_size);
708
} else {
709
*actual_word_size = 0;
710
}
711
712
return result;
713
}
714
715
void G1CollectedHeap::populate_archive_regions_bot_part(MemRegion* ranges, size_t count) {
716
assert(!is_init_completed(), "Expect to be called at JVM init time");
717
assert(ranges != NULL, "MemRegion array NULL");
718
assert(count != 0, "No MemRegions provided");
719
720
HeapWord* st = ranges[0].start();
721
HeapWord* last = ranges[count-1].last();
722
HeapRegion* hr_st = _hrm.addr_to_region(st);
723
HeapRegion* hr_last = _hrm.addr_to_region(last);
724
725
HeapRegion* hr_curr = hr_st;
726
while (hr_curr != NULL) {
727
hr_curr->update_bot();
728
if (hr_curr != hr_last) {
729
hr_curr = _hrm.next_region_in_heap(hr_curr);
730
} else {
731
hr_curr = NULL;
732
}
733
}
734
}
735
736
void G1CollectedHeap::dealloc_archive_regions(MemRegion* ranges, size_t count) {
737
assert(!is_init_completed(), "Expect to be called at JVM init time");
738
assert(ranges != NULL, "MemRegion array NULL");
739
assert(count != 0, "No MemRegions provided");
740
MemRegion reserved = _hrm.reserved();
741
HeapWord* prev_last_addr = NULL;
742
HeapRegion* prev_last_region = NULL;
743
size_t size_used = 0;
744
uint shrink_count = 0;
745
746
// For each Memregion, free the G1 regions that constitute it, and
747
// notify mark-sweep that the range is no longer to be considered 'archive.'
748
MutexLocker x(Heap_lock);
749
for (size_t i = 0; i < count; i++) {
750
HeapWord* start_address = ranges[i].start();
751
HeapWord* last_address = ranges[i].last();
752
753
assert(reserved.contains(start_address) && reserved.contains(last_address),
754
"MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
755
p2i(start_address), p2i(last_address));
756
assert(start_address > prev_last_addr,
757
"Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
758
p2i(start_address), p2i(prev_last_addr));
759
size_used += ranges[i].byte_size();
760
prev_last_addr = last_address;
761
762
HeapRegion* start_region = _hrm.addr_to_region(start_address);
763
HeapRegion* last_region = _hrm.addr_to_region(last_address);
764
765
// Check for ranges that start in the same G1 region in which the previous
766
// range ended, and adjust the start address so we don't try to free
767
// the same region again. If the current range is entirely within that
768
// region, skip it.
769
if (start_region == prev_last_region) {
770
start_address = start_region->end();
771
if (start_address > last_address) {
772
continue;
773
}
774
start_region = _hrm.addr_to_region(start_address);
775
}
776
prev_last_region = last_region;
777
778
// After verifying that each region was marked as an archive region by
779
// alloc_archive_regions, set it free and empty and uncommit it.
780
HeapRegion* curr_region = start_region;
781
while (curr_region != NULL) {
782
guarantee(curr_region->is_archive(),
783
"Expected archive region at index %u", curr_region->hrm_index());
784
uint curr_index = curr_region->hrm_index();
785
_archive_set.remove(curr_region);
786
curr_region->set_free();
787
curr_region->set_top(curr_region->bottom());
788
if (curr_region != last_region) {
789
curr_region = _hrm.next_region_in_heap(curr_region);
790
} else {
791
curr_region = NULL;
792
}
793
794
_hrm.shrink_at(curr_index, 1);
795
shrink_count++;
796
}
797
}
798
799
if (shrink_count != 0) {
800
log_debug(gc, ergo, heap)("Attempt heap shrinking (archive regions). Total size: " SIZE_FORMAT "B",
801
HeapRegion::GrainWords * HeapWordSize * shrink_count);
802
// Explicit uncommit.
803
uncommit_regions(shrink_count);
804
}
805
decrease_used(size_used);
806
}
807
808
HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) {
809
ResourceMark rm; // For retrieving the thread names in log messages.
810
811
// The structure of this method has a lot of similarities to
812
// attempt_allocation_slow(). The reason these two were not merged
813
// into a single one is that such a method would require several "if
814
// allocation is not humongous do this, otherwise do that"
815
// conditional paths which would obscure its flow. In fact, an early
816
// version of this code did use a unified method which was harder to
817
// follow and, as a result, it had subtle bugs that were hard to
818
// track down. So keeping these two methods separate allows each to
819
// be more readable. It will be good to keep these two in sync as
820
// much as possible.
821
822
assert_heap_not_locked_and_not_at_safepoint();
823
assert(is_humongous(word_size), "attempt_allocation_humongous() "
824
"should only be called for humongous allocations");
825
826
// Humongous objects can exhaust the heap quickly, so we should check if we
827
// need to start a marking cycle at each humongous object allocation. We do
828
// the check before we do the actual allocation. The reason for doing it
829
// before the allocation is that we avoid having to keep track of the newly
830
// allocated memory while we do a GC.
831
if (policy()->need_to_start_conc_mark("concurrent humongous allocation",
832
word_size)) {
833
collect(GCCause::_g1_humongous_allocation);
834
}
835
836
// We will loop until a) we manage to successfully perform the
837
// allocation or b) we successfully schedule a collection which
838
// fails to perform the allocation. b) is the only case when we'll
839
// return NULL.
840
HeapWord* result = NULL;
841
for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
842
bool should_try_gc;
843
uint gc_count_before;
844
845
846
{
847
MutexLocker x(Heap_lock);
848
849
// Given that humongous objects are not allocated in young
850
// regions, we'll first try to do the allocation without doing a
851
// collection hoping that there's enough space in the heap.
852
result = humongous_obj_allocate(word_size);
853
if (result != NULL) {
854
size_t size_in_regions = humongous_obj_size_in_regions(word_size);
855
policy()->old_gen_alloc_tracker()->
856
add_allocated_humongous_bytes_since_last_gc(size_in_regions * HeapRegion::GrainBytes);
857
return result;
858
}
859
860
// Only try a GC if the GCLocker does not signal the need for a GC. Wait until
861
// the GCLocker initiated GC has been performed and then retry. This includes
862
// the case when the GC Locker is not active but has not been performed.
863
should_try_gc = !GCLocker::needs_gc();
864
// Read the GC count while still holding the Heap_lock.
865
gc_count_before = total_collections();
866
}
867
868
if (should_try_gc) {
869
bool succeeded;
870
result = do_collection_pause(word_size, gc_count_before, &succeeded,
871
GCCause::_g1_humongous_allocation);
872
if (result != NULL) {
873
assert(succeeded, "only way to get back a non-NULL result");
874
log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
875
Thread::current()->name(), p2i(result));
876
size_t size_in_regions = humongous_obj_size_in_regions(word_size);
877
policy()->old_gen_alloc_tracker()->
878
record_collection_pause_humongous_allocation(size_in_regions * HeapRegion::GrainBytes);
879
return result;
880
}
881
882
if (succeeded) {
883
// We successfully scheduled a collection which failed to allocate. No
884
// point in trying to allocate further. We'll just return NULL.
885
log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
886
SIZE_FORMAT " words", Thread::current()->name(), word_size);
887
return NULL;
888
}
889
log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT "",
890
Thread::current()->name(), word_size);
891
} else {
892
// Failed to schedule a collection.
893
if (gclocker_retry_count > GCLockerRetryAllocationCount) {
894
log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
895
SIZE_FORMAT " words", Thread::current()->name(), word_size);
896
return NULL;
897
}
898
log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
899
// The GCLocker is either active or the GCLocker initiated
900
// GC has not yet been performed. Stall until it is and
901
// then retry the allocation.
902
GCLocker::stall_until_clear();
903
gclocker_retry_count += 1;
904
}
905
906
907
// We can reach here if we were unsuccessful in scheduling a
908
// collection (because another thread beat us to it) or if we were
909
// stalled due to the GC locker. In either can we should retry the
910
// allocation attempt in case another thread successfully
911
// performed a collection and reclaimed enough space.
912
// Humongous object allocation always needs a lock, so we wait for the retry
913
// in the next iteration of the loop, unlike for the regular iteration case.
914
// Give a warning if we seem to be looping forever.
915
916
if ((QueuedAllocationWarningCount > 0) &&
917
(try_count % QueuedAllocationWarningCount == 0)) {
918
log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",
919
Thread::current()->name(), try_count, word_size);
920
}
921
}
922
923
ShouldNotReachHere();
924
return NULL;
925
}
926
927
HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
928
bool expect_null_mutator_alloc_region) {
929
assert_at_safepoint_on_vm_thread();
930
assert(!_allocator->has_mutator_alloc_region() || !expect_null_mutator_alloc_region,
931
"the current alloc region was unexpectedly found to be non-NULL");
932
933
if (!is_humongous(word_size)) {
934
return _allocator->attempt_allocation_locked(word_size);
935
} else {
936
HeapWord* result = humongous_obj_allocate(word_size);
937
if (result != NULL && policy()->need_to_start_conc_mark("STW humongous allocation")) {
938
collector_state()->set_initiate_conc_mark_if_possible(true);
939
}
940
return result;
941
}
942
943
ShouldNotReachHere();
944
}
945
946
class PostCompactionPrinterClosure: public HeapRegionClosure {
947
private:
948
G1HRPrinter* _hr_printer;
949
public:
950
bool do_heap_region(HeapRegion* hr) {
951
assert(!hr->is_young(), "not expecting to find young regions");
952
_hr_printer->post_compaction(hr);
953
return false;
954
}
955
956
PostCompactionPrinterClosure(G1HRPrinter* hr_printer)
957
: _hr_printer(hr_printer) { }
958
};
959
960
void G1CollectedHeap::print_hrm_post_compaction() {
961
if (_hr_printer.is_active()) {
962
PostCompactionPrinterClosure cl(hr_printer());
963
heap_region_iterate(&cl);
964
}
965
}
966
967
void G1CollectedHeap::abort_concurrent_cycle() {
968
// If we start the compaction before the CM threads finish
969
// scanning the root regions we might trip them over as we'll
970
// be moving objects / updating references. So let's wait until
971
// they are done. By telling them to abort, they should complete
972
// early.
973
_cm->root_regions()->abort();
974
_cm->root_regions()->wait_until_scan_finished();
975
976
// Disable discovery and empty the discovered lists
977
// for the CM ref processor.
978
_ref_processor_cm->disable_discovery();
979
_ref_processor_cm->abandon_partial_discovery();
980
_ref_processor_cm->verify_no_references_recorded();
981
982
// Abandon current iterations of concurrent marking and concurrent
983
// refinement, if any are in progress.
984
concurrent_mark()->concurrent_cycle_abort();
985
}
986
987
void G1CollectedHeap::prepare_heap_for_full_collection() {
988
// Make sure we'll choose a new allocation region afterwards.
989
_allocator->release_mutator_alloc_regions();
990
_allocator->abandon_gc_alloc_regions();
991
992
// We may have added regions to the current incremental collection
993
// set between the last GC or pause and now. We need to clear the
994
// incremental collection set and then start rebuilding it afresh
995
// after this full GC.
996
abandon_collection_set(collection_set());
997
998
_hrm.remove_all_free_regions();
999
}
1000
1001
void G1CollectedHeap::verify_before_full_collection(bool explicit_gc) {
1002
assert(!GCCause::is_user_requested_gc(gc_cause()) || explicit_gc, "invariant");
1003
assert_used_and_recalculate_used_equal(this);
1004
_verifier->verify_region_sets_optional();
1005
_verifier->verify_before_gc(G1HeapVerifier::G1VerifyFull);
1006
_verifier->check_bitmaps("Full GC Start");
1007
}
1008
1009
void G1CollectedHeap::prepare_heap_for_mutators() {
1010
// Delete metaspaces for unloaded class loaders and clean up loader_data graph
1011
ClassLoaderDataGraph::purge(/*at_safepoint*/true);
1012
DEBUG_ONLY(MetaspaceUtils::verify();)
1013
1014
// Prepare heap for normal collections.
1015
assert(num_free_regions() == 0, "we should not have added any free regions");
1016
rebuild_region_sets(false /* free_list_only */);
1017
abort_refinement();
1018
resize_heap_if_necessary();
1019
uncommit_regions_if_necessary();
1020
1021
// Rebuild the strong code root lists for each region
1022
rebuild_strong_code_roots();
1023
1024
// Purge code root memory
1025
purge_code_root_memory();
1026
1027
// Start a new incremental collection set for the next pause
1028
start_new_collection_set();
1029
1030
_allocator->init_mutator_alloc_regions();
1031
1032
// Post collection state updates.
1033
MetaspaceGC::compute_new_size();
1034
}
1035
1036
void G1CollectedHeap::abort_refinement() {
1037
if (_hot_card_cache->use_cache()) {
1038
_hot_card_cache->reset_hot_cache();
1039
}
1040
1041
// Discard all remembered set updates and reset refinement statistics.
1042
G1BarrierSet::dirty_card_queue_set().abandon_logs();
1043
assert(G1BarrierSet::dirty_card_queue_set().num_cards() == 0,
1044
"DCQS should be empty");
1045
concurrent_refine()->get_and_reset_refinement_stats();
1046
}
1047
1048
void G1CollectedHeap::verify_after_full_collection() {
1049
_hrm.verify_optional();
1050
_verifier->verify_region_sets_optional();
1051
_verifier->verify_after_gc(G1HeapVerifier::G1VerifyFull);
1052
1053
// This call implicitly verifies that the next bitmap is clear after Full GC.
1054
_verifier->check_bitmaps("Full GC End");
1055
1056
// At this point there should be no regions in the
1057
// entire heap tagged as young.
1058
assert(check_young_list_empty(), "young list should be empty at this point");
1059
1060
// Note: since we've just done a full GC, concurrent
1061
// marking is no longer active. Therefore we need not
1062
// re-enable reference discovery for the CM ref processor.
1063
// That will be done at the start of the next marking cycle.
1064
// We also know that the STW processor should no longer
1065
// discover any new references.
1066
assert(!_ref_processor_stw->discovery_enabled(), "Postcondition");
1067
assert(!_ref_processor_cm->discovery_enabled(), "Postcondition");
1068
_ref_processor_stw->verify_no_references_recorded();
1069
_ref_processor_cm->verify_no_references_recorded();
1070
}
1071
1072
void G1CollectedHeap::print_heap_after_full_collection(G1HeapTransition* heap_transition) {
1073
// Post collection logging.
1074
// We should do this after we potentially resize the heap so
1075
// that all the COMMIT / UNCOMMIT events are generated before
1076
// the compaction events.
1077
print_hrm_post_compaction();
1078
heap_transition->print();
1079
print_heap_after_gc();
1080
print_heap_regions();
1081
}
1082
1083
bool G1CollectedHeap::do_full_collection(bool explicit_gc,
1084
bool clear_all_soft_refs,
1085
bool do_maximum_compaction) {
1086
assert_at_safepoint_on_vm_thread();
1087
1088
if (GCLocker::check_active_before_gc()) {
1089
// Full GC was not completed.
1090
return false;
1091
}
1092
1093
const bool do_clear_all_soft_refs = clear_all_soft_refs ||
1094
soft_ref_policy()->should_clear_all_soft_refs();
1095
1096
G1FullCollector collector(this, explicit_gc, do_clear_all_soft_refs, do_maximum_compaction);
1097
GCTraceTime(Info, gc) tm("Pause Full", NULL, gc_cause(), true);
1098
1099
collector.prepare_collection();
1100
collector.collect();
1101
collector.complete_collection();
1102
1103
// Full collection was successfully completed.
1104
return true;
1105
}
1106
1107
void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1108
// Currently, there is no facility in the do_full_collection(bool) API to notify
1109
// the caller that the collection did not succeed (e.g., because it was locked
1110
// out by the GC locker). So, right now, we'll ignore the return value.
1111
// When clear_all_soft_refs is set we want to do a maximum compaction
1112
// not leaving any dead wood.
1113
bool do_maximum_compaction = clear_all_soft_refs;
1114
bool dummy = do_full_collection(true, /* explicit_gc */
1115
clear_all_soft_refs,
1116
do_maximum_compaction);
1117
}
1118
1119
void G1CollectedHeap::resize_heap_if_necessary() {
1120
assert_at_safepoint_on_vm_thread();
1121
1122
bool should_expand;
1123
size_t resize_amount = _heap_sizing_policy->full_collection_resize_amount(should_expand);
1124
1125
if (resize_amount == 0) {
1126
return;
1127
} else if (should_expand) {
1128
expand(resize_amount, _workers);
1129
} else {
1130
shrink(resize_amount);
1131
}
1132
}
1133
1134
HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size,
1135
bool do_gc,
1136
bool clear_all_soft_refs,
1137
bool expect_null_mutator_alloc_region,
1138
bool* gc_succeeded) {
1139
*gc_succeeded = true;
1140
// Let's attempt the allocation first.
1141
HeapWord* result =
1142
attempt_allocation_at_safepoint(word_size,
1143
expect_null_mutator_alloc_region);
1144
if (result != NULL) {
1145
return result;
1146
}
1147
1148
// In a G1 heap, we're supposed to keep allocation from failing by
1149
// incremental pauses. Therefore, at least for now, we'll favor
1150
// expansion over collection. (This might change in the future if we can
1151
// do something smarter than full collection to satisfy a failed alloc.)
1152
result = expand_and_allocate(word_size);
1153
if (result != NULL) {
1154
return result;
1155
}
1156
1157
if (do_gc) {
1158
// When clear_all_soft_refs is set we want to do a maximum compaction
1159
// not leaving any dead wood.
1160
bool do_maximum_compaction = clear_all_soft_refs;
1161
// Expansion didn't work, we'll try to do a Full GC.
1162
*gc_succeeded = do_full_collection(false, /* explicit_gc */
1163
clear_all_soft_refs,
1164
do_maximum_compaction);
1165
}
1166
1167
return NULL;
1168
}
1169
1170
HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size,
1171
bool* succeeded) {
1172
assert_at_safepoint_on_vm_thread();
1173
1174
// Attempts to allocate followed by Full GC.
1175
HeapWord* result =
1176
satisfy_failed_allocation_helper(word_size,
1177
true, /* do_gc */
1178
false, /* clear_all_soft_refs */
1179
false, /* expect_null_mutator_alloc_region */
1180
succeeded);
1181
1182
if (result != NULL || !*succeeded) {
1183
return result;
1184
}
1185
1186
// Attempts to allocate followed by Full GC that will collect all soft references.
1187
result = satisfy_failed_allocation_helper(word_size,
1188
true, /* do_gc */
1189
true, /* clear_all_soft_refs */
1190
true, /* expect_null_mutator_alloc_region */
1191
succeeded);
1192
1193
if (result != NULL || !*succeeded) {
1194
return result;
1195
}
1196
1197
// Attempts to allocate, no GC
1198
result = satisfy_failed_allocation_helper(word_size,
1199
false, /* do_gc */
1200
false, /* clear_all_soft_refs */
1201
true, /* expect_null_mutator_alloc_region */
1202
succeeded);
1203
1204
if (result != NULL) {
1205
return result;
1206
}
1207
1208
assert(!soft_ref_policy()->should_clear_all_soft_refs(),
1209
"Flag should have been handled and cleared prior to this point");
1210
1211
// What else? We might try synchronous finalization later. If the total
1212
// space available is large enough for the allocation, then a more
1213
// complete compaction phase than we've tried so far might be
1214
// appropriate.
1215
return NULL;
1216
}
1217
1218
// Attempting to expand the heap sufficiently
1219
// to support an allocation of the given "word_size". If
1220
// successful, perform the allocation and return the address of the
1221
// allocated block, or else "NULL".
1222
1223
HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1224
assert_at_safepoint_on_vm_thread();
1225
1226
_verifier->verify_region_sets_optional();
1227
1228
size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
1229
log_debug(gc, ergo, heap)("Attempt heap expansion (allocation request failed). Allocation request: " SIZE_FORMAT "B",
1230
word_size * HeapWordSize);
1231
1232
1233
if (expand(expand_bytes, _workers)) {
1234
_hrm.verify_optional();
1235
_verifier->verify_region_sets_optional();
1236
return attempt_allocation_at_safepoint(word_size,
1237
false /* expect_null_mutator_alloc_region */);
1238
}
1239
return NULL;
1240
}
1241
1242
bool G1CollectedHeap::expand(size_t expand_bytes, WorkGang* pretouch_workers, double* expand_time_ms) {
1243
size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);
1244
aligned_expand_bytes = align_up(aligned_expand_bytes,
1245
HeapRegion::GrainBytes);
1246
1247
log_debug(gc, ergo, heap)("Expand the heap. requested expansion amount: " SIZE_FORMAT "B expansion amount: " SIZE_FORMAT "B",
1248
expand_bytes, aligned_expand_bytes);
1249
1250
if (is_maximal_no_gc()) {
1251
log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");
1252
return false;
1253
}
1254
1255
double expand_heap_start_time_sec = os::elapsedTime();
1256
uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes);
1257
assert(regions_to_expand > 0, "Must expand by at least one region");
1258
1259
uint expanded_by = _hrm.expand_by(regions_to_expand, pretouch_workers);
1260
if (expand_time_ms != NULL) {
1261
*expand_time_ms = (os::elapsedTime() - expand_heap_start_time_sec) * MILLIUNITS;
1262
}
1263
1264
if (expanded_by > 0) {
1265
size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes;
1266
assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
1267
policy()->record_new_heap_size(num_regions());
1268
} else {
1269
log_debug(gc, ergo, heap)("Did not expand the heap (heap expansion operation failed)");
1270
1271
// The expansion of the virtual storage space was unsuccessful.
1272
// Let's see if it was because we ran out of swap.
1273
if (G1ExitOnExpansionFailure &&
1274
_hrm.available() >= regions_to_expand) {
1275
// We had head room...
1276
vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");
1277
}
1278
}
1279
return regions_to_expand > 0;
1280
}
1281
1282
bool G1CollectedHeap::expand_single_region(uint node_index) {
1283
uint expanded_by = _hrm.expand_on_preferred_node(node_index);
1284
1285
if (expanded_by == 0) {
1286
assert(is_maximal_no_gc(), "Should be no regions left, available: %u", _hrm.available());
1287
log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");
1288
return false;
1289
}
1290
1291
policy()->record_new_heap_size(num_regions());
1292
return true;
1293
}
1294
1295
void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
1296
size_t aligned_shrink_bytes =
1297
ReservedSpace::page_align_size_down(shrink_bytes);
1298
aligned_shrink_bytes = align_down(aligned_shrink_bytes,
1299
HeapRegion::GrainBytes);
1300
uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);
1301
1302
uint num_regions_removed = _hrm.shrink_by(num_regions_to_remove);
1303
size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;
1304
1305
log_debug(gc, ergo, heap)("Shrink the heap. requested shrinking amount: " SIZE_FORMAT "B aligned shrinking amount: " SIZE_FORMAT "B attempted shrinking amount: " SIZE_FORMAT "B",
1306
shrink_bytes, aligned_shrink_bytes, shrunk_bytes);
1307
if (num_regions_removed > 0) {
1308
log_debug(gc, heap)("Uncommittable regions after shrink: %u", num_regions_removed);
1309
policy()->record_new_heap_size(num_regions());
1310
} else {
1311
log_debug(gc, ergo, heap)("Did not expand the heap (heap shrinking operation failed)");
1312
}
1313
}
1314
1315
void G1CollectedHeap::shrink(size_t shrink_bytes) {
1316
_verifier->verify_region_sets_optional();
1317
1318
// We should only reach here at the end of a Full GC or during Remark which
1319
// means we should not not be holding to any GC alloc regions. The method
1320
// below will make sure of that and do any remaining clean up.
1321
_allocator->abandon_gc_alloc_regions();
1322
1323
// Instead of tearing down / rebuilding the free lists here, we
1324
// could instead use the remove_all_pending() method on free_list to
1325
// remove only the ones that we need to remove.
1326
_hrm.remove_all_free_regions();
1327
shrink_helper(shrink_bytes);
1328
rebuild_region_sets(true /* free_list_only */);
1329
1330
_hrm.verify_optional();
1331
_verifier->verify_region_sets_optional();
1332
}
1333
1334
class OldRegionSetChecker : public HeapRegionSetChecker {
1335
public:
1336
void check_mt_safety() {
1337
// Master Old Set MT safety protocol:
1338
// (a) If we're at a safepoint, operations on the master old set
1339
// should be invoked:
1340
// - by the VM thread (which will serialize them), or
1341
// - by the GC workers while holding the FreeList_lock, if we're
1342
// at a safepoint for an evacuation pause (this lock is taken
1343
// anyway when an GC alloc region is retired so that a new one
1344
// is allocated from the free list), or
1345
// - by the GC workers while holding the OldSets_lock, if we're at a
1346
// safepoint for a cleanup pause.
1347
// (b) If we're not at a safepoint, operations on the master old set
1348
// should be invoked while holding the Heap_lock.
1349
1350
if (SafepointSynchronize::is_at_safepoint()) {
1351
guarantee(Thread::current()->is_VM_thread() ||
1352
FreeList_lock->owned_by_self() || OldSets_lock->owned_by_self(),
1353
"master old set MT safety protocol at a safepoint");
1354
} else {
1355
guarantee(Heap_lock->owned_by_self(), "master old set MT safety protocol outside a safepoint");
1356
}
1357
}
1358
bool is_correct_type(HeapRegion* hr) { return hr->is_old(); }
1359
const char* get_description() { return "Old Regions"; }
1360
};
1361
1362
class ArchiveRegionSetChecker : public HeapRegionSetChecker {
1363
public:
1364
void check_mt_safety() {
1365
guarantee(!Universe::is_fully_initialized() || SafepointSynchronize::is_at_safepoint(),
1366
"May only change archive regions during initialization or safepoint.");
1367
}
1368
bool is_correct_type(HeapRegion* hr) { return hr->is_archive(); }
1369
const char* get_description() { return "Archive Regions"; }
1370
};
1371
1372
class HumongousRegionSetChecker : public HeapRegionSetChecker {
1373
public:
1374
void check_mt_safety() {
1375
// Humongous Set MT safety protocol:
1376
// (a) If we're at a safepoint, operations on the master humongous
1377
// set should be invoked by either the VM thread (which will
1378
// serialize them) or by the GC workers while holding the
1379
// OldSets_lock.
1380
// (b) If we're not at a safepoint, operations on the master
1381
// humongous set should be invoked while holding the Heap_lock.
1382
1383
if (SafepointSynchronize::is_at_safepoint()) {
1384
guarantee(Thread::current()->is_VM_thread() ||
1385
OldSets_lock->owned_by_self(),
1386
"master humongous set MT safety protocol at a safepoint");
1387
} else {
1388
guarantee(Heap_lock->owned_by_self(),
1389
"master humongous set MT safety protocol outside a safepoint");
1390
}
1391
}
1392
bool is_correct_type(HeapRegion* hr) { return hr->is_humongous(); }
1393
const char* get_description() { return "Humongous Regions"; }
1394
};
1395
1396
G1CollectedHeap::G1CollectedHeap() :
1397
CollectedHeap(),
1398
_service_thread(NULL),
1399
_periodic_gc_task(NULL),
1400
_workers(NULL),
1401
_card_table(NULL),
1402
_collection_pause_end(Ticks::now()),
1403
_soft_ref_policy(),
1404
_old_set("Old Region Set", new OldRegionSetChecker()),
1405
_archive_set("Archive Region Set", new ArchiveRegionSetChecker()),
1406
_humongous_set("Humongous Region Set", new HumongousRegionSetChecker()),
1407
_bot(NULL),
1408
_listener(),
1409
_numa(G1NUMA::create()),
1410
_hrm(),
1411
_allocator(NULL),
1412
_verifier(NULL),
1413
_summary_bytes_used(0),
1414
_bytes_used_during_gc(0),
1415
_archive_allocator(NULL),
1416
_survivor_evac_stats("Young", YoungPLABSize, PLABWeight),
1417
_old_evac_stats("Old", OldPLABSize, PLABWeight),
1418
_expand_heap_after_alloc_failure(true),
1419
_g1mm(NULL),
1420
_humongous_reclaim_candidates(),
1421
_num_humongous_objects(0),
1422
_num_humongous_reclaim_candidates(0),
1423
_hr_printer(),
1424
_collector_state(),
1425
_old_marking_cycles_started(0),
1426
_old_marking_cycles_completed(0),
1427
_eden(),
1428
_survivor(),
1429
_gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),
1430
_gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),
1431
_policy(new G1Policy(_gc_timer_stw)),
1432
_heap_sizing_policy(NULL),
1433
_collection_set(this, _policy),
1434
_hot_card_cache(NULL),
1435
_rem_set(NULL),
1436
_cm(NULL),
1437
_cm_thread(NULL),
1438
_cr(NULL),
1439
_task_queues(NULL),
1440
_num_regions_failed_evacuation(0),
1441
_evacuation_failed_info_array(NULL),
1442
_preserved_marks_set(true /* in_c_heap */),
1443
#ifndef PRODUCT
1444
_evacuation_failure_alot_for_current_gc(false),
1445
_evacuation_failure_alot_gc_number(0),
1446
_evacuation_failure_alot_count(0),
1447
#endif
1448
_ref_processor_stw(NULL),
1449
_is_alive_closure_stw(this),
1450
_is_subject_to_discovery_stw(this),
1451
_ref_processor_cm(NULL),
1452
_is_alive_closure_cm(this),
1453
_is_subject_to_discovery_cm(this),
1454
_region_attr() {
1455
1456
_verifier = new G1HeapVerifier(this);
1457
1458
_allocator = new G1Allocator(this);
1459
1460
_heap_sizing_policy = G1HeapSizingPolicy::create(this, _policy->analytics());
1461
1462
_humongous_object_threshold_in_words = humongous_threshold_for(HeapRegion::GrainWords);
1463
1464
// Override the default _filler_array_max_size so that no humongous filler
1465
// objects are created.
1466
_filler_array_max_size = _humongous_object_threshold_in_words;
1467
1468
uint n_queues = ParallelGCThreads;
1469
_task_queues = new G1ScannerTasksQueueSet(n_queues);
1470
1471
_evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);
1472
1473
for (uint i = 0; i < n_queues; i++) {
1474
G1ScannerTasksQueue* q = new G1ScannerTasksQueue();
1475
q->initialize();
1476
_task_queues->register_queue(i, q);
1477
::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();
1478
}
1479
1480
// Initialize the G1EvacuationFailureALot counters and flags.
1481
NOT_PRODUCT(reset_evacuation_should_fail();)
1482
_gc_tracer_stw->initialize();
1483
1484
guarantee(_task_queues != NULL, "task_queues allocation failure.");
1485
}
1486
1487
G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description,
1488
size_t size,
1489
size_t translation_factor) {
1490
size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1);
1491
// Allocate a new reserved space, preferring to use large pages.
1492
ReservedSpace rs(size, preferred_page_size);
1493
size_t page_size = rs.page_size();
1494
G1RegionToSpaceMapper* result =
1495
G1RegionToSpaceMapper::create_mapper(rs,
1496
size,
1497
page_size,
1498
HeapRegion::GrainBytes,
1499
translation_factor,
1500
mtGC);
1501
1502
os::trace_page_sizes_for_requested_size(description,
1503
size,
1504
page_size,
1505
preferred_page_size,
1506
rs.base(),
1507
rs.size());
1508
1509
return result;
1510
}
1511
1512
jint G1CollectedHeap::initialize_concurrent_refinement() {
1513
jint ecode = JNI_OK;
1514
_cr = G1ConcurrentRefine::create(&ecode);
1515
return ecode;
1516
}
1517
1518
jint G1CollectedHeap::initialize_service_thread() {
1519
_service_thread = new G1ServiceThread();
1520
if (_service_thread->osthread() == NULL) {
1521
vm_shutdown_during_initialization("Could not create G1ServiceThread");
1522
return JNI_ENOMEM;
1523
}
1524
return JNI_OK;
1525
}
1526
1527
jint G1CollectedHeap::initialize() {
1528
1529
// Necessary to satisfy locking discipline assertions.
1530
1531
MutexLocker x(Heap_lock);
1532
1533
// While there are no constraints in the GC code that HeapWordSize
1534
// be any particular value, there are multiple other areas in the
1535
// system which believe this to be true (e.g. oop->object_size in some
1536
// cases incorrectly returns the size in wordSize units rather than
1537
// HeapWordSize).
1538
guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1539
1540
size_t init_byte_size = InitialHeapSize;
1541
size_t reserved_byte_size = G1Arguments::heap_reserved_size_bytes();
1542
1543
// Ensure that the sizes are properly aligned.
1544
Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
1545
Universe::check_alignment(reserved_byte_size, HeapRegion::GrainBytes, "g1 heap");
1546
Universe::check_alignment(reserved_byte_size, HeapAlignment, "g1 heap");
1547
1548
// Reserve the maximum.
1549
1550
// When compressed oops are enabled, the preferred heap base
1551
// is calculated by subtracting the requested size from the
1552
// 32Gb boundary and using the result as the base address for
1553
// heap reservation. If the requested size is not aligned to
1554
// HeapRegion::GrainBytes (i.e. the alignment that is passed
1555
// into the ReservedHeapSpace constructor) then the actual
1556
// base of the reserved heap may end up differing from the
1557
// address that was requested (i.e. the preferred heap base).
1558
// If this happens then we could end up using a non-optimal
1559
// compressed oops mode.
1560
1561
ReservedHeapSpace heap_rs = Universe::reserve_heap(reserved_byte_size,
1562
HeapAlignment);
1563
1564
initialize_reserved_region(heap_rs);
1565
1566
// Create the barrier set for the entire reserved region.
1567
G1CardTable* ct = new G1CardTable(heap_rs.region());
1568
ct->initialize();
1569
G1BarrierSet* bs = new G1BarrierSet(ct);
1570
bs->initialize();
1571
assert(bs->is_a(BarrierSet::G1BarrierSet), "sanity");
1572
BarrierSet::set_barrier_set(bs);
1573
_card_table = ct;
1574
1575
{
1576
G1SATBMarkQueueSet& satbqs = bs->satb_mark_queue_set();
1577
satbqs.set_process_completed_buffers_threshold(G1SATBProcessCompletedThreshold);
1578
satbqs.set_buffer_enqueue_threshold_percentage(G1SATBBufferEnqueueingThresholdPercent);
1579
}
1580
1581
// Create the hot card cache.
1582
_hot_card_cache = new G1HotCardCache(this);
1583
1584
// Create space mappers.
1585
size_t page_size = heap_rs.page_size();
1586
G1RegionToSpaceMapper* heap_storage =
1587
G1RegionToSpaceMapper::create_mapper(heap_rs,
1588
heap_rs.size(),
1589
page_size,
1590
HeapRegion::GrainBytes,
1591
1,
1592
mtJavaHeap);
1593
if(heap_storage == NULL) {
1594
vm_shutdown_during_initialization("Could not initialize G1 heap");
1595
return JNI_ERR;
1596
}
1597
1598
os::trace_page_sizes("Heap",
1599
MinHeapSize,
1600
reserved_byte_size,
1601
page_size,
1602
heap_rs.base(),
1603
heap_rs.size());
1604
heap_storage->set_mapping_changed_listener(&_listener);
1605
1606
// Create storage for the BOT, card table, card counts table (hot card cache) and the bitmaps.
1607
G1RegionToSpaceMapper* bot_storage =
1608
create_aux_memory_mapper("Block Offset Table",
1609
G1BlockOffsetTable::compute_size(heap_rs.size() / HeapWordSize),
1610
G1BlockOffsetTable::heap_map_factor());
1611
1612
G1RegionToSpaceMapper* cardtable_storage =
1613
create_aux_memory_mapper("Card Table",
1614
G1CardTable::compute_size(heap_rs.size() / HeapWordSize),
1615
G1CardTable::heap_map_factor());
1616
1617
G1RegionToSpaceMapper* card_counts_storage =
1618
create_aux_memory_mapper("Card Counts Table",
1619
G1CardCounts::compute_size(heap_rs.size() / HeapWordSize),
1620
G1CardCounts::heap_map_factor());
1621
1622
size_t bitmap_size = G1CMBitMap::compute_size(heap_rs.size());
1623
G1RegionToSpaceMapper* prev_bitmap_storage =
1624
create_aux_memory_mapper("Prev Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());
1625
G1RegionToSpaceMapper* next_bitmap_storage =
1626
create_aux_memory_mapper("Next Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());
1627
1628
_hrm.initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage);
1629
_card_table->initialize(cardtable_storage);
1630
1631
// Do later initialization work for concurrent refinement.
1632
_hot_card_cache->initialize(card_counts_storage);
1633
1634
// 6843694 - ensure that the maximum region index can fit
1635
// in the remembered set structures.
1636
const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
1637
guarantee((max_reserved_regions() - 1) <= max_region_idx, "too many regions");
1638
1639
// The G1FromCardCache reserves card with value 0 as "invalid", so the heap must not
1640
// start within the first card.
1641
guarantee(heap_rs.base() >= (char*)G1CardTable::card_size, "Java heap must not start within the first card.");
1642
G1FromCardCache::initialize(max_reserved_regions());
1643
// Also create a G1 rem set.
1644
_rem_set = new G1RemSet(this, _card_table, _hot_card_cache);
1645
_rem_set->initialize(max_reserved_regions());
1646
1647
size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
1648
guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
1649
guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,
1650
"too many cards per region");
1651
1652
FreeRegionList::set_unrealistically_long_length(max_regions() + 1);
1653
1654
_bot = new G1BlockOffsetTable(reserved(), bot_storage);
1655
1656
{
1657
size_t granularity = HeapRegion::GrainBytes;
1658
1659
_region_attr.initialize(reserved(), granularity);
1660
_humongous_reclaim_candidates.initialize(reserved(), granularity);
1661
}
1662
1663
_workers = new WorkGang("GC Thread", ParallelGCThreads,
1664
true /* are_GC_task_threads */,
1665
false /* are_ConcurrentGC_threads */);
1666
if (_workers == NULL) {
1667
return JNI_ENOMEM;
1668
}
1669
_workers->initialize_workers();
1670
1671
_numa->set_region_info(HeapRegion::GrainBytes, page_size);
1672
1673
// Create the G1ConcurrentMark data structure and thread.
1674
// (Must do this late, so that "max_[reserved_]regions" is defined.)
1675
_cm = new G1ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage);
1676
_cm_thread = _cm->cm_thread();
1677
1678
// Now expand into the initial heap size.
1679
if (!expand(init_byte_size, _workers)) {
1680
vm_shutdown_during_initialization("Failed to allocate initial heap.");
1681
return JNI_ENOMEM;
1682
}
1683
1684
// Perform any initialization actions delegated to the policy.
1685
policy()->init(this, &_collection_set);
1686
1687
jint ecode = initialize_concurrent_refinement();
1688
if (ecode != JNI_OK) {
1689
return ecode;
1690
}
1691
1692
ecode = initialize_service_thread();
1693
if (ecode != JNI_OK) {
1694
return ecode;
1695
}
1696
1697
// Initialize and schedule sampling task on service thread.
1698
_rem_set->initialize_sampling_task(service_thread());
1699
1700
// Create and schedule the periodic gc task on the service thread.
1701
_periodic_gc_task = new G1PeriodicGCTask("Periodic GC Task");
1702
_service_thread->register_task(_periodic_gc_task);
1703
1704
{
1705
G1DirtyCardQueueSet& dcqs = G1BarrierSet::dirty_card_queue_set();
1706
dcqs.set_process_cards_threshold(concurrent_refine()->yellow_zone());
1707
dcqs.set_max_cards(concurrent_refine()->red_zone());
1708
}
1709
1710
// Here we allocate the dummy HeapRegion that is required by the
1711
// G1AllocRegion class.
1712
HeapRegion* dummy_region = _hrm.get_dummy_region();
1713
1714
// We'll re-use the same region whether the alloc region will
1715
// require BOT updates or not and, if it doesn't, then a non-young
1716
// region will complain that it cannot support allocations without
1717
// BOT updates. So we'll tag the dummy region as eden to avoid that.
1718
dummy_region->set_eden();
1719
// Make sure it's full.
1720
dummy_region->set_top(dummy_region->end());
1721
G1AllocRegion::setup(this, dummy_region);
1722
1723
_allocator->init_mutator_alloc_regions();
1724
1725
// Do create of the monitoring and management support so that
1726
// values in the heap have been properly initialized.
1727
_g1mm = new G1MonitoringSupport(this);
1728
1729
_preserved_marks_set.init(ParallelGCThreads);
1730
1731
_collection_set.initialize(max_reserved_regions());
1732
1733
G1InitLogger::print();
1734
1735
return JNI_OK;
1736
}
1737
1738
void G1CollectedHeap::stop() {
1739
// Stop all concurrent threads. We do this to make sure these threads
1740
// do not continue to execute and access resources (e.g. logging)
1741
// that are destroyed during shutdown.
1742
_cr->stop();
1743
_service_thread->stop();
1744
_cm_thread->stop();
1745
}
1746
1747
void G1CollectedHeap::safepoint_synchronize_begin() {
1748
SuspendibleThreadSet::synchronize();
1749
}
1750
1751
void G1CollectedHeap::safepoint_synchronize_end() {
1752
SuspendibleThreadSet::desynchronize();
1753
}
1754
1755
void G1CollectedHeap::post_initialize() {
1756
CollectedHeap::post_initialize();
1757
ref_processing_init();
1758
}
1759
1760
void G1CollectedHeap::ref_processing_init() {
1761
// Reference processing in G1 currently works as follows:
1762
//
1763
// * There are two reference processor instances. One is
1764
// used to record and process discovered references
1765
// during concurrent marking; the other is used to
1766
// record and process references during STW pauses
1767
// (both full and incremental).
1768
// * Both ref processors need to 'span' the entire heap as
1769
// the regions in the collection set may be dotted around.
1770
//
1771
// * For the concurrent marking ref processor:
1772
// * Reference discovery is enabled at concurrent start.
1773
// * Reference discovery is disabled and the discovered
1774
// references processed etc during remarking.
1775
// * Reference discovery is MT (see below).
1776
// * Reference discovery requires a barrier (see below).
1777
// * Reference processing may or may not be MT
1778
// (depending on the value of ParallelRefProcEnabled
1779
// and ParallelGCThreads).
1780
// * A full GC disables reference discovery by the CM
1781
// ref processor and abandons any entries on it's
1782
// discovered lists.
1783
//
1784
// * For the STW processor:
1785
// * Non MT discovery is enabled at the start of a full GC.
1786
// * Processing and enqueueing during a full GC is non-MT.
1787
// * During a full GC, references are processed after marking.
1788
//
1789
// * Discovery (may or may not be MT) is enabled at the start
1790
// of an incremental evacuation pause.
1791
// * References are processed near the end of a STW evacuation pause.
1792
// * For both types of GC:
1793
// * Discovery is atomic - i.e. not concurrent.
1794
// * Reference discovery will not need a barrier.
1795
1796
// Concurrent Mark ref processor
1797
_ref_processor_cm =
1798
new ReferenceProcessor(&_is_subject_to_discovery_cm,
1799
ParallelGCThreads, // degree of mt processing
1800
(ParallelGCThreads > 1) || (ConcGCThreads > 1), // mt discovery
1801
MAX2(ParallelGCThreads, ConcGCThreads), // degree of mt discovery
1802
false, // Reference discovery is not atomic
1803
&_is_alive_closure_cm, // is alive closure
1804
true); // allow changes to number of processing threads
1805
1806
// STW ref processor
1807
_ref_processor_stw =
1808
new ReferenceProcessor(&_is_subject_to_discovery_stw,
1809
ParallelGCThreads, // degree of mt processing
1810
(ParallelGCThreads > 1), // mt discovery
1811
ParallelGCThreads, // degree of mt discovery
1812
true, // Reference discovery is atomic
1813
&_is_alive_closure_stw, // is alive closure
1814
true); // allow changes to number of processing threads
1815
}
1816
1817
SoftRefPolicy* G1CollectedHeap::soft_ref_policy() {
1818
return &_soft_ref_policy;
1819
}
1820
1821
size_t G1CollectedHeap::capacity() const {
1822
return _hrm.length() * HeapRegion::GrainBytes;
1823
}
1824
1825
size_t G1CollectedHeap::unused_committed_regions_in_bytes() const {
1826
return _hrm.total_free_bytes();
1827
}
1828
1829
void G1CollectedHeap::iterate_hcc_closure(G1CardTableEntryClosure* cl, uint worker_id) {
1830
_hot_card_cache->drain(cl, worker_id);
1831
}
1832
1833
// Computes the sum of the storage used by the various regions.
1834
size_t G1CollectedHeap::used() const {
1835
size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions();
1836
if (_archive_allocator != NULL) {
1837
result += _archive_allocator->used();
1838
}
1839
return result;
1840
}
1841
1842
size_t G1CollectedHeap::used_unlocked() const {
1843
return _summary_bytes_used;
1844
}
1845
1846
class SumUsedClosure: public HeapRegionClosure {
1847
size_t _used;
1848
public:
1849
SumUsedClosure() : _used(0) {}
1850
bool do_heap_region(HeapRegion* r) {
1851
_used += r->used();
1852
return false;
1853
}
1854
size_t result() { return _used; }
1855
};
1856
1857
size_t G1CollectedHeap::recalculate_used() const {
1858
SumUsedClosure blk;
1859
heap_region_iterate(&blk);
1860
return blk.result();
1861
}
1862
1863
bool G1CollectedHeap::is_user_requested_concurrent_full_gc(GCCause::Cause cause) {
1864
switch (cause) {
1865
case GCCause::_java_lang_system_gc: return ExplicitGCInvokesConcurrent;
1866
case GCCause::_dcmd_gc_run: return ExplicitGCInvokesConcurrent;
1867
case GCCause::_wb_conc_mark: return true;
1868
default : return false;
1869
}
1870
}
1871
1872
bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
1873
switch (cause) {
1874
case GCCause::_g1_humongous_allocation: return true;
1875
case GCCause::_g1_periodic_collection: return G1PeriodicGCInvokesConcurrent;
1876
case GCCause::_wb_breakpoint: return true;
1877
default: return is_user_requested_concurrent_full_gc(cause);
1878
}
1879
}
1880
1881
bool G1CollectedHeap::should_upgrade_to_full_gc(GCCause::Cause cause) {
1882
if (should_do_concurrent_full_gc(_gc_cause)) {
1883
return false;
1884
} else if (has_regions_left_for_allocation()) {
1885
return false;
1886
} else {
1887
return true;
1888
}
1889
}
1890
1891
#ifndef PRODUCT
1892
void G1CollectedHeap::allocate_dummy_regions() {
1893
// Let's fill up most of the region
1894
size_t word_size = HeapRegion::GrainWords - 1024;
1895
// And as a result the region we'll allocate will be humongous.
1896
guarantee(is_humongous(word_size), "sanity");
1897
1898
// _filler_array_max_size is set to humongous object threshold
1899
// but temporarily change it to use CollectedHeap::fill_with_object().
1900
AutoModifyRestore<size_t> temporarily(_filler_array_max_size, word_size);
1901
1902
for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {
1903
// Let's use the existing mechanism for the allocation
1904
HeapWord* dummy_obj = humongous_obj_allocate(word_size);
1905
if (dummy_obj != NULL) {
1906
MemRegion mr(dummy_obj, word_size);
1907
CollectedHeap::fill_with_object(mr);
1908
} else {
1909
// If we can't allocate once, we probably cannot allocate
1910
// again. Let's get out of the loop.
1911
break;
1912
}
1913
}
1914
}
1915
#endif // !PRODUCT
1916
1917
void G1CollectedHeap::increment_old_marking_cycles_started() {
1918
assert(_old_marking_cycles_started == _old_marking_cycles_completed ||
1919
_old_marking_cycles_started == _old_marking_cycles_completed + 1,
1920
"Wrong marking cycle count (started: %d, completed: %d)",
1921
_old_marking_cycles_started, _old_marking_cycles_completed);
1922
1923
_old_marking_cycles_started++;
1924
}
1925
1926
void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent,
1927
bool whole_heap_examined) {
1928
MonitorLocker ml(G1OldGCCount_lock, Mutex::_no_safepoint_check_flag);
1929
1930
// We assume that if concurrent == true, then the caller is a
1931
// concurrent thread that was joined the Suspendible Thread
1932
// Set. If there's ever a cheap way to check this, we should add an
1933
// assert here.
1934
1935
// Given that this method is called at the end of a Full GC or of a
1936
// concurrent cycle, and those can be nested (i.e., a Full GC can
1937
// interrupt a concurrent cycle), the number of full collections
1938
// completed should be either one (in the case where there was no
1939
// nesting) or two (when a Full GC interrupted a concurrent cycle)
1940
// behind the number of full collections started.
1941
1942
// This is the case for the inner caller, i.e. a Full GC.
1943
assert(concurrent ||
1944
(_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||
1945
(_old_marking_cycles_started == _old_marking_cycles_completed + 2),
1946
"for inner caller (Full GC): _old_marking_cycles_started = %u "
1947
"is inconsistent with _old_marking_cycles_completed = %u",
1948
_old_marking_cycles_started, _old_marking_cycles_completed);
1949
1950
// This is the case for the outer caller, i.e. the concurrent cycle.
1951
assert(!concurrent ||
1952
(_old_marking_cycles_started == _old_marking_cycles_completed + 1),
1953
"for outer caller (concurrent cycle): "
1954
"_old_marking_cycles_started = %u "
1955
"is inconsistent with _old_marking_cycles_completed = %u",
1956
_old_marking_cycles_started, _old_marking_cycles_completed);
1957
1958
_old_marking_cycles_completed += 1;
1959
if (whole_heap_examined) {
1960
// Signal that we have completed a visit to all live objects.
1961
record_whole_heap_examined_timestamp();
1962
}
1963
1964
// We need to clear the "in_progress" flag in the CM thread before
1965
// we wake up any waiters (especially when ExplicitInvokesConcurrent
1966
// is set) so that if a waiter requests another System.gc() it doesn't
1967
// incorrectly see that a marking cycle is still in progress.
1968
if (concurrent) {
1969
_cm_thread->set_idle();
1970
}
1971
1972
// Notify threads waiting in System.gc() (with ExplicitGCInvokesConcurrent)
1973
// for a full GC to finish that their wait is over.
1974
ml.notify_all();
1975
}
1976
1977
void G1CollectedHeap::collect(GCCause::Cause cause) {
1978
try_collect(cause);
1979
}
1980
1981
// Return true if (x < y) with allowance for wraparound.
1982
static bool gc_counter_less_than(uint x, uint y) {
1983
return (x - y) > (UINT_MAX/2);
1984
}
1985
1986
// LOG_COLLECT_CONCURRENTLY(cause, msg, args...)
1987
// Macro so msg printing is format-checked.
1988
#define LOG_COLLECT_CONCURRENTLY(cause, ...) \
1989
do { \
1990
LogTarget(Trace, gc) LOG_COLLECT_CONCURRENTLY_lt; \
1991
if (LOG_COLLECT_CONCURRENTLY_lt.is_enabled()) { \
1992
ResourceMark rm; /* For thread name. */ \
1993
LogStream LOG_COLLECT_CONCURRENTLY_s(&LOG_COLLECT_CONCURRENTLY_lt); \
1994
LOG_COLLECT_CONCURRENTLY_s.print("%s: Try Collect Concurrently (%s): ", \
1995
Thread::current()->name(), \
1996
GCCause::to_string(cause)); \
1997
LOG_COLLECT_CONCURRENTLY_s.print(__VA_ARGS__); \
1998
} \
1999
} while (0)
2000
2001
#define LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, result) \
2002
LOG_COLLECT_CONCURRENTLY(cause, "complete %s", BOOL_TO_STR(result))
2003
2004
bool G1CollectedHeap::try_collect_concurrently(GCCause::Cause cause,
2005
uint gc_counter,
2006
uint old_marking_started_before) {
2007
assert_heap_not_locked();
2008
assert(should_do_concurrent_full_gc(cause),
2009
"Non-concurrent cause %s", GCCause::to_string(cause));
2010
2011
for (uint i = 1; true; ++i) {
2012
// Try to schedule concurrent start evacuation pause that will
2013
// start a concurrent cycle.
2014
LOG_COLLECT_CONCURRENTLY(cause, "attempt %u", i);
2015
VM_G1TryInitiateConcMark op(gc_counter,
2016
cause,
2017
policy()->max_pause_time_ms());
2018
VMThread::execute(&op);
2019
2020
// Request is trivially finished.
2021
if (cause == GCCause::_g1_periodic_collection) {
2022
LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, op.gc_succeeded());
2023
return op.gc_succeeded();
2024
}
2025
2026
// If VMOp skipped initiating concurrent marking cycle because
2027
// we're terminating, then we're done.
2028
if (op.terminating()) {
2029
LOG_COLLECT_CONCURRENTLY(cause, "skipped: terminating");
2030
return false;
2031
}
2032
2033
// Lock to get consistent set of values.
2034
uint old_marking_started_after;
2035
uint old_marking_completed_after;
2036
{
2037
MutexLocker ml(Heap_lock);
2038
// Update gc_counter for retrying VMOp if needed. Captured here to be
2039
// consistent with the values we use below for termination tests. If
2040
// a retry is needed after a possible wait, and another collection
2041
// occurs in the meantime, it will cause our retry to be skipped and
2042
// we'll recheck for termination with updated conditions from that
2043
// more recent collection. That's what we want, rather than having
2044
// our retry possibly perform an unnecessary collection.
2045
gc_counter = total_collections();
2046
old_marking_started_after = _old_marking_cycles_started;
2047
old_marking_completed_after = _old_marking_cycles_completed;
2048
}
2049
2050
if (cause == GCCause::_wb_breakpoint) {
2051
if (op.gc_succeeded()) {
2052
LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2053
return true;
2054
}
2055
// When _wb_breakpoint there can't be another cycle or deferred.
2056
assert(!op.cycle_already_in_progress(), "invariant");
2057
assert(!op.whitebox_attached(), "invariant");
2058
// Concurrent cycle attempt might have been cancelled by some other
2059
// collection, so retry. Unlike other cases below, we want to retry
2060
// even if cancelled by a STW full collection, because we really want
2061
// to start a concurrent cycle.
2062
if (old_marking_started_before != old_marking_started_after) {
2063
LOG_COLLECT_CONCURRENTLY(cause, "ignoring STW full GC");
2064
old_marking_started_before = old_marking_started_after;
2065
}
2066
} else if (!GCCause::is_user_requested_gc(cause)) {
2067
// For an "automatic" (not user-requested) collection, we just need to
2068
// ensure that progress is made.
2069
//
2070
// Request is finished if any of
2071
// (1) the VMOp successfully performed a GC,
2072
// (2) a concurrent cycle was already in progress,
2073
// (3) whitebox is controlling concurrent cycles,
2074
// (4) a new cycle was started (by this thread or some other), or
2075
// (5) a Full GC was performed.
2076
// Cases (4) and (5) are detected together by a change to
2077
// _old_marking_cycles_started.
2078
//
2079
// Note that (1) does not imply (4). If we're still in the mixed
2080
// phase of an earlier concurrent collection, the request to make the
2081
// collection a concurrent start won't be honored. If we don't check for
2082
// both conditions we'll spin doing back-to-back collections.
2083
if (op.gc_succeeded() ||
2084
op.cycle_already_in_progress() ||
2085
op.whitebox_attached() ||
2086
(old_marking_started_before != old_marking_started_after)) {
2087
LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2088
return true;
2089
}
2090
} else { // User-requested GC.
2091
// For a user-requested collection, we want to ensure that a complete
2092
// full collection has been performed before returning, but without
2093
// waiting for more than needed.
2094
2095
// For user-requested GCs (unlike non-UR), a successful VMOp implies a
2096
// new cycle was started. That's good, because it's not clear what we
2097
// should do otherwise. Trying again just does back to back GCs.
2098
// Can't wait for someone else to start a cycle. And returning fails
2099
// to meet the goal of ensuring a full collection was performed.
2100
assert(!op.gc_succeeded() ||
2101
(old_marking_started_before != old_marking_started_after),
2102
"invariant: succeeded %s, started before %u, started after %u",
2103
BOOL_TO_STR(op.gc_succeeded()),
2104
old_marking_started_before, old_marking_started_after);
2105
2106
// Request is finished if a full collection (concurrent or stw)
2107
// was started after this request and has completed, e.g.
2108
// started_before < completed_after.
2109
if (gc_counter_less_than(old_marking_started_before,
2110
old_marking_completed_after)) {
2111
LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2112
return true;
2113
}
2114
2115
if (old_marking_started_after != old_marking_completed_after) {
2116
// If there is an in-progress cycle (possibly started by us), then
2117
// wait for that cycle to complete, e.g.
2118
// while completed_now < started_after.
2119
LOG_COLLECT_CONCURRENTLY(cause, "wait");
2120
MonitorLocker ml(G1OldGCCount_lock);
2121
while (gc_counter_less_than(_old_marking_cycles_completed,
2122
old_marking_started_after)) {
2123
ml.wait();
2124
}
2125
// Request is finished if the collection we just waited for was
2126
// started after this request.
2127
if (old_marking_started_before != old_marking_started_after) {
2128
LOG_COLLECT_CONCURRENTLY(cause, "complete after wait");
2129
return true;
2130
}
2131
}
2132
2133
// If VMOp was successful then it started a new cycle that the above
2134
// wait &etc should have recognized as finishing this request. This
2135
// differs from a non-user-request, where gc_succeeded does not imply
2136
// a new cycle was started.
2137
assert(!op.gc_succeeded(), "invariant");
2138
2139
if (op.cycle_already_in_progress()) {
2140
// If VMOp failed because a cycle was already in progress, it
2141
// is now complete. But it didn't finish this user-requested
2142
// GC, so try again.
2143
LOG_COLLECT_CONCURRENTLY(cause, "retry after in-progress");
2144
continue;
2145
} else if (op.whitebox_attached()) {
2146
// If WhiteBox wants control, wait for notification of a state
2147
// change in the controller, then try again. Don't wait for
2148
// release of control, since collections may complete while in
2149
// control. Note: This won't recognize a STW full collection
2150
// while waiting; we can't wait on multiple monitors.
2151
LOG_COLLECT_CONCURRENTLY(cause, "whitebox control stall");
2152
MonitorLocker ml(ConcurrentGCBreakpoints::monitor());
2153
if (ConcurrentGCBreakpoints::is_controlled()) {
2154
ml.wait();
2155
}
2156
continue;
2157
}
2158
}
2159
2160
// Collection failed and should be retried.
2161
assert(op.transient_failure(), "invariant");
2162
2163
if (GCLocker::is_active_and_needs_gc()) {
2164
// If GCLocker is active, wait until clear before retrying.
2165
LOG_COLLECT_CONCURRENTLY(cause, "gc-locker stall");
2166
GCLocker::stall_until_clear();
2167
}
2168
2169
LOG_COLLECT_CONCURRENTLY(cause, "retry");
2170
}
2171
}
2172
2173
bool G1CollectedHeap::try_collect(GCCause::Cause cause) {
2174
assert_heap_not_locked();
2175
2176
// Lock to get consistent set of values.
2177
uint gc_count_before;
2178
uint full_gc_count_before;
2179
uint old_marking_started_before;
2180
{
2181
MutexLocker ml(Heap_lock);
2182
gc_count_before = total_collections();
2183
full_gc_count_before = total_full_collections();
2184
old_marking_started_before = _old_marking_cycles_started;
2185
}
2186
2187
if (should_do_concurrent_full_gc(cause)) {
2188
return try_collect_concurrently(cause,
2189
gc_count_before,
2190
old_marking_started_before);
2191
} else if (GCLocker::should_discard(cause, gc_count_before)) {
2192
// Indicate failure to be consistent with VMOp failure due to
2193
// another collection slipping in after our gc_count but before
2194
// our request is processed.
2195
return false;
2196
} else if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc
2197
DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
2198
2199
// Schedule a standard evacuation pause. We're setting word_size
2200
// to 0 which means that we are not requesting a post-GC allocation.
2201
VM_G1CollectForAllocation op(0, /* word_size */
2202
gc_count_before,
2203
cause,
2204
policy()->max_pause_time_ms());
2205
VMThread::execute(&op);
2206
return op.gc_succeeded();
2207
} else {
2208
// Schedule a Full GC.
2209
VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause);
2210
VMThread::execute(&op);
2211
return op.gc_succeeded();
2212
}
2213
}
2214
2215
bool G1CollectedHeap::is_in(const void* p) const {
2216
return is_in_reserved(p) && _hrm.is_available(addr_to_region((HeapWord*)p));
2217
}
2218
2219
// Iteration functions.
2220
2221
// Iterates an ObjectClosure over all objects within a HeapRegion.
2222
2223
class IterateObjectClosureRegionClosure: public HeapRegionClosure {
2224
ObjectClosure* _cl;
2225
public:
2226
IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
2227
bool do_heap_region(HeapRegion* r) {
2228
if (!r->is_continues_humongous()) {
2229
r->object_iterate(_cl);
2230
}
2231
return false;
2232
}
2233
};
2234
2235
void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
2236
IterateObjectClosureRegionClosure blk(cl);
2237
heap_region_iterate(&blk);
2238
}
2239
2240
class G1ParallelObjectIterator : public ParallelObjectIterator {
2241
private:
2242
G1CollectedHeap* _heap;
2243
HeapRegionClaimer _claimer;
2244
2245
public:
2246
G1ParallelObjectIterator(uint thread_num) :
2247
_heap(G1CollectedHeap::heap()),
2248
_claimer(thread_num == 0 ? G1CollectedHeap::heap()->workers()->active_workers() : thread_num) {}
2249
2250
virtual void object_iterate(ObjectClosure* cl, uint worker_id) {
2251
_heap->object_iterate_parallel(cl, worker_id, &_claimer);
2252
}
2253
};
2254
2255
ParallelObjectIterator* G1CollectedHeap::parallel_object_iterator(uint thread_num) {
2256
return new G1ParallelObjectIterator(thread_num);
2257
}
2258
2259
void G1CollectedHeap::object_iterate_parallel(ObjectClosure* cl, uint worker_id, HeapRegionClaimer* claimer) {
2260
IterateObjectClosureRegionClosure blk(cl);
2261
heap_region_par_iterate_from_worker_offset(&blk, claimer, worker_id);
2262
}
2263
2264
void G1CollectedHeap::keep_alive(oop obj) {
2265
G1BarrierSet::enqueue(obj);
2266
}
2267
2268
void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
2269
_hrm.iterate(cl);
2270
}
2271
2272
void G1CollectedHeap::heap_region_par_iterate_from_worker_offset(HeapRegionClosure* cl,
2273
HeapRegionClaimer *hrclaimer,
2274
uint worker_id) const {
2275
_hrm.par_iterate(cl, hrclaimer, hrclaimer->offset_for_worker(worker_id));
2276
}
2277
2278
void G1CollectedHeap::heap_region_par_iterate_from_start(HeapRegionClosure* cl,
2279
HeapRegionClaimer *hrclaimer) const {
2280
_hrm.par_iterate(cl, hrclaimer, 0);
2281
}
2282
2283
void G1CollectedHeap::collection_set_iterate_all(HeapRegionClosure* cl) {
2284
_collection_set.iterate(cl);
2285
}
2286
2287
void G1CollectedHeap::collection_set_par_iterate_all(HeapRegionClosure* cl, HeapRegionClaimer* hr_claimer, uint worker_id) {
2288
_collection_set.par_iterate(cl, hr_claimer, worker_id, workers()->active_workers());
2289
}
2290
2291
void G1CollectedHeap::collection_set_iterate_increment_from(HeapRegionClosure *cl, HeapRegionClaimer* hr_claimer, uint worker_id) {
2292
_collection_set.iterate_incremental_part_from(cl, hr_claimer, worker_id, workers()->active_workers());
2293
}
2294
2295
HeapWord* G1CollectedHeap::block_start(const void* addr) const {
2296
HeapRegion* hr = heap_region_containing(addr);
2297
return hr->block_start(addr);
2298
}
2299
2300
bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
2301
HeapRegion* hr = heap_region_containing(addr);
2302
return hr->block_is_obj(addr);
2303
}
2304
2305
size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
2306
return (_policy->young_list_target_length() - _survivor.length()) * HeapRegion::GrainBytes;
2307
}
2308
2309
size_t G1CollectedHeap::tlab_used(Thread* ignored) const {
2310
return _eden.length() * HeapRegion::GrainBytes;
2311
}
2312
2313
// For G1 TLABs should not contain humongous objects, so the maximum TLAB size
2314
// must be equal to the humongous object limit.
2315
size_t G1CollectedHeap::max_tlab_size() const {
2316
return align_down(_humongous_object_threshold_in_words, MinObjAlignment);
2317
}
2318
2319
size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
2320
return _allocator->unsafe_max_tlab_alloc();
2321
}
2322
2323
size_t G1CollectedHeap::max_capacity() const {
2324
return max_regions() * HeapRegion::GrainBytes;
2325
}
2326
2327
void G1CollectedHeap::prepare_for_verify() {
2328
_verifier->prepare_for_verify();
2329
}
2330
2331
void G1CollectedHeap::verify(VerifyOption vo) {
2332
_verifier->verify(vo);
2333
}
2334
2335
bool G1CollectedHeap::supports_concurrent_gc_breakpoints() const {
2336
return true;
2337
}
2338
2339
bool G1CollectedHeap::is_archived_object(oop object) const {
2340
return object != NULL && heap_region_containing(object)->is_archive();
2341
}
2342
2343
class PrintRegionClosure: public HeapRegionClosure {
2344
outputStream* _st;
2345
public:
2346
PrintRegionClosure(outputStream* st) : _st(st) {}
2347
bool do_heap_region(HeapRegion* r) {
2348
r->print_on(_st);
2349
return false;
2350
}
2351
};
2352
2353
bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2354
const HeapRegion* hr,
2355
const VerifyOption vo) const {
2356
switch (vo) {
2357
case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);
2358
case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);
2359
case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj, hr);
2360
default: ShouldNotReachHere();
2361
}
2362
return false; // keep some compilers happy
2363
}
2364
2365
bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2366
const VerifyOption vo) const {
2367
switch (vo) {
2368
case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);
2369
case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);
2370
case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj);
2371
default: ShouldNotReachHere();
2372
}
2373
return false; // keep some compilers happy
2374
}
2375
2376
void G1CollectedHeap::print_heap_regions() const {
2377
LogTarget(Trace, gc, heap, region) lt;
2378
if (lt.is_enabled()) {
2379
LogStream ls(lt);
2380
print_regions_on(&ls);
2381
}
2382
}
2383
2384
void G1CollectedHeap::print_on(outputStream* st) const {
2385
size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();
2386
st->print(" %-20s", "garbage-first heap");
2387
st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
2388
capacity()/K, heap_used/K);
2389
st->print(" [" PTR_FORMAT ", " PTR_FORMAT ")",
2390
p2i(_hrm.reserved().start()),
2391
p2i(_hrm.reserved().end()));
2392
st->cr();
2393
st->print(" region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);
2394
uint young_regions = young_regions_count();
2395
st->print("%u young (" SIZE_FORMAT "K), ", young_regions,
2396
(size_t) young_regions * HeapRegion::GrainBytes / K);
2397
uint survivor_regions = survivor_regions_count();
2398
st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,
2399
(size_t) survivor_regions * HeapRegion::GrainBytes / K);
2400
st->cr();
2401
if (_numa->is_enabled()) {
2402
uint num_nodes = _numa->num_active_nodes();
2403
st->print(" remaining free region(s) on each NUMA node: ");
2404
const int* node_ids = _numa->node_ids();
2405
for (uint node_index = 0; node_index < num_nodes; node_index++) {
2406
uint num_free_regions = _hrm.num_free_regions(node_index);
2407
st->print("%d=%u ", node_ids[node_index], num_free_regions);
2408
}
2409
st->cr();
2410
}
2411
MetaspaceUtils::print_on(st);
2412
}
2413
2414
void G1CollectedHeap::print_regions_on(outputStream* st) const {
2415
st->print_cr("Heap Regions: E=young(eden), S=young(survivor), O=old, "
2416
"HS=humongous(starts), HC=humongous(continues), "
2417
"CS=collection set, F=free, "
2418
"OA=open archive, CA=closed archive, "
2419
"TAMS=top-at-mark-start (previous, next)");
2420
PrintRegionClosure blk(st);
2421
heap_region_iterate(&blk);
2422
}
2423
2424
void G1CollectedHeap::print_extended_on(outputStream* st) const {
2425
print_on(st);
2426
2427
// Print the per-region information.
2428
st->cr();
2429
print_regions_on(st);
2430
}
2431
2432
void G1CollectedHeap::print_on_error(outputStream* st) const {
2433
this->CollectedHeap::print_on_error(st);
2434
2435
if (_cm != NULL) {
2436
st->cr();
2437
_cm->print_on_error(st);
2438
}
2439
}
2440
2441
void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
2442
workers()->threads_do(tc);
2443
tc->do_thread(_cm_thread);
2444
_cm->threads_do(tc);
2445
_cr->threads_do(tc);
2446
tc->do_thread(_service_thread);
2447
}
2448
2449
void G1CollectedHeap::print_tracing_info() const {
2450
rem_set()->print_summary_info();
2451
concurrent_mark()->print_summary_info();
2452
}
2453
2454
#ifndef PRODUCT
2455
// Helpful for debugging RSet issues.
2456
2457
class PrintRSetsClosure : public HeapRegionClosure {
2458
private:
2459
const char* _msg;
2460
size_t _occupied_sum;
2461
2462
public:
2463
bool do_heap_region(HeapRegion* r) {
2464
HeapRegionRemSet* hrrs = r->rem_set();
2465
size_t occupied = hrrs->occupied();
2466
_occupied_sum += occupied;
2467
2468
tty->print_cr("Printing RSet for region " HR_FORMAT, HR_FORMAT_PARAMS(r));
2469
if (occupied == 0) {
2470
tty->print_cr(" RSet is empty");
2471
} else {
2472
hrrs->print();
2473
}
2474
tty->print_cr("----------");
2475
return false;
2476
}
2477
2478
PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
2479
tty->cr();
2480
tty->print_cr("========================================");
2481
tty->print_cr("%s", msg);
2482
tty->cr();
2483
}
2484
2485
~PrintRSetsClosure() {
2486
tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum);
2487
tty->print_cr("========================================");
2488
tty->cr();
2489
}
2490
};
2491
2492
void G1CollectedHeap::print_cset_rsets() {
2493
PrintRSetsClosure cl("Printing CSet RSets");
2494
collection_set_iterate_all(&cl);
2495
}
2496
2497
void G1CollectedHeap::print_all_rsets() {
2498
PrintRSetsClosure cl("Printing All RSets");;
2499
heap_region_iterate(&cl);
2500
}
2501
#endif // PRODUCT
2502
2503
bool G1CollectedHeap::print_location(outputStream* st, void* addr) const {
2504
return BlockLocationPrinter<G1CollectedHeap>::print_location(st, addr);
2505
}
2506
2507
G1HeapSummary G1CollectedHeap::create_g1_heap_summary() {
2508
2509
size_t eden_used_bytes = _eden.used_bytes();
2510
size_t survivor_used_bytes = _survivor.used_bytes();
2511
size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();
2512
2513
size_t eden_capacity_bytes =
2514
(policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes;
2515
2516
VirtualSpaceSummary heap_summary = create_heap_space_summary();
2517
return G1HeapSummary(heap_summary, heap_used, eden_used_bytes,
2518
eden_capacity_bytes, survivor_used_bytes, num_regions());
2519
}
2520
2521
G1EvacSummary G1CollectedHeap::create_g1_evac_summary(G1EvacStats* stats) {
2522
return G1EvacSummary(stats->allocated(), stats->wasted(), stats->undo_wasted(),
2523
stats->unused(), stats->used(), stats->region_end_waste(),
2524
stats->regions_filled(), stats->direct_allocated(),
2525
stats->failure_used(), stats->failure_waste());
2526
}
2527
2528
void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {
2529
const G1HeapSummary& heap_summary = create_g1_heap_summary();
2530
gc_tracer->report_gc_heap_summary(when, heap_summary);
2531
2532
const MetaspaceSummary& metaspace_summary = create_metaspace_summary();
2533
gc_tracer->report_metaspace_summary(when, metaspace_summary);
2534
}
2535
2536
void G1CollectedHeap::gc_prologue(bool full) {
2537
assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
2538
2539
// This summary needs to be printed before incrementing total collections.
2540
rem_set()->print_periodic_summary_info("Before GC RS summary", total_collections());
2541
2542
// Update common counters.
2543
increment_total_collections(full /* full gc */);
2544
if (full || collector_state()->in_concurrent_start_gc()) {
2545
increment_old_marking_cycles_started();
2546
}
2547
2548
// Fill TLAB's and such
2549
{
2550
Ticks start = Ticks::now();
2551
ensure_parsability(true);
2552
Tickspan dt = Ticks::now() - start;
2553
phase_times()->record_prepare_tlab_time_ms(dt.seconds() * MILLIUNITS);
2554
}
2555
2556
if (!full) {
2557
// Flush dirty card queues to qset, so later phases don't need to account
2558
// for partially filled per-thread queues and such. Not needed for full
2559
// collections, which ignore those logs.
2560
Ticks start = Ticks::now();
2561
G1BarrierSet::dirty_card_queue_set().concatenate_logs();
2562
Tickspan dt = Ticks::now() - start;
2563
phase_times()->record_concatenate_dirty_card_logs_time_ms(dt.seconds() * MILLIUNITS);
2564
}
2565
}
2566
2567
void G1CollectedHeap::gc_epilogue(bool full) {
2568
// Update common counters.
2569
if (full) {
2570
// Update the number of full collections that have been completed.
2571
increment_old_marking_cycles_completed(false /* concurrent */, true /* liveness_completed */);
2572
}
2573
2574
// We are at the end of the GC. Total collections has already been increased.
2575
rem_set()->print_periodic_summary_info("After GC RS summary", total_collections() - 1);
2576
2577
#if COMPILER2_OR_JVMCI
2578
assert(DerivedPointerTable::is_empty(), "derived pointer present");
2579
#endif
2580
2581
double start = os::elapsedTime();
2582
resize_all_tlabs();
2583
phase_times()->record_resize_tlab_time_ms((os::elapsedTime() - start) * 1000.0);
2584
2585
MemoryService::track_memory_usage();
2586
// We have just completed a GC. Update the soft reference
2587
// policy with the new heap occupancy
2588
Universe::heap()->update_capacity_and_used_at_gc();
2589
2590
// Print NUMA statistics.
2591
_numa->print_statistics();
2592
2593
_collection_pause_end = Ticks::now();
2594
}
2595
2596
uint G1CollectedHeap::uncommit_regions(uint region_limit) {
2597
return _hrm.uncommit_inactive_regions(region_limit);
2598
}
2599
2600
bool G1CollectedHeap::has_uncommittable_regions() {
2601
return _hrm.has_inactive_regions();
2602
}
2603
2604
void G1CollectedHeap::uncommit_regions_if_necessary() {
2605
if (has_uncommittable_regions()) {
2606
G1UncommitRegionTask::enqueue();
2607
}
2608
}
2609
2610
void G1CollectedHeap::verify_numa_regions(const char* desc) {
2611
LogTarget(Trace, gc, heap, verify) lt;
2612
2613
if (lt.is_enabled()) {
2614
LogStream ls(lt);
2615
// Iterate all heap regions to print matching between preferred numa id and actual numa id.
2616
G1NodeIndexCheckClosure cl(desc, _numa, &ls);
2617
heap_region_iterate(&cl);
2618
}
2619
}
2620
2621
HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
2622
uint gc_count_before,
2623
bool* succeeded,
2624
GCCause::Cause gc_cause) {
2625
assert_heap_not_locked_and_not_at_safepoint();
2626
VM_G1CollectForAllocation op(word_size,
2627
gc_count_before,
2628
gc_cause,
2629
policy()->max_pause_time_ms());
2630
VMThread::execute(&op);
2631
2632
HeapWord* result = op.result();
2633
bool ret_succeeded = op.prologue_succeeded() && op.gc_succeeded();
2634
assert(result == NULL || ret_succeeded,
2635
"the result should be NULL if the VM did not succeed");
2636
*succeeded = ret_succeeded;
2637
2638
assert_heap_not_locked();
2639
return result;
2640
}
2641
2642
void G1CollectedHeap::start_concurrent_cycle(bool concurrent_operation_is_full_mark) {
2643
assert(!_cm_thread->in_progress(), "Can not start concurrent operation while in progress");
2644
2645
MutexLocker x(CGC_lock, Mutex::_no_safepoint_check_flag);
2646
if (concurrent_operation_is_full_mark) {
2647
_cm->post_concurrent_mark_start();
2648
_cm_thread->start_full_mark();
2649
} else {
2650
_cm->post_concurrent_undo_start();
2651
_cm_thread->start_undo_mark();
2652
}
2653
CGC_lock->notify();
2654
}
2655
2656
bool G1CollectedHeap::is_potential_eager_reclaim_candidate(HeapRegion* r) const {
2657
// We don't nominate objects with many remembered set entries, on
2658
// the assumption that such objects are likely still live.
2659
HeapRegionRemSet* rem_set = r->rem_set();
2660
2661
return G1EagerReclaimHumongousObjectsWithStaleRefs ?
2662
rem_set->occupancy_less_or_equal_than(G1EagerReclaimRemSetThreshold) :
2663
G1EagerReclaimHumongousObjects && rem_set->is_empty();
2664
}
2665
2666
#ifndef PRODUCT
2667
void G1CollectedHeap::verify_region_attr_remset_update() {
2668
class VerifyRegionAttrRemSet : public HeapRegionClosure {
2669
public:
2670
virtual bool do_heap_region(HeapRegion* r) {
2671
G1CollectedHeap* g1h = G1CollectedHeap::heap();
2672
bool const needs_remset_update = g1h->region_attr(r->bottom()).needs_remset_update();
2673
assert(r->rem_set()->is_tracked() == needs_remset_update,
2674
"Region %u remset tracking status (%s) different to region attribute (%s)",
2675
r->hrm_index(), BOOL_TO_STR(r->rem_set()->is_tracked()), BOOL_TO_STR(needs_remset_update));
2676
return false;
2677
}
2678
} cl;
2679
heap_region_iterate(&cl);
2680
}
2681
#endif
2682
2683
class VerifyRegionRemSetClosure : public HeapRegionClosure {
2684
public:
2685
bool do_heap_region(HeapRegion* hr) {
2686
if (!hr->is_archive() && !hr->is_continues_humongous()) {
2687
hr->verify_rem_set();
2688
}
2689
return false;
2690
}
2691
};
2692
2693
uint G1CollectedHeap::num_task_queues() const {
2694
return _task_queues->size();
2695
}
2696
2697
#if TASKQUEUE_STATS
2698
void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
2699
st->print_raw_cr("GC Task Stats");
2700
st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
2701
st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
2702
}
2703
2704
void G1CollectedHeap::print_taskqueue_stats() const {
2705
if (!log_is_enabled(Trace, gc, task, stats)) {
2706
return;
2707
}
2708
Log(gc, task, stats) log;
2709
ResourceMark rm;
2710
LogStream ls(log.trace());
2711
outputStream* st = &ls;
2712
2713
print_taskqueue_stats_hdr(st);
2714
2715
TaskQueueStats totals;
2716
const uint n = num_task_queues();
2717
for (uint i = 0; i < n; ++i) {
2718
st->print("%3u ", i); task_queue(i)->stats.print(st); st->cr();
2719
totals += task_queue(i)->stats;
2720
}
2721
st->print_raw("tot "); totals.print(st); st->cr();
2722
2723
DEBUG_ONLY(totals.verify());
2724
}
2725
2726
void G1CollectedHeap::reset_taskqueue_stats() {
2727
const uint n = num_task_queues();
2728
for (uint i = 0; i < n; ++i) {
2729
task_queue(i)->stats.reset();
2730
}
2731
}
2732
#endif // TASKQUEUE_STATS
2733
2734
void G1CollectedHeap::wait_for_root_region_scanning() {
2735
double scan_wait_start = os::elapsedTime();
2736
// We have to wait until the CM threads finish scanning the
2737
// root regions as it's the only way to ensure that all the
2738
// objects on them have been correctly scanned before we start
2739
// moving them during the GC.
2740
bool waited = _cm->root_regions()->wait_until_scan_finished();
2741
double wait_time_ms = 0.0;
2742
if (waited) {
2743
double scan_wait_end = os::elapsedTime();
2744
wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;
2745
}
2746
phase_times()->record_root_region_scan_wait_time(wait_time_ms);
2747
}
2748
2749
class G1PrintCollectionSetClosure : public HeapRegionClosure {
2750
private:
2751
G1HRPrinter* _hr_printer;
2752
public:
2753
G1PrintCollectionSetClosure(G1HRPrinter* hr_printer) : HeapRegionClosure(), _hr_printer(hr_printer) { }
2754
2755
virtual bool do_heap_region(HeapRegion* r) {
2756
_hr_printer->cset(r);
2757
return false;
2758
}
2759
};
2760
2761
void G1CollectedHeap::start_new_collection_set() {
2762
double start = os::elapsedTime();
2763
2764
collection_set()->start_incremental_building();
2765
2766
clear_region_attr();
2767
2768
guarantee(_eden.length() == 0, "eden should have been cleared");
2769
policy()->transfer_survivors_to_cset(survivor());
2770
2771
// We redo the verification but now wrt to the new CSet which
2772
// has just got initialized after the previous CSet was freed.
2773
_cm->verify_no_collection_set_oops();
2774
2775
phase_times()->record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0);
2776
}
2777
2778
void G1CollectedHeap::calculate_collection_set(G1EvacuationInfo& evacuation_info, double target_pause_time_ms) {
2779
2780
_collection_set.finalize_initial_collection_set(target_pause_time_ms, &_survivor);
2781
evacuation_info.set_collectionset_regions(collection_set()->region_length() +
2782
collection_set()->optional_region_length());
2783
2784
_cm->verify_no_collection_set_oops();
2785
2786
if (_hr_printer.is_active()) {
2787
G1PrintCollectionSetClosure cl(&_hr_printer);
2788
_collection_set.iterate(&cl);
2789
_collection_set.iterate_optional(&cl);
2790
}
2791
}
2792
2793
G1HeapVerifier::G1VerifyType G1CollectedHeap::young_collection_verify_type() const {
2794
if (collector_state()->in_concurrent_start_gc()) {
2795
return G1HeapVerifier::G1VerifyConcurrentStart;
2796
} else if (collector_state()->in_young_only_phase()) {
2797
return G1HeapVerifier::G1VerifyYoungNormal;
2798
} else {
2799
return G1HeapVerifier::G1VerifyMixed;
2800
}
2801
}
2802
2803
void G1CollectedHeap::verify_before_young_collection(G1HeapVerifier::G1VerifyType type) {
2804
if (VerifyRememberedSets) {
2805
log_info(gc, verify)("[Verifying RemSets before GC]");
2806
VerifyRegionRemSetClosure v_cl;
2807
heap_region_iterate(&v_cl);
2808
}
2809
_verifier->verify_before_gc(type);
2810
_verifier->check_bitmaps("GC Start");
2811
verify_numa_regions("GC Start");
2812
}
2813
2814
void G1CollectedHeap::verify_after_young_collection(G1HeapVerifier::G1VerifyType type) {
2815
if (VerifyRememberedSets) {
2816
log_info(gc, verify)("[Verifying RemSets after GC]");
2817
VerifyRegionRemSetClosure v_cl;
2818
heap_region_iterate(&v_cl);
2819
}
2820
_verifier->verify_after_gc(type);
2821
_verifier->check_bitmaps("GC End");
2822
verify_numa_regions("GC End");
2823
}
2824
2825
void G1CollectedHeap::expand_heap_after_young_collection(){
2826
size_t expand_bytes = _heap_sizing_policy->young_collection_expansion_amount();
2827
if (expand_bytes > 0) {
2828
// No need for an ergo logging here,
2829
// expansion_amount() does this when it returns a value > 0.
2830
double expand_ms = 0.0;
2831
if (!expand(expand_bytes, _workers, &expand_ms)) {
2832
// We failed to expand the heap. Cannot do anything about it.
2833
}
2834
phase_times()->record_expand_heap_time(expand_ms);
2835
}
2836
}
2837
2838
void G1CollectedHeap::set_young_gc_name(char* young_gc_name) {
2839
G1GCPauseType pause_type =
2840
// The strings for all Concurrent Start pauses are the same, so the parameter
2841
// does not matter here.
2842
collector_state()->young_gc_pause_type(false /* concurrent_operation_is_full_mark */);
2843
snprintf(young_gc_name,
2844
MaxYoungGCNameLength,
2845
"Pause Young (%s)",
2846
G1GCPauseTypeHelper::to_string(pause_type));
2847
}
2848
2849
bool G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
2850
assert_at_safepoint_on_vm_thread();
2851
guarantee(!is_gc_active(), "collection is not reentrant");
2852
2853
if (GCLocker::check_active_before_gc()) {
2854
return false;
2855
}
2856
2857
do_collection_pause_at_safepoint_helper(target_pause_time_ms);
2858
if (should_upgrade_to_full_gc(gc_cause())) {
2859
log_info(gc, ergo)("Attempting maximally compacting collection");
2860
bool result = do_full_collection(false /* explicit gc */,
2861
true /* clear_all_soft_refs */,
2862
false /* do_maximum_compaction */);
2863
// do_full_collection only fails if blocked by GC locker, but
2864
// we've already checked for that above.
2865
assert(result, "invariant");
2866
}
2867
return true;
2868
}
2869
2870
void G1CollectedHeap::gc_tracer_report_gc_start() {
2871
_gc_timer_stw->register_gc_start();
2872
_gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
2873
}
2874
2875
void G1CollectedHeap::gc_tracer_report_gc_end(bool concurrent_operation_is_full_mark,
2876
G1EvacuationInfo& evacuation_info) {
2877
_gc_tracer_stw->report_evacuation_info(&evacuation_info);
2878
_gc_tracer_stw->report_tenuring_threshold(_policy->tenuring_threshold());
2879
2880
_gc_timer_stw->register_gc_end();
2881
_gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(),
2882
_gc_timer_stw->time_partitions());
2883
}
2884
2885
void G1CollectedHeap::do_collection_pause_at_safepoint_helper(double target_pause_time_ms) {
2886
GCIdMark gc_id_mark;
2887
2888
SvcGCMarker sgcm(SvcGCMarker::MINOR);
2889
ResourceMark rm;
2890
2891
policy()->note_gc_start();
2892
2893
gc_tracer_report_gc_start();
2894
2895
wait_for_root_region_scanning();
2896
2897
print_heap_before_gc();
2898
print_heap_regions();
2899
trace_heap_before_gc(_gc_tracer_stw);
2900
2901
_verifier->verify_region_sets_optional();
2902
_verifier->verify_dirty_young_regions();
2903
2904
// We should not be doing concurrent start unless the concurrent mark thread is running
2905
if (!_cm_thread->should_terminate()) {
2906
// This call will decide whether this pause is a concurrent start
2907
// pause. If it is, in_concurrent_start_gc() will return true
2908
// for the duration of this pause.
2909
policy()->decide_on_conc_mark_initiation();
2910
}
2911
2912
// We do not allow concurrent start to be piggy-backed on a mixed GC.
2913
assert(!collector_state()->in_concurrent_start_gc() ||
2914
collector_state()->in_young_only_phase(), "sanity");
2915
// We also do not allow mixed GCs during marking.
2916
assert(!collector_state()->mark_or_rebuild_in_progress() || collector_state()->in_young_only_phase(), "sanity");
2917
2918
// Record whether this pause may need to trigger a concurrent operation. Later,
2919
// when we signal the G1ConcurrentMarkThread, the collector state has already
2920
// been reset for the next pause.
2921
bool should_start_concurrent_mark_operation = collector_state()->in_concurrent_start_gc();
2922
bool concurrent_operation_is_full_mark = false;
2923
2924
// Inner scope for scope based logging, timers, and stats collection
2925
{
2926
G1EvacuationInfo evacuation_info;
2927
2928
GCTraceCPUTime tcpu;
2929
2930
char young_gc_name[MaxYoungGCNameLength];
2931
set_young_gc_name(young_gc_name);
2932
2933
GCTraceTime(Info, gc) tm(young_gc_name, NULL, gc_cause(), true);
2934
2935
uint active_workers = WorkerPolicy::calc_active_workers(workers()->total_workers(),
2936
workers()->active_workers(),
2937
Threads::number_of_non_daemon_threads());
2938
active_workers = workers()->update_active_workers(active_workers);
2939
log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->total_workers());
2940
2941
G1MonitoringScope ms(g1mm(),
2942
false /* full_gc */,
2943
collector_state()->in_mixed_phase() /* all_memory_pools_affected */);
2944
2945
G1HeapTransition heap_transition(this);
2946
2947
{
2948
IsGCActiveMark x;
2949
2950
gc_prologue(false);
2951
2952
G1HeapVerifier::G1VerifyType verify_type = young_collection_verify_type();
2953
verify_before_young_collection(verify_type);
2954
2955
{
2956
// The elapsed time induced by the start time below deliberately elides
2957
// the possible verification above.
2958
double sample_start_time_sec = os::elapsedTime();
2959
2960
// Please see comment in g1CollectedHeap.hpp and
2961
// G1CollectedHeap::ref_processing_init() to see how
2962
// reference processing currently works in G1.
2963
_ref_processor_stw->enable_discovery();
2964
2965
// We want to temporarily turn off discovery by the
2966
// CM ref processor, if necessary, and turn it back on
2967
// on again later if we do. Using a scoped
2968
// NoRefDiscovery object will do this.
2969
NoRefDiscovery no_cm_discovery(_ref_processor_cm);
2970
2971
policy()->record_collection_pause_start(sample_start_time_sec);
2972
2973
// Forget the current allocation region (we might even choose it to be part
2974
// of the collection set!).
2975
_allocator->release_mutator_alloc_regions();
2976
2977
calculate_collection_set(evacuation_info, target_pause_time_ms);
2978
2979
G1RedirtyCardsQueueSet rdcqs(G1BarrierSet::dirty_card_queue_set().allocator());
2980
G1ParScanThreadStateSet per_thread_states(this,
2981
&rdcqs,
2982
workers()->active_workers(),
2983
collection_set()->young_region_length(),
2984
collection_set()->optional_region_length());
2985
pre_evacuate_collection_set(evacuation_info, &per_thread_states);
2986
2987
bool may_do_optional_evacuation = _collection_set.optional_region_length() != 0;
2988
// Actually do the work...
2989
evacuate_initial_collection_set(&per_thread_states, may_do_optional_evacuation);
2990
2991
if (may_do_optional_evacuation) {
2992
evacuate_optional_collection_set(&per_thread_states);
2993
}
2994
post_evacuate_collection_set(evacuation_info, &rdcqs, &per_thread_states);
2995
2996
start_new_collection_set();
2997
2998
_survivor_evac_stats.adjust_desired_plab_sz();
2999
_old_evac_stats.adjust_desired_plab_sz();
3000
3001
allocate_dummy_regions();
3002
3003
_allocator->init_mutator_alloc_regions();
3004
3005
expand_heap_after_young_collection();
3006
3007
// Refine the type of a concurrent mark operation now that we did the
3008
// evacuation, eventually aborting it.
3009
concurrent_operation_is_full_mark = policy()->concurrent_operation_is_full_mark("Revise IHOP");
3010
3011
// Need to report the collection pause now since record_collection_pause_end()
3012
// modifies it to the next state.
3013
_gc_tracer_stw->report_young_gc_pause(collector_state()->young_gc_pause_type(concurrent_operation_is_full_mark));
3014
3015
double sample_end_time_sec = os::elapsedTime();
3016
double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
3017
policy()->record_collection_pause_end(pause_time_ms, concurrent_operation_is_full_mark);
3018
}
3019
3020
verify_after_young_collection(verify_type);
3021
3022
gc_epilogue(false);
3023
}
3024
3025
// Print the remainder of the GC log output.
3026
if (evacuation_failed()) {
3027
log_info(gc)("To-space exhausted");
3028
}
3029
3030
policy()->print_phases();
3031
heap_transition.print();
3032
3033
_hrm.verify_optional();
3034
_verifier->verify_region_sets_optional();
3035
3036
TASKQUEUE_STATS_ONLY(print_taskqueue_stats());
3037
TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
3038
3039
print_heap_after_gc();
3040
print_heap_regions();
3041
trace_heap_after_gc(_gc_tracer_stw);
3042
3043
// We must call G1MonitoringSupport::update_sizes() in the same scoping level
3044
// as an active TraceMemoryManagerStats object (i.e. before the destructor for the
3045
// TraceMemoryManagerStats is called) so that the G1 memory pools are updated
3046
// before any GC notifications are raised.
3047
g1mm()->update_sizes();
3048
3049
gc_tracer_report_gc_end(concurrent_operation_is_full_mark, evacuation_info);
3050
}
3051
// It should now be safe to tell the concurrent mark thread to start
3052
// without its logging output interfering with the logging output
3053
// that came from the pause.
3054
3055
if (should_start_concurrent_mark_operation) {
3056
// CAUTION: after the start_concurrent_cycle() call below, the concurrent marking
3057
// thread(s) could be running concurrently with us. Make sure that anything
3058
// after this point does not assume that we are the only GC thread running.
3059
// Note: of course, the actual marking work will not start until the safepoint
3060
// itself is released in SuspendibleThreadSet::desynchronize().
3061
start_concurrent_cycle(concurrent_operation_is_full_mark);
3062
ConcurrentGCBreakpoints::notify_idle_to_active();
3063
}
3064
}
3065
3066
void G1CollectedHeap::preserve_mark_during_evac_failure(uint worker_id, oop obj, markWord m) {
3067
_evacuation_failed_info_array[worker_id].register_copy_failure(obj->size());
3068
_preserved_marks_set.get(worker_id)->push_if_necessary(obj, m);
3069
}
3070
3071
bool G1ParEvacuateFollowersClosure::offer_termination() {
3072
EventGCPhaseParallel event;
3073
G1ParScanThreadState* const pss = par_scan_state();
3074
start_term_time();
3075
const bool res = (terminator() == nullptr) ? true : terminator()->offer_termination();
3076
end_term_time();
3077
event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(G1GCPhaseTimes::Termination));
3078
return res;
3079
}
3080
3081
void G1ParEvacuateFollowersClosure::do_void() {
3082
EventGCPhaseParallel event;
3083
G1ParScanThreadState* const pss = par_scan_state();
3084
pss->trim_queue();
3085
event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
3086
do {
3087
EventGCPhaseParallel event;
3088
pss->steal_and_trim_queue(queues());
3089
event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
3090
} while (!offer_termination());
3091
}
3092
3093
void G1CollectedHeap::complete_cleaning(BoolObjectClosure* is_alive,
3094
bool class_unloading_occurred) {
3095
uint num_workers = workers()->active_workers();
3096
G1ParallelCleaningTask unlink_task(is_alive, num_workers, class_unloading_occurred);
3097
workers()->run_task(&unlink_task);
3098
}
3099
3100
// Weak Reference Processing support
3101
3102
bool G1STWIsAliveClosure::do_object_b(oop p) {
3103
// An object is reachable if it is outside the collection set,
3104
// or is inside and copied.
3105
return !_g1h->is_in_cset(p) || p->is_forwarded();
3106
}
3107
3108
bool G1STWSubjectToDiscoveryClosure::do_object_b(oop obj) {
3109
assert(obj != NULL, "must not be NULL");
3110
assert(_g1h->is_in_reserved(obj), "Trying to discover obj " PTR_FORMAT " not in heap", p2i(obj));
3111
// The areas the CM and STW ref processor manage must be disjoint. The is_in_cset() below
3112
// may falsely indicate that this is not the case here: however the collection set only
3113
// contains old regions when concurrent mark is not running.
3114
return _g1h->is_in_cset(obj) || _g1h->heap_region_containing(obj)->is_survivor();
3115
}
3116
3117
// Non Copying Keep Alive closure
3118
class G1KeepAliveClosure: public OopClosure {
3119
G1CollectedHeap*_g1h;
3120
public:
3121
G1KeepAliveClosure(G1CollectedHeap* g1h) :_g1h(g1h) {}
3122
void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
3123
void do_oop(oop* p) {
3124
oop obj = *p;
3125
assert(obj != NULL, "the caller should have filtered out NULL values");
3126
3127
const G1HeapRegionAttr region_attr =_g1h->region_attr(obj);
3128
if (!region_attr.is_in_cset_or_humongous()) {
3129
return;
3130
}
3131
if (region_attr.is_in_cset()) {
3132
assert( obj->is_forwarded(), "invariant" );
3133
*p = obj->forwardee();
3134
} else {
3135
assert(!obj->is_forwarded(), "invariant" );
3136
assert(region_attr.is_humongous(),
3137
"Only allowed G1HeapRegionAttr state is IsHumongous, but is %d", region_attr.type());
3138
_g1h->set_humongous_is_live(obj);
3139
}
3140
}
3141
};
3142
3143
// Copying Keep Alive closure - can be called from both
3144
// serial and parallel code as long as different worker
3145
// threads utilize different G1ParScanThreadState instances
3146
// and different queues.
3147
3148
class G1CopyingKeepAliveClosure: public OopClosure {
3149
G1CollectedHeap* _g1h;
3150
G1ParScanThreadState* _par_scan_state;
3151
3152
public:
3153
G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
3154
G1ParScanThreadState* pss):
3155
_g1h(g1h),
3156
_par_scan_state(pss)
3157
{}
3158
3159
virtual void do_oop(narrowOop* p) { do_oop_work(p); }
3160
virtual void do_oop( oop* p) { do_oop_work(p); }
3161
3162
template <class T> void do_oop_work(T* p) {
3163
oop obj = RawAccess<>::oop_load(p);
3164
3165
if (_g1h->is_in_cset_or_humongous(obj)) {
3166
// If the referent object has been forwarded (either copied
3167
// to a new location or to itself in the event of an
3168
// evacuation failure) then we need to update the reference
3169
// field and, if both reference and referent are in the G1
3170
// heap, update the RSet for the referent.
3171
//
3172
// If the referent has not been forwarded then we have to keep
3173
// it alive by policy. Therefore we have copy the referent.
3174
//
3175
// When the queue is drained (after each phase of reference processing)
3176
// the object and it's followers will be copied, the reference field set
3177
// to point to the new location, and the RSet updated.
3178
_par_scan_state->push_on_queue(ScannerTask(p));
3179
}
3180
}
3181
};
3182
3183
// Serial drain queue closure. Called as the 'complete_gc'
3184
// closure for each discovered list in some of the
3185
// reference processing phases.
3186
3187
class G1STWDrainQueueClosure: public VoidClosure {
3188
protected:
3189
G1CollectedHeap* _g1h;
3190
G1ParScanThreadState* _par_scan_state;
3191
3192
G1ParScanThreadState* par_scan_state() { return _par_scan_state; }
3193
3194
public:
3195
G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :
3196
_g1h(g1h),
3197
_par_scan_state(pss)
3198
{ }
3199
3200
void do_void() {
3201
G1ParScanThreadState* const pss = par_scan_state();
3202
pss->trim_queue();
3203
}
3204
};
3205
3206
class G1STWRefProcProxyTask : public RefProcProxyTask {
3207
G1CollectedHeap& _g1h;
3208
G1ParScanThreadStateSet& _pss;
3209
TaskTerminator _terminator;
3210
G1ScannerTasksQueueSet& _task_queues;
3211
3212
public:
3213
G1STWRefProcProxyTask(uint max_workers, G1CollectedHeap& g1h, G1ParScanThreadStateSet& pss, G1ScannerTasksQueueSet& task_queues)
3214
: RefProcProxyTask("G1STWRefProcProxyTask", max_workers),
3215
_g1h(g1h),
3216
_pss(pss),
3217
_terminator(max_workers, &task_queues),
3218
_task_queues(task_queues) {}
3219
3220
void work(uint worker_id) override {
3221
assert(worker_id < _max_workers, "sanity");
3222
uint index = (_tm == RefProcThreadModel::Single) ? 0 : worker_id;
3223
_pss.state_for_worker(index)->set_ref_discoverer(nullptr);
3224
G1STWIsAliveClosure is_alive(&_g1h);
3225
G1CopyingKeepAliveClosure keep_alive(&_g1h, _pss.state_for_worker(index));
3226
G1ParEvacuateFollowersClosure complete_gc(&_g1h, _pss.state_for_worker(index), &_task_queues, _tm == RefProcThreadModel::Single ? nullptr : &_terminator, G1GCPhaseTimes::ObjCopy);
3227
_rp_task->rp_work(worker_id, &is_alive, &keep_alive, &complete_gc);
3228
}
3229
3230
void prepare_run_task_hook() override {
3231
_terminator.reset_for_reuse(_queue_count);
3232
}
3233
};
3234
3235
// End of weak reference support closures
3236
3237
void G1CollectedHeap::process_discovered_references(G1ParScanThreadStateSet* per_thread_states) {
3238
double ref_proc_start = os::elapsedTime();
3239
3240
ReferenceProcessor* rp = _ref_processor_stw;
3241
assert(rp->discovery_enabled(), "should have been enabled");
3242
3243
// Use only a single queue for this PSS.
3244
G1ParScanThreadState* pss = per_thread_states->state_for_worker(0);
3245
pss->set_ref_discoverer(NULL);
3246
assert(pss->queue_is_empty(), "pre-condition");
3247
3248
// Setup the soft refs policy...
3249
rp->setup_policy(false);
3250
3251
ReferenceProcessorPhaseTimes& pt = *phase_times()->ref_phase_times();
3252
3253
ReferenceProcessorStats stats;
3254
uint no_of_gc_workers = workers()->active_workers();
3255
3256
// Parallel reference processing
3257
assert(no_of_gc_workers <= rp->max_num_queues(),
3258
"Mismatch between the number of GC workers %u and the maximum number of Reference process queues %u",
3259
no_of_gc_workers, rp->max_num_queues());
3260
3261
rp->set_active_mt_degree(no_of_gc_workers);
3262
G1STWRefProcProxyTask task(rp->max_num_queues(), *this, *per_thread_states, *_task_queues);
3263
stats = rp->process_discovered_references(task, pt);
3264
3265
_gc_tracer_stw->report_gc_reference_stats(stats);
3266
3267
// We have completed copying any necessary live referent objects.
3268
assert(pss->queue_is_empty(), "both queue and overflow should be empty");
3269
3270
make_pending_list_reachable();
3271
3272
assert(!rp->discovery_enabled(), "Postcondition");
3273
rp->verify_no_references_recorded();
3274
3275
double ref_proc_time = os::elapsedTime() - ref_proc_start;
3276
phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);
3277
}
3278
3279
void G1CollectedHeap::make_pending_list_reachable() {
3280
if (collector_state()->in_concurrent_start_gc()) {
3281
oop pll_head = Universe::reference_pending_list();
3282
if (pll_head != NULL) {
3283
// Any valid worker id is fine here as we are in the VM thread and single-threaded.
3284
_cm->mark_in_next_bitmap(0 /* worker_id */, pll_head);
3285
}
3286
}
3287
}
3288
3289
static bool do_humongous_object_logging() {
3290
return log_is_enabled(Debug, gc, humongous);
3291
}
3292
3293
bool G1CollectedHeap::should_do_eager_reclaim() const {
3294
// As eager reclaim logging also gives information about humongous objects in
3295
// the heap in general, always do the eager reclaim pass even without known
3296
// candidates.
3297
return (G1EagerReclaimHumongousObjects &&
3298
(has_humongous_reclaim_candidates() || do_humongous_object_logging()));
3299
}
3300
3301
class G1PrepareEvacuationTask : public AbstractGangTask {
3302
class G1PrepareRegionsClosure : public HeapRegionClosure {
3303
G1CollectedHeap* _g1h;
3304
G1PrepareEvacuationTask* _parent_task;
3305
uint _worker_humongous_total;
3306
uint _worker_humongous_candidates;
3307
3308
bool humongous_region_is_candidate(HeapRegion* region) const {
3309
assert(region->is_starts_humongous(), "Must start a humongous object");
3310
3311
oop obj = cast_to_oop(region->bottom());
3312
3313
// Dead objects cannot be eager reclaim candidates. Due to class
3314
// unloading it is unsafe to query their classes so we return early.
3315
if (_g1h->is_obj_dead(obj, region)) {
3316
return false;
3317
}
3318
3319
// If we do not have a complete remembered set for the region, then we can
3320
// not be sure that we have all references to it.
3321
if (!region->rem_set()->is_complete()) {
3322
return false;
3323
}
3324
// Candidate selection must satisfy the following constraints
3325
// while concurrent marking is in progress:
3326
//
3327
// * In order to maintain SATB invariants, an object must not be
3328
// reclaimed if it was allocated before the start of marking and
3329
// has not had its references scanned. Such an object must have
3330
// its references (including type metadata) scanned to ensure no
3331
// live objects are missed by the marking process. Objects
3332
// allocated after the start of concurrent marking don't need to
3333
// be scanned.
3334
//
3335
// * An object must not be reclaimed if it is on the concurrent
3336
// mark stack. Objects allocated after the start of concurrent
3337
// marking are never pushed on the mark stack.
3338
//
3339
// Nominating only objects allocated after the start of concurrent
3340
// marking is sufficient to meet both constraints. This may miss
3341
// some objects that satisfy the constraints, but the marking data
3342
// structures don't support efficiently performing the needed
3343
// additional tests or scrubbing of the mark stack.
3344
//
3345
// However, we presently only nominate is_typeArray() objects.
3346
// A humongous object containing references induces remembered
3347
// set entries on other regions. In order to reclaim such an
3348
// object, those remembered sets would need to be cleaned up.
3349
//
3350
// We also treat is_typeArray() objects specially, allowing them
3351
// to be reclaimed even if allocated before the start of
3352
// concurrent mark. For this we rely on mark stack insertion to
3353
// exclude is_typeArray() objects, preventing reclaiming an object
3354
// that is in the mark stack. We also rely on the metadata for
3355
// such objects to be built-in and so ensured to be kept live.
3356
// Frequent allocation and drop of large binary blobs is an
3357
// important use case for eager reclaim, and this special handling
3358
// may reduce needed headroom.
3359
3360
return obj->is_typeArray() &&
3361
_g1h->is_potential_eager_reclaim_candidate(region);
3362
}
3363
3364
public:
3365
G1PrepareRegionsClosure(G1CollectedHeap* g1h, G1PrepareEvacuationTask* parent_task) :
3366
_g1h(g1h),
3367
_parent_task(parent_task),
3368
_worker_humongous_total(0),
3369
_worker_humongous_candidates(0) { }
3370
3371
~G1PrepareRegionsClosure() {
3372
_parent_task->add_humongous_candidates(_worker_humongous_candidates);
3373
_parent_task->add_humongous_total(_worker_humongous_total);
3374
}
3375
3376
virtual bool do_heap_region(HeapRegion* hr) {
3377
// First prepare the region for scanning
3378
_g1h->rem_set()->prepare_region_for_scan(hr);
3379
3380
// Now check if region is a humongous candidate
3381
if (!hr->is_starts_humongous()) {
3382
_g1h->register_region_with_region_attr(hr);
3383
return false;
3384
}
3385
3386
uint index = hr->hrm_index();
3387
if (humongous_region_is_candidate(hr)) {
3388
_g1h->set_humongous_reclaim_candidate(index, true);
3389
_g1h->register_humongous_region_with_region_attr(index);
3390
_worker_humongous_candidates++;
3391
// We will later handle the remembered sets of these regions.
3392
} else {
3393
_g1h->set_humongous_reclaim_candidate(index, false);
3394
_g1h->register_region_with_region_attr(hr);
3395
}
3396
_worker_humongous_total++;
3397
3398
return false;
3399
}
3400
};
3401
3402
G1CollectedHeap* _g1h;
3403
HeapRegionClaimer _claimer;
3404
volatile uint _humongous_total;
3405
volatile uint _humongous_candidates;
3406
public:
3407
G1PrepareEvacuationTask(G1CollectedHeap* g1h) :
3408
AbstractGangTask("Prepare Evacuation"),
3409
_g1h(g1h),
3410
_claimer(_g1h->workers()->active_workers()),
3411
_humongous_total(0),
3412
_humongous_candidates(0) { }
3413
3414
void work(uint worker_id) {
3415
G1PrepareRegionsClosure cl(_g1h, this);
3416
_g1h->heap_region_par_iterate_from_worker_offset(&cl, &_claimer, worker_id);
3417
}
3418
3419
void add_humongous_candidates(uint candidates) {
3420
Atomic::add(&_humongous_candidates, candidates);
3421
}
3422
3423
void add_humongous_total(uint total) {
3424
Atomic::add(&_humongous_total, total);
3425
}
3426
3427
uint humongous_candidates() {
3428
return _humongous_candidates;
3429
}
3430
3431
uint humongous_total() {
3432
return _humongous_total;
3433
}
3434
};
3435
3436
void G1CollectedHeap::pre_evacuate_collection_set(G1EvacuationInfo& evacuation_info, G1ParScanThreadStateSet* per_thread_states) {
3437
_bytes_used_during_gc = 0;
3438
3439
_expand_heap_after_alloc_failure = true;
3440
Atomic::store(&_num_regions_failed_evacuation, 0u);
3441
3442
// Disable the hot card cache.
3443
_hot_card_cache->reset_hot_cache_claimed_index();
3444
_hot_card_cache->set_use_cache(false);
3445
3446
// Initialize the GC alloc regions.
3447
_allocator->init_gc_alloc_regions(evacuation_info);
3448
3449
{
3450
Ticks start = Ticks::now();
3451
rem_set()->prepare_for_scan_heap_roots();
3452
phase_times()->record_prepare_heap_roots_time_ms((Ticks::now() - start).seconds() * 1000.0);
3453
}
3454
3455
{
3456
G1PrepareEvacuationTask g1_prep_task(this);
3457
Tickspan task_time = run_task_timed(&g1_prep_task);
3458
3459
phase_times()->record_register_regions(task_time.seconds() * 1000.0);
3460
_num_humongous_objects = g1_prep_task.humongous_total();
3461
_num_humongous_reclaim_candidates = g1_prep_task.humongous_candidates();
3462
}
3463
3464
assert(_verifier->check_region_attr_table(), "Inconsistency in the region attributes table.");
3465
_preserved_marks_set.assert_empty();
3466
3467
#if COMPILER2_OR_JVMCI
3468
DerivedPointerTable::clear();
3469
#endif
3470
3471
// Concurrent start needs claim bits to keep track of the marked-through CLDs.
3472
if (collector_state()->in_concurrent_start_gc()) {
3473
concurrent_mark()->pre_concurrent_start(gc_cause());
3474
3475
double start_clear_claimed_marks = os::elapsedTime();
3476
3477
ClassLoaderDataGraph::clear_claimed_marks();
3478
3479
double recorded_clear_claimed_marks_time_ms = (os::elapsedTime() - start_clear_claimed_marks) * 1000.0;
3480
phase_times()->record_clear_claimed_marks_time_ms(recorded_clear_claimed_marks_time_ms);
3481
}
3482
3483
// Should G1EvacuationFailureALot be in effect for this GC?
3484
NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)
3485
}
3486
3487
class G1EvacuateRegionsBaseTask : public AbstractGangTask {
3488
protected:
3489
G1CollectedHeap* _g1h;
3490
G1ParScanThreadStateSet* _per_thread_states;
3491
G1ScannerTasksQueueSet* _task_queues;
3492
TaskTerminator _terminator;
3493
uint _num_workers;
3494
3495
void evacuate_live_objects(G1ParScanThreadState* pss,
3496
uint worker_id,
3497
G1GCPhaseTimes::GCParPhases objcopy_phase,
3498
G1GCPhaseTimes::GCParPhases termination_phase) {
3499
G1GCPhaseTimes* p = _g1h->phase_times();
3500
3501
Ticks start = Ticks::now();
3502
G1ParEvacuateFollowersClosure cl(_g1h, pss, _task_queues, &_terminator, objcopy_phase);
3503
cl.do_void();
3504
3505
assert(pss->queue_is_empty(), "should be empty");
3506
3507
Tickspan evac_time = (Ticks::now() - start);
3508
p->record_or_add_time_secs(objcopy_phase, worker_id, evac_time.seconds() - cl.term_time());
3509
3510
if (termination_phase == G1GCPhaseTimes::Termination) {
3511
p->record_time_secs(termination_phase, worker_id, cl.term_time());
3512
p->record_thread_work_item(termination_phase, worker_id, cl.term_attempts());
3513
} else {
3514
p->record_or_add_time_secs(termination_phase, worker_id, cl.term_time());
3515
p->record_or_add_thread_work_item(termination_phase, worker_id, cl.term_attempts());
3516
}
3517
assert(pss->trim_ticks().value() == 0,
3518
"Unexpected partial trimming during evacuation value " JLONG_FORMAT,
3519
pss->trim_ticks().value());
3520
}
3521
3522
virtual void start_work(uint worker_id) { }
3523
3524
virtual void end_work(uint worker_id) { }
3525
3526
virtual void scan_roots(G1ParScanThreadState* pss, uint worker_id) = 0;
3527
3528
virtual void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) = 0;
3529
3530
public:
3531
G1EvacuateRegionsBaseTask(const char* name,
3532
G1ParScanThreadStateSet* per_thread_states,
3533
G1ScannerTasksQueueSet* task_queues,
3534
uint num_workers) :
3535
AbstractGangTask(name),
3536
_g1h(G1CollectedHeap::heap()),
3537
_per_thread_states(per_thread_states),
3538
_task_queues(task_queues),
3539
_terminator(num_workers, _task_queues),
3540
_num_workers(num_workers)
3541
{ }
3542
3543
void work(uint worker_id) {
3544
start_work(worker_id);
3545
3546
{
3547
ResourceMark rm;
3548
3549
G1ParScanThreadState* pss = _per_thread_states->state_for_worker(worker_id);
3550
pss->set_ref_discoverer(_g1h->ref_processor_stw());
3551
3552
scan_roots(pss, worker_id);
3553
evacuate_live_objects(pss, worker_id);
3554
}
3555
3556
end_work(worker_id);
3557
}
3558
};
3559
3560
class G1EvacuateRegionsTask : public G1EvacuateRegionsBaseTask {
3561
G1RootProcessor* _root_processor;
3562
bool _has_optional_evacuation_work;
3563
3564
void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
3565
_root_processor->evacuate_roots(pss, worker_id);
3566
_g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::ObjCopy, _has_optional_evacuation_work);
3567
_g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::CodeRoots, G1GCPhaseTimes::ObjCopy);
3568
}
3569
3570
void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
3571
G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::ObjCopy, G1GCPhaseTimes::Termination);
3572
}
3573
3574
void start_work(uint worker_id) {
3575
_g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, Ticks::now().seconds());
3576
}
3577
3578
void end_work(uint worker_id) {
3579
_g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, Ticks::now().seconds());
3580
}
3581
3582
public:
3583
G1EvacuateRegionsTask(G1CollectedHeap* g1h,
3584
G1ParScanThreadStateSet* per_thread_states,
3585
G1ScannerTasksQueueSet* task_queues,
3586
G1RootProcessor* root_processor,
3587
uint num_workers,
3588
bool has_optional_evacuation_work) :
3589
G1EvacuateRegionsBaseTask("G1 Evacuate Regions", per_thread_states, task_queues, num_workers),
3590
_root_processor(root_processor),
3591
_has_optional_evacuation_work(has_optional_evacuation_work)
3592
{ }
3593
};
3594
3595
void G1CollectedHeap::evacuate_initial_collection_set(G1ParScanThreadStateSet* per_thread_states,
3596
bool has_optional_evacuation_work) {
3597
G1GCPhaseTimes* p = phase_times();
3598
3599
{
3600
Ticks start = Ticks::now();
3601
rem_set()->merge_heap_roots(true /* initial_evacuation */);
3602
p->record_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);
3603
}
3604
3605
Tickspan task_time;
3606
const uint num_workers = workers()->active_workers();
3607
3608
Ticks start_processing = Ticks::now();
3609
{
3610
G1RootProcessor root_processor(this, num_workers);
3611
G1EvacuateRegionsTask g1_par_task(this,
3612
per_thread_states,
3613
_task_queues,
3614
&root_processor,
3615
num_workers,
3616
has_optional_evacuation_work);
3617
task_time = run_task_timed(&g1_par_task);
3618
// Closing the inner scope will execute the destructor for the G1RootProcessor object.
3619
// To extract its code root fixup time we measure total time of this scope and
3620
// subtract from the time the WorkGang task took.
3621
}
3622
Tickspan total_processing = Ticks::now() - start_processing;
3623
3624
p->record_initial_evac_time(task_time.seconds() * 1000.0);
3625
p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);
3626
3627
rem_set()->complete_evac_phase(has_optional_evacuation_work);
3628
}
3629
3630
class G1EvacuateOptionalRegionsTask : public G1EvacuateRegionsBaseTask {
3631
3632
void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
3633
_g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptObjCopy, true /* remember_already_scanned_cards */);
3634
_g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptCodeRoots, G1GCPhaseTimes::OptObjCopy);
3635
}
3636
3637
void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
3638
G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::OptObjCopy, G1GCPhaseTimes::OptTermination);
3639
}
3640
3641
public:
3642
G1EvacuateOptionalRegionsTask(G1ParScanThreadStateSet* per_thread_states,
3643
G1ScannerTasksQueueSet* queues,
3644
uint num_workers) :
3645
G1EvacuateRegionsBaseTask("G1 Evacuate Optional Regions", per_thread_states, queues, num_workers) {
3646
}
3647
};
3648
3649
void G1CollectedHeap::evacuate_next_optional_regions(G1ParScanThreadStateSet* per_thread_states) {
3650
class G1MarkScope : public MarkScope { };
3651
3652
Tickspan task_time;
3653
3654
Ticks start_processing = Ticks::now();
3655
{
3656
G1MarkScope code_mark_scope;
3657
G1EvacuateOptionalRegionsTask task(per_thread_states, _task_queues, workers()->active_workers());
3658
task_time = run_task_timed(&task);
3659
// See comment in evacuate_collection_set() for the reason of the scope.
3660
}
3661
Tickspan total_processing = Ticks::now() - start_processing;
3662
3663
G1GCPhaseTimes* p = phase_times();
3664
p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);
3665
}
3666
3667
void G1CollectedHeap::evacuate_optional_collection_set(G1ParScanThreadStateSet* per_thread_states) {
3668
const double gc_start_time_ms = phase_times()->cur_collection_start_sec() * 1000.0;
3669
3670
while (!evacuation_failed() && _collection_set.optional_region_length() > 0) {
3671
3672
double time_used_ms = os::elapsedTime() * 1000.0 - gc_start_time_ms;
3673
double time_left_ms = MaxGCPauseMillis - time_used_ms;
3674
3675
if (time_left_ms < 0 ||
3676
!_collection_set.finalize_optional_for_evacuation(time_left_ms * policy()->optional_evacuation_fraction())) {
3677
log_trace(gc, ergo, cset)("Skipping evacuation of %u optional regions, no more regions can be evacuated in %.3fms",
3678
_collection_set.optional_region_length(), time_left_ms);
3679
break;
3680
}
3681
3682
{
3683
Ticks start = Ticks::now();
3684
rem_set()->merge_heap_roots(false /* initial_evacuation */);
3685
phase_times()->record_or_add_optional_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);
3686
}
3687
3688
{
3689
Ticks start = Ticks::now();
3690
evacuate_next_optional_regions(per_thread_states);
3691
phase_times()->record_or_add_optional_evac_time((Ticks::now() - start).seconds() * 1000.0);
3692
}
3693
3694
rem_set()->complete_evac_phase(true /* has_more_than_one_evacuation_phase */);
3695
}
3696
3697
_collection_set.abandon_optional_collection_set(per_thread_states);
3698
}
3699
3700
void G1CollectedHeap::post_evacuate_collection_set(G1EvacuationInfo& evacuation_info,
3701
G1RedirtyCardsQueueSet* rdcqs,
3702
G1ParScanThreadStateSet* per_thread_states) {
3703
G1GCPhaseTimes* p = phase_times();
3704
3705
// Process any discovered reference objects - we have
3706
// to do this _before_ we retire the GC alloc regions
3707
// as we may have to copy some 'reachable' referent
3708
// objects (and their reachable sub-graphs) that were
3709
// not copied during the pause.
3710
process_discovered_references(per_thread_states);
3711
3712
G1STWIsAliveClosure is_alive(this);
3713
G1KeepAliveClosure keep_alive(this);
3714
3715
WeakProcessor::weak_oops_do(workers(), &is_alive, &keep_alive, p->weak_phase_times());
3716
3717
_allocator->release_gc_alloc_regions(evacuation_info);
3718
3719
post_evacuate_cleanup_1(per_thread_states, rdcqs);
3720
3721
post_evacuate_cleanup_2(&_preserved_marks_set, rdcqs, &evacuation_info, per_thread_states->surviving_young_words());
3722
3723
assert_used_and_recalculate_used_equal(this);
3724
3725
rebuild_free_region_list();
3726
3727
record_obj_copy_mem_stats();
3728
3729
evacuation_info.set_collectionset_used_before(collection_set()->bytes_used_before());
3730
evacuation_info.set_bytes_used(_bytes_used_during_gc);
3731
3732
policy()->print_age_table();
3733
}
3734
3735
void G1CollectedHeap::record_obj_copy_mem_stats() {
3736
policy()->old_gen_alloc_tracker()->
3737
add_allocated_bytes_since_last_gc(_old_evac_stats.allocated() * HeapWordSize);
3738
3739
_gc_tracer_stw->report_evacuation_statistics(create_g1_evac_summary(&_survivor_evac_stats),
3740
create_g1_evac_summary(&_old_evac_stats));
3741
}
3742
3743
void G1CollectedHeap::free_region(HeapRegion* hr, FreeRegionList* free_list) {
3744
assert(!hr->is_free(), "the region should not be free");
3745
assert(!hr->is_empty(), "the region should not be empty");
3746
assert(_hrm.is_available(hr->hrm_index()), "region should be committed");
3747
3748
if (G1VerifyBitmaps) {
3749
MemRegion mr(hr->bottom(), hr->end());
3750
concurrent_mark()->clear_range_in_prev_bitmap(mr);
3751
}
3752
3753
// Clear the card counts for this region.
3754
// Note: we only need to do this if the region is not young
3755
// (since we don't refine cards in young regions).
3756
if (!hr->is_young()) {
3757
_hot_card_cache->reset_card_counts(hr);
3758
}
3759
3760
// Reset region metadata to allow reuse.
3761
hr->hr_clear(true /* clear_space */);
3762
_policy->remset_tracker()->update_at_free(hr);
3763
3764
if (free_list != NULL) {
3765
free_list->add_ordered(hr);
3766
}
3767
}
3768
3769
void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
3770
FreeRegionList* free_list) {
3771
assert(hr->is_humongous(), "this is only for humongous regions");
3772
hr->clear_humongous();
3773
free_region(hr, free_list);
3774
}
3775
3776
void G1CollectedHeap::remove_from_old_gen_sets(const uint old_regions_removed,
3777
const uint archive_regions_removed,
3778
const uint humongous_regions_removed) {
3779
if (old_regions_removed > 0 || archive_regions_removed > 0 || humongous_regions_removed > 0) {
3780
MutexLocker x(OldSets_lock, Mutex::_no_safepoint_check_flag);
3781
_old_set.bulk_remove(old_regions_removed);
3782
_archive_set.bulk_remove(archive_regions_removed);
3783
_humongous_set.bulk_remove(humongous_regions_removed);
3784
}
3785
3786
}
3787
3788
void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {
3789
assert(list != NULL, "list can't be null");
3790
if (!list->is_empty()) {
3791
MutexLocker x(FreeList_lock, Mutex::_no_safepoint_check_flag);
3792
_hrm.insert_list_into_free_list(list);
3793
}
3794
}
3795
3796
void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {
3797
decrease_used(bytes);
3798
}
3799
3800
void G1CollectedHeap::post_evacuate_cleanup_1(G1ParScanThreadStateSet* per_thread_states,
3801
G1RedirtyCardsQueueSet* rdcqs) {
3802
Ticks start = Ticks::now();
3803
{
3804
G1PostEvacuateCollectionSetCleanupTask1 cl(per_thread_states, rdcqs);
3805
run_batch_task(&cl);
3806
}
3807
phase_times()->record_post_evacuate_cleanup_task_1_time((Ticks::now() - start).seconds() * 1000.0);
3808
}
3809
3810
void G1CollectedHeap::post_evacuate_cleanup_2(PreservedMarksSet* preserved_marks,
3811
G1RedirtyCardsQueueSet* rdcqs,
3812
G1EvacuationInfo* evacuation_info,
3813
const size_t* surviving_young_words) {
3814
Ticks start = Ticks::now();
3815
{
3816
G1PostEvacuateCollectionSetCleanupTask2 cl(preserved_marks, rdcqs, evacuation_info, surviving_young_words);
3817
run_batch_task(&cl);
3818
}
3819
phase_times()->record_post_evacuate_cleanup_task_2_time((Ticks::now() - start).seconds() * 1000.0);
3820
}
3821
3822
void G1CollectedHeap::clear_eden() {
3823
_eden.clear();
3824
}
3825
3826
void G1CollectedHeap::clear_collection_set() {
3827
collection_set()->clear();
3828
}
3829
3830
void G1CollectedHeap::rebuild_free_region_list() {
3831
Ticks start = Ticks::now();
3832
_hrm.rebuild_free_list(workers());
3833
phase_times()->record_total_rebuild_freelist_time_ms((Ticks::now() - start).seconds() * 1000.0);
3834
}
3835
3836
class G1AbandonCollectionSetClosure : public HeapRegionClosure {
3837
public:
3838
virtual bool do_heap_region(HeapRegion* r) {
3839
assert(r->in_collection_set(), "Region %u must have been in collection set", r->hrm_index());
3840
G1CollectedHeap::heap()->clear_region_attr(r);
3841
r->clear_young_index_in_cset();
3842
return false;
3843
}
3844
};
3845
3846
void G1CollectedHeap::abandon_collection_set(G1CollectionSet* collection_set) {
3847
G1AbandonCollectionSetClosure cl;
3848
collection_set_iterate_all(&cl);
3849
3850
collection_set->clear();
3851
collection_set->stop_incremental_building();
3852
}
3853
3854
bool G1CollectedHeap::is_old_gc_alloc_region(HeapRegion* hr) {
3855
return _allocator->is_retained_old_region(hr);
3856
}
3857
3858
void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
3859
_eden.add(hr);
3860
_policy->set_region_eden(hr);
3861
}
3862
3863
#ifdef ASSERT
3864
3865
class NoYoungRegionsClosure: public HeapRegionClosure {
3866
private:
3867
bool _success;
3868
public:
3869
NoYoungRegionsClosure() : _success(true) { }
3870
bool do_heap_region(HeapRegion* r) {
3871
if (r->is_young()) {
3872
log_error(gc, verify)("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young",
3873
p2i(r->bottom()), p2i(r->end()));
3874
_success = false;
3875
}
3876
return false;
3877
}
3878
bool success() { return _success; }
3879
};
3880
3881
bool G1CollectedHeap::check_young_list_empty() {
3882
bool ret = (young_regions_count() == 0);
3883
3884
NoYoungRegionsClosure closure;
3885
heap_region_iterate(&closure);
3886
ret = ret && closure.success();
3887
3888
return ret;
3889
}
3890
3891
#endif // ASSERT
3892
3893
// Remove the given HeapRegion from the appropriate region set.
3894
void G1CollectedHeap::prepare_region_for_full_compaction(HeapRegion* hr) {
3895
if (hr->is_archive()) {
3896
_archive_set.remove(hr);
3897
} else if (hr->is_humongous()) {
3898
_humongous_set.remove(hr);
3899
} else if (hr->is_old()) {
3900
_old_set.remove(hr);
3901
} else if (hr->is_young()) {
3902
// Note that emptying the eden and survivor lists is postponed and instead
3903
// done as the first step when rebuilding the regions sets again. The reason
3904
// for this is that during a full GC string deduplication needs to know if
3905
// a collected region was young or old when the full GC was initiated.
3906
hr->uninstall_surv_rate_group();
3907
} else {
3908
// We ignore free regions, we'll empty the free list afterwards.
3909
assert(hr->is_free(), "it cannot be another type");
3910
}
3911
}
3912
3913
void G1CollectedHeap::increase_used(size_t bytes) {
3914
_summary_bytes_used += bytes;
3915
}
3916
3917
void G1CollectedHeap::decrease_used(size_t bytes) {
3918
assert(_summary_bytes_used >= bytes,
3919
"invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT,
3920
_summary_bytes_used, bytes);
3921
_summary_bytes_used -= bytes;
3922
}
3923
3924
void G1CollectedHeap::set_used(size_t bytes) {
3925
_summary_bytes_used = bytes;
3926
}
3927
3928
class RebuildRegionSetsClosure : public HeapRegionClosure {
3929
private:
3930
bool _free_list_only;
3931
3932
HeapRegionSet* _old_set;
3933
HeapRegionSet* _archive_set;
3934
HeapRegionSet* _humongous_set;
3935
3936
HeapRegionManager* _hrm;
3937
3938
size_t _total_used;
3939
3940
public:
3941
RebuildRegionSetsClosure(bool free_list_only,
3942
HeapRegionSet* old_set,
3943
HeapRegionSet* archive_set,
3944
HeapRegionSet* humongous_set,
3945
HeapRegionManager* hrm) :
3946
_free_list_only(free_list_only), _old_set(old_set), _archive_set(archive_set),
3947
_humongous_set(humongous_set), _hrm(hrm), _total_used(0) {
3948
assert(_hrm->num_free_regions() == 0, "pre-condition");
3949
if (!free_list_only) {
3950
assert(_old_set->is_empty(), "pre-condition");
3951
assert(_archive_set->is_empty(), "pre-condition");
3952
assert(_humongous_set->is_empty(), "pre-condition");
3953
}
3954
}
3955
3956
bool do_heap_region(HeapRegion* r) {
3957
if (r->is_empty()) {
3958
assert(r->rem_set()->is_empty(), "Empty regions should have empty remembered sets.");
3959
// Add free regions to the free list
3960
r->set_free();
3961
_hrm->insert_into_free_list(r);
3962
} else if (!_free_list_only) {
3963
assert(r->rem_set()->is_empty(), "At this point remembered sets must have been cleared.");
3964
3965
if (r->is_humongous()) {
3966
_humongous_set->add(r);
3967
} else if (r->is_archive()) {
3968
_archive_set->add(r);
3969
} else {
3970
assert(r->is_young() || r->is_free() || r->is_old(), "invariant");
3971
// We now move all (non-humongous, non-old, non-archive) regions to old gen,
3972
// and register them as such.
3973
r->move_to_old();
3974
_old_set->add(r);
3975
}
3976
_total_used += r->used();
3977
}
3978
3979
return false;
3980
}
3981
3982
size_t total_used() {
3983
return _total_used;
3984
}
3985
};
3986
3987
void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
3988
assert_at_safepoint_on_vm_thread();
3989
3990
if (!free_list_only) {
3991
_eden.clear();
3992
_survivor.clear();
3993
}
3994
3995
RebuildRegionSetsClosure cl(free_list_only,
3996
&_old_set, &_archive_set, &_humongous_set,
3997
&_hrm);
3998
heap_region_iterate(&cl);
3999
4000
if (!free_list_only) {
4001
set_used(cl.total_used());
4002
if (_archive_allocator != NULL) {
4003
_archive_allocator->clear_used();
4004
}
4005
}
4006
assert_used_and_recalculate_used_equal(this);
4007
}
4008
4009
// Methods for the mutator alloc region
4010
4011
HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
4012
bool force,
4013
uint node_index) {
4014
assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
4015
bool should_allocate = policy()->should_allocate_mutator_region();
4016
if (force || should_allocate) {
4017
HeapRegion* new_alloc_region = new_region(word_size,
4018
HeapRegionType::Eden,
4019
false /* do_expand */,
4020
node_index);
4021
if (new_alloc_region != NULL) {
4022
set_region_short_lived_locked(new_alloc_region);
4023
_hr_printer.alloc(new_alloc_region, !should_allocate);
4024
_verifier->check_bitmaps("Mutator Region Allocation", new_alloc_region);
4025
_policy->remset_tracker()->update_at_allocate(new_alloc_region);
4026
return new_alloc_region;
4027
}
4028
}
4029
return NULL;
4030
}
4031
4032
void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
4033
size_t allocated_bytes) {
4034
assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
4035
assert(alloc_region->is_eden(), "all mutator alloc regions should be eden");
4036
4037
collection_set()->add_eden_region(alloc_region);
4038
increase_used(allocated_bytes);
4039
_eden.add_used_bytes(allocated_bytes);
4040
_hr_printer.retire(alloc_region);
4041
4042
// We update the eden sizes here, when the region is retired,
4043
// instead of when it's allocated, since this is the point that its
4044
// used space has been recorded in _summary_bytes_used.
4045
g1mm()->update_eden_size();
4046
}
4047
4048
// Methods for the GC alloc regions
4049
4050
bool G1CollectedHeap::has_more_regions(G1HeapRegionAttr dest) {
4051
if (dest.is_old()) {
4052
return true;
4053
} else {
4054
return survivor_regions_count() < policy()->max_survivor_regions();
4055
}
4056
}
4057
4058
HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index) {
4059
assert(FreeList_lock->owned_by_self(), "pre-condition");
4060
4061
if (!has_more_regions(dest)) {
4062
return NULL;
4063
}
4064
4065
HeapRegionType type;
4066
if (dest.is_young()) {
4067
type = HeapRegionType::Survivor;
4068
} else {
4069
type = HeapRegionType::Old;
4070
}
4071
4072
HeapRegion* new_alloc_region = new_region(word_size,
4073
type,
4074
true /* do_expand */,
4075
node_index);
4076
4077
if (new_alloc_region != NULL) {
4078
if (type.is_survivor()) {
4079
new_alloc_region->set_survivor();
4080
_survivor.add(new_alloc_region);
4081
_verifier->check_bitmaps("Survivor Region Allocation", new_alloc_region);
4082
} else {
4083
new_alloc_region->set_old();
4084
_verifier->check_bitmaps("Old Region Allocation", new_alloc_region);
4085
}
4086
_policy->remset_tracker()->update_at_allocate(new_alloc_region);
4087
register_region_with_region_attr(new_alloc_region);
4088
_hr_printer.alloc(new_alloc_region);
4089
return new_alloc_region;
4090
}
4091
return NULL;
4092
}
4093
4094
void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
4095
size_t allocated_bytes,
4096
G1HeapRegionAttr dest) {
4097
_bytes_used_during_gc += allocated_bytes;
4098
if (dest.is_old()) {
4099
old_set_add(alloc_region);
4100
} else {
4101
assert(dest.is_young(), "Retiring alloc region should be young (%d)", dest.type());
4102
_survivor.add_used_bytes(allocated_bytes);
4103
}
4104
4105
bool const during_im = collector_state()->in_concurrent_start_gc();
4106
if (during_im && allocated_bytes > 0) {
4107
_cm->root_regions()->add(alloc_region->next_top_at_mark_start(), alloc_region->top());
4108
}
4109
_hr_printer.retire(alloc_region);
4110
}
4111
4112
HeapRegion* G1CollectedHeap::alloc_highest_free_region() {
4113
bool expanded = false;
4114
uint index = _hrm.find_highest_free(&expanded);
4115
4116
if (index != G1_NO_HRM_INDEX) {
4117
if (expanded) {
4118
log_debug(gc, ergo, heap)("Attempt heap expansion (requested address range outside heap bounds). region size: " SIZE_FORMAT "B",
4119
HeapRegion::GrainWords * HeapWordSize);
4120
}
4121
return _hrm.allocate_free_regions_starting_at(index, 1);
4122
}
4123
return NULL;
4124
}
4125
4126
// Optimized nmethod scanning
4127
4128
class RegisterNMethodOopClosure: public OopClosure {
4129
G1CollectedHeap* _g1h;
4130
nmethod* _nm;
4131
4132
template <class T> void do_oop_work(T* p) {
4133
T heap_oop = RawAccess<>::oop_load(p);
4134
if (!CompressedOops::is_null(heap_oop)) {
4135
oop obj = CompressedOops::decode_not_null(heap_oop);
4136
HeapRegion* hr = _g1h->heap_region_containing(obj);
4137
assert(!hr->is_continues_humongous(),
4138
"trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
4139
" starting at " HR_FORMAT,
4140
p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));
4141
4142
// HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries.
4143
hr->add_strong_code_root_locked(_nm);
4144
}
4145
}
4146
4147
public:
4148
RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
4149
_g1h(g1h), _nm(nm) {}
4150
4151
void do_oop(oop* p) { do_oop_work(p); }
4152
void do_oop(narrowOop* p) { do_oop_work(p); }
4153
};
4154
4155
class UnregisterNMethodOopClosure: public OopClosure {
4156
G1CollectedHeap* _g1h;
4157
nmethod* _nm;
4158
4159
template <class T> void do_oop_work(T* p) {
4160
T heap_oop = RawAccess<>::oop_load(p);
4161
if (!CompressedOops::is_null(heap_oop)) {
4162
oop obj = CompressedOops::decode_not_null(heap_oop);
4163
HeapRegion* hr = _g1h->heap_region_containing(obj);
4164
assert(!hr->is_continues_humongous(),
4165
"trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
4166
" starting at " HR_FORMAT,
4167
p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));
4168
4169
hr->remove_strong_code_root(_nm);
4170
}
4171
}
4172
4173
public:
4174
UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
4175
_g1h(g1h), _nm(nm) {}
4176
4177
void do_oop(oop* p) { do_oop_work(p); }
4178
void do_oop(narrowOop* p) { do_oop_work(p); }
4179
};
4180
4181
void G1CollectedHeap::register_nmethod(nmethod* nm) {
4182
guarantee(nm != NULL, "sanity");
4183
RegisterNMethodOopClosure reg_cl(this, nm);
4184
nm->oops_do(&reg_cl);
4185
}
4186
4187
void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
4188
guarantee(nm != NULL, "sanity");
4189
UnregisterNMethodOopClosure reg_cl(this, nm);
4190
nm->oops_do(&reg_cl, true);
4191
}
4192
4193
void G1CollectedHeap::update_used_after_gc() {
4194
if (evacuation_failed()) {
4195
// Reset the G1EvacuationFailureALot counters and flags
4196
NOT_PRODUCT(reset_evacuation_should_fail();)
4197
4198
set_used(recalculate_used());
4199
4200
if (_archive_allocator != NULL) {
4201
_archive_allocator->clear_used();
4202
}
4203
for (uint i = 0; i < ParallelGCThreads; i++) {
4204
if (_evacuation_failed_info_array[i].has_failed()) {
4205
_gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
4206
}
4207
}
4208
} else {
4209
// The "used" of the the collection set have already been subtracted
4210
// when they were freed. Add in the bytes used.
4211
increase_used(_bytes_used_during_gc);
4212
}
4213
}
4214
4215
void G1CollectedHeap::reset_hot_card_cache() {
4216
_hot_card_cache->reset_hot_cache();
4217
_hot_card_cache->set_use_cache(true);
4218
}
4219
4220
void G1CollectedHeap::purge_code_root_memory() {
4221
G1CodeRootSet::purge();
4222
}
4223
4224
class RebuildStrongCodeRootClosure: public CodeBlobClosure {
4225
G1CollectedHeap* _g1h;
4226
4227
public:
4228
RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :
4229
_g1h(g1h) {}
4230
4231
void do_code_blob(CodeBlob* cb) {
4232
nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
4233
if (nm == NULL) {
4234
return;
4235
}
4236
4237
_g1h->register_nmethod(nm);
4238
}
4239
};
4240
4241
void G1CollectedHeap::rebuild_strong_code_roots() {
4242
RebuildStrongCodeRootClosure blob_cl(this);
4243
CodeCache::blobs_do(&blob_cl);
4244
}
4245
4246
void G1CollectedHeap::initialize_serviceability() {
4247
_g1mm->initialize_serviceability();
4248
}
4249
4250
MemoryUsage G1CollectedHeap::memory_usage() {
4251
return _g1mm->memory_usage();
4252
}
4253
4254
GrowableArray<GCMemoryManager*> G1CollectedHeap::memory_managers() {
4255
return _g1mm->memory_managers();
4256
}
4257
4258
GrowableArray<MemoryPool*> G1CollectedHeap::memory_pools() {
4259
return _g1mm->memory_pools();
4260
}
4261
4262