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