1 /*
   2  * Copyright (c) 2019, 2020, 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/shenandoahConcurrentRoots.hpp"
  29 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  30 #include "gc/shenandoah/shenandoahNMethod.inline.hpp"
  31 #include "memory/resourceArea.hpp"
  32 
  33 ShenandoahNMethod::ShenandoahNMethod(nmethod* nm, GrowableArray<oop*>& oops, bool non_immediate_oops) :
  34   _nm(nm), _oops(NULL), _oops_count(0), _unregistered(false) {
  35 
  36   if (!oops.is_empty()) {
  37     _oops_count = oops.length();
  38     _oops = NEW_C_HEAP_ARRAY(oop*, _oops_count, mtGC);
  39     for (int c = 0; c < _oops_count; c++) {
  40       _oops[c] = oops.at(c);
  41     }
  42   }
  43   _has_non_immed_oops = non_immediate_oops;
  44 
  45   assert_same_oops();
  46 }
  47 
  48 ShenandoahNMethod::~ShenandoahNMethod() {
  49   if (_oops != NULL) {
  50     FREE_C_HEAP_ARRAY(oop*, _oops);
  51   }
  52 }
  53 
  54 class ShenandoahHasCSetOopClosure : public OopClosure {
  55 private:
  56   ShenandoahHeap* const _heap;
  57   bool                  _has_cset_oops;
  58 
  59 public:
  60   ShenandoahHasCSetOopClosure() :
  61     _heap(ShenandoahHeap::heap()),
  62     _has_cset_oops(false) {
  63   }
  64 
  65   bool has_cset_oops() const {
  66     return _has_cset_oops;
  67   }
  68 
  69   void do_oop(oop* p) {
  70     oop value = RawAccess<>::oop_load(p);
  71     if (!_has_cset_oops && _heap->in_collection_set(value)) {
  72       _has_cset_oops = true;
  73     }
  74   }
  75 
  76   void do_oop(narrowOop* p) {
  77     ShouldNotReachHere();
  78   }
  79 };
  80 
  81 bool ShenandoahNMethod::has_cset_oops(ShenandoahHeap *heap) {
  82   ShenandoahHasCSetOopClosure cl;
  83   oops_do(&cl);
  84   return cl.has_cset_oops();
  85 }
  86 
  87 void ShenandoahNMethod::update() {
  88   ResourceMark rm;
  89   bool non_immediate_oops = false;
  90   GrowableArray<oop*> oops;
  91 
  92   detect_reloc_oops(nm(), oops, non_immediate_oops);
  93   if (oops.length() != _oops_count) {
  94     if (_oops != NULL) {
  95       FREE_C_HEAP_ARRAY(oop*, _oops);
  96       _oops = NULL;
  97     }
  98 
  99     _oops_count = oops.length();
 100     if (_oops_count > 0) {
 101       _oops = NEW_C_HEAP_ARRAY(oop*, _oops_count, mtGC);
 102     }
 103   }
 104 
 105   for (int index = 0; index < _oops_count; index ++) {
 106     _oops[index] = oops.at(index);
 107   }
 108   _has_non_immed_oops = non_immediate_oops;
 109 
 110   assert_same_oops();
 111 }
 112 
 113 void ShenandoahNMethod::oops_do(OopClosure* oops, bool fix_relocations) {
 114   for (int c = 0; c < _oops_count; c ++) {
 115     oops->do_oop(_oops[c]);
 116   }
 117 
 118   oop* const begin = _nm->oops_begin();
 119   oop* const end = _nm->oops_end();
 120   for (oop* p = begin; p < end; p++) {
 121     if (*p != Universe::non_oop_word()) {
 122       oops->do_oop(p);
 123     }
 124   }
 125 
 126   if (fix_relocations && _has_non_immed_oops) {
 127     _nm->fix_oop_relocations();
 128   }
 129 }
 130 
 131 void ShenandoahNMethod::detect_reloc_oops(nmethod* nm, GrowableArray<oop*>& oops, bool& has_non_immed_oops) {
 132   has_non_immed_oops = false;
 133   // Find all oops relocations
 134   RelocIterator iter(nm);
 135   while (iter.next()) {
 136     if (iter.type() != relocInfo::oop_type) {
 137       // Not an oop
 138       continue;
 139     }
 140 
 141     oop_Relocation* r = iter.oop_reloc();
 142     if (!r->oop_is_immediate()) {
 143       // Non-immediate oop found
 144       has_non_immed_oops = true;
 145       continue;
 146     }
 147 
 148     oop value = r->oop_value();
 149     if (value != NULL) {
 150       oop* addr = r->oop_addr();
 151       shenandoah_assert_correct(addr, value);
 152       shenandoah_assert_not_in_cset_except(addr, value, ShenandoahHeap::heap()->cancelled_gc());
 153       shenandoah_assert_not_forwarded(addr, value);
 154       // Non-NULL immediate oop found. NULL oops can safely be
 155       // ignored since the method will be re-registered if they
 156       // are later patched to be non-NULL.
 157       oops.push(addr);
 158     }
 159   }
 160 }
 161 
 162 ShenandoahNMethod* ShenandoahNMethod::for_nmethod(nmethod* nm) {
 163   ResourceMark rm;
 164   bool non_immediate_oops = false;
 165   GrowableArray<oop*> oops;
 166 
 167   detect_reloc_oops(nm, oops, non_immediate_oops);
 168 
 169   // No embedded oops
 170   if(!ShenandoahConcurrentRoots::can_do_concurrent_class_unloading() &&
 171     oops.is_empty() && nm->oops_begin() >= nm->oops_end()) {
 172     return NULL;
 173   }
 174 
 175   return new ShenandoahNMethod(nm, oops, non_immediate_oops);
 176 }
 177 
 178 void ShenandoahNMethod::heal_nmethod(nmethod* nm) {
 179   assert(ShenandoahHeap::heap()->is_concurrent_root_in_progress(), "Only this phase");
 180   ShenandoahNMethod* data = gc_data(nm);
 181   assert(data != NULL, "Sanity");
 182   assert(data->lock()->owned_by_self(), "Must hold the lock");
 183 
 184   ShenandoahEvacOOMScope evac_scope;
 185   ShenandoahEvacuateUpdateRootsClosure<> cl;
 186   data->oops_do(&cl, true /*fix relocation*/);
 187 }
 188 
 189 #ifdef ASSERT
 190 void ShenandoahNMethod::assert_alive_and_correct() {
 191   assert(_nm->is_alive(), "only alive nmethods here");
 192   ShenandoahHeap* heap = ShenandoahHeap::heap();
 193   for (int c = 0; c < _oops_count; c++) {
 194     oop *loc = _oops[c];
 195     assert(_nm->code_contains((address) loc) || _nm->oops_contains(loc), "nmethod should contain the oop*");
 196     oop o = RawAccess<>::oop_load(loc);
 197     shenandoah_assert_correct_except(loc, o, o == NULL || heap->is_full_gc_move_in_progress());
 198   }
 199 
 200   oop* const begin = _nm->oops_begin();
 201   oop* const end = _nm->oops_end();
 202   for (oop* p = begin; p < end; p++) {
 203     if (*p != Universe::non_oop_word()) {
 204       oop o = RawAccess<>::oop_load(p);
 205       shenandoah_assert_correct_except(p, o, o == NULL || heap->is_full_gc_move_in_progress());
 206     }
 207   }
 208 }
 209 
 210 class ShenandoahNMethodOopDetector : public OopClosure {
 211 private:
 212   ResourceMark rm; // For growable array allocation below.
 213   GrowableArray<oop*> _oops;
 214 
 215 public:
 216   ShenandoahNMethodOopDetector() : _oops(10) {};
 217 
 218   void do_oop(oop* o) {
 219     _oops.append(o);
 220   }
 221   void do_oop(narrowOop* o) {
 222     fatal("NMethods should not have compressed oops embedded.");
 223   }
 224 
 225   GrowableArray<oop*>* oops() {
 226     return &_oops;
 227   }
 228 
 229   bool has_oops() {
 230     return !_oops.is_empty();
 231   }
 232 };
 233 
 234 void ShenandoahNMethod::assert_same_oops(bool allow_dead) {
 235   ShenandoahNMethodOopDetector detector;
 236   nm()->oops_do(&detector, allow_dead);
 237 
 238   GrowableArray<oop*>* oops = detector.oops();
 239 
 240   int count = 0;
 241   for (int index = 0; index < _oops_count; index ++) {
 242     count++;
 243     assert(oops->contains(_oops[index]), "Must contain this oop");
 244   }
 245 
 246   for (oop* p = nm()->oops_begin(); p < nm()->oops_end(); p ++) {
 247     if (*p == Universe::non_oop_word()) continue;
 248     count++;
 249     assert(oops->contains(p), "Must contain this oop");
 250   }
 251 #ifdef ASSERT_DISABLED
 252   if (oops->length() < count) {
 253     tty->print_cr("detected locs: %d", oops->length());
 254     for (int i = 0; i < oops->length(); i++) {
 255       tty->print_cr("-> " PTR_FORMAT, p2i(oops->at(i)));
 256     }
 257     tty->print_cr("recorded oops: %d", _oops_count);
 258     for (int i = 0; i < _oops_count; i++) {
 259       tty->print_cr("-> " PTR_FORMAT, p2i(_oops[i]));
 260     }
 261     GrowableArray<oop*> check;
 262     bool non_immed;
 263     detect_reloc_oops(nm(), check, non_immed);
 264     tty->print_cr("check oops: %d", check.length());
 265     for (int i = 0; i < check.length(); i++) {
 266       tty->print_cr("-> " PTR_FORMAT, p2i(check.at(i)));
 267     }
 268     assert(false, "Must match #detected: %d, #recorded: %d, #total: %d, begin: " PTR_FORMAT ", end: " PTR_FORMAT, oops->length(), _oops_count, count, p2i(nm()->oops_begin()), p2i(nm()->oops_end()));
 269   }
 270 #endif
 271   assert(oops->length() >= count,
 272          "Must match #detected: %d, #recorded: %d, #total: %d, begin: " PTR_FORMAT ", end: " PTR_FORMAT,
 273          oops->length(), _oops_count, count, p2i(nm()->oops_begin()), p2i(nm()->oops_end()));
 274 }
 275 
 276 void ShenandoahNMethod::assert_no_oops(nmethod* nm, bool allow_dead) {
 277   ShenandoahNMethodOopDetector detector;
 278   nm->oops_do(&detector, allow_dead);
 279   assert(detector.oops()->length() == 0, "Should not have oops");
 280 }
 281 #endif
 282 
 283 ShenandoahNMethodTable::ShenandoahNMethodTable() :
 284   _heap(ShenandoahHeap::heap()),
 285   _size(minSize),
 286   _index(0),
 287   _iteration_in_progress(false) {
 288   _array = NEW_C_HEAP_ARRAY(ShenandoahNMethod*, _size, mtGC);
 289 }
 290 
 291 ShenandoahNMethodTable::~ShenandoahNMethodTable() {
 292   assert(_array != NULL, "Sanity");
 293   FREE_C_HEAP_ARRAY(ShenandoahNMethod*, _array);
 294 }
 295 
 296 void ShenandoahNMethodTable::register_nmethod(nmethod* nm) {
 297   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
 298   assert(_index >= 0 && _index <= _size, "Sanity");
 299 
 300   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
 301   ShenandoahReentrantLocker data_locker(data != NULL ? data->lock() : NULL);
 302 
 303   if (data != NULL) {
 304     assert(contain(nm), "Must have been registered");
 305     assert(nm == data->nm(), "must be same nmethod");
 306     data->update();
 307   } else {
 308     data = ShenandoahNMethod::for_nmethod(nm);
 309     if (data == NULL) {
 310       assert(!ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 311              "Only possible when concurrent class unloading is off");
 312       return;
 313     }
 314     ShenandoahNMethod::attach_gc_data(nm, data);
 315     ShenandoahLocker locker(&_lock);
 316     log_register_nmethod(nm);
 317     append(data);
 318   }
 319   // Disarm new nmethod
 320   ShenandoahNMethod::disarm_nmethod(nm);
 321 }
 322 
 323 void ShenandoahNMethodTable::unregister_nmethod(nmethod* nm) {
 324   assert_locked_or_safepoint(CodeCache_lock);
 325 
 326   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
 327   if (data == NULL) {
 328     assert(!ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 329            "Only possible when concurrent class unloading is off");
 330     ShenandoahNMethod::assert_no_oops(nm, true /*allow_dead*/);
 331     return;
 332   }
 333 
 334   if (Thread::current()->is_Code_cache_sweeper_thread()) {
 335     wait_until_concurrent_iteration_done();
 336   }
 337   log_unregister_nmethod(nm);
 338   ShenandoahLocker locker(&_lock);
 339   assert(contain(nm), "Must have been registered");
 340 
 341   ShenandoahReentrantLocker data_locker(data->lock());
 342   data->mark_unregistered();
 343 }
 344 
 345 void ShenandoahNMethodTable::flush_nmethod(nmethod* nm) {
 346   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
 347   assert(Thread::current()->is_Code_cache_sweeper_thread(), "Must from Sweep thread");
 348   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
 349   assert(data != NULL || !ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 350          "Only possible when concurrent class unloading is off");
 351   if (data == NULL) {
 352     ShenandoahNMethod::assert_no_oops(nm, true /*allow_dead*/);
 353     return;
 354   }
 355 
 356   // Can not alter the array when iteration is in progress
 357   wait_until_concurrent_iteration_done();
 358   log_flush_nmethod(nm);
 359 
 360   ShenandoahLocker locker(&_lock);
 361   int idx = index_of(nm);
 362   assert(idx >= 0 && idx < _index, "Invalid index");
 363   ShenandoahNMethod::attach_gc_data(nm, NULL);
 364   remove(idx);
 365 }
 366 
 367 bool ShenandoahNMethodTable::contain(nmethod* nm) const {
 368   return index_of(nm) != -1;
 369 }
 370 
 371 ShenandoahNMethod* ShenandoahNMethodTable::at(int index) const {
 372   assert(index >= 0 && index < _index, "Out of bound");
 373   return _array[index];
 374 }
 375 
 376 int ShenandoahNMethodTable::index_of(nmethod* nm) const {
 377   for (int index = 0; index < length(); index ++) {
 378     if (_array[index]->nm() == nm) {
 379       return index;
 380     }
 381   }
 382   return -1;
 383 }
 384 
 385 void ShenandoahNMethodTable::remove(int idx) {
 386   shenandoah_assert_locked_or_safepoint(CodeCache_lock);
 387   assert(!_iteration_in_progress, "Can not happen");
 388   assert(_index >= 0 && _index <= _size, "Sanity");
 389 
 390   assert(idx >= 0 && idx < _index, "Out of bound");
 391   ShenandoahNMethod* snm = _array[idx];
 392 
 393   _index --;
 394   _array[idx] = _array[_index];
 395 
 396   delete snm;
 397 }
 398 
 399 void ShenandoahNMethodTable::wait_until_concurrent_iteration_done() {
 400   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
 401   while (iteration_in_progress()) {
 402     CodeCache_lock->wait_without_safepoint_check();
 403   }
 404 }
 405 
 406 void ShenandoahNMethodTable::append(ShenandoahNMethod* snm) {
 407   if (is_full()) {
 408     int new_size = 2 * _size;
 409     ShenandoahNMethod** old_table = _array;
 410 
 411     // Rebuild table and replace current one
 412     rebuild(new_size);
 413 
 414     // An iteration is in progress over early snapshot,
 415     // can not release the array until iteration is completed
 416     if (!iteration_in_progress()) {
 417       FREE_C_HEAP_ARRAY(ShenandoahNMethod*, old_table);
 418     }
 419   }
 420 
 421   _array[_index ++] = snm;
 422   assert(_index >= 0 && _index <= _size, "Sanity");
 423 }
 424 
 425 void ShenandoahNMethodTable::rebuild(int size) {
 426   ShenandoahNMethod** arr = NEW_C_HEAP_ARRAY(ShenandoahNMethod*, size, mtGC);
 427   for (int index = 0; index < _index; index ++) {
 428       arr[index] = _array[index];
 429   }
 430   _array = arr;
 431   _size = size;
 432 }
 433 
 434 ShenandoahNMethodTableSnapshot* ShenandoahNMethodTable::snapshot_for_iteration() {
 435   assert(!iteration_in_progress(), "Already in progress");
 436   _iteration_in_progress = true;
 437 
 438   return new ShenandoahNMethodTableSnapshot(this);
 439 }
 440 
 441 void ShenandoahNMethodTable::finish_iteration(ShenandoahNMethodTableSnapshot* snapshot) {
 442   assert(iteration_in_progress(), "Why we here?");
 443   assert(snapshot != NULL, "No snapshot");
 444   _iteration_in_progress = false;
 445 
 446   // Table has been rebuilt during iteration, free old table
 447   if (snapshot->_array != _array) {
 448     FREE_C_HEAP_ARRAY(ShenandoahNMethod*, snapshot->_array);
 449   }
 450   delete snapshot;
 451 }
 452 
 453 void ShenandoahNMethodTable::log_register_nmethod(nmethod* nm) {
 454   LogTarget(Debug, gc, nmethod) log;
 455   if (!log.is_enabled()) {
 456     return;
 457   }
 458 
 459   ResourceMark rm;
 460   log.print("Register NMethod: %s.%s [" PTR_FORMAT "] (%s)",
 461             nm->method()->method_holder()->external_name(),
 462             nm->method()->name()->as_C_string(),
 463             p2i(nm),
 464             nm->compiler_name());
 465 }
 466 
 467 void ShenandoahNMethodTable::log_unregister_nmethod(nmethod* nm) {
 468   LogTarget(Debug, gc, nmethod) log;
 469   if (!log.is_enabled()) {
 470     return;
 471   }
 472 
 473   ResourceMark rm;
 474   log.print("Unregister NMethod: %s.%s [" PTR_FORMAT "]",
 475             nm->method()->method_holder()->external_name(),
 476             nm->method()->name()->as_C_string(),
 477             p2i(nm));
 478 }
 479 
 480 void ShenandoahNMethodTable::log_flush_nmethod(nmethod* nm) {
 481   LogTarget(Debug, gc, nmethod) log;
 482   if (!log.is_enabled()) {
 483     return;
 484   }
 485 
 486   ResourceMark rm;
 487   log.print("Flush NMethod: (" PTR_FORMAT ")", p2i(nm));
 488 }
 489 
 490 #ifdef ASSERT
 491 void ShenandoahNMethodTable::assert_nmethods_alive_and_correct() {
 492   assert_locked_or_safepoint(CodeCache_lock);
 493 
 494   for (int index = 0; index < length(); index ++) {
 495     ShenandoahNMethod* m = _array[index];
 496     // Concurrent unloading may have dead nmethods to be cleaned by sweeper
 497     if (m->is_unregistered()) continue;
 498     m->assert_alive_and_correct();
 499   }
 500 }
 501 #endif
 502 
 503 ShenandoahNMethodTableSnapshot::ShenandoahNMethodTableSnapshot(ShenandoahNMethodTable* table) :
 504   _heap(ShenandoahHeap::heap()), _table(table), _array(table->_array), _length(table->_index), _claimed(0) {
 505 }
 506 
 507 void ShenandoahNMethodTableSnapshot::concurrent_nmethods_do(NMethodClosure* cl) {
 508   size_t stride = 256; // educated guess
 509 
 510   ShenandoahNMethod** list = _array;
 511   size_t max = (size_t)_length;
 512   while (_claimed < max) {
 513     size_t cur = Atomic::fetch_and_add(&_claimed, stride);
 514     size_t start = cur;
 515     size_t end = MIN2(cur + stride, max);
 516     if (start >= max) break;
 517 
 518     for (size_t idx = start; idx < end; idx++) {
 519       ShenandoahNMethod* data = list[idx];
 520       assert(data != NULL, "Should not be NULL");
 521       if (!data->is_unregistered()) {
 522         cl->do_nmethod(data->nm());
 523       }
 524     }
 525   }
 526 }
 527 
 528 ShenandoahConcurrentNMethodIterator::ShenandoahConcurrentNMethodIterator(ShenandoahNMethodTable* table) :
 529   _table(table), _table_snapshot(NULL) {
 530 }
 531 
 532 void ShenandoahConcurrentNMethodIterator::nmethods_do_begin() {
 533   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
 534   assert(ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 535          "Only for concurrent class unloading");
 536   _table_snapshot = _table->snapshot_for_iteration();
 537 }
 538 
 539 void ShenandoahConcurrentNMethodIterator::nmethods_do(NMethodClosure* cl) {
 540   assert(_table_snapshot != NULL, "Must first call nmethod_do_begin()");
 541   _table_snapshot->concurrent_nmethods_do(cl);
 542 }
 543 
 544 void ShenandoahConcurrentNMethodIterator::nmethods_do_end() {
 545   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
 546   assert(ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 547          "Only for concurrent class unloading");
 548   _table->finish_iteration(_table_snapshot);
 549   CodeCache_lock->notify_all();
 550 }