1 /*
  2  * Copyright (c) 2002, 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/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.inline.hpp"
 31 #include "gc/shared/continuationGCSupport.inline.hpp"
 32 #include "gc/shared/gcTrace.hpp"
 33 #include "gc/shared/partialArraySplitter.inline.hpp"
 34 #include "gc/shared/partialArrayState.hpp"
 35 #include "gc/shared/preservedMarks.inline.hpp"
 36 #include "gc/shared/taskqueue.inline.hpp"
 37 #include "logging/log.hpp"
 38 #include "logging/logStream.hpp"
 39 #include "memory/allocation.inline.hpp"
 40 #include "memory/iterator.inline.hpp"
 41 #include "memory/memRegion.hpp"
 42 #include "memory/padded.inline.hpp"
 43 #include "memory/resourceArea.hpp"
 44 #include "oops/access.inline.hpp"
 45 #include "oops/compressedOops.inline.hpp"
 46 #include "utilities/checkedCast.hpp"
 47 
 48 PaddedEnd<PSPromotionManager>* PSPromotionManager::_manager_array = nullptr;
 49 PSPromotionManager::PSScannerTasksQueueSet* PSPromotionManager::_stack_array_depth = nullptr;
 50 PreservedMarksSet*             PSPromotionManager::_preserved_marks_set = nullptr;
 51 PSOldGen*                      PSPromotionManager::_old_gen = nullptr;
 52 MutableSpace*                  PSPromotionManager::_young_space = nullptr;
 53 PartialArrayStateManager*      PSPromotionManager::_partial_array_state_manager = nullptr;
 54 
 55 void PSPromotionManager::initialize() {
 56   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 57 
 58   _old_gen = heap->old_gen();
 59   _young_space = heap->young_gen()->to_space();
 60 
 61   const uint promotion_manager_num = ParallelGCThreads;
 62 
 63   assert(_partial_array_state_manager == nullptr, "Attempt to initialize twice");
 64   _partial_array_state_manager
 65     = new PartialArrayStateManager(promotion_manager_num);
 66 
 67   // To prevent false sharing, we pad the PSPromotionManagers
 68   // and make sure that the first instance starts at a cache line.
 69   assert(_manager_array == nullptr, "Attempt to initialize twice");
 70   _manager_array = PaddedArray<PSPromotionManager, mtGC>::create_unfreeable(promotion_manager_num);
 71 
 72   _stack_array_depth = new PSScannerTasksQueueSet(promotion_manager_num);
 73 
 74   // Create and register the PSPromotionManager(s) for the worker threads.
 75   for(uint i=0; i<ParallelGCThreads; i++) {
 76     stack_array_depth()->register_queue(i, _manager_array[i].claimed_stack_depth());
 77   }
 78   // The VMThread gets its own PSPromotionManager, which is not available
 79   // for work stealing.
 80 
 81   assert(_preserved_marks_set == nullptr, "Attempt to initialize twice");
 82   _preserved_marks_set = new PreservedMarksSet(true /* in_c_heap */);
 83   _preserved_marks_set->init(promotion_manager_num);
 84   for (uint i = 0; i < promotion_manager_num; i += 1) {
 85     _manager_array[i].register_preserved_marks(_preserved_marks_set->get(i));
 86   }
 87 }
 88 
 89 // Helper functions to get around the circular dependency between
 90 // psScavenge.inline.hpp and psPromotionManager.inline.hpp.
 91 bool PSPromotionManager::should_scavenge(oop* p, bool check_to_space) {
 92   return PSScavenge::should_scavenge(p, check_to_space);
 93 }
 94 bool PSPromotionManager::should_scavenge(narrowOop* p, bool check_to_space) {
 95   return PSScavenge::should_scavenge(p, check_to_space);
 96 }
 97 
 98 PSPromotionManager* PSPromotionManager::gc_thread_promotion_manager(uint index) {
 99   assert(index < ParallelGCThreads, "index out of range");
100   assert(_manager_array != nullptr, "Sanity");
101   return &_manager_array[index];
102 }
103 
104 PSPromotionManager* PSPromotionManager::vm_thread_promotion_manager() {
105   assert(_manager_array != nullptr, "Sanity");
106   return &_manager_array[0];
107 }
108 
109 void PSPromotionManager::pre_scavenge() {
110   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
111 
112   _preserved_marks_set->assert_empty();
113   _young_space = heap->young_gen()->to_space();
114 
115   for(uint i=0; i<ParallelGCThreads; i++) {
116     manager_array(i)->reset();
117   }
118 }
119 
120 bool PSPromotionManager::post_scavenge(YoungGCTracer& gc_tracer) {
121   bool promotion_failure_occurred = false;
122 
123   TASKQUEUE_STATS_ONLY(print_and_reset_taskqueue_stats());
124   for (uint i = 0; i < ParallelGCThreads; i++) {
125     PSPromotionManager* manager = manager_array(i);
126     assert(manager->claimed_stack_depth()->is_empty(), "should be empty");
127     if (manager->_promotion_failed_info.has_failed()) {
128       gc_tracer.report_promotion_failed(manager->_promotion_failed_info);
129       promotion_failure_occurred = true;
130     }
131     manager->flush_labs();
132     manager->flush_string_dedup_requests();
133   }
134   // All PartialArrayStates have been returned to the allocator, since the
135   // claimed_stack_depths are all empty.  Leave them there for use by future
136   // collections.
137 
138   if (!promotion_failure_occurred) {
139     // If there was no promotion failure, the preserved mark stacks
140     // should be empty.
141     _preserved_marks_set->assert_empty();
142   }
143   return promotion_failure_occurred;
144 }
145 
146 #if TASKQUEUE_STATS
147 
148 void PSPromotionManager::print_and_reset_taskqueue_stats() {
149   stack_array_depth()->print_and_reset_taskqueue_stats("Oop Queue");
150 
151   auto get_pa_stats = [&](uint i) {
152     return manager_array(i)->partial_array_task_stats();
153   };
154   PartialArrayTaskStats::log_set(ParallelGCThreads, get_pa_stats,
155                                  "Partial Array Task Stats");
156   for (uint i = 0; i < ParallelGCThreads; ++i) {
157     get_pa_stats(i)->reset();
158   }
159 }
160 
161 PartialArrayTaskStats* PSPromotionManager::partial_array_task_stats() {
162   return _partial_array_splitter.stats();
163 }
164 
165 #endif // TASKQUEUE_STATS
166 
167 // Most members are initialized either by initialize() or reset().
168 PSPromotionManager::PSPromotionManager()
169   : _partial_array_splitter(_partial_array_state_manager, ParallelGCThreads)
170 {
171   // We set the old lab's start array.
172   _old_lab.set_start_array(old_gen()->start_array());
173 
174   if (ParallelGCThreads == 1) {
175     _target_stack_size = 0;
176   } else {
177     _target_stack_size = GCDrainStackTargetSize;
178   }
179 
180   // let's choose 1.5x the chunk size
181   _min_array_size_for_chunking = (3 * ParGCArrayScanChunk / 2);
182 
183   _preserved_marks = nullptr;
184 
185   reset();
186 }
187 
188 void PSPromotionManager::reset() {
189   assert(stacks_empty(), "reset of non-empty stack");
190 
191   // We need to get an assert in here to make sure the labs are always flushed.
192 
193   // Do not prefill the LAB's, save heap wastage!
194   HeapWord* lab_base = young_space()->top();
195   _young_lab.initialize(MemRegion(lab_base, (size_t)0));
196   _young_gen_is_full = false;
197 
198   lab_base = old_gen()->object_space()->top();
199   _old_lab.initialize(MemRegion(lab_base, (size_t)0));
200   _old_gen_is_full = false;
201 
202   _promotion_failed_info.reset();
203 }
204 
205 void PSPromotionManager::register_preserved_marks(PreservedMarks* preserved_marks) {
206   assert(_preserved_marks == nullptr, "do not set it twice");
207   _preserved_marks = preserved_marks;
208 }
209 
210 void PSPromotionManager::restore_preserved_marks() {
211   _preserved_marks_set->restore(&ParallelScavengeHeap::heap()->workers());
212 }
213 
214 void PSPromotionManager::drain_stacks_depth(bool totally_drain) {
215   const uint threshold = totally_drain ? 0
216                                        : _target_stack_size;
217 
218   PSScannerTasksQueue* const tq = claimed_stack_depth();
219   do {
220     ScannerTask task;
221 
222     // Drain overflow stack first, so other threads can steal from
223     // claimed stack while we work.
224     while (tq->pop_overflow(task)) {
225       if (!tq->try_push_to_taskqueue(task)) {
226         process_popped_location_depth(task, false);
227       }
228     }
229 
230     while (tq->pop_local(task, threshold)) {
231       process_popped_location_depth(task, false);
232     }
233   } while (!tq->overflow_empty());
234 
235   assert(!totally_drain || tq->taskqueue_empty(), "Sanity");
236   assert(totally_drain || tq->size() <= _target_stack_size, "Sanity");
237   assert(tq->overflow_empty(), "Sanity");
238 }
239 
240 void PSPromotionManager::flush_labs() {
241   assert(stacks_empty(), "Attempt to flush lab with live stack");
242 
243   // If either promotion lab fills up, we can flush the
244   // lab but not refill it, so check first.
245   assert(!_young_lab.is_flushed() || _young_gen_is_full, "Sanity");
246   if (!_young_lab.is_flushed())
247     _young_lab.flush();
248 
249   assert(!_old_lab.is_flushed() || _old_gen_is_full, "Sanity");
250   if (!_old_lab.is_flushed())
251     _old_lab.flush();
252 
253   // Let PSScavenge know if we overflowed
254   if (_young_gen_is_full) {
255     PSScavenge::set_survivor_overflow(true);
256   }
257 }
258 
259 template <class T>
260 void PSPromotionManager::process_array_chunk_work(oop obj, int start, int end) {
261   assert(start <= end, "invariant");
262   T* const base      = (T*)objArrayOop(obj)->base();
263   T* p               = base + start;
264   T* const chunk_end = base + end;
265   while (p < chunk_end) {
266     claim_or_forward_depth(p);
267     ++p;
268   }
269 }
270 
271 void PSPromotionManager::process_array_chunk(PartialArrayState* state, bool stolen) {
272   // Access before release by claim().
273   oop new_obj = state->destination();
274   PartialArraySplitter::Claim claim =
275     _partial_array_splitter.claim(state, &_claimed_stack_depth, stolen);
276   int start = checked_cast<int>(claim._start);
277   int end = checked_cast<int>(claim._end);
278   if (UseCompressedOops) {
279     process_array_chunk_work<narrowOop>(new_obj, start, end);
280   } else {
281     process_array_chunk_work<oop>(new_obj, start, end);
282   }
283 }
284 
285 void PSPromotionManager::push_objArray(oop old_obj, oop new_obj) {
286   assert(old_obj->is_forwarded(), "precondition");
287   assert(old_obj->forwardee() == new_obj, "precondition");
288   assert(new_obj->is_objArray(), "precondition");
289 
290   objArrayOop to_array = objArrayOop(new_obj);
291   size_t array_length = to_array->length();
292   size_t initial_chunk_size =
293     // The source array is unused when processing states.
294     _partial_array_splitter.start(&_claimed_stack_depth, nullptr, to_array, array_length);
295   int end = checked_cast<int>(initial_chunk_size);
296   if (UseCompressedOops) {
297     process_array_chunk_work<narrowOop>(to_array, 0, end);
298   } else {
299     process_array_chunk_work<oop>(to_array, 0, end);
300   }
301 }
302 
303 oop PSPromotionManager::oop_promotion_failed(oop obj, markWord obj_mark) {
304   assert(_old_gen_is_full || PromotionFailureALot, "Sanity");
305 
306   // Attempt to CAS in the header.
307   // This tests if the header is still the same as when
308   // this started.  If it is the same (i.e., no forwarding
309   // pointer has been installed), then this thread owns
310   // it.
311   if (obj->forward_to_self_atomic(obj_mark) == nullptr) {
312     // We won any races, we "own" this object.
313     assert(obj == obj->forwardee(), "Sanity");
314 
315     _promotion_failed_info.register_copy_failure(obj->size());
316 
317     ContinuationGCSupport::transform_stack_chunk(obj);
318 
319     push_contents(obj);
320 
321     // Save the markWord of promotion-failed objs in _preserved_marks for later
322     // restoration. This way we don't have to walk the young-gen to locate
323     // these promotion-failed objs.
324     _preserved_marks->push_always(obj, obj_mark);
325   }  else {
326     // We lost, someone else "owns" this object
327     guarantee(obj->is_forwarded(), "Object must be forwarded if the cas failed.");
328 
329     // No unallocation to worry about.
330     obj = obj->forwardee();
331   }
332 
333   return obj;
334 }