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