1 /*
  2  * Copyright (c) 2013, 2022, Red Hat, Inc. All rights reserved.
  3  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
  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 "gc/shared/barrierSetNMethod.hpp"
 27 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
 28 #include "gc/shenandoah/shenandoahBarrierSetNMethod.hpp"
 29 #include "gc/shenandoah/shenandoahBarrierSetStackChunk.hpp"
 30 #include "gc/shenandoah/shenandoahCardTable.hpp"
 31 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
 32 #include "gc/shenandoah/shenandoahCollectionSet.inline.hpp"
 33 #include "gc/shenandoah/shenandoahForwarding.inline.hpp"
 34 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 35 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
 36 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp"
 37 #include "gc/shenandoah/shenandoahStackWatermark.hpp"
 38 #include "memory/iterator.inline.hpp"
 39 #include "oops/compressedOops.inline.hpp"
 40 #ifdef COMPILER1
 41 #include "gc/shenandoah/c1/shenandoahBarrierSetC1.hpp"
 42 #endif
 43 #ifdef COMPILER2
 44 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
 45 #endif
 46 
 47 class ShenandoahBarrierSetC1;
 48 class ShenandoahBarrierSetC2;
 49 
 50 ShenandoahBarrierSet::ShenandoahBarrierSet(ShenandoahHeap* heap, MemRegion heap_region) :
 51   BarrierSet(make_barrier_set_assembler<ShenandoahBarrierSetAssembler>(),
 52              make_barrier_set_c1<ShenandoahBarrierSetC1>(),
 53              make_barrier_set_c2<ShenandoahBarrierSetC2>(),
 54              new ShenandoahBarrierSetNMethod(heap),
 55              new ShenandoahBarrierSetStackChunk(),
 56              BarrierSet::FakeRtti(BarrierSet::ShenandoahBarrierSet)),
 57   _heap(heap),
 58   _card_table(nullptr),
 59   _satb_mark_queue_buffer_allocator("SATB Buffer Allocator", ShenandoahSATBBufferSize),
 60   _satb_mark_queue_set(&_satb_mark_queue_buffer_allocator)
 61 {
 62   if (ShenandoahCardBarrier) {
 63     _card_table = new ShenandoahCardTable(heap_region);
 64     _card_table->initialize();
 65   }
 66 }
 67 
 68 ShenandoahBarrierSetAssembler* ShenandoahBarrierSet::assembler() {
 69   BarrierSetAssembler* const bsa = BarrierSet::barrier_set()->barrier_set_assembler();
 70   return reinterpret_cast<ShenandoahBarrierSetAssembler*>(bsa);
 71 }
 72 
 73 void ShenandoahBarrierSet::print_on(outputStream* st) const {
 74   st->print("ShenandoahBarrierSet");
 75 }
 76 
 77 bool ShenandoahBarrierSet::need_load_reference_barrier(DecoratorSet decorators, BasicType type) {
 78   if (!ShenandoahLoadRefBarrier) return false;
 79   return is_reference_type(type);
 80 }
 81 
 82 bool ShenandoahBarrierSet::need_keep_alive_barrier(DecoratorSet decorators, BasicType type) {
 83   if (!ShenandoahSATBBarrier) return false;
 84   if (!is_reference_type(type)) return false;
 85   bool keep_alive = (decorators & AS_NO_KEEPALIVE) == 0;
 86   bool unknown = (decorators & ON_UNKNOWN_OOP_REF) != 0;
 87   bool on_weak_ref = (decorators & (ON_WEAK_OOP_REF | ON_PHANTOM_OOP_REF)) != 0;
 88   return (on_weak_ref || unknown) && keep_alive;
 89 }
 90 
 91 bool ShenandoahBarrierSet::need_satb_barrier(DecoratorSet decorators, BasicType type) {
 92   if (!ShenandoahSATBBarrier) return false;
 93   if (!is_reference_type(type)) return false;
 94   bool as_normal = (decorators & AS_NORMAL) != 0;
 95   bool dest_uninitialized = (decorators & IS_DEST_UNINITIALIZED) != 0;
 96   return as_normal && !dest_uninitialized;
 97 }
 98 
 99 bool ShenandoahBarrierSet::need_card_barrier(DecoratorSet decorators, BasicType type) {
100   if (!ShenandoahCardBarrier) return false;
101   if (!is_reference_type(type)) return false;
102   return is_heap_access(decorators);
103 }
104 
105 void ShenandoahBarrierSet::on_slowpath_allocation_exit(JavaThread* thread, oop new_obj) {
106 #ifdef COMPILER2
107   if (ReduceInitialCardMarks && ShenandoahCardBarrier && !ShenandoahHeap::heap()->is_in_young(new_obj)) {
108     log_debug(gc)("Newly allocated object (" PTR_FORMAT ") is not in the young generation", p2i(new_obj));
109     // This can happen when an object is newly allocated, but we come to a safepoint before returning
110     // the object. If the safepoint runs a degenerated cycle that is upgraded to a full GC, this object
111     // will have survived two GC cycles. If the tenuring age is very low (1), this object may be promoted.
112     // In this case, we have an allocated object, but it has received no stores yet. If card marking barriers
113     // have been elided, we could end up with an object in old holding pointers to young that won't be in
114     // the remembered set. The solution here is conservative, but this problem should be rare, and it will
115     // correct itself on subsequent cycles when the remembered set is updated.
116     ShenandoahGenerationalHeap::heap()->old_generation()->card_scan()->mark_range_as_dirty(
117       cast_from_oop<HeapWord*>(new_obj), new_obj->size()
118     );
119   }
120 #endif // COMPILER2
121 }
122 
123 void ShenandoahBarrierSet::on_thread_create(Thread* thread) {
124   // Create thread local data
125   ShenandoahThreadLocalData::create(thread);
126 }
127 
128 void ShenandoahBarrierSet::on_thread_destroy(Thread* thread) {
129   // Destroy thread local data
130   ShenandoahThreadLocalData::destroy(thread);
131 }
132 
133 void ShenandoahBarrierSet::on_thread_attach(Thread *thread) {
134   assert(!thread->is_Java_thread() || !SafepointSynchronize::is_at_safepoint(),
135          "We should not be at a safepoint");
136   SATBMarkQueue& queue = ShenandoahThreadLocalData::satb_mark_queue(thread);
137   assert(!queue.is_active(), "SATB queue should not be active");
138   assert(queue.buffer() == nullptr, "SATB queue should not have a buffer");
139   assert(queue.index() == 0, "SATB queue index should be zero");
140   queue.set_active(_satb_mark_queue_set.is_active());
141 
142   if (ShenandoahCardBarrier) {
143     // Every thread always have a pointer to the _current_ _write_ version of the card table.
144     // The JIT'ed code will use this address (+card entry offset) to mark the card as dirty.
145     ShenandoahThreadLocalData::set_card_table(thread, _card_table->write_byte_map_base());
146   }
147   ShenandoahThreadLocalData::set_gc_state(thread, _heap->gc_state());
148 
149   if (thread->is_Java_thread()) {
150     ShenandoahThreadLocalData::initialize_gclab(thread);
151 
152     BarrierSetNMethod* bs_nm = barrier_set_nmethod();
153     thread->set_nmethod_disarmed_guard_value(bs_nm->disarmed_guard_value());
154 
155     JavaThread* const jt = JavaThread::cast(thread);
156     StackWatermark* const watermark = new ShenandoahStackWatermark(jt);
157     StackWatermarkSet::add_watermark(jt, watermark);
158   }
159 }
160 
161 void ShenandoahBarrierSet::on_thread_detach(Thread *thread) {
162   SATBMarkQueue& queue = ShenandoahThreadLocalData::satb_mark_queue(thread);
163   _satb_mark_queue_set.flush_queue(queue);
164   if (thread->is_Java_thread()) {
165     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
166     if (gclab != nullptr) {
167       gclab->retire();
168     }
169 
170     ShenandoahPLAB* shenandoah_plab = ShenandoahThreadLocalData::shenandoah_plab(thread);
171     if (shenandoah_plab != nullptr) {
172       shenandoah_plab->retire();
173     }
174 
175     // SATB protocol requires to keep alive reachable oops from roots at the beginning of GC
176     if (_heap->is_concurrent_mark_in_progress()) {
177       ShenandoahKeepAliveClosure oops;
178       StackWatermarkSet::finish_processing(JavaThread::cast(thread), &oops, StackWatermarkKind::gc);
179     } else if (_heap->is_concurrent_weak_root_in_progress() && _heap->is_evacuation_in_progress()) {
180       ShenandoahContextEvacuateUpdateRootsClosure oops;
181       StackWatermarkSet::finish_processing(JavaThread::cast(thread), &oops, StackWatermarkKind::gc);
182     }
183 
184     _heap->flush_region_pin_cache(JavaThread::cast(thread));
185   }
186 }
187 
188 void ShenandoahBarrierSet::keepalive_barrier_slow(oop obj, Filter filter) {
189   if (!ShenandoahSATBBarrier) {
190     return;
191   }
192   assert(obj != nullptr, "Filtered by caller");
193   assert(_heap->is_concurrent_mark_in_progress(), "Filtered by caller");
194 
195   // Filter marked objects before hitting the SATB queues. The same predicate would
196   // be used by SATBMQ::filter to eliminate already marked objects downstream, but
197   // filtering here helps to avoid wasteful SATB queueing work to begin with.
198   if (((filter & FILTER_MARKED) != 0) && !_heap->requires_marking(obj)) {
199     return;
200   }
201 
202   shenandoah_assert_correct(nullptr, obj);
203   assert(_satb_mark_queue_set.is_active(), "only get here when SATB active");
204 
205   SATBMarkQueue& queue = ShenandoahThreadLocalData::satb_mark_queue(Thread::current());
206   _satb_mark_queue_set.enqueue_known_active(queue, obj);
207 }
208 
209 template <typename T>
210 oop ShenandoahBarrierSet::load_reference_barrier_slow(oop obj, T* load_addr) {
211   if (!ShenandoahLoadRefBarrier) {
212     return obj;
213   }
214   assert(_heap->has_forwarded_objects(), "Filtered by caller");
215   assert(_heap->in_collection_set(obj), "Filtered by caller");
216   oop fwd = ShenandoahForwarding::get_forwardee(obj);
217   if (obj == fwd && _heap->is_evacuation_in_progress()) {
218     Thread* t = Thread::current();
219     fwd = _heap->evacuate_object(obj, t);
220   }
221   if (load_addr != nullptr && fwd != obj) {
222     // Since we are here and we know the load address, update the reference.
223     ShenandoahHeap::atomic_update_oop(fwd, load_addr, obj);
224   }
225   return fwd;
226 }
227 
228 template oop ShenandoahBarrierSet::load_reference_barrier_slow(oop obj, oop* load_addr);
229 template oop ShenandoahBarrierSet::load_reference_barrier_slow(oop obj, narrowOop* load_addr);
230 
231 void ShenandoahBarrierSet::card_barrier_array_slow(HeapWord* start, size_t count) {
232   assert(ShenandoahCardBarrier, "Filtered by caller");
233 
234   HeapWord* end = (HeapWord*)((char*) start + (count * heapOopSize));
235   // In the case of compressed oops, start and end may potentially be misaligned;
236   // so we need to conservatively align the first downward (this is not
237   // strictly necessary for current uses, but a case of good hygiene and,
238   // if you will, aesthetics) and the second upward (this is essential for
239   // current uses) to a HeapWord boundary, so we mark all cards overlapping
240   // this write.
241   HeapWord* aligned_start = align_down(start, HeapWordSize);
242   HeapWord* aligned_end   = align_up  (end,   HeapWordSize);
243   // If compressed oops were not being used, these should already be aligned
244   assert(UseCompressedOops || (aligned_start == start && aligned_end == end),
245          "Expected heap word alignment of start and end");
246   _heap->old_generation()->card_scan()->mark_range_as_dirty(aligned_start, (aligned_end - aligned_start));
247 }
248 
249 // Clone barrier support
250 template <bool EVAC>
251 class ShenandoahUpdateEvacForCloneOopClosure : public BasicOopIterateClosure {
252 private:
253   ShenandoahHeap* const _heap;
254   const ShenandoahCollectionSet* const _cset;
255   Thread* const _thread;
256 
257   template <typename T>
258   inline void do_oop_work(T* p) {
259     T o = RawAccess<>::oop_load(p);
260     if (!CompressedOops::is_null(o)) {
261       oop obj = CompressedOops::decode_not_null(o);
262       if (_cset->is_in(obj)) {
263         oop fwd = ShenandoahForwarding::get_forwardee(obj);
264         if (EVAC && obj == fwd) {
265           fwd = _heap->evacuate_object(obj, _thread);
266         }
267         shenandoah_assert_forwarded_except(p, obj, _heap->cancelled_gc());
268         ShenandoahHeap::atomic_update_oop(fwd, p, o);
269         obj = fwd;
270       }
271     }
272   }
273 
274 public:
275   ShenandoahUpdateEvacForCloneOopClosure() :
276           _heap(ShenandoahHeap::heap()),
277           _cset(_heap->collection_set()),
278           _thread(Thread::current()) {}
279 
280   virtual void do_oop(oop* p)       { do_oop_work(p); }
281   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
282 };
283 
284 void ShenandoahBarrierSet::clone_evacuation(oop obj) {
285   if (!ShenandoahCloneBarrier) {
286     return;
287   }
288   if (!need_bulk_update(cast_from_oop<HeapWord*>(obj))) {
289     return;
290   }
291 
292   ShenandoahUpdateEvacForCloneOopClosure<true> cl;
293   obj->oop_iterate(&cl);
294 }
295 
296 void ShenandoahBarrierSet::clone_update(oop obj) {
297   if (!ShenandoahCloneBarrier) {
298     return;
299   }
300   if (!need_bulk_update(cast_from_oop<HeapWord*>(obj))) {
301     return;
302   }
303 
304   ShenandoahUpdateEvacForCloneOopClosure<false> cl;
305   obj->oop_iterate(&cl);
306 }
307 
308 template <bool IS_GENERATIONAL, typename T>
309 bool ShenandoahBarrierSet::is_above_tams(const ShenandoahMarkingContext* ctx, T* dst) const {
310   // TAMS for an old region is unreliable during a young-only mark, so overwritten pointers in old dst arrays must
311   // be enqueued to preserve old->young referents copied in and overwritten after init mark. See JDK-8373116.
312   return ctx->allocated_after_mark_start(reinterpret_cast<HeapWord*>(dst))
313          && !(IS_GENERATIONAL
314               && _heap->heap_region_containing(dst)->is_old()
315               && _heap->is_concurrent_young_mark_in_progress());
316 }
317 
318 inline bool ShenandoahBarrierSet::need_bulk_update(HeapWord* ary) const {
319   return ary < _heap->heap_region_containing(ary)->get_update_watermark();
320 }
321 
322 template <bool IS_GENERATIONAL, typename T>
323 void ShenandoahBarrierSet::arraycopy_marking(T* dst, size_t count) {
324   assert(_heap->is_concurrent_mark_in_progress(), "only during marking");
325   if (!ShenandoahSATBBarrier) {
326     return;
327   }
328 
329   const ShenandoahMarkingContext* ctx = _heap->marking_context();
330   // Everything allocated above TAMS is alive and doesn't need the barrier to keep it that way
331   if (is_above_tams<IS_GENERATIONAL>(ctx, dst)) {
332     return;
333   }
334 
335   assert(!_heap->has_forwarded_objects() || _heap->is_concurrent_old_mark_in_progress(), "Forwarded object status is sane");
336   Thread* thread = Thread::current();
337   SATBMarkQueue& queue = ShenandoahThreadLocalData::satb_mark_queue(thread);
338   T* end = dst + count;
339   for (T* elem_ptr = dst; elem_ptr < end; ++elem_ptr) {
340     T o = RawAccess<>::oop_load(elem_ptr);
341     if (!CompressedOops::is_null(o)) {
342       oop obj = CompressedOops::decode_not_null(o);
343       if (!ctx->is_marked_strong(obj)) {
344         _satb_mark_queue_set.enqueue_known_active(queue, obj);
345       }
346     }
347   }
348 }
349 
350 template void ShenandoahBarrierSet::arraycopy_marking<false, oop>(oop* dst, size_t count);
351 template void ShenandoahBarrierSet::arraycopy_marking<false, narrowOop>(narrowOop* dst, size_t count);
352 template void ShenandoahBarrierSet::arraycopy_marking<true, oop>(oop* dst, size_t count);
353 template void ShenandoahBarrierSet::arraycopy_marking<true, narrowOop>(narrowOop* dst, size_t count);
354 
355 template <typename T>
356 void ShenandoahBarrierSet::arraycopy_evacuation(T* src, size_t count) {
357   assert(_heap->is_evacuation_in_progress(), "only during evacuation");
358   if (!need_bulk_update(reinterpret_cast<HeapWord*>(src))) {
359     return;
360   }
361 
362   assert(_heap->has_forwarded_objects(), "Forwarded object status is sane");
363   Thread* thread = Thread::current();
364   const ShenandoahCollectionSet* const cset = _heap->collection_set();
365   T* end = src + count;
366   for (T* elem_ptr = src; elem_ptr < end; ++elem_ptr) {
367     T o = RawAccess<>::oop_load(elem_ptr);
368     if (!CompressedOops::is_null(o)) {
369       oop obj = CompressedOops::decode_not_null(o);
370       if (cset->is_in(obj)) {
371         oop fwd = ShenandoahForwarding::get_forwardee(obj);
372         if (obj == fwd) {
373           fwd = _heap->evacuate_object(obj, thread);
374         }
375         shenandoah_assert_forwarded_except(elem_ptr, obj, _heap->cancelled_gc());
376         ShenandoahHeap::atomic_update_oop(fwd, elem_ptr, o);
377       }
378     }
379   }
380 }
381 
382 template void ShenandoahBarrierSet::arraycopy_evacuation<oop>(oop* src, size_t count);
383 template void ShenandoahBarrierSet::arraycopy_evacuation<narrowOop>(narrowOop* src, size_t count);
384 
385 template <typename T>
386 void ShenandoahBarrierSet::arraycopy_update(T* src, size_t count) {
387   assert(_heap->is_update_refs_in_progress(), "only during update-refs");
388   if (!need_bulk_update(reinterpret_cast<HeapWord*>(src))) {
389     return;
390   }
391 
392   assert(_heap->has_forwarded_objects(), "Forwarded object status is sane");
393   const ShenandoahCollectionSet* const cset = _heap->collection_set();
394   T* end = src + count;
395   for (T* elem_ptr = src; elem_ptr < end; ++elem_ptr) {
396     T o = RawAccess<>::oop_load(elem_ptr);
397     if (!CompressedOops::is_null(o)) {
398       oop obj = CompressedOops::decode_not_null(o);
399       if (cset->is_in(obj)) {
400         oop fwd = ShenandoahForwarding::get_forwardee(obj);
401         shenandoah_assert_forwarded_except(elem_ptr, obj, _heap->cancelled_gc());
402         ShenandoahHeap::atomic_update_oop(fwd, elem_ptr, o);
403       }
404     }
405   }
406 }
407 
408 template void ShenandoahBarrierSet::arraycopy_update<oop>(oop* src, size_t count);
409 template void ShenandoahBarrierSet::arraycopy_update<narrowOop>(narrowOop* src, size_t count);