1 /* 2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "code/codeCache.hpp" 27 #include "code/compiledIC.hpp" 28 #include "code/icBuffer.hpp" 29 #include "code/nmethod.hpp" 30 #include "compiler/compileBroker.hpp" 31 #include "memory/resourceArea.hpp" 32 #include "oops/method.hpp" 33 #include "runtime/atomic.hpp" 34 #include "runtime/compilationPolicy.hpp" 35 #include "runtime/mutexLocker.hpp" 36 #include "runtime/os.hpp" 37 #include "runtime/sweeper.hpp" 38 #include "runtime/vm_operations.hpp" 39 #include "trace/tracing.hpp" 40 #include "utilities/events.hpp" 41 #include "utilities/ticks.inline.hpp" 42 #include "utilities/xmlstream.hpp" 43 44 #ifdef ASSERT 45 46 #define SWEEP(nm) record_sweep(nm, __LINE__) 47 // Sweeper logging code 48 class SweeperRecord { 49 public: 50 int traversal; 51 int invocation; 52 int compile_id; 53 long traversal_mark; 54 int state; 55 const char* kind; 56 address vep; 57 address uep; 58 int line; 59 60 void print() { 61 tty->print_cr("traversal = %d invocation = %d compile_id = %d %s uep = " PTR_FORMAT " vep = " 62 PTR_FORMAT " state = %d traversal_mark %d line = %d", 63 traversal, 64 invocation, 65 compile_id, 66 kind == NULL ? "" : kind, 67 uep, 68 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].invocation = _invocations; 117 _records[_sweep_index].compile_id = nm->compile_id(); 118 _records[_sweep_index].kind = nm->compile_kind(); 119 _records[_sweep_index].state = nm->_state; 120 _records[_sweep_index].vep = nm->verified_entry_point(); 121 _records[_sweep_index].uep = nm->entry_point(); 122 _records[_sweep_index].line = line; 123 124 _sweep_index = (_sweep_index + 1) % SweeperLogEntries; 125 } 126 } 127 #else 128 #define SWEEP(nm) 129 #endif 130 131 nmethod* NMethodSweeper::_current = NULL; // Current nmethod 132 long NMethodSweeper::_traversals = 0; // Nof. stack traversals performed 133 int NMethodSweeper::_seen = 0; // Nof. nmethods we have currently processed in current pass of CodeCache 134 int NMethodSweeper::_flushed_count = 0; // Nof. nmethods flushed in current sweep 135 int NMethodSweeper::_zombified_count = 0; // Nof. nmethods made zombie in current sweep 136 int NMethodSweeper::_marked_count = 0; // Nof. nmethods marked for reclaim in current sweep 137 138 volatile int NMethodSweeper::_invocations = 0; // Nof. invocations left until we are completed with this pass 139 volatile int NMethodSweeper::_sweep_started = 0; // Whether a sweep is in progress. 140 141 jint NMethodSweeper::_locked_seen = 0; 142 jint NMethodSweeper::_not_entrant_seen_on_stack = 0; 143 bool NMethodSweeper::_request_mark_phase = false; 144 145 int NMethodSweeper::_total_nof_methods_reclaimed = 0; 146 Tickspan NMethodSweeper::_total_time_sweeping; 147 Tickspan NMethodSweeper::_total_time_this_sweep; 148 Tickspan NMethodSweeper::_peak_sweep_time; 149 Tickspan NMethodSweeper::_peak_sweep_fraction_time; 150 int NMethodSweeper::_hotness_counter_reset_val = 0; 151 152 153 class MarkActivationClosure: public CodeBlobClosure { 154 public: 155 virtual void do_code_blob(CodeBlob* cb) { 156 if (cb->is_nmethod()) { 157 nmethod* nm = (nmethod*)cb; 158 nm->set_hotness_counter(NMethodSweeper::hotness_counter_reset_val()); 159 // If we see an activation belonging to a non_entrant nmethod, we mark it. 160 if (nm->is_not_entrant()) { 161 nm->mark_as_seen_on_stack(); 162 } 163 } 164 } 165 }; 166 static MarkActivationClosure mark_activation_closure; 167 168 class SetHotnessClosure: public CodeBlobClosure { 169 public: 170 virtual void do_code_blob(CodeBlob* cb) { 171 if (cb->is_nmethod()) { 172 nmethod* nm = (nmethod*)cb; 173 nm->set_hotness_counter(NMethodSweeper::hotness_counter_reset_val()); 174 } 175 } 176 }; 177 static SetHotnessClosure set_hotness_closure; 178 179 180 int NMethodSweeper::hotness_counter_reset_val() { 181 if (_hotness_counter_reset_val == 0) { 182 _hotness_counter_reset_val = (ReservedCodeCacheSize < M) ? 1 : (ReservedCodeCacheSize / M) * 2; 183 } 184 return _hotness_counter_reset_val; 185 } 186 bool NMethodSweeper::sweep_in_progress() { 187 return (_current != NULL); 188 } 189 190 // Scans the stacks of all Java threads and marks activations of not-entrant methods. 191 // No need to synchronize access, since 'mark_active_nmethods' is always executed at a 192 // safepoint. 193 void NMethodSweeper::mark_active_nmethods() { 194 assert(SafepointSynchronize::is_at_safepoint(), "must be executed at a safepoint"); 195 // If we do not want to reclaim not-entrant or zombie methods there is no need 196 // to scan stacks 197 if (!MethodFlushing) { 198 return; 199 } 200 201 // Check for restart 202 assert(CodeCache::find_blob_unsafe(_current) == _current, "Sweeper nmethod cached state invalid"); 203 if (!sweep_in_progress() && need_marking_phase()) { 204 _seen = 0; 205 _invocations = NmethodSweepFraction; 206 _current = CodeCache::first_nmethod(); 207 _traversals += 1; 208 _total_time_this_sweep = Tickspan(); 209 210 if (PrintMethodFlushing) { 211 tty->print_cr("### Sweep: stack traversal %d", _traversals); 212 } 213 Threads::nmethods_do(&mark_activation_closure); 214 215 // reset the flags since we started a scan from the beginning. 216 reset_nmethod_marking(); 217 _locked_seen = 0; 218 _not_entrant_seen_on_stack = 0; 219 } else { 220 // Only set hotness counter 221 Threads::nmethods_do(&set_hotness_closure); 222 } 223 224 OrderAccess::storestore(); 225 } 226 227 void NMethodSweeper::possibly_sweep() { 228 assert(JavaThread::current()->thread_state() == _thread_in_vm, "must run in vm mode"); 229 if (!MethodFlushing || !sweep_in_progress()) { 230 return; 231 } 232 233 if (_invocations > 0) { 234 // Only one thread at a time will sweep 235 jint old = Atomic::cmpxchg( 1, &_sweep_started, 0 ); 236 if (old != 0) { 237 return; 238 } 239 #ifdef ASSERT 240 if (LogSweeper && _records == NULL) { 241 // Create the ring buffer for the logging code 242 _records = NEW_C_HEAP_ARRAY(SweeperRecord, SweeperLogEntries, mtGC); 243 memset(_records, 0, sizeof(SweeperRecord) * SweeperLogEntries); 244 } 245 #endif 246 if (_invocations > 0) { 247 sweep_code_cache(); 248 _invocations--; 249 } 250 _sweep_started = 0; 251 } 252 } 253 254 void NMethodSweeper::sweep_code_cache() { 255 256 const Ticks sweep_start_counter = Ticks::now(); 257 258 _flushed_count = 0; 259 _zombified_count = 0; 260 _marked_count = 0; 261 262 if (PrintMethodFlushing && Verbose) { 263 tty->print_cr("### Sweep at %d out of %d. Invocations left: %d", _seen, CodeCache::nof_nmethods(), _invocations); 264 } 265 266 if (!CompileBroker::should_compile_new_jobs()) { 267 // If we have turned off compilations we might as well do full sweeps 268 // in order to reach the clean state faster. Otherwise the sleeping compiler 269 // threads will slow down sweeping. 270 _invocations = 1; 271 } 272 273 // We want to visit all nmethods after NmethodSweepFraction 274 // invocations so divide the remaining number of nmethods by the 275 // remaining number of invocations. This is only an estimate since 276 // the number of nmethods changes during the sweep so the final 277 // stage must iterate until it there are no more nmethods. 278 int todo = (CodeCache::nof_nmethods() - _seen) / _invocations; 279 int swept_count = 0; 280 281 282 assert(!SafepointSynchronize::is_at_safepoint(), "should not be in safepoint when we get here"); 283 assert(!CodeCache_lock->owned_by_self(), "just checking"); 284 285 int freed_memory = 0; 286 { 287 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 288 289 // The last invocation iterates until there are no more nmethods 290 for (int i = 0; (i < todo || _invocations == 1) && _current != NULL; i++) { 291 swept_count++; 292 if (SafepointSynchronize::is_synchronizing()) { // Safepoint request 293 if (PrintMethodFlushing && Verbose) { 294 tty->print_cr("### Sweep at %d out of %d, invocation: %d, yielding to safepoint", _seen, CodeCache::nof_nmethods(), _invocations); 295 } 296 MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 297 298 assert(Thread::current()->is_Java_thread(), "should be java thread"); 299 JavaThread* thread = (JavaThread*)Thread::current(); 300 ThreadBlockInVM tbivm(thread); 301 thread->java_suspend_self(); 302 } 303 // Since we will give up the CodeCache_lock, always skip ahead 304 // to the next nmethod. Other blobs can be deleted by other 305 // threads but nmethods are only reclaimed by the sweeper. 306 nmethod* next = CodeCache::next_nmethod(_current); 307 308 // Now ready to process nmethod and give up CodeCache_lock 309 { 310 MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 311 freed_memory += process_nmethod(_current); 312 } 313 _seen++; 314 _current = next; 315 } 316 } 317 318 assert(_invocations > 1 || _current == NULL, "must have scanned the whole cache"); 319 320 if (!sweep_in_progress() && !need_marking_phase() && (_locked_seen || _not_entrant_seen_on_stack)) { 321 // we've completed a scan without making progress but there were 322 // nmethods we were unable to process either because they were 323 // locked or were still on stack. We don't have to aggressively 324 // clean them up so just stop scanning. We could scan once more 325 // but that complicates the control logic and it's unlikely to 326 // matter much. 327 if (PrintMethodFlushing) { 328 tty->print_cr("### Couldn't make progress on some nmethods so stopping sweep"); 329 } 330 } 331 332 const Ticks sweep_end_counter = Ticks::now(); 333 const Tickspan sweep_time = sweep_end_counter - sweep_start_counter; 334 _total_time_sweeping += sweep_time; 335 _total_time_this_sweep += sweep_time; 336 _peak_sweep_fraction_time = MAX2(sweep_time, _peak_sweep_fraction_time); 337 _total_nof_methods_reclaimed += _flushed_count; 338 339 EventSweepCodeCache event(UNTIMED); 340 if (event.should_commit()) { 341 event.set_starttime(sweep_start_counter); 342 event.set_endtime(sweep_end_counter); 343 event.set_sweepIndex(_traversals); 344 event.set_sweepFractionIndex(NmethodSweepFraction - _invocations + 1); 345 event.set_sweptCount(swept_count); 346 event.set_flushedCount(_flushed_count); 347 event.set_markedCount(_marked_count); 348 event.set_zombifiedCount(_zombified_count); 349 event.commit(); 350 } 351 352 #ifdef ASSERT 353 if(PrintMethodFlushing) { 354 tty->print_cr("### sweeper: sweep time(%d): " INT64_FORMAT, _invocations, sweep_time.value()); 355 } 356 #endif 357 358 if (_invocations == 1) { 359 _peak_sweep_time = MAX2(_peak_sweep_time, _total_time_this_sweep); 360 log_sweep("finished"); 361 } 362 363 // Sweeper is the only case where memory is released, check here if it 364 // is time to restart the compiler. Only checking if there is a certain 365 // amount of free memory in the code cache might lead to re-enabling 366 // compilation although no memory has been released. For example, there are 367 // cases when compilation was disabled although there is 4MB (or more) free 368 // memory in the code cache. The reason is code cache fragmentation. Therefore, 369 // it only makes sense to re-enable compilation if we have actually freed memory. 370 // Note that typically several kB are released for sweeping 16MB of the code 371 // cache. As a result, 'freed_memory' > 0 to restart the compiler. 372 if (UseCodeCacheFlushing && (!CompileBroker::should_compile_new_jobs() && (freed_memory > 0))) { 373 CompileBroker::set_should_compile_new_jobs(CompileBroker::run_compilation); 374 log_sweep("restart_compiler"); 375 } 376 } 377 378 class NMethodMarker: public StackObj { 379 private: 380 CompilerThread* _thread; 381 public: 382 NMethodMarker(nmethod* nm) { 383 _thread = CompilerThread::current(); 384 if (!nm->is_zombie() && !nm->is_unloaded()) { 385 // Only expose live nmethods for scanning 386 _thread->set_scanned_nmethod(nm); 387 } 388 } 389 ~NMethodMarker() { 390 _thread->set_scanned_nmethod(NULL); 391 } 392 }; 393 394 void NMethodSweeper::release_nmethod(nmethod *nm) { 395 // Clean up any CompiledICHolders 396 { 397 ResourceMark rm; 398 MutexLocker ml_patch(CompiledIC_lock); 399 RelocIterator iter(nm); 400 while (iter.next()) { 401 if (iter.type() == relocInfo::virtual_call_type) { 402 CompiledIC::cleanup_call_site(iter.virtual_call_reloc()); 403 } 404 } 405 } 406 407 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 408 nm->flush(); 409 } 410 411 int NMethodSweeper::process_nmethod(nmethod *nm) { 412 assert(!CodeCache_lock->owned_by_self(), "just checking"); 413 414 int freed_memory = 0; 415 // Make sure this nmethod doesn't get unloaded during the scan, 416 // since safepoints may happen during acquired below locks. 417 NMethodMarker nmm(nm); 418 SWEEP(nm); 419 420 // Skip methods that are currently referenced by the VM 421 if (nm->is_locked_by_vm()) { 422 // But still remember to clean-up inline caches for alive nmethods 423 if (nm->is_alive()) { 424 // Clean inline caches that point to zombie/non-entrant methods 425 MutexLocker cl(CompiledIC_lock); 426 nm->cleanup_inline_caches(); 427 SWEEP(nm); 428 } else { 429 _locked_seen++; 430 SWEEP(nm); 431 } 432 return freed_memory; 433 } 434 435 if (nm->is_zombie()) { 436 // If it is the first time we see nmethod then we mark it. Otherwise, 437 // we reclaim it. When we have seen a zombie method twice, we know that 438 // there are no inline caches that refer to it. 439 if (nm->is_marked_for_reclamation()) { 440 assert(!nm->is_locked_by_vm(), "must not flush locked nmethods"); 441 if (PrintMethodFlushing && Verbose) { 442 tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (marked for reclamation) being flushed", nm->compile_id(), nm); 443 } 444 freed_memory = nm->total_size(); 445 release_nmethod(nm); 446 _flushed_count++; 447 } else { 448 if (PrintMethodFlushing && Verbose) { 449 tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (zombie) being marked for reclamation", nm->compile_id(), nm); 450 } 451 nm->mark_for_reclamation(); 452 request_nmethod_marking(); 453 _marked_count++; 454 SWEEP(nm); 455 } 456 } else if (nm->is_not_entrant()) { 457 // If there are no current activations of this method on the 458 // stack we can safely convert it to a zombie method 459 if (nm->can_not_entrant_be_converted()) { 460 if (PrintMethodFlushing && Verbose) { 461 tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (not entrant) being made zombie", nm->compile_id(), nm); 462 } 463 nm->make_zombie(); 464 request_nmethod_marking(); 465 _zombified_count++; 466 SWEEP(nm); 467 } else { 468 // Still alive, clean up its inline caches 469 MutexLocker cl(CompiledIC_lock); 470 nm->cleanup_inline_caches(); 471 // we coudn't transition this nmethod so don't immediately 472 // request a rescan. If this method stays on the stack for a 473 // long time we don't want to keep rescanning the code cache. 474 _not_entrant_seen_on_stack++; 475 SWEEP(nm); 476 } 477 } else if (nm->is_unloaded()) { 478 // Unloaded code, just make it a zombie 479 if (PrintMethodFlushing && Verbose) { 480 tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (unloaded) being made zombie", nm->compile_id(), nm); 481 } 482 if (nm->is_osr_method()) { 483 SWEEP(nm); 484 // No inline caches will ever point to osr methods, so we can just remove it 485 freed_memory = nm->total_size(); 486 release_nmethod(nm); 487 _flushed_count++; 488 } else { 489 nm->make_zombie(); 490 request_nmethod_marking(); 491 _zombified_count++; 492 SWEEP(nm); 493 } 494 } else { 495 if (UseCodeCacheFlushing) { 496 if (!nm->is_locked_by_vm() && !nm->is_osr_method() && !nm->is_native_method()) { 497 // Do not make native methods and OSR-methods not-entrant 498 nm->dec_hotness_counter(); 499 // Get the initial value of the hotness counter. This value depends on the 500 // ReservedCodeCacheSize 501 int reset_val = hotness_counter_reset_val(); 502 int time_since_reset = reset_val - nm->hotness_counter(); 503 double threshold = -reset_val + (CodeCache::reverse_free_ratio() * NmethodSweepActivity); 504 // The less free space in the code cache we have - the bigger reverse_free_ratio() is. 505 // I.e., 'threshold' increases with lower available space in the code cache and a higher 506 // NmethodSweepActivity. If the current hotness counter - which decreases from its initial 507 // value until it is reset by stack walking - is smaller than the computed threshold, the 508 // corresponding nmethod is considered for removal. 509 if ((NmethodSweepActivity > 0) && (nm->hotness_counter() < threshold) && (time_since_reset > 10)) { 510 // A method is marked as not-entrant if the method is 511 // 1) 'old enough': nm->hotness_counter() < threshold 512 // 2) The method was in_use for a minimum amount of time: (time_since_reset > 10) 513 // The second condition is necessary if we are dealing with very small code cache 514 // sizes (e.g., <10m) and the code cache size is too small to hold all hot methods. 515 // The second condition ensures that methods are not immediately made not-entrant 516 // after compilation. 517 nm->make_not_entrant(); 518 request_nmethod_marking(); 519 } 520 } 521 } 522 // Clean-up all inline caches that point to zombie/non-reentrant methods 523 MutexLocker cl(CompiledIC_lock); 524 nm->cleanup_inline_caches(); 525 SWEEP(nm); 526 } 527 return freed_memory; 528 } 529 530 // Print out some state information about the current sweep and the 531 // state of the code cache if it's requested. 532 void NMethodSweeper::log_sweep(const char* msg, const char* format, ...) { 533 if (PrintMethodFlushing) { 534 stringStream s; 535 // Dump code cache state into a buffer before locking the tty, 536 // because log_state() will use locks causing lock conflicts. 537 CodeCache::log_state(&s); 538 539 ttyLocker ttyl; 540 tty->print("### sweeper: %s ", msg); 541 if (format != NULL) { 542 va_list ap; 543 va_start(ap, format); 544 tty->vprint(format, ap); 545 va_end(ap); 546 } 547 tty->print_cr(s.as_string()); 548 } 549 550 if (LogCompilation && (xtty != NULL)) { 551 stringStream s; 552 // Dump code cache state into a buffer before locking the tty, 553 // because log_state() will use locks causing lock conflicts. 554 CodeCache::log_state(&s); 555 556 ttyLocker ttyl; 557 xtty->begin_elem("sweeper state='%s' traversals='" INTX_FORMAT "' ", msg, (intx)traversal_count()); 558 if (format != NULL) { 559 va_list ap; 560 va_start(ap, format); 561 xtty->vprint(format, ap); 562 va_end(ap); 563 } 564 xtty->print(s.as_string()); 565 xtty->stamp(); 566 xtty->end_elem(); 567 } 568 }