]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mprof.go
runtime: remove dead code
[gostls13.git] / src / runtime / mprof.go
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.
4
5 // Malloc profiling.
6 // Patterned after tcmalloc's algorithms; shorter code.
7
8 package runtime
9
10 import (
11         "unsafe"
12 )
13
14 // NOTE(rsc): Everything here could use cas if contention became an issue.
15 var proflock mutex
16
17 // All memory allocations are local and do not escape outside of the profiler.
18 // The profiler is forbidden from referring to garbage-collected memory.
19
20 const (
21         // profile types
22         memProfile bucketType = 1 + iota
23         blockProfile
24
25         // size of bucket hash table
26         buckHashSize = 179999
27
28         // max depth of stack to record in bucket
29         maxStack = 32
30 )
31
32 type bucketType int
33
34 // A bucket holds per-call-stack profiling information.
35 // The representation is a bit sleazy, inherited from C.
36 // This struct defines the bucket header. It is followed in
37 // memory by the stack words and then the actual record
38 // data, either a memRecord or a blockRecord.
39 //
40 // Per-call-stack profiling information.
41 // Lookup by hashing call stack into a linked-list hash table.
42 type bucket struct {
43         next    *bucket
44         allnext *bucket
45         typ     bucketType // memBucket or blockBucket
46         hash    uintptr
47         size    uintptr
48         nstk    uintptr
49 }
50
51 // A memRecord is the bucket data for a bucket of type memProfile,
52 // part of the memory profile.
53 type memRecord struct {
54         // The following complex 3-stage scheme of stats accumulation
55         // is required to obtain a consistent picture of mallocs and frees
56         // for some point in time.
57         // The problem is that mallocs come in real time, while frees
58         // come only after a GC during concurrent sweeping. So if we would
59         // naively count them, we would get a skew toward mallocs.
60         //
61         // Mallocs are accounted in recent stats.
62         // Explicit frees are accounted in recent stats.
63         // GC frees are accounted in prev stats.
64         // After GC prev stats are added to final stats and
65         // recent stats are moved into prev stats.
66         allocs      uintptr
67         frees       uintptr
68         alloc_bytes uintptr
69         free_bytes  uintptr
70
71         // changes between next-to-last GC and last GC
72         prev_allocs      uintptr
73         prev_frees       uintptr
74         prev_alloc_bytes uintptr
75         prev_free_bytes  uintptr
76
77         // changes since last GC
78         recent_allocs      uintptr
79         recent_frees       uintptr
80         recent_alloc_bytes uintptr
81         recent_free_bytes  uintptr
82 }
83
84 // A blockRecord is the bucket data for a bucket of type blockProfile,
85 // part of the blocking profile.
86 type blockRecord struct {
87         count  int64
88         cycles int64
89 }
90
91 var (
92         mbuckets  *bucket // memory profile buckets
93         bbuckets  *bucket // blocking profile buckets
94         buckhash  *[179999]*bucket
95         bucketmem uintptr
96 )
97
98 // newBucket allocates a bucket with the given type and number of stack entries.
99 func newBucket(typ bucketType, nstk int) *bucket {
100         size := unsafe.Sizeof(bucket{}) + uintptr(nstk)*unsafe.Sizeof(uintptr(0))
101         switch typ {
102         default:
103                 throw("invalid profile bucket type")
104         case memProfile:
105                 size += unsafe.Sizeof(memRecord{})
106         case blockProfile:
107                 size += unsafe.Sizeof(blockRecord{})
108         }
109
110         b := (*bucket)(persistentalloc(size, 0, &memstats.buckhash_sys))
111         bucketmem += size
112         b.typ = typ
113         b.nstk = uintptr(nstk)
114         return b
115 }
116
117 // stk returns the slice in b holding the stack.
118 func (b *bucket) stk() []uintptr {
119         stk := (*[maxStack]uintptr)(add(unsafe.Pointer(b), unsafe.Sizeof(*b)))
120         return stk[:b.nstk:b.nstk]
121 }
122
123 // mp returns the memRecord associated with the memProfile bucket b.
124 func (b *bucket) mp() *memRecord {
125         if b.typ != memProfile {
126                 throw("bad use of bucket.mp")
127         }
128         data := add(unsafe.Pointer(b), unsafe.Sizeof(*b)+b.nstk*unsafe.Sizeof(uintptr(0)))
129         return (*memRecord)(data)
130 }
131
132 // bp returns the blockRecord associated with the blockProfile bucket b.
133 func (b *bucket) bp() *blockRecord {
134         if b.typ != blockProfile {
135                 throw("bad use of bucket.bp")
136         }
137         data := add(unsafe.Pointer(b), unsafe.Sizeof(*b)+b.nstk*unsafe.Sizeof(uintptr(0)))
138         return (*blockRecord)(data)
139 }
140
141 // Return the bucket for stk[0:nstk], allocating new bucket if needed.
142 func stkbucket(typ bucketType, size uintptr, stk []uintptr, alloc bool) *bucket {
143         if buckhash == nil {
144                 buckhash = (*[buckHashSize]*bucket)(sysAlloc(unsafe.Sizeof(*buckhash), &memstats.buckhash_sys))
145                 if buckhash == nil {
146                         throw("runtime: cannot allocate memory")
147                 }
148         }
149
150         // Hash stack.
151         var h uintptr
152         for _, pc := range stk {
153                 h += pc
154                 h += h << 10
155                 h ^= h >> 6
156         }
157         // hash in size
158         h += size
159         h += h << 10
160         h ^= h >> 6
161         // finalize
162         h += h << 3
163         h ^= h >> 11
164
165         i := int(h % buckHashSize)
166         for b := buckhash[i]; b != nil; b = b.next {
167                 if b.typ == typ && b.hash == h && b.size == size && eqslice(b.stk(), stk) {
168                         return b
169                 }
170         }
171
172         if !alloc {
173                 return nil
174         }
175
176         // Create new bucket.
177         b := newBucket(typ, len(stk))
178         copy(b.stk(), stk)
179         b.hash = h
180         b.size = size
181         b.next = buckhash[i]
182         buckhash[i] = b
183         if typ == memProfile {
184                 b.allnext = mbuckets
185                 mbuckets = b
186         } else {
187                 b.allnext = bbuckets
188                 bbuckets = b
189         }
190         return b
191 }
192
193 func eqslice(x, y []uintptr) bool {
194         if len(x) != len(y) {
195                 return false
196         }
197         for i, xi := range x {
198                 if xi != y[i] {
199                         return false
200                 }
201         }
202         return true
203 }
204
205 func mprof_GC() {
206         for b := mbuckets; b != nil; b = b.allnext {
207                 mp := b.mp()
208                 mp.allocs += mp.prev_allocs
209                 mp.frees += mp.prev_frees
210                 mp.alloc_bytes += mp.prev_alloc_bytes
211                 mp.free_bytes += mp.prev_free_bytes
212
213                 mp.prev_allocs = mp.recent_allocs
214                 mp.prev_frees = mp.recent_frees
215                 mp.prev_alloc_bytes = mp.recent_alloc_bytes
216                 mp.prev_free_bytes = mp.recent_free_bytes
217
218                 mp.recent_allocs = 0
219                 mp.recent_frees = 0
220                 mp.recent_alloc_bytes = 0
221                 mp.recent_free_bytes = 0
222         }
223 }
224
225 // Record that a gc just happened: all the 'recent' statistics are now real.
226 func mProf_GC() {
227         lock(&proflock)
228         mprof_GC()
229         unlock(&proflock)
230 }
231
232 // Called by malloc to record a profiled block.
233 func mProf_Malloc(p unsafe.Pointer, size uintptr) {
234         var stk [maxStack]uintptr
235         nstk := callers(4, stk[:])
236         lock(&proflock)
237         b := stkbucket(memProfile, size, stk[:nstk], true)
238         mp := b.mp()
239         mp.recent_allocs++
240         mp.recent_alloc_bytes += size
241         unlock(&proflock)
242
243         // Setprofilebucket locks a bunch of other mutexes, so we call it outside of proflock.
244         // This reduces potential contention and chances of deadlocks.
245         // Since the object must be alive during call to mProf_Malloc,
246         // it's fine to do this non-atomically.
247         systemstack(func() {
248                 setprofilebucket(p, b)
249         })
250 }
251
252 // Called when freeing a profiled block.
253 func mProf_Free(b *bucket, size uintptr) {
254         lock(&proflock)
255         mp := b.mp()
256         mp.prev_frees++
257         mp.prev_free_bytes += size
258         unlock(&proflock)
259 }
260
261 var blockprofilerate uint64 // in CPU ticks
262
263 // SetBlockProfileRate controls the fraction of goroutine blocking events
264 // that are reported in the blocking profile.  The profiler aims to sample
265 // an average of one blocking event per rate nanoseconds spent blocked.
266 //
267 // To include every blocking event in the profile, pass rate = 1.
268 // To turn off profiling entirely, pass rate <= 0.
269 func SetBlockProfileRate(rate int) {
270         var r int64
271         if rate <= 0 {
272                 r = 0 // disable profiling
273         } else if rate == 1 {
274                 r = 1 // profile everything
275         } else {
276                 // convert ns to cycles, use float64 to prevent overflow during multiplication
277                 r = int64(float64(rate) * float64(tickspersecond()) / (1000 * 1000 * 1000))
278                 if r == 0 {
279                         r = 1
280                 }
281         }
282
283         atomicstore64(&blockprofilerate, uint64(r))
284 }
285
286 func blockevent(cycles int64, skip int) {
287         if cycles <= 0 {
288                 cycles = 1
289         }
290         rate := int64(atomicload64(&blockprofilerate))
291         if rate <= 0 || (rate > cycles && int64(fastrand1())%rate > cycles) {
292                 return
293         }
294         gp := getg()
295         var nstk int
296         var stk [maxStack]uintptr
297         if gp.m.curg == nil || gp.m.curg == gp {
298                 nstk = callers(skip, stk[:])
299         } else {
300                 nstk = gcallers(gp.m.curg, skip, stk[:])
301         }
302         lock(&proflock)
303         b := stkbucket(blockProfile, 0, stk[:nstk], true)
304         b.bp().count++
305         b.bp().cycles += cycles
306         unlock(&proflock)
307 }
308
309 // Go interface to profile data.
310
311 // A StackRecord describes a single execution stack.
312 type StackRecord struct {
313         Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry
314 }
315
316 // Stack returns the stack trace associated with the record,
317 // a prefix of r.Stack0.
318 func (r *StackRecord) Stack() []uintptr {
319         for i, v := range r.Stack0 {
320                 if v == 0 {
321                         return r.Stack0[0:i]
322                 }
323         }
324         return r.Stack0[0:]
325 }
326
327 // MemProfileRate controls the fraction of memory allocations
328 // that are recorded and reported in the memory profile.
329 // The profiler aims to sample an average of
330 // one allocation per MemProfileRate bytes allocated.
331 //
332 // To include every allocated block in the profile, set MemProfileRate to 1.
333 // To turn off profiling entirely, set MemProfileRate to 0.
334 //
335 // The tools that process the memory profiles assume that the
336 // profile rate is constant across the lifetime of the program
337 // and equal to the current value.  Programs that change the
338 // memory profiling rate should do so just once, as early as
339 // possible in the execution of the program (for example,
340 // at the beginning of main).
341 var MemProfileRate int = 512 * 1024
342
343 // A MemProfileRecord describes the live objects allocated
344 // by a particular call sequence (stack trace).
345 type MemProfileRecord struct {
346         AllocBytes, FreeBytes     int64       // number of bytes allocated, freed
347         AllocObjects, FreeObjects int64       // number of objects allocated, freed
348         Stack0                    [32]uintptr // stack trace for this record; ends at first 0 entry
349 }
350
351 // InUseBytes returns the number of bytes in use (AllocBytes - FreeBytes).
352 func (r *MemProfileRecord) InUseBytes() int64 { return r.AllocBytes - r.FreeBytes }
353
354 // InUseObjects returns the number of objects in use (AllocObjects - FreeObjects).
355 func (r *MemProfileRecord) InUseObjects() int64 {
356         return r.AllocObjects - r.FreeObjects
357 }
358
359 // Stack returns the stack trace associated with the record,
360 // a prefix of r.Stack0.
361 func (r *MemProfileRecord) Stack() []uintptr {
362         for i, v := range r.Stack0 {
363                 if v == 0 {
364                         return r.Stack0[0:i]
365                 }
366         }
367         return r.Stack0[0:]
368 }
369
370 // MemProfile returns n, the number of records in the current memory profile.
371 // If len(p) >= n, MemProfile copies the profile into p and returns n, true.
372 // If len(p) < n, MemProfile does not change p and returns n, false.
373 //
374 // If inuseZero is true, the profile includes allocation records
375 // where r.AllocBytes > 0 but r.AllocBytes == r.FreeBytes.
376 // These are sites where memory was allocated, but it has all
377 // been released back to the runtime.
378 //
379 // Most clients should use the runtime/pprof package or
380 // the testing package's -test.memprofile flag instead
381 // of calling MemProfile directly.
382 func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool) {
383         lock(&proflock)
384         clear := true
385         for b := mbuckets; b != nil; b = b.allnext {
386                 mp := b.mp()
387                 if inuseZero || mp.alloc_bytes != mp.free_bytes {
388                         n++
389                 }
390                 if mp.allocs != 0 || mp.frees != 0 {
391                         clear = false
392                 }
393         }
394         if clear {
395                 // Absolutely no data, suggesting that a garbage collection
396                 // has not yet happened. In order to allow profiling when
397                 // garbage collection is disabled from the beginning of execution,
398                 // accumulate stats as if a GC just happened, and recount buckets.
399                 mprof_GC()
400                 mprof_GC()
401                 n = 0
402                 for b := mbuckets; b != nil; b = b.allnext {
403                         mp := b.mp()
404                         if inuseZero || mp.alloc_bytes != mp.free_bytes {
405                                 n++
406                         }
407                 }
408         }
409         if n <= len(p) {
410                 ok = true
411                 idx := 0
412                 for b := mbuckets; b != nil; b = b.allnext {
413                         mp := b.mp()
414                         if inuseZero || mp.alloc_bytes != mp.free_bytes {
415                                 record(&p[idx], b)
416                                 idx++
417                         }
418                 }
419         }
420         unlock(&proflock)
421         return
422 }
423
424 // Write b's data to r.
425 func record(r *MemProfileRecord, b *bucket) {
426         mp := b.mp()
427         r.AllocBytes = int64(mp.alloc_bytes)
428         r.FreeBytes = int64(mp.free_bytes)
429         r.AllocObjects = int64(mp.allocs)
430         r.FreeObjects = int64(mp.frees)
431         copy(r.Stack0[:], b.stk())
432         for i := int(b.nstk); i < len(r.Stack0); i++ {
433                 r.Stack0[i] = 0
434         }
435 }
436
437 func iterate_memprof(fn func(*bucket, uintptr, *uintptr, uintptr, uintptr, uintptr)) {
438         lock(&proflock)
439         for b := mbuckets; b != nil; b = b.allnext {
440                 mp := b.mp()
441                 fn(b, uintptr(b.nstk), &b.stk()[0], b.size, mp.allocs, mp.frees)
442         }
443         unlock(&proflock)
444 }
445
446 // BlockProfileRecord describes blocking events originated
447 // at a particular call sequence (stack trace).
448 type BlockProfileRecord struct {
449         Count  int64
450         Cycles int64
451         StackRecord
452 }
453
454 // BlockProfile returns n, the number of records in the current blocking profile.
455 // If len(p) >= n, BlockProfile copies the profile into p and returns n, true.
456 // If len(p) < n, BlockProfile does not change p and returns n, false.
457 //
458 // Most clients should use the runtime/pprof package or
459 // the testing package's -test.blockprofile flag instead
460 // of calling BlockProfile directly.
461 func BlockProfile(p []BlockProfileRecord) (n int, ok bool) {
462         lock(&proflock)
463         for b := bbuckets; b != nil; b = b.allnext {
464                 n++
465         }
466         if n <= len(p) {
467                 ok = true
468                 for b := bbuckets; b != nil; b = b.allnext {
469                         bp := b.bp()
470                         r := &p[0]
471                         r.Count = int64(bp.count)
472                         r.Cycles = int64(bp.cycles)
473                         i := copy(r.Stack0[:], b.stk())
474                         for ; i < len(r.Stack0); i++ {
475                                 r.Stack0[i] = 0
476                         }
477                         p = p[1:]
478                 }
479         }
480         unlock(&proflock)
481         return
482 }
483
484 // ThreadCreateProfile returns n, the number of records in the thread creation profile.
485 // If len(p) >= n, ThreadCreateProfile copies the profile into p and returns n, true.
486 // If len(p) < n, ThreadCreateProfile does not change p and returns n, false.
487 //
488 // Most clients should use the runtime/pprof package instead
489 // of calling ThreadCreateProfile directly.
490 func ThreadCreateProfile(p []StackRecord) (n int, ok bool) {
491         first := (*m)(atomicloadp(unsafe.Pointer(&allm)))
492         for mp := first; mp != nil; mp = mp.alllink {
493                 n++
494         }
495         if n <= len(p) {
496                 ok = true
497                 i := 0
498                 for mp := first; mp != nil; mp = mp.alllink {
499                         for s := range mp.createstack {
500                                 p[i].Stack0[s] = uintptr(mp.createstack[s])
501                         }
502                         i++
503                 }
504         }
505         return
506 }
507
508 // GoroutineProfile returns n, the number of records in the active goroutine stack profile.
509 // If len(p) >= n, GoroutineProfile copies the profile into p and returns n, true.
510 // If len(p) < n, GoroutineProfile does not change p and returns n, false.
511 //
512 // Most clients should use the runtime/pprof package instead
513 // of calling GoroutineProfile directly.
514 func GoroutineProfile(p []StackRecord) (n int, ok bool) {
515
516         n = NumGoroutine()
517         if n <= len(p) {
518                 gp := getg()
519                 stopTheWorld("profile")
520
521                 n = NumGoroutine()
522                 if n <= len(p) {
523                         ok = true
524                         r := p
525                         sp := getcallersp(unsafe.Pointer(&p))
526                         pc := getcallerpc(unsafe.Pointer(&p))
527                         systemstack(func() {
528                                 saveg(pc, sp, gp, &r[0])
529                         })
530                         r = r[1:]
531                         for _, gp1 := range allgs {
532                                 if gp1 == gp || readgstatus(gp1) == _Gdead {
533                                         continue
534                                 }
535                                 saveg(^uintptr(0), ^uintptr(0), gp1, &r[0])
536                                 r = r[1:]
537                         }
538                 }
539
540                 startTheWorld()
541         }
542
543         return n, ok
544 }
545
546 func saveg(pc, sp uintptr, gp *g, r *StackRecord) {
547         n := gentraceback(pc, sp, 0, gp, 0, &r.Stack0[0], len(r.Stack0), nil, nil, 0)
548         if n < len(r.Stack0) {
549                 r.Stack0[n] = 0
550         }
551 }
552
553 // Stack formats a stack trace of the calling goroutine into buf
554 // and returns the number of bytes written to buf.
555 // If all is true, Stack formats stack traces of all other goroutines
556 // into buf after the trace for the current goroutine.
557 func Stack(buf []byte, all bool) int {
558         if all {
559                 stopTheWorld("stack trace")
560         }
561
562         n := 0
563         if len(buf) > 0 {
564                 gp := getg()
565                 sp := getcallersp(unsafe.Pointer(&buf))
566                 pc := getcallerpc(unsafe.Pointer(&buf))
567                 systemstack(func() {
568                         g0 := getg()
569                         g0.writebuf = buf[0:0:len(buf)]
570                         goroutineheader(gp)
571                         traceback(pc, sp, 0, gp)
572                         if all {
573                                 tracebackothers(gp)
574                         }
575                         n = len(g0.writebuf)
576                         g0.writebuf = nil
577                 })
578         }
579
580         if all {
581                 startTheWorld()
582         }
583         return n
584 }
585
586 // Tracing of alloc/free/gc.
587
588 var tracelock mutex
589
590 func tracealloc(p unsafe.Pointer, size uintptr, typ *_type) {
591         lock(&tracelock)
592         gp := getg()
593         gp.m.traceback = 2
594         if typ == nil {
595                 print("tracealloc(", p, ", ", hex(size), ")\n")
596         } else {
597                 print("tracealloc(", p, ", ", hex(size), ", ", *typ._string, ")\n")
598         }
599         if gp.m.curg == nil || gp == gp.m.curg {
600                 goroutineheader(gp)
601                 pc := getcallerpc(unsafe.Pointer(&p))
602                 sp := getcallersp(unsafe.Pointer(&p))
603                 systemstack(func() {
604                         traceback(pc, sp, 0, gp)
605                 })
606         } else {
607                 goroutineheader(gp.m.curg)
608                 traceback(^uintptr(0), ^uintptr(0), 0, gp.m.curg)
609         }
610         print("\n")
611         gp.m.traceback = 0
612         unlock(&tracelock)
613 }
614
615 func tracefree(p unsafe.Pointer, size uintptr) {
616         lock(&tracelock)
617         gp := getg()
618         gp.m.traceback = 2
619         print("tracefree(", p, ", ", hex(size), ")\n")
620         goroutineheader(gp)
621         pc := getcallerpc(unsafe.Pointer(&p))
622         sp := getcallersp(unsafe.Pointer(&p))
623         systemstack(func() {
624                 traceback(pc, sp, 0, gp)
625         })
626         print("\n")
627         gp.m.traceback = 0
628         unlock(&tracelock)
629 }
630
631 func tracegc() {
632         lock(&tracelock)
633         gp := getg()
634         gp.m.traceback = 2
635         print("tracegc()\n")
636         // running on m->g0 stack; show all non-g0 goroutines
637         tracebackothers(gp)
638         print("end tracegc\n")
639         print("\n")
640         gp.m.traceback = 0
641         unlock(&tracelock)
642 }