1 /*
  2  * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2017, Red Hat, Inc. and/or its affiliates.
  4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  5  *
  6  * This code is free software; you can redistribute it and/or modify it
  7  * under the terms of the GNU General Public License version 2 only, as
  8  * published by the Free Software Foundation.
  9  *
 10  * This code is distributed in the hope that it will be useful, but WITHOUT
 11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 13  * version 2 for more details (a copy is included in the LICENSE file that
 14  * accompanied this code).
 15  *
 16  * You should have received a copy of the GNU General Public License version
 17  * 2 along with this work; if not, write to the Free Software Foundation,
 18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 19  *
 20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 21  * or visit www.oracle.com if you need additional information or have any
 22  * questions.
 23  *
 24  */
 25 
 26 #include "cds/cdsConfig.hpp"
 27 #include "gc/g1/g1Arguments.hpp"
 28 #include "gc/g1/g1CardSet.hpp"
 29 #include "gc/g1/g1CardSetContainers.inline.hpp"
 30 #include "gc/g1/g1CollectedHeap.inline.hpp"
 31 #include "gc/g1/g1HeapRegion.hpp"
 32 #include "gc/g1/g1HeapRegionBounds.inline.hpp"
 33 #include "gc/g1/g1HeapRegionRemSet.hpp"
 34 #include "gc/g1/g1HeapVerifier.hpp"
 35 #include "gc/shared/cardTable.hpp"
 36 #include "gc/shared/fullGCForwarding.hpp"
 37 #include "gc/shared/gcArguments.hpp"
 38 #include "gc/shared/workerPolicy.hpp"
 39 #include "runtime/flags/jvmFlagLimit.hpp"
 40 #include "runtime/globals.hpp"
 41 #include "runtime/globals_extension.hpp"
 42 #include "runtime/java.hpp"
 43 
 44 static size_t calculate_heap_alignment(size_t space_alignment) {
 45   size_t card_table_alignment = CardTable::ct_max_alignment_constraint();
 46   size_t page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();
 47   return MAX3(card_table_alignment, space_alignment, page_size);
 48 }
 49 
 50 void G1Arguments::initialize_alignments() {
 51   // Initialize card size before initializing alignments
 52   CardTable::initialize_card_size();
 53 
 54   // Set up the region size and associated fields.
 55   //
 56   // There is a circular dependency here. We base the region size on the heap
 57   // size, but the heap size should be aligned with the region size. To get
 58   // around this we use the unaligned values for the heap.
 59   G1HeapRegion::setup_heap_region_size(MaxHeapSize);
 60 
 61   SpaceAlignment = G1HeapRegion::GrainBytes;
 62   HeapAlignment = calculate_heap_alignment(SpaceAlignment);
 63 
 64   // We need to initialize card set configuration as soon as heap region size is
 65   // known as it depends on it and is used really early.
 66   initialize_card_set_configuration();
 67   // Needs remembered set initialization as the ergonomics are based
 68   // on it.
 69   if (FLAG_IS_DEFAULT(G1EagerReclaimRemSetThreshold)) {
 70     FLAG_SET_ERGO(G1EagerReclaimRemSetThreshold, G1RemSetArrayOfCardsEntries);
 71   }
 72   // G1 prefers to use conditional card marking to avoid overwriting cards that
 73   // have already been found to contain a to-collection set reference. This reduces
 74   // refinement effort.
 75   if (FLAG_IS_DEFAULT(UseCondCardMark)) {
 76     FLAG_SET_ERGO(UseCondCardMark, true);
 77   }
 78 }
 79 
 80 size_t G1Arguments::conservative_max_heap_alignment() {
 81   const size_t region_size = FLAG_IS_DEFAULT(G1HeapRegionSize)
 82                            ? G1HeapRegion::max_ergonomics_size()
 83                            : G1HeapRegion::max_region_size();
 84 
 85   return calculate_heap_alignment(region_size);
 86 }
 87 
 88 void G1Arguments::initialize_verification_types() {
 89   if (strlen(VerifyGCType) > 0) {
 90     const char delimiter[] = " ,\n";
 91     size_t length = strlen(VerifyGCType);
 92     char* type_list = NEW_C_HEAP_ARRAY(char, length + 1, mtInternal);
 93     strncpy(type_list, VerifyGCType, length + 1);
 94     char* save_ptr;
 95 
 96     char* token = strtok_r(type_list, delimiter, &save_ptr);
 97     while (token != nullptr) {
 98       parse_verification_type(token);
 99       token = strtok_r(nullptr, delimiter, &save_ptr);
100     }
101     FREE_C_HEAP_ARRAY(char, type_list);
102   }
103 }
104 
105 void G1Arguments::parse_verification_type(const char* type) {
106   if (strcmp(type, "young-normal") == 0) {
107     G1HeapVerifier::enable_verification_type(G1HeapVerifier::G1VerifyYoungNormal);
108   } else if (strcmp(type, "concurrent-start") == 0) {
109     G1HeapVerifier::enable_verification_type(G1HeapVerifier::G1VerifyConcurrentStart);
110   } else if (strcmp(type, "mixed") == 0) {
111     G1HeapVerifier::enable_verification_type(G1HeapVerifier::G1VerifyMixed);
112   } else if (strcmp(type, "young-evac-fail") == 0) {
113     G1HeapVerifier::enable_verification_type(G1HeapVerifier::G1VerifyYoungEvacFail);
114   } else if (strcmp(type, "remark") == 0) {
115     G1HeapVerifier::enable_verification_type(G1HeapVerifier::G1VerifyRemark);
116   } else if (strcmp(type, "cleanup") == 0) {
117     G1HeapVerifier::enable_verification_type(G1HeapVerifier::G1VerifyCleanup);
118   } else if (strcmp(type, "full") == 0) {
119     G1HeapVerifier::enable_verification_type(G1HeapVerifier::G1VerifyFull);
120   } else {
121     log_warning(gc, verify)("VerifyGCType: '%s' is unknown. Available types are: "
122                             "young-normal, young-evac-fail, concurrent-start, mixed, remark, cleanup and full", type);
123   }
124 }
125 
126 // Returns the maximum number of workers to be used in a concurrent
127 // phase based on the number of GC workers being used in a STW
128 // phase.
129 static uint scale_concurrent_worker_threads(uint num_gc_workers) {
130   return MAX2((num_gc_workers + 2) / 4, 1U);
131 }
132 
133 void G1Arguments::initialize_mark_stack_size() {
134   if (FLAG_IS_DEFAULT(MarkStackSize)) {
135     size_t mark_stack_size = MIN2(MarkStackSizeMax,
136                                   MAX2(MarkStackSize, (size_t)ConcGCThreads * TASKQUEUE_SIZE));
137     FLAG_SET_ERGO(MarkStackSize, mark_stack_size);
138   }
139 }
140 
141 void G1Arguments::initialize_card_set_configuration() {
142   assert(G1HeapRegion::LogOfHRGrainBytes != 0, "not initialized");
143   // Array of Cards card set container globals.
144   const uint LOG_M = 20;
145   assert(log2i_exact(G1HeapRegionBounds::min_size()) == LOG_M, "inv");
146   assert(G1HeapRegion::LogOfHRGrainBytes >= LOG_M, "from the above");
147   uint region_size_log_mb = G1HeapRegion::LogOfHRGrainBytes - LOG_M;
148 
149   if (FLAG_IS_DEFAULT(G1RemSetArrayOfCardsEntries)) {
150     uint max_cards_in_inline_ptr = G1CardSetConfiguration::max_cards_in_inline_ptr(G1HeapRegion::LogCardsPerRegion);
151     FLAG_SET_ERGO(G1RemSetArrayOfCardsEntries, MAX2(max_cards_in_inline_ptr * 2,
152                                                     G1RemSetArrayOfCardsEntriesBase << region_size_log_mb));
153   }
154 
155   // Howl card set container globals.
156   if (FLAG_IS_DEFAULT(G1RemSetHowlNumBuckets)) {
157     FLAG_SET_ERGO(G1RemSetHowlNumBuckets, G1CardSetHowl::num_buckets(G1HeapRegion::CardsPerRegion,
158                                                                      G1RemSetArrayOfCardsEntries,
159                                                                      G1RemSetHowlMaxNumBuckets));
160   }
161 
162   if (FLAG_IS_DEFAULT(G1RemSetHowlMaxNumBuckets)) {
163     FLAG_SET_ERGO(G1RemSetHowlMaxNumBuckets, MAX2(G1RemSetHowlMaxNumBuckets, G1RemSetHowlNumBuckets));
164   } else if (G1RemSetHowlMaxNumBuckets < G1RemSetHowlNumBuckets) {
165     FormatBuffer<> buf("Maximum Howl card set container bucket size %u smaller than requested bucket size %u",
166                        G1RemSetHowlMaxNumBuckets, G1RemSetHowlNumBuckets);
167     vm_exit_during_initialization(buf);
168   }
169 }
170 
171 void G1Arguments::initialize() {
172   GCArguments::initialize();
173   assert(UseG1GC, "Error");
174   FLAG_SET_DEFAULT(ParallelGCThreads, WorkerPolicy::parallel_worker_threads());
175   if (ParallelGCThreads == 0) {
176     assert(!FLAG_IS_DEFAULT(ParallelGCThreads), "The default value for ParallelGCThreads should not be 0.");
177     vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", nullptr);
178   }
179 
180   // When dumping the CDS heap we want to reduce fragmentation by
181   // triggering a full collection. To get as low fragmentation as
182   // possible we only use one worker thread.
183   if (CDSConfig::is_dumping_heap()) {
184     FLAG_SET_ERGO(ParallelGCThreads, 1);
185   }
186 
187   if (!G1UseConcRefinement) {
188     if (!FLAG_IS_DEFAULT(G1ConcRefinementThreads)) {
189       log_warning(gc, ergo)("Ignoring -XX:G1ConcRefinementThreads "
190                             "because of -XX:-G1UseConcRefinement");
191     }
192     FLAG_SET_DEFAULT(G1ConcRefinementThreads, 0);
193   } else if (FLAG_IS_DEFAULT(G1ConcRefinementThreads)) {
194     const JVMTypedFlagLimit<uint>* conc_refinement_threads_limits = JVMFlagLimit::get_range_at(FLAG_MEMBER_ENUM(G1ConcRefinementThreads))->cast<uint>();
195     FLAG_SET_ERGO(G1ConcRefinementThreads, MIN2(ParallelGCThreads, conc_refinement_threads_limits->max()));
196   }
197 
198   if (FLAG_IS_DEFAULT(ConcGCThreads) || ConcGCThreads == 0) {
199     // Calculate the number of concurrent worker threads by scaling
200     // the number of parallel GC threads.
201     uint marking_thread_num = scale_concurrent_worker_threads(ParallelGCThreads);
202     FLAG_SET_ERGO(ConcGCThreads, marking_thread_num);
203   }
204 
205   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
206     // In G1, we want the default GC overhead goal to be higher than
207     // it is for PS, or the heap might be expanded too aggressively.
208     // We set it here to 4%.
209     FLAG_SET_DEFAULT(GCTimeRatio, 24);
210   }
211 
212   // Do not interfere with GC-Pressure driven heap resizing unless the user
213   // explicitly sets otherwise. G1 heap sizing should be free to grow or shrink
214   // the heap based on GC pressure, rather than being forced to satisfy
215   // MinHeapFreeRatio or MaxHeapFreeRatio defaults that the user did not set.
216   if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
217     FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
218   }
219   if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
220     FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
221   }
222 
223   // Below, we might need to calculate the pause time interval based on
224   // the pause target. When we do so we are going to give G1 maximum
225   // flexibility and allow it to do pauses when it needs to. So, we'll
226   // arrange that the pause interval to be pause time target + 1 to
227   // ensure that a) the pause time target is maximized with respect to
228   // the pause interval and b) we maintain the invariant that pause
229   // time target < pause interval. If the user does not want this
230   // maximum flexibility, they will have to set the pause interval
231   // explicitly.
232 
233   if (FLAG_IS_DEFAULT(MaxGCPauseMillis)) {
234     // The default pause time target in G1 is 200ms
235     FLAG_SET_DEFAULT(MaxGCPauseMillis, 200);
236   }
237 
238   // Then, if the interval parameter was not set, set it according to
239   // the pause time target (this will also deal with the case when the
240   // pause time target is the default value).
241   if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
242     FLAG_SET_DEFAULT(GCPauseIntervalMillis, MaxGCPauseMillis + 1);
243   }
244 
245 #ifdef COMPILER2
246   // Enable loop strip mining to offer better pause time guarantees
247   if (FLAG_IS_DEFAULT(UseCountedLoopSafepoints)) {
248     FLAG_SET_DEFAULT(UseCountedLoopSafepoints, true);
249     if (FLAG_IS_DEFAULT(LoopStripMiningIter)) {
250       FLAG_SET_DEFAULT(LoopStripMiningIter, 1000);
251     }
252   }
253 #endif
254 
255   initialize_mark_stack_size();
256   initialize_verification_types();
257 
258   // Verify that the maximum parallelism isn't too high to eventually overflow
259   // the refcount in G1CardSetContainer.
260   uint const divisor = 3;  // Safe divisor; we increment by 2 for each claim, but there is a small initial value.
261   if (G1ConcRefinementThreads > UINT_MAX / divisor) {
262     vm_exit_during_initialization("Too large parallelism for remembered sets.");
263   }
264 
265   FullGCForwarding::initialize_flags(heap_reserved_size_bytes());
266 }
267 
268 CollectedHeap* G1Arguments::create_heap() {
269   return new G1CollectedHeap();
270 }
271 
272 size_t G1Arguments::heap_reserved_size_bytes() {
273   return MaxHeapSize;
274 }