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     } else {
183       ShenandoahNoOpClosure oops;
184       StackWatermarkSet::finish_processing(JavaThread::cast(thread), &oops, StackWatermarkKind::gc);
185     }
186 
187     _heap->flush_region_pin_cache(JavaThread::cast(thread));
188   }
189 }
190 
191 void ShenandoahBarrierSet::keepalive_barrier_slow(oop obj, Filter filter) {
192   if (!ShenandoahSATBBarrier) {
193     return;
194   }
195   assert(obj != nullptr, "Filtered by caller");
196   assert(_heap->is_concurrent_mark_in_progress(), "Filtered by caller");
197 
198   // Filter marked objects before hitting the SATB queues. The same predicate would
199   // be used by SATBMQ::filter to eliminate already marked objects downstream, but
200   // filtering here helps to avoid wasteful SATB queueing work to begin with.
201   if (((filter & FILTER_MARKED) != 0) && !_heap->requires_marking(obj)) {
202     return;
203   }
204 
205   shenandoah_assert_correct(nullptr, obj);
206   assert(_satb_mark_queue_set.is_active(), "only get here when SATB active");
207 
208   SATBMarkQueue& queue = ShenandoahThreadLocalData::satb_mark_queue(Thread::current());
209   _satb_mark_queue_set.enqueue_known_active(queue, obj);
210 }
211 
212 template <typename T>
213 oop ShenandoahBarrierSet::load_reference_barrier_slow(oop obj, T* load_addr) {
214   if (!ShenandoahLoadRefBarrier) {
215     return obj;
216   }
217   assert(_heap->has_forwarded_objects(), "Filtered by caller");
218   assert(_heap->in_collection_set(obj), "Filtered by caller");
219   oop fwd = ShenandoahForwarding::get_forwardee(obj);
220   if (obj == fwd && _heap->is_evacuation_in_progress()) {
221     Thread* t = Thread::current();
222     fwd = _heap->evacuate_object(obj, t);
223   }
224   if (load_addr != nullptr && fwd != obj) {
225     // Since we are here and we know the load address, update the reference.
226     ShenandoahHeap::atomic_update_oop(fwd, load_addr, obj);
227   }
228   return fwd;
229 }
230 
231 template oop ShenandoahBarrierSet::load_reference_barrier_slow(oop obj, oop* load_addr);
232 template oop ShenandoahBarrierSet::load_reference_barrier_slow(oop obj, narrowOop* load_addr);
233 
234 void ShenandoahBarrierSet::card_barrier_array_slow(HeapWord* start, size_t count) {
235   assert(ShenandoahCardBarrier, "Filtered by caller");
236 
237   HeapWord* end = (HeapWord*)((char*) start + (count * heapOopSize));
238   // In the case of compressed oops, start and end may potentially be misaligned;
239   // so we need to conservatively align the first downward (this is not
240   // strictly necessary for current uses, but a case of good hygiene and,
241   // if you will, aesthetics) and the second upward (this is essential for
242   // current uses) to a HeapWord boundary, so we mark all cards overlapping
243   // this write.
244   HeapWord* aligned_start = align_down(start, HeapWordSize);
245   HeapWord* aligned_end   = align_up  (end,   HeapWordSize);
246   // If compressed oops were not being used, these should already be aligned
247   assert(UseCompressedOops || (aligned_start == start && aligned_end == end),
248          "Expected heap word alignment of start and end");
249   _heap->old_generation()->card_scan()->mark_range_as_dirty(aligned_start, (aligned_end - aligned_start));
250 }
251 
252 // Clone barrier support
253 template <bool EVAC>
254 class ShenandoahUpdateEvacForCloneOopClosure : public BasicOopIterateClosure {
255 private:
256   ShenandoahHeap* const _heap;
257   const ShenandoahCollectionSet* const _cset;
258   Thread* const _thread;
259 
260   template <typename T>
261   inline void do_oop_work(T* p) {
262     T o = RawAccess<>::oop_load(p);
263     if (!CompressedOops::is_null(o)) {
264       oop obj = CompressedOops::decode_not_null(o);
265       if (_cset->is_in(obj)) {
266         oop fwd = ShenandoahForwarding::get_forwardee(obj);
267         if (EVAC && obj == fwd) {
268           fwd = _heap->evacuate_object(obj, _thread);
269         }
270         shenandoah_assert_forwarded_except(p, obj, _heap->cancelled_gc());
271         ShenandoahHeap::atomic_update_oop(fwd, p, o);
272         obj = fwd;
273       }
274     }
275   }
276 
277 public:
278   ShenandoahUpdateEvacForCloneOopClosure() :
279           _heap(ShenandoahHeap::heap()),
280           _cset(_heap->collection_set()),
281           _thread(Thread::current()) {}
282 
283   virtual void do_oop(oop* p)       { do_oop_work(p); }
284   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
285 };
286 
287 void ShenandoahBarrierSet::clone_evacuation(oop obj) {
288   if (!ShenandoahCloneBarrier) {
289     return;
290   }
291   if (!need_bulk_update(cast_from_oop<HeapWord*>(obj))) {
292     return;
293   }
294 
295   ShenandoahUpdateEvacForCloneOopClosure<true> cl;
296   obj->oop_iterate(&cl);
297 }
298 
299 void ShenandoahBarrierSet::clone_update(oop obj) {
300   if (!ShenandoahCloneBarrier) {
301     return;
302   }
303   if (!need_bulk_update(cast_from_oop<HeapWord*>(obj))) {
304     return;
305   }
306 
307   ShenandoahUpdateEvacForCloneOopClosure<false> cl;
308   obj->oop_iterate(&cl);
309 }
310 
311 template <bool IS_GENERATIONAL, typename T>
312 bool ShenandoahBarrierSet::is_above_tams(const ShenandoahMarkingContext* ctx, T* dst) const {
313   // TAMS for an old region is unreliable during a young-only mark, so overwritten pointers in old dst arrays must
314   // be enqueued to preserve old->young referents copied in and overwritten after init mark. See JDK-8373116.
315   return ctx->allocated_after_mark_start(reinterpret_cast<HeapWord*>(dst))
316          && !(IS_GENERATIONAL
317               && _heap->heap_region_containing(dst)->is_old()
318               && _heap->is_concurrent_young_mark_in_progress());
319 }
320 
321 inline bool ShenandoahBarrierSet::need_bulk_update(HeapWord* ary) const {
322   return ary < _heap->heap_region_containing(ary)->get_update_watermark();
323 }
324 
325 template <bool IS_GENERATIONAL, typename T>
326 void ShenandoahBarrierSet::arraycopy_marking(T* dst, size_t count) {
327   assert(_heap->is_concurrent_mark_in_progress(), "only during marking");
328   if (!ShenandoahSATBBarrier) {
329     return;
330   }
331 
332   const ShenandoahMarkingContext* ctx = _heap->marking_context();
333   // Everything allocated above TAMS is alive and doesn't need the barrier to keep it that way
334   if (is_above_tams<IS_GENERATIONAL>(ctx, dst)) {
335     return;
336   }
337 
338   assert(!_heap->has_forwarded_objects() || _heap->is_concurrent_old_mark_in_progress(), "Forwarded object status is sane");
339   Thread* thread = Thread::current();
340   SATBMarkQueue& queue = ShenandoahThreadLocalData::satb_mark_queue(thread);
341   T* end = dst + count;
342   for (T* elem_ptr = dst; elem_ptr < end; ++elem_ptr) {
343     T o = RawAccess<>::oop_load(elem_ptr);
344     if (!CompressedOops::is_null(o)) {
345       oop obj = CompressedOops::decode_not_null(o);
346       if (!ctx->is_marked_strong(obj)) {
347         _satb_mark_queue_set.enqueue_known_active(queue, obj);
348       }
349     }
350   }
351 }
352 
353 template void ShenandoahBarrierSet::arraycopy_marking<false, oop>(oop* dst, size_t count);
354 template void ShenandoahBarrierSet::arraycopy_marking<false, narrowOop>(narrowOop* dst, size_t count);
355 template void ShenandoahBarrierSet::arraycopy_marking<true, oop>(oop* dst, size_t count);
356 template void ShenandoahBarrierSet::arraycopy_marking<true, narrowOop>(narrowOop* dst, size_t count);
357 
358 template <typename T>
359 void ShenandoahBarrierSet::arraycopy_evacuation(T* src, size_t count) {
360   assert(_heap->is_evacuation_in_progress(), "only during evacuation");
361   if (!need_bulk_update(reinterpret_cast<HeapWord*>(src))) {
362     return;
363   }
364 
365   assert(_heap->has_forwarded_objects(), "Forwarded object status is sane");
366   Thread* thread = Thread::current();
367   const ShenandoahCollectionSet* const cset = _heap->collection_set();
368   T* end = src + count;
369   for (T* elem_ptr = src; elem_ptr < end; ++elem_ptr) {
370     T o = RawAccess<>::oop_load(elem_ptr);
371     if (!CompressedOops::is_null(o)) {
372       oop obj = CompressedOops::decode_not_null(o);
373       if (cset->is_in(obj)) {
374         oop fwd = ShenandoahForwarding::get_forwardee(obj);
375         if (obj == fwd) {
376           fwd = _heap->evacuate_object(obj, thread);
377         }
378         shenandoah_assert_forwarded_except(elem_ptr, obj, _heap->cancelled_gc());
379         ShenandoahHeap::atomic_update_oop(fwd, elem_ptr, o);
380       }
381     }
382   }
383 }
384 
385 template void ShenandoahBarrierSet::arraycopy_evacuation<oop>(oop* src, size_t count);
386 template void ShenandoahBarrierSet::arraycopy_evacuation<narrowOop>(narrowOop* src, size_t count);
387 
388 template <typename T>
389 void ShenandoahBarrierSet::arraycopy_update(T* src, size_t count) {
390   assert(_heap->is_update_refs_in_progress(), "only during update-refs");
391   if (!need_bulk_update(reinterpret_cast<HeapWord*>(src))) {
392     return;
393   }
394 
395   assert(_heap->has_forwarded_objects(), "Forwarded object status is sane");
396   const ShenandoahCollectionSet* const cset = _heap->collection_set();
397   T* end = src + count;
398   for (T* elem_ptr = src; elem_ptr < end; ++elem_ptr) {
399     T o = RawAccess<>::oop_load(elem_ptr);
400     if (!CompressedOops::is_null(o)) {
401       oop obj = CompressedOops::decode_not_null(o);
402       if (cset->is_in(obj)) {
403         oop fwd = ShenandoahForwarding::get_forwardee(obj);
404         shenandoah_assert_forwarded_except(elem_ptr, obj, _heap->cancelled_gc());
405         ShenandoahHeap::atomic_update_oop(fwd, elem_ptr, o);
406       }
407     }
408   }
409 }
410 
411 template void ShenandoahBarrierSet::arraycopy_update<oop>(oop* src, size_t count);
412 template void ShenandoahBarrierSet::arraycopy_update<narrowOop>(narrowOop* src, size_t count);