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