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