-
Notifications
You must be signed in to change notification settings - Fork 12
/
monitor.c
2946 lines (2607 loc) · 100 KB
/
monitor.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 <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
#include <pthread.h>
#include <signal.h>
#include <ctype.h>
#define _GNU_SOURCE
#include <unistd.h>
#include <dirent.h>
#include <linux/perf_event.h>
#include <sys/time.h>
#include <linux/kvm.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/utsname.h>
#include <sys/resource.h>
#include <sys/signalfd.h>
#include <sys/wait.h>
#if defined(__i386__) || defined(__x86_64__)
#include <cpuid.h>
#endif
#include <linux/thread_map.h>
#include <linux/cgroup.h>
#include <trace_helpers.h>
#include <monitor.h>
#include <tep.h>
#include <timer.h>
#include <stack_helpers.h>
#include <api/fs/fs.h>
static int daylight_active;
static unsigned int page_size;
struct event_poll *main_epoll = NULL;
struct list_head prof_dev_list = LIST_HEAD_INIT(prof_dev_list);
struct monitor *monitors_list = NULL;
struct monitor *monitor = NULL;
void monitor_register(struct monitor *m)
{
m->next = monitors_list;
monitors_list = m;
}
struct monitor * monitor_find(const char *name)
{
struct monitor *m = monitors_list;
while(m) {
if (!strcmp(m->name, name))
return m;
m = m->next;
}
return NULL;
}
struct monitor *monitor_next(struct monitor *m)
{
if (!m)
return monitors_list;
else
return m->next;
}
int prof_dev_nr_ins(struct prof_dev *dev)
{
int nr_ins;
nr_ins = perf_cpu_map__nr(dev->cpus);
if (perf_cpu_map__empty(dev->cpus))
nr_ins = perf_thread_map__nr(dev->threads);
return nr_ins;
}
int prof_dev_ins_cpu(struct prof_dev *dev, int ins)
{
return perf_cpu_map__cpu(dev->cpus, ins);
}
int prof_dev_ins_thread(struct prof_dev *dev, int ins)
{
return perf_thread_map__pid(dev->threads, ins);
}
int prof_dev_ins_oncpu(struct prof_dev *dev)
{
return !perf_cpu_map__empty(dev->cpus);
}
int main_epoll_add(int fd, unsigned int events, void *ptr, handle_event handle)
{
return event_poll__add(main_epoll, fd, events, ptr, handle);
}
int main_epoll_del(int fd)
{
return event_poll__del(main_epoll, fd);
}
/******************************************************
perf-prof argc argv
******************************************************/
struct env env;
static volatile int running = 0;
const char *main_program_version = PROGRAME " 1.4";
enum {
LONG_OPT_start = 500,
LONG_OPT_than,
LONG_OPT_only_than,
LONG_OPT_lower,
LONG_OPT_order_mem,
LONG_OPT_detail,
LONG_OPT_period,
};
static int workload_prepare(struct workload *workload, char *argv[]);
/**
* Parses a string into a number. The number stored at @ptr is
* potentially suffixed with K, M, G, T, P, E.
*/
static unsigned long memparse(const char *ptr, char **retptr)
{
char *endptr; /* local pointer to end of parsed string */
unsigned long ret = strtoul(ptr, &endptr, 10);
switch (*endptr) {
case 'E':
case 'e':
ret <<= 10;
/* fall through */
case 'P':
case 'p':
ret <<= 10;
/* fall through */
case 'T':
case 't':
ret <<= 10;
/* fall through */
case 'G':
case 'g':
ret <<= 10;
/* fall through */
case 'M':
case 'm':
ret <<= 10;
/* fall through */
case 'K':
case 'k':
ret <<= 10;
/* fall through */
case 'B':
case 'b':
endptr++;
default:
break;
}
if (retptr)
*retptr = endptr;
return ret;
}
/**
* Parses a string into ns. The number stored at @ptr is
* potentially suffixed with s, ms, us, ns.
*/
static unsigned long nsparse(const char *ptr, char **retptr)
{
char *endptr; /* local pointer to end of parsed string */
unsigned long ret = strtoul(ptr, &endptr, 10);
unsigned long tmp = ret;
switch (*endptr) {
case 'S':
case 's':
tmp *= 1000;
endptr--;
/* fall through */
case 'M':
case 'm':
tmp *= 1000;
/* fall through */
case 'U':
case 'u':
tmp *= 1000;
/* fall through */
case 'N':
case 'n':
endptr++;
if (*endptr == 's') {
endptr++;
ret = tmp;
}
default:
break;
}
if (retptr)
*retptr = endptr;
return ret;
}
static void detail_parse(const char *s)
{
if (strcmp(s, "samecpu") == 0)
env.samecpu = true;
else if (strcmp(s, "samepid") == 0)
env.samepid = true;
else if (strcmp(s, "sametid") == 0)
env.sametid = true;
else if (strcmp(s, "samekey") == 0)
env.samekey = true;
else if (strncmp(s, "hide<", 5) == 0)
env.hide_than = nsparse(s+5, NULL);
else if (s[0] == '-')
env.before_event1 = nsparse(s+1, NULL);
else
env.after_event2 = nsparse(s, NULL);
}
static int parse_arg(int key, char *arg)
{
switch (key) {
case 'e':
env.events = realloc(env.events, (env.nr_events + 1) * sizeof(*env.events));
env.events[env.nr_events] = strdup(arg);
if (env.nr_events == 0)
env.event = env.events[0];
env.nr_events ++;
break;
case LONG_OPT_only_than:
env.only_print_greater_than = true;
// fall through
case LONG_OPT_than:
env.greater_than = nsparse(arg, NULL);
break;
case LONG_OPT_lower:
env.lower_than = nsparse(arg, NULL);
break;
case LONG_OPT_order_mem:
env.order_mem = memparse(arg, NULL);
break;
case LONG_OPT_detail:
env.detail = true;
if (arg) {
char *ss = strdup(arg);
char *sep, *s = ss;
while ((sep = strchr(s, ',')) != NULL) {
*sep = '\0';
detail_parse(s);
s = sep + 1;
}
if (*s)
detail_parse(s);
free(ss);
}
break;
case LONG_OPT_period:
env.sample_period = nsparse(arg, NULL);
break;
case 'V':
printf("%s\n", main_program_version);
exit(0);
default:
break;
}
return 0;
}
static int parse_help_cb(const struct option *opt, const char *arg, int unset)
{
help();
return 0;
}
static int parse_arg_cb(const struct option *opt, const char *arg, int unset)
{
return parse_arg(opt->short_name, (char *)arg);
}
static void compgen_events(char **evt_list, int evt_num, void *opaque)
{
struct {
char *prefix;
const char *match;
int skiplen;
int comp_type;
} *op = opaque;
const char *prefix = op->prefix ?: "";
char *prev = NULL, *found;
int match_len = op->match ? strlen(op->match) : 0;
int i, j, matched = 0;
unsigned int maxprefix = -1;
if (match_len == 0) {
for (i = 0; i < evt_num; i++)
printf("'%s%s'\n", prefix, evt_list[i]);
return;
}
/*
# COMP_TYPE Need prefix? Substring matching? matched==1
# 9 [Tab] Y Y (Prefix first) Output ','
# ? [Tab][Tab] N Y Output ','
# % menu-complete Y Y Output ','
# * insert-completions Y Y (!prefix) No output ','
#
# ! show-all-if-ambiguous Same as [Tab][Tab]
# @ show-all-if-unmodified Same as [Tab][Tab]
*/
// ![Tab]: [Tab][Tab], menu-complete, etc.
// substring matching: strstr.
if (op->comp_type != 9) {
for (i = 0; i < evt_num; i++)
if (strstr(evt_list[i], op->match) != NULL) {
if (op->comp_type != '*')
printf("'%s%s'\n", prefix, evt_list[i] + op->skiplen);
else if (!op->prefix)
printf("'%s'\n", evt_list[i]);
found = evt_list[i];
matched++;
}
if (matched == 1 && op->comp_type != '*')
printf("'%s%s,'\n", prefix, found + op->skiplen);
return;
}
// [Tab] prefix matching: strncmp.
for (i = 0; i < evt_num; i++)
if (strncmp(evt_list[i], op->match, match_len) == 0)
matched++;
if (matched != 0) {
j = matched;
for (i = 0; j; i++)
if (strncmp(evt_list[i], op->match, match_len) == 0) {
printf("'%s%s'\n", prefix, evt_list[i] + op->skiplen);
if (matched == 1)
printf("'%s%s,'\n", prefix, evt_list[i] + op->skiplen);
j--;
}
return;
}
// [Tab] substring matching. The longest common prefix must contain `op->match'.
for (i = 0; i < evt_num; i++)
if ((found = strstr(evt_list[i], op->match)) != NULL) {
matched++;
if (prev) {
const char *s1 = prev, *s2 = evt_list[i];
j = 0; while (*s1++ == *s2++) j++;
if (j < maxprefix) maxprefix = j;
if (maxprefix < found - evt_list[i] + match_len)
goto failed;
}
prev = evt_list[i];
}
if (matched != 0) {
j = matched;
for (i = 0; j; i++)
if (strstr(evt_list[i], op->match) != NULL) {
printf("'%s%s'\n", prefix, evt_list[i] + op->skiplen);
if (matched == 1)
printf("'%s%s,'\n", prefix, evt_list[i] + op->skiplen);
j--;
}
return;
}
failed:
printf("'%s%s'\n", prefix, op->match + op->skiplen);
printf("'%s%s,'\n", prefix, op->match + op->skiplen);
}
static int compgen_arg(const struct option *opt, const char *arg, int comp_type)
{
const char *comma;
char *prefix = NULL;
char *COMP_SKIPLEN = getenv("COMP_SKIPLEN");
int skiplen = 0;
switch (opt->short_name) {
case 'e':
comma = strrchr(arg, ',');
if (comp_type == 9 || comp_type == '%' || comp_type == '*') {
if (COMP_SKIPLEN) {
/*
* If option parameter contains "$COMP_WORDBREAKS" characters, it will be separated
* into multiple words. But completion only operates on the word pointed to by
* COMP_POINT.
* COMP_SKIPLEN represents the length of the previous word, which needs to be skipped
* when perf-prof outputs completion.
*
* perf-prof trace -e sched:sched_wakeup/pid>1/,sch[TAB]
* COMP_WORDBREAKS=" \n\"'><=;|&(:"
* COMP_WORDS='(... [2]="-e" [3]="sched" [4]=":" [5]="sched_wakeup/pid" [6]=">" [7]="1/,sch")'
* COMP_SKIPLEN=23 (Contains the length of COMP_WORDS [3], [4], [5], [6])
* OUTPUT='([0]="1/,sched:sched_kthread_stop" ...)'
*/
int comp_skiplen = atoi(COMP_SKIPLEN);
const char *skip = arg + comp_skiplen;
if (comma) {
if (skip < comma) {
arg = skip;
goto make_prefix;
}
arg = comma + 1;
comma = NULL;
}
if (arg < skip)
skiplen = skip - arg;
} else if (comma) {
make_prefix:
prefix = strndup(arg, comma - arg + 1);
}
} {
struct {
char *prefix;
const char *match;
int skiplen;
int comp_type;
} op = {
.prefix = prefix,
.match = comma ? comma + 1 : arg,
.skiplen = skiplen,
.comp_type = comp_type,
};
print_tracepoint_events(compgen_events, (void *)&op);
}
if (prefix) free(prefix);
break;
default:
break;
}
return 0;
}
#define OPT_BOOL_NONEG(s, l, v, h) { .type = OPTION_BOOLEAN, .short_name = (s), .long_name = (l), .value = check_vtype(v, bool *), .help = (h), .flags = PARSE_OPT_NONEG }
#define OPT_INT_NONEG(s, l, v, a, h) { .type = OPTION_INTEGER, .short_name = (s), .long_name = (l), .value = check_vtype(v, int *), .argh = (a), .help = (h), .flags = PARSE_OPT_NONEG }
#define OPT_INT_NONEG_SET(s, l, v, os, a, h) { .type = OPTION_INTEGER, .short_name = (s), .long_name = (l), .value = check_vtype(v, int *), .set = check_vtype(os, bool *), .argh = (a), .help = (h), .flags = PARSE_OPT_NONEG }
#define OPT_UINT_NONEG(s, l, v, a, h) { .type = OPTION_UINTEGER, .short_name = (s), .long_name = (l), .value = check_vtype(v, unsigned int *), .argh = (a), .help = (h), .flags = PARSE_OPT_NONEG }
#define OPT_LONG_NONEG(s, l, v, a, h) { .type = OPTION_LONG, .short_name = (s), .long_name = (l), .value = check_vtype(v, long *), .argh = (a), .help = (h), .flags = PARSE_OPT_NONEG }
#define OPT_ULONG_NONEG(s, l, v, a, h) { .type = OPTION_ULONG, .short_name = (s), .long_name = (l), .value = check_vtype(v, unsigned long *), .argh = (a), .help = (h), .flags = PARSE_OPT_NONEG }
#define OPT_U64_NONEG(s, l, v, a, h) { .type = OPTION_U64, .short_name = (s), .long_name = (l), .value = check_vtype(v, u64 *), .argh = (a), .help = (h), .flags = PARSE_OPT_NONEG }
#define OPT_STRDUP_NONEG(s, l, v, a, h) { .type = OPTION_STRING, .short_name = (s), .long_name = (l), .value = check_vtype(v, char **), .argh = (a), .help = (h), .flags = PARSE_OPT_NONEG | PARSE_OPT_NOEMPTY }
#define OPT_PARSE_NONEG(s, l, v, a, h) \
{ .type = OPTION_CALLBACK, .short_name = (BUILD_BUG_ON_ZERO(s==0) + s), .long_name = (l), .value = (v), .argh = (a), .help = (h), .flags = PARSE_OPT_NONEG, .callback = (parse_arg_cb), .compgen = (compgen_arg) }
#define OPT_PARSE_NOARG(s, l, v, a, h) \
{ .type = OPTION_CALLBACK, .short_name = (BUILD_BUG_ON_ZERO(s==0) + s), .long_name = (l), .value = (v), .argh = (a), .help = (h), .flags = PARSE_OPT_NONEG | PARSE_OPT_NOARG, .callback = (parse_arg_cb) }
#define OPT_PARSE_OPTARG(s, l, v, a, h) \
{ .type = OPTION_CALLBACK, .short_name = (BUILD_BUG_ON_ZERO(s==0) + s), .long_name = (l), .value = (v), .argh = (a), .help = (h), .flags = PARSE_OPT_NONEG | PARSE_OPT_OPTARG, .callback = (parse_arg_cb) }
#define OPT_INT_OPTARG(s, l, v, d, a, h) \
{ .type = OPTION_INTEGER, .short_name = (s), .long_name = (l), .value = check_vtype(v, int *), .argh = (a), .defval = (intptr_t)(d), .help = (h), .flags = PARSE_OPT_NONEG | PARSE_OPT_OPTARG }
#define OPT_INT_OPTARG_SET(s, l, v, os, d, a, h) \
{ .type = OPTION_INTEGER, .short_name = (s), .long_name = (l), .value = check_vtype(v, int *), .set = check_vtype(os, bool *), .argh = (a), .defval = (intptr_t)(d), .help = (h), .flags = PARSE_OPT_NONEG | PARSE_OPT_OPTARG }
#define OPT_HELP() \
{ .type = OPTION_CALLBACK, .short_name = ('h'), .long_name = ("help"), .help = ("Give this help list"), .flags = PARSE_OPT_NONEG | PARSE_OPT_NOARG, .callback = (parse_help_cb) }
struct option main_options[] = {
OPT_GROUP("OPTION:"),
OPT_STRDUP_NONEG('C', "cpus", &env.cpumask, "cpu[-cpu],...", "Monitor the specified CPU, Dflt: all cpu"),
OPT_STRDUP_NONEG('p', "pids", &env.pids, "pid,...", "Attach to processes"),
OPT_STRDUP_NONEG('t', "tids", &env.tids, "tid,...", "Attach to threads"),
OPT_STRDUP_NONEG( 0 , "cgroups", &env.cgroups, "cgroup,...", "Attach to cgroups, support regular expression."),
OPT_BOOL_NONEG ( 0 , "inherit", &env.inherit, "Child tasks do inherit counters."),
OPT_INT_NONEG_SET( 0 , "watermark", &env.watermark, &env.watermark_set, "0-100", "Wake up "PROGRAME" watermark."),
OPT_INT_NONEG ('i', "interval", &env.interval, "ms", "Interval, Unit: ms"),
OPT_STRDUP_NONEG('o', "output", &env.output, "file", "Output file name"),
OPT_BOOL_NONEG ( 0 , "order", &env.order, "Order events by timestamp."),
OPT_PARSE_NONEG (LONG_OPT_order_mem, "order-mem", &env.order_mem, "bytes", "Maximum memory used by ordering events. Unit: GB/MB/KB/*B."),
OPT_INT_NONEG ('m', "mmap-pages", &env.mmap_pages, "pages", "Number of mmap data pages and AUX area tracing mmap pages"),
OPT_LONG_NONEG ('N', "exit-N", &env.exit_n, "N", "Exit after N events have been sampled."),
OPT_BOOL_NONEG ( 0 , "tsc", &env.tsc, "Convert perf clock to tsc."),
OPT_STRDUP_NONEG( 0 , "kvmclock", &env.kvmclock, "uuid", "Convert perf clock to Guest's kvmclock."),
OPT_U64_NONEG ( 0 ,"clock-offset", &env.clock_offset, NULL, "Sum with clock-offset to get the final clock."),
OPT_INT_NONEG ( 0 , "usage-self", &env.usage_self, "ms", "Periodically output the CPU usage of perf-prof itself, Unit: ms"),
OPT_INT_NONEG ( 0 ,"sampling-limit", &env.sampling_limit, "N", "Limit the number of samples per second per instance."),
OPT_STRDUP_NONEG( 0 , "perfeval-cpus", &env.perfeval_cpus, "cpu", "Performance evaluation cpu list."),
OPT_STRDUP_NONEG( 0 , "perfeval-pids", &env.perfeval_pids, "pid", "Performance evaluation pid list."),
OPT_PARSE_NOARG ('V', "version", NULL, NULL, "Version info"),
OPT__VERBOSITY(&env.verbose),
OPT_HELP(),
OPT_GROUP("FILTER OPTION:"),
OPT_BOOL_NONEG ('G', "exclude-host", &env.exclude_host, "Monitor GUEST, exclude host"),
OPT_BOOL_NONEG ( 0 , "exclude-guest", &env.exclude_guest, "exclude guest"),
OPT_BOOL_NONEG ( 0 , "exclude-user", &env.exclude_user, "exclude user"),
OPT_BOOL_NONEG ( 0 , "exclude-kernel", &env.exclude_kernel, "exclude kernel"),
OPT_BOOLEAN_SET ( 0 , "user-callchain", &env.user_callchain, &env.user_callchain_set, "include user callchains, no- prefix to exclude"),
OPT_BOOLEAN_SET ( 0 , "kernel-callchain", &env.kernel_callchain, &env.kernel_callchain_set, "include kernel callchains, no- prefix to exclude"),
OPT_INT_OPTARG_SET( 0 , "irqs_disabled", &env.irqs_disabled, &env.irqs_disabled_set, 1, "0|1", "ebpf, irqs disabled or not."),
OPT_INT_OPTARG_SET( 0 , "tif_need_resched", &env.tif_need_resched, &env.tif_need_resched_set, 1, "0|1", "ebpf, TIF_NEED_RESCHED is set or not."),
OPT_INT_NONEG_SET ( 0 , "exclude_pid", &env.exclude_pid, &env.exclude_pid_set, "pid", "ebpf, exclude pid"),
OPT_INT_NONEG_SET ( 0 , "nr_running_min", &env.nr_running_min, &env.nr_running_min_set, NULL, "ebpf, minimum number of running processes for CPU runqueue."),
OPT_INT_NONEG_SET ( 0 , "nr_running_max", &env.nr_running_max, &env.nr_running_max_set, NULL, "ebpf, maximum number of running processes for CPU runqueue."),
OPT_GROUP("PROFILER OPTION:"),
OPT_PARSE_NONEG ('e', "event", NULL, "EVENT,...", "Event selector. use '"PROGRAME" list' to list available tp events.\n"
" EVENT,EVENT,...\n"
" EVENT: sys:name[/filter/ATTR/ATTR/.../]\n"
" profiler[/option/ATTR/ATTR/.../]\n"
" kprobe:func[/filter/ATTR/ATTR/.../]\n"
" uprobe:func@\"file\"[/filter/ATTR/ATTR/.../]\n"
" filter: trace events filter\n"
" ATTR:\n"
" stack: sample_type PERF_SAMPLE_CALLCHAIN\n"
" max-stack=int : sample_max_stack\n"
" alias=str: event alias\n"
" exec=EXPR: a public expression executed by any profiler\n"
" cpus=cpu[-cpu]: attach to a different cpu list.\n"
" top-by=EXPR: add to top, sort by this field\n"
" top-add=EXPR: add to top\n"
" comm=EXPR: top, show COMM\n"
" ptr=EXPR: kmemleak, ptr field, Dflt: ptr=ptr\n"
" size=EXPR: kmemleak, size field, Dflt: size=bytes_alloc\n"
" num=EXPR: num-dist, num field\n"
" key=EXPR: key for multiple events: top, multi-trace\n"
" role=EXPR: multi-trace, Bit 0: as event1, Bit 1: as event2.\n"
" untraced: multi-trace, auxiliary, no two-event analysis\n"
" trigger: multi-trace, use events to trigger interval output\n"
" vm=uuid: get the mapping from Guest vcpu to Host tid\n"
" push=[IP:]PORT: push events to the local broadcast server IP:PORT\n"
" push=chardev: push events to chardev, e.g., /dev/virtio-ports/*\n"
" push=file: push events to file\n"
" pull=[IP:]PORT: pull events from server IP:PORT\n"
" pull=chardev: pull events from chardev\n"
" pull=file: pull events from file\n"
" EXPR:\n"
" C expression. See `"PROGRAME" expr -h` for more information."
),
OPT_INT_NONEG ('F', "freq", &env.freq, NULL, "Profile at this frequency, No profile: 0"),
OPT_STRDUP_NONEG('k', "key", &env.key, "str", "Key for series events"),
OPT_STRDUP_NONEG( 0 , "filter", &env.filter, "filter", "Event filter/comm filter"),
OPT_PARSE_NONEG (LONG_OPT_period, "period", &env.sample_period, "ns", "Sample period, Unit: s/ms/us/*ns"),
OPT_STRDUP_NONEG(0, "impl", &env.impl, "impl", "Implementation of two-event analysis class. Dflt: delay.\n"
" delay: latency distribution between two events\n"
" pair: determine if two events are paired\n"
" kmemprof: profile memory allocated and freed bytes\n"
" syscalls: syscall delay\n"
" call: analyze function calls, only for nested-trace.\n"
" call-delay: call + delay, only for nested-trace."),
OPT_BOOLEAN_SET ('S', "interruptible", &env.interruptible, &env.interruptible_set, "TASK_INTERRUPTIBLE, no- prefix to exclude"),
OPT_BOOL_NONEG ('D', "uninterruptible", &env.uninterruptible, "TASK_UNINTERRUPTIBLE"),
OPT_PARSE_NONEG ( LONG_OPT_than, "than", &env.greater_than, "ns", "Greater than specified time, Unit: s/ms/us/*ns/percent"),
OPT_PARSE_NONEG ( LONG_OPT_only_than, "only-than", &env.greater_than,"ns", "Only print those that are greater than the specified time."),
OPT_PARSE_NONEG ( LONG_OPT_lower, "lower", &env.lower_than, "ns", "Lower than specified time, Unit: s/ms/us/*ns"),
OPT_STRDUP_NONEG( 0 , "alloc", &env.tp_alloc, "EVENT", "Memory alloc tracepoint/kprobe/uprobe"),
OPT_STRDUP_NONEG( 0 , "free", &env.tp_free, "EVENT", "Memory free tracepoint/kprobe/uprobe"),
OPT_BOOL_NONEG ( 0 , "syscalls", &env.syscalls, "Trace syscalls"),
OPT_BOOL_NONEG ( 0 , "perins", &env.perins, "Print per instance stat"),
OPT_BOOL_NONEG ('g', "call-graph", &env.callchain, "Enable call-graph recording"),
OPT_STRDUP_NONEG( 0 , "flame-graph", &env.flame_graph, "file", "Specify the folded stack file."),
OPT_STRDUP_NONEG( 0 , "heatmap", &env.heatmap, "file", "Specify the output latency file."),
OPT_PARSE_OPTARG( LONG_OPT_detail, "detail", NULL, "-N,+N,hide<N,same*",
"More detailed information output.\n"
"For multi-trace profiler:\n"
" -N: Before event1, print events within N nanoseconds.\n"
" +N: After event2, print events within N nanoseconds.\n"
"hide<N: Hide event intervals less than N nanoseconds.\n"
"samecpu: Only show events with the same cpu as event1 or event2.\n"
"samepid: Only show events with the same pid as event1 or event2.\n"
"sametid: Only show events with the same tid as event1 or event2.\n"
"samekey: Only show events with the same key as event1 or event2."),
OPT_INT_NONEG ('T', "trigger", &env.trigger_freq, NULL, "Trigger Threshold, No trigger: 0"),
OPT_BOOL_NONEG ( 0 , "test", &env.test, "Split-lock test verification"),
OPT_STRDUP_NONEG( 0 , "symbols", &env.symbols, NULL, "Maps addresses to symbol names.\n"
"Similar to pprof --symbols."),
OPT_STRDUP_NONEG('d', "device", &env.device, "device", "Block device, /dev/sdx"),
OPT_INT_NONEG ( 0 , "ldlat", &env.ldlat, "cycles", "mem-loads latency, Unit: cycles"),
OPT_BOOL_NONEG ( 0 , "overwrite", &env.overwrite, "use overwrite mode"),
OPT_BOOL_NONEG ( 0 , "spte", &env.spte, "kvmmmu: enable kvmmmu:kvm_mmu_set_spte"),
OPT_BOOL_NONEG ( 0 , "mmio", &env.mmio, "kvmmmu: enable kvmmmu:mark_mmio_spte"),
OPT_BOOL_NONEG ( 0 , "only-comm", &env.only_comm, "top: only show comm but not key"),
OPT_BOOL_NONEG ( 0 , "cycle", &env.cycle, "multi-trace: event cycle, from the last one back to the first."),
OPT_BOOL_NONEG ( 0 , "ptrace", &env.using_ptrace, "Use ptrace to track newly created threads."),
OPT_END()
};
const char * const main_usage[] = {
PROGRAME " profiler [PROFILER OPTION...] [help] [cmd [args...]]",
PROGRAME " --symbols /path/to/bin",
"",
"Profiling based on perf_event and ebpf",
NULL
};
static void free_env(struct env *e)
{
if (e->nr_events) {
while (e->nr_events--) free(e->events[e->nr_events]);
free(e->events);
}
if (e->cpumask) free(e->cpumask);
if (e->pids) free(e->pids);
if (e->tids) free(e->tids);
if (e->cgroups) free(e->cgroups);
if (e->output) free(e->output);
if (e->key) free(e->key);
if (e->filter) free(e->filter);
if (e->impl) free(e->impl);
if (e->tp_alloc) free(e->tp_alloc);
if (e->tp_free) free(e->tp_free);
if (e->flame_graph) free(e->flame_graph);
if (e->heatmap) free(e->heatmap);
if (e->symbols) free(e->symbols);
if (e->device) free(e->device);
if (e->kvmclock) free(e->kvmclock);
if (e->perfeval_cpus) free(e->perfeval_cpus);
if (e->perfeval_pids) free(e->perfeval_pids);
if (e->workload.pid > 0) {
kill(e->workload.pid, SIGTERM);
}
if (e != &env) free(e);
else
memset(e, 0, sizeof(*e));
}
struct env *clone_env(struct env *p)
{
struct env *e = malloc(sizeof(*e));
if (!e) return NULL;
*e = *p;
e->workload.cork_fd = 0;
e->workload.pid = 0;
e->help_monitor = NULL;
if (e->nr_events) {
int i;
e->events = calloc(e->nr_events, sizeof(*e->events));
e->nr_events = 0;
if (!e->events) goto failed;
for (i = 0 ; i < p->nr_events; i++) {
e->events[i] = strdup(p->events[i]);
if (!e->events[i]) goto failed;
e->nr_events ++;
}
e->event = e->events[0];
}
#define CLONE(f) if (e->f) {e->f = strdup(e->f); if (!e->f) goto failed;}
CLONE (cpumask);
CLONE (pids);
CLONE (tids);
CLONE (cgroups);
CLONE (output);
CLONE (key);
CLONE (filter);
CLONE (impl);
CLONE (tp_alloc);
CLONE (tp_free);
CLONE (flame_graph);
CLONE (heatmap);
CLONE (symbols);
CLONE (device);
CLONE (kvmclock);
CLONE (perfeval_cpus);
CLONE (perfeval_pids);
return e;
failed:
free_env(e);
return NULL;
}
void help(void)
{
int argc = 2;
const char *argv[] = {PROGRAME, "--help"};
const char * const *usagestr = main_usage;
struct monitor *m = monitor;
if (m) {
if (m->argv && m->desc) {
argc = 0;
while (m->argv[argc++] != NULL);
parse_options(argc - 1, m->argv, main_options, m->desc, PARSE_OPT_INTERNAL_HELP_NO_ORDER);
} else
parse_options(argc, argv, main_options, main_usage, PARSE_OPT_INTERNAL_HELP_NO_ORDER);
}
fprintf(stderr, "\n Usage: %s\n", *usagestr++);
while (*usagestr && **usagestr)
fprintf(stderr, " or: %s\n", *usagestr++);
while (*usagestr) {
fprintf(stderr, "%s%s\n",
**usagestr ? " " : "",
*usagestr);
usagestr++;
}
fprintf(stderr, "\n Available Profilers:\n");
while((m = monitor_next(m))) {
fprintf(stderr, " %-20s", m->name);
if (m->desc && m->desc[2] && m->desc[2][0])
fprintf(stderr, " %s\n", m->desc[2]);
else
fprintf(stderr, "\n");
}
fprintf(stderr, "\n See '%s profiler -h' for more information on a specific profiler.\n\n", PROGRAME);
exit(129);
}
static void disable_help(void)
{
struct option *opts = main_options;
for (; opts->type != OPTION_END; opts++) {
if (opts->short_name == 'h') {
opts->short_name = 0;
opts->long_name = "disable-help";
}
}
}
static void flush_main_options(profiler *p)
{
struct option *opts;
int i;
if (!p->argv)
return ;
// disable all opts
opts = main_options;
for (; opts->type != OPTION_END; opts++) {
opts->flags |= PARSE_OPT_DISABLED;
}
// enable profiler opts
opts = main_options;
for (; opts->type != OPTION_END; opts++) {
for (i = 2/*PROGRAME, "-h"*/; p->argv[i]; i ++) {
if (p->argv[i][1] == '\0' &&
opts->short_name < 256 && isalnum(opts->short_name) && /* isshort */
p->argv[i][0] == opts->short_name)
goto enable;
if (opts->long_name && strcmp(opts->long_name, p->argv[i]) == 0)
goto enable;
if (opts->type == OPTION_GROUP && strcmp(opts->help, p->argv[i]) == 0)
goto enable;
}
continue;
enable:
opts->flags &= (~PARSE_OPT_DISABLED);
}
}
#ifndef CONFIG_LIBBPF
static const char *LIBBPF_BUILD = "NO CONFIG_LIBBPF=y";
#endif
static profiler *parse_main_options(int argc, char *argv[])
{
profiler *prof = NULL;
bool stop_at_non_option = true;
bool dashdash = false;
char *COMP_TYPE = getenv("COMP_TYPE"); // Bash Completion COMP_TYPE variable
int comp_type = COMP_TYPE ? atoi(COMP_TYPE) : 0;
bool enable_optcomp = false;
#ifndef CONFIG_LIBBPF
set_option_nobuild(main_options, 0, "irqs_disabled", LIBBPF_BUILD, true);
set_option_nobuild(main_options, 0, "tif_need_resched", LIBBPF_BUILD, true);
set_option_nobuild(main_options, 0, "exclude_pid", LIBBPF_BUILD, true);
set_option_nobuild(main_options, 0, "nr_running_min", LIBBPF_BUILD, true);
set_option_nobuild(main_options, 0, "nr_running_max", LIBBPF_BUILD, true);
#endif
while (argc > 0) {
argc = parse_options(argc, (const char **)argv, main_options, main_usage,
PARSE_OPT_NO_INTERNAL_HELP | PARSE_OPT_KEEP_DASHDASH |
(enable_optcomp ? PARSE_OPT_BASH_COMPLETION : 0) |
(stop_at_non_option ? PARSE_OPT_STOP_AT_NON_OPTION :
PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN));
if (argc && argv[0][0] != '\0' && argv[0][0] != '-') {
struct monitor *m = monitor_find(argv[0]);
if (m != NULL) {
if (strcmp(m->name, "help") == 0)
env.help_monitor = prof;
else if (prof) {
#ifdef MULTI_PROF
struct env *e = zalloc(sizeof(struct env));
if (e) {
*e = env;
prof_dev_open(prof, e);
}
memset(&env, 0, sizeof(struct env));
#else
goto stop_at;
#endif
}
prof = m;
monitor = m; // monitor only used in help();
flush_main_options(m);
enable_optcomp = comp_type ? true : false;
continue;
} else if (comp_type) {
break;
} else stop_at: if (stop_at_non_option) {
stop_at_non_option = false;
disable_help();
continue;
}
}
if (comp_type)
break;
// --
if (argc && argv[0][0] == '-' && argv[0][1] == '-') {
argc--;
memmove(argv, argv + 1, argc * sizeof(argv[0]));
argv[argc] = NULL;
dashdash = true;
}
break;
}
if (comp_type) {
if (prof) {
if (argc == 0)
printf(prof->compgen ? "\"%s %s\"\n" : "%s%s\n", prof->name, prof->compgen ?: "");
} else {
struct monitor *m = NULL;
while((m = monitor_next(m))) {
if (!argc || argv[0][0] == '\0' ||
strncmp(m->name, argv[0], strlen(argv[0])) == 0) {
if (m->compgen && comp_type != '?')
printf("\"%s %s\"\n", m->name, m->compgen);
else
printf("%s\n", m->name);
}
}
}
exit(0);
}
if (env.symbols) {
syms__convert(stdin, stdout, env.symbols);
exit(0);
}
if (prof == NULL)
help();
if (!dashdash) {
if (prof && prof->argc_init)
argc = prof->argc_init(argc, argv);
else if (argc && env.verbose > 0) {
int i;
printf("Unparsed options:");
for (i = 0; i < argc; i ++)
printf(" %s", argv[i]);
printf("\n");
}
}
if (argc > 0) {
if (workload_prepare(&env.workload, argv) < 0)
goto failed;
}
return prof;
failed:
free_env(&env);
return NULL;
}
struct env *parse_string_options(char *str)
{
char *token;
int argc = 1; // argv[0] = "perf-prof"
char **argv = malloc((argc + 1)*sizeof(char*));
struct env *e = NULL;
token = strtok(str, " ");
while (token && argv) {
argv[argc++] = token;
argv = realloc(argv, (argc + 1)*sizeof(char*));
token = strtok(NULL, " ");
}
if (!argv)
return NULL;
memset(&env, 0, sizeof(struct env));
if (parse_main_options(argc, argv)) {
e = malloc(sizeof(*e));
if (e) *e = env;
}
free(argv);
return e;
}
static char *perf_type_str(int type)
{
static int nr_types = 0;
static char **perf_types = NULL;
if (!nr_types) {
char path[PATH_MAX];
struct dirent **namelist = NULL;
int i, items, n, type;
n = snprintf(path, PATH_MAX, "%s/bus/event_source/devices/", sysfs__mountpoint());
items = scandir(path, &namelist, NULL, NULL);
if (items <= 0)
return NULL;
for (i = 0; i < items; i++) {
if (namelist[i]->d_name[0] == '.')
continue;
snprintf(path+n, PATH_MAX-n, "%s/type", namelist[i]->d_name);
if (filename__read_int(path, &type) == 0) {
int nr = type + 1;
if (nr_types < nr) {
perf_types = realloc(perf_types, nr*sizeof(*perf_types));
if (!perf_types) goto failed;
memset(perf_types+nr_types, 0, (nr-nr_types)*sizeof(*perf_types));
nr_types = nr;
}
perf_types[type] = strdup(namelist[i]->d_name);
}
}
failed:
for (i = 0; i < items; i++)
free(namelist[i]);
free(namelist);
}
return type < nr_types ? perf_types[type] : NULL;
}
static void print_event(struct perf_event_attr *attr)
{
const char *str = "unknown";
if (attr->type == PERF_TYPE_HARDWARE) {
switch (attr->config) {
case PERF_COUNT_HW_CPU_CYCLES: str = "cpu-cycles"; break;
case PERF_COUNT_HW_INSTRUCTIONS: str = "instructions"; break;
case PERF_COUNT_HW_CACHE_REFERENCES: str = "cache-references"; break;
case PERF_COUNT_HW_CACHE_MISSES: str = "cache-misses"; break;
case PERF_COUNT_HW_BRANCH_INSTRUCTIONS: str = "branch-instructions"; break;
case PERF_COUNT_HW_BRANCH_MISSES: str = "branch-misses"; break;
case PERF_COUNT_HW_BUS_CYCLES: str = "bus-cycles"; break;
case PERF_COUNT_HW_STALLED_CYCLES_FRONTEND: str = "stalled-frontend"; break;
case PERF_COUNT_HW_STALLED_CYCLES_BACKEND: str = "stalled-backend"; break;
case PERF_COUNT_HW_REF_CPU_CYCLES: str = "ref-cpu-cycles"; break;
default: break;
}
printf("%s", str);
} else if (attr->type == PERF_TYPE_SOFTWARE) {
switch (attr->config) {
case PERF_COUNT_SW_CPU_CLOCK: str = "cpu-clock"; break;
case PERF_COUNT_SW_TASK_CLOCK: str = "task-clock"; break;
case PERF_COUNT_SW_PAGE_FAULTS: str = "page-faults"; break;
case PERF_COUNT_SW_CONTEXT_SWITCHES: str = "context-switches"; break;
case PERF_COUNT_SW_CPU_MIGRATIONS: str = "cpu-migrations"; break;
case PERF_COUNT_SW_PAGE_FAULTS_MIN: str = "page-faults-min"; break;
case PERF_COUNT_SW_PAGE_FAULTS_MAJ: str = "page-faults-maj"; break;
case PERF_COUNT_SW_ALIGNMENT_FAULTS: str = "alignment-faults"; break;
case PERF_COUNT_SW_EMULATION_FAULTS: str = "emulation-faults"; break;
case PERF_COUNT_SW_DUMMY: str = "dummy"; break;
case PERF_COUNT_SW_BPF_OUTPUT: str = "bpf-output"; break;
case PERF_COUNT_SW_CGROUP_SWITCHES: str = "cgroup-switches"; break;
default: break;
}
printf("%s", str);
} else if (attr->type == PERF_TYPE_TRACEPOINT) {
struct tep_event *e = tep_find_event(tep__ref(), (int)attr->config);
if (e) printf("%s:%s", e->system, e->name);
tep__unref();
} else if (attr->type == PERF_TYPE_RAW) {
printf("raw:0x%lx", (long)attr->config);
} else if (attr->type == PERF_TYPE_BREAKPOINT) {
printf("breakpoint");
} else {
printf("%s", perf_type_str(attr->type) ?: "unknown");
}
}
static void print_thread(struct perf_thread_map *threads)