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