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