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