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