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