1 /*
  2  * Copyright (c) 2019, 2022, Red Hat, Inc. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 
 27 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
 28 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 29 #include "gc/shenandoah/shenandoahNMethod.inline.hpp"
 30 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
 31 #include "memory/resourceArea.hpp"
 32 #include "runtime/continuation.hpp"
 33 
 34 ShenandoahNMethod::ShenandoahNMethod(nmethod* nm, GrowableArray<oop*>& oops, bool non_immediate_oops) :
 35   _nm(nm), _oops(nullptr), _oops_count(0), _unregistered(false) {
 36 
 37   if (!oops.is_empty()) {
 38     _oops_count = oops.length();
 39     _oops = NEW_C_HEAP_ARRAY(oop*, _oops_count, mtGC);
 40     for (int c = 0; c < _oops_count; c++) {
 41       _oops[c] = oops.at(c);
 42     }
 43   }
 44   _has_non_immed_oops = non_immediate_oops;
 45 
 46   assert_same_oops();
 47 }
 48 
 49 ShenandoahNMethod::~ShenandoahNMethod() {
 50   if (_oops != nullptr) {
 51     FREE_C_HEAP_ARRAY(oop*, _oops);
 52   }
 53 }
 54 
 55 class ShenandoahHasCSetOopClosure : public OopClosure {
 56 private:
 57   ShenandoahHeap* const _heap;
 58   bool                  _has_cset_oops;
 59 
 60 public:
 61   ShenandoahHasCSetOopClosure(ShenandoahHeap *heap) :
 62     _heap(heap),
 63     _has_cset_oops(false) {
 64   }
 65 
 66   bool has_cset_oops() const {
 67     return _has_cset_oops;
 68   }
 69 
 70   void do_oop(oop* p) {
 71     oop value = RawAccess<>::oop_load(p);
 72     if (!_has_cset_oops && _heap->in_collection_set(value)) {
 73       _has_cset_oops = true;
 74     }
 75   }
 76 
 77   void do_oop(narrowOop* p) {
 78     ShouldNotReachHere();
 79   }
 80 };
 81 
 82 bool ShenandoahNMethod::has_cset_oops(ShenandoahHeap *heap) {
 83   ShenandoahHasCSetOopClosure cl(heap);
 84   oops_do(&cl);
 85   return cl.has_cset_oops();
 86 }
 87 
 88 void ShenandoahNMethod::update() {
 89   ResourceMark rm;
 90   bool non_immediate_oops = false;
 91   GrowableArray<oop*> oops;
 92 
 93   detect_reloc_oops(nm(), oops, non_immediate_oops);
 94   if (oops.length() != _oops_count) {
 95     if (_oops != nullptr) {
 96       FREE_C_HEAP_ARRAY(oop*, _oops);
 97       _oops = nullptr;
 98     }
 99 
100     _oops_count = oops.length();
101     if (_oops_count > 0) {
102       _oops = NEW_C_HEAP_ARRAY(oop*, _oops_count, mtGC);
103     }
104   }
105 
106   for (int index = 0; index < _oops_count; index ++) {
107     _oops[index] = oops.at(index);
108   }
109   _has_non_immed_oops = non_immediate_oops;
110 
111   assert_same_oops();
112 }
113 
114 void ShenandoahNMethod::detect_reloc_oops(nmethod* nm, GrowableArray<oop*>& oops, bool& has_non_immed_oops) {
115   has_non_immed_oops = false;
116   // Find all oops relocations
117   RelocIterator iter(nm);
118   while (iter.next()) {
119     if (iter.type() != relocInfo::oop_type) {
120       // Not an oop
121       continue;
122     }
123 
124     oop_Relocation* r = iter.oop_reloc();
125     if (!r->oop_is_immediate()) {
126       // Non-immediate oop found
127       has_non_immed_oops = true;
128       continue;
129     }
130 
131     oop value = r->oop_value();
132     if (value != nullptr) {
133       oop* addr = r->oop_addr();
134       shenandoah_assert_correct(addr, value);
135       shenandoah_assert_not_in_cset_except(addr, value, ShenandoahHeap::heap()->cancelled_gc());
136       shenandoah_assert_not_forwarded(addr, value);
137       // Non-null immediate oop found. null oops can safely be
138       // ignored since the method will be re-registered if they
139       // are later patched to be non-null.
140       oops.push(addr);
141     }
142   }
143 }
144 
145 ShenandoahNMethod* ShenandoahNMethod::for_nmethod(nmethod* nm) {
146   ResourceMark rm;
147   bool non_immediate_oops = false;
148   GrowableArray<oop*> oops;
149 
150   detect_reloc_oops(nm, oops, non_immediate_oops);
151   return new ShenandoahNMethod(nm, oops, non_immediate_oops);
152 }
153 
154 void ShenandoahNMethod::heal_nmethod(nmethod* nm) {
155   ShenandoahNMethod* data = gc_data(nm);
156   assert(data != nullptr, "Sanity");
157   assert(data->lock()->owned_by_self(), "Must hold the lock");
158 
159   ShenandoahHeap* const heap = ShenandoahHeap::heap();
160   if (heap->is_concurrent_mark_in_progress()) {
161     ShenandoahKeepAliveClosure cl;
162     data->oops_do(&cl);
163   } else if (heap->is_concurrent_weak_root_in_progress() ||
164              heap->is_concurrent_strong_root_in_progress() ) {
165     ShenandoahEvacOOMScope evac_scope;
166     heal_nmethod_metadata(data);
167   } else {
168     // There is possibility that GC is cancelled when it arrives final mark.
169     // In this case, concurrent root phase is skipped and degenerated GC should be
170     // followed, where nmethods are disarmed.
171   }
172 }
173 
174 #ifdef ASSERT
175 void ShenandoahNMethod::assert_correct() {
176   ShenandoahHeap* heap = ShenandoahHeap::heap();
177   for (int c = 0; c < _oops_count; c++) {
178     oop *loc = _oops[c];
179     assert(_nm->code_contains((address) loc) || _nm->oops_contains(loc), "nmethod should contain the oop*");
180     oop o = RawAccess<>::oop_load(loc);
181     shenandoah_assert_correct_except(loc, o, o == nullptr || heap->is_full_gc_move_in_progress());
182   }
183 
184   oop* const begin = _nm->oops_begin();
185   oop* const end = _nm->oops_end();
186   for (oop* p = begin; p < end; p++) {
187     if (*p != Universe::non_oop_word()) {
188       oop o = RawAccess<>::oop_load(p);
189       shenandoah_assert_correct_except(p, o, o == nullptr || heap->is_full_gc_move_in_progress());
190     }
191   }
192 }
193 
194 class ShenandoahNMethodOopDetector : public OopClosure {
195 private:
196   ResourceMark rm; // For growable array allocation below.
197   GrowableArray<oop*> _oops;
198 
199 public:
200   ShenandoahNMethodOopDetector() : _oops(10) {};
201 
202   void do_oop(oop* o) {
203     _oops.append(o);
204   }
205   void do_oop(narrowOop* o) {
206     fatal("NMethods should not have compressed oops embedded.");
207   }
208 
209   GrowableArray<oop*>* oops() {
210     return &_oops;
211   }
212 
213   bool has_oops() {
214     return !_oops.is_empty();
215   }
216 };
217 
218 void ShenandoahNMethod::assert_same_oops(bool allow_dead) {
219   ShenandoahNMethodOopDetector detector;
220   nm()->oops_do(&detector, allow_dead);
221 
222   GrowableArray<oop*>* oops = detector.oops();
223 
224   int count = _oops_count;
225   for (int index = 0; index < _oops_count; index ++) {
226     assert(oops->contains(_oops[index]), "Must contain this oop");
227   }
228 
229   for (oop* p = nm()->oops_begin(); p < nm()->oops_end(); p ++) {
230     if (*p == Universe::non_oop_word()) continue;
231     count++;
232     assert(oops->contains(p), "Must contain this oop");
233   }
234 
235   if (oops->length() < count) {
236     stringStream debug_stream;
237     debug_stream.print_cr("detected locs: %d", oops->length());
238     for (int i = 0; i < oops->length(); i++) {
239       debug_stream.print_cr("-> " PTR_FORMAT, p2i(oops->at(i)));
240     }
241     debug_stream.print_cr("recorded oops: %d", _oops_count);
242     for (int i = 0; i < _oops_count; i++) {
243       debug_stream.print_cr("-> " PTR_FORMAT, p2i(_oops[i]));
244     }
245     GrowableArray<oop*> check;
246     bool non_immed;
247     detect_reloc_oops(nm(), check, non_immed);
248     debug_stream.print_cr("check oops: %d", check.length());
249     for (int i = 0; i < check.length(); i++) {
250       debug_stream.print_cr("-> " PTR_FORMAT, p2i(check.at(i)));
251     }
252     fatal("Must match #detected: %d, #recorded: %d, #total: %d, begin: " PTR_FORMAT ", end: " PTR_FORMAT "\n%s",
253           oops->length(), _oops_count, count, p2i(nm()->oops_begin()), p2i(nm()->oops_end()), debug_stream.freeze());
254   }
255 }
256 #endif
257 
258 ShenandoahNMethodTable::ShenandoahNMethodTable() :
259   _heap(ShenandoahHeap::heap()),
260   _index(0),
261   _itr_cnt(0) {
262   _list = new ShenandoahNMethodList(minSize);
263 }
264 
265 ShenandoahNMethodTable::~ShenandoahNMethodTable() {
266   assert(_list != nullptr, "Sanity");
267   _list->release();
268 }
269 
270 void ShenandoahNMethodTable::register_nmethod(nmethod* nm) {
271   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
272   assert(_index >= 0 && _index <= _list->size(), "Sanity");
273 
274   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
275 
276   if (data != nullptr) {
277     assert(contain(nm), "Must have been registered");
278     assert(nm == data->nm(), "Must be same nmethod");
279     // Prevent updating a nmethod while concurrent iteration is in progress.
280     wait_until_concurrent_iteration_done();
281     ShenandoahReentrantLocker data_locker(data->lock());
282     data->update();
283   } else {
284     // For a new nmethod, we can safely append it to the list, because
285     // concurrent iteration will not touch it.
286     data = ShenandoahNMethod::for_nmethod(nm);
287     assert(data != nullptr, "Sanity");
288     ShenandoahNMethod::attach_gc_data(nm, data);
289     ShenandoahLocker locker(&_lock);
290     log_register_nmethod(nm);
291     append(data);
292   }
293   // Disarm new nmethod
294   ShenandoahNMethod::disarm_nmethod(nm);
295 }
296 
297 void ShenandoahNMethodTable::unregister_nmethod(nmethod* nm) {
298   assert_locked_or_safepoint(CodeCache_lock);
299 
300   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
301   assert(data != nullptr, "Sanity");
302   log_unregister_nmethod(nm);
303   ShenandoahLocker locker(&_lock);
304   assert(contain(nm), "Must have been registered");
305 
306   int idx = index_of(nm);
307   assert(idx >= 0 && idx < _index, "Invalid index");
308   ShenandoahNMethod::attach_gc_data(nm, nullptr);
309   remove(idx);
310 }
311 
312 bool ShenandoahNMethodTable::contain(nmethod* nm) const {
313   return index_of(nm) != -1;
314 }
315 
316 ShenandoahNMethod* ShenandoahNMethodTable::at(int index) const {
317   assert(index >= 0 && index < _index, "Out of bound");
318   return _list->at(index);
319 }
320 
321 int ShenandoahNMethodTable::index_of(nmethod* nm) const {
322   for (int index = 0; index < length(); index ++) {
323     if (at(index)->nm() == nm) {
324       return index;
325     }
326   }
327   return -1;
328 }
329 
330 void ShenandoahNMethodTable::remove(int idx) {
331   shenandoah_assert_locked_or_safepoint(CodeCache_lock);
332   assert(_index >= 0 && _index <= _list->size(), "Sanity");
333 
334   assert(idx >= 0 && idx < _index, "Out of bound");
335   ShenandoahNMethod* snm = _list->at(idx);
336   ShenandoahNMethod* tmp = _list->at(_index - 1);
337   _list->set(idx, tmp);
338   _index --;
339 
340   delete snm;
341 }
342 
343 void ShenandoahNMethodTable::wait_until_concurrent_iteration_done() {
344   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
345   while (iteration_in_progress()) {
346     CodeCache_lock->wait_without_safepoint_check();
347   }
348 }
349 
350 void ShenandoahNMethodTable::append(ShenandoahNMethod* snm) {
351   if (is_full()) {
352     int new_size = 2 * _list->size();
353     // Rebuild table and replace current one
354     rebuild(new_size);
355   }
356 
357   _list->set(_index++,  snm);
358   assert(_index >= 0 && _index <= _list->size(), "Sanity");
359 }
360 
361 void ShenandoahNMethodTable::rebuild(int size) {
362   ShenandoahNMethodList* new_list = new ShenandoahNMethodList(size);
363   new_list->transfer(_list, _index);
364 
365   // Release old list
366   _list->release();
367   _list = new_list;
368 }
369 
370 ShenandoahNMethodTableSnapshot* ShenandoahNMethodTable::snapshot_for_iteration() {
371   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
372   _itr_cnt++;
373   return new ShenandoahNMethodTableSnapshot(this);
374 }
375 
376 void ShenandoahNMethodTable::finish_iteration(ShenandoahNMethodTableSnapshot* snapshot) {
377   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
378   assert(iteration_in_progress(), "Why we here?");
379   assert(snapshot != nullptr, "No snapshot");
380   _itr_cnt--;
381 
382   delete snapshot;
383 }
384 
385 void ShenandoahNMethodTable::log_register_nmethod(nmethod* nm) {
386   LogTarget(Debug, gc, nmethod) log;
387   if (!log.is_enabled()) {
388     return;
389   }
390 
391   ResourceMark rm;
392   log.print("Register NMethod: %s.%s [" PTR_FORMAT "] (%s)",
393             nm->method()->method_holder()->external_name(),
394             nm->method()->name()->as_C_string(),
395             p2i(nm),
396             nm->compiler_name());
397 }
398 
399 void ShenandoahNMethodTable::log_unregister_nmethod(nmethod* nm) {
400   LogTarget(Debug, gc, nmethod) log;
401   if (!log.is_enabled()) {
402     return;
403   }
404 
405   ResourceMark rm;
406   log.print("Unregister NMethod: %s.%s [" PTR_FORMAT "]",
407             nm->method()->method_holder()->external_name(),
408             nm->method()->name()->as_C_string(),
409             p2i(nm));
410 }
411 
412 #ifdef ASSERT
413 void ShenandoahNMethodTable::assert_nmethods_correct() {
414   assert_locked_or_safepoint(CodeCache_lock);
415 
416   for (int index = 0; index < length(); index ++) {
417     ShenandoahNMethod* m = _list->at(index);
418     // Concurrent unloading may have dead nmethods to be cleaned by sweeper
419     if (m->is_unregistered()) continue;
420     m->assert_correct();
421   }
422 }
423 #endif
424 
425 
426 ShenandoahNMethodList::ShenandoahNMethodList(int size) :
427   _size(size), _ref_count(1) {
428   _list = NEW_C_HEAP_ARRAY(ShenandoahNMethod*, size, mtGC);
429 }
430 
431 ShenandoahNMethodList::~ShenandoahNMethodList() {
432   assert(_list != nullptr, "Sanity");
433   assert(_ref_count == 0, "Must be");
434   FREE_C_HEAP_ARRAY(ShenandoahNMethod*, _list);
435 }
436 
437 void ShenandoahNMethodList::transfer(ShenandoahNMethodList* const list, int limit) {
438   assert(limit <= size(), "Sanity");
439   ShenandoahNMethod** old_list = list->list();
440   for (int index = 0; index < limit; index++) {
441     _list[index] = old_list[index];
442   }
443 }
444 
445 ShenandoahNMethodList* ShenandoahNMethodList::acquire() {
446   assert_locked_or_safepoint(CodeCache_lock);
447   _ref_count++;
448   return this;
449 }
450 
451 void ShenandoahNMethodList::release() {
452   assert_locked_or_safepoint(CodeCache_lock);
453   _ref_count--;
454   if (_ref_count == 0) {
455     delete this;
456   }
457 }
458 
459 ShenandoahNMethodTableSnapshot::ShenandoahNMethodTableSnapshot(ShenandoahNMethodTable* table) :
460   _heap(ShenandoahHeap::heap()), _list(table->_list->acquire()), _limit(table->_index), _claimed(0) {
461 }
462 
463 ShenandoahNMethodTableSnapshot::~ShenandoahNMethodTableSnapshot() {
464   _list->release();
465 }
466 
467 void ShenandoahNMethodTableSnapshot::parallel_blobs_do(CodeBlobClosure *f) {
468   size_t stride = 256; // educated guess
469 
470   ShenandoahNMethod** const list = _list->list();
471 
472   size_t max = (size_t)_limit;
473   while (_claimed < max) {
474     size_t cur = Atomic::fetch_then_add(&_claimed, stride, memory_order_relaxed);
475     size_t start = cur;
476     size_t end = MIN2(cur + stride, max);
477     if (start >= max) break;
478 
479     for (size_t idx = start; idx < end; idx++) {
480       ShenandoahNMethod* nmr = list[idx];
481       assert(nmr != nullptr, "Sanity");
482       if (nmr->is_unregistered()) {
483         continue;
484       }
485 
486       nmr->assert_correct();
487       f->do_code_blob(nmr->nm());
488     }
489   }
490 }
491 
492 void ShenandoahNMethodTableSnapshot::concurrent_nmethods_do(NMethodClosure* cl) {
493   size_t stride = 256; // educated guess
494 
495   ShenandoahNMethod** list = _list->list();
496   size_t max = (size_t)_limit;
497   while (_claimed < max) {
498     size_t cur = Atomic::fetch_then_add(&_claimed, stride, memory_order_relaxed);
499     size_t start = cur;
500     size_t end = MIN2(cur + stride, max);
501     if (start >= max) break;
502 
503     for (size_t idx = start; idx < end; idx++) {
504       ShenandoahNMethod* data = list[idx];
505       assert(data != nullptr, "Should not be null");
506       if (!data->is_unregistered()) {
507         cl->do_nmethod(data->nm());
508       }
509     }
510   }
511 }
512 
513 ShenandoahConcurrentNMethodIterator::ShenandoahConcurrentNMethodIterator(ShenandoahNMethodTable* table) :
514   _table(table), _table_snapshot(nullptr) {
515 }
516 
517 void ShenandoahConcurrentNMethodIterator::nmethods_do_begin() {
518   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
519   _table_snapshot = _table->snapshot_for_iteration();
520 }
521 
522 void ShenandoahConcurrentNMethodIterator::nmethods_do(NMethodClosure* cl) {
523   assert(_table_snapshot != nullptr, "Must first call nmethod_do_begin()");
524   _table_snapshot->concurrent_nmethods_do(cl);
525 }
526 
527 void ShenandoahConcurrentNMethodIterator::nmethods_do_end() {
528   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
529   _table->finish_iteration(_table_snapshot);
530   CodeCache_lock->notify_all();
531 }