1 /*
2 * Copyright (c) 2001, 2025, 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 "classfile/classLoaderDataGraph.hpp"
26 #include "classfile/metadataOnStackMark.hpp"
27 #include "classfile/systemDictionary.hpp"
28 #include "code/codeCache.hpp"
29 #include "compiler/oopMap.hpp"
30 #include "gc/g1/g1Allocator.inline.hpp"
31 #include "gc/g1/g1Arguments.hpp"
32 #include "gc/g1/g1BarrierSet.hpp"
33 #include "gc/g1/g1BatchedTask.hpp"
34 #include "gc/g1/g1CollectedHeap.inline.hpp"
35 #include "gc/g1/g1CollectionSet.hpp"
36 #include "gc/g1/g1CollectionSetCandidates.hpp"
37 #include "gc/g1/g1CollectorState.hpp"
38 #include "gc/g1/g1ConcurrentMarkThread.inline.hpp"
39 #include "gc/g1/g1ConcurrentRefine.hpp"
40 #include "gc/g1/g1ConcurrentRefineThread.hpp"
41 #include "gc/g1/g1EvacStats.inline.hpp"
42 #include "gc/g1/g1FullCollector.hpp"
43 #include "gc/g1/g1GCCounters.hpp"
44 #include "gc/g1/g1GCParPhaseTimesTracker.hpp"
45 #include "gc/g1/g1GCPauseType.hpp"
46 #include "gc/g1/g1GCPhaseTimes.hpp"
47 #include "gc/g1/g1HeapRegion.inline.hpp"
48 #include "gc/g1/g1HeapRegionPrinter.hpp"
49 #include "gc/g1/g1HeapRegionRemSet.inline.hpp"
50 #include "gc/g1/g1HeapRegionSet.inline.hpp"
51 #include "gc/g1/g1HeapSizingPolicy.hpp"
52 #include "gc/g1/g1HeapTransition.hpp"
53 #include "gc/g1/g1HeapVerifier.hpp"
54 #include "gc/g1/g1InitLogger.hpp"
55 #include "gc/g1/g1MemoryPool.hpp"
56 #include "gc/g1/g1MonotonicArenaFreeMemoryTask.hpp"
57 #include "gc/g1/g1OopClosures.inline.hpp"
58 #include "gc/g1/g1ParallelCleaning.hpp"
59 #include "gc/g1/g1ParScanThreadState.inline.hpp"
60 #include "gc/g1/g1PeriodicGCTask.hpp"
61 #include "gc/g1/g1Policy.hpp"
62 #include "gc/g1/g1RegionPinCache.inline.hpp"
63 #include "gc/g1/g1RegionToSpaceMapper.hpp"
64 #include "gc/g1/g1RemSet.hpp"
65 #include "gc/g1/g1ReviseYoungLengthTask.hpp"
66 #include "gc/g1/g1RootClosures.hpp"
67 #include "gc/g1/g1SATBMarkQueueSet.hpp"
68 #include "gc/g1/g1ServiceThread.hpp"
69 #include "gc/g1/g1ThreadLocalData.hpp"
70 #include "gc/g1/g1Trace.hpp"
71 #include "gc/g1/g1UncommitRegionTask.hpp"
72 #include "gc/g1/g1VMOperations.hpp"
73 #include "gc/g1/g1YoungCollector.hpp"
74 #include "gc/g1/g1YoungGCAllocationFailureInjector.hpp"
75 #include "gc/shared/barrierSetNMethod.hpp"
76 #include "gc/shared/classUnloadingContext.hpp"
77 #include "gc/shared/concurrentGCBreakpoints.hpp"
78 #include "gc/shared/fullGCForwarding.inline.hpp"
79 #include "gc/shared/gcBehaviours.hpp"
80 #include "gc/shared/gcHeapSummary.hpp"
81 #include "gc/shared/gcId.hpp"
82 #include "gc/shared/gcTimer.hpp"
83 #include "gc/shared/gcTraceTime.inline.hpp"
84 #include "gc/shared/isGCActiveMark.hpp"
85 #include "gc/shared/locationPrinter.inline.hpp"
86 #include "gc/shared/oopStorageParState.hpp"
87 #include "gc/shared/partialArrayState.hpp"
88 #include "gc/shared/referenceProcessor.inline.hpp"
89 #include "gc/shared/suspendibleThreadSet.hpp"
90 #include "gc/shared/taskqueue.inline.hpp"
91 #include "gc/shared/taskTerminator.hpp"
92 #include "gc/shared/tlab_globals.hpp"
93 #include "gc/shared/weakProcessor.inline.hpp"
94 #include "gc/shared/workerPolicy.hpp"
95 #include "logging/log.hpp"
96 #include "memory/allocation.hpp"
97 #include "memory/heapInspection.hpp"
98 #include "memory/iterator.hpp"
99 #include "memory/memoryReserver.hpp"
100 #include "memory/metaspaceUtils.hpp"
101 #include "memory/resourceArea.hpp"
102 #include "memory/universe.hpp"
103 #include "oops/access.inline.hpp"
104 #include "oops/compressedOops.inline.hpp"
105 #include "oops/oop.inline.hpp"
106 #include "runtime/atomicAccess.hpp"
107 #include "runtime/cpuTimeCounters.hpp"
108 #include "runtime/handles.inline.hpp"
109 #include "runtime/init.hpp"
110 #include "runtime/java.hpp"
111 #include "runtime/orderAccess.hpp"
112 #include "runtime/threads.hpp"
113 #include "runtime/threadSMR.hpp"
114 #include "runtime/vmThread.hpp"
115 #include "utilities/align.hpp"
116 #include "utilities/autoRestore.hpp"
117 #include "utilities/bitMap.inline.hpp"
118 #include "utilities/globalDefinitions.hpp"
119 #include "utilities/stack.inline.hpp"
120
121 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
122
123 // INVARIANTS/NOTES
124 //
125 // All allocation activity covered by the G1CollectedHeap interface is
126 // serialized by acquiring the HeapLock. This happens in mem_allocate
127 // and allocate_new_tlab, which are the "entry" points to the
128 // allocation code from the rest of the JVM. (Note that this does not
129 // apply to TLAB allocation, which is not part of this interface: it
130 // is done by clients of this interface.)
131
132 void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) {
133 G1HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions);
134 }
135
136 void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) {
137 // The from card cache is not the memory that is actually committed. So we cannot
138 // take advantage of the zero_filled parameter.
139 reset_from_card_cache(start_idx, num_regions);
140 }
141
142 void G1CollectedHeap::run_batch_task(G1BatchedTask* 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 uint G1CollectedHeap::get_chunks_per_region_for_scan() {
149 uint log_region_size = G1HeapRegion::LogOfHRGrainBytes;
150 // Limit the expected input values to current known possible values of the
151 // (log) region size. Adjust as necessary after testing if changing the permissible
152 // values for region size.
153 assert(log_region_size >= 20 && log_region_size <= 29,
154 "expected value in [20,29], but got %u", log_region_size);
155 return 1u << (log_region_size / 2 - 4);
156 }
157
158 uint G1CollectedHeap::get_chunks_per_region_for_merge() {
159 uint log_region_size = G1HeapRegion::LogOfHRGrainBytes;
160 // Limit the expected input values to current known possible values of the
161 // (log) region size. Adjust as necessary after testing if changing the permissible
162 // values for region size.
163 assert(log_region_size >= 20 && log_region_size <= 29,
164 "expected value in [20,29], but got %u", log_region_size);
165
166 uint half_log_region_size = (log_region_size + 1) / 2;
167 return 1 << (half_log_region_size - 9);
168 }
169
170 G1HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index,
171 MemRegion mr) {
172 return new G1HeapRegion(hrs_index, bot(), mr, &_card_set_config);
173 }
174
175 // Private methods.
176
177 G1HeapRegion* G1CollectedHeap::new_region(size_t word_size,
178 G1HeapRegionType type,
179 bool do_expand,
180 uint node_index) {
181 assert(!is_humongous(word_size) || word_size <= G1HeapRegion::GrainWords,
182 "the only time we use this to allocate a humongous region is "
183 "when we are allocating a single humongous region");
184
185 G1HeapRegion* res = _hrm.allocate_free_region(type, node_index);
186
187 if (res == nullptr && do_expand) {
188 // There are two situations where do_expand is set to true:
189 // - for mutator regions during initialization
190 // - for GC alloc regions during a safepoint
191 // Make sure we only reach here before initialization is complete
192 // or during a safepoint.
193 assert(!is_init_completed() ||
194 SafepointSynchronize::is_at_safepoint() , "invariant");
195
196 log_debug(gc, ergo, heap)("Attempt heap expansion (region allocation request failed). Allocation request: %zuB",
197 word_size * HeapWordSize);
198
199 assert(word_size * HeapWordSize < G1HeapRegion::GrainBytes,
200 "This kind of expansion should never be more than one region. Size: %zu",
201 word_size * HeapWordSize);
202 if (expand_single_region(node_index)) {
203 // Given that expand_single_region() succeeded in expanding the heap, and we
204 // always expand the heap by an amount aligned to the heap
205 // region size, the free list should in theory not be empty.
206 // In either case allocate_free_region() will check for null.
207 res = _hrm.allocate_free_region(type, node_index);
208 }
209 }
210 return res;
211 }
212
213 void G1CollectedHeap::set_humongous_metadata(G1HeapRegion* first_hr,
214 uint num_regions,
215 size_t word_size,
216 bool update_remsets) {
217 // Calculate the new top of the humongous object.
218 HeapWord* obj_top = first_hr->bottom() + word_size;
219 // The word size sum of all the regions used
220 size_t word_size_sum = num_regions * G1HeapRegion::GrainWords;
221 assert(word_size <= word_size_sum, "sanity");
222
223 // How many words memory we "waste" which cannot hold a filler object.
224 size_t words_not_fillable = 0;
225
226 // Pad out the unused tail of the last region with filler
227 // objects, for improved usage accounting.
228
229 // How many words can we use for filler objects.
230 size_t words_fillable = word_size_sum - word_size;
231
232 if (words_fillable >= G1CollectedHeap::min_fill_size()) {
233 G1CollectedHeap::fill_with_objects(obj_top, words_fillable);
234 } else {
235 // We have space to fill, but we cannot fit an object there.
236 words_not_fillable = words_fillable;
237 words_fillable = 0;
238 }
239
240 // We will set up the first region as "starts humongous". This
241 // will also update the BOT covering all the regions to reflect
242 // that there is a single object that starts at the bottom of the
243 // first region.
244 first_hr->hr_clear(false /* clear_space */);
245 first_hr->set_starts_humongous(obj_top, words_fillable);
246
247 if (update_remsets) {
248 _policy->remset_tracker()->update_at_allocate(first_hr);
249 }
250
251 // Indices of first and last regions in the series.
252 uint first = first_hr->hrm_index();
253 uint last = first + num_regions - 1;
254
255 G1HeapRegion* hr = nullptr;
256 for (uint i = first + 1; i <= last; ++i) {
257 hr = region_at(i);
258 hr->hr_clear(false /* clear_space */);
259 hr->set_continues_humongous(first_hr);
260 if (update_remsets) {
261 _policy->remset_tracker()->update_at_allocate(hr);
262 }
263 }
264
265 // Up to this point no concurrent thread would have been able to
266 // do any scanning on any region in this series. All the top
267 // fields still point to bottom, so the intersection between
268 // [bottom,top] and [card_start,card_end] will be empty. Before we
269 // update the top fields, we'll do a storestore to make sure that
270 // no thread sees the update to top before the zeroing of the
271 // object header and the BOT initialization.
272 OrderAccess::storestore();
273
274 // Now, we will update the top fields of the "continues humongous"
275 // regions except the last one.
276 for (uint i = first; i < last; ++i) {
277 hr = region_at(i);
278 hr->set_top(hr->end());
279 }
280
281 hr = region_at(last);
282 // If we cannot fit a filler object, we must set top to the end
283 // of the humongous object, otherwise we cannot iterate the heap
284 // and the BOT will not be complete.
285 hr->set_top(hr->end() - words_not_fillable);
286
287 assert(hr->bottom() < obj_top && obj_top <= hr->end(),
288 "obj_top should be in last region");
289
290 assert(words_not_fillable == 0 ||
291 first_hr->bottom() + word_size_sum - words_not_fillable == hr->top(),
292 "Miscalculation in humongous allocation");
293 }
294
295 HeapWord*
296 G1CollectedHeap::humongous_obj_allocate_initialize_regions(G1HeapRegion* first_hr,
297 uint num_regions,
298 size_t word_size) {
299 assert(first_hr != nullptr, "pre-condition");
300 assert(is_humongous(word_size), "word_size should be humongous");
301 assert(num_regions * G1HeapRegion::GrainWords >= word_size, "pre-condition");
302
303 // Index of last region in the series.
304 uint first = first_hr->hrm_index();
305 uint last = first + num_regions - 1;
306
307 // We need to initialize the region(s) we just discovered. This is
308 // a bit tricky given that it can happen concurrently with
309 // refinement threads refining cards on these regions and
310 // potentially wanting to refine the BOT as they are scanning
311 // those cards (this can happen shortly after a cleanup; see CR
312 // 6991377). So we have to set up the region(s) carefully and in
313 // a specific order.
314
315 // The passed in hr will be the "starts humongous" region. The header
316 // of the new object will be placed at the bottom of this region.
317 HeapWord* new_obj = first_hr->bottom();
318
319 // First, we need to zero the header of the space that we will be
320 // allocating. When we update top further down, some refinement
321 // threads might try to scan the region. By zeroing the header we
322 // ensure that any thread that will try to scan the region will
323 // come across the zero klass word and bail out.
324 //
325 // NOTE: It would not have been correct to have used
326 // CollectedHeap::fill_with_object() and make the space look like
327 // an int array. The thread that is doing the allocation will
328 // later update the object header to a potentially different array
329 // type and, for a very short period of time, the klass and length
330 // fields will be inconsistent. This could cause a refinement
331 // thread to calculate the object size incorrectly.
332 Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
333
334 // Next, update the metadata for the regions.
335 set_humongous_metadata(first_hr, num_regions, word_size, true);
336
337 G1HeapRegion* last_hr = region_at(last);
338 size_t used = byte_size(first_hr->bottom(), last_hr->top());
339
340 increase_used(used);
341
342 for (uint i = first; i <= last; ++i) {
343 G1HeapRegion *hr = region_at(i);
344 _humongous_set.add(hr);
345 G1HeapRegionPrinter::alloc(hr);
346 }
347
348 return new_obj;
349 }
350
351 size_t G1CollectedHeap::humongous_obj_size_in_regions(size_t word_size) {
352 assert(is_humongous(word_size), "Object of size %zu must be humongous here", word_size);
353 return align_up(word_size, G1HeapRegion::GrainWords) / G1HeapRegion::GrainWords;
354 }
355
356 size_t G1CollectedHeap::allocation_used_bytes(size_t allocation_word_size) {
357 if (is_humongous(allocation_word_size)) {
358 return humongous_obj_size_in_regions(allocation_word_size) * G1HeapRegion::GrainBytes;
359 } else {
360 return allocation_word_size * HeapWordSize;
361 }
362 }
363
364 // If could fit into free regions w/o expansion, try.
365 // Otherwise, if can expand, do so.
366 // Otherwise, if using ex regions might help, try with ex given back.
367 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {
368 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
369
370 _verifier->verify_region_sets_optional();
371
372 uint obj_regions = (uint) humongous_obj_size_in_regions(word_size);
373 if (obj_regions > num_available_regions()) {
374 // Can't satisfy this allocation; early-return.
375 return nullptr;
376 }
377
378 // Policy: First try to allocate a humongous object in the free list.
379 G1HeapRegion* humongous_start = _hrm.allocate_humongous(obj_regions);
380 if (humongous_start == nullptr) {
381 // Policy: We could not find enough regions for the humongous object in the
382 // free list. Look through the heap to find a mix of free and uncommitted regions.
383 // If so, expand the heap and allocate the humongous object.
384 humongous_start = _hrm.expand_and_allocate_humongous(obj_regions);
385 if (humongous_start != nullptr) {
386 // We managed to find a region by expanding the heap.
387 log_debug(gc, ergo, heap)("Heap expansion (humongous allocation request). Allocation request: %zuB",
388 word_size * HeapWordSize);
389 policy()->record_new_heap_size(num_committed_regions());
390 } else {
391 // Policy: Potentially trigger a defragmentation GC.
392 }
393 }
394
395 HeapWord* result = nullptr;
396 if (humongous_start != nullptr) {
397 result = humongous_obj_allocate_initialize_regions(humongous_start, obj_regions, word_size);
398 assert(result != nullptr, "it should always return a valid result");
399
400 // A successful humongous object allocation changes the used space
401 // information of the old generation so we need to recalculate the
402 // sizes and update the jstat counters here.
403 monitoring_support()->update_sizes();
404 }
405
406 _verifier->verify_region_sets_optional();
407
408 return result;
409 }
410
411 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t min_size,
412 size_t requested_size,
413 size_t* actual_size) {
414 assert_heap_not_locked_and_not_at_safepoint();
415 assert(!is_humongous(requested_size), "we do not allow humongous TLABs");
416
417 // Do not allow a GC because we are allocating a new TLAB to avoid an issue
418 // with UseGCOverheadLimit: although this GC would return null if the overhead
419 // limit would be exceeded, but it would likely free at least some space.
420 // So the subsequent outside-TLAB allocation could be successful anyway and
421 // the indication that the overhead limit had been exceeded swallowed.
422 return attempt_allocation(min_size, requested_size, actual_size, false /* allow_gc */);
423 }
424
425 HeapWord* G1CollectedHeap::mem_allocate(size_t word_size) {
426 assert_heap_not_locked_and_not_at_safepoint();
427
428 if (is_humongous(word_size)) {
429 return attempt_allocation_humongous(word_size);
430 }
431 size_t dummy = 0;
432 return attempt_allocation(word_size, word_size, &dummy, true /* allow_gc */);
433 }
434
435 HeapWord* G1CollectedHeap::attempt_allocation_slow(uint node_index, size_t word_size, bool allow_gc) {
436 ResourceMark rm; // For retrieving the thread names in log messages.
437
438 // Make sure you read the note in attempt_allocation_humongous().
439
440 assert_heap_not_locked_and_not_at_safepoint();
441 assert(!is_humongous(word_size), "attempt_allocation_slow() should not "
442 "be called for humongous allocation requests");
443
444 // We should only get here after the first-level allocation attempt
445 // (attempt_allocation()) failed to allocate.
446
447 // We will loop until a) we manage to successfully perform the allocation or b)
448 // successfully schedule a collection which fails to perform the allocation.
449 // Case b) is the only case when we'll return null.
450 HeapWord* result = nullptr;
451 for (uint try_count = 1; /* we'll return */; try_count++) {
452 uint gc_count_before;
453
454 {
455 MutexLocker x(Heap_lock);
456
457 // Now that we have the lock, we first retry the allocation in case another
458 // thread changed the region while we were waiting to acquire the lock.
459 result = _allocator->attempt_allocation_locked(node_index, word_size);
460 if (result != nullptr) {
461 return result;
462 } else if (!allow_gc) {
463 return nullptr;
464 }
465
466 // Read the GC count while still holding the Heap_lock.
467 gc_count_before = total_collections();
468 }
469
470 bool succeeded;
471 result = do_collection_pause(word_size, gc_count_before, &succeeded, GCCause::_g1_inc_collection_pause);
472 if (succeeded) {
473 log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
474 Thread::current()->name(), p2i(result));
475 return result;
476 }
477
478 log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating %zu words",
479 Thread::current()->name(), word_size);
480
481 // Has the gc overhead limit been reached in the meantime? If so, this mutator
482 // should receive null even when unsuccessfully scheduling a collection as well
483 // for global consistency.
484 if (gc_overhead_limit_exceeded()) {
485 return nullptr;
486 }
487
488 // We can reach here if we were unsuccessful in scheduling a collection (because
489 // another thread beat us to it). In this case immediately retry the allocation
490 // attempt because another thread successfully performed a collection and possibly
491 // reclaimed enough space. The first attempt (without holding the Heap_lock) is
492 // here and the follow-on attempt will be at the start of the next loop
493 // iteration (after taking the Heap_lock).
494 size_t dummy = 0;
495 result = _allocator->attempt_allocation(node_index, word_size, word_size, &dummy);
496 if (result != nullptr) {
497 return result;
498 }
499
500 // Give a warning if we seem to be looping forever.
501 if ((QueuedAllocationWarningCount > 0) &&
502 (try_count % QueuedAllocationWarningCount == 0)) {
503 log_warning(gc, alloc)("%s: Retried allocation %u times for %zu words",
504 Thread::current()->name(), try_count, word_size);
505 }
506 }
507
508 ShouldNotReachHere();
509 return nullptr;
510 }
511
512 template <typename Func>
513 void G1CollectedHeap::iterate_regions_in_range(MemRegion range, const Func& func) {
514 // Mark each G1 region touched by the range as old, add it to
515 // the old set, and set top.
516 G1HeapRegion* curr_region = _hrm.addr_to_region(range.start());
517 G1HeapRegion* end_region = _hrm.addr_to_region(range.last());
518
519 while (curr_region != nullptr) {
520 bool is_last = curr_region == end_region;
521 G1HeapRegion* next_region = is_last ? nullptr : _hrm.next_region_in_heap(curr_region);
522
523 func(curr_region, is_last);
524
525 curr_region = next_region;
526 }
527 }
528
529 HeapWord* G1CollectedHeap::alloc_archive_region(size_t word_size, HeapWord* preferred_addr) {
530 assert(!is_init_completed(), "Expect to be called at JVM init time");
531 MutexLocker x(Heap_lock);
532
533 MemRegion reserved = _hrm.reserved();
534
535 if (reserved.word_size() <= word_size) {
536 log_info(gc, heap)("Unable to allocate regions as archive heap is too large; size requested = %zu"
537 " bytes, heap = %zu bytes", word_size * HeapWordSize, reserved.byte_size());
538 return nullptr;
539 }
540
541 // Temporarily disable pretouching of heap pages. This interface is used
542 // when mmap'ing archived heap data in, so pre-touching is wasted.
543 FlagSetting fs(AlwaysPreTouch, false);
544
545 size_t commits = 0;
546 // Attempt to allocate towards the end of the heap.
547 HeapWord* start_addr = reserved.end() - align_up(word_size, G1HeapRegion::GrainWords);
548 MemRegion range = MemRegion(start_addr, word_size);
549 HeapWord* last_address = range.last();
550 if (!_hrm.allocate_containing_regions(range, &commits, workers())) {
551 return nullptr;
552 }
553 increase_used(word_size * HeapWordSize);
554 if (commits != 0) {
555 log_debug(gc, ergo, heap)("Attempt heap expansion (allocate archive regions). Total size: %zuB",
556 G1HeapRegion::GrainWords * HeapWordSize * commits);
557 }
558
559 // Mark each G1 region touched by the range as old, add it to
560 // the old set, and set top.
561 auto set_region_to_old = [&] (G1HeapRegion* r, bool is_last) {
562 assert(r->is_empty(), "Region already in use (%u)", r->hrm_index());
563
564 HeapWord* top = is_last ? last_address + 1 : r->end();
565 r->set_top(top);
566
567 r->set_old();
568 G1HeapRegionPrinter::alloc(r);
569 _old_set.add(r);
570 };
571
572 iterate_regions_in_range(range, set_region_to_old);
573 return start_addr;
574 }
575
576 void G1CollectedHeap::populate_archive_regions_bot(MemRegion range) {
577 assert(!is_init_completed(), "Expect to be called at JVM init time");
578
579 iterate_regions_in_range(range,
580 [&] (G1HeapRegion* r, bool is_last) {
581 r->update_bot();
582 });
583 }
584
585 void G1CollectedHeap::dealloc_archive_regions(MemRegion range) {
586 assert(!is_init_completed(), "Expect to be called at JVM init time");
587 MemRegion reserved = _hrm.reserved();
588 size_t size_used = 0;
589
590 // Free the G1 regions that are within the specified range.
591 MutexLocker x(Heap_lock);
592 HeapWord* start_address = range.start();
593 HeapWord* last_address = range.last();
594
595 assert(reserved.contains(start_address) && reserved.contains(last_address),
596 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
597 p2i(start_address), p2i(last_address));
598 size_used += range.byte_size();
599
600 uint max_shrink_count = 0;
601 if (capacity() > MinHeapSize) {
602 size_t max_shrink_bytes = capacity() - MinHeapSize;
603 max_shrink_count = (uint)(max_shrink_bytes / G1HeapRegion::GrainBytes);
604 }
605
606 uint shrink_count = 0;
607 // Free, empty and uncommit regions with CDS archive content.
608 auto dealloc_archive_region = [&] (G1HeapRegion* r, bool is_last) {
609 guarantee(r->is_old(), "Expected old region at index %u", r->hrm_index());
610 _old_set.remove(r);
611 r->set_free();
612 r->set_top(r->bottom());
613 if (shrink_count < max_shrink_count) {
614 _hrm.shrink_at(r->hrm_index(), 1);
615 shrink_count++;
616 } else {
617 _hrm.insert_into_free_list(r);
618 }
619 };
620
621 iterate_regions_in_range(range, dealloc_archive_region);
622
623 if (shrink_count != 0) {
624 log_debug(gc, ergo, heap)("Attempt heap shrinking (CDS archive regions). Total size: %zuB (%u Regions)",
625 G1HeapRegion::GrainWords * HeapWordSize * shrink_count, shrink_count);
626 // Explicit uncommit.
627 uncommit_regions(shrink_count);
628 }
629 decrease_used(size_used);
630 }
631
632 inline HeapWord* G1CollectedHeap::attempt_allocation(size_t min_word_size,
633 size_t desired_word_size,
634 size_t* actual_word_size,
635 bool allow_gc) {
636 assert_heap_not_locked_and_not_at_safepoint();
637 assert(!is_humongous(desired_word_size), "attempt_allocation() should not "
638 "be called for humongous allocation requests");
639
640 // Fix NUMA node association for the duration of this allocation
641 const uint node_index = _allocator->current_node_index();
642
643 HeapWord* result = _allocator->attempt_allocation(node_index, min_word_size, desired_word_size, actual_word_size);
644
645 if (result == nullptr) {
646 *actual_word_size = desired_word_size;
647 result = attempt_allocation_slow(node_index, desired_word_size, allow_gc);
648 }
649
650 assert_heap_not_locked();
651 if (result != nullptr) {
652 assert(*actual_word_size != 0, "Actual size must have been set here");
653 } else {
654 *actual_word_size = 0;
655 }
656
657 return result;
658 }
659
660 // Helper for [try_]collect().
661 static G1GCCounters collection_counters(G1CollectedHeap* g1h) {
662 MutexLocker ml(Heap_lock);
663 return G1GCCounters(g1h);
664 }
665
666 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) {
667 ResourceMark rm; // For retrieving the thread names in log messages.
668
669 // The structure of this method has a lot of similarities to
670 // attempt_allocation_slow(). The reason these two were not merged
671 // into a single one is that such a method would require several "if
672 // allocation is not humongous do this, otherwise do that"
673 // conditional paths which would obscure its flow. In fact, an early
674 // version of this code did use a unified method which was harder to
675 // follow and, as a result, it had subtle bugs that were hard to
676 // track down. So keeping these two methods separate allows each to
677 // be more readable. It will be good to keep these two in sync as
678 // much as possible.
679
680 assert_heap_not_locked_and_not_at_safepoint();
681 assert(is_humongous(word_size), "attempt_allocation_humongous() "
682 "should only be called for humongous allocations");
683
684 // Humongous objects can exhaust the heap quickly, so we should check if we
685 // need to start a marking cycle at each humongous object allocation. We do
686 // the check before we do the actual allocation. The reason for doing it
687 // before the allocation is that we avoid having to keep track of the newly
688 // allocated memory while we do a GC.
689 if (policy()->need_to_start_conc_mark("concurrent humongous allocation",
690 word_size)) {
691 try_collect(word_size, GCCause::_g1_humongous_allocation, collection_counters(this));
692 }
693
694 // We will loop until a) we manage to successfully perform the allocation or b)
695 // successfully schedule a collection which fails to perform the allocation.
696 // Case b) is the only case when we'll return null.
697 HeapWord* result = nullptr;
698 for (uint try_count = 1; /* we'll return */; try_count++) {
699 uint gc_count_before;
700
701 // The amount of bytes the humongous object will actually take.
702 size_t humongous_byte_size = G1HeapRegion::align_up_to_region_byte_size(word_size * HeapWordSize);
703
704 {
705 MutexLocker x(Heap_lock);
706
707 // Given that humongous objects are not allocated in young
708 // regions, we'll first try to do the allocation without doing a
709 // collection hoping that there's enough space in the heap.
710 result = humongous_obj_allocate(word_size);
711 if (result != nullptr) {
712 policy()->old_gen_alloc_tracker()->
713 add_allocated_humongous_bytes_since_last_gc(humongous_byte_size);
714 return result;
715 }
716
717 // Read the GC count while still holding the Heap_lock.
718 gc_count_before = total_collections();
719 }
720
721 bool succeeded;
722 result = do_collection_pause(word_size, gc_count_before, &succeeded, GCCause::_g1_humongous_allocation);
723 if (succeeded) {
724 log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
725 Thread::current()->name(), p2i(result));
726 if (result != nullptr) {
727 policy()->old_gen_alloc_tracker()->
728 record_collection_pause_humongous_allocation(humongous_byte_size);
729 }
730 return result;
731 }
732
733 log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating %zu",
734 Thread::current()->name(), word_size);
735
736 // Has the gc overhead limit been reached in the meantime? If so, this mutator
737 // should receive null even when unsuccessfully scheduling a collection as well
738 // for global consistency.
739 if (gc_overhead_limit_exceeded()) {
740 return nullptr;
741 }
742
743 // We can reach here if we were unsuccessful in scheduling a collection (because
744 // another thread beat us to it).
745 // Humongous object allocation always needs a lock, so we wait for the retry
746 // in the next iteration of the loop, unlike for the regular iteration case.
747 // Give a warning if we seem to be looping forever.
748
749 if ((QueuedAllocationWarningCount > 0) &&
750 (try_count % QueuedAllocationWarningCount == 0)) {
751 log_warning(gc, alloc)("%s: Retried allocation %u times for %zu words",
752 Thread::current()->name(), try_count, word_size);
753 }
754 }
755
756 ShouldNotReachHere();
757 return nullptr;
758 }
759
760 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
761 bool expect_null_mutator_alloc_region) {
762 assert_at_safepoint_on_vm_thread();
763 assert(!_allocator->has_mutator_alloc_region() || !expect_null_mutator_alloc_region,
764 "the current alloc region was unexpectedly found to be non-null");
765
766 // Fix NUMA node association for the duration of this allocation
767 const uint node_index = _allocator->current_node_index();
768
769 if (!is_humongous(word_size)) {
770 return _allocator->attempt_allocation_locked(node_index, word_size);
771 } else {
772 HeapWord* result = humongous_obj_allocate(word_size);
773 if (result != nullptr &&
774 // We just allocated the humongous object, so the given allocation size is 0.
775 policy()->need_to_start_conc_mark("STW humongous allocation", 0 /* allocation_word_size */)) {
776 collector_state()->set_initiate_conc_mark_if_possible(true);
777 }
778 return result;
779 }
780
781 ShouldNotReachHere();
782 }
783
784 class PostCompactionPrinterClosure: public G1HeapRegionClosure {
785 public:
786 bool do_heap_region(G1HeapRegion* hr) {
787 assert(!hr->is_young(), "not expecting to find young regions");
788 G1HeapRegionPrinter::post_compaction(hr);
789 return false;
790 }
791 };
792
793 void G1CollectedHeap::print_heap_after_full_collection() {
794 // Post collection region logging.
795 // We should do this after we potentially resize the heap so
796 // that all the COMMIT / UNCOMMIT events are generated before
797 // the compaction events.
798 if (G1HeapRegionPrinter::is_active()) {
799 PostCompactionPrinterClosure cl;
800 heap_region_iterate(&cl);
801 }
802 }
803
804 bool G1CollectedHeap::abort_concurrent_cycle() {
805 // Disable discovery and empty the discovered lists
806 // for the CM ref processor.
807 _ref_processor_cm->disable_discovery();
808 _ref_processor_cm->abandon_partial_discovery();
809 _ref_processor_cm->verify_no_references_recorded();
810
811 // Abandon current iterations of concurrent marking and concurrent
812 // refinement, if any are in progress.
813 return concurrent_mark()->concurrent_cycle_abort();
814 }
815
816 void G1CollectedHeap::prepare_heap_for_full_collection() {
817 // Make sure we'll choose a new allocation region afterwards.
818 _allocator->release_mutator_alloc_regions();
819 _allocator->abandon_gc_alloc_regions();
820
821 // We may have added regions to the current incremental collection
822 // set between the last GC or pause and now. We need to clear the
823 // incremental collection set and then start rebuilding it afresh
824 // after this full GC.
825 abandon_collection_set();
826
827 _hrm.remove_all_free_regions();
828 }
829
830 void G1CollectedHeap::verify_before_full_collection() {
831 assert_used_and_recalculate_used_equal(this);
832 if (!VerifyBeforeGC) {
833 return;
834 }
835 if (!G1HeapVerifier::should_verify(G1HeapVerifier::G1VerifyFull)) {
836 return;
837 }
838 _verifier->verify_region_sets_optional();
839 _verifier->verify_before_gc();
840 _verifier->verify_bitmap_clear(true /* above_tams_only */);
841 }
842
843 void G1CollectedHeap::prepare_for_mutator_after_full_collection(size_t allocation_word_size) {
844 // Prepare heap for normal collections.
845 assert(num_free_regions() == 0, "we should not have added any free regions");
846 rebuild_region_sets(false /* free_list_only */);
847 abort_refinement();
848 resize_heap_after_full_collection(allocation_word_size);
849
850 // Rebuild the code root lists for each region
851 rebuild_code_roots();
852 finish_codecache_marking_cycle();
853
854 start_new_collection_set();
855 _allocator->init_mutator_alloc_regions();
856
857 // Post collection state updates.
858 MetaspaceGC::compute_new_size();
859 }
860
861 void G1CollectedHeap::abort_refinement() {
862 G1ConcurrentRefineSweepState& sweep_state = concurrent_refine()->sweep_state();
863 if (sweep_state.is_in_progress()) {
864
865 if (!sweep_state.are_java_threads_synched()) {
866 // Synchronize Java threads with global card table that has already been swapped.
867 class SwapThreadCardTableClosure : public ThreadClosure {
868 public:
869
870 virtual void do_thread(Thread* t) {
871 G1BarrierSet* bs = G1BarrierSet::g1_barrier_set();
872 bs->update_card_table_base(t);
873 }
874 } cl;
875 Threads::java_threads_do(&cl);
876 }
877
878 // Record any available refinement statistics.
879 policy()->record_refinement_stats(sweep_state.stats());
880 sweep_state.complete_work(false /* concurrent */, false /* print_log */);
881 }
882 sweep_state.reset_stats();
883 }
884
885 void G1CollectedHeap::verify_after_full_collection() {
886 if (!VerifyAfterGC) {
887 return;
888 }
889 if (!G1HeapVerifier::should_verify(G1HeapVerifier::G1VerifyFull)) {
890 return;
891 }
892 _hrm.verify_optional();
893 _verifier->verify_region_sets_optional();
894 _verifier->verify_card_tables_clean(true /* both_card_tables */);
895 _verifier->verify_after_gc();
896 _verifier->verify_bitmap_clear(false /* above_tams_only */);
897
898 // At this point there should be no regions in the
899 // entire heap tagged as young.
900 assert(check_young_list_empty(), "young list should be empty at this point");
901
902 // Note: since we've just done a full GC, concurrent
903 // marking is no longer active. Therefore we need not
904 // re-enable reference discovery for the CM ref processor.
905 // That will be done at the start of the next marking cycle.
906 // We also know that the STW processor should no longer
907 // discover any new references.
908 assert(!_ref_processor_stw->discovery_enabled(), "Postcondition");
909 assert(!_ref_processor_cm->discovery_enabled(), "Postcondition");
910 _ref_processor_stw->verify_no_references_recorded();
911 _ref_processor_cm->verify_no_references_recorded();
912 }
913
914 void G1CollectedHeap::do_full_collection(size_t allocation_word_size,
915 bool clear_all_soft_refs,
916 bool do_maximal_compaction) {
917 assert_at_safepoint_on_vm_thread();
918
919 G1FullGCMark gc_mark;
920 GCTraceTime(Info, gc) tm("Pause Full", nullptr, gc_cause(), true);
921 G1FullCollector collector(this, clear_all_soft_refs, do_maximal_compaction, gc_mark.tracer());
922
923 collector.prepare_collection();
924 collector.collect();
925 collector.complete_collection(allocation_word_size);
926 }
927
928 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
929 // Currently, there is no facility in the do_full_collection(bool) API to notify
930 // the caller that the collection did not succeed (e.g., because it was locked
931 // out by the GC locker). So, right now, we'll ignore the return value.
932
933 do_full_collection(size_t(0) /* allocation_word_size */,
934 clear_all_soft_refs,
935 false /* do_maximal_compaction */);
936 }
937
938 void G1CollectedHeap::upgrade_to_full_collection() {
939 GCCauseSetter compaction(this, GCCause::_g1_compaction_pause);
940 log_info(gc, ergo)("Attempting full compaction clearing soft references");
941 do_full_collection(size_t(0) /* allocation_word_size */,
942 true /* clear_all_soft_refs */,
943 false /* do_maximal_compaction */);
944 }
945
946
947 void G1CollectedHeap::resize_heap(size_t resize_bytes, bool should_expand) {
948 if (should_expand) {
949 expand(resize_bytes, _workers);
950 } else {
951 shrink(resize_bytes);
952 uncommit_regions_if_necessary();
953 }
954 }
955
956 void G1CollectedHeap::resize_heap_after_full_collection(size_t allocation_word_size) {
957 assert_at_safepoint_on_vm_thread();
958
959 bool should_expand;
960 size_t resize_bytes = _heap_sizing_policy->full_collection_resize_amount(should_expand, allocation_word_size);
961
962 if (resize_bytes != 0) {
963 resize_heap(resize_bytes, should_expand);
964 }
965 }
966
967 void G1CollectedHeap::resize_heap_after_young_collection(size_t allocation_word_size) {
968 Ticks start = Ticks::now();
969
970 bool should_expand;
971
972 size_t resize_bytes = _heap_sizing_policy->young_collection_resize_amount(should_expand, allocation_word_size);
973
974 if (resize_bytes != 0) {
975 resize_heap(resize_bytes, should_expand);
976 }
977
978 phase_times()->record_resize_heap_time((Ticks::now() - start).seconds() * 1000.0);
979 }
980
981 void G1CollectedHeap::update_gc_overhead_counter() {
982 assert(SafepointSynchronize::is_at_safepoint(), "precondition");
983
984 if (!UseGCOverheadLimit) {
985 return;
986 }
987
988 bool gc_time_over_limit = (_policy->analytics()->long_term_gc_time_ratio() * 100) >= GCTimeLimit;
989 double free_space_percent = percent_of(num_available_regions() * G1HeapRegion::GrainBytes, max_capacity());
990 bool free_space_below_limit = free_space_percent < GCHeapFreeLimit;
991
992 log_debug(gc)("GC Overhead Limit: GC Time %f Free Space %f Counter %zu",
993 (_policy->analytics()->long_term_gc_time_ratio() * 100),
994 free_space_percent,
995 _gc_overhead_counter);
996
997 if (gc_time_over_limit && free_space_below_limit) {
998 _gc_overhead_counter++;
999 } else {
1000 _gc_overhead_counter = 0;
1001 }
1002 }
1003
1004 bool G1CollectedHeap::gc_overhead_limit_exceeded() {
1005 return _gc_overhead_counter >= GCOverheadLimitThreshold;
1006 }
1007
1008 HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size,
1009 bool do_gc,
1010 bool maximal_compaction,
1011 bool expect_null_mutator_alloc_region) {
1012 // Skip allocation if GC overhead limit has been exceeded to let the mutator run
1013 // into an OOME. It can either exit "gracefully" or try to free up memory asap.
1014 // For the latter situation, keep running GCs. If the mutator frees up enough
1015 // memory quickly enough, the overhead(s) will go below the threshold(s) again
1016 // and the VM may continue running.
1017 // If we did not continue garbage collections, the (gc overhead) limit may decrease
1018 // enough by itself to not count as exceeding the limit any more, in the worst
1019 // case bouncing back-and-forth all the time.
1020 if (!gc_overhead_limit_exceeded()) {
1021 // Let's attempt the allocation first.
1022 HeapWord* result =
1023 attempt_allocation_at_safepoint(word_size,
1024 expect_null_mutator_alloc_region);
1025 if (result != nullptr) {
1026 return result;
1027 }
1028
1029 // In a G1 heap, we're supposed to keep allocation from failing by
1030 // incremental pauses. Therefore, at least for now, we'll favor
1031 // expansion over collection. (This might change in the future if we can
1032 // do something smarter than full collection to satisfy a failed alloc.)
1033 result = expand_and_allocate(word_size);
1034 if (result != nullptr) {
1035 return result;
1036 }
1037 }
1038
1039 if (do_gc) {
1040 GCCauseSetter compaction(this, GCCause::_g1_compaction_pause);
1041 // Expansion didn't work, we'll try to do a Full GC.
1042 // If maximal_compaction is set we clear all soft references and don't
1043 // allow any dead wood to be left on the heap.
1044 if (maximal_compaction) {
1045 log_info(gc, ergo)("Attempting maximal full compaction clearing soft references");
1046 } else {
1047 log_info(gc, ergo)("Attempting full compaction");
1048 }
1049 do_full_collection(word_size /* allocation_word_size */,
1050 maximal_compaction /* clear_all_soft_refs */,
1051 maximal_compaction /* do_maximal_compaction */);
1052 }
1053
1054 return nullptr;
1055 }
1056
1057 HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size) {
1058 assert_at_safepoint_on_vm_thread();
1059
1060 // Update GC overhead limits after the initial garbage collection leading to this
1061 // allocation attempt.
1062 update_gc_overhead_counter();
1063
1064 // Attempts to allocate followed by Full GC.
1065 HeapWord* result =
1066 satisfy_failed_allocation_helper(word_size,
1067 true, /* do_gc */
1068 false, /* maximal_compaction */
1069 false /* expect_null_mutator_alloc_region */);
1070
1071 if (result != nullptr) {
1072 return result;
1073 }
1074
1075 // Attempts to allocate followed by Full GC that will collect all soft references.
1076 result = satisfy_failed_allocation_helper(word_size,
1077 true, /* do_gc */
1078 true, /* maximal_compaction */
1079 true /* expect_null_mutator_alloc_region */);
1080
1081 if (result != nullptr) {
1082 return result;
1083 }
1084
1085 // Attempts to allocate, no GC
1086 result = satisfy_failed_allocation_helper(word_size,
1087 false, /* do_gc */
1088 false, /* maximal_compaction */
1089 true /* expect_null_mutator_alloc_region */);
1090
1091 if (result != nullptr) {
1092 return result;
1093 }
1094
1095 if (gc_overhead_limit_exceeded()) {
1096 log_info(gc)("GC Overhead Limit exceeded too often (%zu).", GCOverheadLimitThreshold);
1097 }
1098
1099 // What else? We might try synchronous finalization later. If the total
1100 // space available is large enough for the allocation, then a more
1101 // complete compaction phase than we've tried so far might be
1102 // appropriate.
1103 return nullptr;
1104 }
1105
1106 // Attempting to expand the heap sufficiently
1107 // to support an allocation of the given "word_size". If
1108 // successful, perform the allocation and return the address of the
1109 // allocated block, or else null.
1110
1111 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1112 assert_at_safepoint_on_vm_thread();
1113
1114 _verifier->verify_region_sets_optional();
1115
1116 size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
1117 log_debug(gc, ergo, heap)("Attempt heap expansion (allocation request failed). Allocation request: %zuB",
1118 word_size * HeapWordSize);
1119
1120
1121 if (expand(expand_bytes, _workers)) {
1122 _hrm.verify_optional();
1123 _verifier->verify_region_sets_optional();
1124 return attempt_allocation_at_safepoint(word_size,
1125 false /* expect_null_mutator_alloc_region */);
1126 }
1127 return nullptr;
1128 }
1129
1130 bool G1CollectedHeap::expand(size_t expand_bytes, WorkerThreads* pretouch_workers) {
1131 assert(expand_bytes > 0, "precondition");
1132
1133 size_t aligned_expand_bytes = os::align_up_vm_page_size(expand_bytes);
1134 aligned_expand_bytes = align_up(aligned_expand_bytes, G1HeapRegion::GrainBytes);
1135
1136 uint num_regions_to_expand = (uint)(aligned_expand_bytes / G1HeapRegion::GrainBytes);
1137
1138 log_debug(gc, ergo, heap)("Heap resize. Requested expansion amount: %zuB aligned expansion amount: %zuB (%u regions)",
1139 expand_bytes, aligned_expand_bytes, num_regions_to_expand);
1140
1141 if (num_inactive_regions() == 0) {
1142 log_debug(gc, ergo, heap)("Heap resize. Did not expand the heap (heap already fully expanded)");
1143 return false;
1144 }
1145
1146 uint expanded_by = _hrm.expand_by(num_regions_to_expand, pretouch_workers);
1147
1148 size_t actual_expand_bytes = expanded_by * G1HeapRegion::GrainBytes;
1149 assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
1150 policy()->record_new_heap_size(num_committed_regions());
1151
1152 return true;
1153 }
1154
1155 bool G1CollectedHeap::expand_single_region(uint node_index) {
1156 uint expanded_by = _hrm.expand_on_preferred_node(node_index);
1157
1158 if (expanded_by == 0) {
1159 assert(num_inactive_regions() == 0, "Should be no regions left, available: %u", num_inactive_regions());
1160 log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");
1161 return false;
1162 }
1163
1164 policy()->record_new_heap_size(num_committed_regions());
1165 return true;
1166 }
1167
1168 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
1169 assert(shrink_bytes > 0, "must be");
1170 assert(is_aligned(shrink_bytes, G1HeapRegion::GrainBytes),
1171 "Shrink request for %zuB not aligned to heap region size %zuB",
1172 shrink_bytes, G1HeapRegion::GrainBytes);
1173
1174 uint num_regions_to_remove = (uint)(shrink_bytes / G1HeapRegion::GrainBytes);
1175
1176 uint num_regions_removed = _hrm.shrink_by(num_regions_to_remove);
1177 size_t shrunk_bytes = num_regions_removed * G1HeapRegion::GrainBytes;
1178
1179 log_debug(gc, ergo, heap)("Heap resize. Requested shrinking amount: %zuB actual shrinking amount: %zuB (%u regions)",
1180 shrink_bytes, shrunk_bytes, num_regions_removed);
1181 if (num_regions_removed > 0) {
1182 policy()->record_new_heap_size(num_committed_regions());
1183 } else {
1184 log_debug(gc, ergo, heap)("Heap resize. Did not shrink the heap (heap shrinking operation failed)");
1185 }
1186 }
1187
1188 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1189 if (capacity() == min_capacity()) {
1190 log_debug(gc, ergo, heap)("Heap resize. Did not shrink the heap (heap already at minimum)");
1191 return;
1192 }
1193
1194 size_t aligned_shrink_bytes = os::align_down_vm_page_size(shrink_bytes);
1195 aligned_shrink_bytes = align_down(aligned_shrink_bytes, G1HeapRegion::GrainBytes);
1196
1197 aligned_shrink_bytes = capacity() - MAX2(capacity() - aligned_shrink_bytes, min_capacity());
1198 assert(is_aligned(aligned_shrink_bytes, G1HeapRegion::GrainBytes), "Bytes to shrink %zuB not aligned", aligned_shrink_bytes);
1199
1200 log_debug(gc, ergo, heap)("Heap resize. Requested shrink amount: %zuB aligned shrink amount: %zuB",
1201 shrink_bytes, aligned_shrink_bytes);
1202
1203 if (aligned_shrink_bytes == 0) {
1204 log_debug(gc, ergo, heap)("Heap resize. Did not shrink the heap (shrink request too small)");
1205 return;
1206 }
1207
1208 _verifier->verify_region_sets_optional();
1209
1210 // We should only reach here at the end of a Full GC or during Remark which
1211 // means we should not not be holding to any GC alloc regions. The method
1212 // below will make sure of that and do any remaining clean up.
1213 _allocator->abandon_gc_alloc_regions();
1214
1215 // Instead of tearing down / rebuilding the free lists here, we
1216 // could instead use the remove_all_pending() method on free_list to
1217 // remove only the ones that we need to remove.
1218 _hrm.remove_all_free_regions();
1219 shrink_helper(aligned_shrink_bytes);
1220 rebuild_region_sets(true /* free_list_only */);
1221
1222 _hrm.verify_optional();
1223 _verifier->verify_region_sets_optional();
1224 }
1225
1226 class OldRegionSetChecker : public G1HeapRegionSetChecker {
1227 public:
1228 void check_mt_safety() {
1229 // Master Old Set MT safety protocol:
1230 // (a) If we're at a safepoint, operations on the master old set
1231 // should be invoked:
1232 // - by the VM thread (which will serialize them), or
1233 // - by the GC workers while holding the FreeList_lock, if we're
1234 // at a safepoint for an evacuation pause (this lock is taken
1235 // anyway when an GC alloc region is retired so that a new one
1236 // is allocated from the free list), or
1237 // - by the GC workers while holding the OldSets_lock, if we're at a
1238 // safepoint for a cleanup pause.
1239 // (b) If we're not at a safepoint, operations on the master old set
1240 // should be invoked while holding the Heap_lock.
1241
1242 if (SafepointSynchronize::is_at_safepoint()) {
1243 guarantee(Thread::current()->is_VM_thread() ||
1244 G1FreeList_lock->owned_by_self() || G1OldSets_lock->owned_by_self(),
1245 "master old set MT safety protocol at a safepoint");
1246 } else {
1247 guarantee(Heap_lock->owned_by_self(), "master old set MT safety protocol outside a safepoint");
1248 }
1249 }
1250 bool is_correct_type(G1HeapRegion* hr) { return hr->is_old(); }
1251 const char* get_description() { return "Old Regions"; }
1252 };
1253
1254 class HumongousRegionSetChecker : public G1HeapRegionSetChecker {
1255 public:
1256 void check_mt_safety() {
1257 // Humongous Set MT safety protocol:
1258 // (a) If we're at a safepoint, operations on the master humongous
1259 // set should be invoked by either the VM thread (which will
1260 // serialize them) or by the GC workers while holding the
1261 // OldSets_lock.
1262 // (b) If we're not at a safepoint, operations on the master
1263 // humongous set should be invoked while holding the Heap_lock.
1264
1265 if (SafepointSynchronize::is_at_safepoint()) {
1266 guarantee(Thread::current()->is_VM_thread() ||
1267 G1OldSets_lock->owned_by_self(),
1268 "master humongous set MT safety protocol at a safepoint");
1269 } else {
1270 guarantee(Heap_lock->owned_by_self(),
1271 "master humongous set MT safety protocol outside a safepoint");
1272 }
1273 }
1274 bool is_correct_type(G1HeapRegion* hr) { return hr->is_humongous(); }
1275 const char* get_description() { return "Humongous Regions"; }
1276 };
1277
1278 G1CollectedHeap::G1CollectedHeap() :
1279 CollectedHeap(),
1280 _gc_overhead_counter(0),
1281 _service_thread(nullptr),
1282 _periodic_gc_task(nullptr),
1283 _free_arena_memory_task(nullptr),
1284 _revise_young_length_task(nullptr),
1285 _workers(nullptr),
1286 _refinement_epoch(0),
1287 _last_synchronized_start(0),
1288 _last_refinement_epoch_start(0),
1289 _yield_duration_in_refinement_epoch(0),
1290 _last_safepoint_refinement_epoch(0),
1291 _collection_pause_end(Ticks::now()),
1292 _old_set("Old Region Set", new OldRegionSetChecker()),
1293 _humongous_set("Humongous Region Set", new HumongousRegionSetChecker()),
1294 _bot(nullptr),
1295 _listener(),
1296 _numa(G1NUMA::create()),
1297 _hrm(),
1298 _allocator(nullptr),
1299 _allocation_failure_injector(),
1300 _verifier(nullptr),
1301 _summary_bytes_used(0),
1302 _bytes_used_during_gc(0),
1303 _survivor_evac_stats("Young", YoungPLABSize, PLABWeight),
1304 _old_evac_stats("Old", OldPLABSize, PLABWeight),
1305 _monitoring_support(nullptr),
1306 _num_humongous_objects(0),
1307 _num_humongous_reclaim_candidates(0),
1308 _collector_state(),
1309 _old_marking_cycles_started(0),
1310 _old_marking_cycles_completed(0),
1311 _eden(),
1312 _survivor(),
1313 _gc_timer_stw(new STWGCTimer()),
1314 _gc_tracer_stw(new G1NewTracer()),
1315 _policy(new G1Policy(_gc_timer_stw)),
1316 _heap_sizing_policy(nullptr),
1317 _collection_set(this, _policy),
1318 _rem_set(nullptr),
1319 _card_set_config(),
1320 _card_set_freelist_pool(G1CardSetConfiguration::num_mem_object_types()),
1321 _young_regions_cset_group(card_set_config(), &_card_set_freelist_pool, G1CSetCandidateGroup::YoungRegionId),
1322 _cm(nullptr),
1323 _cm_thread(nullptr),
1324 _cr(nullptr),
1325 _task_queues(nullptr),
1326 _partial_array_state_manager(nullptr),
1327 _ref_processor_stw(nullptr),
1328 _is_alive_closure_stw(this),
1329 _is_subject_to_discovery_stw(this),
1330 _ref_processor_cm(nullptr),
1331 _is_alive_closure_cm(),
1332 _is_subject_to_discovery_cm(this),
1333 _region_attr() {
1334
1335 _verifier = new G1HeapVerifier(this);
1336
1337 _allocator = new G1Allocator(this);
1338
1339 _heap_sizing_policy = G1HeapSizingPolicy::create(this, _policy->analytics());
1340
1341 _humongous_object_threshold_in_words = humongous_threshold_for(G1HeapRegion::GrainWords);
1342
1343 // Since filler arrays are never referenced, we can make them region sized.
1344 // This simplifies filling up the region in case we have some potentially
1345 // unreferenced (by Java code, but still in use by native code) pinned objects
1346 // in there.
1347 _filler_array_max_size = G1HeapRegion::GrainWords;
1348
1349 // Override the default _stack_chunk_max_size so that no humongous stack chunks are created
1350 _stack_chunk_max_size = _humongous_object_threshold_in_words;
1351
1352 uint n_queues = ParallelGCThreads;
1353 _task_queues = new G1ScannerTasksQueueSet(n_queues);
1354
1355 for (uint i = 0; i < n_queues; i++) {
1356 G1ScannerTasksQueue* q = new G1ScannerTasksQueue();
1357 _task_queues->register_queue(i, q);
1358 }
1359
1360 _partial_array_state_manager = new PartialArrayStateManager(n_queues);
1361
1362 _gc_tracer_stw->initialize();
1363 }
1364
1365 PartialArrayStateManager* G1CollectedHeap::partial_array_state_manager() const {
1366 return _partial_array_state_manager;
1367 }
1368
1369 G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description,
1370 size_t size,
1371 size_t translation_factor) {
1372 size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1);
1373
1374 // When a page size is given we don't want to mix large
1375 // and normal pages. If the size is not a multiple of the
1376 // page size it will be aligned up to achieve this.
1377 size_t alignment = os::vm_allocation_granularity();
1378 if (preferred_page_size != os::vm_page_size()) {
1379 alignment = MAX2(preferred_page_size, alignment);
1380 size = align_up(size, alignment);
1381 }
1382
1383 // Allocate a new reserved space, preferring to use large pages.
1384 ReservedSpace rs = MemoryReserver::reserve(size,
1385 alignment,
1386 preferred_page_size,
1387 mtGC);
1388
1389 size_t page_size = rs.page_size();
1390 G1RegionToSpaceMapper* result =
1391 G1RegionToSpaceMapper::create_mapper(rs,
1392 size,
1393 page_size,
1394 G1HeapRegion::GrainBytes,
1395 translation_factor,
1396 mtGC);
1397
1398 os::trace_page_sizes_for_requested_size(description,
1399 size,
1400 preferred_page_size,
1401 rs.base(),
1402 rs.size(),
1403 page_size);
1404
1405 return result;
1406 }
1407
1408 jint G1CollectedHeap::initialize_concurrent_refinement() {
1409 jint ecode = JNI_OK;
1410 _cr = G1ConcurrentRefine::create(this, &ecode);
1411 return ecode;
1412 }
1413
1414 jint G1CollectedHeap::initialize_service_thread() {
1415 _service_thread = new G1ServiceThread();
1416 if (_service_thread->osthread() == nullptr) {
1417 vm_shutdown_during_initialization("Could not create G1ServiceThread");
1418 return JNI_ENOMEM;
1419 }
1420 return JNI_OK;
1421 }
1422
1423 jint G1CollectedHeap::initialize() {
1424
1425 if (!os::is_thread_cpu_time_supported()) {
1426 vm_exit_during_initialization("G1 requires cpu time gathering support");
1427 }
1428 // Necessary to satisfy locking discipline assertions.
1429
1430 MutexLocker x(Heap_lock);
1431
1432 // While there are no constraints in the GC code that HeapWordSize
1433 // be any particular value, there are multiple other areas in the
1434 // system which believe this to be true (e.g. oop->object_size in some
1435 // cases incorrectly returns the size in wordSize units rather than
1436 // HeapWordSize).
1437 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1438
1439 size_t init_byte_size = InitialHeapSize;
1440 size_t reserved_byte_size = G1Arguments::heap_reserved_size_bytes();
1441
1442 // Ensure that the sizes are properly aligned.
1443 Universe::check_alignment(init_byte_size, G1HeapRegion::GrainBytes, "g1 heap");
1444 Universe::check_alignment(reserved_byte_size, G1HeapRegion::GrainBytes, "g1 heap");
1445 Universe::check_alignment(reserved_byte_size, HeapAlignment, "g1 heap");
1446
1447 // Reserve the maximum.
1448
1449 // When compressed oops are enabled, the preferred heap base
1450 // is calculated by subtracting the requested size from the
1451 // 32Gb boundary and using the result as the base address for
1452 // heap reservation. If the requested size is not aligned to
1453 // G1HeapRegion::GrainBytes (i.e. the alignment that is passed
1454 // into the ReservedHeapSpace constructor) then the actual
1455 // base of the reserved heap may end up differing from the
1456 // address that was requested (i.e. the preferred heap base).
1457 // If this happens then we could end up using a non-optimal
1458 // compressed oops mode.
1459
1460 ReservedHeapSpace heap_rs = Universe::reserve_heap(reserved_byte_size,
1461 HeapAlignment);
1462
1463 initialize_reserved_region(heap_rs);
1464
1465 // Create the barrier set for the entire reserved region.
1466 G1CardTable* card_table = new G1CardTable(_reserved);
1467 G1CardTable* refinement_table = new G1CardTable(_reserved);
1468
1469 G1BarrierSet* bs = new G1BarrierSet(card_table, refinement_table);
1470 assert(bs->is_a(BarrierSet::G1BarrierSet), "sanity");
1471
1472 // Create space mappers.
1473 size_t page_size = heap_rs.page_size();
1474 G1RegionToSpaceMapper* heap_storage =
1475 G1RegionToSpaceMapper::create_mapper(heap_rs,
1476 heap_rs.size(),
1477 page_size,
1478 G1HeapRegion::GrainBytes,
1479 1,
1480 mtJavaHeap);
1481 if(heap_storage == nullptr) {
1482 vm_shutdown_during_initialization("Could not initialize G1 heap");
1483 return JNI_ERR;
1484 }
1485
1486 os::trace_page_sizes("Heap",
1487 min_capacity(),
1488 reserved_byte_size,
1489 heap_rs.base(),
1490 heap_rs.size(),
1491 page_size);
1492 heap_storage->set_mapping_changed_listener(&_listener);
1493
1494 // Create storage for the BOT, card table and the bitmap.
1495 G1RegionToSpaceMapper* bot_storage =
1496 create_aux_memory_mapper("Block Offset Table",
1497 G1BlockOffsetTable::compute_size(heap_rs.size() / HeapWordSize),
1498 G1BlockOffsetTable::heap_map_factor());
1499
1500 G1RegionToSpaceMapper* cardtable_storage =
1501 create_aux_memory_mapper("Card Table",
1502 G1CardTable::compute_size(heap_rs.size() / HeapWordSize),
1503 G1CardTable::heap_map_factor());
1504
1505 G1RegionToSpaceMapper* refinement_cards_storage =
1506 create_aux_memory_mapper("Refinement Card Table",
1507 G1CardTable::compute_size(heap_rs.size() / HeapWordSize),
1508 G1CardTable::heap_map_factor());
1509
1510 size_t bitmap_size = G1CMBitMap::compute_size(heap_rs.size());
1511 G1RegionToSpaceMapper* bitmap_storage =
1512 create_aux_memory_mapper("Mark Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());
1513
1514 _hrm.initialize(heap_storage, bitmap_storage, bot_storage, cardtable_storage, refinement_cards_storage);
1515 card_table->initialize(cardtable_storage);
1516 refinement_table->initialize(refinement_cards_storage);
1517
1518 BarrierSet::set_barrier_set(bs);
1519
1520 {
1521 G1SATBMarkQueueSet& satbqs = bs->satb_mark_queue_set();
1522 satbqs.set_process_completed_buffers_threshold(G1SATBProcessCompletedThreshold);
1523 satbqs.set_buffer_enqueue_threshold_percentage(G1SATBBufferEnqueueingThresholdPercent);
1524 }
1525
1526 // 6843694 - ensure that the maximum region index can fit
1527 // in the remembered set structures.
1528 const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
1529 guarantee((max_num_regions() - 1) <= max_region_idx, "too many regions");
1530
1531 // The G1FromCardCache reserves card with value 0 as "invalid", so the heap must not
1532 // start within the first card.
1533 guarantee((uintptr_t)(heap_rs.base()) >= G1CardTable::card_size(), "Java heap must not start within the first card.");
1534 G1FromCardCache::initialize(max_num_regions());
1535 // Also create a G1 rem set.
1536 _rem_set = new G1RemSet(this);
1537 _rem_set->initialize(max_num_regions());
1538
1539 size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
1540 guarantee(G1HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
1541 guarantee(G1HeapRegion::CardsPerRegion < max_cards_per_region,
1542 "too many cards per region");
1543
1544 G1HeapRegionRemSet::initialize(_reserved);
1545
1546 G1FreeRegionList::set_unrealistically_long_length(max_num_regions() + 1);
1547
1548 _bot = new G1BlockOffsetTable(reserved(), bot_storage);
1549
1550 {
1551 size_t granularity = G1HeapRegion::GrainBytes;
1552
1553 _region_attr.initialize(reserved(), granularity);
1554 }
1555
1556 _workers = new WorkerThreads("GC Thread", ParallelGCThreads);
1557 if (_workers == nullptr) {
1558 return JNI_ENOMEM;
1559 }
1560 _workers->initialize_workers();
1561
1562 _numa->set_region_info(G1HeapRegion::GrainBytes, page_size);
1563
1564 // Create the G1ConcurrentMark data structure and thread.
1565 // (Must do this late, so that "max_[reserved_]regions" is defined.)
1566 _cm = new G1ConcurrentMark(this, bitmap_storage);
1567 _cm_thread = _cm->cm_thread();
1568
1569 // Now expand into the initial heap size.
1570 if (!expand(init_byte_size, _workers)) {
1571 vm_shutdown_during_initialization("Failed to allocate initial heap.");
1572 return JNI_ENOMEM;
1573 }
1574
1575 // Perform any initialization actions delegated to the policy.
1576 policy()->init(this, &_collection_set);
1577
1578 jint ecode = initialize_concurrent_refinement();
1579 if (ecode != JNI_OK) {
1580 return ecode;
1581 }
1582
1583 ecode = initialize_service_thread();
1584 if (ecode != JNI_OK) {
1585 return ecode;
1586 }
1587
1588 // Create and schedule the periodic gc task on the service thread.
1589 _periodic_gc_task = new G1PeriodicGCTask("Periodic GC Task");
1590 _service_thread->register_task(_periodic_gc_task);
1591
1592 _free_arena_memory_task = new G1MonotonicArenaFreeMemoryTask("Card Set Free Memory Task");
1593 _service_thread->register_task(_free_arena_memory_task);
1594
1595 if (policy()->use_adaptive_young_list_length()) {
1596 _revise_young_length_task = new G1ReviseYoungLengthTask("Revise Young Length List Task");
1597 _service_thread->register_task(_revise_young_length_task);
1598 }
1599
1600 // Here we allocate the dummy G1HeapRegion that is required by the
1601 // G1AllocRegion class.
1602 G1HeapRegion* dummy_region = _hrm.get_dummy_region();
1603
1604 // We'll re-use the same region whether the alloc region will
1605 // require BOT updates or not and, if it doesn't, then a non-young
1606 // region will complain that it cannot support allocations without
1607 // BOT updates. So we'll tag the dummy region as eden to avoid that.
1608 dummy_region->set_eden();
1609 // Make sure it's full.
1610 dummy_region->set_top(dummy_region->end());
1611 G1AllocRegion::setup(this, dummy_region);
1612
1613 _allocator->init_mutator_alloc_regions();
1614
1615 // Do create of the monitoring and management support so that
1616 // values in the heap have been properly initialized.
1617 _monitoring_support = new G1MonitoringSupport(this);
1618
1619 _collection_set.initialize(max_num_regions());
1620
1621 start_new_collection_set();
1622
1623 allocation_failure_injector()->reset();
1624
1625 CPUTimeCounters::create_counter(CPUTimeGroups::CPUTimeType::gc_parallel_workers);
1626 CPUTimeCounters::create_counter(CPUTimeGroups::CPUTimeType::gc_conc_mark);
1627 CPUTimeCounters::create_counter(CPUTimeGroups::CPUTimeType::gc_conc_refine);
1628 CPUTimeCounters::create_counter(CPUTimeGroups::CPUTimeType::gc_conc_refine_control);
1629 CPUTimeCounters::create_counter(CPUTimeGroups::CPUTimeType::gc_service);
1630
1631 G1InitLogger::print();
1632
1633 FullGCForwarding::initialize(_reserved);
1634
1635 return JNI_OK;
1636 }
1637
1638 bool G1CollectedHeap::concurrent_mark_is_terminating() const {
1639 return _cm_thread->should_terminate();
1640 }
1641
1642 void G1CollectedHeap::stop() {
1643 // Stop all concurrent threads. We do this to make sure these threads
1644 // do not continue to execute and access resources (e.g. logging)
1645 // that are destroyed during shutdown.
1646 _cr->stop();
1647 _service_thread->stop();
1648 _cm_thread->stop();
1649 }
1650
1651 void G1CollectedHeap::safepoint_synchronize_begin() {
1652 SuspendibleThreadSet::synchronize();
1653
1654 _last_synchronized_start = os::elapsed_counter();
1655 }
1656
1657 void G1CollectedHeap::safepoint_synchronize_end() {
1658 jlong now = os::elapsed_counter();
1659 jlong synchronize_duration = now - _last_synchronized_start;
1660
1661 if (_last_safepoint_refinement_epoch == _refinement_epoch) {
1662 _yield_duration_in_refinement_epoch += synchronize_duration;
1663 } else {
1664 _last_refinement_epoch_start = now;
1665 _last_safepoint_refinement_epoch = _refinement_epoch;
1666 _yield_duration_in_refinement_epoch = 0;
1667 }
1668
1669 SuspendibleThreadSet::desynchronize();
1670 }
1671
1672 void G1CollectedHeap::set_last_refinement_epoch_start(jlong epoch_start, jlong last_yield_duration) {
1673 _last_refinement_epoch_start = epoch_start;
1674 guarantee(_yield_duration_in_refinement_epoch >= last_yield_duration, "should be");
1675 _yield_duration_in_refinement_epoch -= last_yield_duration;
1676 }
1677
1678 jlong G1CollectedHeap::yield_duration_in_refinement_epoch() {
1679 return _yield_duration_in_refinement_epoch;
1680 }
1681
1682 void G1CollectedHeap::post_initialize() {
1683 CollectedHeap::post_initialize();
1684 ref_processing_init();
1685 }
1686
1687 void G1CollectedHeap::ref_processing_init() {
1688 // Reference processing in G1 currently works as follows:
1689 //
1690 // * There are two reference processor instances. One is
1691 // used to record and process discovered references
1692 // during concurrent marking; the other is used to
1693 // record and process references during STW pauses
1694 // (both full and incremental).
1695 // * Both ref processors need to 'span' the entire heap as
1696 // the regions in the collection set may be dotted around.
1697 //
1698 // * For the concurrent marking ref processor:
1699 // * Reference discovery is enabled at concurrent start.
1700 // * Reference discovery is disabled and the discovered
1701 // references processed etc during remarking.
1702 // * Reference discovery is MT (see below).
1703 // * Reference discovery requires a barrier (see below).
1704 // * Reference processing may or may not be MT
1705 // (depending on the value of ParallelRefProcEnabled
1706 // and ParallelGCThreads).
1707 // * A full GC disables reference discovery by the CM
1708 // ref processor and abandons any entries on it's
1709 // discovered lists.
1710 //
1711 // * For the STW processor:
1712 // * Non MT discovery is enabled at the start of a full GC.
1713 // * Processing and enqueueing during a full GC is non-MT.
1714 // * During a full GC, references are processed after marking.
1715 //
1716 // * Discovery (may or may not be MT) is enabled at the start
1717 // of an incremental evacuation pause.
1718 // * References are processed near the end of a STW evacuation pause.
1719 // * For both types of GC:
1720 // * Discovery is atomic - i.e. not concurrent.
1721 // * Reference discovery will not need a barrier.
1722
1723 _is_alive_closure_cm.initialize(concurrent_mark());
1724 // Concurrent Mark ref processor
1725 _ref_processor_cm =
1726 new ReferenceProcessor(&_is_subject_to_discovery_cm,
1727 ParallelGCThreads, // degree of mt processing
1728 // We discover with the gc worker threads during Remark, so both
1729 // thread counts must be considered for discovery.
1730 MAX2(ParallelGCThreads, ConcGCThreads), // degree of mt discovery
1731 true, // Reference discovery is concurrent
1732 &_is_alive_closure_cm); // is alive closure
1733
1734 // STW ref processor
1735 _ref_processor_stw =
1736 new ReferenceProcessor(&_is_subject_to_discovery_stw,
1737 ParallelGCThreads, // degree of mt processing
1738 ParallelGCThreads, // degree of mt discovery
1739 false, // Reference discovery is not concurrent
1740 &_is_alive_closure_stw); // is alive closure
1741 }
1742
1743 size_t G1CollectedHeap::capacity() const {
1744 return _hrm.num_committed_regions() * G1HeapRegion::GrainBytes;
1745 }
1746
1747 size_t G1CollectedHeap::unused_committed_regions_in_bytes() const {
1748 return _hrm.total_free_bytes();
1749 }
1750
1751 // Computes the sum of the storage used by the various regions.
1752 size_t G1CollectedHeap::used() const {
1753 size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions();
1754 return result;
1755 }
1756
1757 size_t G1CollectedHeap::used_unlocked() const {
1758 return _summary_bytes_used;
1759 }
1760
1761 class SumUsedClosure: public G1HeapRegionClosure {
1762 size_t _used;
1763 public:
1764 SumUsedClosure() : _used(0) {}
1765 bool do_heap_region(G1HeapRegion* r) {
1766 _used += r->used();
1767 return false;
1768 }
1769 size_t result() { return _used; }
1770 };
1771
1772 size_t G1CollectedHeap::recalculate_used() const {
1773 SumUsedClosure blk;
1774 heap_region_iterate(&blk);
1775 return blk.result();
1776 }
1777
1778 bool G1CollectedHeap::is_user_requested_concurrent_full_gc(GCCause::Cause cause) {
1779 return GCCause::is_user_requested_gc(cause) && ExplicitGCInvokesConcurrent;
1780 }
1781
1782 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
1783 switch (cause) {
1784 case GCCause::_g1_humongous_allocation: return true;
1785 case GCCause::_g1_periodic_collection: return G1PeriodicGCInvokesConcurrent;
1786 case GCCause::_wb_breakpoint: return true;
1787 case GCCause::_codecache_GC_aggressive: return true;
1788 case GCCause::_codecache_GC_threshold: return true;
1789 default: return is_user_requested_concurrent_full_gc(cause);
1790 }
1791 }
1792
1793 void G1CollectedHeap::increment_old_marking_cycles_started() {
1794 assert(_old_marking_cycles_started == _old_marking_cycles_completed ||
1795 _old_marking_cycles_started == _old_marking_cycles_completed + 1,
1796 "Wrong marking cycle count (started: %d, completed: %d)",
1797 _old_marking_cycles_started, _old_marking_cycles_completed);
1798
1799 _old_marking_cycles_started++;
1800 }
1801
1802 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent,
1803 bool whole_heap_examined) {
1804 MonitorLocker ml(G1OldGCCount_lock, Mutex::_no_safepoint_check_flag);
1805
1806 // We assume that if concurrent == true, then the caller is a
1807 // concurrent thread that was joined the Suspendible Thread
1808 // Set. If there's ever a cheap way to check this, we should add an
1809 // assert here.
1810
1811 // Given that this method is called at the end of a Full GC or of a
1812 // concurrent cycle, and those can be nested (i.e., a Full GC can
1813 // interrupt a concurrent cycle), the number of full collections
1814 // completed should be either one (in the case where there was no
1815 // nesting) or two (when a Full GC interrupted a concurrent cycle)
1816 // behind the number of full collections started.
1817
1818 // This is the case for the inner caller, i.e. a Full GC.
1819 assert(concurrent ||
1820 (_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||
1821 (_old_marking_cycles_started == _old_marking_cycles_completed + 2),
1822 "for inner caller (Full GC): _old_marking_cycles_started = %u "
1823 "is inconsistent with _old_marking_cycles_completed = %u",
1824 _old_marking_cycles_started, _old_marking_cycles_completed);
1825
1826 // This is the case for the outer caller, i.e. the concurrent cycle.
1827 assert(!concurrent ||
1828 (_old_marking_cycles_started == _old_marking_cycles_completed + 1),
1829 "for outer caller (concurrent cycle): "
1830 "_old_marking_cycles_started = %u "
1831 "is inconsistent with _old_marking_cycles_completed = %u",
1832 _old_marking_cycles_started, _old_marking_cycles_completed);
1833
1834 _old_marking_cycles_completed += 1;
1835 if (whole_heap_examined) {
1836 // Signal that we have completed a visit to all live objects.
1837 record_whole_heap_examined_timestamp();
1838 }
1839
1840 // We need to clear the "in_progress" flag in the CM thread before
1841 // we wake up any waiters (especially when ExplicitInvokesConcurrent
1842 // is set) so that if a waiter requests another System.gc() it doesn't
1843 // incorrectly see that a marking cycle is still in progress.
1844 if (concurrent) {
1845 _cm_thread->set_idle();
1846 }
1847
1848 // Notify threads waiting in System.gc() (with ExplicitGCInvokesConcurrent)
1849 // for a full GC to finish that their wait is over.
1850 ml.notify_all();
1851 }
1852
1853 void G1CollectedHeap::collect(GCCause::Cause cause) {
1854 try_collect(0 /* allocation_word_size */, cause, collection_counters(this));
1855 }
1856
1857 // Return true if (x < y) with allowance for wraparound.
1858 static bool gc_counter_less_than(uint x, uint y) {
1859 return (x - y) > (UINT_MAX/2);
1860 }
1861
1862 // LOG_COLLECT_CONCURRENTLY(cause, msg, args...)
1863 // Macro so msg printing is format-checked.
1864 #define LOG_COLLECT_CONCURRENTLY(cause, ...) \
1865 do { \
1866 LogTarget(Trace, gc) LOG_COLLECT_CONCURRENTLY_lt; \
1867 if (LOG_COLLECT_CONCURRENTLY_lt.is_enabled()) { \
1868 ResourceMark rm; /* For thread name. */ \
1869 LogStream LOG_COLLECT_CONCURRENTLY_s(&LOG_COLLECT_CONCURRENTLY_lt); \
1870 LOG_COLLECT_CONCURRENTLY_s.print("%s: Try Collect Concurrently (%s): ", \
1871 Thread::current()->name(), \
1872 GCCause::to_string(cause)); \
1873 LOG_COLLECT_CONCURRENTLY_s.print(__VA_ARGS__); \
1874 } \
1875 } while (0)
1876
1877 #define LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, result) \
1878 LOG_COLLECT_CONCURRENTLY(cause, "complete %s", BOOL_TO_STR(result))
1879
1880 bool G1CollectedHeap::wait_full_mark_finished(GCCause::Cause cause,
1881 uint old_marking_started_before,
1882 uint old_marking_started_after,
1883 uint old_marking_completed_after) {
1884 // Request is finished if a full collection (concurrent or stw)
1885 // was started after this request and has completed, e.g.
1886 // started_before < completed_after.
1887 if (gc_counter_less_than(old_marking_started_before,
1888 old_marking_completed_after)) {
1889 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
1890 return true;
1891 }
1892
1893 if (old_marking_started_after != old_marking_completed_after) {
1894 // If there is an in-progress cycle (possibly started by us), then
1895 // wait for that cycle to complete, e.g.
1896 // while completed_now < started_after.
1897 LOG_COLLECT_CONCURRENTLY(cause, "wait");
1898 MonitorLocker ml(G1OldGCCount_lock);
1899 while (gc_counter_less_than(_old_marking_cycles_completed,
1900 old_marking_started_after)) {
1901 ml.wait();
1902 }
1903 // Request is finished if the collection we just waited for was
1904 // started after this request.
1905 if (old_marking_started_before != old_marking_started_after) {
1906 LOG_COLLECT_CONCURRENTLY(cause, "complete after wait");
1907 return true;
1908 }
1909 }
1910 return false;
1911 }
1912
1913 // After calling wait_full_mark_finished(), this method determines whether we
1914 // previously failed for ordinary reasons (concurrent cycle in progress, whitebox
1915 // has control). Returns if this has been such an ordinary reason.
1916 static bool should_retry_vm_op(GCCause::Cause cause,
1917 VM_G1TryInitiateConcMark* op) {
1918 if (op->cycle_already_in_progress()) {
1919 // If VMOp failed because a cycle was already in progress, it
1920 // is now complete. But it didn't finish this user-requested
1921 // GC, so try again.
1922 LOG_COLLECT_CONCURRENTLY(cause, "retry after in-progress");
1923 return true;
1924 } else if (op->whitebox_attached()) {
1925 // If WhiteBox wants control, wait for notification of a state
1926 // change in the controller, then try again. Don't wait for
1927 // release of control, since collections may complete while in
1928 // control. Note: This won't recognize a STW full collection
1929 // while waiting; we can't wait on multiple monitors.
1930 LOG_COLLECT_CONCURRENTLY(cause, "whitebox control stall");
1931 MonitorLocker ml(ConcurrentGCBreakpoints::monitor());
1932 if (ConcurrentGCBreakpoints::is_controlled()) {
1933 ml.wait();
1934 }
1935 return true;
1936 }
1937 return false;
1938 }
1939
1940 bool G1CollectedHeap::try_collect_concurrently(size_t allocation_word_size,
1941 GCCause::Cause cause,
1942 uint gc_counter,
1943 uint old_marking_started_before) {
1944 assert_heap_not_locked();
1945 assert(should_do_concurrent_full_gc(cause),
1946 "Non-concurrent cause %s", GCCause::to_string(cause));
1947
1948 for (uint i = 1; true; ++i) {
1949 // Try to schedule concurrent start evacuation pause that will
1950 // start a concurrent cycle.
1951 LOG_COLLECT_CONCURRENTLY(cause, "attempt %u", i);
1952 VM_G1TryInitiateConcMark op(allocation_word_size, gc_counter, cause);
1953 VMThread::execute(&op);
1954
1955 // Request is trivially finished.
1956 if (cause == GCCause::_g1_periodic_collection) {
1957 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, op.gc_succeeded());
1958 return op.gc_succeeded();
1959 }
1960
1961 // If VMOp skipped initiating concurrent marking cycle because
1962 // we're shutting down, then we're done.
1963 if (op.is_shutting_down()) {
1964 LOG_COLLECT_CONCURRENTLY(cause, "skipped: terminating");
1965 return false;
1966 }
1967
1968 // Lock to get consistent set of values.
1969 uint old_marking_started_after;
1970 uint old_marking_completed_after;
1971 {
1972 MutexLocker ml(Heap_lock);
1973 // Update gc_counter for retrying VMOp if needed. Captured here to be
1974 // consistent with the values we use below for termination tests. If
1975 // a retry is needed after a possible wait, and another collection
1976 // occurs in the meantime, it will cause our retry to be skipped and
1977 // we'll recheck for termination with updated conditions from that
1978 // more recent collection. That's what we want, rather than having
1979 // our retry possibly perform an unnecessary collection.
1980 gc_counter = total_collections();
1981 old_marking_started_after = _old_marking_cycles_started;
1982 old_marking_completed_after = _old_marking_cycles_completed;
1983 }
1984
1985 if (cause == GCCause::_wb_breakpoint) {
1986 if (op.gc_succeeded()) {
1987 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
1988 return true;
1989 }
1990 // When _wb_breakpoint there can't be another cycle or deferred.
1991 assert(!op.cycle_already_in_progress(), "invariant");
1992 assert(!op.whitebox_attached(), "invariant");
1993 // Concurrent cycle attempt might have been cancelled by some other
1994 // collection, so retry. Unlike other cases below, we want to retry
1995 // even if cancelled by a STW full collection, because we really want
1996 // to start a concurrent cycle.
1997 if (old_marking_started_before != old_marking_started_after) {
1998 LOG_COLLECT_CONCURRENTLY(cause, "ignoring STW full GC");
1999 old_marking_started_before = old_marking_started_after;
2000 }
2001 } else if (GCCause::is_codecache_requested_gc(cause)) {
2002 assert(allocation_word_size == 0, "must be");
2003 // For a CodeCache requested GC, before marking, progress is ensured as the
2004 // following Remark pause unloads code (and signals the requester such).
2005 // Otherwise we must ensure that it is restarted.
2006 //
2007 // For a CodeCache requested GC, a successful GC operation means that
2008 // (1) marking is in progress. I.e. the VMOp started the marking or a
2009 // Remark pause is pending from a different VM op; we will potentially
2010 // abort a mixed phase if needed.
2011 // (2) a new cycle was started (by this thread or some other), or
2012 // (3) a Full GC was performed.
2013 //
2014 // Cases (2) and (3) are detected together by a change to
2015 // _old_marking_cycles_started.
2016 //
2017 // Compared to other "automatic" GCs (see below), we do not consider being
2018 // in whitebox as sufficient too because we might be anywhere within that
2019 // cycle and we need to make progress.
2020 if (op.mark_in_progress() ||
2021 (old_marking_started_before != old_marking_started_after)) {
2022 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2023 return true;
2024 }
2025
2026 if (wait_full_mark_finished(cause,
2027 old_marking_started_before,
2028 old_marking_started_after,
2029 old_marking_completed_after)) {
2030 return true;
2031 }
2032
2033 if (should_retry_vm_op(cause, &op)) {
2034 continue;
2035 }
2036 } else if (!GCCause::is_user_requested_gc(cause)) {
2037 assert(cause == GCCause::_g1_humongous_allocation ||
2038 cause == GCCause::_g1_periodic_collection,
2039 "Unsupported cause %s", GCCause::to_string(cause));
2040
2041 // For an "automatic" (not user-requested) collection, we just need to
2042 // ensure that progress is made.
2043 //
2044 // Request is finished if any of
2045 // (1) the VMOp successfully performed a GC,
2046 // (2) a concurrent cycle was already in progress,
2047 // (3) whitebox is controlling concurrent cycles,
2048 // (4) a new cycle was started (by this thread or some other), or
2049 // (5) a Full GC was performed.
2050 // Cases (4) and (5) are detected together by a change to
2051 // _old_marking_cycles_started.
2052 if (op.gc_succeeded() ||
2053 op.cycle_already_in_progress() ||
2054 op.whitebox_attached() ||
2055 (old_marking_started_before != old_marking_started_after)) {
2056 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2057 return true;
2058 }
2059 } else { // User-requested GC.
2060 // For a user-requested collection, we want to ensure that a complete
2061 // full collection has been performed before returning, but without
2062 // waiting for more than needed.
2063
2064 // For user-requested GCs (unlike non-UR), a successful VMOp implies a
2065 // new cycle was started. That's good, because it's not clear what we
2066 // should do otherwise. Trying again just does back to back GCs.
2067 // Can't wait for someone else to start a cycle. And returning fails
2068 // to meet the goal of ensuring a full collection was performed.
2069 assert(!op.gc_succeeded() ||
2070 (old_marking_started_before != old_marking_started_after),
2071 "invariant: succeeded %s, started before %u, started after %u",
2072 BOOL_TO_STR(op.gc_succeeded()),
2073 old_marking_started_before, old_marking_started_after);
2074
2075 if (wait_full_mark_finished(cause,
2076 old_marking_started_before,
2077 old_marking_started_after,
2078 old_marking_completed_after)) {
2079 return true;
2080 }
2081
2082 // If VMOp was successful then it started a new cycle that the above
2083 // wait &etc should have recognized as finishing this request. This
2084 // differs from a non-user-request, where gc_succeeded does not imply
2085 // a new cycle was started.
2086 assert(!op.gc_succeeded(), "invariant");
2087
2088 if (should_retry_vm_op(cause, &op)) {
2089 continue;
2090 }
2091 }
2092
2093 // Collection failed and should be retried.
2094 assert(op.transient_failure(), "invariant");
2095
2096 LOG_COLLECT_CONCURRENTLY(cause, "retry");
2097 }
2098 }
2099
2100 bool G1CollectedHeap::try_collect(size_t allocation_word_size,
2101 GCCause::Cause cause,
2102 const G1GCCounters& counters_before) {
2103 if (should_do_concurrent_full_gc(cause)) {
2104 return try_collect_concurrently(allocation_word_size,
2105 cause,
2106 counters_before.total_collections(),
2107 counters_before.old_marking_cycles_started());
2108 } else if (cause == GCCause::_wb_young_gc
2109 DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
2110
2111 assert(allocation_word_size == 0, "must be");
2112 // Schedule a standard evacuation pause. We're setting word_size
2113 // to 0 which means that we are not requesting a post-GC allocation.
2114 VM_G1CollectForAllocation op(0, /* word_size */
2115 counters_before.total_collections(),
2116 cause);
2117 VMThread::execute(&op);
2118 return op.gc_succeeded();
2119 } else {
2120 // The only path to get here is because of a periodic collection using a Full GC
2121 // or WhiteBox full gc.
2122 assert(allocation_word_size == 0, "must be");
2123 // Schedule a Full GC.
2124 VM_G1CollectFull op(counters_before.total_collections(),
2125 counters_before.total_full_collections(),
2126 cause);
2127 VMThread::execute(&op);
2128 return op.gc_succeeded();
2129 }
2130 }
2131
2132 void G1CollectedHeap::start_concurrent_gc_for_metadata_allocation(GCCause::Cause gc_cause) {
2133 GCCauseSetter x(this, gc_cause);
2134
2135 // At this point we are supposed to start a concurrent cycle. We
2136 // will do so if one is not already in progress.
2137 bool should_start = policy()->force_concurrent_start_if_outside_cycle(gc_cause);
2138 if (should_start) {
2139 do_collection_pause_at_safepoint(0 /* allocation_word_size */);
2140 }
2141 }
2142
2143 bool G1CollectedHeap::is_in(const void* p) const {
2144 return is_in_reserved(p) && _hrm.is_available(addr_to_region(p));
2145 }
2146
2147 // Iteration functions.
2148
2149 // Iterates an ObjectClosure over all objects within a G1HeapRegion.
2150
2151 class IterateObjectClosureRegionClosure: public G1HeapRegionClosure {
2152 ObjectClosure* _cl;
2153 public:
2154 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
2155 bool do_heap_region(G1HeapRegion* r) {
2156 if (!r->is_continues_humongous()) {
2157 r->object_iterate(_cl);
2158 }
2159 return false;
2160 }
2161 };
2162
2163 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
2164 IterateObjectClosureRegionClosure blk(cl);
2165 heap_region_iterate(&blk);
2166 }
2167
2168 class G1ParallelObjectIterator : public ParallelObjectIteratorImpl {
2169 private:
2170 G1CollectedHeap* _heap;
2171 G1HeapRegionClaimer _claimer;
2172
2173 public:
2174 G1ParallelObjectIterator(uint thread_num) :
2175 _heap(G1CollectedHeap::heap()),
2176 _claimer(thread_num == 0 ? G1CollectedHeap::heap()->workers()->active_workers() : thread_num) {}
2177
2178 virtual void object_iterate(ObjectClosure* cl, uint worker_id) {
2179 _heap->object_iterate_parallel(cl, worker_id, &_claimer);
2180 }
2181 };
2182
2183 ParallelObjectIteratorImpl* G1CollectedHeap::parallel_object_iterator(uint thread_num) {
2184 return new G1ParallelObjectIterator(thread_num);
2185 }
2186
2187 void G1CollectedHeap::object_iterate_parallel(ObjectClosure* cl, uint worker_id, G1HeapRegionClaimer* claimer) {
2188 IterateObjectClosureRegionClosure blk(cl);
2189 heap_region_par_iterate_from_worker_offset(&blk, claimer, worker_id);
2190 }
2191
2192 void G1CollectedHeap::keep_alive(oop obj) {
2193 G1BarrierSet::enqueue_preloaded(obj);
2194 }
2195
2196 void G1CollectedHeap::heap_region_iterate(G1HeapRegionClosure* cl) const {
2197 _hrm.iterate(cl);
2198 }
2199
2200 void G1CollectedHeap::heap_region_iterate(G1HeapRegionIndexClosure* cl) const {
2201 _hrm.iterate(cl);
2202 }
2203
2204 void G1CollectedHeap::heap_region_par_iterate_from_worker_offset(G1HeapRegionClosure* cl,
2205 G1HeapRegionClaimer *hrclaimer,
2206 uint worker_id) const {
2207 _hrm.par_iterate(cl, hrclaimer, hrclaimer->offset_for_worker(worker_id));
2208 }
2209
2210 void G1CollectedHeap::heap_region_par_iterate_from_start(G1HeapRegionClosure* cl,
2211 G1HeapRegionClaimer *hrclaimer) const {
2212 _hrm.par_iterate(cl, hrclaimer, 0);
2213 }
2214
2215 void G1CollectedHeap::collection_set_iterate_all(G1HeapRegionClosure* cl) {
2216 _collection_set.iterate(cl);
2217 }
2218
2219 void G1CollectedHeap::collection_set_par_iterate_all(G1HeapRegionClosure* cl,
2220 G1HeapRegionClaimer* hr_claimer,
2221 uint worker_id) {
2222 _collection_set.par_iterate(cl, hr_claimer, worker_id);
2223 }
2224
2225 void G1CollectedHeap::collection_set_iterate_increment_from(G1HeapRegionClosure *cl,
2226 G1HeapRegionClaimer* hr_claimer,
2227 uint worker_id) {
2228 _collection_set.iterate_incremental_part_from(cl, hr_claimer, worker_id);
2229 }
2230
2231 void G1CollectedHeap::par_iterate_regions_array(G1HeapRegionClosure* cl,
2232 G1HeapRegionClaimer* hr_claimer,
2233 const uint regions[],
2234 size_t length,
2235 uint worker_id) const {
2236 assert_at_safepoint();
2237 if (length == 0) {
2238 return;
2239 }
2240 uint total_workers = workers()->active_workers();
2241
2242 size_t start_pos = (worker_id * length) / total_workers;
2243 size_t cur_pos = start_pos;
2244
2245 do {
2246 uint region_idx = regions[cur_pos];
2247 if (hr_claimer == nullptr || hr_claimer->claim_region(region_idx)) {
2248 G1HeapRegion* r = region_at(region_idx);
2249 bool result = cl->do_heap_region(r);
2250 guarantee(!result, "Must not cancel iteration");
2251 }
2252
2253 cur_pos++;
2254 if (cur_pos == length) {
2255 cur_pos = 0;
2256 }
2257 } while (cur_pos != start_pos);
2258 }
2259
2260 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
2261 G1HeapRegion* hr = heap_region_containing(addr);
2262 // The CollectedHeap API requires us to not fail for any given address within
2263 // the heap. G1HeapRegion::block_start() has been optimized to not accept addresses
2264 // outside of the allocated area.
2265 if (addr >= hr->top()) {
2266 return nullptr;
2267 }
2268 return hr->block_start(addr);
2269 }
2270
2271 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
2272 G1HeapRegion* hr = heap_region_containing(addr);
2273 return hr->block_is_obj(addr, hr->parsable_bottom_acquire());
2274 }
2275
2276 size_t G1CollectedHeap::tlab_capacity() const {
2277 return eden_target_length() * G1HeapRegion::GrainBytes;
2278 }
2279
2280 size_t G1CollectedHeap::tlab_used() const {
2281 return _eden.length() * G1HeapRegion::GrainBytes;
2282 }
2283
2284 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size
2285 // must be equal to the humongous object limit.
2286 size_t G1CollectedHeap::max_tlab_size() const {
2287 return align_down(_humongous_object_threshold_in_words, MinObjAlignment);
2288 }
2289
2290 size_t G1CollectedHeap::unsafe_max_tlab_alloc() const {
2291 return _allocator->unsafe_max_tlab_alloc();
2292 }
2293
2294 size_t G1CollectedHeap::max_capacity() const {
2295 return max_num_regions() * G1HeapRegion::GrainBytes;
2296 }
2297
2298 size_t G1CollectedHeap::min_capacity() const {
2299 return MinHeapSize;
2300 }
2301
2302 void G1CollectedHeap::prepare_for_verify() {
2303 _verifier->prepare_for_verify();
2304 }
2305
2306 void G1CollectedHeap::verify(VerifyOption vo) {
2307 _verifier->verify(vo);
2308 }
2309
2310 bool G1CollectedHeap::supports_concurrent_gc_breakpoints() const {
2311 return true;
2312 }
2313
2314 class G1PrintRegionClosure: public G1HeapRegionClosure {
2315 outputStream* _st;
2316 public:
2317 G1PrintRegionClosure(outputStream* st) : _st(st) {}
2318 bool do_heap_region(G1HeapRegion* r) {
2319 r->print_on(_st);
2320 return false;
2321 }
2322 };
2323
2324 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2325 const G1HeapRegion* hr,
2326 const VerifyOption vo) const {
2327 switch (vo) {
2328 case VerifyOption::G1UseConcMarking: return is_obj_dead(obj, hr);
2329 case VerifyOption::G1UseFullMarking: return is_obj_dead_full(obj, hr);
2330 default: ShouldNotReachHere();
2331 }
2332 return false; // keep some compilers happy
2333 }
2334
2335 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2336 const VerifyOption vo) const {
2337 switch (vo) {
2338 case VerifyOption::G1UseConcMarking: return is_obj_dead(obj);
2339 case VerifyOption::G1UseFullMarking: return is_obj_dead_full(obj);
2340 default: ShouldNotReachHere();
2341 }
2342 return false; // keep some compilers happy
2343 }
2344
2345 void G1CollectedHeap::print_heap_regions() const {
2346 LogTarget(Trace, gc, heap, region) lt;
2347 if (lt.is_enabled()) {
2348 LogStream ls(lt);
2349 print_regions_on(&ls);
2350 }
2351 }
2352
2353 static void print_region_type(outputStream* st, const char* type, uint count, bool last = false) {
2354 st->print("%u %s (%zuM)%s", count, type, count * G1HeapRegion::GrainBytes / M, last ? "\n" : ", ");
2355 }
2356
2357 void G1CollectedHeap::print_heap_on(outputStream* st) const {
2358 size_t heap_used = (Thread::current_or_null_safe() != nullptr &&
2359 Heap_lock->owned_by_self()) ? used() : used_unlocked();
2360 st->print("%-20s", "garbage-first heap");
2361 st->print(" total reserved %zuK, committed %zuK, used %zuK",
2362 _hrm.reserved().byte_size()/K, capacity()/K, heap_used/K);
2363 st->print(" [" PTR_FORMAT ", " PTR_FORMAT ")",
2364 p2i(_hrm.reserved().start()),
2365 p2i(_hrm.reserved().end()));
2366 st->cr();
2367
2368 StreamIndentor si(st, 1);
2369 st->print("region size %zuM, ", G1HeapRegion::GrainBytes / M);
2370 print_region_type(st, "eden", eden_regions_count());
2371 print_region_type(st, "survivor", survivor_regions_count());
2372 print_region_type(st, "old", old_regions_count());
2373 print_region_type(st, "humongous", humongous_regions_count());
2374 print_region_type(st, "free", num_free_regions(), true /* last */);
2375
2376 if (_numa->is_enabled()) {
2377 uint num_nodes = _numa->num_active_nodes();
2378 st->print("remaining free region(s) on each NUMA node: ");
2379 const uint* node_ids = _numa->node_ids();
2380 for (uint node_index = 0; node_index < num_nodes; node_index++) {
2381 uint num_free_regions = _hrm.num_free_regions(node_index);
2382 st->print("%u=%u ", node_ids[node_index], num_free_regions);
2383 }
2384 st->cr();
2385 }
2386 }
2387
2388 void G1CollectedHeap::print_regions_on(outputStream* st) const {
2389 st->print_cr("Heap Regions: E=young(eden), S=young(survivor), O=old, "
2390 "HS=humongous(starts), HC=humongous(continues), "
2391 "CS=collection set, F=free, "
2392 "TAMS=top-at-mark-start, "
2393 "PB=parsable bottom");
2394 G1PrintRegionClosure blk(st);
2395 heap_region_iterate(&blk);
2396 }
2397
2398 void G1CollectedHeap::print_extended_on(outputStream* st) const {
2399 print_heap_on(st);
2400
2401 // Print the per-region information.
2402 st->cr();
2403 print_regions_on(st);
2404 }
2405
2406 void G1CollectedHeap::print_gc_on(outputStream* st) const {
2407 // Print the per-region information.
2408 print_regions_on(st);
2409 st->cr();
2410
2411 BarrierSet* bs = BarrierSet::barrier_set();
2412 if (bs != nullptr) {
2413 bs->print_on(st);
2414 }
2415
2416 if (_cm != nullptr) {
2417 st->cr();
2418 _cm->print_on(st);
2419 }
2420 }
2421
2422 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
2423 workers()->threads_do(tc);
2424 tc->do_thread(_cm_thread);
2425 _cm->threads_do(tc);
2426 _cr->threads_do(tc);
2427 tc->do_thread(_service_thread);
2428 }
2429
2430 void G1CollectedHeap::print_tracing_info() const {
2431 rem_set()->print_summary_info();
2432 concurrent_mark()->print_summary_info();
2433 }
2434
2435 bool G1CollectedHeap::print_location(outputStream* st, void* addr) const {
2436 return BlockLocationPrinter<G1CollectedHeap>::print_location(st, addr);
2437 }
2438
2439 G1HeapSummary G1CollectedHeap::create_g1_heap_summary() {
2440
2441 size_t eden_used_bytes = _monitoring_support->eden_space_used();
2442 size_t survivor_used_bytes = _monitoring_support->survivor_space_used();
2443 size_t old_gen_used_bytes = _monitoring_support->old_gen_used();
2444 size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();
2445
2446 size_t eden_capacity_bytes =
2447 (policy()->young_list_target_length() * G1HeapRegion::GrainBytes) - survivor_used_bytes;
2448
2449 VirtualSpaceSummary heap_summary = create_heap_space_summary();
2450 return G1HeapSummary(heap_summary, heap_used, eden_used_bytes, eden_capacity_bytes,
2451 survivor_used_bytes, old_gen_used_bytes, num_committed_regions());
2452 }
2453
2454 G1EvacSummary G1CollectedHeap::create_g1_evac_summary(G1EvacStats* stats) {
2455 return G1EvacSummary(stats->allocated(), stats->wasted(), stats->undo_wasted(),
2456 stats->unused(), stats->used(), stats->region_end_waste(),
2457 stats->regions_filled(), stats->num_plab_filled(),
2458 stats->direct_allocated(), stats->num_direct_allocated(),
2459 stats->failure_used(), stats->failure_waste());
2460 }
2461
2462 void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {
2463 const G1HeapSummary& heap_summary = create_g1_heap_summary();
2464 gc_tracer->report_gc_heap_summary(when, heap_summary);
2465
2466 const MetaspaceSummary& metaspace_summary = create_metaspace_summary();
2467 gc_tracer->report_metaspace_summary(when, metaspace_summary);
2468 }
2469
2470 void G1CollectedHeap::gc_prologue(bool full) {
2471 // Update common counters.
2472 increment_total_collections(full /* full gc */);
2473 if (full || collector_state()->in_concurrent_start_gc()) {
2474 increment_old_marking_cycles_started();
2475 }
2476 }
2477
2478 void G1CollectedHeap::gc_epilogue(bool full) {
2479 // Update common counters.
2480 if (full) {
2481 // Update the number of full collections that have been completed.
2482 increment_old_marking_cycles_completed(false /* concurrent */, true /* liveness_completed */);
2483 }
2484
2485 #if COMPILER2_OR_JVMCI
2486 assert(DerivedPointerTable::is_empty(), "derived pointer present");
2487 #endif
2488
2489 // We have just completed a GC. Update the soft reference
2490 // policy with the new heap occupancy
2491 Universe::heap()->update_capacity_and_used_at_gc();
2492
2493 _collection_pause_end = Ticks::now();
2494
2495 _free_arena_memory_task->notify_new_stats(&_young_gen_card_set_stats,
2496 &_collection_set_candidates_card_set_stats);
2497
2498 update_perf_counter_cpu_time();
2499 _refinement_epoch++;
2500 }
2501
2502 uint G1CollectedHeap::uncommit_regions(uint region_limit) {
2503 return _hrm.uncommit_inactive_regions(region_limit);
2504 }
2505
2506 bool G1CollectedHeap::has_uncommittable_regions() {
2507 return _hrm.has_inactive_regions();
2508 }
2509
2510 void G1CollectedHeap::uncommit_regions_if_necessary() {
2511 if (has_uncommittable_regions()) {
2512 G1UncommitRegionTask::enqueue();
2513 }
2514 }
2515
2516 void G1CollectedHeap::verify_numa_regions(const char* desc) {
2517 LogTarget(Trace, gc, heap, verify) lt;
2518
2519 if (lt.is_enabled()) {
2520 LogStream ls(lt);
2521 // Iterate all heap regions to print matching between preferred numa id and actual numa id.
2522 G1NodeIndexCheckClosure cl(desc, _numa, &ls);
2523 heap_region_iterate(&cl);
2524 }
2525 }
2526
2527 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
2528 uint gc_count_before,
2529 bool* succeeded,
2530 GCCause::Cause gc_cause) {
2531 assert_heap_not_locked_and_not_at_safepoint();
2532 VM_G1CollectForAllocation op(word_size, gc_count_before, gc_cause);
2533 VMThread::execute(&op);
2534
2535 HeapWord* result = op.result();
2536 *succeeded = op.gc_succeeded();
2537 assert(result == nullptr || *succeeded,
2538 "the result should be null if the VM did not succeed");
2539
2540 assert_heap_not_locked();
2541 return result;
2542 }
2543
2544 void G1CollectedHeap::start_concurrent_cycle(bool concurrent_operation_is_full_mark) {
2545 assert(!_cm_thread->in_progress(), "Can not start concurrent operation while in progress");
2546
2547 MutexLocker x(G1CGC_lock, Mutex::_no_safepoint_check_flag);
2548 if (concurrent_operation_is_full_mark) {
2549 _cm->post_concurrent_mark_start();
2550 _cm_thread->start_full_mark();
2551 } else {
2552 _cm->post_concurrent_undo_start();
2553 _cm_thread->start_undo_mark();
2554 }
2555 G1CGC_lock->notify();
2556 }
2557
2558 bool G1CollectedHeap::is_potential_eager_reclaim_candidate(G1HeapRegion* r) const {
2559 // We don't nominate objects with many remembered set entries, on
2560 // the assumption that such objects are likely still live.
2561 G1HeapRegionRemSet* rem_set = r->rem_set();
2562
2563 return rem_set->occupancy_less_or_equal_than(G1EagerReclaimRemSetThreshold);
2564 }
2565
2566 #ifndef PRODUCT
2567 void G1CollectedHeap::verify_region_attr_is_remset_tracked() {
2568 class VerifyRegionAttrRemSet : public G1HeapRegionClosure {
2569 public:
2570 virtual bool do_heap_region(G1HeapRegion* r) {
2571 G1CollectedHeap* g1h = G1CollectedHeap::heap();
2572 G1HeapRegionAttr attr = g1h->region_attr(r->bottom());
2573 bool const is_remset_tracked = attr.is_remset_tracked();
2574 assert((r->rem_set()->is_tracked() == is_remset_tracked) ||
2575 (attr.is_new_survivor() && is_remset_tracked),
2576 "Region %u (%s) remset tracking status (%s) different to region attribute (%s)",
2577 r->hrm_index(), r->get_type_str(), BOOL_TO_STR(r->rem_set()->is_tracked()), BOOL_TO_STR(is_remset_tracked));
2578 return false;
2579 }
2580 } cl;
2581 heap_region_iterate(&cl);
2582 }
2583 #endif
2584
2585 void G1CollectedHeap::update_perf_counter_cpu_time() {
2586 assert(Thread::current()->is_VM_thread(),
2587 "Must be called from VM thread to avoid races");
2588 if (!UsePerfData) {
2589 return;
2590 }
2591
2592 // Ensure ThreadTotalCPUTimeClosure destructor is called before publishing gc
2593 // time.
2594 {
2595 ThreadTotalCPUTimeClosure tttc(CPUTimeGroups::CPUTimeType::gc_parallel_workers);
2596 // Currently parallel worker threads never terminate (JDK-8081682), so it is
2597 // safe for VMThread to read their CPU times. However, if JDK-8087340 is
2598 // resolved so they terminate, we should rethink if it is still safe.
2599 workers()->threads_do(&tttc);
2600 }
2601
2602 CPUTimeCounters::publish_gc_total_cpu_time();
2603 }
2604
2605 void G1CollectedHeap::start_new_collection_set() {
2606 collection_set()->start();
2607
2608 clear_region_attr();
2609
2610 guarantee(_eden.length() == 0, "eden should have been cleared");
2611 policy()->transfer_survivors_to_cset(survivor());
2612
2613 // We redo the verification but now wrt to the new CSet which
2614 // has just got initialized after the previous CSet was freed.
2615 _cm->verify_no_collection_set_oops();
2616 }
2617
2618 void G1CollectedHeap::verify_before_young_collection(G1HeapVerifier::G1VerifyType type) {
2619 if (!VerifyBeforeGC) {
2620 return;
2621 }
2622 if (!G1HeapVerifier::should_verify(type)) {
2623 return;
2624 }
2625 Ticks start = Ticks::now();
2626 _verifier->prepare_for_verify();
2627 _verifier->verify_region_sets_optional();
2628 _verifier->verify_before_gc();
2629 verify_numa_regions("GC Start");
2630 phase_times()->record_verify_before_time_ms((Ticks::now() - start).seconds() * MILLIUNITS);
2631 }
2632
2633 void G1CollectedHeap::verify_after_young_collection(G1HeapVerifier::G1VerifyType type) {
2634 if (!VerifyAfterGC) {
2635 return;
2636 }
2637 if (!G1HeapVerifier::should_verify(type)) {
2638 return;
2639 }
2640 Ticks start = Ticks::now();
2641 _verifier->verify_after_gc();
2642 verify_numa_regions("GC End");
2643 _verifier->verify_region_sets_optional();
2644
2645 if (collector_state()->in_concurrent_start_gc()) {
2646 log_debug(gc, verify)("Marking state");
2647 _verifier->verify_marking_state();
2648 }
2649 _verifier->verify_free_regions_card_tables_clean();
2650
2651 phase_times()->record_verify_after_time_ms((Ticks::now() - start).seconds() * MILLIUNITS);
2652 }
2653
2654 G1HeapPrinterMark::G1HeapPrinterMark(G1CollectedHeap* g1h) : _g1h(g1h), _heap_transition(g1h) {
2655 // This summary needs to be printed before incrementing total collections.
2656 _g1h->rem_set()->print_periodic_summary_info("Before GC RS summary",
2657 _g1h->total_collections(),
2658 true /* show_thread_times */);
2659 _g1h->print_before_gc();
2660 _g1h->print_heap_regions();
2661 }
2662
2663 G1HeapPrinterMark::~G1HeapPrinterMark() {
2664 _g1h->policy()->print_age_table();
2665 _g1h->rem_set()->print_coarsen_stats();
2666 // We are at the end of the GC. Total collections has already been increased.
2667 _g1h->rem_set()->print_periodic_summary_info("After GC RS summary",
2668 _g1h->total_collections() - 1,
2669 false /* show_thread_times */);
2670
2671 _heap_transition.print();
2672 _g1h->print_heap_regions();
2673 _g1h->print_after_gc();
2674 // Print NUMA statistics.
2675 _g1h->numa()->print_statistics();
2676 }
2677
2678 G1JFRTracerMark::G1JFRTracerMark(STWGCTimer* timer, GCTracer* tracer) :
2679 _timer(timer), _tracer(tracer) {
2680
2681 _timer->register_gc_start();
2682 _tracer->report_gc_start(G1CollectedHeap::heap()->gc_cause(), _timer->gc_start());
2683 G1CollectedHeap::heap()->trace_heap_before_gc(_tracer);
2684 }
2685
2686 G1JFRTracerMark::~G1JFRTracerMark() {
2687 G1CollectedHeap::heap()->trace_heap_after_gc(_tracer);
2688 _timer->register_gc_end();
2689 _tracer->report_gc_end(_timer->gc_end(), _timer->time_partitions());
2690 }
2691
2692 void G1CollectedHeap::prepare_for_mutator_after_young_collection() {
2693 Ticks start = Ticks::now();
2694
2695 _survivor_evac_stats.adjust_desired_plab_size();
2696 _old_evac_stats.adjust_desired_plab_size();
2697
2698 // Start a new incremental collection set for the mutator phase.
2699 start_new_collection_set();
2700 _allocator->init_mutator_alloc_regions();
2701
2702 phase_times()->record_prepare_for_mutator_time_ms((Ticks::now() - start).seconds() * 1000.0);
2703 }
2704
2705 void G1CollectedHeap::retire_tlabs() {
2706 ensure_parsability(true);
2707 }
2708
2709 void G1CollectedHeap::flush_region_pin_cache() {
2710 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) {
2711 G1ThreadLocalData::pin_count_cache(thread).flush();
2712 }
2713 }
2714
2715 void G1CollectedHeap::do_collection_pause_at_safepoint(size_t allocation_word_size) {
2716 assert_at_safepoint_on_vm_thread();
2717 assert(!is_stw_gc_active(), "collection is not reentrant");
2718
2719 ResourceMark rm;
2720
2721 IsSTWGCActiveMark active_gc_mark;
2722 GCIdMark gc_id_mark;
2723 SvcGCMarker sgcm(SvcGCMarker::MINOR);
2724
2725 GCTraceCPUTime tcpu(_gc_tracer_stw);
2726
2727 _bytes_used_during_gc = 0;
2728
2729 policy()->decide_on_concurrent_start_pause();
2730 // Record whether this pause may need to trigger a concurrent operation. Later,
2731 // when we signal the G1ConcurrentMarkThread, the collector state has already
2732 // been reset for the next pause.
2733 bool should_start_concurrent_mark_operation = collector_state()->in_concurrent_start_gc();
2734
2735 // Perform the collection.
2736 G1YoungCollector collector(gc_cause(), allocation_word_size);
2737 collector.collect();
2738
2739 // It should now be safe to tell the concurrent mark thread to start
2740 // without its logging output interfering with the logging output
2741 // that came from the pause.
2742 if (should_start_concurrent_mark_operation) {
2743 verifier()->verify_bitmap_clear(true /* above_tams_only */);
2744 // CAUTION: after the start_concurrent_cycle() call below, the concurrent marking
2745 // thread(s) could be running concurrently with us. Make sure that anything
2746 // after this point does not assume that we are the only GC thread running.
2747 // Note: of course, the actual marking work will not start until the safepoint
2748 // itself is released in SuspendibleThreadSet::desynchronize().
2749 start_concurrent_cycle(collector.concurrent_operation_is_full_mark());
2750 ConcurrentGCBreakpoints::notify_idle_to_active();
2751 }
2752 }
2753
2754 void G1CollectedHeap::complete_cleaning(bool class_unloading_occurred) {
2755 G1ParallelCleaningTask unlink_task(class_unloading_occurred);
2756 workers()->run_task(&unlink_task);
2757 }
2758
2759 void G1CollectedHeap::unload_classes_and_code(const char* description, BoolObjectClosure* is_alive, GCTimer* timer) {
2760 GCTraceTime(Debug, gc, phases) debug(description, timer);
2761
2762 ClassUnloadingContext ctx(workers()->active_workers(),
2763 false /* unregister_nmethods_during_purge */,
2764 false /* lock_nmethod_free_separately */);
2765 {
2766 CodeCache::UnlinkingScope scope(is_alive);
2767 bool unloading_occurred = SystemDictionary::do_unloading(timer);
2768 GCTraceTime(Debug, gc, phases) t("G1 Complete Cleaning", timer);
2769 complete_cleaning(unloading_occurred);
2770 }
2771 {
2772 GCTraceTime(Debug, gc, phases) t("Purge Unlinked NMethods", timer);
2773 ctx.purge_nmethods();
2774 }
2775 {
2776 GCTraceTime(Debug, gc, phases) ur("Unregister NMethods", timer);
2777 G1CollectedHeap::heap()->bulk_unregister_nmethods();
2778 }
2779 {
2780 GCTraceTime(Debug, gc, phases) t("Free Code Blobs", timer);
2781 ctx.free_nmethods();
2782 }
2783 {
2784 GCTraceTime(Debug, gc, phases) t("Purge Class Loader Data", timer);
2785 ClassLoaderDataGraph::purge(true /* at_safepoint */);
2786 DEBUG_ONLY(MetaspaceUtils::verify();)
2787 }
2788 }
2789
2790 class G1BulkUnregisterNMethodTask : public WorkerTask {
2791 G1HeapRegionClaimer _hrclaimer;
2792
2793 class UnregisterNMethodsHeapRegionClosure : public G1HeapRegionClosure {
2794 public:
2795
2796 bool do_heap_region(G1HeapRegion* hr) {
2797 hr->rem_set()->bulk_remove_code_roots();
2798 return false;
2799 }
2800 } _cl;
2801
2802 public:
2803 G1BulkUnregisterNMethodTask(uint num_workers)
2804 : WorkerTask("G1 Remove Unlinked NMethods From Code Root Set Task"),
2805 _hrclaimer(num_workers) { }
2806
2807 void work(uint worker_id) {
2808 G1CollectedHeap::heap()->heap_region_par_iterate_from_worker_offset(&_cl, &_hrclaimer, worker_id);
2809 }
2810 };
2811
2812 void G1CollectedHeap::bulk_unregister_nmethods() {
2813 uint num_workers = workers()->active_workers();
2814 G1BulkUnregisterNMethodTask t(num_workers);
2815 workers()->run_task(&t);
2816 }
2817
2818 bool G1STWSubjectToDiscoveryClosure::do_object_b(oop obj) {
2819 assert(obj != nullptr, "must not be null");
2820 assert(_g1h->is_in_reserved(obj), "Trying to discover obj " PTR_FORMAT " not in heap", p2i(obj));
2821 // The areas the CM and STW ref processor manage must be disjoint. The is_in_cset() below
2822 // may falsely indicate that this is not the case here: however the collection set only
2823 // contains old regions when concurrent mark is not running.
2824 return _g1h->is_in_cset(obj) || _g1h->heap_region_containing(obj)->is_survivor();
2825 }
2826
2827 void G1CollectedHeap::make_pending_list_reachable() {
2828 if (collector_state()->in_concurrent_start_gc()) {
2829 oop pll_head = Universe::reference_pending_list();
2830 if (pll_head != nullptr) {
2831 // Any valid worker id is fine here as we are in the VM thread and single-threaded.
2832 _cm->mark_in_bitmap(0 /* worker_id */, pll_head);
2833 }
2834 }
2835 }
2836
2837 void G1CollectedHeap::set_humongous_stats(uint num_humongous_total, uint num_humongous_candidates) {
2838 _num_humongous_objects = num_humongous_total;
2839 _num_humongous_reclaim_candidates = num_humongous_candidates;
2840 }
2841
2842 bool G1CollectedHeap::should_sample_collection_set_candidates() const {
2843 const G1CollectionSetCandidates* candidates = collection_set()->candidates();
2844 return !candidates->is_empty();
2845 }
2846
2847 void G1CollectedHeap::set_collection_set_candidates_stats(G1MonotonicArenaMemoryStats& stats) {
2848 _collection_set_candidates_card_set_stats = stats;
2849 }
2850
2851 void G1CollectedHeap::set_young_gen_card_set_stats(const G1MonotonicArenaMemoryStats& stats) {
2852 _young_gen_card_set_stats = stats;
2853 }
2854
2855 void G1CollectedHeap::record_obj_copy_mem_stats() {
2856 size_t total_old_allocated = _old_evac_stats.allocated() + _old_evac_stats.direct_allocated();
2857 uint total_allocated = _survivor_evac_stats.regions_filled() + _old_evac_stats.regions_filled();
2858
2859 log_debug(gc)("Allocated %u survivor %u old percent total %1.2f%% (%u%%)",
2860 _survivor_evac_stats.regions_filled(), _old_evac_stats.regions_filled(),
2861 percent_of(total_allocated, num_committed_regions() - total_allocated),
2862 G1ReservePercent);
2863
2864 policy()->old_gen_alloc_tracker()->
2865 add_allocated_bytes_since_last_gc(total_old_allocated * HeapWordSize);
2866
2867 _gc_tracer_stw->report_evacuation_statistics(create_g1_evac_summary(&_survivor_evac_stats),
2868 create_g1_evac_summary(&_old_evac_stats));
2869 }
2870
2871 void G1CollectedHeap::clear_bitmap_for_region(G1HeapRegion* hr) {
2872 concurrent_mark()->clear_bitmap_for_region(hr);
2873 }
2874
2875 void G1CollectedHeap::free_region(G1HeapRegion* hr, G1FreeRegionList* free_list) {
2876 assert(!hr->is_free(), "the region should not be free");
2877 assert(!hr->is_empty(), "the region should not be empty");
2878 assert(_hrm.is_available(hr->hrm_index()), "region should be committed");
2879 assert(!hr->has_pinned_objects(),
2880 "must not free a region which contains pinned objects");
2881
2882 // Reset region metadata to allow reuse.
2883 hr->hr_clear(true /* clear_space */);
2884 _policy->remset_tracker()->update_at_free(hr);
2885
2886 if (free_list != nullptr) {
2887 free_list->add_ordered(hr);
2888 }
2889 if (VerifyDuringGC) {
2890 // Card and refinement table must be clear for freed regions.
2891 card_table()->verify_region(MemRegion(hr->bottom(), hr->end()), G1CardTable::clean_card_val(), true);
2892 refinement_table()->verify_region(MemRegion(hr->bottom(), hr->end()), G1CardTable::clean_card_val(), true);
2893 }
2894 }
2895
2896 void G1CollectedHeap::retain_region(G1HeapRegion* hr) {
2897 MutexLocker x(G1RareEvent_lock, Mutex::_no_safepoint_check_flag);
2898 collection_set()->candidates()->add_retained_region_unsorted(hr);
2899 }
2900
2901 void G1CollectedHeap::free_humongous_region(G1HeapRegion* hr,
2902 G1FreeRegionList* free_list) {
2903 assert(hr->is_humongous(), "this is only for humongous regions");
2904 hr->clear_humongous();
2905 free_region(hr, free_list);
2906 }
2907
2908 void G1CollectedHeap::remove_from_old_gen_sets(const uint old_regions_removed,
2909 const uint humongous_regions_removed) {
2910 if (old_regions_removed > 0 || humongous_regions_removed > 0) {
2911 MutexLocker x(G1OldSets_lock, Mutex::_no_safepoint_check_flag);
2912 _old_set.bulk_remove(old_regions_removed);
2913 _humongous_set.bulk_remove(humongous_regions_removed);
2914 }
2915
2916 }
2917
2918 void G1CollectedHeap::prepend_to_freelist(G1FreeRegionList* list) {
2919 assert(list != nullptr, "list can't be null");
2920 if (!list->is_empty()) {
2921 MutexLocker x(G1FreeList_lock, Mutex::_no_safepoint_check_flag);
2922 _hrm.insert_list_into_free_list(list);
2923 }
2924 }
2925
2926 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {
2927 decrease_used(bytes);
2928 }
2929
2930 void G1CollectedHeap::clear_eden() {
2931 _eden.clear();
2932 }
2933
2934 void G1CollectedHeap::clear_collection_set() {
2935 collection_set()->clear();
2936 }
2937
2938 void G1CollectedHeap::rebuild_free_region_list() {
2939 Ticks start = Ticks::now();
2940 _hrm.rebuild_free_list(workers());
2941 phase_times()->record_total_rebuild_freelist_time_ms((Ticks::now() - start).seconds() * 1000.0);
2942 }
2943
2944 class G1AbandonCollectionSetClosure : public G1HeapRegionClosure {
2945 public:
2946 virtual bool do_heap_region(G1HeapRegion* r) {
2947 assert(r->in_collection_set(), "Region %u must have been in collection set", r->hrm_index());
2948 G1CollectedHeap::heap()->clear_region_attr(r);
2949 r->clear_young_index_in_cset();
2950 return false;
2951 }
2952 };
2953
2954 void G1CollectedHeap::abandon_collection_set() {
2955 G1AbandonCollectionSetClosure cl;
2956 collection_set_iterate_all(&cl);
2957
2958 collection_set()->abandon();
2959 }
2960
2961 size_t G1CollectedHeap::non_young_occupancy_after_allocation(size_t allocation_word_size) {
2962 const size_t cur_occupancy = (old_regions_count() + humongous_regions_count()) * G1HeapRegion::GrainBytes -
2963 _allocator->free_bytes_in_retained_old_region();
2964 // Humongous allocations will always be assigned to non-young heap, so consider
2965 // that allocation in the result as well. Otherwise the allocation will always
2966 // be in young gen, so there is no need to account it here.
2967 return cur_occupancy + (is_humongous(allocation_word_size) ? allocation_used_bytes(allocation_word_size) : 0);
2968 }
2969
2970 bool G1CollectedHeap::is_old_gc_alloc_region(G1HeapRegion* hr) {
2971 return _allocator->is_retained_old_region(hr);
2972 }
2973
2974 #ifdef ASSERT
2975
2976 class NoYoungRegionsClosure: public G1HeapRegionClosure {
2977 private:
2978 bool _success;
2979 public:
2980 NoYoungRegionsClosure() : _success(true) { }
2981 bool do_heap_region(G1HeapRegion* r) {
2982 if (r->is_young()) {
2983 log_error(gc, verify)("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young",
2984 p2i(r->bottom()), p2i(r->end()));
2985 _success = false;
2986 }
2987 return false;
2988 }
2989 bool success() { return _success; }
2990 };
2991
2992 bool G1CollectedHeap::check_young_list_empty() {
2993 bool ret = (young_regions_count() == 0);
2994
2995 NoYoungRegionsClosure closure;
2996 heap_region_iterate(&closure);
2997 ret = ret && closure.success();
2998
2999 return ret;
3000 }
3001
3002 #endif // ASSERT
3003
3004 // Remove the given G1HeapRegion from the appropriate region set.
3005 void G1CollectedHeap::prepare_region_for_full_compaction(G1HeapRegion* hr) {
3006 if (hr->is_humongous()) {
3007 _humongous_set.remove(hr);
3008 } else if (hr->is_old()) {
3009 _old_set.remove(hr);
3010 } else if (hr->is_young()) {
3011 // Note that emptying the eden and survivor lists is postponed and instead
3012 // done as the first step when rebuilding the regions sets again. The reason
3013 // for this is that during a full GC string deduplication needs to know if
3014 // a collected region was young or old when the full GC was initiated.
3015 hr->uninstall_surv_rate_group();
3016 } else {
3017 // We ignore free regions, we'll empty the free list afterwards.
3018 assert(hr->is_free(), "it cannot be another type");
3019 }
3020 }
3021
3022 void G1CollectedHeap::increase_used(size_t bytes) {
3023 _summary_bytes_used += bytes;
3024 }
3025
3026 void G1CollectedHeap::decrease_used(size_t bytes) {
3027 assert(_summary_bytes_used >= bytes,
3028 "invariant: _summary_bytes_used: %zu should be >= bytes: %zu",
3029 _summary_bytes_used, bytes);
3030 _summary_bytes_used -= bytes;
3031 }
3032
3033 void G1CollectedHeap::set_used(size_t bytes) {
3034 _summary_bytes_used = bytes;
3035 }
3036
3037 class RebuildRegionSetsClosure : public G1HeapRegionClosure {
3038 private:
3039 bool _free_list_only;
3040
3041 G1HeapRegionSet* _old_set;
3042 G1HeapRegionSet* _humongous_set;
3043
3044 G1HeapRegionManager* _hrm;
3045
3046 size_t _total_used;
3047
3048 public:
3049 RebuildRegionSetsClosure(bool free_list_only,
3050 G1HeapRegionSet* old_set,
3051 G1HeapRegionSet* humongous_set,
3052 G1HeapRegionManager* hrm) :
3053 _free_list_only(free_list_only), _old_set(old_set),
3054 _humongous_set(humongous_set), _hrm(hrm), _total_used(0) {
3055 assert(_hrm->num_free_regions() == 0, "pre-condition");
3056 if (!free_list_only) {
3057 assert(_old_set->is_empty(), "pre-condition");
3058 assert(_humongous_set->is_empty(), "pre-condition");
3059 }
3060 }
3061
3062 bool do_heap_region(G1HeapRegion* r) {
3063 if (r->is_empty()) {
3064 assert(r->rem_set()->is_empty(), "Empty regions should have empty remembered sets.");
3065 // Add free regions to the free list
3066 r->set_free();
3067 _hrm->insert_into_free_list(r);
3068 } else if (!_free_list_only) {
3069 assert(r->rem_set()->is_empty(), "At this point remembered sets must have been cleared.");
3070
3071 if (r->is_humongous()) {
3072 _humongous_set->add(r);
3073 } else {
3074 assert(r->is_young() || r->is_free() || r->is_old(), "invariant");
3075 // We now move all (non-humongous, non-old) regions to old gen,
3076 // and register them as such.
3077 r->move_to_old();
3078 _old_set->add(r);
3079 }
3080 _total_used += r->used();
3081 }
3082
3083 return false;
3084 }
3085
3086 size_t total_used() {
3087 return _total_used;
3088 }
3089 };
3090
3091 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
3092 assert_at_safepoint_on_vm_thread();
3093
3094 if (!free_list_only) {
3095 _eden.clear();
3096 _survivor.clear();
3097 }
3098
3099 RebuildRegionSetsClosure cl(free_list_only,
3100 &_old_set, &_humongous_set,
3101 &_hrm);
3102 heap_region_iterate(&cl);
3103
3104 if (!free_list_only) {
3105 set_used(cl.total_used());
3106 }
3107 assert_used_and_recalculate_used_equal(this);
3108 }
3109
3110 // Methods for the mutator alloc region
3111
3112 G1HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
3113 uint node_index) {
3114 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
3115 bool should_allocate = policy()->should_allocate_mutator_region();
3116 if (should_allocate) {
3117 G1HeapRegion* new_alloc_region = new_region(word_size,
3118 G1HeapRegionType::Eden,
3119 policy()->should_expand_on_mutator_allocation() /* do_expand */,
3120 node_index);
3121 if (new_alloc_region != nullptr) {
3122 new_alloc_region->set_eden();
3123 _eden.add(new_alloc_region);
3124 _policy->set_region_eden(new_alloc_region);
3125
3126 collection_set()->add_eden_region(new_alloc_region);
3127 G1HeapRegionPrinter::alloc(new_alloc_region);
3128 return new_alloc_region;
3129 }
3130 }
3131 return nullptr;
3132 }
3133
3134 void G1CollectedHeap::retire_mutator_alloc_region(G1HeapRegion* alloc_region,
3135 size_t allocated_bytes) {
3136 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
3137 assert(alloc_region->is_eden(), "all mutator alloc regions should be eden");
3138
3139 increase_used(allocated_bytes);
3140 _eden.add_used_bytes(allocated_bytes);
3141 G1HeapRegionPrinter::retire(alloc_region);
3142
3143 // We update the eden sizes here, when the region is retired,
3144 // instead of when it's allocated, since this is the point that its
3145 // used space has been recorded in _summary_bytes_used.
3146 monitoring_support()->update_eden_size();
3147 }
3148
3149 // Methods for the GC alloc regions
3150
3151 bool G1CollectedHeap::has_more_regions(G1HeapRegionAttr dest) {
3152 if (dest.is_old()) {
3153 return true;
3154 } else {
3155 return survivor_regions_count() < policy()->max_survivor_regions();
3156 }
3157 }
3158
3159 G1HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index) {
3160 assert(G1FreeList_lock->owned_by_self(), "pre-condition");
3161
3162 if (!has_more_regions(dest)) {
3163 return nullptr;
3164 }
3165
3166 G1HeapRegionType type;
3167 if (dest.is_young()) {
3168 type = G1HeapRegionType::Survivor;
3169 } else {
3170 type = G1HeapRegionType::Old;
3171 }
3172
3173 G1HeapRegion* new_alloc_region = new_region(word_size,
3174 type,
3175 true /* do_expand */,
3176 node_index);
3177
3178 if (new_alloc_region != nullptr) {
3179 if (type.is_survivor()) {
3180 new_alloc_region->set_survivor();
3181 _survivor.add(new_alloc_region);
3182 // The remembered set/group cardset for this region will be installed at the
3183 // end of GC. Cannot do that right now because we still need the current young
3184 // gen cardset group.
3185 // However, register with the attribute table to collect remembered set entries
3186 // immediately as it is the only source for determining the need for remembered
3187 // set tracking during GC.
3188 register_new_survivor_region_with_region_attr(new_alloc_region);
3189 } else {
3190 new_alloc_region->set_old();
3191 // Update remembered set/cardset.
3192 _policy->remset_tracker()->update_at_allocate(new_alloc_region);
3193 // Synchronize with region attribute table.
3194 update_region_attr(new_alloc_region);
3195 }
3196 G1HeapRegionPrinter::alloc(new_alloc_region);
3197 return new_alloc_region;
3198 }
3199 return nullptr;
3200 }
3201
3202 void G1CollectedHeap::retire_gc_alloc_region(G1HeapRegion* alloc_region,
3203 size_t allocated_bytes,
3204 G1HeapRegionAttr dest) {
3205 _bytes_used_during_gc += allocated_bytes;
3206 if (dest.is_old()) {
3207 old_set_add(alloc_region);
3208 } else {
3209 assert(dest.is_young(), "Retiring alloc region should be young (%d)", dest.type());
3210 _survivor.add_used_bytes(allocated_bytes);
3211 }
3212
3213 bool const during_im = collector_state()->in_concurrent_start_gc();
3214 if (during_im && allocated_bytes > 0) {
3215 _cm->add_root_region(alloc_region);
3216 }
3217 G1HeapRegionPrinter::retire(alloc_region);
3218 }
3219
3220 void G1CollectedHeap::mark_evac_failure_object(uint worker_id, const oop obj, size_t obj_size) const {
3221 assert(!_cm->is_marked_in_bitmap(obj), "must be");
3222
3223 _cm->raw_mark_in_bitmap(obj);
3224 }
3225
3226 // Optimized nmethod scanning
3227 class RegisterNMethodOopClosure: public OopClosure {
3228 G1CollectedHeap* _g1h;
3229 nmethod* _nm;
3230
3231 public:
3232 RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
3233 _g1h(g1h), _nm(nm) {}
3234
3235 void do_oop(oop* p) {
3236 oop heap_oop = RawAccess<>::oop_load(p);
3237 if (!CompressedOops::is_null(heap_oop)) {
3238 oop obj = CompressedOops::decode_not_null(heap_oop);
3239 G1HeapRegion* hr = _g1h->heap_region_containing(obj);
3240 assert(!hr->is_continues_humongous(),
3241 "trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
3242 " starting at " HR_FORMAT,
3243 p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));
3244
3245 hr->add_code_root(_nm);
3246 }
3247 }
3248
3249 void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3250 };
3251
3252 void G1CollectedHeap::register_nmethod(nmethod* nm) {
3253 guarantee(nm != nullptr, "sanity");
3254 RegisterNMethodOopClosure reg_cl(this, nm);
3255 nm->oops_do(®_cl);
3256 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
3257 bs_nm->disarm(nm);
3258 }
3259
3260 void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
3261 // We always unregister nmethods in bulk during code unloading only.
3262 ShouldNotReachHere();
3263 }
3264
3265 void G1CollectedHeap::update_used_after_gc(bool evacuation_failed) {
3266 if (evacuation_failed) {
3267 set_used(recalculate_used());
3268 } else {
3269 // The "used" of the collection set have already been subtracted
3270 // when they were freed. Add in the bytes used.
3271 increase_used(_bytes_used_during_gc);
3272 }
3273 }
3274
3275 class RebuildCodeRootClosure: public NMethodClosure {
3276 G1CollectedHeap* _g1h;
3277
3278 public:
3279 RebuildCodeRootClosure(G1CollectedHeap* g1h) :
3280 _g1h(g1h) {}
3281
3282 void do_nmethod(nmethod* nm) {
3283 assert(nm != nullptr, "Sanity");
3284 _g1h->register_nmethod(nm);
3285 }
3286 };
3287
3288 void G1CollectedHeap::rebuild_code_roots() {
3289 RebuildCodeRootClosure nmethod_cl(this);
3290 CodeCache::nmethods_do(&nmethod_cl);
3291 }
3292
3293 void G1CollectedHeap::initialize_serviceability() {
3294 _monitoring_support->initialize_serviceability();
3295 }
3296
3297 MemoryUsage G1CollectedHeap::memory_usage() {
3298 return _monitoring_support->memory_usage();
3299 }
3300
3301 GrowableArray<GCMemoryManager*> G1CollectedHeap::memory_managers() {
3302 return _monitoring_support->memory_managers();
3303 }
3304
3305 GrowableArray<MemoryPool*> G1CollectedHeap::memory_pools() {
3306 return _monitoring_support->memory_pools();
3307 }
3308
3309 void G1CollectedHeap::fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap) {
3310 G1HeapRegion* region = heap_region_containing(start);
3311 region->fill_with_dummy_object(start, pointer_delta(end, start), zap);
3312 }
3313
3314 void G1CollectedHeap::start_codecache_marking_cycle_if_inactive(bool concurrent_mark_start) {
3315 // We can reach here with an active code cache marking cycle either because the
3316 // previous G1 concurrent marking cycle was undone (if heap occupancy after the
3317 // concurrent start young collection was below the threshold) or aborted. See
3318 // CodeCache::on_gc_marking_cycle_finish() why this is. We must not start a new code
3319 // cache cycle then. If we are about to start a new g1 concurrent marking cycle we
3320 // still have to arm all nmethod entry barriers. They are needed for adding oop
3321 // constants to the SATB snapshot. Full GC does not need nmethods to be armed.
3322 if (!CodeCache::is_gc_marking_cycle_active()) {
3323 CodeCache::on_gc_marking_cycle_start();
3324 }
3325 if (concurrent_mark_start) {
3326 CodeCache::arm_all_nmethods();
3327 }
3328 }
3329
3330 void G1CollectedHeap::finish_codecache_marking_cycle() {
3331 CodeCache::on_gc_marking_cycle_finish();
3332 CodeCache::arm_all_nmethods();
3333 }