1 /*
  2  * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2019, 2022, Red Hat, Inc. 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 
 27 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
 28 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
 29 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 30 #include "gc/shenandoah/shenandoahNMethod.inline.hpp"
 31 #include "memory/resourceArea.hpp"
 32 #include "runtime/continuation.hpp"
 33 #include "runtime/safepointVerifiers.hpp"
 34 
 35 ShenandoahNMethod::ShenandoahNMethod(nmethod* nm) :
 36   _nm(nm), _oops(nullptr), _oops_count(0), _barriers(nullptr), _barriers_count(0), _unregistered(false), _lock(), _ic_lock() {
 37   init_from(nm);
 38 }
 39 
 40 ShenandoahNMethod::~ShenandoahNMethod() {
 41   if (_oops != nullptr) {
 42     FREE_C_HEAP_ARRAY(_oops);
 43   }
 44   if (_barriers != nullptr) {
 45     FREE_C_HEAP_ARRAY(_barriers);
 46   }
 47 }
 48 
 49 void ShenandoahNMethod::update() {
 50   init_from(nm());
 51 }
 52 
 53 void ShenandoahNMethod::init_from(nmethod* nm) {
 54   ResourceMark rm;
 55   bool non_immediate_oops = false;
 56   GrowableArray<oop*> oops;
 57   GrowableArray<ShenandoahNMethodBarrier> barriers;
 58 
 59   parse(nm, oops, non_immediate_oops, barriers);
 60 
 61   if (_oops_count != oops.length()) {
 62     _oops_count = oops.length();
 63     if (_oops != nullptr) {
 64       FREE_C_HEAP_ARRAY(_oops);
 65     }
 66     _oops = NEW_C_HEAP_ARRAY(oop*, _oops_count, mtGC);
 67   }
 68   for (int c = 0; c < _oops_count; c++) {
 69     _oops[c] = oops.at(c);
 70   }
 71   assert_same_oops();
 72 
 73   if (_barriers_count != barriers.length()) {
 74     _barriers_count = barriers.length();
 75     if (_barriers != nullptr) {
 76       FREE_C_HEAP_ARRAY(_barriers);
 77     }
 78     _barriers = NEW_C_HEAP_ARRAY(ShenandoahNMethodBarrier, _barriers_count, mtGC);
 79   }
 80   for (int c = 0; c < _barriers_count; c++) {
 81     _barriers[c] = barriers.at(c);
 82   }
 83 
 84   _has_non_immed_oops = non_immediate_oops;
 85 }
 86 
 87 void ShenandoahNMethod::parse(nmethod* nm, GrowableArray<oop*>& oops, bool& has_non_immed_oops, GrowableArray<ShenandoahNMethodBarrier>& barriers) {
 88   has_non_immed_oops = false;
 89   address code_begin = nm->code_begin();
 90   RelocIterator iter(nm);
 91   while (iter.next()) {
 92     switch (iter.type()) {
 93       case relocInfo::oop_type: {
 94         oop_Relocation* r = iter.oop_reloc();
 95         if (!r->oop_is_immediate()) {
 96           // Non-immediate oop found
 97           has_non_immed_oops = true;
 98           break;
 99         }
100 
101         oop value = r->oop_value();
102         if (value != nullptr) {
103           oop* addr = r->oop_addr();
104           shenandoah_assert_correct(addr, value);
105           shenandoah_assert_not_in_cset_except(addr, value, ShenandoahHeap::heap()->cancelled_gc());
106           shenandoah_assert_not_forwarded(addr, value);
107           // Non-null immediate oop found. null oops can safely be
108           // ignored since the method will be re-registered if they
109           // are later patched to be non-null.
110           oops.push(addr);
111         }
112         break;
113       }
114 #ifdef COMPILER2
115       case relocInfo::patchable_barrier_type: {
116         patchable_barrier_Relocation* r = iter.patchable_barrier_reloc();
117 
118         ShenandoahNMethodBarrier b;
119         b._rel_pc = pointer_delta(r->addr(), code_begin, 1);
120         b._rel_target = r->target_offset();
121         b._metadata = r->metadata();
122         barriers.push(b);
123         break;
124       }
125 #endif
126       default:
127         // We do not care about other relocations.
128         break;
129     }
130   }
131 }
132 
133 ShenandoahNMethod* ShenandoahNMethod::for_nmethod(nmethod* nm) {
134   return new ShenandoahNMethod(nm);
135 }
136 
137 void ShenandoahNMethod::heal_nmethod(nmethod* nm) {
138   ShenandoahNMethod* data = gc_data(nm);
139   assert(data != nullptr, "Sanity");
140   assert(data->lock()->owned_by_self(), "Must hold the lock");
141 
142   ShenandoahHeap* const heap = ShenandoahHeap::heap();
143   if ((heap->is_concurrent_weak_root_in_progress() && heap->is_evacuation_in_progress()) ||
144       heap->is_concurrent_strong_root_in_progress()) {
145     heal_nmethod_metadata(data);
146   } else if (heap->is_concurrent_mark_in_progress()) {
147     ShenandoahKeepAliveClosure cl;
148     data->oops_do(&cl);
149   } else {
150     // There is possibility that GC is cancelled when it arrives final mark.
151     // In this case, concurrent root phase is skipped and degenerated GC should be
152     // followed, where nmethods are disarmed.
153   }
154 }
155 
156 bool ShenandoahNMethod::update_barriers(nmethod* nm) {
157   bool changed = false;
158 #ifdef COMPILER2
159   ShenandoahNMethod* data = gc_data(nm);
160   assert(data != nullptr, "Sanity");
161   assert(data->lock()->owned_by_self(), "Must hold the lock");
162 
163   char gc_state = ShenandoahHeap::heap()->gc_state();
164   address code_begin = nm->code_begin();
165   for (int c = 0; c < data->_barriers_count; c++) {
166     address pc = code_begin + data->_barriers[c]._rel_pc;
167     address target = pc + data->_barriers[c]._rel_target;
168     char trigger_state = decode_reloc_gc_state(data->_barriers[c]._metadata);
169     bool inverted = decode_reloc_inverted(data->_barriers[c]._metadata);
170     bool active = ((gc_state & trigger_state) != 0) ^ inverted;
171     if (active) {
172       changed |= ShenandoahBarrierSetAssembler::patch_nop_to_branch(pc, target);
173     } else {
174       changed |= ShenandoahBarrierSetAssembler::patch_branch_to_nop(pc);
175     }
176   }
177 #endif
178   return changed;
179 }
180 
181 #ifdef ASSERT
182 void ShenandoahNMethod::assert_correct() {
183   ShenandoahHeap* heap = ShenandoahHeap::heap();
184   for (int c = 0; c < _oops_count; c++) {
185     oop *loc = _oops[c];
186     assert(_nm->code_contains((address) loc) || _nm->oops_contains(loc), "nmethod should contain the oop*");
187     oop o = RawAccess<>::oop_load(loc);
188     shenandoah_assert_correct_except(loc, o, o == nullptr || heap->is_full_gc_move_in_progress());
189   }
190 
191   oop* const begin = _nm->oops_begin();
192   oop* const end = _nm->oops_end();
193   for (oop* p = begin; p < end; p++) {
194     if (*p != Universe::non_oop_word()) {
195       oop o = RawAccess<>::oop_load(p);
196       shenandoah_assert_correct_except(p, o, o == nullptr || heap->is_full_gc_move_in_progress());
197     }
198   }
199 }
200 
201 class ShenandoahNMethodOopDetector : public OopClosure {
202 private:
203   ResourceMark rm; // For growable array allocation below.
204   GrowableArray<oop*> _oops;
205 
206 public:
207   ShenandoahNMethodOopDetector() : _oops(10) {};
208 
209   void do_oop(oop* o) {
210     _oops.append(o);
211   }
212   void do_oop(narrowOop* o) {
213     fatal("NMethods should not have compressed oops embedded.");
214   }
215 
216   GrowableArray<oop*>* oops() {
217     return &_oops;
218   }
219 };
220 
221 void ShenandoahNMethod::assert_same_oops() {
222   ShenandoahNMethodOopDetector detector;
223   nm()->oops_do(&detector);
224 
225   GrowableArray<oop*>* oops = detector.oops();
226 
227   int count = _oops_count;
228   for (int index = 0; index < _oops_count; index ++) {
229     assert(oops->contains(_oops[index]), "Must contain this oop");
230   }
231 
232   for (oop* p = nm()->oops_begin(); p < nm()->oops_end(); p ++) {
233     if (*p == Universe::non_oop_word()) continue;
234     count++;
235     assert(oops->contains(p), "Must contain this oop");
236   }
237 
238   if (oops->length() < count) {
239     stringStream debug_stream;
240     debug_stream.print_cr("detected locs: %d", oops->length());
241     for (int i = 0; i < oops->length(); i++) {
242       debug_stream.print_cr("-> " PTR_FORMAT, p2i(oops->at(i)));
243     }
244     debug_stream.print_cr("recorded oops: %d", _oops_count);
245     for (int i = 0; i < _oops_count; i++) {
246       debug_stream.print_cr("-> " PTR_FORMAT, p2i(_oops[i]));
247     }
248     GrowableArray<oop*> check;
249     GrowableArray<ShenandoahNMethodBarrier> barriers;
250     bool non_immed;
251     parse(nm(), check, non_immed, barriers);
252     debug_stream.print_cr("check oops: %d", check.length());
253     for (int i = 0; i < check.length(); i++) {
254       debug_stream.print_cr("-> " PTR_FORMAT, p2i(check.at(i)));
255     }
256     fatal("Must match #detected: %d, #recorded: %d, #total: %d, begin: " PTR_FORMAT ", end: " PTR_FORMAT "\n%s",
257           oops->length(), _oops_count, count, p2i(nm()->oops_begin()), p2i(nm()->oops_end()), debug_stream.freeze());
258   }
259 }
260 #endif
261 
262 ShenandoahNMethodTable::ShenandoahNMethodTable() :
263   _heap(ShenandoahHeap::heap()),
264   _index(0),
265   _itr_cnt(0) {
266   _list = new ShenandoahNMethodList(minSize);
267 }
268 
269 ShenandoahNMethodTable::~ShenandoahNMethodTable() {
270   assert(_list != nullptr, "Sanity");
271   _list->release();
272 }
273 
274 void ShenandoahNMethodTable::register_nmethod(nmethod* nm) {
275   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
276   assert(_index >= 0 && _index <= _list->size(), "Sanity");
277 
278   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
279 
280   if (data != nullptr) {
281     assert(contain(nm), "Must have been registered");
282     assert(nm == data->nm(), "Must be same nmethod");
283     // Prevent updating a nmethod while concurrent iteration is in progress.
284     wait_until_concurrent_iteration_done();
285     ShenandoahNMethodLocker data_locker(data->lock());
286     data->update();
287     ShenandoahNMethod::update_barriers(nm);
288   } else {
289     // For a new nmethod, we can safely append it to the list, because
290     // concurrent iteration will not touch it.
291     data = ShenandoahNMethod::for_nmethod(nm);
292     assert(data != nullptr, "Sanity");
293     ShenandoahNMethod::attach_gc_data(nm, data);
294     ShenandoahLocker locker(&_lock);
295     log_register_nmethod(nm);
296     append(data);
297     ShenandoahNMethodLocker data_locker(data->lock());
298     ShenandoahNMethod::update_barriers(nm);
299   }
300   // Disarm new nmethod
301   ShenandoahNMethod::disarm_nmethod(nm);
302 }
303 
304 void ShenandoahNMethodTable::unregister_nmethod(nmethod* nm) {
305   assert_locked_or_safepoint(CodeCache_lock);
306 
307   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
308   assert(data != nullptr, "Sanity");
309   log_unregister_nmethod(nm);
310   ShenandoahLocker locker(&_lock);
311   assert(contain(nm), "Must have been registered");
312 
313   int idx = index_of(nm);
314   assert(idx >= 0 && idx < _index, "Invalid index");
315   ShenandoahNMethod::attach_gc_data(nm, nullptr);
316   remove(idx);
317 }
318 
319 bool ShenandoahNMethodTable::contain(nmethod* nm) const {
320   return index_of(nm) != -1;
321 }
322 
323 ShenandoahNMethod* ShenandoahNMethodTable::at(int index) const {
324   assert(index >= 0 && index < _index, "Out of bound");
325   return _list->at(index);
326 }
327 
328 int ShenandoahNMethodTable::index_of(nmethod* nm) const {
329   for (int index = 0; index < length(); index ++) {
330     if (at(index)->nm() == nm) {
331       return index;
332     }
333   }
334   return -1;
335 }
336 
337 void ShenandoahNMethodTable::remove(int idx) {
338   shenandoah_assert_locked_or_safepoint(CodeCache_lock);
339   assert(_index >= 0 && _index <= _list->size(), "Sanity");
340 
341   assert(idx >= 0 && idx < _index, "Out of bound");
342   ShenandoahNMethod* snm = _list->at(idx);
343   ShenandoahNMethod* tmp = _list->at(_index - 1);
344   _list->set(idx, tmp);
345   _index --;
346 
347   delete snm;
348 }
349 
350 void ShenandoahNMethodTable::wait_until_concurrent_iteration_done() {
351   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
352   while (iteration_in_progress()) {
353     CodeCache_lock->wait_without_safepoint_check();
354   }
355 }
356 
357 void ShenandoahNMethodTable::append(ShenandoahNMethod* snm) {
358   if (is_full()) {
359     int new_size = 2 * _list->size();
360     // Rebuild table and replace current one
361     rebuild(new_size);
362   }
363 
364   _list->set(_index++,  snm);
365   assert(_index >= 0 && _index <= _list->size(), "Sanity");
366 }
367 
368 void ShenandoahNMethodTable::rebuild(int size) {
369   ShenandoahNMethodList* new_list = new ShenandoahNMethodList(size);
370   new_list->transfer(_list, _index);
371 
372   // Release old list
373   _list->release();
374   _list = new_list;
375 }
376 
377 ShenandoahNMethodTableSnapshot* ShenandoahNMethodTable::snapshot_for_iteration() {
378   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
379   _itr_cnt++;
380   return new ShenandoahNMethodTableSnapshot(this);
381 }
382 
383 void ShenandoahNMethodTable::finish_iteration(ShenandoahNMethodTableSnapshot* snapshot) {
384   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
385   assert(iteration_in_progress(), "Why we here?");
386   assert(snapshot != nullptr, "No snapshot");
387   _itr_cnt--;
388 
389   delete snapshot;
390 }
391 
392 void ShenandoahNMethodTable::log_register_nmethod(nmethod* nm) {
393   LogTarget(Debug, gc, nmethod) log;
394   if (!log.is_enabled()) {
395     return;
396   }
397 
398   ResourceMark rm;
399   log.print("Register NMethod: %s.%s [" PTR_FORMAT "] (%s)",
400             nm->method()->method_holder()->external_name(),
401             nm->method()->name()->as_C_string(),
402             p2i(nm),
403             nm->compiler_name());
404 }
405 
406 void ShenandoahNMethodTable::log_unregister_nmethod(nmethod* nm) {
407   LogTarget(Debug, gc, nmethod) log;
408   if (!log.is_enabled()) {
409     return;
410   }
411 
412   ResourceMark rm;
413   log.print("Unregister NMethod: %s.%s [" PTR_FORMAT "]",
414             nm->method()->method_holder()->external_name(),
415             nm->method()->name()->as_C_string(),
416             p2i(nm));
417 }
418 
419 #ifdef ASSERT
420 void ShenandoahNMethodTable::assert_nmethods_correct() {
421   assert_locked_or_safepoint(CodeCache_lock);
422 
423   for (int index = 0; index < length(); index ++) {
424     ShenandoahNMethod* m = _list->at(index);
425     // Concurrent unloading may have dead nmethods to be cleaned by sweeper
426     if (m->is_unregistered()) continue;
427     m->assert_correct();
428   }
429 }
430 #endif
431 
432 
433 ShenandoahNMethodList::ShenandoahNMethodList(int size) :
434   _size(size), _ref_count(1) {
435   _list = NEW_C_HEAP_ARRAY(ShenandoahNMethod*, size, mtGC);
436 }
437 
438 ShenandoahNMethodList::~ShenandoahNMethodList() {
439   assert(_list != nullptr, "Sanity");
440   assert(_ref_count == 0, "Must be");
441   FREE_C_HEAP_ARRAY(_list);
442 }
443 
444 void ShenandoahNMethodList::transfer(ShenandoahNMethodList* const list, int limit) {
445   assert(limit <= size(), "Sanity");
446   ShenandoahNMethod** old_list = list->list();
447   for (int index = 0; index < limit; index++) {
448     _list[index] = old_list[index];
449   }
450 }
451 
452 ShenandoahNMethodList* ShenandoahNMethodList::acquire() {
453   assert_locked_or_safepoint(CodeCache_lock);
454   _ref_count++;
455   return this;
456 }
457 
458 void ShenandoahNMethodList::release() {
459   assert_locked_or_safepoint(CodeCache_lock);
460   _ref_count--;
461   if (_ref_count == 0) {
462     delete this;
463   }
464 }
465 
466 ShenandoahNMethodTableSnapshot::ShenandoahNMethodTableSnapshot(ShenandoahNMethodTable* table) :
467   _heap(ShenandoahHeap::heap()), _list(table->_list->acquire()), _limit(table->_index), _claimed(0) {
468 }
469 
470 ShenandoahNMethodTableSnapshot::~ShenandoahNMethodTableSnapshot() {
471   _list->release();
472 }
473 
474 void ShenandoahNMethodTableSnapshot::parallel_nmethods_do(NMethodClosure *f) {
475   size_t stride = 256; // educated guess
476 
477   ShenandoahNMethod** const list = _list->list();
478 
479   size_t max = (size_t)_limit;
480   while (_claimed.load_relaxed() < max) {
481     size_t cur = _claimed.fetch_then_add(stride, memory_order_relaxed);
482     size_t start = cur;
483     size_t end = MIN2(cur + stride, max);
484     if (start >= max) break;
485 
486     for (size_t idx = start; idx < end; idx++) {
487       ShenandoahNMethod* nmr = list[idx];
488       assert(nmr != nullptr, "Sanity");
489       if (nmr->is_unregistered()) {
490         continue;
491       }
492 
493       nmr->assert_correct();
494       f->do_nmethod(nmr->nm());
495     }
496   }
497 }
498 
499 void ShenandoahNMethodTableSnapshot::concurrent_nmethods_do(NMethodClosure* cl) {
500   size_t stride = 256; // educated guess
501 
502   ShenandoahNMethod** list = _list->list();
503   size_t max = (size_t)_limit;
504   while (_claimed.load_relaxed() < max) {
505     size_t cur = _claimed.fetch_then_add(stride, memory_order_relaxed);
506     size_t start = cur;
507     size_t end = MIN2(cur + stride, max);
508     if (start >= max) break;
509 
510     for (size_t idx = start; idx < end; idx++) {
511       ShenandoahNMethod* data = list[idx];
512       assert(data != nullptr, "Should not be null");
513       if (!data->is_unregistered()) {
514         cl->do_nmethod(data->nm());
515       }
516     }
517   }
518 }
519 
520 ShenandoahConcurrentNMethodIterator::ShenandoahConcurrentNMethodIterator(ShenandoahNMethodTable* table) :
521   _table(table),
522   _table_snapshot(nullptr),
523   _started_workers(0),
524   _finished_workers(0) {}
525 
526 void ShenandoahConcurrentNMethodIterator::nmethods_do(NMethodClosure* cl) {
527   // Cannot safepoint when iteration is running, because this can cause deadlocks
528   // with other threads waiting on iteration to be over.
529   NoSafepointVerifier nsv;
530 
531   MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag);
532 
533   if (_finished_workers > 0) {
534     // Some threads have already finished. We are now in rampdown: we are now
535     // waiting for all currently recorded workers to finish. No new workers
536     // should start.
537     return;
538   }
539 
540   // Record a new worker and initialize the snapshot if it is a first visitor.
541   if (_started_workers++ == 0) {
542     _table_snapshot = _table->snapshot_for_iteration();
543   }
544 
545   // All set, relinquish the lock and go concurrent.
546   {
547     MutexUnlocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
548     _table_snapshot->concurrent_nmethods_do(cl);
549   }
550 
551   // Record completion. Last worker shuts down the iterator and notifies any waiters.
552   uint count = ++_finished_workers;
553   if (count == _started_workers) {
554     _table->finish_iteration(_table_snapshot);
555     CodeCache_lock->notify_all();
556   }
557 }