1 /*
  2  * Copyright (c) 2002, 2026, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "classfile/javaClasses.inline.hpp"
 26 #include "gc/parallel/mutableSpace.hpp"
 27 #include "gc/parallel/parallelScavengeHeap.hpp"
 28 #include "gc/parallel/psOldGen.hpp"
 29 #include "gc/parallel/psPromotionManager.inline.hpp"
 30 #include "gc/parallel/psScavenge.hpp"
 31 #include "gc/shared/continuationGCSupport.inline.hpp"
 32 #include "gc/shared/gc_globals.hpp"
 33 #include "gc/shared/gcTrace.hpp"
 34 #include "gc/shared/partialArraySplitter.inline.hpp"
 35 #include "gc/shared/partialArrayState.hpp"
 36 #include "gc/shared/preservedMarks.inline.hpp"
 37 #include "gc/shared/taskqueue.inline.hpp"
 38 #include "logging/log.hpp"
 39 #include "logging/logStream.hpp"
 40 #include "memory/allocation.inline.hpp"
 41 #include "memory/iterator.inline.hpp"
 42 #include "memory/memRegion.hpp"
 43 #include "memory/padded.inline.hpp"
 44 #include "memory/resourceArea.hpp"
 45 #include "oops/access.inline.hpp"
 46 #include "oops/compressedOops.inline.hpp"
 47 #include "oops/oopsHierarchy.hpp"
 48 #include "utilities/checkedCast.hpp"
 49 #include "utilities/debug.hpp"
 50 
 51 PaddedEnd<PSPromotionManager>* PSPromotionManager::_manager_array = nullptr;
 52 PSPromotionManager::PSScannerTasksQueueSet* PSPromotionManager::_stack_array_depth = nullptr;
 53 PreservedMarksSet*             PSPromotionManager::_preserved_marks_set = nullptr;
 54 PSOldGen*                      PSPromotionManager::_old_gen = nullptr;
 55 MutableSpace*                  PSPromotionManager::_young_space = nullptr;
 56 PartialArrayStateManager*      PSPromotionManager::_partial_array_state_manager = nullptr;
 57 
 58 void PSPromotionManager::initialize() {
 59   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 60 
 61   _old_gen = heap->old_gen();
 62   _young_space = heap->young_gen()->to_space();
 63 
 64   const uint promotion_manager_num = ParallelGCThreads;
 65 
 66   assert(_partial_array_state_manager == nullptr, "Attempt to initialize twice");
 67   _partial_array_state_manager
 68     = new PartialArrayStateManager(promotion_manager_num);
 69 
 70   // To prevent false sharing, we pad the PSPromotionManagers
 71   // and make sure that the first instance starts at a cache line.
 72   assert(_manager_array == nullptr, "Attempt to initialize twice");
 73   _manager_array = PaddedArray<PSPromotionManager, mtGC>::create_unfreeable(promotion_manager_num);
 74 
 75   _stack_array_depth = new PSScannerTasksQueueSet(promotion_manager_num);
 76 
 77   // Create and register the PSPromotionManager(s) for the worker threads.
 78   for(uint i=0; i<ParallelGCThreads; i++) {
 79     stack_array_depth()->register_queue(i, _manager_array[i].claimed_stack_depth());
 80   }
 81   // The VMThread gets its own PSPromotionManager, which is not available
 82   // for work stealing.
 83 
 84   assert(_preserved_marks_set == nullptr, "Attempt to initialize twice");
 85   _preserved_marks_set = new PreservedMarksSet(true /* in_c_heap */);
 86   _preserved_marks_set->init(promotion_manager_num);
 87   for (uint i = 0; i < promotion_manager_num; i += 1) {
 88     _manager_array[i].register_preserved_marks(_preserved_marks_set->get(i));
 89   }
 90 }
 91 
 92 PSPromotionManager* PSPromotionManager::gc_thread_promotion_manager(uint index) {
 93   assert(index < ParallelGCThreads, "index out of range");
 94   assert(_manager_array != nullptr, "Sanity");
 95   return &_manager_array[index];
 96 }
 97 
 98 PSPromotionManager* PSPromotionManager::vm_thread_promotion_manager() {
 99   assert(_manager_array != nullptr, "Sanity");
100   return &_manager_array[0];
101 }
102 
103 void PSPromotionManager::pre_scavenge() {
104   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
105 
106   _preserved_marks_set->assert_empty();
107   _young_space = heap->young_gen()->to_space();
108 
109   for(uint i=0; i<ParallelGCThreads; i++) {
110     manager_array(i)->reset();
111   }
112 }
113 
114 bool PSPromotionManager::post_scavenge(YoungGCTracer& gc_tracer) {
115   bool promotion_failure_occurred = false;
116 
117   TASKQUEUE_STATS_ONLY(print_and_reset_taskqueue_stats());
118   for (uint i = 0; i < ParallelGCThreads; i++) {
119     PSPromotionManager* manager = manager_array(i);
120     assert(manager->claimed_stack_depth()->is_empty(), "should be empty");
121     if (manager->_promotion_failed_info.has_failed()) {
122       gc_tracer.report_promotion_failed(manager->_promotion_failed_info);
123       promotion_failure_occurred = true;
124     }
125     manager->flush_labs();
126     manager->flush_string_dedup_requests();
127   }
128   // All PartialArrayStates have been returned to the allocator, since the
129   // claimed_stack_depths are all empty.  Leave them there for use by future
130   // collections.
131 
132   if (!promotion_failure_occurred) {
133     // If there was no promotion failure, the preserved mark stacks
134     // should be empty.
135     _preserved_marks_set->assert_empty();
136   }
137   return promotion_failure_occurred;
138 }
139 
140 #if TASKQUEUE_STATS
141 
142 void PSPromotionManager::print_and_reset_taskqueue_stats() {
143   stack_array_depth()->print_and_reset_taskqueue_stats("Young GC");
144 
145   auto get_pa_stats = [&](uint i) {
146     return manager_array(i)->partial_array_task_stats();
147   };
148   PartialArrayTaskStats::log_set(ParallelGCThreads, get_pa_stats,
149                                  "Young GC Partial Array");
150   for (uint i = 0; i < ParallelGCThreads; ++i) {
151     get_pa_stats(i)->reset();
152   }
153 }
154 
155 PartialArrayTaskStats* PSPromotionManager::partial_array_task_stats() {
156   return _partial_array_splitter.stats();
157 }
158 
159 #endif // TASKQUEUE_STATS
160 
161 // Most members are initialized either by initialize() or reset().
162 PSPromotionManager::PSPromotionManager()
163   : _partial_array_splitter(_partial_array_state_manager, ParallelGCThreads)
164 {
165   // We set the old lab's start array.
166   _old_lab.set_start_array(old_gen()->start_array());
167 
168   // let's choose 1.5x the chunk size
169   _min_array_size_for_chunking = (3 * ParGCArrayScanChunk / 2);
170 
171   _preserved_marks = nullptr;
172 
173   reset();
174 }
175 
176 void PSPromotionManager::reset() {
177   assert(stacks_empty(), "reset of non-empty stack");
178 
179   // We need to get an assert in here to make sure the labs are always flushed.
180 
181   // Do not prefill the LAB's, save heap wastage!
182   HeapWord* lab_base = young_space()->top();
183   _young_lab.initialize(MemRegion(lab_base, (size_t)0));
184   _young_gen_has_alloc_failure = false;
185   _young_gen_is_full = false;
186 
187   lab_base = old_gen()->object_space()->top();
188   _old_lab.initialize(MemRegion(lab_base, (size_t)0));
189   _old_gen_is_full = false;
190 
191   _promotion_failed_info.reset();
192 }
193 
194 void PSPromotionManager::register_preserved_marks(PreservedMarks* preserved_marks) {
195   assert(_preserved_marks == nullptr, "do not set it twice");
196   _preserved_marks = preserved_marks;
197 }
198 
199 void PSPromotionManager::restore_preserved_marks() {
200   _preserved_marks_set->restore(&ParallelScavengeHeap::heap()->workers());
201 }
202 
203 void PSPromotionManager::trim_stacks_to_threshold(uint threshold) {
204   PSScannerTasksQueue* const tq = claimed_stack_depth();
205   do {
206     ScannerTask task;
207 
208     // Drain overflow stack first, so other threads can steal from
209     // claimed stack while we work.
210     while (tq->pop_overflow(task)) {
211       if (!tq->try_push_to_taskqueue(task)) {
212         process_popped_location_depth(task, false);
213       }
214     }
215 
216     while (tq->pop_local(task, threshold)) {
217       process_popped_location_depth(task, false);
218     }
219   } while (!tq->overflow_empty());
220 
221   assert(tq->size() <= threshold, "Sanity");
222   assert(tq->overflow_empty(), "Sanity");
223 }
224 
225 void PSPromotionManager::trim_stacks() {
226   const uint target_stack_size = GCDrainStackTargetSize;
227   const uint max_stack_size = target_stack_size * 2 + 1;
228 
229   PSScannerTasksQueue* const tq = claimed_stack_depth();
230   if (!tq->overflow_empty() || tq->size() > max_stack_size) {
231     trim_stacks_to_threshold(target_stack_size);
232   }
233 }
234 
235 void PSPromotionManager::drain_stacks() {
236   trim_stacks_to_threshold(0);
237 }
238 
239 void PSPromotionManager::flush_labs() {
240   assert(stacks_empty(), "Attempt to flush lab with live stack");
241 
242   // If either promotion lab fills up, we can flush the
243   // lab but not refill it, so check first.
244   assert(!_young_lab.is_flushed() || _young_gen_is_full, "Sanity");
245   if (!_young_lab.is_flushed())
246     _young_lab.flush();
247 
248   assert(!_old_lab.is_flushed() || _old_gen_is_full, "Sanity");
249   if (!_old_lab.is_flushed())
250     _old_lab.flush();
251 
252   // Let PSScavenge know if we overflowed
253   if (_young_gen_is_full || _young_gen_has_alloc_failure) {
254     PSScavenge::set_survivor_overflow(true);
255   }
256 }
257 
258 void PSPromotionManager::process_array_chunk(objArrayOop obj, size_t start, size_t end) {
259   PSPushContentsClosure pcc(this);
260   obj->oop_iterate_elements_range(&pcc,
261                                   checked_cast<int>(start),
262                                   checked_cast<int>(end));
263 }
264 
265 void PSPromotionManager::process_array_chunk(PartialArrayState* state, bool stolen) {
266   // Access before release by claim().
267   objArrayOop to_array = objArrayOop(state->destination());
268   precond(to_array->is_array_with_oops());
269 
270   PartialArraySplitter::Claim claim =
271     _partial_array_splitter.claim(state, &_claimed_stack_depth, stolen);
272 
273   process_array_chunk(to_array, claim._start, claim._end);
274 }
275 
276 void PSPromotionManager::push_objArray(oop old_obj, oop new_obj) {
277   assert(old_obj->is_forwarded(), "precondition");
278   assert(old_obj->forwardee() == new_obj, "precondition");
279   precond(new_obj->is_array_with_oops());
280 
281   objArrayOop to_array = objArrayOop(new_obj);
282   size_t array_length = to_array->length();
283   size_t initial_chunk_size =
284     // The source array is unused when processing states.
285     _partial_array_splitter.start(&_claimed_stack_depth, nullptr, to_array, array_length, ParGCArrayScanChunk);
286 
287   process_array_chunk(to_array, 0, initial_chunk_size);
288 }
289 
290 oop PSPromotionManager::oop_promotion_failed(oop obj, markWord obj_mark) {
291   assert(_old_gen_is_full || PromotionFailureALot, "Sanity");
292 
293   // Attempt to CAS in the header.
294   // This tests if the header is still the same as when
295   // this started.  If it is the same (i.e., no forwarding
296   // pointer has been installed), then this thread owns
297   // it.
298   if (obj->forward_to_self_atomic(obj_mark) == nullptr) {
299     // We won any races, we "own" this object.
300     assert(obj == obj->forwardee(), "Sanity");
301 
302     _promotion_failed_info.register_copy_failure(obj->size());
303 
304     ContinuationGCSupport::transform_stack_chunk(obj);
305 
306     push_contents(obj, obj->klass());
307 
308     // Save the markWord of promotion-failed objs in _preserved_marks for later
309     // restoration. This way we don't have to walk the young-gen to locate
310     // these promotion-failed objs.
311     _preserved_marks->push_always(obj, obj_mark);
312   }  else {
313     // We lost, someone else "owns" this object
314     guarantee(obj->is_forwarded(), "Object must be forwarded if the cas failed.");
315 
316     // No unallocation to worry about.
317     obj = obj->forwardee();
318   }
319 
320   return obj;
321 }