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