OSDN Git Service

Fix calling make with slice whose element type is size zero.
[pf3gnuchains/gcc-fork.git] / libgo / runtime / cpuprof.c
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.
4
5 // CPU profiling.
6 // Based on algorithms and data structures used in
7 // http://code.google.com/p/google-perftools/.
8 //
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.
13 //
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
28 // piece it obtained.
29 //
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.  
41 //
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.
50
51 #include "runtime.h"
52 #include "malloc.h"
53
54 #include "array.h"
55 typedef struct __go_open_array Slice;
56 #define array __values
57 #define len __count
58 #define cap __capacity
59
60 enum
61 {
62         HashSize = 1<<10,
63         LogSize = 1<<17,
64         Assoc = 4,
65         MaxStack = 64,
66 };
67
68 typedef struct Profile Profile;
69 typedef struct Bucket Bucket;
70 typedef struct Entry Entry;
71
72 struct Entry {
73         uintptr count;
74         uintptr depth;
75         uintptr stack[MaxStack];
76 };
77
78 struct Bucket {
79         Entry entry[Assoc];
80 };
81
82 struct Profile {
83         bool on;                // profiling is on
84         Note wait;              // goroutine waits here
85         uintptr count;          // tick count
86         uintptr evicts;         // eviction count
87         uintptr lost;           // lost ticks that need to be logged
88         uintptr totallost;      // total lost ticks
89
90         // Active recent stack traces.
91         Bucket hash[HashSize];
92
93         // Log of traces evicted from hash.
94         // Signal handler has filled log[toggle][:nlog].
95         // Goroutine is writing log[1-toggle][:handoff].
96         uintptr log[2][LogSize/2];
97         uintptr nlog;
98         int32 toggle;
99         uint32 handoff;
100         
101         // Writer state.
102         // Writer maintains its own toggle to avoid races
103         // looking at signal handler's toggle.
104         uint32 wtoggle;
105         bool wholding;  // holding & need to release a log half
106         bool flushing;  // flushing hash table - profile is over
107 };
108
109 static Lock lk;
110 static Profile *prof;
111
112 static void tick(uintptr*, int32);
113 static void add(Profile*, uintptr*, int32);
114 static bool evict(Profile*, Entry*);
115 static bool flushlog(Profile*);
116
117 void
118 runtime_cpuprofinit(void)
119 {
120         runtime_initlock(&lk);
121 }
122
123 // LostProfileData is a no-op function used in profiles
124 // to mark the number of profiling stack traces that were
125 // discarded due to slow data writers.
126 static void LostProfileData(void) {
127 }
128
129 extern void runtime_SetCPUProfileRate(int32)
130      __asm__("libgo_runtime.runtime.SetCPUProfileRate");
131
132 // SetCPUProfileRate sets the CPU profiling rate.
133 // The user documentation is in debug.go.
134 void
135 runtime_SetCPUProfileRate(int32 hz)
136 {
137         uintptr *p;
138         uintptr n;
139
140         // Clamp hz to something reasonable.
141         if(hz < 0)
142                 hz = 0;
143         if(hz > 1000000)
144                 hz = 1000000;
145
146         runtime_lock(&lk);
147         if(hz > 0) {
148                 if(prof == nil) {
149                         prof = runtime_SysAlloc(sizeof *prof);
150                         if(prof == nil) {
151                                 runtime_printf("runtime: cpu profiling cannot allocate memory\n");
152                                 runtime_unlock(&lk);
153                                 return;
154                         }
155                 }
156                 if(prof->on || prof->handoff != 0) {
157                         runtime_printf("runtime: cannot set cpu profile rate until previous profile has finished.\n");
158                         runtime_unlock(&lk);
159                         return;
160                 }
161
162                 prof->on = true;
163                 p = prof->log[0];
164                 // pprof binary header format.
165                 // http://code.google.com/p/google-perftools/source/browse/trunk/src/profiledata.cc#117
166                 *p++ = 0;  // count for header
167                 *p++ = 3;  // depth for header
168                 *p++ = 0;  // version number
169                 *p++ = 1000000 / hz;  // period (microseconds)
170                 *p++ = 0;
171                 prof->nlog = p - prof->log[0];
172                 prof->toggle = 0;
173                 prof->wholding = false;
174                 prof->wtoggle = 0;
175                 prof->flushing = false;
176                 runtime_noteclear(&prof->wait);
177
178                 runtime_setcpuprofilerate(tick, hz);
179         } else if(prof->on) {
180                 runtime_setcpuprofilerate(nil, 0);
181                 prof->on = false;
182
183                 // Now add is not running anymore, and getprofile owns the entire log.
184                 // Set the high bit in prof->handoff to tell getprofile.
185                 for(;;) {
186                         n = prof->handoff;
187                         if(n&0x80000000)
188                                 runtime_printf("runtime: setcpuprofile(off) twice");
189                         if(runtime_cas(&prof->handoff, n, n|0x80000000))
190                                 break;
191                 }
192                 if(n == 0) {
193                         // we did the transition from 0 -> nonzero so we wake getprofile
194                         runtime_notewakeup(&prof->wait);
195                 }
196         }
197         runtime_unlock(&lk);
198 }
199
200 static void
201 tick(uintptr *pc, int32 n)
202 {
203         add(prof, pc, n);
204 }
205
206 // add adds the stack trace to the profile.
207 // It is called from signal handlers and other limited environments
208 // and cannot allocate memory or acquire locks that might be
209 // held at the time of the signal, nor can it use substantial amounts
210 // of stack.  It is allowed to call evict.
211 static void
212 add(Profile *p, uintptr *pc, int32 n)
213 {
214         int32 i, j;
215         uintptr h, x;
216         Bucket *b;
217         Entry *e;
218
219         if(n > MaxStack)
220                 n = MaxStack;
221         
222         // Compute hash.
223         h = 0;
224         for(i=0; i<n; i++) {
225                 h = h<<8 | (h>>(8*(sizeof(h)-1)));
226                 x = pc[i];
227                 h += x*31 + x*7 + x*3;
228         }
229         p->count++;
230
231         // Add to entry count if already present in table.
232         b = &p->hash[h%HashSize];
233         for(i=0; i<Assoc; i++) {
234                 e = &b->entry[i];
235                 if(e->depth != (uintptr)n)      
236                         continue;
237                 for(j=0; j<n; j++)
238                         if(e->stack[j] != pc[j])
239                                 goto ContinueAssoc;
240                 e->count++;
241                 return;
242         ContinueAssoc:;
243         }
244
245         // Evict entry with smallest count.
246         e = &b->entry[0];
247         for(i=1; i<Assoc; i++)
248                 if(b->entry[i].count < e->count)
249                         e = &b->entry[i];
250         if(e->count > 0) {
251                 if(!evict(p, e)) {
252                         // Could not evict entry.  Record lost stack.
253                         p->lost++;
254                         p->totallost++;
255                         return;
256                 }
257                 p->evicts++;
258         }
259         
260         // Reuse the newly evicted entry.
261         e->depth = n;
262         e->count = 1;
263         for(i=0; i<n; i++)
264                 e->stack[i] = pc[i];
265 }
266
267 // evict copies the given entry's data into the log, so that
268 // the entry can be reused.  evict is called from add, which
269 // is called from the profiling signal handler, so it must not
270 // allocate memory or block.  It is safe to call flushLog.
271 // evict returns true if the entry was copied to the log,
272 // false if there was no room available.
273 static bool
274 evict(Profile *p, Entry *e)
275 {
276         int32 i, d, nslot;
277         uintptr *log, *q;
278         
279         d = e->depth;
280         nslot = d+2;
281         log = p->log[p->toggle];
282         if(p->nlog+nslot > nelem(p->log[0])) {
283                 if(!flushlog(p))
284                         return false;
285                 log = p->log[p->toggle];
286         }
287         
288         q = log+p->nlog;
289         *q++ = e->count;
290         *q++ = d;
291         for(i=0; i<d; i++)
292                 *q++ = e->stack[i];
293         p->nlog = q - log;
294         e->count = 0;
295         return true;
296 }
297
298 // flushlog tries to flush the current log and switch to the other one.
299 // flushlog is called from evict, called from add, called from the signal handler,
300 // so it cannot allocate memory or block.  It can try to swap logs with
301 // the writing goroutine, as explained in the comment at the top of this file.
302 static bool
303 flushlog(Profile *p)
304 {
305         uintptr *log, *q;
306
307         if(!runtime_cas(&p->handoff, 0, p->nlog))
308                 return false;
309         runtime_notewakeup(&p->wait);
310
311         p->toggle = 1 - p->toggle;
312         log = p->log[p->toggle];
313         q = log;
314         if(p->lost > 0) {
315                 *q++ = p->lost;
316                 *q++ = 1;
317                 *q++ = (uintptr)LostProfileData;
318         }
319         p->nlog = q - log;
320         return true;
321 }
322
323 // getprofile blocks until the next block of profiling data is available
324 // and returns it as a []byte.  It is called from the writing goroutine.
325 Slice
326 getprofile(Profile *p)
327 {
328         uint32 i, j, n;
329         Slice ret;
330         Bucket *b;
331         Entry *e;
332
333         ret.array = nil;
334         ret.len = 0;
335         ret.cap = 0;
336         
337         if(p == nil)    
338                 return ret;
339
340         if(p->wholding) {
341                 // Release previous log to signal handling side.
342                 // Loop because we are racing against setprofile(off).
343                 for(;;) {
344                         n = p->handoff;
345                         if(n == 0) {
346                                 runtime_printf("runtime: phase error during cpu profile handoff\n");
347                                 return ret;
348                         }
349                         if(n & 0x80000000) {
350                                 p->wtoggle = 1 - p->wtoggle;
351                                 p->wholding = false;
352                                 p->flushing = true;
353                                 goto flush;
354                         }
355                         if(runtime_cas(&p->handoff, n, 0))
356                                 break;
357                 }
358                 p->wtoggle = 1 - p->wtoggle;
359                 p->wholding = false;
360         }
361         
362         if(p->flushing)
363                 goto flush;
364         
365         if(!p->on && p->handoff == 0)
366                 return ret;
367
368         // Wait for new log.
369         // runtime·entersyscall();
370         runtime_notesleep(&p->wait);
371         // runtime·exitsyscall();
372         runtime_noteclear(&p->wait);
373
374         n = p->handoff;
375         if(n == 0) {
376                 runtime_printf("runtime: phase error during cpu profile wait\n");
377                 return ret;
378         }
379         if(n == 0x80000000) {
380                 p->flushing = true;
381                 goto flush;
382         }
383         n &= ~0x80000000;
384
385         // Return new log to caller.
386         p->wholding = true;
387
388         ret.array = (byte*)p->log[p->wtoggle];
389         ret.len = n*sizeof(uintptr);
390         ret.cap = ret.len;
391         return ret;
392
393 flush:
394         // In flush mode.
395         // Add is no longer being called.  We own the log.
396         // Also, p->handoff is non-zero, so flushlog will return false.
397         // Evict the hash table into the log and return it.
398         for(i=0; i<HashSize; i++) {
399                 b = &p->hash[i];
400                 for(j=0; j<Assoc; j++) {
401                         e = &b->entry[j];
402                         if(e->count > 0 && !evict(p, e)) {
403                                 // Filled the log.  Stop the loop and return what we've got.
404                                 goto breakflush;
405                         }
406                 }
407         }
408 breakflush:
409
410         // Return pending log data.
411         if(p->nlog > 0) {
412                 // Note that we're using toggle now, not wtoggle,
413                 // because we're working on the log directly.
414                 ret.array = (byte*)p->log[p->toggle];
415                 ret.len = p->nlog*sizeof(uintptr);
416                 ret.cap = ret.len;
417                 p->nlog = 0;
418                 return ret;
419         }
420
421         // Made it through the table without finding anything to log.
422         // Finally done.  Clean up and return nil.
423         p->flushing = false;
424         if(!runtime_cas(&p->handoff, p->handoff, 0))
425                 runtime_printf("runtime: profile flush racing with something\n");
426         return ret;  // set to nil at top of function
427 }
428
429 extern Slice runtime_CPUProfile(void)
430      __asm__("libgo_runtime.runtime.CPUProfile");
431
432 // CPUProfile returns the next cpu profile block as a []byte.
433 // The user documentation is in debug.go.
434 Slice
435 runtime_CPUProfile(void)
436 {
437         return getprofile(prof);
438 }