1 // Copyright 2011 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 // Based on algorithms and data structures used in
7 // http://code.google.com/p/google-perftools/.
9 // The main difference between this code and the google-perftools
10 // code is that this code is written to allow copying the profile data
11 // to an arbitrary io.Writer, while the google-perftools code always
12 // writes to an operating system file.
14 // The signal handler for the profiling clock tick adds a new stack trace
15 // to a hash table tracking counts for recent traces. Most clock ticks
16 // hit in the cache. In the event of a cache miss, an entry must be
17 // evicted from the hash table, copied to a log that will eventually be
18 // written as profile data. The google-perftools code flushed the
19 // log itself during the signal handler. This code cannot do that, because
20 // the io.Writer might block or need system calls or locks that are not
21 // safe to use from within the signal handler. Instead, we split the log
22 // into two halves and let the signal handler fill one half while a goroutine
23 // is writing out the other half. When the signal handler fills its half, it
24 // offers to swap with the goroutine. If the writer is not done with its half,
25 // we lose the stack trace for this clock tick (and record that loss).
26 // The goroutine interacts with the signal handler by calling getprofile() to
27 // get the next log piece to write, implicitly handing back the last log
30 // The state of this dance between the signal handler and the goroutine
31 // is encoded in the Profile.handoff field. If handoff == 0, then the goroutine
32 // is not using either log half and is waiting (or will soon be waiting) for
33 // a new piece by calling notesleep(&p.wait). If the signal handler
34 // changes handoff from 0 to non-zero, it must call notewakeup(&p.wait)
35 // to wake the goroutine. The value indicates the number of entries in the
36 // log half being handed off. The goroutine leaves the non-zero value in
37 // place until it has finished processing the log half and then flips the number
38 // back to zero. Setting the high bit in handoff means that the profiling is over,
39 // and the goroutine is now in charge of flushing the data left in the hash table
40 // to the log and returning that data.
42 // The handoff field is manipulated using atomic operations.
43 // For the most part, the manipulation of handoff is orderly: if handoff == 0
44 // then the signal handler owns it and can change it to non-zero.
45 // If handoff != 0 then the goroutine owns it and can change it to zero.
46 // If that were the end of the story then we would not need to manipulate
47 // handoff using atomic operations. The operations are needed, however,
48 // in order to let the log closer set the high bit to indicate "EOF" safely
49 // in the situation when normally the goroutine "owns" handoff.
62 type cpuprofEntry struct {
65 stack [maxCPUProfStack]uintptr
68 type cpuProfile struct {
69 on bool // profiling is on
70 wait note // goroutine waits here
71 count uintptr // tick count
72 evicts uintptr // eviction count
73 lost uintptr // lost ticks that need to be logged
75 // Active recent stack traces.
76 hash [numBuckets]struct {
77 entry [assoc]cpuprofEntry
80 // Log of traces evicted from hash.
81 // Signal handler has filled log[toggle][:nlog].
82 // Goroutine is writing log[1-toggle][:handoff].
83 log [2][logSize / 2]uintptr
89 // Writer maintains its own toggle to avoid races
90 // looking at signal handler's toggle.
92 wholding bool // holding & need to release a log half
93 flushing bool // flushing hash table - profile is over
94 eodSent bool // special end-of-data record sent; => flushing
101 eod = [3]uintptr{0, 1, 0}
104 func setcpuprofilerate(hz int32) {
106 setcpuprofilerate_m(hz)
110 // lostProfileData is a no-op function used in profiles
111 // to mark the number of profiling stack traces that were
112 // discarded due to slow data writers.
113 func lostProfileData() {}
115 // SetCPUProfileRate sets the CPU profiling rate to hz samples per second.
116 // If hz <= 0, SetCPUProfileRate turns off profiling.
117 // If the profiler is on, the rate cannot be changed without first turning it off.
119 // Most clients should use the runtime/pprof package or
120 // the testing package's -test.cpuprofile flag instead of calling
121 // SetCPUProfileRate directly.
122 func SetCPUProfileRate(hz int) {
123 // Clamp hz to something reasonable.
134 cpuprof = (*cpuProfile)(sysAlloc(unsafe.Sizeof(cpuProfile{}), &memstats.other_sys))
136 print("runtime: cpu profiling cannot allocate memory\n")
141 if cpuprof.on || cpuprof.handoff != 0 {
142 print("runtime: cannot set cpu profile rate until previous profile has finished.\n")
148 // pprof binary header format.
149 // http://code.google.com/p/google-perftools/source/browse/trunk/src/profiledata.cc#117
151 p[0] = 0 // count for header
152 p[1] = 3 // depth for header
153 p[2] = 0 // version number
154 p[3] = uintptr(1e6 / hz) // period (microseconds)
158 cpuprof.wholding = false
160 cpuprof.flushing = false
161 cpuprof.eodSent = false
162 noteclear(&cpuprof.wait)
164 setcpuprofilerate(int32(hz))
165 } else if cpuprof != nil && cpuprof.on {
169 // Now add is not running anymore, and getprofile owns the entire log.
170 // Set the high bit in cpuprof.handoff to tell getprofile.
173 if n&0x80000000 != 0 {
174 print("runtime: setcpuprofile(off) twice\n")
176 if cas(&cpuprof.handoff, n, n|0x80000000) {
178 // we did the transition from 0 -> nonzero so we wake getprofile
179 notewakeup(&cpuprof.wait)
188 // add adds the stack trace to the profile.
189 // It is called from signal handlers and other limited environments
190 // and cannot allocate memory or acquire locks that might be
191 // held at the time of the signal, nor can it use substantial amounts
192 // of stack. It is allowed to call evict.
193 func (p *cpuProfile) add(pc []uintptr) {
194 if len(pc) > maxCPUProfStack {
195 pc = pc[:maxCPUProfStack]
200 for _, x := range pc {
201 h = h<<8 | (h >> (8 * (unsafe.Sizeof(h) - 1)))
206 // Add to entry count if already present in table.
207 b := &p.hash[h%numBuckets]
209 for i := range b.entry {
211 if e.depth != len(pc) {
215 if e.stack[j] != pc[j] {
223 // Evict entry with smallest count.
225 for i := range b.entry {
226 if e == nil || b.entry[i].count < e.count {
232 // Could not evict entry. Record lost stack.
239 // Reuse the newly evicted entry.
245 // evict copies the given entry's data into the log, so that
246 // the entry can be reused. evict is called from add, which
247 // is called from the profiling signal handler, so it must not
248 // allocate memory or block. It is safe to call flushlog.
249 // evict returns true if the entry was copied to the log,
250 // false if there was no room available.
251 func (p *cpuProfile) evict(e *cpuprofEntry) bool {
254 log := &p.log[p.toggle]
255 if p.nlog+nslot > len(log) {
259 log = &p.log[p.toggle]
267 copy(log[q:], e.stack[:d])
274 // flushlog tries to flush the current log and switch to the other one.
275 // flushlog is called from evict, called from add, called from the signal handler,
276 // so it cannot allocate memory or block. It can try to swap logs with
277 // the writing goroutine, as explained in the comment at the top of this file.
278 func (p *cpuProfile) flushlog() bool {
279 if !cas(&p.handoff, 0, uint32(p.nlog)) {
284 p.toggle = 1 - p.toggle
285 log := &p.log[p.toggle]
288 lostPC := funcPC(lostProfileData)
299 // getprofile blocks until the next block of profiling data is available
300 // and returns it as a []byte. It is called from the writing goroutine.
301 func (p *cpuProfile) getprofile() []byte {
307 // Release previous log to signal handling side.
308 // Loop because we are racing against SetCPUProfileRate(0).
312 print("runtime: phase error during cpu profile handoff\n")
315 if n&0x80000000 != 0 {
316 p.wtoggle = 1 - p.wtoggle
321 if cas(&p.handoff, n, 0) {
325 p.wtoggle = 1 - p.wtoggle
333 if !p.on && p.handoff == 0 {
338 notetsleepg(&p.wait, -1)
341 switch n := p.handoff; {
343 print("runtime: phase error during cpu profile wait\n")
345 case n == 0x80000000:
351 // Return new log to caller.
354 return uintptrBytes(p.log[p.wtoggle][:n])
358 // Add is no longer being called. We own the log.
359 // Also, p.handoff is non-zero, so flushlog will return false.
360 // Evict the hash table into the log and return it.
362 for i := range p.hash {
364 for j := range b.entry {
366 if e.count > 0 && !p.evict(e) {
367 // Filled the log. Stop the loop and return what we've got.
373 // Return pending log data.
375 // Note that we're using toggle now, not wtoggle,
376 // because we're working on the log directly.
379 return uintptrBytes(p.log[p.toggle][:n])
382 // Made it through the table without finding anything to log.
384 // We may not have space to append this to the partial log buf,
385 // so we always return a new slice for the end-of-data marker.
387 return uintptrBytes(eod[:])
390 // Finally done. Clean up and return nil.
392 if !cas(&p.handoff, p.handoff, 0) {
393 print("runtime: profile flush racing with something\n")
398 func uintptrBytes(p []uintptr) (ret []byte) {
399 pp := (*sliceStruct)(unsafe.Pointer(&p))
400 rp := (*sliceStruct)(unsafe.Pointer(&ret))
403 rp.len = pp.len * int(unsafe.Sizeof(p[0]))
409 // CPUProfile returns the next chunk of binary CPU profiling stack trace data,
410 // blocking until data is available. If profiling is turned off and all the profile
411 // data accumulated while it was on has been returned, CPUProfile returns nil.
412 // The caller must save the returned data before calling CPUProfile again.
414 // Most clients should use the runtime/pprof package or
415 // the testing package's -test.cpuprofile flag instead of calling
416 // CPUProfile directly.
417 func CPUProfile() []byte {
418 return cpuprof.getprofile()
421 //go:linkname runtime_pprof_runtime_cyclesPerSecond runtime/pprof.runtime_cyclesPerSecond
422 func runtime_pprof_runtime_cyclesPerSecond() int64 {
423 return tickspersecond()