1 /*
   2  * Copyright (c) 2012, 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 #include "precompiled.hpp"
  25 
  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 "runtime/vm_operations.hpp"
  33 #include "services/memPtr.hpp"
  34 #include "services/memReporter.hpp"
  35 #include "services/memTracker.hpp"
  36 #include "utilities/decoder.hpp"
  37 #include "utilities/defaultStream.hpp"
  38 #include "utilities/globalDefinitions.hpp"
  39 
  40 bool NMT_track_callsite = false;
  41 
  42 // walk all 'known' threads at NMT sync point, and collect their recorders
  43 void SyncThreadRecorderClosure::do_thread(Thread* thread) {
  44   assert(SafepointSynchronize::is_at_safepoint(), "Safepoint required");
  45   if (thread->is_Java_thread()) {
  46     JavaThread* javaThread = (JavaThread*)thread;
  47     MemRecorder* recorder = javaThread->get_recorder();
  48     if (recorder != NULL) {
  49       MemTracker::enqueue_pending_recorder(recorder);
  50       javaThread->set_recorder(NULL);
  51     }
  52   }
  53   _thread_count ++;
  54 }
  55 
  56 
  57 MemRecorder* volatile           MemTracker::_global_recorder = NULL;
  58 MemSnapshot*                    MemTracker::_snapshot = NULL;
  59 MemBaseline                     MemTracker::_baseline;
  60 Mutex*                          MemTracker::_query_lock = NULL;
  61 MemRecorder* volatile           MemTracker::_merge_pending_queue = NULL;
  62 MemRecorder* volatile           MemTracker::_pooled_recorders = NULL;
  63 MemTrackWorker*                 MemTracker::_worker_thread = NULL;
  64 int                             MemTracker::_sync_point_skip_count = 0;
  65 MemTracker::NMTLevel            MemTracker::_tracking_level = MemTracker::NMT_off;
  66 volatile MemTracker::NMTStates  MemTracker::_state = NMT_uninited;
  67 MemTracker::ShutdownReason      MemTracker::_reason = NMT_shutdown_none;
  68 int                             MemTracker::_thread_count = 255;
  69 volatile jint                   MemTracker::_pooled_recorder_count = 0;
  70 volatile unsigned long          MemTracker::_processing_generation = 0;
  71 volatile bool                   MemTracker::_worker_thread_idle = false;
  72 volatile jint                   MemTracker::_pending_op_count = 0;
  73 volatile bool                   MemTracker::_slowdown_calling_thread = false;
  74 debug_only(intx                 MemTracker::_main_thread_tid = 0;)
  75 NOT_PRODUCT(volatile jint       MemTracker::_pending_recorder_count = 0;)
  76 
  77 void MemTracker::init_tracking_options(const char* option_line) {
  78   _tracking_level = NMT_off;
  79   if (strcmp(option_line, "=summary") == 0) {
  80     _tracking_level = NMT_summary;
  81   } else if (strcmp(option_line, "=detail") == 0) {
  82     // detail relies on a stack-walking ability that may not
  83     // be available depending on platform and/or compiler flags
  84 #if PLATFORM_NATIVE_STACK_WALKING_SUPPORTED
  85       _tracking_level = NMT_detail;
  86 #else
  87       jio_fprintf(defaultStream::error_stream(),
  88         "NMT detail is not supported on this platform.  Using NMT summary instead.\n");
  89       _tracking_level = NMT_summary;
  90 #endif
  91   } else if (strcmp(option_line, "=off") != 0) {
  92     vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
  93   }
  94 }
  95 
  96 // first phase of bootstrapping, when VM is still in single-threaded mode.
  97 void MemTracker::bootstrap_single_thread() {
  98   if (_tracking_level > NMT_off) {
  99     assert(_state == NMT_uninited, "wrong state");
 100 
 101     // NMT is not supported with UseMallocOnly is on. NMT can NOT
 102     // handle the amount of malloc data without significantly impacting
 103     // runtime performance when this flag is on.
 104     if (UseMallocOnly) {
 105       shutdown(NMT_use_malloc_only);
 106       return;
 107     }
 108 
 109     _query_lock = new (std::nothrow) Mutex(Monitor::max_nonleaf, "NMT_queryLock");
 110     if (_query_lock == NULL) {
 111       shutdown(NMT_out_of_memory);
 112       return;
 113     }
 114 
 115     debug_only(_main_thread_tid = os::current_thread_id();)
 116     _state = NMT_bootstrapping_single_thread;
 117     NMT_track_callsite = (_tracking_level == NMT_detail && can_walk_stack());
 118   }
 119 }
 120 
 121 // second phase of bootstrapping, when VM is about to or already entered multi-theaded mode.
 122 void MemTracker::bootstrap_multi_thread() {
 123   if (_tracking_level > NMT_off && _state == NMT_bootstrapping_single_thread) {
 124   // create nmt lock for multi-thread execution
 125     assert(_main_thread_tid == os::current_thread_id(), "wrong thread");
 126     _state = NMT_bootstrapping_multi_thread;
 127     NMT_track_callsite = (_tracking_level == NMT_detail && can_walk_stack());
 128   }
 129 }
 130 
 131 // fully start nmt
 132 void MemTracker::start() {
 133   // Native memory tracking is off from command line option
 134   if (_tracking_level == NMT_off || shutdown_in_progress()) return;
 135 
 136   assert(_main_thread_tid == os::current_thread_id(), "wrong thread");
 137   assert(_state == NMT_bootstrapping_multi_thread, "wrong state");
 138 
 139   _snapshot = new (std::nothrow)MemSnapshot();
 140   if (_snapshot != NULL) {
 141     if (!_snapshot->out_of_memory() && start_worker(_snapshot)) {
 142       _state = NMT_started;
 143       NMT_track_callsite = (_tracking_level == NMT_detail && can_walk_stack());
 144       return;
 145     }
 146 
 147     delete _snapshot;
 148     _snapshot = NULL;
 149   }
 150 
 151   // fail to start native memory tracking, shut it down
 152   shutdown(NMT_initialization);
 153 }
 154 
 155 /**
 156  * Shutting down native memory tracking.
 157  * We can not shutdown native memory tracking immediately, so we just
 158  * setup shutdown pending flag, every native memory tracking component
 159  * should orderly shut itself down.
 160  *
 161  * The shutdown sequences:
 162  *  1. MemTracker::shutdown() sets MemTracker to shutdown pending state
 163  *  2. Worker thread calls MemTracker::final_shutdown(), which transites
 164  *     MemTracker to final shutdown state.
 165  *  3. At sync point, MemTracker does final cleanup, before sets memory
 166  *     tracking level to off to complete shutdown.
 167  */
 168 void MemTracker::shutdown(ShutdownReason reason) {
 169   if (_tracking_level == NMT_off) return;
 170 
 171   if (_state <= NMT_bootstrapping_single_thread) {
 172     // we still in single thread mode, there is not contention
 173     _state = NMT_shutdown_pending;
 174     _reason = reason;
 175   } else {
 176     // we want to know who initialized shutdown
 177     if ((jint)NMT_started == Atomic::cmpxchg((jint)NMT_shutdown_pending,
 178                                        (jint*)&_state, (jint)NMT_started)) {
 179         _reason = reason;
 180     }
 181   }
 182 }
 183 
 184 // final phase of shutdown
 185 void MemTracker::final_shutdown() {
 186   // delete all pending recorders and pooled recorders
 187   delete_all_pending_recorders();
 188   delete_all_pooled_recorders();
 189 
 190   {
 191     // shared baseline and snapshot are the only objects needed to
 192     // create query results
 193     MutexLockerEx locker(_query_lock, true);
 194     // cleanup baseline data and snapshot
 195     _baseline.clear();
 196     delete _snapshot;
 197     _snapshot = NULL;
 198   }
 199 
 200   // shutdown shared decoder instance, since it is only
 201   // used by native memory tracking so far.
 202   Decoder::shutdown();
 203 
 204   MemTrackWorker* worker = NULL;
 205   {
 206     ThreadCritical tc;
 207     // can not delete worker inside the thread critical
 208     if (_worker_thread != NULL && Thread::current() == _worker_thread) {
 209       worker = _worker_thread;
 210       _worker_thread = NULL;
 211     }
 212   }
 213   if (worker != NULL) {
 214     delete worker;
 215   }
 216   _state = NMT_final_shutdown;
 217 }
 218 
 219 // delete all pooled recorders
 220 void MemTracker::delete_all_pooled_recorders() {
 221   // free all pooled recorders
 222   MemRecorder* volatile cur_head = _pooled_recorders;
 223   if (cur_head != NULL) {
 224     MemRecorder* null_ptr = NULL;
 225     while (cur_head != NULL && (void*)cur_head != Atomic::cmpxchg_ptr((void*)null_ptr,
 226       (void*)&_pooled_recorders, (void*)cur_head)) {
 227       cur_head = _pooled_recorders;
 228     }
 229     if (cur_head != NULL) {
 230       delete cur_head;
 231       _pooled_recorder_count = 0;
 232     }
 233   }
 234 }
 235 
 236 // delete all recorders in pending queue
 237 void MemTracker::delete_all_pending_recorders() {
 238   // free all pending recorders
 239   MemRecorder* pending_head = get_pending_recorders();
 240   if (pending_head != NULL) {
 241     delete pending_head;
 242   }
 243 }
 244 
 245 /*
 246  * retrieve per-thread recorder of specified thread.
 247  * if thread == NULL, it means global recorder
 248  */
 249 MemRecorder* MemTracker::get_thread_recorder(JavaThread* thread) {
 250   if (shutdown_in_progress()) return NULL;
 251 
 252   MemRecorder* rc;
 253   if (thread == NULL) {
 254     rc = _global_recorder;
 255   } else {
 256     rc = thread->get_recorder();
 257   }
 258 
 259   if (rc != NULL && rc->is_full()) {
 260     enqueue_pending_recorder(rc);
 261     rc = NULL;
 262   }
 263 
 264   if (rc == NULL) {
 265     rc = get_new_or_pooled_instance();
 266     if (thread == NULL) {
 267       _global_recorder = rc;
 268     } else {
 269       thread->set_recorder(rc);
 270     }
 271   }
 272   return rc;
 273 }
 274 
 275 /*
 276  * get a per-thread recorder from pool, or create a new one if
 277  * there is not one available.
 278  */
 279 MemRecorder* MemTracker::get_new_or_pooled_instance() {
 280    MemRecorder* cur_head = const_cast<MemRecorder*> (_pooled_recorders);
 281    if (cur_head == NULL) {
 282      MemRecorder* rec = new (std::nothrow)MemRecorder();
 283      if (rec == NULL || rec->out_of_memory()) {
 284        shutdown(NMT_out_of_memory);
 285        if (rec != NULL) {
 286          delete rec;
 287          rec = NULL;
 288        }
 289      }
 290      return rec;
 291    } else {
 292      MemRecorder* next_head = cur_head->next();
 293      if ((void*)cur_head != Atomic::cmpxchg_ptr((void*)next_head, (void*)&_pooled_recorders,
 294        (void*)cur_head)) {
 295        return get_new_or_pooled_instance();
 296      }
 297      cur_head->set_next(NULL);
 298      Atomic::dec(&_pooled_recorder_count);
 299      cur_head->set_generation();
 300      return cur_head;
 301   }
 302 }
 303 
 304 /*
 305  * retrieve all recorders in pending queue, and empty the queue
 306  */
 307 MemRecorder* MemTracker::get_pending_recorders() {
 308   MemRecorder* cur_head = const_cast<MemRecorder*>(_merge_pending_queue);
 309   MemRecorder* null_ptr = NULL;
 310   while ((void*)cur_head != Atomic::cmpxchg_ptr((void*)null_ptr, (void*)&_merge_pending_queue,
 311     (void*)cur_head)) {
 312     cur_head = const_cast<MemRecorder*>(_merge_pending_queue);
 313   }
 314   NOT_PRODUCT(Atomic::store(0, &_pending_recorder_count));
 315   return cur_head;
 316 }
 317 
 318 /*
 319  * release a recorder to recorder pool.
 320  */
 321 void MemTracker::release_thread_recorder(MemRecorder* rec) {
 322   assert(rec != NULL, "null recorder");
 323   // we don't want to pool too many recorders
 324   rec->set_next(NULL);
 325   if (shutdown_in_progress() || _pooled_recorder_count > _thread_count * 2) {
 326     delete rec;
 327     return;
 328   }
 329 
 330   rec->clear();
 331   MemRecorder* cur_head = const_cast<MemRecorder*>(_pooled_recorders);
 332   rec->set_next(cur_head);
 333   while ((void*)cur_head != Atomic::cmpxchg_ptr((void*)rec, (void*)&_pooled_recorders,
 334     (void*)cur_head)) {
 335     cur_head = const_cast<MemRecorder*>(_pooled_recorders);
 336     rec->set_next(cur_head);
 337   }
 338   Atomic::inc(&_pooled_recorder_count);
 339 }
 340 
 341 // write a record to proper recorder. No lock can be taken from this method
 342 // down.
 343 void MemTracker::write_tracking_record(address addr, MEMFLAGS flags,
 344     size_t size, jint seq, address pc, JavaThread* thread) {
 345 
 346     MemRecorder* rc = get_thread_recorder(thread);
 347     if (rc != NULL) {
 348       rc->record(addr, flags, size, seq, pc);
 349     }
 350 }
 351 
 352 /**
 353  * enqueue a recorder to pending queue
 354  */
 355 void MemTracker::enqueue_pending_recorder(MemRecorder* rec) {
 356   assert(rec != NULL, "null recorder");
 357 
 358   // we are shutting down, so just delete it
 359   if (shutdown_in_progress()) {
 360     rec->set_next(NULL);
 361     delete rec;
 362     return;
 363   }
 364 
 365   MemRecorder* cur_head = const_cast<MemRecorder*>(_merge_pending_queue);
 366   rec->set_next(cur_head);
 367   while ((void*)cur_head != Atomic::cmpxchg_ptr((void*)rec, (void*)&_merge_pending_queue,
 368     (void*)cur_head)) {
 369     cur_head = const_cast<MemRecorder*>(_merge_pending_queue);
 370     rec->set_next(cur_head);
 371   }
 372   NOT_PRODUCT(Atomic::inc(&_pending_recorder_count);)
 373 }
 374 
 375 /*
 376  * The method is called at global safepoint
 377  * during it synchronization process.
 378  *   1. enqueue all JavaThreads' per-thread recorders
 379  *   2. enqueue global recorder
 380  *   3. retrieve all pending recorders
 381  *   4. reset global sequence number generator
 382  *   5. call worker's sync
 383  */
 384 #define MAX_SAFEPOINTS_TO_SKIP     128
 385 #define SAFE_SEQUENCE_THRESHOLD    30
 386 #define HIGH_GENERATION_THRESHOLD  60
 387 #define MAX_RECORDER_THREAD_RATIO  30
 388 #define MAX_RECORDER_PER_THREAD    100
 389 
 390 void MemTracker::sync() {
 391   assert(_tracking_level > NMT_off, "NMT is not enabled");
 392   assert(SafepointSynchronize::is_at_safepoint(), "Safepoint required");
 393 
 394   // Some GC tests hit large number of safepoints in short period of time
 395   // without meaningful activities. We should prevent going to
 396   // sync point in these cases, which can potentially exhaust generation buffer.
 397   // Here is the factots to determine if we should go into sync point:
 398   // 1. not to overflow sequence number
 399   // 2. if we are in danger to overflow generation buffer
 400   // 3. how many safepoints we already skipped sync point
 401   if (_state == NMT_started) {
 402     // worker thread is not ready, no one can manage generation
 403     // buffer, so skip this safepoint
 404     if (_worker_thread == NULL) return;
 405 
 406     if (_sync_point_skip_count < MAX_SAFEPOINTS_TO_SKIP) {
 407       int per_seq_in_use = SequenceGenerator::peek() * 100 / max_jint;
 408       int per_gen_in_use = _worker_thread->generations_in_use() * 100 / MAX_GENERATIONS;
 409       if (per_seq_in_use < SAFE_SEQUENCE_THRESHOLD && per_gen_in_use >= HIGH_GENERATION_THRESHOLD) {
 410         _sync_point_skip_count ++;
 411         return;
 412       }
 413     }
 414     {
 415       // This method is running at safepoint, with ThreadCritical lock,
 416       // it should guarantee that NMT is fully sync-ed.
 417       ThreadCritical tc;
 418 
 419       // We can NOT execute NMT sync-point if there are pending tracking ops.
 420       if (_pending_op_count == 0) {
 421         SequenceGenerator::reset();
 422         _sync_point_skip_count = 0;
 423 
 424         // walk all JavaThreads to collect recorders
 425         SyncThreadRecorderClosure stc;
 426         Threads::threads_do(&stc);
 427 
 428         _thread_count = stc.get_thread_count();
 429         MemRecorder* pending_recorders = get_pending_recorders();
 430 
 431         if (_global_recorder != NULL) {
 432           _global_recorder->set_next(pending_recorders);
 433           pending_recorders = _global_recorder;
 434           _global_recorder = NULL;
 435         }
 436 
 437         // see if NMT has too many outstanding recorder instances, it usually
 438         // means that worker thread is lagging behind in processing them.
 439         if (!AutoShutdownNMT) {
 440           _slowdown_calling_thread = (MemRecorder::_instance_count > MAX_RECORDER_THREAD_RATIO * _thread_count);
 441         } else {
 442           // If auto shutdown is on, enforce MAX_RECORDER_PER_THREAD threshold to prevent OOM
 443           if (MemRecorder::_instance_count >= _thread_count * MAX_RECORDER_PER_THREAD) {
 444             shutdown(NMT_out_of_memory);
 445           }
 446         }
 447 
 448         // check _worker_thread with lock to avoid racing condition
 449         if (_worker_thread != NULL) {
 450           _worker_thread->at_sync_point(pending_recorders, InstanceKlass::number_of_instance_classes());
 451         }
 452         assert(SequenceGenerator::peek() == 1, "Should not have memory activities during sync-point");
 453       } else {
 454         _sync_point_skip_count ++;
 455       }
 456     }
 457   }
 458 
 459   // now, it is the time to shut whole things off
 460   if (_state == NMT_final_shutdown) {
 461     // walk all JavaThreads to delete all recorders
 462     SyncThreadRecorderClosure stc;
 463     Threads::threads_do(&stc);
 464     // delete global recorder
 465     {
 466       ThreadCritical tc;
 467       if (_global_recorder != NULL) {
 468         delete _global_recorder;
 469         _global_recorder = NULL;
 470       }
 471     }
 472     MemRecorder* pending_recorders = get_pending_recorders();
 473     if (pending_recorders != NULL) {
 474       delete pending_recorders;
 475     }
 476     // try at a later sync point to ensure MemRecorder instance drops to zero to
 477     // completely shutdown NMT
 478     if (MemRecorder::_instance_count == 0) {
 479       _state = NMT_shutdown;
 480       _tracking_level = NMT_off;
 481     }
 482   }
 483 }
 484 
 485 /*
 486  * Start worker thread.
 487  */
 488 bool MemTracker::start_worker(MemSnapshot* snapshot) {
 489   assert(_worker_thread == NULL && _snapshot != NULL, "Just Check");
 490   _worker_thread = new (std::nothrow) MemTrackWorker(snapshot);
 491   if (_worker_thread == NULL) {
 492     return false;
 493   } else if (_worker_thread->has_error()) {
 494     delete _worker_thread;
 495     _worker_thread = NULL;
 496     return false;
 497   }
 498   _worker_thread->start();
 499   return true;
 500 }
 501 
 502 /*
 503  * We need to collect a JavaThread's per-thread recorder
 504  * before it exits.
 505  */
 506 void MemTracker::thread_exiting(JavaThread* thread) {
 507   if (is_on()) {
 508     MemRecorder* rec = thread->get_recorder();
 509     if (rec != NULL) {
 510       enqueue_pending_recorder(rec);
 511       thread->set_recorder(NULL);
 512     }
 513   }
 514 }
 515 
 516 // baseline current memory snapshot
 517 bool MemTracker::baseline() {
 518   MutexLocker lock(_query_lock);
 519   MemSnapshot* snapshot = get_snapshot();
 520   if (snapshot != NULL) {
 521     return _baseline.baseline(*snapshot, false);
 522   }
 523   return false;
 524 }
 525 
 526 // print memory usage from current snapshot
 527 bool MemTracker::print_memory_usage(BaselineOutputer& out, size_t unit, bool summary_only) {
 528   MemBaseline  baseline;
 529   MutexLocker  lock(_query_lock);
 530   MemSnapshot* snapshot = get_snapshot();
 531   if (snapshot != NULL && baseline.baseline(*snapshot, summary_only)) {
 532     BaselineReporter reporter(out, unit);
 533     reporter.report_baseline(baseline, summary_only);
 534     return true;
 535   }
 536   return false;
 537 }
 538 
 539 // Whitebox API for blocking until the current generation of NMT data has been merged
 540 bool MemTracker::wbtest_wait_for_data_merge() {
 541   // NMT can't be shutdown while we're holding _query_lock
 542   MutexLocker lock(_query_lock);
 543   assert(_worker_thread != NULL, "Invalid query");
 544   // the generation at query time, so NMT will spin till this generation is processed
 545   unsigned long generation_at_query_time = SequenceGenerator::current_generation();
 546   unsigned long current_processing_generation = _processing_generation;
 547   // if generation counter overflown
 548   bool generation_overflown = (generation_at_query_time < current_processing_generation);
 549   long generations_to_wrap = MAX_UNSIGNED_LONG - current_processing_generation;
 550   // spin
 551   while (!shutdown_in_progress()) {
 552     if (!generation_overflown) {
 553       if (current_processing_generation > generation_at_query_time) {
 554         return true;
 555       }
 556     } else {
 557       assert(generations_to_wrap >= 0, "Sanity check");
 558       long current_generations_to_wrap = MAX_UNSIGNED_LONG - current_processing_generation;
 559       assert(current_generations_to_wrap >= 0, "Sanity check");
 560       // to overflow an unsigned long should take long time, so to_wrap check should be sufficient
 561       if (current_generations_to_wrap > generations_to_wrap &&
 562           current_processing_generation > generation_at_query_time) {
 563         return true;
 564       }
 565     }
 566 
 567     // if worker thread is idle, but generation is not advancing, that means
 568     // there is not safepoint to let NMT advance generation, force one.
 569     if (_worker_thread_idle) {
 570       VM_ForceSafepoint vfs;
 571       VMThread::execute(&vfs);
 572     }
 573     MemSnapshot* snapshot = get_snapshot();
 574     if (snapshot == NULL) {
 575       return false;
 576     }
 577     snapshot->wait(1000);
 578     current_processing_generation = _processing_generation;
 579   }
 580   // We end up here if NMT is shutting down before our data has been merged
 581   return false;
 582 }
 583 
 584 // compare memory usage between current snapshot and baseline
 585 bool MemTracker::compare_memory_usage(BaselineOutputer& out, size_t unit, bool summary_only) {
 586   MutexLocker lock(_query_lock);
 587   if (_baseline.baselined()) {
 588     MemBaseline baseline;
 589     MemSnapshot* snapshot = get_snapshot();
 590     if (snapshot != NULL && baseline.baseline(*snapshot, summary_only)) {
 591       BaselineReporter reporter(out, unit);
 592       reporter.diff_baselines(baseline, _baseline, summary_only);
 593       return true;
 594     }
 595   }
 596   return false;
 597 }
 598 
 599 #ifndef PRODUCT
 600 void MemTracker::walk_stack(int toSkip, char* buf, int len) {
 601   int cur_len = 0;
 602   char tmp[1024];
 603   address pc;
 604 
 605   while (cur_len < len) {
 606     pc = os::get_caller_pc(toSkip + 1);
 607     if (pc != NULL && os::dll_address_to_function_name(pc, tmp, sizeof(tmp), NULL)) {
 608       jio_snprintf(&buf[cur_len], (len - cur_len), "%s\n", tmp);
 609       cur_len = (int)strlen(buf);
 610     } else {
 611       buf[cur_len] = '\0';
 612       break;
 613     }
 614     toSkip ++;
 615   }
 616 }
 617 
 618 void MemTracker::print_tracker_stats(outputStream* st) {
 619   st->print_cr("\nMemory Tracker Stats:");
 620   st->print_cr("\tMax sequence number = %d", SequenceGenerator::max_seq_num());
 621   st->print_cr("\tthead count = %d", _thread_count);
 622   st->print_cr("\tArena instance = %d", Arena::_instance_count);
 623   st->print_cr("\tpooled recorder count = %d", _pooled_recorder_count);
 624   st->print_cr("\tqueued recorder count = %d", _pending_recorder_count);
 625   st->print_cr("\tmemory recorder instance count = %d", MemRecorder::_instance_count);
 626   if (_worker_thread != NULL) {
 627     st->print_cr("\tWorker thread:");
 628     st->print_cr("\t\tSync point count = %d", _worker_thread->_sync_point_count);
 629     st->print_cr("\t\tpending recorder count = %d", _worker_thread->count_pending_recorders());
 630     st->print_cr("\t\tmerge count = %d", _worker_thread->_merge_count);
 631   } else {
 632     st->print_cr("\tWorker thread is not started");
 633   }
 634   st->print_cr(" ");
 635 
 636   if (_snapshot != NULL) {
 637     _snapshot->print_snapshot_stats(st);
 638   } else {
 639     st->print_cr("No snapshot");
 640   }
 641 }
 642 #endif
 643 
 644 
 645 // Tracker Implementation
 646 
 647 /*
 648  * Create a tracker.
 649  * This is a fairly complicated constructor, as it has to make two important decisions:
 650  *   1) Does it need to take ThreadCritical lock to write tracking record
 651  *   2) Does it need to pre-reserve a sequence number for the tracking record
 652  *
 653  * The rules to determine if ThreadCritical is needed:
 654  *   1. When nmt is in single-threaded bootstrapping mode, no lock is needed as VM
 655  *      still in single thread mode.
 656  *   2. For all threads other than JavaThread, ThreadCritical is needed
 657  *      to write to recorders to global recorder.
 658  *   3. For JavaThreads that are no longer visible by safepoint, also
 659  *      need to take ThreadCritical and records are written to global
 660  *      recorders, since these threads are NOT walked by Threads.do_thread().
 661  *   4. JavaThreads that are running in safepoint-safe states do not stop
 662  *      for safepoints, ThreadCritical lock should be taken to write
 663  *      memory records.
 664  *   5. JavaThreads that are running in VM state do not need any lock and
 665  *      records are written to per-thread recorders.
 666  *   6. For a thread has yet to attach VM 'Thread', they need to take
 667  *      ThreadCritical to write to global recorder.
 668  *
 669  *  The memory operations that need pre-reserve sequence numbers:
 670  *    The memory operations that "release" memory blocks and the
 671  *    operations can fail, need to pre-reserve sequence number. They
 672  *    are realloc, uncommit and release.
 673  *
 674  *  The reason for pre-reserve sequence number, is to prevent race condition:
 675  *    Thread 1                      Thread 2
 676  *    <release>
 677  *                                  <allocate>
 678  *                                  <write allocate record>
 679  *   <write release record>
 680  *   if Thread 2 happens to obtain the memory address Thread 1 just released,
 681  *   then NMT can mistakenly report the memory is free.
 682  *
 683  *  Noticeably, free() does not need pre-reserve sequence number, because the call
 684  *  does not fail, so we can alway write "release" record before the memory is actaully
 685  *  freed.
 686  *
 687  *  For realloc, uncommit and release, following coding pattern should be used:
 688  *
 689  *     MemTracker::Tracker tkr = MemTracker::get_realloc_tracker();
 690  *     ptr = ::realloc(...);
 691  *     if (ptr == NULL) {
 692  *       tkr.record(...)
 693  *     } else {
 694  *       tkr.discard();
 695  *     }
 696  *
 697  *     MemTracker::Tracker tkr = MemTracker::get_virtual_memory_uncommit_tracker();
 698  *     if (uncommit(...)) {
 699  *       tkr.record(...);
 700  *     } else {
 701  *       tkr.discard();
 702  *     }
 703  *
 704  *     MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
 705  *     if (release(...)) {
 706  *       tkr.record(...);
 707  *     } else {
 708  *       tkr.discard();
 709  *     }
 710  *
 711  * Since pre-reserved sequence number is only good for the generation that it is acquired,
 712  * when there is pending Tracker that reserved sequence number, NMT sync-point has
 713  * to be skipped to prevent from advancing generation. This is done by inc and dec
 714  * MemTracker::_pending_op_count, when MemTracker::_pending_op_count > 0, NMT sync-point is skipped.
 715  * Not all pre-reservation of sequence number will increment pending op count. For JavaThreads
 716  * that honor safepoints, safepoint can not occur during the memory operations, so the
 717  * pre-reserved sequence number won't cross the generation boundry.
 718  */
 719 MemTracker::Tracker::Tracker(MemoryOperation op, Thread* thr) {
 720   _op = NoOp;
 721   _seq = 0;
 722   if (MemTracker::is_on()) {
 723     _java_thread = NULL;
 724     _op = op;
 725 
 726     // figure out if ThreadCritical lock is needed to write this operation
 727     // to MemTracker
 728     if (MemTracker::is_single_threaded_bootstrap()) {
 729       thr = NULL;
 730     } else if (thr == NULL) {
 731       // don't use Thread::current(), since it is possible that
 732       // the calling thread has yet to attach to VM 'Thread',
 733       // which will result assertion failure
 734       thr = ThreadLocalStorage::thread();
 735     }
 736 
 737     if (thr != NULL) {
 738       // Check NMT load
 739       MemTracker::check_NMT_load(thr);
 740 
 741       if (thr->is_Java_thread() && ((JavaThread*)thr)->is_safepoint_visible()) {
 742         _java_thread = (JavaThread*)thr;
 743         JavaThreadState  state = _java_thread->thread_state();
 744         // JavaThreads that are safepoint safe, can run through safepoint,
 745         // so ThreadCritical is needed to ensure no threads at safepoint create
 746         // new records while the records are being gathered and the sequence number is changing
 747         _need_thread_critical_lock =
 748           SafepointSynchronize::safepoint_safe(_java_thread, state);
 749       } else {
 750         _need_thread_critical_lock = true;
 751       }
 752     } else {
 753        _need_thread_critical_lock
 754          = !MemTracker::is_single_threaded_bootstrap();
 755     }
 756 
 757     // see if we need to pre-reserve sequence number for this operation
 758     if (_op == Realloc || _op == Uncommit || _op == Release) {
 759       if (_need_thread_critical_lock) {
 760         ThreadCritical tc;
 761         MemTracker::inc_pending_op_count();
 762         _seq = SequenceGenerator::next();
 763       } else {
 764         // for the threads that honor safepoints, no safepoint can occur
 765         // during the lifespan of tracker, so we don't need to increase
 766         // pending op count.
 767         _seq = SequenceGenerator::next();
 768       }
 769     }
 770   }
 771 }
 772 
 773 void MemTracker::Tracker::discard() {
 774   if (MemTracker::is_on() && _seq != 0) {
 775     if (_need_thread_critical_lock) {
 776       ThreadCritical tc;
 777       MemTracker::dec_pending_op_count();
 778     }
 779     _seq = 0;
 780   }
 781 }
 782 
 783 
 784 void MemTracker::Tracker::record(address old_addr, address new_addr, size_t size,
 785   MEMFLAGS flags, address pc) {
 786   assert(old_addr != NULL && new_addr != NULL, "Sanity check");
 787   assert(_op == Realloc || _op == NoOp, "Wrong call");
 788   if (MemTracker::is_on() && NMT_CAN_TRACK(flags) && _op != NoOp && !MemTracker::shutdown_in_progress()) {
 789     assert(_seq > 0, "Need pre-reserve sequence number");
 790     if (_need_thread_critical_lock) {
 791       ThreadCritical tc;
 792       // free old address, use pre-reserved sequence number
 793       MemTracker::write_tracking_record(old_addr, MemPointerRecord::free_tag(),
 794         0, _seq, pc, _java_thread);
 795       MemTracker::write_tracking_record(new_addr, flags | MemPointerRecord::malloc_tag(),
 796         size, SequenceGenerator::next(), pc, _java_thread);
 797       // decrement MemTracker pending_op_count
 798       MemTracker::dec_pending_op_count();
 799     } else {
 800       // free old address, use pre-reserved sequence number
 801       MemTracker::write_tracking_record(old_addr, MemPointerRecord::free_tag(),
 802         0, _seq, pc, _java_thread);
 803       MemTracker::write_tracking_record(new_addr, flags | MemPointerRecord::malloc_tag(),
 804         size, SequenceGenerator::next(), pc, _java_thread);
 805     }
 806     _seq = 0;
 807   }
 808 }
 809 
 810 void MemTracker::Tracker::record(address addr, size_t size, MEMFLAGS flags, address pc) {
 811   // OOM already?
 812   if (addr == NULL) return;
 813 
 814   if (MemTracker::is_on() && NMT_CAN_TRACK(flags) && _op != NoOp && !MemTracker::shutdown_in_progress()) {
 815     bool pre_reserved_seq = (_seq != 0);
 816     address  pc = CALLER_CALLER_PC;
 817     MEMFLAGS orig_flags = flags;
 818 
 819     // or the tagging flags
 820     switch(_op) {
 821       case Malloc:
 822         flags |= MemPointerRecord::malloc_tag();
 823         break;
 824       case Free:
 825         flags = MemPointerRecord::free_tag();
 826         break;
 827       case Realloc:
 828         fatal("Use the other Tracker::record()");
 829         break;
 830       case Reserve:
 831       case ReserveAndCommit:
 832         flags |= MemPointerRecord::virtual_memory_reserve_tag();
 833         break;
 834       case Commit:
 835         flags = MemPointerRecord::virtual_memory_commit_tag();
 836         break;
 837       case Type:
 838         flags |= MemPointerRecord::virtual_memory_type_tag();
 839         break;
 840       case Uncommit:
 841         assert(pre_reserved_seq, "Need pre-reserve sequence number");
 842         flags = MemPointerRecord::virtual_memory_uncommit_tag();
 843         break;
 844       case Release:
 845         assert(pre_reserved_seq, "Need pre-reserve sequence number");
 846         flags = MemPointerRecord::virtual_memory_release_tag();
 847         break;
 848       case ArenaSize:
 849         // a bit of hack here, add a small postive offset to arena
 850         // address for its size record, so the size record is sorted
 851         // right after arena record.
 852         flags = MemPointerRecord::arena_size_tag();
 853         addr += sizeof(void*);
 854         break;
 855       case StackRelease:
 856         flags = MemPointerRecord::virtual_memory_release_tag();
 857         break;
 858       default:
 859         ShouldNotReachHere();
 860     }
 861 
 862     // write memory tracking record
 863     if (_need_thread_critical_lock) {
 864       ThreadCritical tc;
 865       if (_seq == 0) _seq = SequenceGenerator::next();
 866       MemTracker::write_tracking_record(addr, flags, size, _seq, pc, _java_thread);
 867       if (_op == ReserveAndCommit) {
 868         MemTracker::write_tracking_record(addr, orig_flags | MemPointerRecord::virtual_memory_commit_tag(),
 869           size, SequenceGenerator::next(), pc, _java_thread);
 870       }
 871       if (pre_reserved_seq) MemTracker::dec_pending_op_count();
 872     } else {
 873       if (_seq == 0) _seq = SequenceGenerator::next();
 874       MemTracker::write_tracking_record(addr, flags, size, _seq, pc, _java_thread);
 875       if (_op == ReserveAndCommit) {
 876         MemTracker::write_tracking_record(addr, orig_flags | MemPointerRecord::virtual_memory_commit_tag(),
 877           size, SequenceGenerator::next(), pc, _java_thread);
 878       }
 879     }
 880     _seq = 0;
 881   }
 882 }
 883