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(NULL), _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 != NULL) {
 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 != NULL) {
 96       FREE_C_HEAP_ARRAY(oop*, _oops);
 97       _oops = NULL;
 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 != NULL) {
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 != NULL, "Sanity");
157   assert(data->lock()->owned_by_self(), "Must hold the lock");
158 
159   ShenandoahHeap* const heap = ShenandoahHeap::heap();
160   if (heap->is_concurrent_weak_root_in_progress() ||
161       heap->is_concurrent_strong_root_in_progress()) {
162     ShenandoahEvacOOMScope evac_scope;
163     heal_nmethod_metadata(data);
164   } else if (heap->is_concurrent_mark_in_progress()) {
165     ShenandoahKeepAliveClosure cl;
166     data->oops_do(&cl);
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     assert(heap->cancelled_gc() || Continuations::enabled(), "What else?");
172   }
173 }
174 
175 #ifdef ASSERT
176 void ShenandoahNMethod::assert_correct() {
177   ShenandoahHeap* heap = ShenandoahHeap::heap();
178   for (int c = 0; c < _oops_count; c++) {
179     oop *loc = _oops[c];
180     assert(_nm->code_contains((address) loc) || _nm->oops_contains(loc), "nmethod should contain the oop*");
181     oop o = RawAccess<>::oop_load(loc);
182     shenandoah_assert_correct_except(loc, o, o == NULL || heap->is_full_gc_move_in_progress());
183   }
184 
185   oop* const begin = _nm->oops_begin();
186   oop* const end = _nm->oops_end();
187   for (oop* p = begin; p < end; p++) {
188     if (*p != Universe::non_oop_word()) {
189       oop o = RawAccess<>::oop_load(p);
190       shenandoah_assert_correct_except(p, o, o == NULL || heap->is_full_gc_move_in_progress());
191     }
192   }
193 }
194 
195 class ShenandoahNMethodOopDetector : public OopClosure {
196 private:
197   ResourceMark rm; // For growable array allocation below.
198   GrowableArray<oop*> _oops;
199 
200 public:
201   ShenandoahNMethodOopDetector() : _oops(10) {};
202 
203   void do_oop(oop* o) {
204     _oops.append(o);
205   }
206   void do_oop(narrowOop* o) {
207     fatal("NMethods should not have compressed oops embedded.");
208   }
209 
210   GrowableArray<oop*>* oops() {
211     return &_oops;
212   }
213 
214   bool has_oops() {
215     return !_oops.is_empty();
216   }
217 };
218 
219 void ShenandoahNMethod::assert_same_oops(bool allow_dead) {
220   ShenandoahNMethodOopDetector detector;
221   nm()->oops_do(&detector, allow_dead);
222 
223   GrowableArray<oop*>* oops = detector.oops();
224 
225   int count = _oops_count;
226   for (int index = 0; index < _oops_count; index ++) {
227     assert(oops->contains(_oops[index]), "Must contain this oop");
228   }
229 
230   for (oop* p = nm()->oops_begin(); p < nm()->oops_end(); p ++) {
231     if (*p == Universe::non_oop_word()) continue;
232     count++;
233     assert(oops->contains(p), "Must contain this oop");
234   }
235 
236   if (oops->length() < count) {
237     stringStream debug_stream;
238     debug_stream.print_cr("detected locs: %d", oops->length());
239     for (int i = 0; i < oops->length(); i++) {
240       debug_stream.print_cr("-> " PTR_FORMAT, p2i(oops->at(i)));
241     }
242     debug_stream.print_cr("recorded oops: %d", _oops_count);
243     for (int i = 0; i < _oops_count; i++) {
244       debug_stream.print_cr("-> " PTR_FORMAT, p2i(_oops[i]));
245     }
246     GrowableArray<oop*> check;
247     bool non_immed;
248     detect_reloc_oops(nm(), check, non_immed);
249     debug_stream.print_cr("check oops: %d", check.length());
250     for (int i = 0; i < check.length(); i++) {
251       debug_stream.print_cr("-> " PTR_FORMAT, p2i(check.at(i)));
252     }
253     fatal("Must match #detected: %d, #recorded: %d, #total: %d, begin: " PTR_FORMAT ", end: " PTR_FORMAT "\n%s",
254           oops->length(), _oops_count, count, p2i(nm()->oops_begin()), p2i(nm()->oops_end()), debug_stream.as_string());
255   }
256 }
257 #endif
258 
259 ShenandoahNMethodTable::ShenandoahNMethodTable() :
260   _heap(ShenandoahHeap::heap()),
261   _index(0),
262   _itr_cnt(0) {
263   _list = new ShenandoahNMethodList(minSize);
264 }
265 
266 ShenandoahNMethodTable::~ShenandoahNMethodTable() {
267   assert(_list != NULL, "Sanity");
268   _list->release();
269 }
270 
271 void ShenandoahNMethodTable::register_nmethod(nmethod* nm) {
272   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
273   assert(_index >= 0 && _index <= _list->size(), "Sanity");
274 
275   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
276 
277   if (data != NULL) {
278     assert(contain(nm), "Must have been registered");
279     assert(nm == data->nm(), "Must be same nmethod");
280     // Prevent updating a nmethod while concurrent iteration is in progress.
281     wait_until_concurrent_iteration_done();
282     ShenandoahReentrantLocker data_locker(data->lock());
283     data->update();
284   } else {
285     // For a new nmethod, we can safely append it to the list, because
286     // concurrent iteration will not touch it.
287     data = ShenandoahNMethod::for_nmethod(nm);
288     assert(data != NULL, "Sanity");
289     ShenandoahNMethod::attach_gc_data(nm, data);
290     ShenandoahLocker locker(&_lock);
291     log_register_nmethod(nm);
292     append(data);
293   }
294   // Disarm new nmethod
295   ShenandoahNMethod::disarm_nmethod(nm);
296 }
297 
298 void ShenandoahNMethodTable::unregister_nmethod(nmethod* nm) {
299   assert_locked_or_safepoint(CodeCache_lock);
300 
301   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
302   assert(data != NULL, "Sanity");
303   if (Thread::current()->is_Code_cache_sweeper_thread()) {
304     wait_until_concurrent_iteration_done();
305   }
306   log_unregister_nmethod(nm);
307   ShenandoahLocker locker(&_lock);
308   assert(contain(nm), "Must have been registered");
309 
310   ShenandoahReentrantLocker data_locker(data->lock());
311   data->mark_unregistered();
312 }
313 
314 void ShenandoahNMethodTable::flush_nmethod(nmethod* nm) {
315   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
316   assert(Thread::current()->is_Code_cache_sweeper_thread(), "Must from Sweep thread");
317   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
318   assert(data != NULL, "Sanity");
319 
320   // Can not alter the array when iteration is in progress
321   wait_until_concurrent_iteration_done();
322   log_flush_nmethod(nm);
323 
324   ShenandoahLocker locker(&_lock);
325   int idx = index_of(nm);
326   assert(idx >= 0 && idx < _index, "Invalid index");
327   ShenandoahNMethod::attach_gc_data(nm, NULL);
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(!iteration_in_progress(), "Can not happen");
352   assert(_index >= 0 && _index <= _list->size(), "Sanity");
353 
354   assert(idx >= 0 && idx < _index, "Out of bound");
355   ShenandoahNMethod* snm = _list->at(idx);
356   ShenandoahNMethod* tmp = _list->at(_index - 1);
357   _list->set(idx, tmp);
358   _index --;
359 
360   delete snm;
361 }
362 
363 void ShenandoahNMethodTable::wait_until_concurrent_iteration_done() {
364   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
365   while (iteration_in_progress()) {
366     CodeCache_lock->wait_without_safepoint_check();
367   }
368 }
369 
370 void ShenandoahNMethodTable::append(ShenandoahNMethod* snm) {
371   if (is_full()) {
372     int new_size = 2 * _list->size();
373     // Rebuild table and replace current one
374     rebuild(new_size);
375   }
376 
377   _list->set(_index++,  snm);
378   assert(_index >= 0 && _index <= _list->size(), "Sanity");
379 }
380 
381 void ShenandoahNMethodTable::rebuild(int size) {
382   ShenandoahNMethodList* new_list = new ShenandoahNMethodList(size);
383   new_list->transfer(_list, _index);
384 
385   // Release old list
386   _list->release();
387   _list = new_list;
388 }
389 
390 ShenandoahNMethodTableSnapshot* ShenandoahNMethodTable::snapshot_for_iteration() {
391   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
392   _itr_cnt++;
393   return new ShenandoahNMethodTableSnapshot(this);
394 }
395 
396 void ShenandoahNMethodTable::finish_iteration(ShenandoahNMethodTableSnapshot* snapshot) {
397   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
398   assert(iteration_in_progress(), "Why we here?");
399   assert(snapshot != NULL, "No snapshot");
400   _itr_cnt--;
401 
402   delete snapshot;
403 }
404 
405 void ShenandoahNMethodTable::log_register_nmethod(nmethod* nm) {
406   LogTarget(Debug, gc, nmethod) log;
407   if (!log.is_enabled()) {
408     return;
409   }
410 
411   ResourceMark rm;
412   log.print("Register NMethod: %s.%s [" PTR_FORMAT "] (%s)",
413             nm->method()->method_holder()->external_name(),
414             nm->method()->name()->as_C_string(),
415             p2i(nm),
416             nm->compiler_name());
417 }
418 
419 void ShenandoahNMethodTable::log_unregister_nmethod(nmethod* nm) {
420   LogTarget(Debug, gc, nmethod) log;
421   if (!log.is_enabled()) {
422     return;
423   }
424 
425   ResourceMark rm;
426   log.print("Unregister NMethod: %s.%s [" PTR_FORMAT "]",
427             nm->method()->method_holder()->external_name(),
428             nm->method()->name()->as_C_string(),
429             p2i(nm));
430 }
431 
432 void ShenandoahNMethodTable::log_flush_nmethod(nmethod* nm) {
433   LogTarget(Debug, gc, nmethod) log;
434   if (!log.is_enabled()) {
435     return;
436   }
437 
438   ResourceMark rm;
439   log.print("Flush NMethod: (" PTR_FORMAT ")", p2i(nm));
440 }
441 
442 #ifdef ASSERT
443 void ShenandoahNMethodTable::assert_nmethods_correct() {
444   assert_locked_or_safepoint(CodeCache_lock);
445 
446   for (int index = 0; index < length(); index ++) {
447     ShenandoahNMethod* m = _list->at(index);
448     // Concurrent unloading may have dead nmethods to be cleaned by sweeper
449     if (m->is_unregistered()) continue;
450     m->assert_correct();
451   }
452 }
453 #endif
454 
455 
456 ShenandoahNMethodList::ShenandoahNMethodList(int size) :
457   _size(size), _ref_count(1) {
458   _list = NEW_C_HEAP_ARRAY(ShenandoahNMethod*, size, mtGC);
459 }
460 
461 ShenandoahNMethodList::~ShenandoahNMethodList() {
462   assert(_list != NULL, "Sanity");
463   assert(_ref_count == 0, "Must be");
464   FREE_C_HEAP_ARRAY(ShenandoahNMethod*, _list);
465 }
466 
467 void ShenandoahNMethodList::transfer(ShenandoahNMethodList* const list, int limit) {
468   assert(limit <= size(), "Sanity");
469   ShenandoahNMethod** old_list = list->list();
470   for (int index = 0; index < limit; index++) {
471     _list[index] = old_list[index];
472   }
473 }
474 
475 ShenandoahNMethodList* ShenandoahNMethodList::acquire() {
476   assert_locked_or_safepoint(CodeCache_lock);
477   _ref_count++;
478   return this;
479 }
480 
481 void ShenandoahNMethodList::release() {
482   assert_locked_or_safepoint(CodeCache_lock);
483   _ref_count--;
484   if (_ref_count == 0) {
485     delete this;
486   }
487 }
488 
489 ShenandoahNMethodTableSnapshot::ShenandoahNMethodTableSnapshot(ShenandoahNMethodTable* table) :
490   _heap(ShenandoahHeap::heap()), _list(table->_list->acquire()), _limit(table->_index), _claimed(0) {
491 }
492 
493 ShenandoahNMethodTableSnapshot::~ShenandoahNMethodTableSnapshot() {
494   _list->release();
495 }
496 
497 void ShenandoahNMethodTableSnapshot::parallel_blobs_do(CodeBlobClosure *f) {
498   size_t stride = 256; // educated guess
499 
500   ShenandoahNMethod** const list = _list->list();
501 
502   size_t max = (size_t)_limit;
503   while (_claimed < max) {
504     size_t cur = Atomic::fetch_and_add(&_claimed, stride, memory_order_relaxed);
505     size_t start = cur;
506     size_t end = MIN2(cur + stride, max);
507     if (start >= max) break;
508 
509     for (size_t idx = start; idx < end; idx++) {
510       ShenandoahNMethod* nmr = list[idx];
511       assert(nmr != NULL, "Sanity");
512       if (nmr->is_unregistered()) {
513         continue;
514       }
515 
516       // A nmethod can become a zombie before it is unregistered.
517       if (nmr->nm()->is_alive()) {
518         nmr->assert_correct();
519         f->do_code_blob(nmr->nm());
520       }
521     }
522   }
523 }
524 
525 void ShenandoahNMethodTableSnapshot::concurrent_nmethods_do(NMethodClosure* cl) {
526   size_t stride = 256; // educated guess
527 
528   ShenandoahNMethod** list = _list->list();
529   size_t max = (size_t)_limit;
530   while (_claimed < max) {
531     size_t cur = Atomic::fetch_and_add(&_claimed, stride, memory_order_relaxed);
532     size_t start = cur;
533     size_t end = MIN2(cur + stride, max);
534     if (start >= max) break;
535 
536     for (size_t idx = start; idx < end; idx++) {
537       ShenandoahNMethod* data = list[idx];
538       assert(data != NULL, "Should not be NULL");
539       if (!data->is_unregistered()) {
540         cl->do_nmethod(data->nm());
541       }
542     }
543   }
544 }
545 
546 ShenandoahConcurrentNMethodIterator::ShenandoahConcurrentNMethodIterator(ShenandoahNMethodTable* table) :
547   _table(table), _table_snapshot(NULL) {
548 }
549 
550 void ShenandoahConcurrentNMethodIterator::nmethods_do_begin() {
551   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
552   _table_snapshot = _table->snapshot_for_iteration();
553 }
554 
555 void ShenandoahConcurrentNMethodIterator::nmethods_do(NMethodClosure* cl) {
556   assert(_table_snapshot != NULL, "Must first call nmethod_do_begin()");
557   _table_snapshot->concurrent_nmethods_do(cl);
558 }
559 
560 void ShenandoahConcurrentNMethodIterator::nmethods_do_end() {
561   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
562   _table->finish_iteration(_table_snapshot);
563   CodeCache_lock->notify_all();
564 }