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