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