1 /*
   2  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. 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 #include "code/codeCache.hpp"
  27 #include "code/compiledIC.hpp"
  28 #include "code/icBuffer.hpp"
  29 #include "code/nmethod.hpp"
  30 #include "compiler/compileBroker.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "oops/method.hpp"
  33 #include "runtime/atomic.hpp"
  34 #include "runtime/compilationPolicy.hpp"
  35 #include "runtime/mutexLocker.hpp"
  36 #include "runtime/os.hpp"
  37 #include "runtime/sweeper.hpp"
  38 #include "runtime/vm_operations.hpp"
  39 #include "trace/tracing.hpp"
  40 #include "utilities/events.hpp"
  41 #include "utilities/xmlstream.hpp"
  42 
  43 #ifdef ASSERT
  44 
  45 #define SWEEP(nm) record_sweep(nm, __LINE__)
  46 // Sweeper logging code
  47 class SweeperRecord {
  48  public:
  49   int traversal;
  50   int invocation;
  51   int compile_id;
  52   long traversal_mark;
  53   int state;
  54   const char* kind;
  55   address vep;
  56   address uep;
  57   int line;
  58 
  59   void print() {
  60       tty->print_cr("traversal = %d invocation = %d compile_id = %d %s uep = " PTR_FORMAT " vep = "
  61                     PTR_FORMAT " state = %d traversal_mark %d line = %d",
  62                     traversal,
  63                     invocation,
  64                     compile_id,
  65                     kind == NULL ? "" : kind,
  66                     uep,
  67                     vep,
  68                     state,
  69                     traversal_mark,
  70                     line);
  71   }
  72 };
  73 
  74 static int _sweep_index = 0;
  75 static SweeperRecord* _records = NULL;
  76 
  77 void NMethodSweeper::report_events(int id, address entry) {
  78   if (_records != NULL) {
  79     for (int i = _sweep_index; i < SweeperLogEntries; i++) {
  80       if (_records[i].uep == entry ||
  81           _records[i].vep == entry ||
  82           _records[i].compile_id == id) {
  83         _records[i].print();
  84       }
  85     }
  86     for (int i = 0; i < _sweep_index; i++) {
  87       if (_records[i].uep == entry ||
  88           _records[i].vep == entry ||
  89           _records[i].compile_id == id) {
  90         _records[i].print();
  91       }
  92     }
  93   }
  94 }
  95 
  96 void NMethodSweeper::report_events() {
  97   if (_records != NULL) {
  98     for (int i = _sweep_index; i < SweeperLogEntries; i++) {
  99       // skip empty records
 100       if (_records[i].vep == NULL) continue;
 101       _records[i].print();
 102     }
 103     for (int i = 0; i < _sweep_index; i++) {
 104       // skip empty records
 105       if (_records[i].vep == NULL) continue;
 106       _records[i].print();
 107     }
 108   }
 109 }
 110 
 111 void NMethodSweeper::record_sweep(nmethod* nm, int line) {
 112   if (_records != NULL) {
 113     _records[_sweep_index].traversal = _traversals;
 114     _records[_sweep_index].traversal_mark = nm->_stack_traversal_mark;
 115     _records[_sweep_index].invocation = _invocations;
 116     _records[_sweep_index].compile_id = nm->compile_id();
 117     _records[_sweep_index].kind = nm->compile_kind();
 118     _records[_sweep_index].state = nm->_state;
 119     _records[_sweep_index].vep = nm->verified_entry_point();
 120     _records[_sweep_index].uep = nm->entry_point();
 121     _records[_sweep_index].line = line;
 122 
 123     _sweep_index = (_sweep_index + 1) % SweeperLogEntries;
 124   }
 125 }
 126 #else
 127 #define SWEEP(nm)
 128 #endif
 129 
 130 nmethod*  NMethodSweeper::_current_nmethod = NULL; // Current nmethod
 131 int       NMethodSweeper::_current_type    = 0;    // Current CodeBlobType
 132 long      NMethodSweeper::_traversals      = 0;    // Nof. stack traversals performed
 133 int       NMethodSweeper::_seen            = 0;    // Nof. nmethods we have currently processed in current pass of CodeCache
 134 int       NMethodSweeper::_flushed_count   = 0;    // Nof. nmethods flushed in current sweep
 135 int       NMethodSweeper::_zombified_count = 0;    // Nof. nmethods made zombie in current sweep
 136 int       NMethodSweeper::_marked_count    = 0;    // Nof. nmethods marked for reclaim in current sweep
 137 
 138 volatile int NMethodSweeper::_invocations   = 0; // Nof. invocations left until we are completed with this pass
 139 volatile int NMethodSweeper::_sweep_started = 0; // Whether a sweep is in progress.
 140 
 141 jint      NMethodSweeper::_locked_seen               = 0;
 142 jint      NMethodSweeper::_not_entrant_seen_on_stack = 0;
 143 bool      NMethodSweeper::_request_mark_phase        = false;
 144 
 145 int       NMethodSweeper::_total_nof_methods_reclaimed = 0;
 146 jlong     NMethodSweeper::_total_time_sweeping         = 0;
 147 jlong     NMethodSweeper::_total_time_this_sweep       = 0;
 148 jlong     NMethodSweeper::_peak_sweep_time             = 0;
 149 jlong     NMethodSweeper::_peak_sweep_fraction_time    = 0;
 150 int       NMethodSweeper::_hotness_counter_reset_val   = 0;
 151 
 152 
 153 class MarkActivationClosure: public CodeBlobClosure {
 154 public:
 155   virtual void do_code_blob(CodeBlob* cb) {
 156     if (cb->is_nmethod()) {
 157       nmethod* nm = (nmethod*)cb;
 158       nm->set_hotness_counter(NMethodSweeper::hotness_counter_reset_val());
 159       // If we see an activation belonging to a non_entrant nmethod, we mark it.
 160       if (nm->is_not_entrant()) {
 161         nm->mark_as_seen_on_stack();
 162       }
 163     }
 164   }
 165 };
 166 static MarkActivationClosure mark_activation_closure;
 167 
 168 class SetHotnessClosure: public CodeBlobClosure {
 169 public:
 170   virtual void do_code_blob(CodeBlob* cb) {
 171     if (cb->is_nmethod()) {
 172       nmethod* nm = (nmethod*)cb;
 173       nm->set_hotness_counter(NMethodSweeper::hotness_counter_reset_val());
 174     }
 175   }
 176 };
 177 static SetHotnessClosure set_hotness_closure;
 178 
 179 
 180 int NMethodSweeper::hotness_counter_reset_val() {
 181   if (_hotness_counter_reset_val == 0) {
 182     _hotness_counter_reset_val = (ReservedCodeCacheSize < M) ? 1 : (ReservedCodeCacheSize / M) * 2;
 183   }
 184   return _hotness_counter_reset_val;
 185 }
 186 bool NMethodSweeper::sweep_in_progress() {
 187   return (_current_nmethod != NULL);
 188 }
 189 
 190 // Scans the stacks of all Java threads and marks activations of not-entrant methods.
 191 // No need to synchronize access, since 'mark_active_nmethods' is always executed at a
 192 // safepoint.
 193 void NMethodSweeper::mark_active_nmethods() {
 194   assert(SafepointSynchronize::is_at_safepoint(), "must be executed at a safepoint");
 195   // If we do not want to reclaim not-entrant or zombie methods there is no need
 196   // to scan stacks
 197   if (!MethodFlushing) {
 198     return;
 199   }
 200 
 201   // Check for restart
 202   assert(CodeCache::find_blob_unsafe(_current_nmethod) == _current_nmethod, "Sweeper nmethod cached state invalid");
 203   if (!sweep_in_progress() && need_marking_phase()) {
 204     _seen                   = 0;
 205     _invocations            = NmethodSweepFraction;
 206     _current_nmethod        = (nmethod*)CodeCache::first_blob(CodeBlobType::MethodNoProfile);
 207     _current_type           = CodeBlobType::MethodNoProfile;
 208     _traversals            += 1;
 209     _total_time_this_sweep  = 0;
 210 
 211     if (PrintMethodFlushing) {
 212       tty->print_cr("### Sweep: stack traversal %d", _traversals);
 213     }
 214     Threads::nmethods_do(&mark_activation_closure);
 215 
 216     // reset the flags since we started a scan from the beginning.
 217     reset_nmethod_marking();
 218     _locked_seen = 0;
 219     _not_entrant_seen_on_stack = 0;
 220   } else {
 221     // Only set hotness counter
 222     Threads::nmethods_do(&set_hotness_closure);
 223   }
 224 
 225   OrderAccess::storestore();
 226 }
 227 
 228 void NMethodSweeper::possibly_sweep() {
 229   assert(JavaThread::current()->thread_state() == _thread_in_vm, "must run in vm mode");
 230   if (!MethodFlushing || !sweep_in_progress()) {
 231     return;
 232   }
 233 
 234   if (_invocations > 0) {
 235     // Only one thread at a time will sweep
 236     jint old = Atomic::cmpxchg( 1, &_sweep_started, 0 );
 237     if (old != 0) {
 238       return;
 239     }
 240 #ifdef ASSERT
 241     if (LogSweeper && _records == NULL) {
 242       // Create the ring buffer for the logging code
 243       _records = NEW_C_HEAP_ARRAY(SweeperRecord, SweeperLogEntries, mtGC);
 244       memset(_records, 0, sizeof(SweeperRecord) * SweeperLogEntries);
 245     }
 246 #endif
 247     if (_invocations > 0) {
 248       sweep_code_cache();
 249       _invocations--;
 250     }
 251     _sweep_started = 0;
 252   }
 253 }
 254 
 255 void NMethodSweeper::sweep_code_cache() {

 256   jlong sweep_start_counter = os::elapsed_counter();
 257 
 258   _flushed_count   = 0;
 259   _zombified_count = 0;
 260   _marked_count    = 0;
 261 
 262   if (PrintMethodFlushing && Verbose) {
 263     tty->print_cr("### Sweep at %d out of %d. Invocations left: %d", _seen, CodeCache::nof_nmethods(), _invocations);
 264   }
 265 
 266   if (!CompileBroker::should_compile_new_jobs()) {
 267     // If we have turned off compilations we might as well do full sweeps
 268     // in order to reach the clean state faster. Otherwise the sleeping compiler
 269     // threads will slow down sweeping.
 270     _invocations = 1;
 271   }
 272 
 273   // We want to visit all nmethods after NmethodSweepFraction
 274   // invocations so divide the remaining number of nmethods by the
 275   // remaining number of invocations.  This is only an estimate since
 276   // the number of nmethods changes during the sweep so the final
 277   // stage must iterate until it there are no more nmethods.
 278   int todo = (CodeCache::nof_nmethods() - _seen) / _invocations;
 279   int swept_count = 0;
 280 
 281 
 282   assert(!SafepointSynchronize::is_at_safepoint(), "should not be in safepoint when we get here");
 283   assert(!CodeCache_lock->owned_by_self(), "just checking");
 284 
 285   int freed_memory = 0;
 286   {
 287     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 288 
 289     // Sweep non-profiled and profiled nmethods
 290     while (_current_type <= CodeBlobType::MethodProfile) {
 291 
 292       // The last invocation iterates until there are no more nmethods
 293       while ((swept_count < todo || _invocations == 1) && _current_nmethod != NULL) {
 294         swept_count++;
 295         if (SafepointSynchronize::is_synchronizing()) { // Safepoint request
 296           if (PrintMethodFlushing && Verbose) {
 297             tty->print_cr("### Sweep at %d out of %d, invocation: %d, yielding to safepoint", _seen, CodeCache::nof_nmethods(), _invocations);
 298           }
 299           MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 300 
 301           assert(Thread::current()->is_Java_thread(), "should be java thread");
 302           JavaThread* thread = (JavaThread*)Thread::current();
 303           ThreadBlockInVM tbivm(thread);
 304           thread->java_suspend_self();
 305         }
 306         // Since we will give up the CodeCache_lock, always skip ahead
 307         // to the next nmethod.  Other blobs can be deleted by other
 308         // threads but nmethods are only reclaimed by the sweeper.
 309         nmethod* next = (nmethod*)CodeCache::next_blob(_current_nmethod, _current_type);
 310 
 311         // Now ready to process nmethod and give up CodeCache_lock
 312         {
 313           MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 314           process_nmethod(_current_nmethod, _current_type);
 315         }
 316         _seen++;
 317         _current_nmethod = next;
 318       }
 319 
 320       while (_current_nmethod == NULL && _current_type < CodeBlobType::MethodProfile) {
 321         // We reached the last method of the type
 322         // Go to next type that has methods available
 323         _current_type++;
 324         _current_nmethod = (nmethod*)CodeCache::first_blob(_current_type);
 325       }
 326 
 327       if ((swept_count >= todo && _invocations > 1) || _current_nmethod == NULL) {
 328         // We processed enough methods for this invocation
 329         break;
 330       }
 331     }
 332   }
 333 
 334   assert(_invocations > 1 || _current_nmethod == NULL, "must have scanned the whole cache");
 335 
 336   if (!sweep_in_progress() && !need_marking_phase() && (_locked_seen || _not_entrant_seen_on_stack)) {
 337     // we've completed a scan without making progress but there were
 338     // nmethods we were unable to process either because they were
 339     // locked or were still on stack. We don't have to aggressively
 340     // clean them up so just stop scanning. We could scan once more
 341     // but that complicates the control logic and it's unlikely to
 342     // matter much.
 343     if (PrintMethodFlushing) {
 344       tty->print_cr("### Couldn't make progress on some nmethods so stopping sweep");
 345     }
 346   }
 347 
 348   jlong sweep_end_counter = os::elapsed_counter();
 349   jlong sweep_time = sweep_end_counter - sweep_start_counter;
 350   _total_time_sweeping  += sweep_time;
 351   _total_time_this_sweep += sweep_time;
 352   _peak_sweep_fraction_time = MAX2(sweep_time, _peak_sweep_fraction_time);
 353   _total_nof_methods_reclaimed += _flushed_count;
 354 
 355   EventSweepCodeCache event(UNTIMED);
 356   if (event.should_commit()) {
 357     event.set_starttime(sweep_start_counter);
 358     event.set_endtime(sweep_end_counter);
 359     event.set_sweepIndex(_traversals);
 360     event.set_sweepFractionIndex(NmethodSweepFraction - _invocations + 1);
 361     event.set_sweptCount(swept_count);
 362     event.set_flushedCount(_flushed_count);
 363     event.set_markedCount(_marked_count);
 364     event.set_zombifiedCount(_zombified_count);
 365     event.commit();
 366   }
 367 
 368 #ifdef ASSERT
 369   if(PrintMethodFlushing) {
 370     tty->print_cr("### sweeper:      sweep time(%d): " INT64_FORMAT, _invocations, (jlong)sweep_time);
 371   }
 372 #endif
 373 
 374   if (_invocations == 1) {
 375     _peak_sweep_time = MAX2(_peak_sweep_time, _total_time_this_sweep);
 376     log_sweep("finished");
 377   }














 378 }
 379 
 380 class NMethodMarker: public StackObj {
 381  private:
 382   CompilerThread* _thread;
 383  public:
 384   NMethodMarker(nmethod* nm) {
 385     _thread = CompilerThread::current();
 386     if (!nm->is_zombie() && !nm->is_unloaded()) {
 387       // Only expose live nmethods for scanning
 388       _thread->set_scanned_nmethod(nm);
 389     }
 390   }
 391   ~NMethodMarker() {
 392     _thread->set_scanned_nmethod(NULL);
 393   }
 394 };
 395 
 396 void NMethodSweeper::release_nmethod(nmethod *nm) {
 397   // Clean up any CompiledICHolders
 398   {
 399     ResourceMark rm;
 400     MutexLocker ml_patch(CompiledIC_lock);
 401     RelocIterator iter(nm);
 402     while (iter.next()) {
 403       if (iter.type() == relocInfo::virtual_call_type) {
 404         CompiledIC::cleanup_call_site(iter.virtual_call_reloc());
 405       }
 406     }
 407   }
 408 
 409   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 410   nm->flush();
 411 }
 412 
 413 int NMethodSweeper::process_nmethod(nmethod *nm, int code_blob_type) {
 414   assert(!CodeCache_lock->owned_by_self(), "just checking");
 415 
 416   int freed_memory = 0;
 417   // Make sure this nmethod doesn't get unloaded during the scan,
 418   // since safepoints may happen during acquired below locks.
 419   NMethodMarker nmm(nm);
 420   SWEEP(nm);
 421 
 422   // Skip methods that are currently referenced by the VM
 423   if (nm->is_locked_by_vm()) {
 424     // But still remember to clean-up inline caches for alive nmethods
 425     if (nm->is_alive()) {
 426       // Clean inline caches that point to zombie/non-entrant methods
 427       MutexLocker cl(CompiledIC_lock);
 428       nm->cleanup_inline_caches();
 429       SWEEP(nm);
 430     } else {
 431       _locked_seen++;
 432       SWEEP(nm);
 433     }
 434     return freed_memory;
 435   }
 436 
 437   if (nm->is_zombie()) {
 438     // If it is the first time we see nmethod then we mark it. Otherwise,
 439     // we reclaim it. When we have seen a zombie method twice, we know that
 440     // there are no inline caches that refer to it.
 441     if (nm->is_marked_for_reclamation()) {
 442       assert(!nm->is_locked_by_vm(), "must not flush locked nmethods");
 443       if (PrintMethodFlushing && Verbose) {
 444         tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (marked for reclamation) being flushed", nm->compile_id(), nm);
 445       }
 446       freed_memory = nm->total_size();
 447       release_nmethod(nm);
 448       _flushed_count++;
 449     } else {
 450       if (PrintMethodFlushing && Verbose) {
 451         tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (zombie) being marked for reclamation", nm->compile_id(), nm);
 452       }
 453       nm->mark_for_reclamation();
 454       request_nmethod_marking();
 455       _marked_count++;
 456       SWEEP(nm);
 457     }
 458   } else if (nm->is_not_entrant()) {
 459     // If there are no current activations of this method on the
 460     // stack we can safely convert it to a zombie method
 461     if (nm->can_not_entrant_be_converted()) {
 462       if (PrintMethodFlushing && Verbose) {
 463         tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (not entrant) being made zombie", nm->compile_id(), nm);
 464       }
 465       nm->make_zombie();
 466       request_nmethod_marking();
 467       _zombified_count++;
 468       SWEEP(nm);
 469     } else {
 470       // Still alive, clean up its inline caches
 471       MutexLocker cl(CompiledIC_lock);
 472       nm->cleanup_inline_caches();
 473       // we coudn't transition this nmethod so don't immediately
 474       // request a rescan.  If this method stays on the stack for a
 475       // long time we don't want to keep rescanning the code cache.
 476       _not_entrant_seen_on_stack++;
 477       SWEEP(nm);
 478     }
 479   } else if (nm->is_unloaded()) {
 480     // Unloaded code, just make it a zombie
 481     if (PrintMethodFlushing && Verbose) {
 482       tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (unloaded) being made zombie", nm->compile_id(), nm);
 483     }
 484     if (nm->is_osr_method()) {
 485       SWEEP(nm);
 486       // No inline caches will ever point to osr methods, so we can just remove it
 487       freed_memory = nm->total_size();
 488       release_nmethod(nm);
 489       _flushed_count++;
 490     } else {
 491       nm->make_zombie();
 492       request_nmethod_marking();
 493       _zombified_count++;
 494       SWEEP(nm);
 495     }
 496   } else {
 497     if (UseCodeCacheFlushing) {
 498       if (!nm->is_locked_by_vm() && !nm->is_osr_method() && !nm->is_native_method()) {
 499         // Do not make native methods and OSR-methods not-entrant
 500         nm->dec_hotness_counter();
 501         // Get the initial value of the hotness counter. This value depends on the
 502         // ReservedCodeCacheSize
 503         int reset_val = hotness_counter_reset_val();
 504         int time_since_reset = reset_val - nm->hotness_counter();
 505         double threshold = -reset_val + (CodeCache::reverse_free_ratio(code_blob_type) * NmethodSweepActivity);
 506         // The less free space in the code cache we have - the bigger reverse_free_ratio() is.
 507         // I.e., 'threshold' increases with lower available space in the code cache and a higher
 508         // NmethodSweepActivity. If the current hotness counter - which decreases from its initial
 509         // value until it is reset by stack walking - is smaller than the computed threshold, the
 510         // corresponding nmethod is considered for removal.
 511         if ((NmethodSweepActivity > 0) && (nm->hotness_counter() < threshold) && (time_since_reset > 10)) {
 512           // A method is marked as not-entrant if the method is
 513           // 1) 'old enough': nm->hotness_counter() < threshold
 514           // 2) The method was in_use for a minimum amount of time: (time_since_reset > 10)
 515           //    The second condition is necessary if we are dealing with very small code cache
 516           //    sizes (e.g., <10m) and the code cache size is too small to hold all hot methods.
 517           //    The second condition ensures that methods are not immediately made not-entrant
 518           //    after compilation.
 519           nm->make_not_entrant();
 520           request_nmethod_marking();
 521         }
 522       }
 523     }
 524     // Clean-up all inline caches that point to zombie/non-reentrant methods
 525     MutexLocker cl(CompiledIC_lock);
 526     nm->cleanup_inline_caches();
 527     SWEEP(nm);
 528   }
 529   return freed_memory;
 530 }
 531 
 532 // Print out some state information about the current sweep and the
 533 // state of the code cache if it's requested.
 534 void NMethodSweeper::log_sweep(const char* msg, const char* format, ...) {
 535   if (PrintMethodFlushing) {
 536     stringStream s;
 537     // Dump code cache state into a buffer before locking the tty,
 538     // because log_state() will use locks causing lock conflicts.
 539     CodeCache::log_state(&s);
 540 
 541     ttyLocker ttyl;
 542     tty->print("### sweeper: %s ", msg);
 543     if (format != NULL) {
 544       va_list ap;
 545       va_start(ap, format);
 546       tty->vprint(format, ap);
 547       va_end(ap);
 548     }
 549     tty->print_cr(s.as_string());
 550   }
 551 
 552   if (LogCompilation && (xtty != NULL)) {
 553     stringStream s;
 554     // Dump code cache state into a buffer before locking the tty,
 555     // because log_state() will use locks causing lock conflicts.
 556     CodeCache::log_state(&s);
 557 
 558     ttyLocker ttyl;
 559     xtty->begin_elem("sweeper state='%s' traversals='" INTX_FORMAT "' ", msg, (intx)traversal_count());
 560     if (format != NULL) {
 561       va_list ap;
 562       va_start(ap, format);
 563       xtty->vprint(format, ap);
 564       va_end(ap);
 565     }
 566     xtty->print(s.as_string());
 567     xtty->stamp();
 568     xtty->end_elem();
 569   }
 570 }
--- EOF ---