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