-
Notifications
You must be signed in to change notification settings - Fork 11
/
an_malloc.c
2039 lines (1651 loc) · 50.6 KB
/
an_malloc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <assert.h>
#include <ck_cc.h>
#include <ck_pr.h>
#include <ck_spinlock.h>
#include <dlfcn.h>
#include <errno.h>
#include <evhttp.h>
#include <inttypes.h>
#include <link.h>
#include <malloc.h>
#include <pthread.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/queue.h>
#include <sys/time.h>
#include <modp_ascii.h>
#include <modp_burl.h>
#include "common/an_cc.h"
#include "common/an_handler.h"
#include "common/an_malloc.h"
#include "common/an_string.h"
#include "common/an_syslog.h"
#include "common/an_thread.h"
#include "common/an_time.h"
#include "common/assert_dev.h"
#include "common/json_parser.h"
#include "common/libevent_extras.h"
#include "common/module/generic.h"
#include "common/server_config.h"
#include "common/util.h"
static int an_malloc_epoch_module_load(enum an_generic_action action, struct json_object *json);
static void an_malloc_epoch_metrics_cb(struct evbuffer *buf, double elapsed, bool clear);
static void an_malloc_epoch_set_cache_handler(struct evhttp_request *req, void *arg);
AN_GENERIC_MODULE(
this, "an_malloc_epoch", an_malloc_epoch_module_load,
"AN transactional memory allocator module",
.metrics_cb = an_malloc_epoch_metrics_cb,
.uris = {
{ .path = "/set_cache", .cb = an_malloc_epoch_set_cache_handler, .broadcast = false },
});
struct an_malloc_stat {
/* bytes. */
uint64_t total;
uint64_t active;
uint64_t peak;
/* allocations. */
uint64_t count_total;
uint64_t count_active;
uint64_t count_peak;
};
struct an_malloc_thread {
struct an_malloc_stat *stat;
unsigned int length;
int thread_id;
LIST_ENTRY(an_malloc_thread) list_entry;
};
LIST_HEAD(an_malloc_thread_list, an_malloc_thread);
struct an_malloc_owner {
struct an_malloc_stat *stat;
unsigned int length;
};
struct an_malloc_table {
struct an_malloc_type *type;
struct an_malloc_stat *stat;
struct an_malloc_thread_list threads;
struct an_malloc_owner *owners;
unsigned int owner_length;
unsigned int stat_length;
};
enum an_malloc_http_type {
AN_MALLOC_HTTP_ACTIVE = 0,
AN_MALLOC_HTTP_PEAK = 1,
AN_MALLOC_HTTP_TOTAL = 2,
AN_MALLOC_HTTP_COUNT_ACTIVE = 3,
AN_MALLOC_HTTP_COUNT_PEAK = 4,
AN_MALLOC_HTTP_COUNT_TOTAL = 5,
};
static ck_bitmap_t *epoch_map;
static struct an_malloc_epoch_stats {
uint64_t epochs_open;
uint64_t epochs_created;
uint64_t epochs_destroyed;
uint64_t epoch_allocations;
uint64_t non_epoch_allocations;
uint64_t max_ref_count;
uint64_t total_ref_count;
uint64_t epoch_allocated_size;
} epoch_stats;
/* Global type table. */
static struct an_malloc_table global_table;
static pthread_rwlock_t global_table_mutex;
static an_thread_key_t an_malloc_key;
/* string type support */
static AN_MALLOC_DEFINE(an_epoch_alloc_token,
.string = "an_malloc_epoch",
.mode = AN_MEMORY_MODE_VARIABLE,
.use_pool_allocation = false);
static AN_MALLOC_DEFINE(an_epoch_large_alloc_token,
.string = "an_malloc_epoch_large",
.mode = AN_MEMORY_MODE_VARIABLE,
.use_pool_allocation = true);
struct an_malloc_allocator {
const char *name;
int (*init)(struct evhttp *);
};
static struct an_malloc_allocator *allocator = NULL;
static int an_malloc_jemalloc(struct evhttp *);
static int an_malloc_glibc(struct evhttp *);
enum an_malloc_allocators {
AN_MALLOC_ALLOCATOR_DEFAULT = 0,
AN_MALLOC_ALLOCATOR_JEMALLOC = 1
};
/*
* These are the list of supported allocators according to
* a corresponding DSO unique substring. The allocator with
* the NULL name is the default (glibc) selection.
*/
static struct an_malloc_allocator allocators[] = {
[AN_MALLOC_ALLOCATOR_DEFAULT] = {
.name = NULL,
.init = an_malloc_glibc
},
[AN_MALLOC_ALLOCATOR_JEMALLOC] = {
.name = "libjemalloc.so",
.init = an_malloc_jemalloc
}
};
/*
* See the jemalloc man page. nallocx rounds up to the actual
* allocation size, and sallocx returns the allocation size for ptr.
* Flags isn't useful for us.
*/
static size_t (*nallocx)(size_t size, int flags) = NULL;
static size_t (*sallocx)(void *ptr, int flags) = NULL;
static size_t (*mallctl)(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen) = NULL;
static void (*an_malloc_jemalloc_stats_print)(void (*)(void *, const char *), void *, const char *);
#define STAT_FOREACH(OP, DST, SRC) \
do { \
(DST).total OP ck_pr_load_64(&(SRC).total); \
(DST).active OP ck_pr_load_64(&(SRC).active); \
(DST).peak OP ck_pr_load_64(&(SRC).peak); \
\
(DST).count_total OP ck_pr_load_64(&(SRC).count_total); \
(DST).count_active OP ck_pr_load_64(&(SRC).count_active); \
(DST).count_peak OP ck_pr_load_64(&(SRC).count_peak); \
} while (0)
#define STAT_ACTIVE(OP, DST, SRC) \
do { \
(DST).active OP ck_pr_load_64(&(SRC).active); \
} while (0)
static inline size_t
allocation_size(size_t size, void *ptr)
{
if (nallocx != NULL) {
return nallocx(size, 0);
}
return malloc_usable_size(ptr);
}
static void
an_malloc_handler_flot_generic_http(struct evhttp_request *request, enum an_malloc_http_type type)
{
struct an_malloc_thread *cursor;
struct an_malloc_stat stat;
const char *string;
struct timeval tv;
uint64_t value = 0;
size_t i;
if (request == NULL)
return;
an_gettimeofday(&tv, true);
evhttp_add_header(request->output_headers, "Access-Control-Allow-Origin", "*");
evhttp_add_header(request->output_headers, "Content-Type", "application/json");
EVBUFFER_ADD_STRING(request->output_buffer, "[\n");
for (i = 1; i < global_table.stat_length; i++) {
STAT_FOREACH(=, stat, global_table.stat[i]);
pthread_rwlock_rdlock(&global_table_mutex);
LIST_FOREACH(cursor, &global_table.threads, list_entry) {
STAT_FOREACH(+=, stat, cursor->stat[i]);
}
string = global_table.type[i].string;
pthread_rwlock_unlock(&global_table_mutex);
switch (type) {
case AN_MALLOC_HTTP_ACTIVE:
value = stat.active;
break;
case AN_MALLOC_HTTP_PEAK:
value = stat.peak;
break;
case AN_MALLOC_HTTP_TOTAL:
value = stat.total;
break;
case AN_MALLOC_HTTP_COUNT_ACTIVE:
value = stat.count_active;
break;
case AN_MALLOC_HTTP_COUNT_PEAK:
value = stat.count_peak;
break;
case AN_MALLOC_HTTP_COUNT_TOTAL:
value = stat.count_total;
break;
}
EVBUFFER_ADD_STRING(request->output_buffer, "\t{\n");
evbuffer_add_printf(request->output_buffer,
"\t\t\"label\" : \"%s\",\n", string);
evbuffer_add_printf(request->output_buffer,
"\t\t\"data\" : [[%ju, %.4f]]\n",
(uintmax_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000),
(double)value / 1048576.0);
if (i < global_table.stat_length - 1)
EVBUFFER_ADD_STRING(request->output_buffer, "\t},\n");
else
EVBUFFER_ADD_STRING(request->output_buffer, "\t}\n");
}
EVBUFFER_ADD_STRING(request->output_buffer, "]\n");
evhttp_send_reply(request, HTTP_OK, "OK", NULL);
return;
}
static void
an_malloc_handler_flot_active_http(struct evhttp_request *request, void *c)
{
an_malloc_handler_flot_generic_http(request, AN_MALLOC_HTTP_ACTIVE);
return;
}
static void
an_malloc_handler_flot_peak_http(struct evhttp_request *request, void *c)
{
an_malloc_handler_flot_generic_http(request, AN_MALLOC_HTTP_PEAK);
return;
}
static void
an_malloc_handler_flot_total_http(struct evhttp_request *request, void *c)
{
an_malloc_handler_flot_generic_http(request, AN_MALLOC_HTTP_TOTAL);
return;
}
static void
an_malloc_handler_flot_count_active_http(struct evhttp_request *request, void *c)
{
an_malloc_handler_flot_generic_http(request, AN_MALLOC_HTTP_COUNT_ACTIVE);
return;
}
static void
an_malloc_handler_flot_count_peak_http(struct evhttp_request *request, void *c)
{
an_malloc_handler_flot_generic_http(request, AN_MALLOC_HTTP_COUNT_PEAK);
return;
}
static void
an_malloc_handler_flot_count_total_http(struct evhttp_request *request, void *c)
{
an_malloc_handler_flot_generic_http(request, AN_MALLOC_HTTP_COUNT_TOTAL);
return;
}
static void
an_malloc_stats_print(void *r, const char *output)
{
struct evhttp_request *request = r;
evbuffer_add_printf(request->output_buffer, "%s", output);
return;
}
static void
an_malloc_handler_allocator_jemalloc_http(struct evhttp_request *request, void *c)
{
if (request == NULL)
return;
evhttp_add_header(request->output_headers, "Content-Type", "text/plain");
an_malloc_jemalloc_stats_print(an_malloc_stats_print, request, "g");
evhttp_send_reply(request, HTTP_OK, "OK", NULL);
return;
}
static void
an_malloc_handler_allocator_glibc_http(struct evhttp_request *request, void *c)
{
struct mallinfo m = mallinfo();
evhttp_add_header(request->output_headers, "Content-Type", "text/plain");
evbuffer_add_printf(request->output_buffer, "Allocator Statistics\n"
"============================================\n"
" Total memory: %12ju\n"
" |--- mmap: %12d (%d chunks)\n"
" '--- sbrk: %12d\n\n"
"Unused memory: %12d\n",
(uintmax_t)m.arena + (uintmax_t)m.hblkhd,
m.hblkhd, m.hblks, m.arena, m.fordblks);
evhttp_send_reply(request, HTTP_OK, "OK", NULL);
return;
}
static int
an_malloc_glibc(struct evhttp *httpd)
{
if (httpd != NULL)
an_handler_control_register("memory/allocator", an_malloc_handler_allocator_glibc_http, NULL, NULL);
return 0;
}
static int
an_malloc_jemalloc(struct evhttp *httpd)
{
an_malloc_jemalloc_stats_print = dlsym(RTLD_DEFAULT, "malloc_stats_print");
if (an_malloc_jemalloc_stats_print == NULL)
return -1;
if (httpd != NULL)
an_handler_control_register("memory/allocator", an_malloc_handler_allocator_jemalloc_http, NULL, NULL);
mallctl = dlsym(RTLD_DEFAULT, "mallctl");
return 0;
}
static int
an_malloc_detect_dlpi(struct dl_phdr_info *info, size_t size, void *data)
{
size_t i;
if (allocator != NULL) {
return allocator->init(data);
}
for (i = 1; i < ARRAY_SIZE(allocators); i++) {
if (info->dlpi_name == NULL || *info->dlpi_name == '\0')
return 0;
if (strstr(info->dlpi_name, allocators[i].name) != NULL) {
allocator = &allocators[i];
break;
}
}
if (i >= ARRAY_SIZE(allocators)) {
/* Use the default allocator */
allocator = &allocators[AN_MALLOC_ALLOCATOR_DEFAULT];
}
return allocator->init(data);
}
int
an_malloc_detect(struct evhttp *httpd)
{
return dl_iterate_phdr(an_malloc_detect_dlpi, httpd);
}
static uint64_t
get_divider(const struct evkeyvalq *kv)
{
const char *units_str;
uint64_t divider = 1;
units_str = evhttp_find_header(kv, "units");
if (units_str != NULL) {
switch(units_str[0]) {
case 'k':
divider = divider << 10;
break;
case 'm':
divider = divider << 20;
break;
case 'g':
divider = divider << 30;
break;
default:
break;
}
}
return divider;
}
static void
print_memory_row(struct evhttp_request *request, size_t num, const char *string, const struct an_malloc_stat *stat, uint64_t divider)
{
if (divider > 1) {
evbuffer_add_printf(request->output_buffer,
" %5zu %45s %10.2f %10.2f %25.2f %20" PRIu64 " %20" PRIu64 " %20" PRIu64,
num,
string,
(double)stat->active / divider,
(double)stat->peak / divider,
(double)stat->total / divider,
stat->count_active,
stat->count_peak,
stat->count_total
);
} else {
evbuffer_add_printf(request->output_buffer,
" %5zu %45s %12" PRIu64 " %12" PRIu64 " %25" PRIu64 " %20" PRIu64 " %20" PRIu64 " %20" PRIu64 "\t\t",
num,
string,
stat->active,
stat->peak,
stat->total,
stat->count_active,
stat->count_peak,
stat->count_total
);
}
}
static void
print_memory_summary(struct evhttp_request *request, struct an_malloc_stat *sum, uint64_t divider)
{
if (divider > 1) {
evbuffer_add_printf(request->output_buffer,
"\n %5s %45s %10.2f %12s %23.2f\n",
"TOTAL", " ", (double)sum->active / divider, " ", (double)sum->total / divider);
} else {
evbuffer_add_printf(request->output_buffer,
"\n %5s %45s %12" PRIu64 " %12s %25" PRIu64 "\n",
"TOTAL", " ", sum->active, " ", sum->total);
}
}
struct an_malloc_handler_row {
size_t num;
const char *label;
struct an_malloc_stat stat;
};
static int
row_comparator(const void *x, const void *y)
{
const struct an_malloc_handler_row *r1 = x, *r2 = y;
const struct an_malloc_stat *a = &r1->stat, *b = &r2->stat;
if (a->active == b->active) {
return 0;
}
return (a->active > b->active) ? -1 : 1;
}
static void
print_stats(struct evhttp_request *request, const struct evkeyvalq *kv,
struct an_malloc_handler_row *rows, size_t length)
{
uint64_t divider;
unsigned int ncols = 1;
struct an_malloc_stat sum = {
.total = 0,
.active = 0
};
bool all = false; /* Default to skipping rows that have zero allocation */
const char *ncols_str = evhttp_find_header(kv, "ncols");
str2int(ncols_str, (int *)&ncols, 1);
if (ncols < 1 || ncols > 3) {
ncols = 1;
}
divider = get_divider(kv);
const char *sort_str = evhttp_find_header(kv, "sort");
if (sort_str) {
qsort(rows, length, sizeof(struct an_malloc_handler_row), row_comparator);
}
const char *all_str = evhttp_find_header(kv, "all");
if (all_str) {
all = true;
}
evhttp_add_header(request->output_headers, "Content-Type", "text/plain");
for (size_t i = 0; i < ncols; i++) {
evbuffer_add_printf(request->output_buffer,
" %5s %45s %12s %12s %25s %20s %20s %20s\t\t",
"ID",
"Type",
"Active",
"Peak",
"Total",
"ActiveObject",
"PeakObject",
"TotalObject"
);
}
evbuffer_add_printf(request->output_buffer, "\n\n");
unsigned int nrows = (length / ncols) + (length % ncols ? 1 : 0);
/* Skipping over the null token */
for (size_t i = 1; i < nrows; i++) {
for (size_t j = 0; j < ncols; j++) {
size_t k = j * nrows + i;
if (k >= length) {
break;
}
size_t stat_num = rows[k].num;
const struct an_malloc_stat *stat = &rows[k].stat;
sum.total += stat->total;
sum.active += stat->active;
if (all == false && stat->total == 0 && stat->active == 0) {
continue;
}
print_memory_row(request, stat_num, rows[k].label, stat, divider);
if (k % ncols == 0) {
evbuffer_add_printf(request->output_buffer, "\n");
}
}
}
print_memory_summary(request, &sum, divider);
return;
}
uint64_t
an_malloc_owner_get_active(uint16_t owner_id)
{
uint64_t active = 0;
if ((unsigned int)owner_id >= global_table.owner_length) {
return 0;
}
const struct an_malloc_owner *m = &global_table.owners[owner_id];
if (m->length == 0) {
return 0;
}
for (size_t i = 0; i < m->length; i++) {
active += m->stat[i].active;
}
return active;
}
static void
an_malloc_handler_owner_http(struct evhttp_request *request, void *c)
{
struct evkeyvalq kv;
const char *id_str;
const struct an_malloc_owner *m;
uint16_t owner_id = 0;
if (request == NULL) {
return;
}
evhttp_parse_query(evhttp_request_uri(request), &kv);
id_str = evhttp_find_header(&kv, "id");
if (id_str == NULL) {
goto owner_error;
}
owner_id = strtol(id_str, NULL, 0);
if (owner_id >= global_table.owner_length) {
goto owner_error;
}
m = &global_table.owners[owner_id];
if (m->length == 0) {
goto owner_error;
}
{
size_t length = m->length;
struct an_malloc_handler_row *rows;
rows = calloc(length, sizeof(struct an_malloc_handler_row));
for (size_t i = 1; i < length; i++) {
rows[i].num = i;
rows[i].label = global_table.type[i].string;
rows[i].stat = m->stat[i];
}
print_stats(request, &kv, rows, length);
free(rows);
}
owner_error:
evhttp_clear_headers(&kv);
evhttp_send_reply(request, HTTP_OK, "OK", NULL);
return;
}
void
an_malloc_allocator_metrics_print(struct evbuffer *buf)
{
if (allocator == NULL) {
return;
}
if (allocator == &allocators[AN_MALLOC_ALLOCATOR_JEMALLOC] && mallctl != NULL) {
size_t read;
size_t len = sizeof(read);
/*
* Refresh cached mallctl statistics. Without this, the statistics could be indefinitely stale. It
* doesn't matter what value we pass for 'epoch'. Any input value triggers a stats refresh and an
* increment of the epoch. See the jemalloc man page.
*/
uint64_t epoch = 1;
if (mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)) != 0) {
return;
}
#define MAYBE_PRINT(stat) \
if (mallctl("stats."STRINGIFY(stat), &read, &len, NULL, 0) == 0) { \
evbuffer_add_printf(buf, "app.jemalloc."STRINGIFY(stat)"_avg: %zu\n", read); \
}
MAYBE_PRINT(allocated);
MAYBE_PRINT(active);
MAYBE_PRINT(mapped);
#undef MAYBE_PRINT
}
return;
}
void
an_malloc_token_metrics_print(struct evbuffer *buf)
{
struct an_malloc_thread *cursor;
pthread_rwlock_rdlock(&global_table_mutex);
size_t length = global_table.stat_length;
struct an_malloc_handler_row *rows = calloc(length, sizeof(struct an_malloc_handler_row));
/* Skipping over the null token */
for (size_t i = 1; i < length; i++) {
rows[i].num = i;
rows[i].label = global_table.type[i].string;
STAT_ACTIVE(=, rows[i].stat, global_table.stat[i]);
LIST_FOREACH(cursor, &global_table.threads, list_entry) {
STAT_ACTIVE(+=, rows[i].stat, cursor->stat[i]);
}
}
pthread_rwlock_unlock(&global_table_mutex);
for (size_t i = 1; i < length; i++) {
/* replace ':' with '-' for metrics' sake */
char *tmp_label = an_string_dup(rows[i].label);
an_str_replace_char(tmp_label, ':', '_');
evbuffer_add_printf(buf, "an_malloc.%s_avg: %lu\n", tmp_label, rows[i].stat.active);
an_string_free(tmp_label);
}
free(rows);
return;
}
static void
an_malloc_handler_http(struct evhttp_request *request, void *c)
{
struct an_malloc_thread *cursor;
struct evkeyvalq kv;
const char *thread_str;
int thread = -1;
if (request == NULL) {
return;
}
const char *uri = evhttp_request_uri(request);
evhttp_parse_query(uri, &kv);
thread_str = evhttp_find_header(&kv, "thread");
if (thread_str != NULL) {
str2int(thread_str, &thread, -1);
}
pthread_rwlock_rdlock(&global_table_mutex);
size_t length = global_table.stat_length;
struct an_malloc_handler_row *rows = calloc(length, sizeof(struct an_malloc_handler_row));
for (size_t i = 1; i < length; i++) {
rows[i].num = i;
rows[i].label = global_table.type[i].string;
if (thread == -1) {
STAT_FOREACH(=, rows[i].stat, global_table.stat[i]);
}
LIST_FOREACH(cursor, &global_table.threads, list_entry) {
if (thread == -1 || thread == cursor->thread_id) {
STAT_FOREACH(+=, rows[i].stat, cursor->stat[i]);
}
}
}
pthread_rwlock_unlock(&global_table_mutex);
print_stats(request, &kv, rows, length);
free(rows);
evhttp_clear_headers(&kv);
evhttp_send_reply(request, HTTP_OK, "OK", NULL);
return;
}
static void
an_malloc_handler_epoch_http(struct evhttp_request *request, void *c)
{
struct evkeyvalq kv;
const char *uri;
uint64_t cur_epochs_open = ck_pr_load_64(&epoch_stats.epochs_open);
uint64_t cur_epochs_created = ck_pr_load_64(&epoch_stats.epochs_created);
uint64_t cur_epochs_destroyed = ck_pr_load_64(&epoch_stats.epochs_destroyed);
uint64_t cur_epoch_allocations = ck_pr_load_64(&epoch_stats.epoch_allocations);
uint64_t cur_non_epoch_allocations = ck_pr_load_64(&epoch_stats.non_epoch_allocations);
uint64_t cur_total_ref_count = ck_pr_load_64(&epoch_stats.total_ref_count);
uint64_t cur_max_ref_count = ck_pr_load_64(&epoch_stats.max_ref_count);
uint64_t cur_epoch_allocated_size = ck_pr_load_64(&epoch_stats.epoch_allocated_size);
uri = evhttp_request_uri(request);
evhttp_parse_query(uri, &kv);
evhttp_add_header(request->output_headers, "Content-Type", "text/plain");
evbuffer_add_printf(request->output_buffer, "epochs_open: %" PRIu64"\n", cur_epochs_open);
evbuffer_add_printf(request->output_buffer, "epochs_created: %" PRIu64"\n", cur_epochs_created);
evbuffer_add_printf(request->output_buffer, "epoch_destroyed: %" PRIu64"\n", cur_epochs_destroyed);
evbuffer_add_printf(request->output_buffer, "total_epoch_allocations: %" PRIu64"\n", cur_epoch_allocations);
evbuffer_add_printf(request->output_buffer, "total_non_epoch_allocations: %" PRIu64"\n", cur_non_epoch_allocations);
evbuffer_add_printf(request->output_buffer, "allocations_per_epoch: %f\n", (double)cur_epoch_allocations / cur_epochs_destroyed);
evbuffer_add_printf(request->output_buffer, "total_epoch_allocated_size: %" PRIu64"\n", cur_epoch_allocated_size);
evbuffer_add_printf(request->output_buffer, "size_alloced_per_epoch: %f\n", (double)cur_epoch_allocated_size / cur_epochs_destroyed );
evbuffer_add_printf(request->output_buffer, "avg_refcount: %f\n", (double)cur_total_ref_count / cur_epochs_destroyed);
evbuffer_add_printf(request->output_buffer, "max_refcount: %" PRIu64"\n", cur_max_ref_count);
evhttp_clear_headers(&kv);
evhttp_send_reply(request, HTTP_OK, "OK", NULL);
return;
}
void
an_malloc_handler_http_enable(struct evhttp *httpd)
{
if (an_malloc_detect(httpd) == -1)
abort();
if (httpd != NULL) {
an_handler_control_register("memory/list", an_malloc_handler_http, NULL, NULL);
an_handler_control_register("memory/owner", an_malloc_handler_owner_http, NULL, NULL);
an_handler_control_register("memory/flot/active", an_malloc_handler_flot_active_http, NULL, NULL);
an_handler_control_register("memory/flot/peak", an_malloc_handler_flot_peak_http, NULL, NULL);
an_handler_control_register("memory/flot/total", an_malloc_handler_flot_total_http, NULL, NULL);
an_handler_control_register("memory/flot/count_active", an_malloc_handler_flot_count_active_http, NULL, NULL);
an_handler_control_register("memory/flot/count_peak", an_malloc_handler_flot_count_peak_http, NULL, NULL);
an_handler_control_register("memory/flot/count_total", an_malloc_handler_flot_count_total_http, NULL, NULL);
an_handler_control_register("memory/epoch", an_malloc_handler_epoch_http, NULL, NULL);
}
return;
}
static void
an_malloc_message(const char *s)
{
an_syslog(LOG_WARNING, "%s", s);
return;
}
static void
an_malloc_key_destroy(void *p)
{
struct an_malloc_thread *thread = p;
uint64_t peak;
size_t i;
pthread_rwlock_wrlock(&global_table_mutex);
LIST_REMOVE(thread, list_entry);
pthread_rwlock_unlock(&global_table_mutex);
for (i = 0; i < thread->length; i++) {
ck_pr_add_64(&global_table.stat[i].total, thread->stat[i].total);
ck_pr_add_64(&global_table.stat[i].active, thread->stat[i].active);
peak = ck_pr_load_64(&global_table.stat[i].peak);
for (;;) {
if (thread->stat[i].peak <= peak)
break;
if (ck_pr_cas_64_value(&global_table.stat[i].peak, peak, thread->stat[i].peak, &peak) == true)
break;
ck_pr_stall();
}
}
free(thread->stat);
free(thread);
return;
}
#define AN_MALLOC_ROUND_UP_TO_MULTIPLE(N, ROUND_TO_MULTIPLE_OF) \
(((N) + (ROUND_TO_MULTIPLE_OF) - 1) & ~((ROUND_TO_MULTIPLE_OF) -1))
/*
* Malloc's minimal alignment is an ABI guarantee/restriction.
*/
#define AN_MALLOC_GUARANTEED_ALIGNMENT 16ULL
/*
* Alignment and zero granularity must be powers of two. Epoch size
* should be a multiple of both, and probably a power of two as well.
*/
#define AN_MALLOC_EPOCH_ALIGNMENT (1ULL << 20)
#define AN_MALLOC_EPOCH_ZERO_GRANULARITY (1ULL << 12)
#define AN_MALLOC_EPOCH_SIZE (1ULL << 25)
#define AN_MALLOC_EPOCH_AVAILABLE_SIZE \
(AN_MALLOC_EPOCH_SIZE - \
AN_MALLOC_ROUND_UP_TO_MULTIPLE(sizeof(struct an_malloc_epoch), \
AN_MALLOC_GUARANTEED_ALIGNMENT))
/*
* This is 4x the alignment, so worst-case fragmentation from
* alignment is 25%.
*
* It's also ~1/8th the epoch size, so the worst case space wastage
* from creating a new epoch without fully using the current one is
* 12.5%.
*/
#define AN_MALLOC_EPOCH_LARGE_ALLOC (1ULL << 22)
_Static_assert((AN_MALLOC_EPOCH_SIZE % AN_MALLOC_EPOCH_ALIGNMENT == 0),
"Epoch size should be a multiple of the epoch alignment.");
_Static_assert((AN_MALLOC_EPOCH_AVAILABLE_SIZE > 0),
"Epoch should have non-empty capacity");
_Static_assert((AN_MALLOC_EPOCH_LARGE_ALLOC <= AN_MALLOC_EPOCH_AVAILABLE_SIZE),
"Anything bigger than an epoch should be a large allocation.");
/*
* The maximum number of reclaimed epochs any thread will cache.
*
* Lower this value to reduce the per-thread memory usage from epoch caching.
*/
static size_t reclaimed_epochs_limit = 8;
int AN_CC_NO_SANITIZE
an_malloc_init(void)
{
/*
* The next two symbols are created by the linker when the
* an_malloc_register_link_list section is non-empty. Their
* *address* correspond to the first byte and one past the
* last byte in that section, which is why we declare them as
* array of pointers to an_malloc_register_link (the section
* is filled with pointers to an_malloc_register_link).
*/
extern const struct an_malloc_register_link *__start_an_malloc_register_link_list[];
extern const struct an_malloc_register_link *__stop_an_malloc_register_link_list[];
int ret;
AN_BLOCK_EXECUTE_ONCE_GUARD;
AN_MALLOC_FORBID_EPOCH_IN_SCOPE;
if (pthread_rwlock_init(&global_table_mutex, NULL) != 0) {
return -1;
}
ret = an_thread_key_create(&an_malloc_key, an_malloc_key_destroy);
assert(ret == 0);
/*
* Prevent uninitialized tokens from being able to use
* an_malloc, reducing accounting errors.
* This is kosher because every registration does a realloc.
*/
global_table.stat_length = 1;
for (const struct an_malloc_register_link **link_ptr = __start_an_malloc_register_link_list;
link_ptr < __stop_an_malloc_register_link_list;
link_ptr++) {
const struct an_malloc_register_link *link = *link_ptr;
an_malloc_token_t token;
if (link == NULL) {
continue;
}
token = an_malloc_register(link->type);
if (link->token != NULL) {
memcpy(link->token, &token, sizeof(*link->token));
}
}
/*
* x86_64 only uses 48 VMA bits, so only allocate space for a
* bitmap of 2^48 bits / ALIGNMENT instead of
* 2^64 bits / ALIGNMENT. This reduces the size of the bitmap
* by a factor of 64K. For our current alignment of 1MB, the
* space requirements go from 2TB to 32MB, which is nice.
*/
size_t n_pools = (1ULL << CK_MD_VMA_BITS) / AN_MALLOC_EPOCH_ALIGNMENT;
/* This will be 16 MB */
epoch_map = malloc(ck_bitmap_size(n_pools));
ck_bitmap_init(epoch_map, n_pools, false);
memset(&epoch_stats, 0, sizeof(struct an_malloc_epoch_stats));
nallocx = dlsym(RTLD_DEFAULT, "nallocx");
sallocx = dlsym(RTLD_DEFAULT, "sallocx");
if (nallocx == NULL || sallocx == NULL) {
nallocx = NULL;
sallocx = NULL;
}
return 0;
}
an_malloc_token_t
an_malloc_register(an_malloc_type_t *type)
{
struct an_malloc_type copy;
struct an_malloc_type *entry;
struct an_malloc_stat *stat;
an_malloc_token_t ret;
assert(global_table.stat_length < INT_MAX);
/* Fixed size types must have a size associated with them. */
if (type->mode == AN_MEMORY_MODE_FIXED) {
assert(type->size > 0);
}
/* The entry does not exist so create a new entry for the type map. */
type->id = ck_pr_faa_uint(&global_table.stat_length, 1);
assert(type->id > 0 && type->id <= INT_MAX);
entry = realloc(global_table.type, (type->id + 1) * sizeof(struct an_malloc_type));
assert(entry != NULL);
stat = realloc(global_table.stat, (type->id + 1) * sizeof(struct an_malloc_stat));
assert(stat != NULL);