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