1 /*
   2  * Copyright (c) 1997, 2014, 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.inline.hpp"
  34 #include "runtime/compilationPolicy.hpp"
  35 #include "runtime/mutexLocker.hpp"
  36 #include "runtime/orderAccess.inline.hpp"
  37 #include "runtime/os.hpp"
  38 #include "runtime/sweeper.hpp"
  39 #include "runtime/thread.inline.hpp"
  40 #include "runtime/vm_operations.hpp"
  41 #include "trace/tracing.hpp"
  42 #include "utilities/events.hpp"
  43 #include "utilities/ticks.inline.hpp"
  44 #include "utilities/xmlstream.hpp"
  45 
  46 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  47 
  48 #ifdef ASSERT
  49 
  50 #define SWEEP(nm) record_sweep(nm, __LINE__)
  51 // Sweeper logging code
  52 class SweeperRecord {
  53  public:
  54   int traversal;
  55   int invocation;
  56   int compile_id;
  57   long traversal_mark;
  58   int state;
  59   const char* kind;
  60   address vep;
  61   address uep;
  62   int line;
  63 
  64   void print() {
  65       tty->print_cr("traversal = %d invocation = %d compile_id = %d %s uep = " PTR_FORMAT " vep = "
  66                     PTR_FORMAT " state = %d traversal_mark %d line = %d",
  67                     traversal,
  68                     invocation,
  69                     compile_id,
  70                     kind == NULL ? "" : kind,
  71                     uep,
  72                     vep,
  73                     state,
  74                     traversal_mark,
  75                     line);
  76   }
  77 };
  78 
  79 static int _sweep_index = 0;
  80 static SweeperRecord* _records = NULL;
  81 
  82 void NMethodSweeper::report_events(int id, address entry) {
  83   if (_records != NULL) {
  84     for (int i = _sweep_index; i < SweeperLogEntries; i++) {
  85       if (_records[i].uep == entry ||
  86           _records[i].vep == entry ||
  87           _records[i].compile_id == id) {
  88         _records[i].print();
  89       }
  90     }
  91     for (int i = 0; i < _sweep_index; i++) {
  92       if (_records[i].uep == entry ||
  93           _records[i].vep == entry ||
  94           _records[i].compile_id == id) {
  95         _records[i].print();
  96       }
  97     }
  98   }
  99 }
 100 
 101 void NMethodSweeper::report_events() {
 102   if (_records != NULL) {
 103     for (int i = _sweep_index; i < SweeperLogEntries; i++) {
 104       // skip empty records
 105       if (_records[i].vep == NULL) continue;
 106       _records[i].print();
 107     }
 108     for (int i = 0; i < _sweep_index; i++) {
 109       // skip empty records
 110       if (_records[i].vep == NULL) continue;
 111       _records[i].print();
 112     }
 113   }
 114 }
 115 
 116 void NMethodSweeper::record_sweep(nmethod* nm, int line) {
 117   if (_records != NULL) {
 118     _records[_sweep_index].traversal = _traversals;
 119     _records[_sweep_index].traversal_mark = nm->_stack_traversal_mark;
 120     _records[_sweep_index].invocation = _sweep_fractions_left;
 121     _records[_sweep_index].compile_id = nm->compile_id();
 122     _records[_sweep_index].kind = nm->compile_kind();
 123     _records[_sweep_index].state = nm->_state;
 124     _records[_sweep_index].vep = nm->verified_entry_point();
 125     _records[_sweep_index].uep = nm->entry_point();
 126     _records[_sweep_index].line = line;
 127     _sweep_index = (_sweep_index + 1) % SweeperLogEntries;
 128   }
 129 }
 130 #else
 131 #define SWEEP(nm)
 132 #endif
 133 
 134 NMethodIterator NMethodSweeper::_current;                      // Current nmethod
 135 long     NMethodSweeper::_traversals                   = 0;    // Stack scan count, also sweep ID.
 136 long     NMethodSweeper::_total_nof_code_cache_sweeps  = 0;    // Total number of full sweeps of the code cache
 137 long     NMethodSweeper::_time_counter                 = 0;    // Virtual time used to periodically invoke sweeper
 138 long     NMethodSweeper::_last_sweep                   = 0;    // Value of _time_counter when the last sweep happened
 139 int      NMethodSweeper::_seen                         = 0;    // Nof. nmethod we have currently processed in current pass of CodeCache
 140 int      NMethodSweeper::_flushed_count                = 0;    // Nof. nmethods flushed in current sweep
 141 int      NMethodSweeper::_zombified_count              = 0;    // Nof. nmethods made zombie in current sweep
 142 int      NMethodSweeper::_marked_for_reclamation_count = 0;    // Nof. nmethods marked for reclaim in current sweep
 143 
 144 volatile bool NMethodSweeper::_should_sweep            = true; // Indicates if we should invoke the sweeper
 145 volatile int  NMethodSweeper::_sweep_fractions_left    = 0;    // Nof. invocations left until we are completed with this pass
 146 volatile int  NMethodSweeper::_sweep_started           = 0;    // Flag to control conc sweeper
 147 volatile int  NMethodSweeper::_bytes_changed           = 0;    // Counts the total nmethod size if the nmethod changed from:
 148                                                                //   1) alive       -> not_entrant
 149                                                                //   2) not_entrant -> zombie
 150                                                                //   3) zombie      -> marked_for_reclamation
 151 int    NMethodSweeper::_hotness_counter_reset_val       = 0;
 152 
 153 long   NMethodSweeper::_total_nof_methods_reclaimed     = 0;   // Accumulated nof methods flushed
 154 long   NMethodSweeper::_total_nof_c2_methods_reclaimed  = 0;   // Accumulated nof methods flushed
 155 size_t NMethodSweeper::_total_flushed_size              = 0;   // Total number of bytes flushed from the code cache
 156 Tickspan NMethodSweeper::_total_time_sweeping;                 // Accumulated time sweeping
 157 Tickspan NMethodSweeper::_total_time_this_sweep;               // Total time this sweep
 158 Tickspan NMethodSweeper::_peak_sweep_time;                     // Peak time for a full sweep
 159 Tickspan NMethodSweeper::_peak_sweep_fraction_time;            // Peak time sweeping one fraction
 160 
 161 
 162 class MarkActivationClosure: public CodeBlobClosure {
 163 public:
 164   virtual void do_code_blob(CodeBlob* cb) {
 165     assert(cb->is_nmethod(), "CodeBlob should be nmethod");
 166     nmethod* nm = (nmethod*)cb;
 167     nm->set_hotness_counter(NMethodSweeper::hotness_counter_reset_val());
 168     // If we see an activation belonging to a non_entrant nmethod, we mark it.
 169     if (nm->is_not_entrant()) {
 170       nm->mark_as_seen_on_stack();
 171     }
 172   }
 173 };
 174 static MarkActivationClosure mark_activation_closure;
 175 
 176 class SetHotnessClosure: public CodeBlobClosure {
 177 public:
 178   virtual void do_code_blob(CodeBlob* cb) {
 179     assert(cb->is_nmethod(), "CodeBlob should be nmethod");
 180     nmethod* nm = (nmethod*)cb;
 181     nm->set_hotness_counter(NMethodSweeper::hotness_counter_reset_val());
 182   }
 183 };
 184 static SetHotnessClosure set_hotness_closure;
 185 
 186 
 187 int NMethodSweeper::hotness_counter_reset_val() {
 188   if (_hotness_counter_reset_val == 0) {
 189     _hotness_counter_reset_val = (ReservedCodeCacheSize < M) ? 1 : (ReservedCodeCacheSize / M) * 2;
 190   }
 191   return _hotness_counter_reset_val;
 192 }
 193 bool NMethodSweeper::sweep_in_progress() {
 194   return !_current.end();
 195 }
 196 
 197 // Scans the stacks of all Java threads and marks activations of not-entrant methods.
 198 // No need to synchronize access, since 'mark_active_nmethods' is always executed at a
 199 // safepoint.
 200 void NMethodSweeper::mark_active_nmethods() {
 201   assert(SafepointSynchronize::is_at_safepoint(), "must be executed at a safepoint");
 202   // If we do not want to reclaim not-entrant or zombie methods there is no need
 203   // to scan stacks
 204   if (!MethodFlushing) {
 205     return;
 206   }
 207 
 208   // Increase time so that we can estimate when to invoke the sweeper again.
 209   _time_counter++;
 210 
 211   // Check for restart
 212   assert(CodeCache::find_blob_unsafe(_current.method()) == _current.method(), "Sweeper nmethod cached state invalid");
 213   if (!sweep_in_progress()) {
 214     _seen = 0;
 215     _sweep_fractions_left = NmethodSweepFraction;
 216     _current = NMethodIterator();
 217     // Initialize to first nmethod
 218     _current.next();
 219     _traversals += 1;
 220     _total_time_this_sweep = Tickspan();
 221 
 222     if (PrintMethodFlushing) {
 223       tty->print_cr("### Sweep: stack traversal %d", _traversals);
 224     }
 225     Threads::nmethods_do(&mark_activation_closure);
 226 
 227   } else {
 228     // Only set hotness counter
 229     Threads::nmethods_do(&set_hotness_closure);
 230   }
 231 
 232   OrderAccess::storestore();
 233 }
 234 /**
 235  * This function invokes the sweeper if at least one of the three conditions is met:
 236  *    (1) The code cache is getting full
 237  *    (2) There are sufficient state changes in/since the last sweep.
 238  *    (3) We have not been sweeping for 'some time'
 239  */
 240 void NMethodSweeper::possibly_sweep() {
 241   assert(JavaThread::current()->thread_state() == _thread_in_vm, "must run in vm mode");
 242   // Only compiler threads are allowed to sweep
 243   if (!MethodFlushing || !sweep_in_progress() || !Thread::current()->is_Compiler_thread()) {
 244     return;
 245   }
 246 
 247   // If there was no state change while nmethod sweeping, 'should_sweep' will be false.
 248   // This is one of the two places where should_sweep can be set to true. The general
 249   // idea is as follows: If there is enough free space in the code cache, there is no
 250   // need to invoke the sweeper. The following formula (which determines whether to invoke
 251   // the sweeper or not) depends on the assumption that for larger ReservedCodeCacheSizes
 252   // we need less frequent sweeps than for smaller ReservedCodecCacheSizes. Furthermore,
 253   // the formula considers how much space in the code cache is currently used. Here are
 254   // some examples that will (hopefully) help in understanding.
 255   //
 256   // Small ReservedCodeCacheSizes:  (e.g., < 16M) We invoke the sweeper every time, since
 257   //                                              the result of the division is 0. This
 258   //                                              keeps the used code cache size small
 259   //                                              (important for embedded Java)
 260   // Large ReservedCodeCacheSize :  (e.g., 256M + code cache is 10% full). The formula
 261   //                                              computes: (256 / 16) - 1 = 15
 262   //                                              As a result, we invoke the sweeper after
 263   //                                              15 invocations of 'mark_active_nmethods.
 264   // Large ReservedCodeCacheSize:   (e.g., 256M + code Cache is 90% full). The formula
 265   //                                              computes: (256 / 16) - 10 = 6.
 266   if (!_should_sweep) {
 267     const int time_since_last_sweep = _time_counter - _last_sweep;
 268     // ReservedCodeCacheSize has an 'unsigned' type. We need a 'signed' type for max_wait_time,
 269     // since 'time_since_last_sweep' can be larger than 'max_wait_time'. If that happens using
 270     // an unsigned type would cause an underflow (wait_until_next_sweep becomes a large positive
 271     // value) that disables the intended periodic sweeps.
 272     const int max_wait_time = ReservedCodeCacheSize / (16 * M);
 273     double wait_until_next_sweep = max_wait_time - time_since_last_sweep -
 274         MAX2(CodeCache::reverse_free_ratio(CodeBlobType::MethodProfiled),
 275              CodeCache::reverse_free_ratio(CodeBlobType::MethodNonProfiled));
 276     assert(wait_until_next_sweep <= (double)max_wait_time, "Calculation of code cache sweeper interval is incorrect");
 277 
 278     if ((wait_until_next_sweep <= 0.0) || !CompileBroker::should_compile_new_jobs()) {
 279       _should_sweep = true;
 280     }
 281   }
 282 
 283   if (_should_sweep && _sweep_fractions_left > 0) {
 284     // Only one thread at a time will sweep
 285     jint old = Atomic::cmpxchg( 1, &_sweep_started, 0 );
 286     if (old != 0) {
 287       return;
 288     }
 289 #ifdef ASSERT
 290     if (LogSweeper && _records == NULL) {
 291       // Create the ring buffer for the logging code
 292       _records = NEW_C_HEAP_ARRAY(SweeperRecord, SweeperLogEntries, mtGC);
 293       memset(_records, 0, sizeof(SweeperRecord) * SweeperLogEntries);
 294     }
 295 #endif
 296 
 297     if (_sweep_fractions_left > 0) {
 298       sweep_code_cache();
 299       _sweep_fractions_left--;
 300     }
 301 
 302     // We are done with sweeping the code cache once.
 303     if (_sweep_fractions_left == 0) {
 304       _total_nof_code_cache_sweeps++;
 305       _last_sweep = _time_counter;
 306       // Reset flag; temporarily disables sweeper
 307       _should_sweep = false;
 308       // If there was enough state change, 'possibly_enable_sweeper()'
 309       // sets '_should_sweep' to true
 310       possibly_enable_sweeper();
 311       // Reset _bytes_changed only if there was enough state change. _bytes_changed
 312       // can further increase by calls to 'report_state_change'.
 313       if (_should_sweep) {
 314         _bytes_changed = 0;
 315       }
 316     }
 317     // Release work, because another compiler thread could continue.
 318     OrderAccess::release_store((int*)&_sweep_started, 0);
 319   }
 320 }
 321 
 322 void NMethodSweeper::sweep_code_cache() {
 323   Ticks sweep_start_counter = Ticks::now();
 324 
 325   _flushed_count                = 0;
 326   _zombified_count              = 0;
 327   _marked_for_reclamation_count = 0;
 328 
 329   if (PrintMethodFlushing && Verbose) {
 330     tty->print_cr("### Sweep at %d out of %d. Invocations left: %d", _seen, CodeCache::nof_nmethods(), _sweep_fractions_left);
 331   }
 332 
 333   if (!CompileBroker::should_compile_new_jobs()) {
 334     // If we have turned off compilations we might as well do full sweeps
 335     // in order to reach the clean state faster. Otherwise the sleeping compiler
 336     // threads will slow down sweeping.
 337     _sweep_fractions_left = 1;
 338   }
 339 
 340   // We want to visit all nmethods after NmethodSweepFraction
 341   // invocations so divide the remaining number of nmethods by the
 342   // remaining number of invocations.  This is only an estimate since
 343   // the number of nmethods changes during the sweep so the final
 344   // stage must iterate until it there are no more nmethods.
 345   int todo = (CodeCache::nof_nmethods() - _seen) / _sweep_fractions_left;
 346   int swept_count = 0;
 347 
 348 
 349   assert(!SafepointSynchronize::is_at_safepoint(), "should not be in safepoint when we get here");
 350   assert(!CodeCache_lock->owned_by_self(), "just checking");
 351 
 352   int freed_memory = 0;
 353   {
 354     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 355 
 356     // The last invocation iterates until there are no more nmethods
 357     while ((swept_count < todo || _sweep_fractions_left == 1) && !_current.end()) {
 358       swept_count++;
 359       if (SafepointSynchronize::is_synchronizing()) { // Safepoint request
 360         if (PrintMethodFlushing && Verbose) {
 361           tty->print_cr("### Sweep at %d out of %d, invocation: %d, yielding to safepoint", _seen, CodeCache::nof_nmethods(), _sweep_fractions_left);
 362         }
 363         MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 364 
 365         assert(Thread::current()->is_Java_thread(), "should be java thread");
 366         JavaThread* thread = (JavaThread*)Thread::current();
 367         ThreadBlockInVM tbivm(thread);
 368         thread->java_suspend_self();
 369       }
 370       // Since we will give up the CodeCache_lock, always skip ahead
 371       // to the next nmethod.  Other blobs can be deleted by other
 372       // threads but nmethods are only reclaimed by the sweeper.
 373       nmethod* nm = _current.method();
 374       _current.next();
 375 
 376       // Now ready to process nmethod and give up CodeCache_lock
 377       {
 378         MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 379         freed_memory += process_nmethod(nm);
 380       }
 381       _seen++;
 382     }
 383   }
 384 
 385   assert(_sweep_fractions_left > 1 || _current.end(), "must have scanned the whole cache");
 386 
 387   const Ticks sweep_end_counter = Ticks::now();
 388   const Tickspan sweep_time = sweep_end_counter - sweep_start_counter;
 389   _total_time_sweeping  += sweep_time;
 390   _total_time_this_sweep += sweep_time;
 391   _peak_sweep_fraction_time = MAX2(sweep_time, _peak_sweep_fraction_time);
 392   _total_flushed_size += freed_memory;
 393   _total_nof_methods_reclaimed += _flushed_count;
 394 
 395   EventSweepCodeCache event(UNTIMED);
 396   if (event.should_commit()) {
 397     event.set_starttime(sweep_start_counter);
 398     event.set_endtime(sweep_end_counter);
 399     event.set_sweepIndex(_traversals);
 400     event.set_sweepFractionIndex(NmethodSweepFraction - _sweep_fractions_left + 1);
 401     event.set_sweptCount(swept_count);
 402     event.set_flushedCount(_flushed_count);
 403     event.set_markedCount(_marked_for_reclamation_count);
 404     event.set_zombifiedCount(_zombified_count);
 405     event.commit();
 406   }
 407 
 408 #ifdef ASSERT
 409   if(PrintMethodFlushing) {
 410     tty->print_cr("### sweeper:      sweep time(%d): "
 411       INT64_FORMAT, _sweep_fractions_left, (jlong)sweep_time.value());
 412   }
 413 #endif
 414 
 415   if (_sweep_fractions_left == 1) {
 416     _peak_sweep_time = MAX2(_peak_sweep_time, _total_time_this_sweep);
 417     log_sweep("finished");
 418   }
 419 
 420   // Sweeper is the only case where memory is released, check here if it
 421   // is time to restart the compiler. Only checking if there is a certain
 422   // amount of free memory in the code cache might lead to re-enabling
 423   // compilation although no memory has been released. For example, there are
 424   // cases when compilation was disabled although there is 4MB (or more) free
 425   // memory in the code cache. The reason is code cache fragmentation. Therefore,
 426   // it only makes sense to re-enable compilation if we have actually freed memory.
 427   // Note that typically several kB are released for sweeping 16MB of the code
 428   // cache. As a result, 'freed_memory' > 0 to restart the compiler.
 429   if (!CompileBroker::should_compile_new_jobs() && (freed_memory > 0)) {
 430     CompileBroker::set_should_compile_new_jobs(CompileBroker::run_compilation);
 431     log_sweep("restart_compiler");
 432   }
 433 }
 434 
 435 /**
 436  * This function updates the sweeper statistics that keep track of nmethods
 437  * state changes. If there is 'enough' state change, the sweeper is invoked
 438  * as soon as possible. There can be data races on _bytes_changed. The data
 439  * races are benign, since it does not matter if we loose a couple of bytes.
 440  * In the worst case we call the sweeper a little later. Also, we are guaranteed
 441  * to invoke the sweeper if the code cache gets full.
 442  */
 443 void NMethodSweeper::report_state_change(nmethod* nm) {
 444   _bytes_changed += nm->total_size();
 445   possibly_enable_sweeper();
 446 }
 447 
 448 /**
 449  * Function determines if there was 'enough' state change in the code cache to invoke
 450  * the sweeper again. Currently, we determine 'enough' as more than 1% state change in
 451  * the code cache since the last sweep.
 452  */
 453 void NMethodSweeper::possibly_enable_sweeper() {
 454   double percent_changed = ((double)_bytes_changed / (double)ReservedCodeCacheSize) * 100;
 455   if (percent_changed > 1.0) {
 456     _should_sweep = true;
 457   }
 458 }
 459 
 460 class NMethodMarker: public StackObj {
 461  private:
 462   CompilerThread* _thread;
 463  public:
 464   NMethodMarker(nmethod* nm) {
 465     _thread = CompilerThread::current();
 466     if (!nm->is_zombie() && !nm->is_unloaded()) {
 467       // Only expose live nmethods for scanning
 468       _thread->set_scanned_nmethod(nm);
 469     }
 470   }
 471   ~NMethodMarker() {
 472     _thread->set_scanned_nmethod(NULL);
 473   }
 474 };
 475 
 476 void NMethodSweeper::release_nmethod(nmethod *nm) {
 477   // Clean up any CompiledICHolders
 478   {
 479     ResourceMark rm;
 480     MutexLocker ml_patch(CompiledIC_lock);
 481     RelocIterator iter(nm);
 482     while (iter.next()) {
 483       if (iter.type() == relocInfo::virtual_call_type) {
 484         CompiledIC::cleanup_call_site(iter.virtual_call_reloc());
 485       }
 486     }
 487   }
 488 
 489   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 490   nm->flush();
 491 }
 492 
 493 int NMethodSweeper::process_nmethod(nmethod *nm) {
 494   assert(!CodeCache_lock->owned_by_self(), "just checking");
 495 
 496   int freed_memory = 0;
 497   // Make sure this nmethod doesn't get unloaded during the scan,
 498   // since safepoints may happen during acquired below locks.
 499   NMethodMarker nmm(nm);
 500   SWEEP(nm);
 501 
 502   // Skip methods that are currently referenced by the VM
 503   if (nm->is_locked_by_vm()) {
 504     // But still remember to clean-up inline caches for alive nmethods
 505     if (nm->is_alive()) {
 506       // Clean inline caches that point to zombie/non-entrant methods
 507       MutexLocker cl(CompiledIC_lock);
 508       nm->cleanup_inline_caches();
 509       SWEEP(nm);
 510     }
 511     return freed_memory;
 512   }
 513 
 514   if (nm->is_zombie()) {
 515     // If it is the first time we see nmethod then we mark it. Otherwise,
 516     // we reclaim it. When we have seen a zombie method twice, we know that
 517     // there are no inline caches that refer to it.
 518     if (nm->is_marked_for_reclamation()) {
 519       assert(!nm->is_locked_by_vm(), "must not flush locked nmethods");
 520       if (PrintMethodFlushing && Verbose) {
 521         tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (marked for reclamation) being flushed", nm->compile_id(), nm);
 522       }
 523       freed_memory = nm->total_size();
 524       if (nm->is_compiled_by_c2()) {
 525         _total_nof_c2_methods_reclaimed++;
 526       }
 527       release_nmethod(nm);
 528       _flushed_count++;
 529     } else {
 530       if (PrintMethodFlushing && Verbose) {
 531         tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (zombie) being marked for reclamation", nm->compile_id(), nm);
 532       }
 533       nm->mark_for_reclamation();
 534       // Keep track of code cache state change
 535       _bytes_changed += nm->total_size();
 536       _marked_for_reclamation_count++;
 537       SWEEP(nm);
 538     }
 539   } else if (nm->is_not_entrant()) {
 540     // If there are no current activations of this method on the
 541     // stack we can safely convert it to a zombie method
 542     if (nm->can_not_entrant_be_converted()) {
 543       if (PrintMethodFlushing && Verbose) {
 544         tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (not entrant) being made zombie", nm->compile_id(), nm);
 545       }
 546       // Clear ICStubs to prevent back patching stubs of zombie or unloaded
 547       // nmethods during the next safepoint (see ICStub::finalize).
 548       MutexLocker cl(CompiledIC_lock);
 549       nm->clear_ic_stubs();
 550       // Code cache state change is tracked in make_zombie()
 551       nm->make_zombie();
 552       _zombified_count++;
 553       SWEEP(nm);
 554     } else {
 555       // Still alive, clean up its inline caches
 556       MutexLocker cl(CompiledIC_lock);
 557       nm->cleanup_inline_caches();
 558       SWEEP(nm);
 559     }
 560   } else if (nm->is_unloaded()) {
 561     // Unloaded code, just make it a zombie
 562     if (PrintMethodFlushing && Verbose) {
 563       tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (unloaded) being made zombie", nm->compile_id(), nm);
 564     }
 565     if (nm->is_osr_method()) {
 566       SWEEP(nm);
 567       // No inline caches will ever point to osr methods, so we can just remove it
 568       freed_memory = nm->total_size();
 569       if (nm->is_compiled_by_c2()) {
 570         _total_nof_c2_methods_reclaimed++;
 571       }
 572       release_nmethod(nm);
 573       _flushed_count++;
 574     } else {
 575       // Code cache state change is tracked in make_zombie()
 576       nm->make_zombie();
 577       _zombified_count++;
 578       SWEEP(nm);
 579     }
 580   } else {
 581     possibly_flush(nm);
 582     // Clean-up all inline caches that point to zombie/non-reentrant methods
 583     MutexLocker cl(CompiledIC_lock);
 584     nm->cleanup_inline_caches();
 585     SWEEP(nm);
 586   }
 587   return freed_memory;
 588 }
 589 
 590 
 591 void NMethodSweeper::possibly_flush(nmethod* nm) {
 592   if (UseCodeCacheFlushing) {
 593     if (!nm->is_locked_by_vm() && !nm->is_osr_method() && !nm->is_native_method()) {
 594       bool make_not_entrant = false;
 595 
 596       // Do not make native methods and OSR-methods not-entrant
 597       nm->dec_hotness_counter();
 598       // Get the initial value of the hotness counter. This value depends on the
 599       // ReservedCodeCacheSize
 600       int reset_val = hotness_counter_reset_val();
 601       int time_since_reset = reset_val - nm->hotness_counter();
 602       int code_blob_type = (CodeCache::get_code_blob_type(nm->comp_level()));
 603       double threshold = -reset_val + (CodeCache::reverse_free_ratio(code_blob_type) * NmethodSweepActivity);
 604       // The less free space in the code cache we have - the bigger reverse_free_ratio() is.
 605       // I.e., 'threshold' increases with lower available space in the code cache and a higher
 606       // NmethodSweepActivity. If the current hotness counter - which decreases from its initial
 607       // value until it is reset by stack walking - is smaller than the computed threshold, the
 608       // corresponding nmethod is considered for removal.
 609       if ((NmethodSweepActivity > 0) && (nm->hotness_counter() < threshold) && (time_since_reset > MinPassesBeforeFlush)) {
 610         // A method is marked as not-entrant if the method is
 611         // 1) 'old enough': nm->hotness_counter() < threshold
 612         // 2) The method was in_use for a minimum amount of time: (time_since_reset > MinPassesBeforeFlush)
 613         //    The second condition is necessary if we are dealing with very small code cache
 614         //    sizes (e.g., <10m) and the code cache size is too small to hold all hot methods.
 615         //    The second condition ensures that methods are not immediately made not-entrant
 616         //    after compilation.
 617         make_not_entrant = true;
 618       }
 619 
 620       // The stack-scanning low-cost detection may not see the method was used (which can happen for
 621       // flat profiles). Check the age counter for possible data.
 622       if (UseCodeAging && make_not_entrant && (nm->is_compiled_by_c2() || nm->is_compiled_by_c1())) {
 623         MethodCounters* mc = nm->method()->get_method_counters(Thread::current());
 624         if (mc != NULL) {
 625           // Snapshot the value as it's changed concurrently
 626           int age = mc->nmethod_age();
 627           if (MethodCounters::is_nmethod_hot(age)) {
 628             // The method has gone through flushing, and it became relatively hot that it deopted
 629             // before we could take a look at it. Give it more time to appear in the stack traces,
 630             // proportional to the number of deopts.
 631             MethodData* md = nm->method()->method_data();
 632             if (md != NULL && time_since_reset > (int)(MinPassesBeforeFlush * (md->tenure_traps() + 1))) {
 633               // It's been long enough, we still haven't seen it on stack.
 634               // Try to flush it, but enable counters the next time.
 635               mc->reset_nmethod_age();
 636             } else {
 637               make_not_entrant = false;
 638             }
 639           } else if (MethodCounters::is_nmethod_warm(age)) {
 640             // Method has counters enabled, and the method was used within
 641             // previous MinPassesBeforeFlush sweeps. Reset the counter. Stay in the existing
 642             // compiled state.
 643             mc->reset_nmethod_age();
 644             // delay the next check
 645             nm->set_hotness_counter(NMethodSweeper::hotness_counter_reset_val());
 646             make_not_entrant = false;
 647           } else if (MethodCounters::is_nmethod_age_unset(age)) {
 648             // No counters were used before. Set the counters to the detection
 649             // limit value. If the method is going to be used again it will be compiled
 650             // with counters that we're going to use for analysis the the next time.
 651             mc->reset_nmethod_age();
 652           } else {
 653             // Method was totally idle for 10 sweeps
 654             // The counter already has the initial value, flush it and may be recompile
 655             // later with counters
 656           }
 657         }
 658       }
 659 
 660       if (make_not_entrant) {
 661         nm->make_not_entrant();
 662 
 663         // Code cache state change is tracked in make_not_entrant()
 664         if (PrintMethodFlushing && Verbose) {
 665           tty->print_cr("### Nmethod %d/" PTR_FORMAT "made not-entrant: hotness counter %d/%d threshold %f",
 666               nm->compile_id(), nm, nm->hotness_counter(), reset_val, threshold);
 667         }
 668       }
 669     }
 670   }
 671 }
 672 
 673 // Print out some state information about the current sweep and the
 674 // state of the code cache if it's requested.
 675 void NMethodSweeper::log_sweep(const char* msg, const char* format, ...) {
 676   if (PrintMethodFlushing) {
 677     stringStream s;
 678     // Dump code cache state into a buffer before locking the tty,
 679     // because log_state() will use locks causing lock conflicts.
 680     CodeCache::log_state(&s);
 681 
 682     ttyLocker ttyl;
 683     tty->print("### sweeper: %s ", msg);
 684     if (format != NULL) {
 685       va_list ap;
 686       va_start(ap, format);
 687       tty->vprint(format, ap);
 688       va_end(ap);
 689     }
 690     tty->print_cr("%s", s.as_string());
 691   }
 692 
 693   if (LogCompilation && (xtty != NULL)) {
 694     stringStream s;
 695     // Dump code cache state into a buffer before locking the tty,
 696     // because log_state() will use locks causing lock conflicts.
 697     CodeCache::log_state(&s);
 698 
 699     ttyLocker ttyl;
 700     xtty->begin_elem("sweeper state='%s' traversals='" INTX_FORMAT "' ", msg, (intx)traversal_count());
 701     if (format != NULL) {
 702       va_list ap;
 703       va_start(ap, format);
 704       xtty->vprint(format, ap);
 705       va_end(ap);
 706     }
 707     xtty->print("%s", s.as_string());
 708     xtty->stamp();
 709     xtty->end_elem();
 710   }
 711 }
 712 
 713 void NMethodSweeper::print() {
 714   ttyLocker ttyl;
 715   tty->print_cr("Code cache sweeper statistics:");
 716   tty->print_cr("  Total sweep time:                %1.0lfms", (double)_total_time_sweeping.value()/1000000);
 717   tty->print_cr("  Total number of full sweeps:     %ld", _total_nof_code_cache_sweeps);
 718   tty->print_cr("  Total number of flushed methods: %ld(%ld C2 methods)", _total_nof_methods_reclaimed,
 719                                                     _total_nof_c2_methods_reclaimed);
 720   tty->print_cr("  Total size of flushed methods:   " SIZE_FORMAT "kB", _total_flushed_size/K);
 721 }