Enable two-step allocator on FreeBSD
[ghc.git] / rts / ProfHeap.c
1 /* ----------------------------------------------------------------------------
2 *
3 * (c) The GHC Team, 1998-2003
4 *
5 * Support for heap profiling
6 *
7 * --------------------------------------------------------------------------*/
8
9 #include "PosixSource.h"
10 #include "Rts.h"
11
12 #include "Capability.h"
13 #include "RtsFlags.h"
14 #include "RtsUtils.h"
15 #include "Profiling.h"
16 #include "ProfHeap.h"
17 #include "Stats.h"
18 #include "Hash.h"
19 #include "RetainerProfile.h"
20 #include "LdvProfile.h"
21 #include "Arena.h"
22 #include "Printer.h"
23 #include "Trace.h"
24 #include "sm/GCThread.h"
25
26 #include <fs_rts.h>
27 #include <string.h>
28
29 /* -----------------------------------------------------------------------------
30 * era stores the current time period. It is the same as the
31 * number of censuses that have been performed.
32 *
33 * RESTRICTION:
34 * era must be no longer than LDV_SHIFT (15 or 30) bits.
35 * Invariants:
36 * era is initialized to 1 in initHeapProfiling().
37 *
38 * max_era is initialized to 2^LDV_SHIFT in initHeapProfiling().
39 * When era reaches max_era, the profiling stops because a closure can
40 * store only up to (max_era - 1) as its creation or last use time.
41 * -------------------------------------------------------------------------- */
42 unsigned int era;
43 static uint32_t max_era;
44
45 /* -----------------------------------------------------------------------------
46 * Counters
47 *
48 * For most heap profiles each closure identity gets a simple count
49 * of live words in the heap at each census. However, if we're
50 * selecting by biography, then we have to keep the various
51 * lag/drag/void counters for each identity.
52 * -------------------------------------------------------------------------- */
53 typedef struct _counter {
54 const void *identity;
55 union {
56 ssize_t resid;
57 struct {
58 // Total sizes of:
59 ssize_t prim; // 'inherently used' closures
60 ssize_t not_used; // 'never used' closures
61 ssize_t used; // 'used at least once' closures
62 ssize_t void_total; // 'destroyed without being used' closures
63 ssize_t drag_total; // 'used at least once and waiting to die'
64 } ldv;
65 } c;
66 struct _counter *next;
67 } counter;
68
69 STATIC_INLINE void
70 initLDVCtr( counter *ctr )
71 {
72 ctr->c.ldv.prim = 0;
73 ctr->c.ldv.not_used = 0;
74 ctr->c.ldv.used = 0;
75 ctr->c.ldv.void_total = 0;
76 ctr->c.ldv.drag_total = 0;
77 }
78
79 typedef struct {
80 double time; // the time in MUT time when the census is made
81 HashTable * hash;
82 counter * ctrs;
83 Arena * arena;
84
85 // for LDV profiling, when just displaying by LDV
86 ssize_t prim;
87 ssize_t not_used;
88 ssize_t used;
89 ssize_t void_total;
90 ssize_t drag_total;
91 } Census;
92
93 static Census *censuses = NULL;
94 static uint32_t n_censuses = 0;
95
96 #if defined(PROFILING)
97 static void aggregateCensusInfo( void );
98 #endif
99
100 static void dumpCensus( Census *census );
101
102 static bool closureSatisfiesConstraints( const StgClosure* p );
103
104 /* ----------------------------------------------------------------------------
105 * Find the "closure identity", which is a unique pointer representing
106 * the band to which this closure's heap space is attributed in the
107 * heap profile.
108 * ------------------------------------------------------------------------- */
109 static const void *
110 closureIdentity( const StgClosure *p )
111 {
112 switch (RtsFlags.ProfFlags.doHeapProfile) {
113
114 #if defined(PROFILING)
115 case HEAP_BY_CCS:
116 return p->header.prof.ccs;
117 case HEAP_BY_MOD:
118 return p->header.prof.ccs->cc->module;
119 case HEAP_BY_DESCR:
120 return GET_PROF_DESC(get_itbl(p));
121 case HEAP_BY_TYPE:
122 return GET_PROF_TYPE(get_itbl(p));
123 case HEAP_BY_RETAINER:
124 // AFAIK, the only closures in the heap which might not have a
125 // valid retainer set are DEAD_WEAK closures.
126 if (isRetainerSetFieldValid(p))
127 return retainerSetOf(p);
128 else
129 return NULL;
130 #endif
131
132 case HEAP_BY_CLOSURE_TYPE:
133 {
134 const StgInfoTable *info;
135 info = get_itbl(p);
136 switch (info->type) {
137 case CONSTR:
138 case CONSTR_1_0:
139 case CONSTR_0_1:
140 case CONSTR_2_0:
141 case CONSTR_1_1:
142 case CONSTR_0_2:
143 case CONSTR_NOCAF:
144 return GET_CON_DESC(itbl_to_con_itbl(info));
145 default:
146 return closure_type_names[info->type];
147 }
148 }
149
150 default:
151 barf("closureIdentity");
152 }
153 }
154
155 /* --------------------------------------------------------------------------
156 * Profiling type predicates
157 * ----------------------------------------------------------------------- */
158 #if defined(PROFILING)
159 STATIC_INLINE bool
160 doingLDVProfiling( void )
161 {
162 return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV
163 || RtsFlags.ProfFlags.bioSelector != NULL);
164 }
165
166 bool
167 doingRetainerProfiling( void )
168 {
169 return (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER
170 || RtsFlags.ProfFlags.retainerSelector != NULL);
171 }
172 #endif /* PROFILING */
173
174 // Processes a closure 'c' being destroyed whose size is 'size'.
175 // Make sure that LDV_recordDead() is not invoked on 'inherently used' closures
176 // such as TSO; they should not be involved in computing dragNew or voidNew.
177 //
178 // Even though era is checked in both LdvCensusForDead() and
179 // LdvCensusKillAll(), we still need to make sure that era is > 0 because
180 // LDV_recordDead() may be called from elsewhere in the runtime system. E.g.,
181 // when a thunk is replaced by an indirection object.
182
183 #if defined(PROFILING)
184 void
185 LDV_recordDead( const StgClosure *c, uint32_t size )
186 {
187 const void *id;
188 uint32_t t;
189 counter *ctr;
190
191 if (era > 0 && closureSatisfiesConstraints(c)) {
192 size -= sizeofW(StgProfHeader);
193 ASSERT(LDVW(c) != 0);
194 if ((LDVW((c)) & LDV_STATE_MASK) == LDV_STATE_CREATE) {
195 t = (LDVW((c)) & LDV_CREATE_MASK) >> LDV_SHIFT;
196 if (t < era) {
197 if (RtsFlags.ProfFlags.bioSelector == NULL) {
198 censuses[t].void_total += size;
199 censuses[era].void_total -= size;
200 ASSERT(censuses[t].void_total < censuses[t].not_used);
201 } else {
202 id = closureIdentity(c);
203 ctr = lookupHashTable(censuses[t].hash, (StgWord)id);
204 ASSERT( ctr != NULL );
205 ctr->c.ldv.void_total += size;
206 ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
207 if (ctr == NULL) {
208 ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
209 initLDVCtr(ctr);
210 insertHashTable(censuses[era].hash, (StgWord)id, ctr);
211 ctr->identity = id;
212 ctr->next = censuses[era].ctrs;
213 censuses[era].ctrs = ctr;
214 }
215 ctr->c.ldv.void_total -= size;
216 }
217 }
218 } else {
219 t = LDVW((c)) & LDV_LAST_MASK;
220 if (t + 1 < era) {
221 if (RtsFlags.ProfFlags.bioSelector == NULL) {
222 censuses[t+1].drag_total += size;
223 censuses[era].drag_total -= size;
224 } else {
225 const void *id;
226 id = closureIdentity(c);
227 ctr = lookupHashTable(censuses[t+1].hash, (StgWord)id);
228 ASSERT( ctr != NULL );
229 ctr->c.ldv.drag_total += size;
230 ctr = lookupHashTable(censuses[era].hash, (StgWord)id);
231 if (ctr == NULL) {
232 ctr = arenaAlloc(censuses[era].arena, sizeof(counter));
233 initLDVCtr(ctr);
234 insertHashTable(censuses[era].hash, (StgWord)id, ctr);
235 ctr->identity = id;
236 ctr->next = censuses[era].ctrs;
237 censuses[era].ctrs = ctr;
238 }
239 ctr->c.ldv.drag_total -= size;
240 }
241 }
242 }
243 }
244 }
245 #endif
246
247 /* --------------------------------------------------------------------------
248 * Initialize censuses[era];
249 * ----------------------------------------------------------------------- */
250
251 STATIC_INLINE void
252 initEra(Census *census)
253 {
254 census->hash = allocHashTable();
255 census->ctrs = NULL;
256 census->arena = newArena();
257
258 census->not_used = 0;
259 census->used = 0;
260 census->prim = 0;
261 census->void_total = 0;
262 census->drag_total = 0;
263 }
264
265 STATIC_INLINE void
266 freeEra(Census *census)
267 {
268 arenaFree(census->arena);
269 freeHashTable(census->hash, NULL);
270 }
271
272 /* --------------------------------------------------------------------------
273 * Increases era by 1 and initialize census[era].
274 * Reallocates gi[] and increases its size if needed.
275 * ----------------------------------------------------------------------- */
276
277 static void
278 nextEra( void )
279 {
280 #if defined(PROFILING)
281 if (doingLDVProfiling()) {
282 era++;
283
284 if (era == max_era) {
285 errorBelch("Maximum number of censuses reached.");
286 if (rtsConfig.rts_opts_suggestions == true) {
287 if (rtsConfig.rts_opts_enabled == RtsOptsAll) {
288 errorBelch("Use `+RTS -i' to reduce censuses.");
289 } else {
290 errorBelch("Relink with -rtsopts and "
291 "use `+RTS -i' to reduce censuses.");
292 }
293 }
294 stg_exit(EXIT_FAILURE);
295 }
296
297 if (era == n_censuses) {
298 n_censuses *= 2;
299 censuses = stgReallocBytes(censuses, sizeof(Census) * n_censuses,
300 "nextEra");
301 }
302 }
303 #endif /* PROFILING */
304
305 initEra( &censuses[era] );
306 }
307
308 /* ----------------------------------------------------------------------------
309 * Heap profiling by info table
310 * ------------------------------------------------------------------------- */
311
312 #if !defined(PROFILING)
313 FILE *hp_file;
314 static char *hp_filename;
315
316 void freeProfiling (void)
317 {
318 }
319
320 void initProfiling (void)
321 {
322 char *prog;
323
324 prog = stgMallocBytes(strlen(prog_name) + 1, "initProfiling2");
325 strcpy(prog, prog_name);
326 #if defined(mingw32_HOST_OS)
327 // on Windows, drop the .exe suffix if there is one
328 {
329 char *suff;
330 suff = strrchr(prog,'.');
331 if (suff != NULL && !strcmp(suff,".exe")) {
332 *suff = '\0';
333 }
334 }
335 #endif
336
337 if (RtsFlags.ProfFlags.doHeapProfile) {
338 /* Initialise the log file name */
339 hp_filename = stgMallocBytes(strlen(prog) + 6, "hpFileName");
340 sprintf(hp_filename, "%s.hp", prog);
341
342 /* open the log file */
343 if ((hp_file = __rts_fopen(hp_filename, "w")) == NULL) {
344 debugBelch("Can't open profiling report file %s\n",
345 hp_filename);
346 RtsFlags.ProfFlags.doHeapProfile = 0;
347 stgFree(prog);
348 return;
349 }
350 }
351
352 stgFree(prog);
353
354 initHeapProfiling();
355 }
356
357 void endProfiling( void )
358 {
359 endHeapProfiling();
360 }
361 #endif /* !PROFILING */
362
363 static void
364 printSample(bool beginSample, StgDouble sampleValue)
365 {
366 fprintf(hp_file, "%s %f\n",
367 (beginSample ? "BEGIN_SAMPLE" : "END_SAMPLE"),
368 sampleValue);
369 if (!beginSample) {
370 fflush(hp_file);
371 }
372 }
373
374 static void
375 dumpCostCentresToEventLog(void)
376 {
377 #if defined(PROFILING)
378 CostCentre *cc, *next;
379 for (cc = CC_LIST; cc != NULL; cc = next) {
380 next = cc->link;
381 traceHeapProfCostCentre(cc->ccID, cc->label, cc->module,
382 cc->srcloc, cc->is_caf);
383 }
384 #endif
385 }
386
387 /* --------------------------------------------------------------------------
388 * Initialize the heap profilier
389 * ----------------------------------------------------------------------- */
390 uint32_t
391 initHeapProfiling(void)
392 {
393 if (! RtsFlags.ProfFlags.doHeapProfile) {
394 return 0;
395 }
396
397 #if defined(PROFILING)
398 if (doingLDVProfiling() && doingRetainerProfiling()) {
399 errorBelch("cannot mix -hb and -hr");
400 stg_exit(EXIT_FAILURE);
401 }
402 #if defined(THREADED_RTS)
403 // See Trac #12019.
404 if (doingLDVProfiling() && RtsFlags.ParFlags.nCapabilities > 1) {
405 errorBelch("-hb cannot be used with multiple capabilities");
406 stg_exit(EXIT_FAILURE);
407 }
408 #endif
409 #endif
410
411 // we only count eras if we're doing LDV profiling. Otherwise era
412 // is fixed at zero.
413 #if defined(PROFILING)
414 if (doingLDVProfiling()) {
415 era = 1;
416 } else
417 #endif
418 {
419 era = 0;
420 }
421
422 // max_era = 2^LDV_SHIFT
423 max_era = 1 << LDV_SHIFT;
424
425 n_censuses = 32;
426 censuses = stgMallocBytes(sizeof(Census) * n_censuses, "initHeapProfiling");
427
428 initEra( &censuses[era] );
429
430 /* initProfilingLogFile(); */
431 fprintf(hp_file, "JOB \"%s", prog_name);
432
433 #if defined(PROFILING)
434 {
435 int count;
436 for(count = 1; count < prog_argc; count++)
437 fprintf(hp_file, " %s", prog_argv[count]);
438 fprintf(hp_file, " +RTS");
439 for(count = 0; count < rts_argc; count++)
440 fprintf(hp_file, " %s", rts_argv[count]);
441 }
442 #endif /* PROFILING */
443
444 fprintf(hp_file, "\"\n" );
445
446 fprintf(hp_file, "DATE \"%s\"\n", time_str());
447
448 fprintf(hp_file, "SAMPLE_UNIT \"seconds\"\n");
449 fprintf(hp_file, "VALUE_UNIT \"bytes\"\n");
450
451 printSample(true, 0);
452 printSample(false, 0);
453
454 #if defined(PROFILING)
455 if (doingRetainerProfiling()) {
456 initRetainerProfiling();
457 }
458 #endif
459
460 traceHeapProfBegin(0);
461 dumpCostCentresToEventLog();
462
463 return 0;
464 }
465
466 void
467 endHeapProfiling(void)
468 {
469 StgDouble seconds;
470
471 if (! RtsFlags.ProfFlags.doHeapProfile) {
472 return;
473 }
474
475 #if defined(PROFILING)
476 if (doingRetainerProfiling()) {
477 endRetainerProfiling();
478 }
479 #endif
480
481 #if defined(PROFILING)
482 if (doingLDVProfiling()) {
483 uint32_t t;
484 LdvCensusKillAll();
485 aggregateCensusInfo();
486 for (t = 1; t < era; t++) {
487 dumpCensus( &censuses[t] );
488 }
489 }
490 #endif
491
492 #if defined(PROFILING)
493 if (doingLDVProfiling()) {
494 uint32_t t;
495 if (RtsFlags.ProfFlags.bioSelector != NULL) {
496 for (t = 1; t <= era; t++) {
497 freeEra( &censuses[t] );
498 }
499 } else {
500 freeEra( &censuses[era] );
501 }
502 } else {
503 freeEra( &censuses[0] );
504 }
505 #else
506 freeEra( &censuses[0] );
507 #endif
508
509 stgFree(censuses);
510
511 seconds = mut_user_time();
512 printSample(true, seconds);
513 printSample(false, seconds);
514 fclose(hp_file);
515 }
516
517
518
519 #if defined(PROFILING)
520 static size_t
521 buf_append(char *p, const char *q, char *end)
522 {
523 int m;
524
525 for (m = 0; p < end; p++, q++, m++) {
526 *p = *q;
527 if (*q == '\0') { break; }
528 }
529 return m;
530 }
531
532 static void
533 fprint_ccs(FILE *fp, CostCentreStack *ccs, uint32_t max_length)
534 {
535 char buf[max_length+1], *p, *buf_end;
536
537 // MAIN on its own gets printed as "MAIN", otherwise we ignore MAIN.
538 if (ccs == CCS_MAIN) {
539 fprintf(fp, "MAIN");
540 return;
541 }
542
543 fprintf(fp, "(%" FMT_Int ")", ccs->ccsID);
544
545 p = buf;
546 buf_end = buf + max_length + 1;
547
548 // keep printing components of the stack until we run out of space
549 // in the buffer. If we run out of space, end with "...".
550 for (; ccs != NULL && ccs != CCS_MAIN; ccs = ccs->prevStack) {
551
552 // CAF cost centres print as M.CAF, but we leave the module
553 // name out of all the others to save space.
554 if (!strcmp(ccs->cc->label,"CAF")) {
555 p += buf_append(p, ccs->cc->module, buf_end);
556 p += buf_append(p, ".CAF", buf_end);
557 } else {
558 p += buf_append(p, ccs->cc->label, buf_end);
559 if (ccs->prevStack != NULL && ccs->prevStack != CCS_MAIN) {
560 p += buf_append(p, "/", buf_end);
561 }
562 }
563
564 if (p >= buf_end) {
565 sprintf(buf+max_length-4, "...");
566 break;
567 }
568 }
569 fprintf(fp, "%s", buf);
570 }
571
572 bool
573 strMatchesSelector( const char* str, const char* sel )
574 {
575 const char* p;
576 // debugBelch("str_matches_selector %s %s\n", str, sel);
577 while (1) {
578 // Compare str against wherever we've got to in sel.
579 p = str;
580 while (*p != '\0' && *sel != ',' && *sel != '\0' && *p == *sel) {
581 p++; sel++;
582 }
583 // Match if all of str used and have reached the end of a sel fragment.
584 if (*p == '\0' && (*sel == ',' || *sel == '\0'))
585 return true;
586
587 // No match. Advance sel to the start of the next elem.
588 while (*sel != ',' && *sel != '\0') sel++;
589 if (*sel == ',') sel++;
590
591 /* Run out of sel ?? */
592 if (*sel == '\0') return false;
593 }
594 }
595
596 #endif /* PROFILING */
597
598 /* -----------------------------------------------------------------------------
599 * Figure out whether a closure should be counted in this census, by
600 * testing against all the specified constraints.
601 * -------------------------------------------------------------------------- */
602 static bool
603 closureSatisfiesConstraints( const StgClosure* p )
604 {
605 #if !defined(PROFILING)
606 (void)p; /* keep gcc -Wall happy */
607 return true;
608 #else
609 bool b;
610
611 // The CCS has a selected field to indicate whether this closure is
612 // deselected by not being mentioned in the module, CC, or CCS
613 // selectors.
614 if (!p->header.prof.ccs->selected) {
615 return false;
616 }
617
618 if (RtsFlags.ProfFlags.descrSelector) {
619 b = strMatchesSelector( (GET_PROF_DESC(get_itbl((StgClosure *)p))),
620 RtsFlags.ProfFlags.descrSelector );
621 if (!b) return false;
622 }
623 if (RtsFlags.ProfFlags.typeSelector) {
624 b = strMatchesSelector( (GET_PROF_TYPE(get_itbl((StgClosure *)p))),
625 RtsFlags.ProfFlags.typeSelector );
626 if (!b) return false;
627 }
628 if (RtsFlags.ProfFlags.retainerSelector) {
629 RetainerSet *rs;
630 uint32_t i;
631 // We must check that the retainer set is valid here. One
632 // reason it might not be valid is if this closure is a
633 // a newly deceased weak pointer (i.e. a DEAD_WEAK), since
634 // these aren't reached by the retainer profiler's traversal.
635 if (isRetainerSetFieldValid((StgClosure *)p)) {
636 rs = retainerSetOf((StgClosure *)p);
637 if (rs != NULL) {
638 for (i = 0; i < rs->num; i++) {
639 b = strMatchesSelector( rs->element[i]->cc->label,
640 RtsFlags.ProfFlags.retainerSelector );
641 if (b) return true;
642 }
643 }
644 }
645 return false;
646 }
647 return true;
648 #endif /* PROFILING */
649 }
650
651 /* -----------------------------------------------------------------------------
652 * Aggregate the heap census info for biographical profiling
653 * -------------------------------------------------------------------------- */
654 #if defined(PROFILING)
655 static void
656 aggregateCensusInfo( void )
657 {
658 HashTable *acc;
659 uint32_t t;
660 counter *c, *d, *ctrs;
661 Arena *arena;
662
663 if (!doingLDVProfiling()) return;
664
665 // Aggregate the LDV counters when displaying by biography.
666 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
667 long void_total, drag_total;
668
669 // Now we compute void_total and drag_total for each census
670 // After the program has finished, the void_total field of
671 // each census contains the count of words that were *created*
672 // in this era and were eventually void. Conversely, if a
673 // void closure was destroyed in this era, it will be
674 // represented by a negative count of words in void_total.
675 //
676 // To get the count of live words that are void at each
677 // census, just propagate the void_total count forwards:
678
679 void_total = 0;
680 drag_total = 0;
681 for (t = 1; t < era; t++) { // note: start at 1, not 0
682 void_total += censuses[t].void_total;
683 drag_total += censuses[t].drag_total;
684 censuses[t].void_total = void_total;
685 censuses[t].drag_total = drag_total;
686
687 ASSERT( censuses[t].void_total <= censuses[t].not_used );
688 // should be true because: void_total is the count of
689 // live words that are void at this census, which *must*
690 // be less than the number of live words that have not
691 // been used yet.
692
693 ASSERT( censuses[t].drag_total <= censuses[t].used );
694 // similar reasoning as above.
695 }
696
697 return;
698 }
699
700 // otherwise... we're doing a heap profile that is restricted to
701 // some combination of lag, drag, void or use. We've kept all the
702 // census info for all censuses so far, but we still need to
703 // aggregate the counters forwards.
704
705 arena = newArena();
706 acc = allocHashTable();
707 ctrs = NULL;
708
709 for (t = 1; t < era; t++) {
710
711 // first look through all the counters we're aggregating
712 for (c = ctrs; c != NULL; c = c->next) {
713 // if one of the totals is non-zero, then this closure
714 // type must be present in the heap at this census time...
715 d = lookupHashTable(censuses[t].hash, (StgWord)c->identity);
716
717 if (d == NULL) {
718 // if this closure identity isn't present in the
719 // census for this time period, then our running
720 // totals *must* be zero.
721 ASSERT(c->c.ldv.void_total == 0 && c->c.ldv.drag_total == 0);
722
723 // debugCCS(c->identity);
724 // debugBelch(" census=%d void_total=%d drag_total=%d\n",
725 // t, c->c.ldv.void_total, c->c.ldv.drag_total);
726 } else {
727 d->c.ldv.void_total += c->c.ldv.void_total;
728 d->c.ldv.drag_total += c->c.ldv.drag_total;
729 c->c.ldv.void_total = d->c.ldv.void_total;
730 c->c.ldv.drag_total = d->c.ldv.drag_total;
731
732 ASSERT( c->c.ldv.void_total >= 0 );
733 ASSERT( c->c.ldv.drag_total >= 0 );
734 }
735 }
736
737 // now look through the counters in this census to find new ones
738 for (c = censuses[t].ctrs; c != NULL; c = c->next) {
739 d = lookupHashTable(acc, (StgWord)c->identity);
740 if (d == NULL) {
741 d = arenaAlloc( arena, sizeof(counter) );
742 initLDVCtr(d);
743 insertHashTable( acc, (StgWord)c->identity, d );
744 d->identity = c->identity;
745 d->next = ctrs;
746 ctrs = d;
747 d->c.ldv.void_total = c->c.ldv.void_total;
748 d->c.ldv.drag_total = c->c.ldv.drag_total;
749 }
750 ASSERT( c->c.ldv.void_total >= 0 );
751 ASSERT( c->c.ldv.drag_total >= 0 );
752 }
753 }
754
755 freeHashTable(acc, NULL);
756 arenaFree(arena);
757 }
758 #endif
759
760 /* -----------------------------------------------------------------------------
761 * Print out the results of a heap census.
762 * -------------------------------------------------------------------------- */
763 static void
764 dumpCensus( Census *census )
765 {
766 counter *ctr;
767 ssize_t count;
768
769 printSample(true, census->time);
770 traceHeapProfSampleBegin(era);
771
772 #if defined(PROFILING)
773 /* change typecast to uint64_t to remove
774 * print formatting warning. See #12636 */
775 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
776 fprintf(hp_file, "VOID\t%" FMT_Word64 "\n",
777 (uint64_t)(census->void_total *
778 sizeof(W_)));
779 fprintf(hp_file, "LAG\t%" FMT_Word64 "\n",
780 (uint64_t)((census->not_used - census->void_total) *
781 sizeof(W_)));
782 fprintf(hp_file, "USE\t%" FMT_Word64 "\n",
783 (uint64_t)((census->used - census->drag_total) *
784 sizeof(W_)));
785 fprintf(hp_file, "INHERENT_USE\t%" FMT_Word64 "\n",
786 (uint64_t)(census->prim * sizeof(W_)));
787 fprintf(hp_file, "DRAG\t%" FMT_Word64 "\n",
788 (uint64_t)(census->drag_total * sizeof(W_)));
789 printSample(false, census->time);
790 return;
791 }
792 #endif
793
794 for (ctr = census->ctrs; ctr != NULL; ctr = ctr->next) {
795
796 #if defined(PROFILING)
797 if (RtsFlags.ProfFlags.bioSelector != NULL) {
798 count = 0;
799 if (strMatchesSelector("lag", RtsFlags.ProfFlags.bioSelector))
800 count += ctr->c.ldv.not_used - ctr->c.ldv.void_total;
801 if (strMatchesSelector("drag", RtsFlags.ProfFlags.bioSelector))
802 count += ctr->c.ldv.drag_total;
803 if (strMatchesSelector("void", RtsFlags.ProfFlags.bioSelector))
804 count += ctr->c.ldv.void_total;
805 if (strMatchesSelector("use", RtsFlags.ProfFlags.bioSelector))
806 count += ctr->c.ldv.used - ctr->c.ldv.drag_total;
807 } else
808 #endif
809 {
810 count = ctr->c.resid;
811 }
812
813 ASSERT( count >= 0 );
814
815 if (count == 0) continue;
816
817 switch (RtsFlags.ProfFlags.doHeapProfile) {
818 case HEAP_BY_CLOSURE_TYPE:
819 fprintf(hp_file, "%s", (char *)ctr->identity);
820 traceHeapProfSampleString(0, (char *)ctr->identity,
821 count * sizeof(W_));
822 break;
823 }
824
825 #if defined(PROFILING)
826 switch (RtsFlags.ProfFlags.doHeapProfile) {
827 case HEAP_BY_CCS:
828 fprint_ccs(hp_file, (CostCentreStack *)ctr->identity,
829 RtsFlags.ProfFlags.ccsLength);
830 traceHeapProfSampleCostCentre(0, (CostCentreStack *)ctr->identity,
831 count * sizeof(W_));
832 break;
833 case HEAP_BY_MOD:
834 case HEAP_BY_DESCR:
835 case HEAP_BY_TYPE:
836 fprintf(hp_file, "%s", (char *)ctr->identity);
837 traceHeapProfSampleString(0, (char *)ctr->identity,
838 count * sizeof(W_));
839 break;
840 case HEAP_BY_RETAINER:
841 {
842 RetainerSet *rs = (RetainerSet *)ctr->identity;
843
844 // it might be the distinguished retainer set rs_MANY:
845 if (rs == &rs_MANY) {
846 fprintf(hp_file, "MANY");
847 break;
848 }
849
850 // Mark this retainer set by negating its id, because it
851 // has appeared in at least one census. We print the
852 // values of all such retainer sets into the log file at
853 // the end. A retainer set may exist but not feature in
854 // any censuses if it arose as the intermediate retainer
855 // set for some closure during retainer set calculation.
856 if (rs->id > 0)
857 rs->id = -(rs->id);
858
859 // report in the unit of bytes: * sizeof(StgWord)
860 printRetainerSetShort(hp_file, rs, RtsFlags.ProfFlags.ccsLength);
861 break;
862 }
863 default:
864 barf("dumpCensus; doHeapProfile");
865 }
866 #endif
867
868 fprintf(hp_file, "\t%" FMT_Word "\n", (W_)count * sizeof(W_));
869 }
870
871 printSample(false, census->time);
872 }
873
874
875 static void heapProfObject(Census *census, StgClosure *p, size_t size,
876 bool prim
877 #if !defined(PROFILING)
878 STG_UNUSED
879 #endif
880 )
881 {
882 const void *identity;
883 size_t real_size;
884 counter *ctr;
885
886 identity = NULL;
887
888 #if defined(PROFILING)
889 // subtract the profiling overhead
890 real_size = size - sizeofW(StgProfHeader);
891 #else
892 real_size = size;
893 #endif
894
895 if (closureSatisfiesConstraints((StgClosure*)p)) {
896 #if defined(PROFILING)
897 if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) {
898 if (prim)
899 census->prim += real_size;
900 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
901 census->not_used += real_size;
902 else
903 census->used += real_size;
904 } else
905 #endif
906 {
907 identity = closureIdentity((StgClosure *)p);
908
909 if (identity != NULL) {
910 ctr = lookupHashTable(census->hash, (StgWord)identity);
911 if (ctr != NULL) {
912 #if defined(PROFILING)
913 if (RtsFlags.ProfFlags.bioSelector != NULL) {
914 if (prim)
915 ctr->c.ldv.prim += real_size;
916 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
917 ctr->c.ldv.not_used += real_size;
918 else
919 ctr->c.ldv.used += real_size;
920 } else
921 #endif
922 {
923 ctr->c.resid += real_size;
924 }
925 } else {
926 ctr = arenaAlloc( census->arena, sizeof(counter) );
927 initLDVCtr(ctr);
928 insertHashTable( census->hash, (StgWord)identity, ctr );
929 ctr->identity = identity;
930 ctr->next = census->ctrs;
931 census->ctrs = ctr;
932
933 #if defined(PROFILING)
934 if (RtsFlags.ProfFlags.bioSelector != NULL) {
935 if (prim)
936 ctr->c.ldv.prim = real_size;
937 else if ((LDVW(p) & LDV_STATE_MASK) == LDV_STATE_CREATE)
938 ctr->c.ldv.not_used = real_size;
939 else
940 ctr->c.ldv.used = real_size;
941 } else
942 #endif
943 {
944 ctr->c.resid = real_size;
945 }
946 }
947 }
948 }
949 }
950 }
951
952 // Compact objects require special handling code because they
953 // are not stored consecutively in memory (rather, each object
954 // is a list of objects), and that would break the while loop
955 // below. But we know that each block holds at most one object
956 // so we don't need the loop.
957 //
958 // See Note [Compact Normal Forms] for details.
959 static void
960 heapCensusCompactList(Census *census, bdescr *bd)
961 {
962 for (; bd != NULL; bd = bd->link) {
963 StgCompactNFDataBlock *block = (StgCompactNFDataBlock*)bd->start;
964 StgCompactNFData *str = block->owner;
965 heapProfObject(census, (StgClosure*)str,
966 compact_nfdata_full_sizeW(str), true);
967 }
968 }
969
970 /* -----------------------------------------------------------------------------
971 * Code to perform a heap census.
972 * -------------------------------------------------------------------------- */
973 static void
974 heapCensusChain( Census *census, bdescr *bd )
975 {
976 StgPtr p;
977 const StgInfoTable *info;
978 size_t size;
979 bool prim;
980
981 for (; bd != NULL; bd = bd->link) {
982
983 // HACK: pretend a pinned block is just one big ARR_WORDS
984 // owned by CCS_PINNED. These blocks can be full of holes due
985 // to alignment constraints so we can't traverse the memory
986 // and do a proper census.
987 if (bd->flags & BF_PINNED) {
988 StgClosure arr;
989 SET_HDR(&arr, &stg_ARR_WORDS_info, CCS_PINNED);
990 heapProfObject(census, &arr, bd->blocks * BLOCK_SIZE_W, true);
991 continue;
992 }
993
994 p = bd->start;
995
996 // When we shrink a large ARR_WORDS, we do not adjust the free pointer
997 // of the associated block descriptor, thus introducing slop at the end
998 // of the object. This slop remains after GC, violating the assumption
999 // of the loop below that all slop has been eliminated (#11627).
1000 // Consequently, we handle large ARR_WORDS objects as a special case.
1001 if (bd->flags & BF_LARGE
1002 && get_itbl((StgClosure *)p)->type == ARR_WORDS) {
1003 size = arr_words_sizeW((StgArrBytes *)p);
1004 prim = true;
1005 heapProfObject(census, (StgClosure *)p, size, prim);
1006 continue;
1007 }
1008
1009 while (p < bd->free) {
1010 info = get_itbl((const StgClosure *)p);
1011 prim = false;
1012
1013 switch (info->type) {
1014
1015 case THUNK:
1016 size = thunk_sizeW_fromITBL(info);
1017 break;
1018
1019 case THUNK_1_1:
1020 case THUNK_0_2:
1021 case THUNK_2_0:
1022 size = sizeofW(StgThunkHeader) + 2;
1023 break;
1024
1025 case THUNK_1_0:
1026 case THUNK_0_1:
1027 case THUNK_SELECTOR:
1028 size = sizeofW(StgThunkHeader) + 1;
1029 break;
1030
1031 case FUN:
1032 case BLACKHOLE:
1033 case BLOCKING_QUEUE:
1034 case FUN_1_0:
1035 case FUN_0_1:
1036 case FUN_1_1:
1037 case FUN_0_2:
1038 case FUN_2_0:
1039 case CONSTR:
1040 case CONSTR_NOCAF:
1041 case CONSTR_1_0:
1042 case CONSTR_0_1:
1043 case CONSTR_1_1:
1044 case CONSTR_0_2:
1045 case CONSTR_2_0:
1046 size = sizeW_fromITBL(info);
1047 break;
1048
1049 case IND:
1050 // Special case/Delicate Hack: INDs don't normally
1051 // appear, since we're doing this heap census right
1052 // after GC. However, GarbageCollect() also does
1053 // resurrectThreads(), which can update some
1054 // blackholes when it calls raiseAsync() on the
1055 // resurrected threads. So we know that any IND will
1056 // be the size of a BLACKHOLE.
1057 size = BLACKHOLE_sizeW();
1058 break;
1059
1060 case BCO:
1061 prim = true;
1062 size = bco_sizeW((StgBCO *)p);
1063 break;
1064
1065 case MVAR_CLEAN:
1066 case MVAR_DIRTY:
1067 case TVAR:
1068 case WEAK:
1069 case PRIM:
1070 case MUT_PRIM:
1071 case MUT_VAR_CLEAN:
1072 case MUT_VAR_DIRTY:
1073 prim = true;
1074 size = sizeW_fromITBL(info);
1075 break;
1076
1077 case AP:
1078 size = ap_sizeW((StgAP *)p);
1079 break;
1080
1081 case PAP:
1082 size = pap_sizeW((StgPAP *)p);
1083 break;
1084
1085 case AP_STACK:
1086 size = ap_stack_sizeW((StgAP_STACK *)p);
1087 break;
1088
1089 case ARR_WORDS:
1090 prim = true;
1091 size = arr_words_sizeW((StgArrBytes*)p);
1092 break;
1093
1094 case MUT_ARR_PTRS_CLEAN:
1095 case MUT_ARR_PTRS_DIRTY:
1096 case MUT_ARR_PTRS_FROZEN_CLEAN:
1097 case MUT_ARR_PTRS_FROZEN_DIRTY:
1098 prim = true;
1099 size = mut_arr_ptrs_sizeW((StgMutArrPtrs *)p);
1100 break;
1101
1102 case SMALL_MUT_ARR_PTRS_CLEAN:
1103 case SMALL_MUT_ARR_PTRS_DIRTY:
1104 case SMALL_MUT_ARR_PTRS_FROZEN_CLEAN:
1105 case SMALL_MUT_ARR_PTRS_FROZEN_DIRTY:
1106 prim = true;
1107 size = small_mut_arr_ptrs_sizeW((StgSmallMutArrPtrs *)p);
1108 break;
1109
1110 case TSO:
1111 prim = true;
1112 #if defined(PROFILING)
1113 if (RtsFlags.ProfFlags.includeTSOs) {
1114 size = sizeofW(StgTSO);
1115 break;
1116 } else {
1117 // Skip this TSO and move on to the next object
1118 p += sizeofW(StgTSO);
1119 continue;
1120 }
1121 #else
1122 size = sizeofW(StgTSO);
1123 break;
1124 #endif
1125
1126 case STACK:
1127 prim = true;
1128 #if defined(PROFILING)
1129 if (RtsFlags.ProfFlags.includeTSOs) {
1130 size = stack_sizeW((StgStack*)p);
1131 break;
1132 } else {
1133 // Skip this TSO and move on to the next object
1134 p += stack_sizeW((StgStack*)p);
1135 continue;
1136 }
1137 #else
1138 size = stack_sizeW((StgStack*)p);
1139 break;
1140 #endif
1141
1142 case TREC_CHUNK:
1143 prim = true;
1144 size = sizeofW(StgTRecChunk);
1145 break;
1146
1147 case COMPACT_NFDATA:
1148 barf("heapCensus, found compact object in the wrong list");
1149 break;
1150
1151 default:
1152 barf("heapCensus, unknown object: %d", info->type);
1153 }
1154
1155 heapProfObject(census,(StgClosure*)p,size,prim);
1156
1157 p += size;
1158 }
1159 }
1160 }
1161
1162 void heapCensus (Time t)
1163 {
1164 uint32_t g, n;
1165 Census *census;
1166 gen_workspace *ws;
1167
1168 census = &censuses[era];
1169 census->time = mut_user_time_until(t);
1170
1171 // calculate retainer sets if necessary
1172 #if defined(PROFILING)
1173 if (doingRetainerProfiling()) {
1174 retainerProfile();
1175 }
1176 #endif
1177
1178 #if defined(PROFILING)
1179 stat_startHeapCensus();
1180 #endif
1181
1182 // Traverse the heap, collecting the census info
1183 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
1184 heapCensusChain( census, generations[g].blocks );
1185 // Are we interested in large objects? might be
1186 // confusing to include the stack in a heap profile.
1187 heapCensusChain( census, generations[g].large_objects );
1188 heapCensusCompactList ( census, generations[g].compact_objects );
1189
1190 for (n = 0; n < n_capabilities; n++) {
1191 ws = &gc_threads[n]->gens[g];
1192 heapCensusChain(census, ws->todo_bd);
1193 heapCensusChain(census, ws->part_list);
1194 heapCensusChain(census, ws->scavd_list);
1195 }
1196 }
1197
1198 // dump out the census info
1199 #if defined(PROFILING)
1200 // We can't generate any info for LDV profiling until
1201 // the end of the run...
1202 if (!doingLDVProfiling())
1203 dumpCensus( census );
1204 #else
1205 dumpCensus( census );
1206 #endif
1207
1208
1209 // free our storage, unless we're keeping all the census info for
1210 // future restriction by biography.
1211 #if defined(PROFILING)
1212 if (RtsFlags.ProfFlags.bioSelector == NULL)
1213 {
1214 freeEra(census);
1215 census->hash = NULL;
1216 census->arena = NULL;
1217 }
1218 #endif
1219
1220 // we're into the next time period now
1221 nextEra();
1222
1223 #if defined(PROFILING)
1224 stat_endHeapCensus();
1225 #endif
1226 }