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 
  25 #ifndef SHARE_VM_SERVICES_MEM_TRACKER_HPP
  26 #define SHARE_VM_SERVICES_MEM_TRACKER_HPP
  27 
  28 #include "utilities/macros.hpp"
  29 
  30 #if !INCLUDE_NMT
  31 
  32 #include "utilities/ostream.hpp"
  33 
  34 class BaselineOutputer : public StackObj {
  35 
  36 };
  37 
  38 class BaselineTTYOutputer : public BaselineOutputer {
  39   public:
  40     BaselineTTYOutputer(outputStream* st) { }
  41 };
  42 
  43 class MemTracker : AllStatic {
  44   public:
  45    enum ShutdownReason {
  46       NMT_shutdown_none,     // no shutdown requested
  47       NMT_shutdown_user,     // user requested shutdown
  48       NMT_normal,            // normal shutdown, process exit
  49       NMT_out_of_memory,     // shutdown due to out of memory
  50       NMT_initialization,    // shutdown due to initialization failure
  51       NMT_use_malloc_only,   // can not combine NMT with UseMallocOnly flag
  52       NMT_error_reporting,   // shutdown by vmError::report_and_die()
  53       NMT_out_of_generation, // running out of generation queue
  54       NMT_sequence_overflow  // overflow the sequence number
  55    };
  56 
  57   class Tracker {
  58    public:
  59     void discard() { }
  60 
  61     void record(address addr, size_t size = 0, MEMFLAGS flags = mtNone, address pc = NULL) { }
  62     void record(address old_addr, address new_addr, size_t size,
  63       MEMFLAGS flags, address pc = NULL) { }
  64   };
  65 
  66 
  67 
  68   public:
  69    static inline void init_tracking_options(const char* option_line) { }
  70    static inline bool is_on()   { return false; }
  71    static const char* reason()  { return "Native memory tracking is not implemented"; }
  72    static inline bool can_walk_stack() { return false; }
  73 
  74    static inline void bootstrap_single_thread() { }
  75    static inline void bootstrap_multi_thread() { }
  76    static inline void start() { }
  77 
  78    static inline void record_malloc(address addr, size_t size, MEMFLAGS flags,
  79         address pc = 0, Thread* thread = NULL) { }
  80    static inline void record_free(address addr, MEMFLAGS flags, Thread* thread = NULL) { }
  81    static inline void record_arena_size(address addr, size_t size) { }
  82    static inline void record_virtual_memory_reserve(address addr, size_t size,
  83         MEMFLAGS flags, address pc = 0, Thread* thread = NULL) { }
  84    static inline void record_virtual_memory_reserve_and_commit(address addr, size_t size,
  85         MEMFLAGS flags, address pc = 0, Thread* thread = NULL) { }
  86    static inline void record_virtual_memory_commit(address addr, size_t size,
  87         address pc = 0, Thread* thread = NULL) { }
  88    static inline void record_virtual_memory_type(address base, MEMFLAGS flags,
  89         Thread* thread = NULL) { }
  90    static inline Tracker get_realloc_tracker() { return Tracker(); }
  91    static inline Tracker get_virtual_memory_uncommit_tracker() { return Tracker(); }
  92    static inline Tracker get_virtual_memory_release_tracker()  { return Tracker(); }
  93    static inline bool baseline() { return false; }
  94    static inline bool has_baseline() { return false; }
  95 
  96    static inline void set_autoShutdown(bool value) { }
  97    static void shutdown(ShutdownReason reason) { }
  98    static inline bool shutdown_in_progress() { return false; }
  99    static bool print_memory_usage(BaselineOutputer& out, size_t unit,
 100             bool summary_only = true) { return false; }
 101    static bool compare_memory_usage(BaselineOutputer& out, size_t unit,
 102             bool summary_only = true) { return false; }
 103 
 104    static bool wbtest_wait_for_data_merge() { return false; }
 105 
 106    static inline void sync() { }
 107    static inline void thread_exiting(JavaThread* thread) { }
 108 };
 109 
 110 
 111 #else // !INCLUDE_NMT
 112 
 113 #include "memory/allocation.hpp"
 114 #include "runtime/globals.hpp"
 115 #include "runtime/mutex.hpp"
 116 #include "runtime/os.hpp"
 117 #include "runtime/thread.hpp"
 118 #include "services/memPtr.hpp"
 119 #include "services/memRecorder.hpp"
 120 #include "services/memSnapshot.hpp"
 121 #include "services/memTrackWorker.hpp"
 122 
 123 extern bool NMT_track_callsite;
 124 
 125 #ifndef MAX_UNSIGNED_LONG
 126 #define MAX_UNSIGNED_LONG    (unsigned long)(-1)
 127 #endif
 128 
 129 #ifdef ASSERT
 130   #define DEBUG_CALLER_PC  (NMT_track_callsite ? os::get_caller_pc(2) : 0)
 131 #else
 132   #define DEBUG_CALLER_PC  0
 133 #endif
 134 
 135 // The thread closure walks threads to collect per-thread
 136 // memory recorders at NMT sync point
 137 class SyncThreadRecorderClosure : public ThreadClosure {
 138  private:
 139   int _thread_count;
 140 
 141  public:
 142   SyncThreadRecorderClosure() {
 143     _thread_count =0;
 144   }
 145 
 146   void do_thread(Thread* thread);
 147   int  get_thread_count() const {
 148     return _thread_count;
 149   }
 150 };
 151 
 152 class BaselineOutputer;
 153 class MemSnapshot;
 154 class MemTrackWorker;
 155 class Thread;
 156 /*
 157  * MemTracker is the 'gate' class to native memory tracking runtime.
 158  */
 159 class MemTracker : AllStatic {
 160   friend class GenerationData;
 161   friend class MemTrackWorker;
 162   friend class MemSnapshot;
 163   friend class SyncThreadRecorderClosure;
 164 
 165   // NMT state
 166   enum NMTStates {
 167     NMT_uninited,                        // not yet initialized
 168     NMT_bootstrapping_single_thread,     // bootstrapping, VM is in single thread mode
 169     NMT_bootstrapping_multi_thread,      // bootstrapping, VM is about to enter multi-thread mode
 170     NMT_started,                         // NMT fully started
 171     NMT_shutdown_pending,                // shutdown pending
 172     NMT_final_shutdown,                  // in final phase of shutdown
 173     NMT_shutdown                         // shutdown
 174   };
 175 
 176  public:
 177   class Tracker : public StackObj {
 178     friend class MemTracker;
 179    public:
 180     enum MemoryOperation {
 181       NoOp,                   // no op
 182       Malloc,                 // malloc
 183       Realloc,                // realloc
 184       Free,                   // free
 185       Reserve,                // virtual memory reserve
 186       Commit,                 // virtual memory commit
 187       ReserveAndCommit,       // virtual memory reserve and commit
 188       StackAlloc = ReserveAndCommit, // allocate thread stack
 189       Type,                   // assign virtual memory type
 190       Uncommit,               // virtual memory uncommit
 191       Release,                // virtual memory release
 192       ArenaSize,              // set arena size
 193       StackRelease            // release thread stack
 194     };
 195 
 196 
 197    protected:
 198     Tracker(MemoryOperation op, Thread* thr = NULL);
 199 
 200    public:
 201     void discard();
 202 
 203     void record(address addr, size_t size = 0, MEMFLAGS flags = mtNone, address pc = NULL);
 204     void record(address old_addr, address new_addr, size_t size,
 205       MEMFLAGS flags, address pc = NULL);
 206 
 207    private:
 208     bool            _need_thread_critical_lock;
 209     JavaThread*     _java_thread;
 210     MemoryOperation _op;          // memory operation
 211     jint            _seq;         // reserved sequence number
 212   };
 213 
 214 
 215  public:
 216   // native memory tracking level
 217   enum NMTLevel {
 218     NMT_off,              // native memory tracking is off
 219     NMT_summary,          // don't track callsite
 220     NMT_detail            // track callsite also
 221   };
 222 
 223    enum ShutdownReason {
 224      NMT_shutdown_none,     // no shutdown requested
 225      NMT_shutdown_user,     // user requested shutdown
 226      NMT_normal,            // normal shutdown, process exit
 227      NMT_out_of_memory,     // shutdown due to out of memory
 228      NMT_initialization,    // shutdown due to initialization failure
 229      NMT_use_malloc_only,   // can not combine NMT with UseMallocOnly flag
 230      NMT_error_reporting,   // shutdown by vmError::report_and_die()
 231      NMT_out_of_generation, // running out of generation queue
 232      NMT_sequence_overflow  // overflow the sequence number
 233    };
 234 
 235  public:
 236   // initialize NMT tracking level from command line options, called
 237    // from VM command line parsing code
 238   static void init_tracking_options(const char* option_line);
 239 
 240   // if NMT is enabled to record memory activities
 241   static inline bool is_on() {
 242     return (_tracking_level >= NMT_summary &&
 243       _state >= NMT_bootstrapping_single_thread);
 244   }
 245 
 246   static inline enum NMTLevel tracking_level() {
 247     return _tracking_level;
 248   }
 249 
 250   // user readable reason for shutting down NMT
 251   static const char* reason() {
 252     switch(_reason) {
 253       case NMT_shutdown_none:
 254         return "Native memory tracking is not enabled";
 255       case NMT_shutdown_user:
 256         return "Native memory tracking has been shutdown by user";
 257       case NMT_normal:
 258         return "Native memory tracking has been shutdown due to process exiting";
 259       case NMT_out_of_memory:
 260         return "Native memory tracking has been shutdown due to out of native memory";
 261       case NMT_initialization:
 262         return "Native memory tracking failed to initialize";
 263       case NMT_error_reporting:
 264         return "Native memory tracking has been shutdown due to error reporting";
 265       case NMT_out_of_generation:
 266         return "Native memory tracking has been shutdown due to running out of generation buffer";
 267       case NMT_sequence_overflow:
 268         return "Native memory tracking has been shutdown due to overflow the sequence number";
 269       case NMT_use_malloc_only:
 270         return "Native memory tracking is not supported when UseMallocOnly is on";
 271       default:
 272         ShouldNotReachHere();
 273         return NULL;
 274     }
 275   }
 276 
 277   // test if we can walk native stack
 278   static bool can_walk_stack() {
 279   // native stack is not walkable during bootstrapping on sparc
 280 #if defined(SPARC)
 281     return (_state == NMT_started);
 282 #else
 283     return (_state >= NMT_bootstrapping_single_thread && _state  <= NMT_started);
 284 #endif
 285   }
 286 
 287   // if native memory tracking tracks callsite
 288   static inline bool track_callsite() { return _tracking_level == NMT_detail; }
 289 
 290   // NMT automatically shuts itself down under extreme situation by default.
 291   // When the value is set to false,  NMT will try its best to stay alive,
 292   // even it has to slow down VM.
 293   static inline void set_autoShutdown(bool value) {
 294     AutoShutdownNMT = value;
 295     if (AutoShutdownNMT && _slowdown_calling_thread) {
 296       _slowdown_calling_thread = false;
 297     }
 298   }
 299 
 300   // shutdown native memory tracking capability. Native memory tracking
 301   // can be shutdown by VM when it encounters low memory scenarios.
 302   // Memory tracker should gracefully shutdown itself, and preserve the
 303   // latest memory statistics for post morten diagnosis.
 304   static void shutdown(ShutdownReason reason);
 305 
 306   // if there is shutdown requested
 307   static inline bool shutdown_in_progress() {
 308     return (_state >= NMT_shutdown_pending);
 309   }
 310 
 311   // bootstrap native memory tracking, so it can start to collect raw data
 312   // before worker thread can start
 313 
 314   // the first phase of bootstrapping, when VM still in single-threaded mode
 315   static void bootstrap_single_thread();
 316   // the second phase of bootstrapping, VM is about or already in multi-threaded mode
 317   static void bootstrap_multi_thread();
 318 
 319 
 320   // start() has to be called when VM still in single thread mode, but after
 321   // command line option parsing is done.
 322   static void start();
 323 
 324   // record a 'malloc' call
 325   static inline void record_malloc(address addr, size_t size, MEMFLAGS flags,
 326                             address pc = 0, Thread* thread = NULL) {
 327     Tracker tkr(Tracker::Malloc, thread);
 328     tkr.record(addr, size, flags, pc);
 329   }
 330   // record a 'free' call
 331   static inline void record_free(address addr, MEMFLAGS flags, Thread* thread = NULL) {
 332     Tracker tkr(Tracker::Free, thread);
 333     tkr.record(addr, 0, flags, DEBUG_CALLER_PC);
 334   }
 335 
 336   static inline void record_arena_size(address addr, size_t size) {
 337     Tracker tkr(Tracker::ArenaSize);
 338     tkr.record(addr, size);
 339   }
 340 
 341   // record a virtual memory 'reserve' call
 342   static inline void record_virtual_memory_reserve(address addr, size_t size,
 343                      MEMFLAGS flags, address pc = 0, Thread* thread = NULL) {
 344     assert(size > 0, "Sanity check");
 345     Tracker tkr(Tracker::Reserve, thread);
 346     tkr.record(addr, size, flags, pc); 
 347   }
 348 
 349   static inline void record_thread_stack(address addr, size_t size, Thread* thr,
 350                            address pc = 0) {
 351     Tracker tkr(Tracker::StackAlloc, thr);
 352     tkr.record(addr, size, mtThreadStack, pc);
 353   }
 354 
 355   static inline void release_thread_stack(address addr, size_t size, Thread* thr) {
 356     Tracker tkr(Tracker::StackRelease, thr);
 357     tkr.record(addr, size, mtThreadStack, DEBUG_CALLER_PC);
 358   }
 359 
 360   // record a virtual memory 'commit' call
 361   static inline void record_virtual_memory_commit(address addr, size_t size,
 362                             address pc, Thread* thread = NULL) {
 363     Tracker tkr(Tracker::Commit, thread);
 364     tkr.record(addr, size, mtNone, pc);
 365   }
 366 
 367   static inline void record_virtual_memory_reserve_and_commit(address addr, size_t size,
 368     MEMFLAGS flags, address pc, Thread* thread = NULL) {
 369     Tracker tkr(Tracker::ReserveAndCommit, thread);
 370     tkr.record(addr, size, flags, pc); 
 371   }
 372 
 373 
 374   // record memory type on virtual memory base address
 375   static inline void record_virtual_memory_type(address base, MEMFLAGS flags,
 376                             Thread* thread = NULL) {
 377     Tracker tkr(Tracker::Type);
 378     tkr.record(base, 0, flags);
 379   }
 380 
 381   // Get memory trackers for memory operations that can result race conditions.
 382   // The memory tracker has to be obtained before realloc, virtual memory uncommit
 383   // and virtual memory release, and call tracker.record() method if operation
 384   // succeeded, or tracker.discard() to abort the tracking.
 385   static inline Tracker get_realloc_tracker() {
 386     return Tracker(Tracker::Realloc);
 387   }
 388 
 389   static inline Tracker get_virtual_memory_uncommit_tracker() {
 390     return Tracker(Tracker::Uncommit);
 391   }
 392 
 393   static inline Tracker get_virtual_memory_release_tracker() {
 394     return Tracker(Tracker::Release);
 395   }
 396 
 397 
 398   // create memory baseline of current memory snapshot
 399   static bool baseline();
 400   // is there a memory baseline
 401   static bool has_baseline() {
 402     return _baseline.baselined();
 403   }
 404 
 405   // print memory usage from current snapshot
 406   static bool print_memory_usage(BaselineOutputer& out, size_t unit,
 407            bool summary_only = true);
 408   // compare memory usage between current snapshot and baseline
 409   static bool compare_memory_usage(BaselineOutputer& out, size_t unit,
 410            bool summary_only = true);
 411 
 412   // the version for whitebox testing support, it ensures that all memory
 413   // activities before this method call, are reflected in the snapshot
 414   // database.
 415   static bool wbtest_wait_for_data_merge();
 416 
 417   // sync is called within global safepoint to synchronize nmt data
 418   static void sync();
 419 
 420   // called when a thread is about to exit
 421   static void thread_exiting(JavaThread* thread);
 422 
 423   // retrieve global snapshot
 424   static MemSnapshot* get_snapshot() {
 425     if (shutdown_in_progress()) {
 426       return NULL;
 427     }
 428     return _snapshot;
 429   }
 430 
 431   // print tracker stats
 432   NOT_PRODUCT(static void print_tracker_stats(outputStream* st);)
 433   NOT_PRODUCT(static void walk_stack(int toSkip, char* buf, int len);)
 434 
 435  private:
 436   // start native memory tracking worker thread
 437   static bool start_worker(MemSnapshot* snapshot);
 438 
 439   // called by worker thread to complete shutdown process
 440   static void final_shutdown();
 441 
 442  protected:
 443   // retrieve per-thread recorder of the specified thread.
 444   // if the recorder is full, it will be enqueued to overflow
 445   // queue, a new recorder is acquired from recorder pool or a
 446   // new instance is created.
 447   // when thread == NULL, it means global recorder
 448   static MemRecorder* get_thread_recorder(JavaThread* thread);
 449 
 450   // per-thread recorder pool
 451   static void release_thread_recorder(MemRecorder* rec);
 452   static void delete_all_pooled_recorders();
 453 
 454   // pending recorder queue. Recorders are queued to pending queue
 455   // when they are overflowed or collected at nmt sync point.
 456   static void enqueue_pending_recorder(MemRecorder* rec);
 457   static MemRecorder* get_pending_recorders();
 458   static void delete_all_pending_recorders();
 459 
 460   // write a memory tracking record in recorder
 461   static void write_tracking_record(address addr, MEMFLAGS type,
 462     size_t size, jint seq, address pc, JavaThread* thread);
 463 
 464   static bool is_single_threaded_bootstrap() {
 465     return _state == NMT_bootstrapping_single_thread;
 466   }
 467 
 468   static void check_NMT_load(Thread* thr) {
 469     assert(thr != NULL, "Sanity check");
 470     if (_slowdown_calling_thread && thr != _worker_thread) {
 471       os::yield_all();
 472     }
 473   }
 474 
 475   static void inc_pending_op_count() {
 476     Atomic::inc(&_pending_op_count);
 477   }
 478 
 479   static void dec_pending_op_count() { 
 480     Atomic::dec(&_pending_op_count);
 481     assert(_pending_op_count >= 0, "Sanity check");
 482   }
 483 
 484 
 485  private:
 486   // retrieve a pooled memory record or create new one if there is not
 487   // one available
 488   static MemRecorder* get_new_or_pooled_instance();
 489   static void create_memory_record(address addr, MEMFLAGS type,
 490                    size_t size, address pc, Thread* thread);
 491   static void create_record_in_recorder(address addr, MEMFLAGS type,
 492                    size_t size, address pc, JavaThread* thread);
 493 
 494   static void set_current_processing_generation(unsigned long generation) {
 495     _worker_thread_idle = false;
 496     _processing_generation = generation;
 497   }
 498 
 499   static void report_worker_idle() {
 500     _worker_thread_idle = true;
 501   }
 502 
 503  private:
 504   // global memory snapshot
 505   static MemSnapshot*     _snapshot;
 506 
 507   // a memory baseline of snapshot
 508   static MemBaseline      _baseline;
 509 
 510   // query lock
 511   static Mutex*           _query_lock;
 512 
 513   // a thread can start to allocate memory before it is attached
 514   // to VM 'Thread', those memory activities are recorded here.
 515   // ThreadCritical is required to guard this global recorder.
 516   static MemRecorder* volatile _global_recorder;
 517 
 518   // main thread id
 519   debug_only(static intx   _main_thread_tid;)
 520 
 521   // pending recorders to be merged
 522   static MemRecorder* volatile     _merge_pending_queue;
 523 
 524   NOT_PRODUCT(static volatile jint   _pending_recorder_count;)
 525 
 526   // pooled memory recorders
 527   static MemRecorder* volatile     _pooled_recorders;
 528 
 529   // memory recorder pool management, uses following
 530   // counter to determine if a released memory recorder
 531   // should be pooled
 532 
 533   // latest thread count
 534   static int               _thread_count;
 535   // pooled recorder count
 536   static volatile jint     _pooled_recorder_count;
 537 
 538 
 539   // worker thread to merge pending recorders into snapshot
 540   static MemTrackWorker*  _worker_thread;
 541 
 542   // how many safepoints we skipped without entering sync point
 543   static int              _sync_point_skip_count;
 544 
 545   // if the tracker is properly intialized
 546   static bool             _is_tracker_ready;
 547   // tracking level (off, summary and detail)
 548   static enum NMTLevel    _tracking_level;
 549 
 550   // current nmt state
 551   static volatile enum NMTStates   _state;
 552   // the reason for shutting down nmt
 553   static enum ShutdownReason       _reason;
 554   // the generation that NMT is processing
 555   static volatile unsigned long    _processing_generation;
 556   // although NMT is still procesing current generation, but
 557   // there is not more recorder to process, set idle state
 558   static volatile bool             _worker_thread_idle;
 559 
 560   // if NMT should slow down calling thread to allow
 561   // worker thread to catch up
 562   static volatile bool             _slowdown_calling_thread;
 563 
 564   // pending memory op count.
 565   // Certain memory ops need to pre-reserve sequence number
 566   // before memory operation can happen to avoid race condition.
 567   // See MemTracker::Tracker for detail
 568   static volatile jint             _pending_op_count;
 569 };
 570 
 571 #endif // !INCLUDE_NMT
 572 
 573 #endif // SHARE_VM_SERVICES_MEM_TRACKER_HPP