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