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