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