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     if (r->oop_value() != NULL) {
 149       // Non-NULL immediate oop found. NULL oops can safely be
 150       // ignored since the method will be re-registered if they
 151       // are later patched to be non-NULL.
 152       oops.push(r->oop_addr());
 153     }
 154   }
 155 }
 156 
 157 ShenandoahNMethod* ShenandoahNMethod::for_nmethod(nmethod* nm) {
 158   ResourceMark rm;
 159   bool non_immediate_oops = false;
 160   GrowableArray<oop*> oops;
 161 
 162   detect_reloc_oops(nm, oops, non_immediate_oops);
 163 
 164   // No embedded oops
 165   if(!ShenandoahConcurrentRoots::can_do_concurrent_class_unloading() &&
 166     oops.is_empty() && nm->oops_begin() >= nm->oops_end()) {
 167     return NULL;
 168   }
 169 
 170   return new ShenandoahNMethod(nm, oops, non_immediate_oops);
 171 }
 172 
 173 void ShenandoahNMethod::heal_nmethod(nmethod* nm) {
 174   assert(ShenandoahHeap::heap()->is_concurrent_root_in_progress(), "Only this phase");
 175   ShenandoahNMethod* data = gc_data(nm);
 176   assert(data != NULL, "Sanity");
 177   assert(data->lock()->owned_by_self(), "Must hold the lock");
 178 
 179   ShenandoahEvacOOMScope evac_scope;
 180   ShenandoahEvacuateUpdateRootsClosure cl;
 181   data->oops_do(&cl, true /*fix relocation*/);
 182 }
 183 
 184 #ifdef ASSERT
 185 void ShenandoahNMethod::assert_alive_and_correct() {
 186   assert(_nm->is_alive(), "only alive nmethods here");
 187   ShenandoahHeap* heap = ShenandoahHeap::heap();
 188   for (int c = 0; c < _oops_count; c++) {
 189     oop *loc = _oops[c];
 190     assert(_nm->code_contains((address) loc) || _nm->oops_contains(loc), "nmethod should contain the oop*");
 191     oop o = RawAccess<>::oop_load(loc);
 192     shenandoah_assert_correct_except(loc, o, o == NULL || heap->is_full_gc_move_in_progress());
 193   }
 194 
 195   oop* const begin = _nm->oops_begin();
 196   oop* const end = _nm->oops_end();
 197   for (oop* p = begin; p < end; p++) {
 198     if (*p != Universe::non_oop_word()) {
 199       oop o = RawAccess<>::oop_load(p);
 200       shenandoah_assert_correct_except(p, o, o == NULL || heap->is_full_gc_move_in_progress());
 201     }
 202   }
 203 }
 204 
 205 class ShenandoahNMethodOopDetector : public OopClosure {
 206 private:
 207   ResourceMark rm; // For growable array allocation below.
 208   GrowableArray<oop*> _oops;
 209 
 210 public:
 211   ShenandoahNMethodOopDetector() : _oops(10) {};
 212 
 213   void do_oop(oop* o) {
 214     _oops.append(o);
 215   }
 216   void do_oop(narrowOop* o) {
 217     fatal("NMethods should not have compressed oops embedded.");
 218   }
 219 
 220   GrowableArray<oop*>* oops() {
 221     return &_oops;
 222   }
 223 
 224   bool has_oops() {
 225     return !_oops.is_empty();
 226   }
 227 };
 228 
 229 void ShenandoahNMethod::assert_same_oops(bool allow_dead) {
 230   ShenandoahNMethodOopDetector detector;
 231   nm()->oops_do(&detector, allow_dead);
 232 
 233   GrowableArray<oop*>* oops = detector.oops();
 234 
 235   assert(oops->length() == oop_count(), "Must match");
 236 
 237   for (int index = 0; index < _oops_count; index ++) {
 238     assert(oops->contains(_oops[index]), "Must contain this oop");
 239   }
 240 
 241   for (oop* p = nm()->oops_begin(); p < nm()->oops_end(); p ++) {
 242     assert(oops->contains(p), "Must contain this oop");
 243   }
 244 }
 245 
 246 void ShenandoahNMethod::assert_no_oops(nmethod* nm, bool allow_dead) {
 247   ShenandoahNMethodOopDetector detector;
 248   nm->oops_do(&detector, allow_dead);
 249   assert(detector.oops()->length() == 0, "Should not have oops");
 250 }
 251 #endif
 252 
 253 ShenandoahNMethodTable::ShenandoahNMethodTable() :
 254   _heap(ShenandoahHeap::heap()),
 255   _size(minSize),
 256   _index(0),
 257   _iteration_in_progress(false) {
 258   _array = NEW_C_HEAP_ARRAY(ShenandoahNMethod*, _size, mtGC);
 259 }
 260 
 261 ShenandoahNMethodTable::~ShenandoahNMethodTable() {
 262   assert(_array != NULL, "Sanity");
 263   FREE_C_HEAP_ARRAY(ShenandoahNMethod*, _array);
 264 }
 265 
 266 void ShenandoahNMethodTable::register_nmethod(nmethod* nm) {
 267   assert(CodeCache_lock->owned_by_self(), "Must have CodeCache_lock held");
 268   assert(_index >= 0 && _index <= _size, "Sanity");
 269 
 270   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
 271   ShenandoahReentrantLocker data_locker(data != NULL ? data->lock() : NULL);
 272 
 273   if (data != NULL) {
 274     assert(contain(nm), "Must have been registered");
 275     data->update();
 276   } else {
 277     data = ShenandoahNMethod::for_nmethod(nm);
 278     if (data == NULL) {
 279       assert(!ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 280              "Only possible when concurrent class unloading is off");
 281       return;
 282     }
 283     ShenandoahNMethod::attach_gc_data(nm, data);
 284     ShenandoahLocker locker(&_lock);
 285     log_register_nmethod(nm);
 286     append(data);
 287   }
 288   // Disarm new nmethod
 289   ShenandoahNMethod::disarm_nmethod(nm);
 290 }
 291 
 292 void ShenandoahNMethodTable::unregister_nmethod(nmethod* nm) {
 293   assert_locked_or_safepoint(CodeCache_lock);
 294 
 295   ShenandoahNMethod* data = ShenandoahNMethod::gc_data(nm);
 296   if (data == NULL) {
 297     assert(!ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 298            "Only possible when concurrent class unloading is off");
 299     ShenandoahNMethod::assert_no_oops(nm, true /*allow_dead*/);
 300     return;
 301   }
 302 
 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 || !ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 319          "Only possible when concurrent class unloading is off");
 320   if (data == NULL) {
 321     ShenandoahNMethod::assert_no_oops(nm, true /*allow_dead*/);
 322     return;
 323   }
 324 
 325   // Can not alter the array when iteration is in progress
 326   wait_until_concurrent_iteration_done();
 327   log_flush_nmethod(nm);
 328 
 329   ShenandoahLocker locker(&_lock);
 330   int idx = index_of(nm);
 331   assert(idx >= 0 && idx < _index, "Invalid index");
 332   ShenandoahNMethod::attach_gc_data(nm, NULL);
 333   remove(idx);
 334 }
 335 
 336 bool ShenandoahNMethodTable::contain(nmethod* nm) const {
 337   return index_of(nm) != -1;
 338 }
 339 
 340 ShenandoahNMethod* ShenandoahNMethodTable::at(int index) const {
 341   assert(index >= 0 && index < _index, "Out of bound");
 342   return _array[index];
 343 }
 344 
 345 int ShenandoahNMethodTable::index_of(nmethod* nm) const {
 346   for (int index = 0; index < length(); index ++) {
 347     if (_array[index]->nm() == nm) {
 348       return index;
 349     }
 350   }
 351   return -1;
 352 }
 353 
 354 void ShenandoahNMethodTable::remove(int idx) {
 355   shenandoah_assert_locked_or_safepoint(CodeCache_lock);
 356   assert(!_iteration_in_progress, "Can not happen");
 357   assert(_index >= 0 && _index <= _size, "Sanity");
 358 
 359   assert(idx >= 0 && idx < _index, "Out of bound");
 360   ShenandoahNMethod* snm = _array[idx];
 361 
 362   _index --;
 363   _array[idx] = _array[_index];
 364 
 365   delete snm;
 366 }
 367 
 368 void ShenandoahNMethodTable::wait_until_concurrent_iteration_done() {
 369   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
 370   while (iteration_in_progress()) {
 371     CodeCache_lock->wait_without_safepoint_check();
 372   }
 373 }
 374 
 375 void ShenandoahNMethodTable::append(ShenandoahNMethod* snm) {
 376   if (is_full()) {
 377     int new_size = 2 * _size;
 378     ShenandoahNMethod** old_table = _array;
 379 
 380     // Rebuild table and replace current one
 381     rebuild(new_size);
 382 
 383     // An iteration is in progress over early snapshot,
 384     // can not release the array until iteration is completed
 385     if (!iteration_in_progress()) {
 386       FREE_C_HEAP_ARRAY(ShenandoahNMethod*, old_table);
 387     }
 388   }
 389 
 390   _array[_index ++] = snm;
 391   assert(_index >= 0 && _index <= _size, "Sanity");
 392 }
 393 
 394 void ShenandoahNMethodTable::rebuild(int size) {
 395   ShenandoahNMethod** arr = NEW_C_HEAP_ARRAY(ShenandoahNMethod*, size, mtGC);
 396   for (int index = 0; index < _index; index ++) {
 397       arr[index] = _array[index];
 398   }
 399   _array = arr;
 400   _size = size;
 401 }
 402 
 403 ShenandoahNMethodTableSnapshot* ShenandoahNMethodTable::snapshot_for_iteration() {
 404   assert(!iteration_in_progress(), "Already in progress");
 405   _iteration_in_progress = true;
 406 
 407   return new ShenandoahNMethodTableSnapshot(this);
 408 }
 409 
 410 void ShenandoahNMethodTable::finish_iteration(ShenandoahNMethodTableSnapshot* snapshot) {
 411   assert(iteration_in_progress(), "Why we here?");
 412   assert(snapshot != NULL, "No snapshot");
 413   _iteration_in_progress = false;
 414 
 415   // Table has been rebuilt during iteration, free old table
 416   if (snapshot->_array != _array) {
 417     FREE_C_HEAP_ARRAY(ShenandoahNMethod*, snapshot->_array);
 418   }
 419   delete snapshot;
 420 }
 421 
 422 void ShenandoahNMethodTable::log_register_nmethod(nmethod* nm) {
 423   LogTarget(Debug, gc, nmethod) log;
 424   if (!log.is_enabled()) {
 425     return;
 426   }
 427 
 428   ResourceMark rm;
 429   log.print("Register NMethod: %s.%s [" PTR_FORMAT "] (%s)",
 430             nm->method()->method_holder()->external_name(),
 431             nm->method()->name()->as_C_string(),
 432             p2i(nm),
 433             nm->compiler_name());
 434 }
 435 
 436 void ShenandoahNMethodTable::log_unregister_nmethod(nmethod* nm) {
 437   LogTarget(Debug, gc, nmethod) log;
 438   if (!log.is_enabled()) {
 439     return;
 440   }
 441 
 442   ResourceMark rm;
 443   log.print("Unregister NMethod: %s.%s [" PTR_FORMAT "]",
 444             nm->method()->method_holder()->external_name(),
 445             nm->method()->name()->as_C_string(),
 446             p2i(nm));
 447 }
 448 
 449 void ShenandoahNMethodTable::log_flush_nmethod(nmethod* nm) {
 450   LogTarget(Debug, gc, nmethod) log;
 451   if (!log.is_enabled()) {
 452     return;
 453   }
 454 
 455   ResourceMark rm;
 456   log.print("Flush NMethod: (" PTR_FORMAT ")", p2i(nm));
 457 }
 458 
 459 #ifdef ASSERT
 460 void ShenandoahNMethodTable::assert_nmethods_alive_and_correct() {
 461   assert_locked_or_safepoint(CodeCache_lock);
 462 
 463   for (int index = 0; index < length(); index ++) {
 464     ShenandoahNMethod* m = _array[index];
 465     // Concurrent unloading may have dead nmethods to be cleaned by sweeper
 466     if (m->is_unregistered()) continue;
 467     m->assert_alive_and_correct();
 468   }
 469 }
 470 #endif
 471 
 472 ShenandoahNMethodTableSnapshot::ShenandoahNMethodTableSnapshot(ShenandoahNMethodTable* table) :
 473   _heap(ShenandoahHeap::heap()), _table(table), _array(table->_array), _length(table->_index), _claimed(0) {
 474 }
 475 
 476 void ShenandoahNMethodTableSnapshot::concurrent_nmethods_do(NMethodClosure* cl) {
 477   size_t stride = 256; // educated guess
 478 
 479   ShenandoahNMethod** list = _array;
 480   size_t max = (size_t)_length;
 481   while (_claimed < max) {
 482     size_t cur = Atomic::add(&_claimed, stride) - stride;
 483     size_t start = cur;
 484     size_t end = MIN2(cur + stride, max);
 485     if (start >= max) break;
 486 
 487     for (size_t idx = start; idx < end; idx++) {
 488       ShenandoahNMethod* data = list[idx];
 489       assert(data != NULL, "Should not be NULL");
 490       if (!data->is_unregistered()) {
 491         cl->do_nmethod(data->nm());
 492       }
 493     }
 494   }
 495 }
 496 
 497 ShenandoahConcurrentNMethodIterator::ShenandoahConcurrentNMethodIterator(ShenandoahNMethodTable* table) :
 498   _table(table), _table_snapshot(NULL) {
 499 }
 500 
 501 void ShenandoahConcurrentNMethodIterator::nmethods_do_begin() {
 502   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
 503   assert(ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 504          "Only for concurrent class unloading");
 505   _table_snapshot = _table->snapshot_for_iteration();
 506 }
 507 
 508 void ShenandoahConcurrentNMethodIterator::nmethods_do(NMethodClosure* cl) {
 509   assert(_table_snapshot != NULL, "Must first call nmethod_do_begin()");
 510   _table_snapshot->concurrent_nmethods_do(cl);
 511 }
 512 
 513 void ShenandoahConcurrentNMethodIterator::nmethods_do_end() {
 514   assert(CodeCache_lock->owned_by_self(), "Lock must be held");
 515   assert(ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(),
 516          "Only for concurrent class unloading");
 517   _table->finish_iteration(_table_snapshot);
 518   CodeCache_lock->notify_all();
 519 }