Mon, 09 Mar 2020 12:54:53 +0000
8240295: hs_err elapsed time in seconds is not accurate enough
Reviewed-by: dholmes, sspitsyn
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 */
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 "memory/resourceArea.hpp"
33 #include "oops/method.hpp"
34 #include "runtime/atomic.hpp"
35 #include "runtime/compilationPolicy.hpp"
36 #include "runtime/mutexLocker.hpp"
37 #include "runtime/orderAccess.inline.hpp"
38 #include "runtime/os.hpp"
39 #include "runtime/sweeper.hpp"
40 #include "runtime/thread.inline.hpp"
41 #include "runtime/vm_operations.hpp"
42 #include "utilities/events.hpp"
43 #include "utilities/ticks.hpp"
44 #include "utilities/xmlstream.hpp"
46 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
48 #ifdef ASSERT
50 #define SWEEP(nm) record_sweep(nm, __LINE__)
51 // Sweeper logging code
52 class SweeperRecord {
53 public:
54 int traversal;
55 int invocation;
56 int compile_id;
57 long traversal_mark;
58 int state;
59 const char* kind;
60 address vep;
61 address uep;
62 int line;
64 void print() {
65 tty->print_cr("traversal = %d invocation = %d compile_id = %d %s uep = " PTR_FORMAT " vep = "
66 PTR_FORMAT " state = %d traversal_mark %d line = %d",
67 traversal,
68 invocation,
69 compile_id,
70 kind == NULL ? "" : kind,
71 uep,
72 vep,
73 state,
74 traversal_mark,
75 line);
76 }
77 };
79 static int _sweep_index = 0;
80 static SweeperRecord* _records = NULL;
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 }
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 }
116 void NMethodSweeper::record_sweep(nmethod* nm, int line) {
117 if (_records != NULL) {
118 _records[_sweep_index].traversal = _traversals;
119 _records[_sweep_index].traversal_mark = nm->_stack_traversal_mark;
120 _records[_sweep_index].invocation = _sweep_fractions_left;
121 _records[_sweep_index].compile_id = nm->compile_id();
122 _records[_sweep_index].kind = nm->compile_kind();
123 _records[_sweep_index].state = nm->_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 #else
131 #define SWEEP(nm)
132 #endif
134 nmethod* NMethodSweeper::_current = NULL; // Current nmethod
135 long NMethodSweeper::_traversals = 0; // Stack scan count, also sweep ID.
136 long NMethodSweeper::_total_nof_code_cache_sweeps = 0; // Total number of full sweeps of the code cache
137 long NMethodSweeper::_time_counter = 0; // Virtual time used to periodically invoke sweeper
138 long NMethodSweeper::_last_sweep = 0; // Value of _time_counter when the last sweep happened
139 int NMethodSweeper::_seen = 0; // Nof. nmethod we have currently processed in current pass of CodeCache
140 int NMethodSweeper::_flushed_count = 0; // Nof. nmethods flushed in current sweep
141 int NMethodSweeper::_zombified_count = 0; // Nof. nmethods made zombie in current sweep
142 int NMethodSweeper::_marked_for_reclamation_count = 0; // Nof. nmethods marked for reclaim in current sweep
144 volatile bool NMethodSweeper::_should_sweep = true; // Indicates if we should invoke the sweeper
145 volatile int NMethodSweeper::_sweep_fractions_left = 0; // Nof. invocations left until we are completed with this pass
146 volatile int NMethodSweeper::_sweep_started = 0; // Flag to control conc sweeper
147 volatile int NMethodSweeper::_bytes_changed = 0; // Counts the total nmethod size if the nmethod changed from:
148 // 1) alive -> not_entrant
149 // 2) not_entrant -> zombie
150 // 3) zombie -> marked_for_reclamation
151 int NMethodSweeper::_hotness_counter_reset_val = 0;
153 long NMethodSweeper::_total_nof_methods_reclaimed = 0; // Accumulated nof methods flushed
154 long NMethodSweeper::_total_nof_c2_methods_reclaimed = 0; // Accumulated nof methods flushed
155 size_t NMethodSweeper::_total_flushed_size = 0; // Total number of bytes flushed from the code cache
156 Tickspan NMethodSweeper::_total_time_sweeping; // Accumulated time sweeping
157 Tickspan NMethodSweeper::_total_time_this_sweep; // Total time this sweep
158 Tickspan NMethodSweeper::_peak_sweep_time; // Peak time for a full sweep
159 Tickspan NMethodSweeper::_peak_sweep_fraction_time; // Peak time sweeping one fraction
163 class MarkActivationClosure: public CodeBlobClosure {
164 public:
165 virtual void do_code_blob(CodeBlob* cb) {
166 if (cb->is_nmethod()) {
167 nmethod* nm = (nmethod*)cb;
168 nm->set_hotness_counter(NMethodSweeper::hotness_counter_reset_val());
169 // If we see an activation belonging to a non_entrant nmethod, we mark it.
170 if (nm->is_not_entrant()) {
171 nm->mark_as_seen_on_stack();
172 }
173 }
174 }
175 };
176 static MarkActivationClosure mark_activation_closure;
178 class SetHotnessClosure: public CodeBlobClosure {
179 public:
180 virtual void do_code_blob(CodeBlob* cb) {
181 if (cb->is_nmethod()) {
182 nmethod* nm = (nmethod*)cb;
183 nm->set_hotness_counter(NMethodSweeper::hotness_counter_reset_val());
184 }
185 }
186 };
187 static SetHotnessClosure set_hotness_closure;
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::sweep_in_progress() {
197 return (_current != NULL);
198 }
200 // Scans the stacks of all Java threads and marks activations of not-entrant methods.
201 // No need to synchronize access, since 'mark_active_nmethods' is always executed at a
202 // safepoint.
203 void NMethodSweeper::mark_active_nmethods() {
204 assert(SafepointSynchronize::is_at_safepoint(), "must be executed at a safepoint");
205 // If we do not want to reclaim not-entrant or zombie methods there is no need
206 // to scan stacks
207 if (!MethodFlushing) {
208 return;
209 }
211 // Increase time so that we can estimate when to invoke the sweeper again.
212 _time_counter++;
214 // Check for restart
215 assert(CodeCache::find_blob_unsafe(_current) == _current, "Sweeper nmethod cached state invalid");
216 if (!sweep_in_progress()) {
217 _seen = 0;
218 _sweep_fractions_left = NmethodSweepFraction;
219 _current = CodeCache::first_nmethod();
220 _traversals += 1;
221 _total_time_this_sweep = Tickspan();
223 if (PrintMethodFlushing) {
224 tty->print_cr("### Sweep: stack traversal %d", _traversals);
225 }
226 Threads::nmethods_do(&mark_activation_closure);
228 } else {
229 // Only set hotness counter
230 Threads::nmethods_do(&set_hotness_closure);
231 }
233 OrderAccess::storestore();
234 }
235 /**
236 * This function invokes the sweeper if at least one of the three conditions is met:
237 * (1) The code cache is getting full
238 * (2) There are sufficient state changes in/since the last sweep.
239 * (3) We have not been sweeping for 'some time'
240 */
241 void NMethodSweeper::possibly_sweep() {
242 assert(JavaThread::current()->thread_state() == _thread_in_vm, "must run in vm mode");
243 // Only compiler threads are allowed to sweep
244 if (!MethodFlushing || !sweep_in_progress() || !Thread::current()->is_Compiler_thread()) {
245 return;
246 }
248 // If there was no state change while nmethod sweeping, 'should_sweep' will be false.
249 // This is one of the two places where should_sweep can be set to true. The general
250 // idea is as follows: If there is enough free space in the code cache, there is no
251 // need to invoke the sweeper. The following formula (which determines whether to invoke
252 // the sweeper or not) depends on the assumption that for larger ReservedCodeCacheSizes
253 // we need less frequent sweeps than for smaller ReservedCodecCacheSizes. Furthermore,
254 // the formula considers how much space in the code cache is currently used. Here are
255 // some examples that will (hopefully) help in understanding.
256 //
257 // Small ReservedCodeCacheSizes: (e.g., < 16M) We invoke the sweeper every time, since
258 // the result of the division is 0. This
259 // keeps the used code cache size small
260 // (important for embedded Java)
261 // Large ReservedCodeCacheSize : (e.g., 256M + code cache is 10% full). The formula
262 // computes: (256 / 16) - 1 = 15
263 // As a result, we invoke the sweeper after
264 // 15 invocations of 'mark_active_nmethods.
265 // Large ReservedCodeCacheSize: (e.g., 256M + code Cache is 90% full). The formula
266 // computes: (256 / 16) - 10 = 6.
267 if (!_should_sweep) {
268 const int time_since_last_sweep = _time_counter - _last_sweep;
269 // ReservedCodeCacheSize has an 'unsigned' type. We need a 'signed' type for max_wait_time,
270 // since 'time_since_last_sweep' can be larger than 'max_wait_time'. If that happens using
271 // an unsigned type would cause an underflow (wait_until_next_sweep becomes a large positive
272 // value) that disables the intended periodic sweeps.
273 const int max_wait_time = ReservedCodeCacheSize / (16 * M);
274 double wait_until_next_sweep = max_wait_time - time_since_last_sweep - CodeCache::reverse_free_ratio();
275 assert(wait_until_next_sweep <= (double)max_wait_time, "Calculation of code cache sweeper interval is incorrect");
277 if ((wait_until_next_sweep <= 0.0) || !CompileBroker::should_compile_new_jobs()) {
278 _should_sweep = true;
279 }
280 }
282 if (_should_sweep && _sweep_fractions_left > 0) {
283 // Only one thread at a time will sweep
284 jint old = Atomic::cmpxchg( 1, &_sweep_started, 0 );
285 if (old != 0) {
286 return;
287 }
288 #ifdef ASSERT
289 if (LogSweeper && _records == NULL) {
290 // Create the ring buffer for the logging code
291 _records = NEW_C_HEAP_ARRAY(SweeperRecord, SweeperLogEntries, mtGC);
292 memset(_records, 0, sizeof(SweeperRecord) * SweeperLogEntries);
293 }
294 #endif
296 if (_sweep_fractions_left > 0) {
297 sweep_code_cache();
298 _sweep_fractions_left--;
299 }
301 // We are done with sweeping the code cache once.
302 if (_sweep_fractions_left == 0) {
303 _total_nof_code_cache_sweeps++;
304 _last_sweep = _time_counter;
305 // Reset flag; temporarily disables sweeper
306 _should_sweep = false;
307 // If there was enough state change, 'possibly_enable_sweeper()'
308 // sets '_should_sweep' to true
309 possibly_enable_sweeper();
310 // Reset _bytes_changed only if there was enough state change. _bytes_changed
311 // can further increase by calls to 'report_state_change'.
312 if (_should_sweep) {
313 _bytes_changed = 0;
314 }
315 }
316 // Release work, because another compiler thread could continue.
317 OrderAccess::release_store((int*)&_sweep_started, 0);
318 }
319 }
321 static void post_sweep_event(EventSweepCodeCache* event,
322 const Ticks& start,
323 const Ticks& end,
324 s4 traversals,
325 int swept,
326 int flushed,
327 int zombified) {
328 assert(event != NULL, "invariant");
329 assert(event->should_commit(), "invariant");
330 event->set_starttime(start);
331 event->set_endtime(end);
332 event->set_sweepId(traversals);
333 event->set_sweptCount(swept);
334 event->set_flushedCount(flushed);
335 event->set_zombifiedCount(zombified);
336 event->commit();
337 }
339 void NMethodSweeper::sweep_code_cache() {
340 ResourceMark rm;
341 Ticks sweep_start_counter = Ticks::now();
343 _flushed_count = 0;
344 _zombified_count = 0;
345 _marked_for_reclamation_count = 0;
347 if (PrintMethodFlushing && Verbose) {
348 tty->print_cr("### Sweep at %d out of %d. Invocations left: %d", _seen, CodeCache::nof_nmethods(), _sweep_fractions_left);
349 }
351 if (!CompileBroker::should_compile_new_jobs()) {
352 // If we have turned off compilations we might as well do full sweeps
353 // in order to reach the clean state faster. Otherwise the sleeping compiler
354 // threads will slow down sweeping.
355 _sweep_fractions_left = 1;
356 }
358 // We want to visit all nmethods after NmethodSweepFraction
359 // invocations so divide the remaining number of nmethods by the
360 // remaining number of invocations. This is only an estimate since
361 // the number of nmethods changes during the sweep so the final
362 // stage must iterate until it there are no more nmethods.
363 int todo = (CodeCache::nof_nmethods() - _seen) / _sweep_fractions_left;
364 int swept_count = 0;
367 assert(!SafepointSynchronize::is_at_safepoint(), "should not be in safepoint when we get here");
368 assert(!CodeCache_lock->owned_by_self(), "just checking");
370 int freed_memory = 0;
371 {
372 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
374 // The last invocation iterates until there are no more nmethods
375 for (int i = 0; (i < todo || _sweep_fractions_left == 1) && _current != NULL; i++) {
376 swept_count++;
377 if (SafepointSynchronize::is_synchronizing()) { // Safepoint request
378 if (PrintMethodFlushing && Verbose) {
379 tty->print_cr("### Sweep at %d out of %d, invocation: %d, yielding to safepoint", _seen, CodeCache::nof_nmethods(), _sweep_fractions_left);
380 }
381 MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
383 assert(Thread::current()->is_Java_thread(), "should be java thread");
384 JavaThread* thread = (JavaThread*)Thread::current();
385 ThreadBlockInVM tbivm(thread);
386 thread->java_suspend_self();
387 }
388 // Since we will give up the CodeCache_lock, always skip ahead
389 // to the next nmethod. Other blobs can be deleted by other
390 // threads but nmethods are only reclaimed by the sweeper.
391 nmethod* next = CodeCache::next_nmethod(_current);
393 // Now ready to process nmethod and give up CodeCache_lock
394 {
395 MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
396 freed_memory += process_nmethod(_current);
397 }
398 _seen++;
399 _current = next;
400 }
401 }
403 assert(_sweep_fractions_left > 1 || _current == NULL, "must have scanned the whole cache");
405 const Ticks sweep_end_counter = Ticks::now();
406 const Tickspan sweep_time = sweep_end_counter - sweep_start_counter;
407 _total_time_sweeping += sweep_time;
408 _total_time_this_sweep += sweep_time;
409 _peak_sweep_fraction_time = MAX2(sweep_time, _peak_sweep_fraction_time);
410 _total_flushed_size += freed_memory;
411 _total_nof_methods_reclaimed += _flushed_count;
413 EventSweepCodeCache event(UNTIMED);
414 if (event.should_commit()) {
415 post_sweep_event(&event, sweep_start_counter, sweep_end_counter, (s4)_traversals, swept_count, _flushed_count, _zombified_count);
416 }
418 #ifdef ASSERT
419 if(PrintMethodFlushing) {
420 tty->print_cr("### sweeper: sweep time(%d): "
421 INT64_FORMAT, _sweep_fractions_left, (jlong)sweep_time.value());
422 }
423 #endif
425 if (_sweep_fractions_left == 1) {
426 _peak_sweep_time = MAX2(_peak_sweep_time, _total_time_this_sweep);
427 log_sweep("finished");
428 }
430 // Sweeper is the only case where memory is released, check here if it
431 // is time to restart the compiler. Only checking if there is a certain
432 // amount of free memory in the code cache might lead to re-enabling
433 // compilation although no memory has been released. For example, there are
434 // cases when compilation was disabled although there is 4MB (or more) free
435 // memory in the code cache. The reason is code cache fragmentation. Therefore,
436 // it only makes sense to re-enable compilation if we have actually freed memory.
437 // Note that typically several kB are released for sweeping 16MB of the code
438 // cache. As a result, 'freed_memory' > 0 to restart the compiler.
439 if (!CompileBroker::should_compile_new_jobs() && (freed_memory > 0)) {
440 CompileBroker::set_should_compile_new_jobs(CompileBroker::run_compilation);
441 log_sweep("restart_compiler");
442 }
443 }
445 /**
446 * This function updates the sweeper statistics that keep track of nmethods
447 * state changes. If there is 'enough' state change, the sweeper is invoked
448 * as soon as possible. There can be data races on _bytes_changed. The data
449 * races are benign, since it does not matter if we loose a couple of bytes.
450 * In the worst case we call the sweeper a little later. Also, we are guaranteed
451 * to invoke the sweeper if the code cache gets full.
452 */
453 void NMethodSweeper::report_state_change(nmethod* nm) {
454 _bytes_changed += nm->total_size();
455 possibly_enable_sweeper();
456 }
458 /**
459 * Function determines if there was 'enough' state change in the code cache to invoke
460 * the sweeper again. Currently, we determine 'enough' as more than 1% state change in
461 * the code cache since the last sweep.
462 */
463 void NMethodSweeper::possibly_enable_sweeper() {
464 double percent_changed = ((double)_bytes_changed / (double)ReservedCodeCacheSize) * 100;
465 if (percent_changed > 1.0) {
466 _should_sweep = true;
467 }
468 }
470 class NMethodMarker: public StackObj {
471 private:
472 CompilerThread* _thread;
473 public:
474 NMethodMarker(nmethod* nm) {
475 _thread = CompilerThread::current();
476 if (!nm->is_zombie() && !nm->is_unloaded()) {
477 // Only expose live nmethods for scanning
478 _thread->set_scanned_nmethod(nm);
479 }
480 }
481 ~NMethodMarker() {
482 _thread->set_scanned_nmethod(NULL);
483 }
484 };
486 void NMethodSweeper::release_nmethod(nmethod *nm) {
487 // Clean up any CompiledICHolders
488 {
489 ResourceMark rm;
490 MutexLocker ml_patch(CompiledIC_lock);
491 RelocIterator iter(nm);
492 while (iter.next()) {
493 if (iter.type() == relocInfo::virtual_call_type) {
494 CompiledIC::cleanup_call_site(iter.virtual_call_reloc());
495 }
496 }
497 }
499 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
500 nm->flush();
501 }
503 int NMethodSweeper::process_nmethod(nmethod *nm) {
504 assert(!CodeCache_lock->owned_by_self(), "just checking");
506 int freed_memory = 0;
507 // Make sure this nmethod doesn't get unloaded during the scan,
508 // since safepoints may happen during acquired below locks.
509 NMethodMarker nmm(nm);
510 SWEEP(nm);
512 // Skip methods that are currently referenced by the VM
513 if (nm->is_locked_by_vm()) {
514 // But still remember to clean-up inline caches for alive nmethods
515 if (nm->is_alive()) {
516 // Clean inline caches that point to zombie/non-entrant methods
517 MutexLocker cl(CompiledIC_lock);
518 nm->cleanup_inline_caches();
519 SWEEP(nm);
520 }
521 return freed_memory;
522 }
524 if (nm->is_zombie()) {
525 // If it is the first time we see nmethod then we mark it. Otherwise,
526 // we reclaim it. When we have seen a zombie method twice, we know that
527 // there are no inline caches that refer to it.
528 if (nm->is_marked_for_reclamation()) {
529 assert(!nm->is_locked_by_vm(), "must not flush locked nmethods");
530 if (PrintMethodFlushing && Verbose) {
531 tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (marked for reclamation) being flushed", nm->compile_id(), nm);
532 }
533 freed_memory = nm->total_size();
534 if (nm->is_compiled_by_c2()) {
535 _total_nof_c2_methods_reclaimed++;
536 }
537 release_nmethod(nm);
538 _flushed_count++;
539 } else {
540 if (PrintMethodFlushing && Verbose) {
541 tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (zombie) being marked for reclamation", nm->compile_id(), nm);
542 }
543 nm->mark_for_reclamation();
544 // Keep track of code cache state change
545 _bytes_changed += nm->total_size();
546 _marked_for_reclamation_count++;
547 SWEEP(nm);
548 }
549 } else if (nm->is_not_entrant()) {
550 // If there are no current activations of this method on the
551 // stack we can safely convert it to a zombie method
552 if (nm->can_convert_to_zombie()) {
553 if (PrintMethodFlushing && Verbose) {
554 tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (not entrant) being made zombie", nm->compile_id(), nm);
555 }
556 // Clear ICStubs to prevent back patching stubs of zombie or unloaded
557 // nmethods during the next safepoint (see ICStub::finalize).
558 MutexLocker cl(CompiledIC_lock);
559 nm->clear_ic_stubs();
560 // Code cache state change is tracked in make_zombie()
561 nm->make_zombie();
562 _zombified_count++;
563 SWEEP(nm);
564 } else {
565 // Still alive, clean up its inline caches
566 MutexLocker cl(CompiledIC_lock);
567 nm->cleanup_inline_caches();
568 SWEEP(nm);
569 }
570 } else if (nm->is_unloaded()) {
571 // Unloaded code, just make it a zombie
572 if (PrintMethodFlushing && Verbose) {
573 tty->print_cr("### Nmethod %3d/" PTR_FORMAT " (unloaded) being made zombie", nm->compile_id(), nm);
574 }
575 if (nm->is_osr_method()) {
576 SWEEP(nm);
577 // No inline caches will ever point to osr methods, so we can just remove it
578 freed_memory = nm->total_size();
579 if (nm->is_compiled_by_c2()) {
580 _total_nof_c2_methods_reclaimed++;
581 }
582 release_nmethod(nm);
583 _flushed_count++;
584 } else {
585 {
586 // Clean ICs of unloaded nmethods as well because they may reference other
587 // unloaded nmethods that may be flushed earlier in the sweeper cycle.
588 MutexLocker cl(CompiledIC_lock);
589 nm->cleanup_inline_caches();
590 }
591 // Code cache state change is tracked in make_zombie()
592 nm->make_zombie();
593 _zombified_count++;
594 SWEEP(nm);
595 }
596 } else {
597 if (UseCodeCacheFlushing) {
598 if (!nm->is_locked_by_vm() && !nm->is_osr_method() && !nm->is_native_method()) {
599 // Do not make native methods and OSR-methods not-entrant
600 nm->dec_hotness_counter();
601 // Get the initial value of the hotness counter. This value depends on the
602 // ReservedCodeCacheSize
603 int reset_val = hotness_counter_reset_val();
604 int time_since_reset = reset_val - nm->hotness_counter();
605 double threshold = -reset_val + (CodeCache::reverse_free_ratio() * NmethodSweepActivity);
606 // The less free space in the code cache we have - the bigger reverse_free_ratio() is.
607 // I.e., 'threshold' increases with lower available space in the code cache and a higher
608 // NmethodSweepActivity. If the current hotness counter - which decreases from its initial
609 // value until it is reset by stack walking - is smaller than the computed threshold, the
610 // corresponding nmethod is considered for removal.
611 if ((NmethodSweepActivity > 0) && (nm->hotness_counter() < threshold) && (time_since_reset > 10)) {
612 // A method is marked as not-entrant if the method is
613 // 1) 'old enough': nm->hotness_counter() < threshold
614 // 2) The method was in_use for a minimum amount of time: (time_since_reset > 10)
615 // The second condition is necessary if we are dealing with very small code cache
616 // sizes (e.g., <10m) and the code cache size is too small to hold all hot methods.
617 // The second condition ensures that methods are not immediately made not-entrant
618 // after compilation.
619 nm->make_not_entrant();
620 // Code cache state change is tracked in make_not_entrant()
621 if (PrintMethodFlushing && Verbose) {
622 tty->print_cr("### Nmethod %d/" PTR_FORMAT "made not-entrant: hotness counter %d/%d threshold %f",
623 nm->compile_id(), nm, nm->hotness_counter(), reset_val, threshold);
624 }
625 }
626 }
627 }
628 // Clean-up all inline caches that point to zombie/non-reentrant methods
629 MutexLocker cl(CompiledIC_lock);
630 nm->cleanup_inline_caches();
631 SWEEP(nm);
632 }
633 return freed_memory;
634 }
636 // Print out some state information about the current sweep and the
637 // state of the code cache if it's requested.
638 void NMethodSweeper::log_sweep(const char* msg, const char* format, ...) {
639 if (PrintMethodFlushing) {
640 ResourceMark rm;
641 stringStream s;
642 // Dump code cache state into a buffer before locking the tty,
643 // because log_state() will use locks causing lock conflicts.
644 CodeCache::log_state(&s);
646 ttyLocker ttyl;
647 tty->print("### sweeper: %s ", msg);
648 if (format != NULL) {
649 va_list ap;
650 va_start(ap, format);
651 tty->vprint(format, ap);
652 va_end(ap);
653 }
654 tty->print_cr("%s", s.as_string());
655 }
657 if (LogCompilation && (xtty != NULL)) {
658 ResourceMark rm;
659 stringStream s;
660 // Dump code cache state into a buffer before locking the tty,
661 // because log_state() will use locks causing lock conflicts.
662 CodeCache::log_state(&s);
664 ttyLocker ttyl;
665 xtty->begin_elem("sweeper state='%s' traversals='" INTX_FORMAT "' ", msg, (intx)traversal_count());
666 if (format != NULL) {
667 va_list ap;
668 va_start(ap, format);
669 xtty->vprint(format, ap);
670 va_end(ap);
671 }
672 xtty->print("%s", s.as_string());
673 xtty->stamp();
674 xtty->end_elem();
675 }
676 }
678 void NMethodSweeper::print() {
679 ttyLocker ttyl;
680 tty->print_cr("Code cache sweeper statistics:");
681 tty->print_cr(" Total sweep time: %1.0lfms", (double)_total_time_sweeping.value()/1000000);
682 tty->print_cr(" Total number of full sweeps: %ld", _total_nof_code_cache_sweeps);
683 tty->print_cr(" Total number of flushed methods: %ld(%ld C2 methods)", _total_nof_methods_reclaimed,
684 _total_nof_c2_methods_reclaimed);
685 tty->print_cr(" Total size of flushed methods: " SIZE_FORMAT "kB", _total_flushed_size/K);
686 }