1 /*
  2  * Copyright (c) 2002, 2022, 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 #ifndef SHARE_GC_PARALLEL_PSPROMOTIONMANAGER_INLINE_HPP
 26 #define SHARE_GC_PARALLEL_PSPROMOTIONMANAGER_INLINE_HPP
 27 
 28 #include "gc/parallel/psPromotionManager.hpp"
 29 
 30 #include "gc/parallel/parallelScavengeHeap.hpp"
 31 #include "gc/parallel/parMarkBitMap.inline.hpp"
 32 #include "gc/parallel/psOldGen.hpp"
 33 #include "gc/parallel/psPromotionLAB.inline.hpp"
 34 #include "gc/parallel/psScavenge.inline.hpp"
 35 #include "gc/parallel/psStringDedup.hpp"
 36 #include "gc/shared/continuationGCSupport.inline.hpp"
 37 #include "gc/shared/taskqueue.inline.hpp"
 38 #include "gc/shared/tlab_globals.hpp"
 39 #include "logging/log.hpp"
 40 #include "memory/iterator.inline.hpp"
 41 #include "oops/access.inline.hpp"
 42 #include "oops/oop.inline.hpp"
 43 #include "runtime/orderAccess.hpp"
 44 #include "runtime/prefetch.inline.hpp"
 45 #include "utilities/copy.hpp"
 46 
 47 inline PSPromotionManager* PSPromotionManager::manager_array(uint index) {
 48   assert(_manager_array != NULL, "access of NULL manager_array");
 49   assert(index < ParallelGCThreads, "out of range manager_array access");
 50   return &_manager_array[index];
 51 }
 52 
 53 inline void PSPromotionManager::push_depth(ScannerTask task) {
 54   claimed_stack_depth()->push(task);
 55 }
 56 
 57 template <class T>
 58 inline void PSPromotionManager::claim_or_forward_depth(T* p) {
 59   assert(should_scavenge(p, true), "revisiting object?");
 60   assert(ParallelScavengeHeap::heap()->is_in(p), "pointer outside heap");
 61   oop obj = RawAccess<IS_NOT_NULL>::oop_load(p);
 62   Prefetch::write(obj->mark_addr(), 0);
 63   push_depth(ScannerTask(p));
 64 }
 65 
 66 inline void PSPromotionManager::promotion_trace_event(oop new_obj, oop old_obj, Klass* klass,
 67                                                       size_t obj_size,
 68                                                       uint age, bool tenured,
 69                                                       const PSPromotionLAB* lab) {
 70   // Skip if memory allocation failed
 71   if (new_obj != NULL) {
 72     const ParallelScavengeTracer* gc_tracer = PSScavenge::gc_tracer();
 73 
 74     if (lab != NULL) {
 75       // Promotion of object through newly allocated PLAB
 76       if (gc_tracer->should_report_promotion_in_new_plab_event()) {
 77         size_t obj_bytes = obj_size * HeapWordSize;
 78         size_t lab_size = lab->capacity();
 79         gc_tracer->report_promotion_in_new_plab_event(klass, obj_bytes,
 80                                                       age, tenured, lab_size);
 81       }
 82     } else {
 83       // Promotion of object directly to heap
 84       if (gc_tracer->should_report_promotion_outside_plab_event()) {
 85         size_t obj_bytes = obj_size * HeapWordSize;
 86         gc_tracer->report_promotion_outside_plab_event(klass, obj_bytes,
 87                                                        age, tenured);
 88       }
 89     }
 90   }
 91 }
 92 
 93 class PSPushContentsClosure: public BasicOopIterateClosure {
 94   PSPromotionManager* _pm;
 95  public:
 96   PSPushContentsClosure(PSPromotionManager* pm) : BasicOopIterateClosure(PSScavenge::reference_processor()), _pm(pm) {}
 97 
 98   template <typename T> void do_oop_nv(T* p) {
 99     if (PSScavenge::should_scavenge(p)) {
100       _pm->claim_or_forward_depth(p);
101     }
102   }
103 
104   virtual void do_oop(oop* p)       { do_oop_nv(p); }
105   virtual void do_oop(narrowOop* p) { do_oop_nv(p); }
106 };
107 
108 //
109 // This closure specialization will override the one that is defined in
110 // instanceRefKlass.inline.cpp. It swaps the order of oop_oop_iterate and
111 // oop_oop_iterate_ref_processing. Unfortunately G1 and Parallel behaves
112 // significantly better (especially in the Derby benchmark) using opposite
113 // order of these function calls.
114 //
115 template <>
116 inline void InstanceRefKlass::oop_oop_iterate_reverse<oop, PSPushContentsClosure>(oop obj, PSPushContentsClosure* closure) {
117   oop_oop_iterate_ref_processing<oop>(obj, closure);
118   InstanceKlass::oop_oop_iterate_reverse<oop>(obj, closure);
119 }
120 
121 template <>
122 inline void InstanceRefKlass::oop_oop_iterate_reverse<narrowOop, PSPushContentsClosure>(oop obj, PSPushContentsClosure* closure) {
123   oop_oop_iterate_ref_processing<narrowOop>(obj, closure);
124   InstanceKlass::oop_oop_iterate_reverse<narrowOop>(obj, closure);
125 }
126 
127 inline void PSPromotionManager::push_contents(oop obj) {
128   if (!obj->klass()->is_typeArray_klass()) {
129     PSPushContentsClosure pcc(this);
130     obj->oop_iterate_backwards(&pcc);
131   }
132 }
133 
134 template<bool promote_immediately>
135 inline oop PSPromotionManager::copy_to_survivor_space(oop o) {
136   assert(should_scavenge(&o), "Sanity");
137 
138   // NOTE! We must be very careful with any methods that access the mark
139   // in o. There may be multiple threads racing on it, and it may be forwarded
140   // at any time.
141   markWord m = o->mark();
142   if (!m.is_marked()) {
143     return copy_unmarked_to_survivor_space<promote_immediately>(o, m);
144   } else {
145     // Ensure any loads from the forwardee follow all changes that precede
146     // the release-cmpxchg that performed the forwarding, possibly in some
147     // other thread.
148     OrderAccess::acquire();
149     // Return the already installed forwardee.
150     return o->forwardee(m);
151   }
152 }
153 
154 //
155 // This method is pretty bulky. It would be nice to split it up
156 // into smaller submethods, but we need to be careful not to hurt
157 // performance.
158 //
159 template<bool promote_immediately>
160 inline oop PSPromotionManager::copy_unmarked_to_survivor_space(oop o,
161                                                                markWord test_mark) {
162   assert(should_scavenge(&o), "Sanity");
163 
164   oop new_obj = NULL;
165   bool new_obj_is_tenured = false;
166 #ifdef _LP64
167   Klass* klass = test_mark.safe_klass();
168 #else
169   Klass* klass = o->klass();
170 #endif
171   size_t new_obj_size = o->size_given_klass(klass);
172 
173   // Find the objects age, MT safe.
174   uint age = (test_mark.has_displaced_mark_helper() /* o->has_displaced_mark() */) ?
175       test_mark.displaced_mark_helper().age() : test_mark.age();
176 
177   if (!promote_immediately) {
178     // Try allocating obj in to-space (unless too old)
179     if (age < PSScavenge::tenuring_threshold()) {
180       new_obj = cast_to_oop(_young_lab.allocate(new_obj_size));
181       if (new_obj == NULL && !_young_gen_is_full) {
182         // Do we allocate directly, or flush and refill?
183         if (new_obj_size > (YoungPLABSize / 2)) {
184           // Allocate this object directly
185           new_obj = cast_to_oop(young_space()->cas_allocate(new_obj_size));
186           promotion_trace_event(new_obj, o, klass, new_obj_size, age, false, NULL);
187         } else {
188           // Flush and fill
189           _young_lab.flush();
190 
191           HeapWord* lab_base = young_space()->cas_allocate(YoungPLABSize);
192           if (lab_base != NULL) {
193             _young_lab.initialize(MemRegion(lab_base, YoungPLABSize));
194             // Try the young lab allocation again.
195             new_obj = cast_to_oop(_young_lab.allocate(new_obj_size));
196             promotion_trace_event(new_obj, o, klass, new_obj_size, age, false, &_young_lab);
197           } else {
198             _young_gen_is_full = true;
199           }
200         }
201       }
202     }
203   }
204 
205   // Otherwise try allocating obj tenured
206   if (new_obj == NULL) {
207 #ifndef PRODUCT
208     if (ParallelScavengeHeap::heap()->promotion_should_fail()) {
209       return oop_promotion_failed(o, test_mark);
210     }
211 #endif  // #ifndef PRODUCT
212 
213     new_obj = cast_to_oop(_old_lab.allocate(new_obj_size));
214     new_obj_is_tenured = true;
215 
216     if (new_obj == NULL) {
217       if (!_old_gen_is_full) {
218         // Do we allocate directly, or flush and refill?
219         if (new_obj_size > (OldPLABSize / 2)) {
220           // Allocate this object directly
221           new_obj = cast_to_oop(old_gen()->allocate(new_obj_size));
222           promotion_trace_event(new_obj, o, klass, new_obj_size, age, true, NULL);
223         } else {
224           // Flush and fill
225           _old_lab.flush();
226 
227           HeapWord* lab_base = old_gen()->allocate(OldPLABSize);
228           if(lab_base != NULL) {
229             _old_lab.initialize(MemRegion(lab_base, OldPLABSize));
230             // Try the old lab allocation again.
231             new_obj = cast_to_oop(_old_lab.allocate(new_obj_size));
232             promotion_trace_event(new_obj, o, klass, new_obj_size, age, true, &_old_lab);
233           }
234         }
235       }
236 
237       // This is the promotion failed test, and code handling.
238       // The code belongs here for two reasons. It is slightly
239       // different than the code below, and cannot share the
240       // CAS testing code. Keeping the code here also minimizes
241       // the impact on the common case fast path code.
242 
243       if (new_obj == NULL) {
244         _old_gen_is_full = true;
245         return oop_promotion_failed(o, test_mark);
246       }
247     }
248   }
249 
250   assert(new_obj != NULL, "allocation should have succeeded");
251 
252   // Copy obj
253   Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(o), cast_from_oop<HeapWord*>(new_obj), new_obj_size);
254 
255   if (!new_obj->mark().is_marked()) {
256     // Parallel GC claims with a release - so other threads might access this object
257     // after claiming and they should see the "completed" object.
258     ContinuationGCSupport::transform_stack_chunk(new_obj);
259   }
260 
261   // Now we have to CAS in the header.
262   // Make copy visible to threads reading the forwardee.
263   oop forwardee = o->forward_to_atomic(new_obj, test_mark, memory_order_release);
264   if (forwardee == NULL) {  // forwardee is NULL when forwarding is successful
265     // We won any races, we "own" this object.
266     assert(new_obj == o->forwardee(), "Sanity");
267 
268     // Increment age if obj still in new generation. Now that
269     // we're dealing with a markWord that cannot change, it is
270     // okay to use the non mt safe oop methods.
271     if (!new_obj_is_tenured) {
272       new_obj->incr_age();
273       assert(young_space()->contains(new_obj), "Attempt to push non-promoted obj");
274     }
275 
276     // Do the size comparison first with new_obj_size, which we
277     // already have. Hopefully, only a few objects are larger than
278     // _min_array_size_for_chunking, and most of them will be arrays.
279     // So, the is->objArray() test would be very infrequent.
280     if (new_obj_size > _min_array_size_for_chunking &&
281         new_obj->is_objArray() &&
282         PSChunkLargeArrays) {
283       // we'll chunk it
284       push_depth(ScannerTask(PartialArrayScanTask(o)));
285       TASKQUEUE_STATS_ONLY(++_arrays_chunked; ++_array_chunk_pushes);
286     } else {
287       // we'll just push its contents
288       push_contents(new_obj);
289 
290       if (StringDedup::is_enabled() &&
291           java_lang_String::is_instance(new_obj) &&
292           psStringDedup::is_candidate_from_evacuation(new_obj, new_obj_is_tenured)) {
293         _string_dedup_requests.add(o);
294       }
295     }
296     return new_obj;
297   } else {
298     // We lost, someone else "owns" this object.
299     // Ensure loads from the forwardee follow all changes that preceded the
300     // release-cmpxchg that performed the forwarding in another thread.
301     OrderAccess::acquire();
302 
303     assert(o->is_forwarded(), "Object must be forwarded if the cas failed.");
304     assert(o->forwardee() == forwardee, "invariant");
305 
306     if (new_obj_is_tenured) {
307       _old_lab.unallocate_object(cast_from_oop<HeapWord*>(new_obj), new_obj_size);
308     } else {
309       _young_lab.unallocate_object(cast_from_oop<HeapWord*>(new_obj), new_obj_size);
310     }
311     return forwardee;
312   }
313 }
314 
315 // Attempt to "claim" oop at p via CAS, push the new obj if successful
316 template <bool promote_immediately, class T>
317 inline void PSPromotionManager::copy_and_push_safe_barrier(T* p) {
318   assert(ParallelScavengeHeap::heap()->is_in_reserved(p), "precondition");
319   assert(should_scavenge(p, true), "revisiting object?");
320 
321   oop o = RawAccess<IS_NOT_NULL>::oop_load(p);
322   oop new_obj = copy_to_survivor_space<promote_immediately>(o);
323   RawAccess<IS_NOT_NULL>::oop_store(p, new_obj);
324 
325   if (!PSScavenge::is_obj_in_young((HeapWord*)p) &&
326        PSScavenge::is_obj_in_young(new_obj)) {
327     PSScavenge::card_table()->inline_write_ref_field_gc(p, new_obj);
328   }
329 }
330 
331 inline void PSPromotionManager::process_popped_location_depth(ScannerTask task) {
332   if (task.is_partial_array_task()) {
333     assert(PSChunkLargeArrays, "invariant");
334     process_array_chunk(task.to_partial_array_task());
335   } else {
336     if (task.is_narrow_oop_ptr()) {
337       assert(UseCompressedOops, "Error");
338       copy_and_push_safe_barrier</*promote_immediately=*/false>(task.to_narrow_oop_ptr());
339     } else {
340       copy_and_push_safe_barrier</*promote_immediately=*/false>(task.to_oop_ptr());
341     }
342   }
343 }
344 
345 inline bool PSPromotionManager::steal_depth(int queue_num, ScannerTask& t) {
346   return stack_array_depth()->steal(queue_num, t);
347 }
348 
349 #if TASKQUEUE_STATS
350 void PSPromotionManager::record_steal(ScannerTask task) {
351   if (task.is_partial_array_task()) {
352     ++_array_chunk_steals;
353   }
354 }
355 #endif // TASKQUEUE_STATS
356 
357 #endif // SHARE_GC_PARALLEL_PSPROMOTIONMANAGER_INLINE_HPP