Tue, 08 Jan 2013 14:04:25 -0500
8005048: NMT: #loaded classes needs to just show the # defined classes
Summary: Count number of instance classes so that it matches class metadata size
Reviewed-by: coleenp, acorn
1 /*
2 * Copyright (c) 2012, 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 #include "precompiled.hpp"
26 #include "oops/instanceKlass.hpp"
27 #include "runtime/atomic.hpp"
28 #include "runtime/interfaceSupport.hpp"
29 #include "runtime/mutexLocker.hpp"
30 #include "runtime/safepoint.hpp"
31 #include "runtime/threadCritical.hpp"
32 #include "services/memPtr.hpp"
33 #include "services/memReporter.hpp"
34 #include "services/memTracker.hpp"
35 #include "utilities/decoder.hpp"
36 #include "utilities/globalDefinitions.hpp"
38 bool NMT_track_callsite = false;
40 // walk all 'known' threads at NMT sync point, and collect their recorders
41 void SyncThreadRecorderClosure::do_thread(Thread* thread) {
42 assert(SafepointSynchronize::is_at_safepoint(), "Safepoint required");
43 if (thread->is_Java_thread()) {
44 JavaThread* javaThread = (JavaThread*)thread;
45 MemRecorder* recorder = javaThread->get_recorder();
46 if (recorder != NULL) {
47 MemTracker::enqueue_pending_recorder(recorder);
48 javaThread->set_recorder(NULL);
49 }
50 }
51 _thread_count ++;
52 }
55 MemRecorder* MemTracker::_global_recorder = NULL;
56 MemSnapshot* MemTracker::_snapshot = NULL;
57 MemBaseline MemTracker::_baseline;
58 Mutex* MemTracker::_query_lock = NULL;
59 volatile MemRecorder* MemTracker::_merge_pending_queue = NULL;
60 volatile MemRecorder* MemTracker::_pooled_recorders = NULL;
61 MemTrackWorker* MemTracker::_worker_thread = NULL;
62 int MemTracker::_sync_point_skip_count = 0;
63 MemTracker::NMTLevel MemTracker::_tracking_level = MemTracker::NMT_off;
64 volatile MemTracker::NMTStates MemTracker::_state = NMT_uninited;
65 MemTracker::ShutdownReason MemTracker::_reason = NMT_shutdown_none;
66 int MemTracker::_thread_count = 255;
67 volatile jint MemTracker::_pooled_recorder_count = 0;
68 debug_only(intx MemTracker::_main_thread_tid = 0;)
69 NOT_PRODUCT(volatile jint MemTracker::_pending_recorder_count = 0;)
71 void MemTracker::init_tracking_options(const char* option_line) {
72 _tracking_level = NMT_off;
73 if (strcmp(option_line, "=summary") == 0) {
74 _tracking_level = NMT_summary;
75 } else if (strcmp(option_line, "=detail") == 0) {
76 _tracking_level = NMT_detail;
77 } else if (strcmp(option_line, "=off") != 0) {
78 vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
79 }
80 }
82 // first phase of bootstrapping, when VM is still in single-threaded mode.
83 void MemTracker::bootstrap_single_thread() {
84 if (_tracking_level > NMT_off) {
85 assert(_state == NMT_uninited, "wrong state");
87 // NMT is not supported with UseMallocOnly is on. NMT can NOT
88 // handle the amount of malloc data without significantly impacting
89 // runtime performance when this flag is on.
90 if (UseMallocOnly) {
91 shutdown(NMT_use_malloc_only);
92 return;
93 }
95 _query_lock = new (std::nothrow) Mutex(Monitor::max_nonleaf, "NMT_queryLock");
96 if (_query_lock == NULL) {
97 shutdown(NMT_out_of_memory);
98 return;
99 }
101 debug_only(_main_thread_tid = os::current_thread_id();)
102 _state = NMT_bootstrapping_single_thread;
103 NMT_track_callsite = (_tracking_level == NMT_detail && can_walk_stack());
104 }
105 }
107 // second phase of bootstrapping, when VM is about to or already entered multi-theaded mode.
108 void MemTracker::bootstrap_multi_thread() {
109 if (_tracking_level > NMT_off && _state == NMT_bootstrapping_single_thread) {
110 // create nmt lock for multi-thread execution
111 assert(_main_thread_tid == os::current_thread_id(), "wrong thread");
112 _state = NMT_bootstrapping_multi_thread;
113 NMT_track_callsite = (_tracking_level == NMT_detail && can_walk_stack());
114 }
115 }
117 // fully start nmt
118 void MemTracker::start() {
119 // Native memory tracking is off from command line option
120 if (_tracking_level == NMT_off || shutdown_in_progress()) return;
122 assert(_main_thread_tid == os::current_thread_id(), "wrong thread");
123 assert(_state == NMT_bootstrapping_multi_thread, "wrong state");
125 _snapshot = new (std::nothrow)MemSnapshot();
126 if (_snapshot != NULL && !_snapshot->out_of_memory()) {
127 if (start_worker()) {
128 _state = NMT_started;
129 NMT_track_callsite = (_tracking_level == NMT_detail && can_walk_stack());
130 return;
131 }
132 }
134 // fail to start native memory tracking, shut it down
135 shutdown(NMT_initialization);
136 }
138 /**
139 * Shutting down native memory tracking.
140 * We can not shutdown native memory tracking immediately, so we just
141 * setup shutdown pending flag, every native memory tracking component
142 * should orderly shut itself down.
143 *
144 * The shutdown sequences:
145 * 1. MemTracker::shutdown() sets MemTracker to shutdown pending state
146 * 2. Worker thread calls MemTracker::final_shutdown(), which transites
147 * MemTracker to final shutdown state.
148 * 3. At sync point, MemTracker does final cleanup, before sets memory
149 * tracking level to off to complete shutdown.
150 */
151 void MemTracker::shutdown(ShutdownReason reason) {
152 if (_tracking_level == NMT_off) return;
154 if (_state <= NMT_bootstrapping_single_thread) {
155 // we still in single thread mode, there is not contention
156 _state = NMT_shutdown_pending;
157 _reason = reason;
158 } else {
159 // we want to know who initialized shutdown
160 if ((jint)NMT_started == Atomic::cmpxchg((jint)NMT_shutdown_pending,
161 (jint*)&_state, (jint)NMT_started)) {
162 _reason = reason;
163 }
164 }
165 }
167 // final phase of shutdown
168 void MemTracker::final_shutdown() {
169 // delete all pending recorders and pooled recorders
170 delete_all_pending_recorders();
171 delete_all_pooled_recorders();
173 {
174 // shared baseline and snapshot are the only objects needed to
175 // create query results
176 MutexLockerEx locker(_query_lock, true);
177 // cleanup baseline data and snapshot
178 _baseline.clear();
179 delete _snapshot;
180 _snapshot = NULL;
181 }
183 // shutdown shared decoder instance, since it is only
184 // used by native memory tracking so far.
185 Decoder::shutdown();
187 MemTrackWorker* worker = NULL;
188 {
189 ThreadCritical tc;
190 // can not delete worker inside the thread critical
191 if (_worker_thread != NULL && Thread::current() == _worker_thread) {
192 worker = _worker_thread;
193 _worker_thread = NULL;
194 }
195 }
196 if (worker != NULL) {
197 delete worker;
198 }
199 _state = NMT_final_shutdown;
200 }
202 // delete all pooled recorders
203 void MemTracker::delete_all_pooled_recorders() {
204 // free all pooled recorders
205 volatile MemRecorder* cur_head = _pooled_recorders;
206 if (cur_head != NULL) {
207 MemRecorder* null_ptr = NULL;
208 while (cur_head != NULL && (void*)cur_head != Atomic::cmpxchg_ptr((void*)null_ptr,
209 (void*)&_pooled_recorders, (void*)cur_head)) {
210 cur_head = _pooled_recorders;
211 }
212 if (cur_head != NULL) {
213 delete cur_head;
214 _pooled_recorder_count = 0;
215 }
216 }
217 }
219 // delete all recorders in pending queue
220 void MemTracker::delete_all_pending_recorders() {
221 // free all pending recorders
222 MemRecorder* pending_head = get_pending_recorders();
223 if (pending_head != NULL) {
224 delete pending_head;
225 }
226 }
228 /*
229 * retrieve per-thread recorder of specified thread.
230 * if thread == NULL, it means global recorder
231 */
232 MemRecorder* MemTracker::get_thread_recorder(JavaThread* thread) {
233 if (shutdown_in_progress()) return NULL;
235 MemRecorder* rc;
236 if (thread == NULL) {
237 rc = _global_recorder;
238 } else {
239 rc = thread->get_recorder();
240 }
242 if (rc != NULL && rc->is_full()) {
243 enqueue_pending_recorder(rc);
244 rc = NULL;
245 }
247 if (rc == NULL) {
248 rc = get_new_or_pooled_instance();
249 if (thread == NULL) {
250 _global_recorder = rc;
251 } else {
252 thread->set_recorder(rc);
253 }
254 }
255 return rc;
256 }
258 /*
259 * get a per-thread recorder from pool, or create a new one if
260 * there is not one available.
261 */
262 MemRecorder* MemTracker::get_new_or_pooled_instance() {
263 MemRecorder* cur_head = const_cast<MemRecorder*> (_pooled_recorders);
264 if (cur_head == NULL) {
265 MemRecorder* rec = new (std::nothrow)MemRecorder();
266 if (rec == NULL || rec->out_of_memory()) {
267 shutdown(NMT_out_of_memory);
268 if (rec != NULL) {
269 delete rec;
270 rec = NULL;
271 }
272 }
273 return rec;
274 } else {
275 MemRecorder* next_head = cur_head->next();
276 if ((void*)cur_head != Atomic::cmpxchg_ptr((void*)next_head, (void*)&_pooled_recorders,
277 (void*)cur_head)) {
278 return get_new_or_pooled_instance();
279 }
280 cur_head->set_next(NULL);
281 Atomic::dec(&_pooled_recorder_count);
282 debug_only(cur_head->set_generation();)
283 return cur_head;
284 }
285 }
287 /*
288 * retrieve all recorders in pending queue, and empty the queue
289 */
290 MemRecorder* MemTracker::get_pending_recorders() {
291 MemRecorder* cur_head = const_cast<MemRecorder*>(_merge_pending_queue);
292 MemRecorder* null_ptr = NULL;
293 while ((void*)cur_head != Atomic::cmpxchg_ptr((void*)null_ptr, (void*)&_merge_pending_queue,
294 (void*)cur_head)) {
295 cur_head = const_cast<MemRecorder*>(_merge_pending_queue);
296 }
297 NOT_PRODUCT(Atomic::store(0, &_pending_recorder_count));
298 return cur_head;
299 }
301 /*
302 * release a recorder to recorder pool.
303 */
304 void MemTracker::release_thread_recorder(MemRecorder* rec) {
305 assert(rec != NULL, "null recorder");
306 // we don't want to pool too many recorders
307 rec->set_next(NULL);
308 if (shutdown_in_progress() || _pooled_recorder_count > _thread_count * 2) {
309 delete rec;
310 return;
311 }
313 rec->clear();
314 MemRecorder* cur_head = const_cast<MemRecorder*>(_pooled_recorders);
315 rec->set_next(cur_head);
316 while ((void*)cur_head != Atomic::cmpxchg_ptr((void*)rec, (void*)&_pooled_recorders,
317 (void*)cur_head)) {
318 cur_head = const_cast<MemRecorder*>(_pooled_recorders);
319 rec->set_next(cur_head);
320 }
321 Atomic::inc(&_pooled_recorder_count);
322 }
324 /*
325 * This is the most important method in whole nmt implementation.
326 *
327 * Create a memory record.
328 * 1. When nmt is in single-threaded bootstrapping mode, no lock is needed as VM
329 * still in single thread mode.
330 * 2. For all threads other than JavaThread, ThreadCritical is needed
331 * to write to recorders to global recorder.
332 * 3. For JavaThreads that are not longer visible by safepoint, also
333 * need to take ThreadCritical and records are written to global
334 * recorders, since these threads are NOT walked by Threads.do_thread().
335 * 4. JavaThreads that are running in native state, have to transition
336 * to VM state before writing to per-thread recorders.
337 * 5. JavaThreads that are running in VM state do not need any lock and
338 * records are written to per-thread recorders.
339 * 6. For a thread has yet to attach VM 'Thread', they need to take
340 * ThreadCritical to write to global recorder.
341 *
342 * Important note:
343 * NO LOCK should be taken inside ThreadCritical lock !!!
344 */
345 void MemTracker::create_memory_record(address addr, MEMFLAGS flags,
346 size_t size, address pc, Thread* thread) {
347 assert(addr != NULL, "Sanity check");
348 if (!shutdown_in_progress()) {
349 // single thread, we just write records direct to global recorder,'
350 // with any lock
351 if (_state == NMT_bootstrapping_single_thread) {
352 assert(_main_thread_tid == os::current_thread_id(), "wrong thread");
353 thread = NULL;
354 } else {
355 if (thread == NULL) {
356 // don't use Thread::current(), since it is possible that
357 // the calling thread has yet to attach to VM 'Thread',
358 // which will result assertion failure
359 thread = ThreadLocalStorage::thread();
360 }
361 }
363 if (thread != NULL) {
364 if (thread->is_Java_thread() && ((JavaThread*)thread)->is_safepoint_visible()) {
365 JavaThread* java_thread = (JavaThread*)thread;
366 JavaThreadState state = java_thread->thread_state();
367 if (SafepointSynchronize::safepoint_safe(java_thread, state)) {
368 // JavaThreads that are safepoint safe, can run through safepoint,
369 // so ThreadCritical is needed to ensure no threads at safepoint create
370 // new records while the records are being gathered and the sequence number is changing
371 ThreadCritical tc;
372 create_record_in_recorder(addr, flags, size, pc, java_thread);
373 } else {
374 create_record_in_recorder(addr, flags, size, pc, java_thread);
375 }
376 } else {
377 // other threads, such as worker and watcher threads, etc. need to
378 // take ThreadCritical to write to global recorder
379 ThreadCritical tc;
380 create_record_in_recorder(addr, flags, size, pc, NULL);
381 }
382 } else {
383 if (_state == NMT_bootstrapping_single_thread) {
384 // single thread, no lock needed
385 create_record_in_recorder(addr, flags, size, pc, NULL);
386 } else {
387 // for thread has yet to attach VM 'Thread', we can not use VM mutex.
388 // use native thread critical instead
389 ThreadCritical tc;
390 create_record_in_recorder(addr, flags, size, pc, NULL);
391 }
392 }
393 }
394 }
396 // write a record to proper recorder. No lock can be taken from this method
397 // down.
398 void MemTracker::create_record_in_recorder(address addr, MEMFLAGS flags,
399 size_t size, address pc, JavaThread* thread) {
401 MemRecorder* rc = get_thread_recorder(thread);
402 if (rc != NULL) {
403 rc->record(addr, flags, size, pc);
404 }
405 }
407 /**
408 * enqueue a recorder to pending queue
409 */
410 void MemTracker::enqueue_pending_recorder(MemRecorder* rec) {
411 assert(rec != NULL, "null recorder");
413 // we are shutting down, so just delete it
414 if (shutdown_in_progress()) {
415 rec->set_next(NULL);
416 delete rec;
417 return;
418 }
420 MemRecorder* cur_head = const_cast<MemRecorder*>(_merge_pending_queue);
421 rec->set_next(cur_head);
422 while ((void*)cur_head != Atomic::cmpxchg_ptr((void*)rec, (void*)&_merge_pending_queue,
423 (void*)cur_head)) {
424 cur_head = const_cast<MemRecorder*>(_merge_pending_queue);
425 rec->set_next(cur_head);
426 }
427 NOT_PRODUCT(Atomic::inc(&_pending_recorder_count);)
428 }
430 /*
431 * The method is called at global safepoint
432 * during it synchronization process.
433 * 1. enqueue all JavaThreads' per-thread recorders
434 * 2. enqueue global recorder
435 * 3. retrieve all pending recorders
436 * 4. reset global sequence number generator
437 * 5. call worker's sync
438 */
439 #define MAX_SAFEPOINTS_TO_SKIP 128
440 #define SAFE_SEQUENCE_THRESHOLD 30
441 #define HIGH_GENERATION_THRESHOLD 60
443 void MemTracker::sync() {
444 assert(_tracking_level > NMT_off, "NMT is not enabled");
445 assert(SafepointSynchronize::is_at_safepoint(), "Safepoint required");
447 // Some GC tests hit large number of safepoints in short period of time
448 // without meaningful activities. We should prevent going to
449 // sync point in these cases, which can potentially exhaust generation buffer.
450 // Here is the factots to determine if we should go into sync point:
451 // 1. not to overflow sequence number
452 // 2. if we are in danger to overflow generation buffer
453 // 3. how many safepoints we already skipped sync point
454 if (_state == NMT_started) {
455 // worker thread is not ready, no one can manage generation
456 // buffer, so skip this safepoint
457 if (_worker_thread == NULL) return;
459 if (_sync_point_skip_count < MAX_SAFEPOINTS_TO_SKIP) {
460 int per_seq_in_use = SequenceGenerator::peek() * 100 / max_jint;
461 int per_gen_in_use = _worker_thread->generations_in_use() * 100 / MAX_GENERATIONS;
462 if (per_seq_in_use < SAFE_SEQUENCE_THRESHOLD && per_gen_in_use >= HIGH_GENERATION_THRESHOLD) {
463 _sync_point_skip_count ++;
464 return;
465 }
466 }
467 _sync_point_skip_count = 0;
468 {
469 // This method is running at safepoint, with ThreadCritical lock,
470 // it should guarantee that NMT is fully sync-ed.
471 ThreadCritical tc;
473 SequenceGenerator::reset();
475 // walk all JavaThreads to collect recorders
476 SyncThreadRecorderClosure stc;
477 Threads::threads_do(&stc);
479 _thread_count = stc.get_thread_count();
480 MemRecorder* pending_recorders = get_pending_recorders();
482 if (_global_recorder != NULL) {
483 _global_recorder->set_next(pending_recorders);
484 pending_recorders = _global_recorder;
485 _global_recorder = NULL;
486 }
487 // check _worker_thread with lock to avoid racing condition
488 if (_worker_thread != NULL) {
489 _worker_thread->at_sync_point(pending_recorders, InstanceKlass::number_of_instance_classes());
490 }
492 assert(SequenceGenerator::peek() == 1, "Should not have memory activities during sync-point");
493 }
494 }
496 // now, it is the time to shut whole things off
497 if (_state == NMT_final_shutdown) {
498 // walk all JavaThreads to delete all recorders
499 SyncThreadRecorderClosure stc;
500 Threads::threads_do(&stc);
501 // delete global recorder
502 {
503 ThreadCritical tc;
504 if (_global_recorder != NULL) {
505 delete _global_recorder;
506 _global_recorder = NULL;
507 }
508 }
509 MemRecorder* pending_recorders = get_pending_recorders();
510 if (pending_recorders != NULL) {
511 delete pending_recorders;
512 }
513 // try at a later sync point to ensure MemRecorder instance drops to zero to
514 // completely shutdown NMT
515 if (MemRecorder::_instance_count == 0) {
516 _state = NMT_shutdown;
517 _tracking_level = NMT_off;
518 }
519 }
520 }
522 /*
523 * Start worker thread.
524 */
525 bool MemTracker::start_worker() {
526 assert(_worker_thread == NULL, "Just Check");
527 _worker_thread = new (std::nothrow) MemTrackWorker();
528 if (_worker_thread == NULL || _worker_thread->has_error()) {
529 shutdown(NMT_initialization);
530 return false;
531 }
532 _worker_thread->start();
533 return true;
534 }
536 /*
537 * We need to collect a JavaThread's per-thread recorder
538 * before it exits.
539 */
540 void MemTracker::thread_exiting(JavaThread* thread) {
541 if (is_on()) {
542 MemRecorder* rec = thread->get_recorder();
543 if (rec != NULL) {
544 enqueue_pending_recorder(rec);
545 thread->set_recorder(NULL);
546 }
547 }
548 }
550 // baseline current memory snapshot
551 bool MemTracker::baseline() {
552 MutexLockerEx lock(_query_lock, true);
553 MemSnapshot* snapshot = get_snapshot();
554 if (snapshot != NULL) {
555 return _baseline.baseline(*snapshot, false);
556 }
557 return false;
558 }
560 // print memory usage from current snapshot
561 bool MemTracker::print_memory_usage(BaselineOutputer& out, size_t unit, bool summary_only) {
562 MemBaseline baseline;
563 MutexLockerEx lock(_query_lock, true);
564 MemSnapshot* snapshot = get_snapshot();
565 if (snapshot != NULL && baseline.baseline(*snapshot, summary_only)) {
566 BaselineReporter reporter(out, unit);
567 reporter.report_baseline(baseline, summary_only);
568 return true;
569 }
570 return false;
571 }
573 // compare memory usage between current snapshot and baseline
574 bool MemTracker::compare_memory_usage(BaselineOutputer& out, size_t unit, bool summary_only) {
575 MutexLockerEx lock(_query_lock, true);
576 if (_baseline.baselined()) {
577 MemBaseline baseline;
578 MemSnapshot* snapshot = get_snapshot();
579 if (snapshot != NULL && baseline.baseline(*snapshot, summary_only)) {
580 BaselineReporter reporter(out, unit);
581 reporter.diff_baselines(baseline, _baseline, summary_only);
582 return true;
583 }
584 }
585 return false;
586 }
588 #ifndef PRODUCT
589 void MemTracker::walk_stack(int toSkip, char* buf, int len) {
590 int cur_len = 0;
591 char tmp[1024];
592 address pc;
594 while (cur_len < len) {
595 pc = os::get_caller_pc(toSkip + 1);
596 if (pc != NULL && os::dll_address_to_function_name(pc, tmp, sizeof(tmp), NULL)) {
597 jio_snprintf(&buf[cur_len], (len - cur_len), "%s\n", tmp);
598 cur_len = (int)strlen(buf);
599 } else {
600 buf[cur_len] = '\0';
601 break;
602 }
603 toSkip ++;
604 }
605 }
607 void MemTracker::print_tracker_stats(outputStream* st) {
608 st->print_cr("\nMemory Tracker Stats:");
609 st->print_cr("\tMax sequence number = %d", SequenceGenerator::max_seq_num());
610 st->print_cr("\tthead count = %d", _thread_count);
611 st->print_cr("\tArena instance = %d", Arena::_instance_count);
612 st->print_cr("\tpooled recorder count = %d", _pooled_recorder_count);
613 st->print_cr("\tqueued recorder count = %d", _pending_recorder_count);
614 st->print_cr("\tmemory recorder instance count = %d", MemRecorder::_instance_count);
615 if (_worker_thread != NULL) {
616 st->print_cr("\tWorker thread:");
617 st->print_cr("\t\tSync point count = %d", _worker_thread->_sync_point_count);
618 st->print_cr("\t\tpending recorder count = %d", _worker_thread->count_pending_recorders());
619 st->print_cr("\t\tmerge count = %d", _worker_thread->_merge_count);
620 } else {
621 st->print_cr("\tWorker thread is not started");
622 }
623 st->print_cr(" ");
625 if (_snapshot != NULL) {
626 _snapshot->print_snapshot_stats(st);
627 } else {
628 st->print_cr("No snapshot");
629 }
630 }
631 #endif