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 = _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     bool non_immed;
 263     detect_reloc_oops(nm(), check, non_immed);
 264     debug_stream.print_cr("check oops: %d", check.length());
 265     for (int i = 0; i < check.length(); i++) {
 266       debug_stream.print_cr("-> " PTR_FORMAT, p2i(check.at(i)));
 267     }
 268     fatal("Must match #detected: %d, #recorded: %d, #total: %d, begin: " PTR_FORMAT ", end: " PTR_FORMAT "\n%s",
 269           oops->length(), _oops_count, count, p2i(nm()->oops_begin()), p2i(nm()->oops_end()), debug_stream.as_string());
 270   }
 271 }
 272 
 273 void ShenandoahNMethod::assert_no_oops(nmethod* nm, bool allow_dead) {
 274   ShenandoahNMethodOopDetector detector;
 275   nm->oops_do(&detector, allow_dead);
 276   assert(detector.oops()->length() == 0, "Should not have oops");
 277 }
 278 #endif
 279 
 280 ShenandoahNMethodTable::ShenandoahNMethodTable() :
 281   _heap(ShenandoahHeap::heap()),
 282   _size(minSize),
 283   _index(0),
 284   _iteration_in_progress(false) {
 285   _array = NEW_C_HEAP_ARRAY(ShenandoahNMethod*, _size, mtGC);
 286 }
 287 
 288 ShenandoahNMethodTable::~ShenandoahNMethodTable() {
 289   assert(_array != NULL, "Sanity");
 290   FREE_C_HEAP_ARRAY(ShenandoahNMethod*, _array);
 291 }
 292 
 293 void ShenandoahNMethodTable::register_nmethod(nmethod* nm) {
 294   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
 295   assert(_index >= 0 && _index <= _size, "Sanity");
 296 
 297   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
 298   ShenandoahReentrantLocker data_locker(data != NULL ? data->lock() : NULL);
 299 
 300   if (data != NULL) {
 301     assert(contain(nm), "Must have been registered");
 302     assert(nm == data->nm(), "Must be same nmethod");
 303     data->update();
 304   } else {
 305     data = ShenandoahNMethod::for_nmethod(nm);
 306     if (data == NULL) {
 307       assert(!ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 308              "Only possible when concurrent class unloading is off");
 309       return;
 310     }
 311     ShenandoahNMethod::attach_gc_data(nm, data);
 312     ShenandoahLocker locker(&_lock);
 313     log_register_nmethod(nm);
 314     append(data);
 315   }
 316   // Disarm new nmethod
 317   ShenandoahNMethod::disarm_nmethod(nm);
 318 }
 319 
 320 void ShenandoahNMethodTable::unregister_nmethod(nmethod* nm) {
 321   assert_locked_or_safepoint(CodeCache_lock);
 322 
 323   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
 324   if (data == NULL) {
 325     assert(!ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 326            "Only possible when concurrent class unloading is off");
 327     ShenandoahNMethod::assert_no_oops(nm, true /*allow_dead*/);
 328     return;
 329   }
 330 
 331   if (Thread::current()->is_Code_cache_sweeper_thread()) {
 332     wait_until_concurrent_iteration_done();
 333   }
 334   log_unregister_nmethod(nm);
 335   ShenandoahLocker locker(&_lock);
 336   assert(contain(nm), "Must have been registered");
 337 
 338   ShenandoahReentrantLocker data_locker(data->lock());
 339   data->mark_unregistered();
 340 }
 341 
 342 void ShenandoahNMethodTable::flush_nmethod(nmethod* nm) {
 343   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
 344   assert(Thread::current()->is_Code_cache_sweeper_thread(), "Must from Sweep thread");
 345   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
 346   assert(data != NULL || !ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 347          "Only possible when concurrent class unloading is off");
 348   if (data == NULL) {
 349     ShenandoahNMethod::assert_no_oops(nm, true /*allow_dead*/);
 350     return;
 351   }
 352 
 353   // Can not alter the array when iteration is in progress
 354   wait_until_concurrent_iteration_done();
 355   log_flush_nmethod(nm);
 356 
 357   ShenandoahLocker locker(&_lock);
 358   int idx = index_of(nm);
 359   assert(idx >= 0 && idx < _index, "Invalid index");
 360   ShenandoahNMethod::attach_gc_data(nm, NULL);
 361   remove(idx);
 362 }
 363 
 364 bool ShenandoahNMethodTable::contain(nmethod* nm) const {
 365   return index_of(nm) != -1;
 366 }
 367 
 368 ShenandoahNMethod* ShenandoahNMethodTable::at(int index) const {
 369   assert(index >= 0 && index < _index, "Out of bound");
 370   return _array[index];
 371 }
 372 
 373 int ShenandoahNMethodTable::index_of(nmethod* nm) const {
 374   for (int index = 0; index < length(); index ++) {
 375     if (_array[index]->nm() == nm) {
 376       return index;
 377     }
 378   }
 379   return -1;
 380 }
 381 
 382 void ShenandoahNMethodTable::remove(int idx) {
 383   shenandoah_assert_locked_or_safepoint(CodeCache_lock);
 384   assert(!_iteration_in_progress, "Can not happen");
 385   assert(_index >= 0 && _index <= _size, "Sanity");
 386 
 387   assert(idx >= 0 && idx < _index, "Out of bound");
 388   ShenandoahNMethod* snm = _array[idx];
 389 
 390   _index --;
 391   _array[idx] = _array[_index];
 392 
 393   delete snm;
 394 }
 395 
 396 void ShenandoahNMethodTable::wait_until_concurrent_iteration_done() {
 397   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
 398   while (iteration_in_progress()) {
 399     CodeCache_lock->wait_without_safepoint_check();
 400   }
 401 }
 402 
 403 void ShenandoahNMethodTable::append(ShenandoahNMethod* snm) {
 404   if (is_full()) {
 405     int new_size = 2 * _size;
 406     ShenandoahNMethod** old_table = _array;
 407 
 408     // Rebuild table and replace current one
 409     rebuild(new_size);
 410 
 411     // An iteration is in progress over early snapshot,
 412     // can not release the array until iteration is completed
 413     if (!iteration_in_progress()) {
 414       FREE_C_HEAP_ARRAY(ShenandoahNMethod*, old_table);
 415     }
 416   }
 417 
 418   _array[_index ++] = snm;
 419   assert(_index >= 0 && _index <= _size, "Sanity");
 420 }
 421 
 422 void ShenandoahNMethodTable::rebuild(int size) {
 423   ShenandoahNMethod** arr = NEW_C_HEAP_ARRAY(ShenandoahNMethod*, size, mtGC);
 424   for (int index = 0; index < _index; index ++) {
 425       arr[index] = _array[index];
 426   }
 427   _array = arr;
 428   _size = size;
 429 }
 430 
 431 ShenandoahNMethodTableSnapshot* ShenandoahNMethodTable::snapshot_for_iteration() {
 432   assert(!iteration_in_progress(), "Already in progress");
 433   _iteration_in_progress = true;
 434 
 435   return new ShenandoahNMethodTableSnapshot(this);
 436 }
 437 
 438 void ShenandoahNMethodTable::finish_iteration(ShenandoahNMethodTableSnapshot* snapshot) {
 439   assert(iteration_in_progress(), "Why we here?");
 440   assert(snapshot != NULL, "No snapshot");
 441   _iteration_in_progress = false;
 442 
 443   // Table has been rebuilt during iteration, free old table
 444   if (snapshot->_array != _array) {
 445     FREE_C_HEAP_ARRAY(ShenandoahNMethod*, snapshot->_array);
 446   }
 447   delete snapshot;
 448 }
 449 
 450 void ShenandoahNMethodTable::log_register_nmethod(nmethod* nm) {
 451   LogTarget(Debug, gc, nmethod) log;
 452   if (!log.is_enabled()) {
 453     return;
 454   }
 455 
 456   ResourceMark rm;
 457   log.print("Register NMethod: %s.%s [" PTR_FORMAT "] (%s)",
 458             nm->method()->method_holder()->external_name(),
 459             nm->method()->name()->as_C_string(),
 460             p2i(nm),
 461             nm->compiler_name());
 462 }
 463 
 464 void ShenandoahNMethodTable::log_unregister_nmethod(nmethod* nm) {
 465   LogTarget(Debug, gc, nmethod) log;
 466   if (!log.is_enabled()) {
 467     return;
 468   }
 469 
 470   ResourceMark rm;
 471   log.print("Unregister NMethod: %s.%s [" PTR_FORMAT "]",
 472             nm->method()->method_holder()->external_name(),
 473             nm->method()->name()->as_C_string(),
 474             p2i(nm));
 475 }
 476 
 477 void ShenandoahNMethodTable::log_flush_nmethod(nmethod* nm) {
 478   LogTarget(Debug, gc, nmethod) log;
 479   if (!log.is_enabled()) {
 480     return;
 481   }
 482 
 483   ResourceMark rm;
 484   log.print("Flush NMethod: (" PTR_FORMAT ")", p2i(nm));
 485 }
 486 
 487 #ifdef ASSERT
 488 void ShenandoahNMethodTable::assert_nmethods_alive_and_correct() {
 489   assert_locked_or_safepoint(CodeCache_lock);
 490 
 491   for (int index = 0; index < length(); index ++) {
 492     ShenandoahNMethod* m = _array[index];
 493     // Concurrent unloading may have dead nmethods to be cleaned by sweeper
 494     if (m->is_unregistered()) continue;
 495     m->assert_alive_and_correct();
 496   }
 497 }
 498 #endif
 499 
 500 ShenandoahNMethodTableSnapshot::ShenandoahNMethodTableSnapshot(ShenandoahNMethodTable* table) :
 501   _heap(ShenandoahHeap::heap()), _table(table), _array(table->_array), _length(table->_index), _claimed(0) {
 502 }
 503 
 504 void ShenandoahNMethodTableSnapshot::concurrent_nmethods_do(NMethodClosure* cl) {
 505   size_t stride = 256; // educated guess
 506 
 507   ShenandoahNMethod** list = _array;
 508   size_t max = (size_t)_length;
 509   while (_claimed < max) {
 510     size_t cur = Atomic::fetch_and_add(&_claimed, stride);
 511     size_t start = cur;
 512     size_t end = MIN2(cur + stride, max);
 513     if (start >= max) break;
 514 
 515     for (size_t idx = start; idx < end; idx++) {
 516       ShenandoahNMethod* data = list[idx];
 517       assert(data != NULL, "Should not be NULL");
 518       if (!data->is_unregistered()) {
 519         cl->do_nmethod(data->nm());
 520       }
 521     }
 522   }
 523 }
 524 
 525 ShenandoahConcurrentNMethodIterator::ShenandoahConcurrentNMethodIterator(ShenandoahNMethodTable* table) :
 526   _table(table), _table_snapshot(NULL) {
 527 }
 528 
 529 void ShenandoahConcurrentNMethodIterator::nmethods_do_begin() {
 530   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
 531   assert(ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 532          "Only for concurrent class unloading");
 533   _table_snapshot = _table->snapshot_for_iteration();
 534 }
 535 
 536 void ShenandoahConcurrentNMethodIterator::nmethods_do(NMethodClosure* cl) {
 537   assert(_table_snapshot != NULL, "Must first call nmethod_do_begin()");
 538   _table_snapshot->concurrent_nmethods_do(cl);
 539 }
 540 
 541 void ShenandoahConcurrentNMethodIterator::nmethods_do_end() {
 542   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
 543   assert(ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 544          "Only for concurrent class unloading");
 545   _table->finish_iteration(_table_snapshot);
 546   CodeCache_lock->notify_all();
 547 }