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