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