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