1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
6 // Patterned after tcmalloc's algorithms; shorter code.
11 "runtime/internal/atomic"
15 // NOTE(rsc): Everything here could use cas if contention became an issue.
18 // All memory allocations are local and do not escape outside of the profiler.
19 // The profiler is forbidden from referring to garbage-collected memory.
23 memProfile bucketType = 1 + iota
26 // size of bucket hash table
29 // max depth of stack to record in bucket
35 // A bucket holds per-call-stack profiling information.
36 // The representation is a bit sleazy, inherited from C.
37 // This struct defines the bucket header. It is followed in
38 // memory by the stack words and then the actual record
39 // data, either a memRecord or a blockRecord.
41 // Per-call-stack profiling information.
42 // Lookup by hashing call stack into a linked-list hash table.
46 typ bucketType // memBucket or blockBucket
52 // A memRecord is the bucket data for a bucket of type memProfile,
53 // part of the memory profile.
54 type memRecord struct {
55 // The following complex 3-stage scheme of stats accumulation
56 // is required to obtain a consistent picture of mallocs and frees
57 // for some point in time.
58 // The problem is that mallocs come in real time, while frees
59 // come only after a GC during concurrent sweeping. So if we would
60 // naively count them, we would get a skew toward mallocs.
62 // Mallocs are accounted in recent stats.
63 // Explicit frees are accounted in recent stats.
64 // GC frees are accounted in prev stats.
65 // After GC prev stats are added to final stats and
66 // recent stats are moved into prev stats.
72 // changes between next-to-last GC and last GC
75 prev_alloc_bytes uintptr
76 prev_free_bytes uintptr
78 // changes since last GC
81 recent_alloc_bytes uintptr
82 recent_free_bytes uintptr
85 // A blockRecord is the bucket data for a bucket of type blockProfile,
86 // part of the blocking profile.
87 type blockRecord struct {
93 mbuckets *bucket // memory profile buckets
94 bbuckets *bucket // blocking profile buckets
95 buckhash *[179999]*bucket
99 // newBucket allocates a bucket with the given type and number of stack entries.
100 func newBucket(typ bucketType, nstk int) *bucket {
101 size := unsafe.Sizeof(bucket{}) + uintptr(nstk)*unsafe.Sizeof(uintptr(0))
104 throw("invalid profile bucket type")
106 size += unsafe.Sizeof(memRecord{})
108 size += unsafe.Sizeof(blockRecord{})
111 b := (*bucket)(persistentalloc(size, 0, &memstats.buckhash_sys))
114 b.nstk = uintptr(nstk)
118 // stk returns the slice in b holding the stack.
119 func (b *bucket) stk() []uintptr {
120 stk := (*[maxStack]uintptr)(add(unsafe.Pointer(b), unsafe.Sizeof(*b)))
121 return stk[:b.nstk:b.nstk]
124 // mp returns the memRecord associated with the memProfile bucket b.
125 func (b *bucket) mp() *memRecord {
126 if b.typ != memProfile {
127 throw("bad use of bucket.mp")
129 data := add(unsafe.Pointer(b), unsafe.Sizeof(*b)+b.nstk*unsafe.Sizeof(uintptr(0)))
130 return (*memRecord)(data)
133 // bp returns the blockRecord associated with the blockProfile bucket b.
134 func (b *bucket) bp() *blockRecord {
135 if b.typ != blockProfile {
136 throw("bad use of bucket.bp")
138 data := add(unsafe.Pointer(b), unsafe.Sizeof(*b)+b.nstk*unsafe.Sizeof(uintptr(0)))
139 return (*blockRecord)(data)
142 // Return the bucket for stk[0:nstk], allocating new bucket if needed.
143 func stkbucket(typ bucketType, size uintptr, stk []uintptr, alloc bool) *bucket {
145 buckhash = (*[buckHashSize]*bucket)(sysAlloc(unsafe.Sizeof(*buckhash), &memstats.buckhash_sys))
147 throw("runtime: cannot allocate memory")
153 for _, pc := range stk {
166 i := int(h % buckHashSize)
167 for b := buckhash[i]; b != nil; b = b.next {
168 if b.typ == typ && b.hash == h && b.size == size && eqslice(b.stk(), stk) {
177 // Create new bucket.
178 b := newBucket(typ, len(stk))
184 if typ == memProfile {
194 func eqslice(x, y []uintptr) bool {
195 if len(x) != len(y) {
198 for i, xi := range x {
207 for b := mbuckets; b != nil; b = b.allnext {
209 mp.allocs += mp.prev_allocs
210 mp.frees += mp.prev_frees
211 mp.alloc_bytes += mp.prev_alloc_bytes
212 mp.free_bytes += mp.prev_free_bytes
214 mp.prev_allocs = mp.recent_allocs
215 mp.prev_frees = mp.recent_frees
216 mp.prev_alloc_bytes = mp.recent_alloc_bytes
217 mp.prev_free_bytes = mp.recent_free_bytes
221 mp.recent_alloc_bytes = 0
222 mp.recent_free_bytes = 0
226 // Record that a gc just happened: all the 'recent' statistics are now real.
233 // Called by malloc to record a profiled block.
234 func mProf_Malloc(p unsafe.Pointer, size uintptr) {
235 var stk [maxStack]uintptr
236 nstk := callers(4, stk[:])
238 b := stkbucket(memProfile, size, stk[:nstk], true)
241 mp.recent_alloc_bytes += size
244 // Setprofilebucket locks a bunch of other mutexes, so we call it outside of proflock.
245 // This reduces potential contention and chances of deadlocks.
246 // Since the object must be alive during call to mProf_Malloc,
247 // it's fine to do this non-atomically.
249 setprofilebucket(p, b)
253 // Called when freeing a profiled block.
254 func mProf_Free(b *bucket, size uintptr) {
258 mp.prev_free_bytes += size
262 var blockprofilerate uint64 // in CPU ticks
264 // SetBlockProfileRate controls the fraction of goroutine blocking events
265 // that are reported in the blocking profile. The profiler aims to sample
266 // an average of one blocking event per rate nanoseconds spent blocked.
268 // To include every blocking event in the profile, pass rate = 1.
269 // To turn off profiling entirely, pass rate <= 0.
270 func SetBlockProfileRate(rate int) {
273 r = 0 // disable profiling
274 } else if rate == 1 {
275 r = 1 // profile everything
277 // convert ns to cycles, use float64 to prevent overflow during multiplication
278 r = int64(float64(rate) * float64(tickspersecond()) / (1000 * 1000 * 1000))
284 atomic.Store64(&blockprofilerate, uint64(r))
287 func blockevent(cycles int64, skip int) {
291 rate := int64(atomic.Load64(&blockprofilerate))
292 if rate <= 0 || (rate > cycles && int64(fastrand1())%rate > cycles) {
297 var stk [maxStack]uintptr
298 if gp.m.curg == nil || gp.m.curg == gp {
299 nstk = callers(skip, stk[:])
301 nstk = gcallers(gp.m.curg, skip, stk[:])
304 b := stkbucket(blockProfile, 0, stk[:nstk], true)
306 b.bp().cycles += cycles
310 // Go interface to profile data.
312 // A StackRecord describes a single execution stack.
313 type StackRecord struct {
314 Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry
317 // Stack returns the stack trace associated with the record,
318 // a prefix of r.Stack0.
319 func (r *StackRecord) Stack() []uintptr {
320 for i, v := range r.Stack0 {
328 // MemProfileRate controls the fraction of memory allocations
329 // that are recorded and reported in the memory profile.
330 // The profiler aims to sample an average of
331 // one allocation per MemProfileRate bytes allocated.
333 // To include every allocated block in the profile, set MemProfileRate to 1.
334 // To turn off profiling entirely, set MemProfileRate to 0.
336 // The tools that process the memory profiles assume that the
337 // profile rate is constant across the lifetime of the program
338 // and equal to the current value. Programs that change the
339 // memory profiling rate should do so just once, as early as
340 // possible in the execution of the program (for example,
341 // at the beginning of main).
342 var MemProfileRate int = 512 * 1024
344 // A MemProfileRecord describes the live objects allocated
345 // by a particular call sequence (stack trace).
346 type MemProfileRecord struct {
347 AllocBytes, FreeBytes int64 // number of bytes allocated, freed
348 AllocObjects, FreeObjects int64 // number of objects allocated, freed
349 Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry
352 // InUseBytes returns the number of bytes in use (AllocBytes - FreeBytes).
353 func (r *MemProfileRecord) InUseBytes() int64 { return r.AllocBytes - r.FreeBytes }
355 // InUseObjects returns the number of objects in use (AllocObjects - FreeObjects).
356 func (r *MemProfileRecord) InUseObjects() int64 {
357 return r.AllocObjects - r.FreeObjects
360 // Stack returns the stack trace associated with the record,
361 // a prefix of r.Stack0.
362 func (r *MemProfileRecord) Stack() []uintptr {
363 for i, v := range r.Stack0 {
371 // MemProfile returns a profile of memory allocated and freed per allocation
374 // MemProfile returns n, the number of records in the current memory profile.
375 // If len(p) >= n, MemProfile copies the profile into p and returns n, true.
376 // If len(p) < n, MemProfile does not change p and returns n, false.
378 // If inuseZero is true, the profile includes allocation records
379 // where r.AllocBytes > 0 but r.AllocBytes == r.FreeBytes.
380 // These are sites where memory was allocated, but it has all
381 // been released back to the runtime.
383 // The returned profile may be up to two garbage collection cycles old.
384 // This is to avoid skewing the profile toward allocations; because
385 // allocations happen in real time but frees are delayed until the garbage
386 // collector performs sweeping, the profile only accounts for allocations
387 // that have had a chance to be freed by the garbage collector.
389 // Most clients should use the runtime/pprof package or
390 // the testing package's -test.memprofile flag instead
391 // of calling MemProfile directly.
392 func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool) {
395 for b := mbuckets; b != nil; b = b.allnext {
397 if inuseZero || mp.alloc_bytes != mp.free_bytes {
400 if mp.allocs != 0 || mp.frees != 0 {
405 // Absolutely no data, suggesting that a garbage collection
406 // has not yet happened. In order to allow profiling when
407 // garbage collection is disabled from the beginning of execution,
408 // accumulate stats as if a GC just happened, and recount buckets.
412 for b := mbuckets; b != nil; b = b.allnext {
414 if inuseZero || mp.alloc_bytes != mp.free_bytes {
422 for b := mbuckets; b != nil; b = b.allnext {
424 if inuseZero || mp.alloc_bytes != mp.free_bytes {
434 // Write b's data to r.
435 func record(r *MemProfileRecord, b *bucket) {
437 r.AllocBytes = int64(mp.alloc_bytes)
438 r.FreeBytes = int64(mp.free_bytes)
439 r.AllocObjects = int64(mp.allocs)
440 r.FreeObjects = int64(mp.frees)
441 copy(r.Stack0[:], b.stk())
442 for i := int(b.nstk); i < len(r.Stack0); i++ {
447 func iterate_memprof(fn func(*bucket, uintptr, *uintptr, uintptr, uintptr, uintptr)) {
449 for b := mbuckets; b != nil; b = b.allnext {
451 fn(b, b.nstk, &b.stk()[0], b.size, mp.allocs, mp.frees)
456 // BlockProfileRecord describes blocking events originated
457 // at a particular call sequence (stack trace).
458 type BlockProfileRecord struct {
464 // BlockProfile returns n, the number of records in the current blocking profile.
465 // If len(p) >= n, BlockProfile copies the profile into p and returns n, true.
466 // If len(p) < n, BlockProfile does not change p and returns n, false.
468 // Most clients should use the runtime/pprof package or
469 // the testing package's -test.blockprofile flag instead
470 // of calling BlockProfile directly.
471 func BlockProfile(p []BlockProfileRecord) (n int, ok bool) {
473 for b := bbuckets; b != nil; b = b.allnext {
478 for b := bbuckets; b != nil; b = b.allnext {
483 i := copy(r.Stack0[:], b.stk())
484 for ; i < len(r.Stack0); i++ {
494 // ThreadCreateProfile returns n, the number of records in the thread creation profile.
495 // If len(p) >= n, ThreadCreateProfile copies the profile into p and returns n, true.
496 // If len(p) < n, ThreadCreateProfile does not change p and returns n, false.
498 // Most clients should use the runtime/pprof package instead
499 // of calling ThreadCreateProfile directly.
500 func ThreadCreateProfile(p []StackRecord) (n int, ok bool) {
501 first := (*m)(atomic.Loadp(unsafe.Pointer(&allm)))
502 for mp := first; mp != nil; mp = mp.alllink {
508 for mp := first; mp != nil; mp = mp.alllink {
509 p[i].Stack0 = mp.createstack
516 // GoroutineProfile returns n, the number of records in the active goroutine stack profile.
517 // If len(p) >= n, GoroutineProfile copies the profile into p and returns n, true.
518 // If len(p) < n, GoroutineProfile does not change p and returns n, false.
520 // Most clients should use the runtime/pprof package instead
521 // of calling GoroutineProfile directly.
522 func GoroutineProfile(p []StackRecord) (n int, ok bool) {
525 isOK := func(gp1 *g) bool {
526 // Checking isSystemGoroutine here makes GoroutineProfile
527 // consistent with both NumGoroutine and Stack.
528 return gp1 != gp && readgstatus(gp1) != _Gdead && !isSystemGoroutine(gp1)
531 stopTheWorld("profile")
534 for _, gp1 := range allgs {
544 // Save current goroutine.
545 sp := getcallersp(unsafe.Pointer(&p))
546 pc := getcallerpc(unsafe.Pointer(&p))
548 saveg(pc, sp, gp, &r[0])
552 // Save other goroutines.
553 for _, gp1 := range allgs {
556 // Should be impossible, but better to return a
557 // truncated profile than to crash the entire process.
560 saveg(^uintptr(0), ^uintptr(0), gp1, &r[0])
571 func saveg(pc, sp uintptr, gp *g, r *StackRecord) {
572 n := gentraceback(pc, sp, 0, gp, 0, &r.Stack0[0], len(r.Stack0), nil, nil, 0)
573 if n < len(r.Stack0) {
578 // Stack formats a stack trace of the calling goroutine into buf
579 // and returns the number of bytes written to buf.
580 // If all is true, Stack formats stack traces of all other goroutines
581 // into buf after the trace for the current goroutine.
582 func Stack(buf []byte, all bool) int {
584 stopTheWorld("stack trace")
590 sp := getcallersp(unsafe.Pointer(&buf))
591 pc := getcallerpc(unsafe.Pointer(&buf))
594 // Force traceback=1 to override GOTRACEBACK setting,
595 // so that Stack's results are consistent.
596 // GOTRACEBACK is only about crash dumps.
598 g0.writebuf = buf[0:0:len(buf)]
600 traceback(pc, sp, 0, gp)
616 // Tracing of alloc/free/gc.
620 func tracealloc(p unsafe.Pointer, size uintptr, typ *_type) {
625 print("tracealloc(", p, ", ", hex(size), ")\n")
627 print("tracealloc(", p, ", ", hex(size), ", ", typ.string(), ")\n")
629 if gp.m.curg == nil || gp == gp.m.curg {
631 pc := getcallerpc(unsafe.Pointer(&p))
632 sp := getcallersp(unsafe.Pointer(&p))
634 traceback(pc, sp, 0, gp)
637 goroutineheader(gp.m.curg)
638 traceback(^uintptr(0), ^uintptr(0), 0, gp.m.curg)
645 func tracefree(p unsafe.Pointer, size uintptr) {
649 print("tracefree(", p, ", ", hex(size), ")\n")
651 pc := getcallerpc(unsafe.Pointer(&p))
652 sp := getcallersp(unsafe.Pointer(&p))
654 traceback(pc, sp, 0, gp)
666 // running on m->g0 stack; show all non-g0 goroutines
668 print("end tracegc\n")