mprof.goc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. // Malloc profiling.
  5. // Patterned after tcmalloc's algorithms; shorter code.
  6. package runtime
  7. #include "runtime.h"
  8. #include "arch.h"
  9. #include "malloc.h"
  10. #include "defs.h"
  11. #include "go-type.h"
  12. #include "go-string.h"
  13. // NOTE(rsc): Everything here could use cas if contention became an issue.
  14. static Lock proflock;
  15. // All memory allocations are local and do not escape outside of the profiler.
  16. // The profiler is forbidden from referring to garbage-collected memory.
  17. enum { MProf, BProf }; // profile types
  18. // Per-call-stack profiling information.
  19. // Lookup by hashing call stack into a linked-list hash table.
  20. struct Bucket
  21. {
  22. Bucket *next; // next in hash list
  23. Bucket *allnext; // next in list of all mbuckets/bbuckets
  24. int32 typ;
  25. // Generally unions can break precise GC,
  26. // this one is fine because it does not contain pointers.
  27. union
  28. {
  29. struct // typ == MProf
  30. {
  31. // The following complex 3-stage scheme of stats accumulation
  32. // is required to obtain a consistent picture of mallocs and frees
  33. // for some point in time.
  34. // The problem is that mallocs come in real time, while frees
  35. // come only after a GC during concurrent sweeping. So if we would
  36. // naively count them, we would get a skew toward mallocs.
  37. //
  38. // Mallocs are accounted in recent stats.
  39. // Explicit frees are accounted in recent stats.
  40. // GC frees are accounted in prev stats.
  41. // After GC prev stats are added to final stats and
  42. // recent stats are moved into prev stats.
  43. uintptr allocs;
  44. uintptr frees;
  45. uintptr alloc_bytes;
  46. uintptr free_bytes;
  47. uintptr prev_allocs; // since last but one till last gc
  48. uintptr prev_frees;
  49. uintptr prev_alloc_bytes;
  50. uintptr prev_free_bytes;
  51. uintptr recent_allocs; // since last gc till now
  52. uintptr recent_frees;
  53. uintptr recent_alloc_bytes;
  54. uintptr recent_free_bytes;
  55. };
  56. struct // typ == BProf
  57. {
  58. int64 count;
  59. int64 cycles;
  60. };
  61. };
  62. uintptr hash; // hash of size + stk
  63. uintptr size;
  64. uintptr nstk;
  65. Location stk[1];
  66. };
  67. enum {
  68. BuckHashSize = 179999,
  69. };
  70. static Bucket **buckhash;
  71. static Bucket *mbuckets; // memory profile buckets
  72. static Bucket *bbuckets; // blocking profile buckets
  73. static uintptr bucketmem;
  74. // Return the bucket for stk[0:nstk], allocating new bucket if needed.
  75. static Bucket*
  76. stkbucket(int32 typ, uintptr size, Location *stk, int32 nstk, bool alloc)
  77. {
  78. int32 i, j;
  79. uintptr h;
  80. Bucket *b;
  81. if(buckhash == nil) {
  82. buckhash = runtime_SysAlloc(BuckHashSize*sizeof buckhash[0], &mstats.buckhash_sys);
  83. if(buckhash == nil)
  84. runtime_throw("runtime: cannot allocate memory");
  85. }
  86. // Hash stack.
  87. h = 0;
  88. for(i=0; i<nstk; i++) {
  89. h += stk[i].pc;
  90. h += h<<10;
  91. h ^= h>>6;
  92. }
  93. // hash in size
  94. h += size;
  95. h += h<<10;
  96. h ^= h>>6;
  97. // finalize
  98. h += h<<3;
  99. h ^= h>>11;
  100. i = h%BuckHashSize;
  101. for(b = buckhash[i]; b; b=b->next) {
  102. if(b->typ == typ && b->hash == h && b->size == size && b->nstk == (uintptr)nstk) {
  103. for(j = 0; j < nstk; j++) {
  104. if(b->stk[j].pc != stk[j].pc ||
  105. b->stk[j].lineno != stk[j].lineno ||
  106. !__go_strings_equal(b->stk[j].filename, stk[j].filename))
  107. break;
  108. }
  109. if (j == nstk)
  110. return b;
  111. }
  112. }
  113. if(!alloc)
  114. return nil;
  115. b = runtime_persistentalloc(sizeof *b + nstk*sizeof stk[0], 0, &mstats.buckhash_sys);
  116. bucketmem += sizeof *b + nstk*sizeof stk[0];
  117. runtime_memmove(b->stk, stk, nstk*sizeof stk[0]);
  118. b->typ = typ;
  119. b->hash = h;
  120. b->size = size;
  121. b->nstk = nstk;
  122. b->next = buckhash[i];
  123. buckhash[i] = b;
  124. if(typ == MProf) {
  125. b->allnext = mbuckets;
  126. mbuckets = b;
  127. } else {
  128. b->allnext = bbuckets;
  129. bbuckets = b;
  130. }
  131. return b;
  132. }
  133. static void
  134. MProf_GC(void)
  135. {
  136. Bucket *b;
  137. for(b=mbuckets; b; b=b->allnext) {
  138. b->allocs += b->prev_allocs;
  139. b->frees += b->prev_frees;
  140. b->alloc_bytes += b->prev_alloc_bytes;
  141. b->free_bytes += b->prev_free_bytes;
  142. b->prev_allocs = b->recent_allocs;
  143. b->prev_frees = b->recent_frees;
  144. b->prev_alloc_bytes = b->recent_alloc_bytes;
  145. b->prev_free_bytes = b->recent_free_bytes;
  146. b->recent_allocs = 0;
  147. b->recent_frees = 0;
  148. b->recent_alloc_bytes = 0;
  149. b->recent_free_bytes = 0;
  150. }
  151. }
  152. // Record that a gc just happened: all the 'recent' statistics are now real.
  153. void
  154. runtime_MProf_GC(void)
  155. {
  156. runtime_lock(&proflock);
  157. MProf_GC();
  158. runtime_unlock(&proflock);
  159. }
  160. // Called by malloc to record a profiled block.
  161. void
  162. runtime_MProf_Malloc(void *p, uintptr size)
  163. {
  164. Location stk[32];
  165. Bucket *b;
  166. int32 nstk;
  167. nstk = runtime_callers(1, stk, nelem(stk), false);
  168. runtime_lock(&proflock);
  169. b = stkbucket(MProf, size, stk, nstk, true);
  170. b->recent_allocs++;
  171. b->recent_alloc_bytes += size;
  172. runtime_unlock(&proflock);
  173. // Setprofilebucket locks a bunch of other mutexes, so we call it outside of proflock.
  174. // This reduces potential contention and chances of deadlocks.
  175. // Since the object must be alive during call to MProf_Malloc,
  176. // it's fine to do this non-atomically.
  177. runtime_setprofilebucket(p, b);
  178. }
  179. // Called when freeing a profiled block.
  180. void
  181. runtime_MProf_Free(Bucket *b, uintptr size, bool freed)
  182. {
  183. runtime_lock(&proflock);
  184. if(freed) {
  185. b->recent_frees++;
  186. b->recent_free_bytes += size;
  187. } else {
  188. b->prev_frees++;
  189. b->prev_free_bytes += size;
  190. }
  191. runtime_unlock(&proflock);
  192. }
  193. int64 runtime_blockprofilerate; // in CPU ticks
  194. void runtime_SetBlockProfileRate(intgo) __asm__ (GOSYM_PREFIX "runtime.SetBlockProfileRate");
  195. void
  196. runtime_SetBlockProfileRate(intgo rate)
  197. {
  198. int64 r;
  199. if(rate <= 0)
  200. r = 0; // disable profiling
  201. else {
  202. // convert ns to cycles, use float64 to prevent overflow during multiplication
  203. r = (float64)rate*runtime_tickspersecond()/(1000*1000*1000);
  204. if(r == 0)
  205. r = 1;
  206. }
  207. runtime_atomicstore64((uint64*)&runtime_blockprofilerate, r);
  208. }
  209. void
  210. runtime_blockevent(int64 cycles, int32 skip)
  211. {
  212. int32 nstk;
  213. int64 rate;
  214. Location stk[32];
  215. Bucket *b;
  216. if(cycles <= 0)
  217. return;
  218. rate = runtime_atomicload64((uint64*)&runtime_blockprofilerate);
  219. if(rate <= 0 || (rate > cycles && runtime_fastrand1()%rate > cycles))
  220. return;
  221. nstk = runtime_callers(skip, stk, nelem(stk), false);
  222. runtime_lock(&proflock);
  223. b = stkbucket(BProf, 0, stk, nstk, true);
  224. b->count++;
  225. b->cycles += cycles;
  226. runtime_unlock(&proflock);
  227. }
  228. // Go interface to profile data. (Declared in debug.go)
  229. // Must match MemProfileRecord in debug.go.
  230. typedef struct Record Record;
  231. struct Record {
  232. int64 alloc_bytes, free_bytes;
  233. int64 alloc_objects, free_objects;
  234. uintptr stk[32];
  235. };
  236. // Write b's data to r.
  237. static void
  238. record(Record *r, Bucket *b)
  239. {
  240. uint32 i;
  241. r->alloc_bytes = b->alloc_bytes;
  242. r->free_bytes = b->free_bytes;
  243. r->alloc_objects = b->allocs;
  244. r->free_objects = b->frees;
  245. for(i=0; i<b->nstk && i<nelem(r->stk); i++)
  246. r->stk[i] = b->stk[i].pc;
  247. for(; i<nelem(r->stk); i++)
  248. r->stk[i] = 0;
  249. }
  250. func MemProfile(p Slice, include_inuse_zero bool) (n int, ok bool) {
  251. Bucket *b;
  252. Record *r;
  253. bool clear;
  254. runtime_lock(&proflock);
  255. n = 0;
  256. clear = true;
  257. for(b=mbuckets; b; b=b->allnext) {
  258. if(include_inuse_zero || b->alloc_bytes != b->free_bytes)
  259. n++;
  260. if(b->allocs != 0 || b->frees != 0)
  261. clear = false;
  262. }
  263. if(clear) {
  264. // Absolutely no data, suggesting that a garbage collection
  265. // has not yet happened. In order to allow profiling when
  266. // garbage collection is disabled from the beginning of execution,
  267. // accumulate stats as if a GC just happened, and recount buckets.
  268. MProf_GC();
  269. MProf_GC();
  270. n = 0;
  271. for(b=mbuckets; b; b=b->allnext)
  272. if(include_inuse_zero || b->alloc_bytes != b->free_bytes)
  273. n++;
  274. }
  275. ok = false;
  276. if(n <= p.__count) {
  277. ok = true;
  278. r = (Record*)p.__values;
  279. for(b=mbuckets; b; b=b->allnext)
  280. if(include_inuse_zero || b->alloc_bytes != b->free_bytes)
  281. record(r++, b);
  282. }
  283. runtime_unlock(&proflock);
  284. }
  285. void
  286. runtime_MProf_Mark(struct Workbuf **wbufp, void (*enqueue1)(struct Workbuf**, Obj))
  287. {
  288. // buckhash is not allocated via mallocgc.
  289. enqueue1(wbufp, (Obj){(byte*)&mbuckets, sizeof mbuckets, 0});
  290. enqueue1(wbufp, (Obj){(byte*)&bbuckets, sizeof bbuckets, 0});
  291. }
  292. void
  293. runtime_iterate_memprof(void (*callback)(Bucket*, uintptr, Location*, uintptr, uintptr, uintptr))
  294. {
  295. Bucket *b;
  296. runtime_lock(&proflock);
  297. for(b=mbuckets; b; b=b->allnext) {
  298. callback(b, b->nstk, b->stk, b->size, b->allocs, b->frees);
  299. }
  300. runtime_unlock(&proflock);
  301. }
  302. // Must match BlockProfileRecord in debug.go.
  303. typedef struct BRecord BRecord;
  304. struct BRecord {
  305. int64 count;
  306. int64 cycles;
  307. uintptr stk[32];
  308. };
  309. func BlockProfile(p Slice) (n int, ok bool) {
  310. Bucket *b;
  311. BRecord *r;
  312. int32 i;
  313. runtime_lock(&proflock);
  314. n = 0;
  315. for(b=bbuckets; b; b=b->allnext)
  316. n++;
  317. ok = false;
  318. if(n <= p.__count) {
  319. ok = true;
  320. r = (BRecord*)p.__values;
  321. for(b=bbuckets; b; b=b->allnext, r++) {
  322. r->count = b->count;
  323. r->cycles = b->cycles;
  324. for(i=0; (uintptr)i<b->nstk && (uintptr)i<nelem(r->stk); i++)
  325. r->stk[i] = b->stk[i].pc;
  326. for(; (uintptr)i<nelem(r->stk); i++)
  327. r->stk[i] = 0;
  328. }
  329. }
  330. runtime_unlock(&proflock);
  331. }
  332. // Must match StackRecord in debug.go.
  333. typedef struct TRecord TRecord;
  334. struct TRecord {
  335. uintptr stk[32];
  336. };
  337. func ThreadCreateProfile(p Slice) (n int, ok bool) {
  338. TRecord *r;
  339. M *first, *mp;
  340. int32 i;
  341. first = runtime_atomicloadp(&runtime_allm);
  342. n = 0;
  343. for(mp=first; mp; mp=mp->alllink)
  344. n++;
  345. ok = false;
  346. if(n <= p.__count) {
  347. ok = true;
  348. r = (TRecord*)p.__values;
  349. for(mp=first; mp; mp=mp->alllink) {
  350. for(i = 0; (uintptr)i < nelem(r->stk); i++) {
  351. r->stk[i] = mp->createstack[i].pc;
  352. }
  353. r++;
  354. }
  355. }
  356. }
  357. func Stack(b Slice, all bool) (n int) {
  358. byte *pc, *sp;
  359. bool enablegc;
  360. sp = runtime_getcallersp(&b);
  361. pc = (byte*)(uintptr)runtime_getcallerpc(&b);
  362. if(all) {
  363. runtime_semacquire(&runtime_worldsema, false);
  364. runtime_m()->gcing = 1;
  365. runtime_stoptheworld();
  366. enablegc = mstats.enablegc;
  367. mstats.enablegc = false;
  368. }
  369. if(b.__count == 0)
  370. n = 0;
  371. else{
  372. G* g = runtime_g();
  373. g->writebuf = (byte*)b.__values;
  374. g->writenbuf = b.__count;
  375. USED(pc);
  376. USED(sp);
  377. runtime_goroutineheader(g);
  378. runtime_traceback();
  379. runtime_printcreatedby(g);
  380. if(all)
  381. runtime_tracebackothers(g);
  382. n = b.__count - g->writenbuf;
  383. g->writebuf = nil;
  384. g->writenbuf = 0;
  385. }
  386. if(all) {
  387. runtime_m()->gcing = 0;
  388. mstats.enablegc = enablegc;
  389. runtime_semrelease(&runtime_worldsema);
  390. runtime_starttheworld();
  391. }
  392. }
  393. static void
  394. saveg(G *gp, TRecord *r)
  395. {
  396. int32 n, i;
  397. Location locstk[nelem(r->stk)];
  398. if(gp == runtime_g()) {
  399. n = runtime_callers(0, locstk, nelem(r->stk), false);
  400. for(i = 0; i < n; i++)
  401. r->stk[i] = locstk[i].pc;
  402. }
  403. else {
  404. // FIXME: Not implemented.
  405. n = 0;
  406. }
  407. if((size_t)n < nelem(r->stk))
  408. r->stk[n] = 0;
  409. }
  410. func GoroutineProfile(b Slice) (n int, ok bool) {
  411. uintptr i;
  412. TRecord *r;
  413. G *gp;
  414. ok = false;
  415. n = runtime_gcount();
  416. if(n <= b.__count) {
  417. runtime_semacquire(&runtime_worldsema, false);
  418. runtime_m()->gcing = 1;
  419. runtime_stoptheworld();
  420. n = runtime_gcount();
  421. if(n <= b.__count) {
  422. G* g = runtime_g();
  423. ok = true;
  424. r = (TRecord*)b.__values;
  425. saveg(g, r++);
  426. for(i = 0; i < runtime_allglen; i++) {
  427. gp = runtime_allg[i];
  428. if(gp == g || gp->status == Gdead)
  429. continue;
  430. saveg(gp, r++);
  431. }
  432. }
  433. runtime_m()->gcing = 0;
  434. runtime_semrelease(&runtime_worldsema);
  435. runtime_starttheworld();
  436. }
  437. }
  438. // Tracing of alloc/free/gc.
  439. static Lock tracelock;
  440. static const char*
  441. typeinfoname(int32 typeinfo)
  442. {
  443. if(typeinfo == TypeInfo_SingleObject)
  444. return "single object";
  445. else if(typeinfo == TypeInfo_Array)
  446. return "array";
  447. else if(typeinfo == TypeInfo_Chan)
  448. return "channel";
  449. runtime_throw("typinfoname: unknown type info");
  450. return nil;
  451. }
  452. void
  453. runtime_tracealloc(void *p, uintptr size, uintptr typ)
  454. {
  455. const char *name;
  456. Type *type;
  457. runtime_lock(&tracelock);
  458. runtime_m()->traceback = 2;
  459. type = (Type*)(typ & ~3);
  460. name = typeinfoname(typ & 3);
  461. if(type == nil)
  462. runtime_printf("tracealloc(%p, %p, %s)\n", p, size, name);
  463. else
  464. runtime_printf("tracealloc(%p, %p, %s of %S)\n", p, size, name, *type->__reflection);
  465. if(runtime_m()->curg == nil || runtime_g() == runtime_m()->curg) {
  466. runtime_goroutineheader(runtime_g());
  467. runtime_traceback();
  468. } else {
  469. runtime_goroutineheader(runtime_m()->curg);
  470. runtime_traceback();
  471. }
  472. runtime_printf("\n");
  473. runtime_m()->traceback = 0;
  474. runtime_unlock(&tracelock);
  475. }
  476. void
  477. runtime_tracefree(void *p, uintptr size)
  478. {
  479. runtime_lock(&tracelock);
  480. runtime_m()->traceback = 2;
  481. runtime_printf("tracefree(%p, %p)\n", p, size);
  482. runtime_goroutineheader(runtime_g());
  483. runtime_traceback();
  484. runtime_printf("\n");
  485. runtime_m()->traceback = 0;
  486. runtime_unlock(&tracelock);
  487. }
  488. void
  489. runtime_tracegc(void)
  490. {
  491. runtime_lock(&tracelock);
  492. runtime_m()->traceback = 2;
  493. runtime_printf("tracegc()\n");
  494. // running on m->g0 stack; show all non-g0 goroutines
  495. runtime_tracebackothers(runtime_g());
  496. runtime_printf("end tracegc\n");
  497. runtime_printf("\n");
  498. runtime_m()->traceback = 0;
  499. runtime_unlock(&tracelock);
  500. }