forked from andikleen/pmu-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
toplev.py
executable file
·1635 lines (1431 loc) · 54.8 KB
/
toplev.py
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
#!/usr/bin/env python
# Copyright (c) 2012-2016, Intel Corporation
# Author: Andi Kleen
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU General Public License,
# version 2, as published by the Free Software Foundation.
#
# This program is distributed in the hope it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# Measure a workload using the topdown performance model:
# estimate on which part of the CPU pipeline it bottlenecks.
#
# Must find ocperf in python module path. add to paths below if needed.
# Handles a variety of perf and kernel versions, but older ones have various
# limitations.
import sys, os, re, itertools, textwrap, platform, pty, subprocess
import exceptions, argparse, time, types, fnmatch, csv, copy
from collections import defaultdict, Counter
from tl_stat import combine_valstat, ComputeStat, ValStat
from tl_cpu import CPU
import tl_output
import ocperf
known_cpus = (
("snb", (42, )),
("jkt", (45, )),
("ivb", (58, )),
("ivt", (62, )),
("hsw", (60, 70, 69 )),
("hsx", (63, )),
("slm", (55, 77, 76, )),
("bdw", (61, 71, )),
("bdx", (79, 86, )),
("simple", ()),
("skl", (94, 78, 142, 158, )),
)
tsx_cpus = ("hsw", "hsx", "bdw", "skl")
fixed_to_num = {
"instructions" : 0,
"cycles" : 1,
"cpu/event=0x3c,umask=0x00,any=1/": 1,
"cpu/event=0x3c,umask=0x0,any=1/": 1,
"ref-cycles" : 2,
"cpu/event=0x0,umask=0x3,any=1/" : 2,
}
# handle kernels that don't support all events
unsup_pebs = (
("BR_MISP_RETIRED.ALL_BRANCHES:pp", (("hsw",), (3, 18), None)),
("MEM_LOAD_UOPS_L3_HIT_RETIRED.XSNP_HITM:pp", (("hsw",), (3, 18), None)),
("MEM_LOAD_UOPS_RETIRED.L3_MISS:pp", (("hsw",), (3, 18), None)),
)
ivb_ht_39 = (("ivb", "ivt"), (4, 1), (3, 9))
# uncomment if you removed commit 741a698f420c3
#ivb_ht_39 = ((), None, None)
# both kernel bugs and first time a core was supported
# disable events if the kernel does not support them properly
# this does not handle backports (override with --force-events)
unsup_events = (
# commit 36bbb2f2988a29
("OFFCORE_RESPONSE.DEMAND_RFO.L3_HIT.HITM_OTHER_CORE", (("hsw", "hsx"), (3, 18), None)),
# commit 741a698f420c3 broke it, commit e979121b1b and later fixed it
("MEM_LOAD_UOPS_L*_HIT_RETIRED.*", ivb_ht_39),
("MEM_LOAD_UOPS_RETIRED.*", ivb_ht_39),
("MEM_LOAD_UOPS_L*_MISS_RETIRED.*", ivb_ht_39),
("MEM_UOPS_RETIRED.*", ivb_ht_39),
# commit 5e176213a6b2bc
# the event works, but it cannot put into the same group as
# any other CYCLE_ACTIVITY.* event. For now black list, but
# could also special case this in the group scheduler.
("CYCLE_ACTIVITY.STALLS_TOTAL", (("bdw", (4, 4), None))),
# commit 91f1b70582c62576
("CYCLE_ACTIVITY.*", (("bdw"), (4, 1), None)),
("L1D_PEND_MISS.PENDING", (("bdw"), (4, 1), None)),
# commit 6113af14c8
("CYCLE_ACTIVITY:CYCLES_LDM_PENDING", (("ivb", "ivt"), (3, 12), None)),
# commit f8378f52596477
("CYCLE_ACTIVITY.*", (("snb", "jkt"), (3, 9), None)),
# commit 0499bd867bd17c (ULT) or commit 3a632cb229bfb18 (other)
# technically most haswells are 3.10, but ULT is 3.11
("L1D_PEND_MISS.PENDING", (("hsw",), (3, 11), None)),
("L1D_PEND_MISS.PENDING", (("hsx"), (3, 10), None)),
# commit c420f19b9cdc
("CYCLE_ACTIVITY.*_L1D_PENDING", (("hsw", "hsx"), (4, 1), None)),
("CYCLE_ACTIVITY.CYCLES_NO_EXECUTE", (("hsw", "hsx"), (4, 1), None)),
# commit 3a632cb229b
("CYCLE_ACTIVITY.*", (("hsw", "hsx"), (3, 11), None)))
errata_whitelist = {
"BDE69", "BDE70",
}
ingroup_events = frozenset(fixed_to_num.keys())
outgroup_events = set(["dummy"])
nonperf_events = set(["interval-ns", "mux"])
valid_events = [r"cpu/.*?/", "uncore.*?/.*?/", "ref-cycles",
r"r[0-9a-fA-F]+", "cycles", "instructions", "dummy"]
# workaround for broken event files for now
event_fixes = {
"UOPS_EXECUTED.CYCLES_GE_1_UOPS_EXEC": "UOPS_EXECUTED.CYCLES_GE_1_UOP_EXEC",
"UOPS_EXECUTED.CYCLES_GE_1_UOP_EXEC": "UOPS_EXECUTED.CYCLES_GE_1_UOPS_EXEC"
}
smt_domains = ("Slots", "CoreClocks", "CoreMetric")
limited_counters = {
"cpu/cycles-ct/": 2,
}
limited_set = set(limited_counters.keys())
smt_mode = False
errata_events = dict()
perf = os.getenv("PERF")
if not perf:
perf = "perf"
def works(x):
return os.system(x + " >/dev/null 2>/dev/null") == 0
class PerfFeatures:
"""Adapt to the quirks of various perf versions."""
def __init__(self):
self.logfd_supported = works(perf + " stat --log-fd 3 3>/dev/null true")
if not self.logfd_supported:
sys.exit("perf binary is too old. please upgrade")
self.supports_power = works(perf + " list | grep -q power/")
def kv_to_key(v):
return v[0] * 100 + v[1]
def unsup_event(e, table, min_kernel=None):
if ":" in e:
e = e[:e.find(":")]
for j in table:
if fnmatch.fnmatch(e, j[0]) and cpu.realcpu in j[1][0]:
break
else:
return False
v = j[1]
if v[1] and kv_to_key(kernel_version) < kv_to_key(v[1]):
if min_kernel:
min_kernel.append(v[1])
return True
if v[2] and kv_to_key(kernel_version) >= kv_to_key(v[2]) :
return True
return False
def needed_limited_counter(evlist, limit_table, limit_set):
limited_only = set(evlist) & set(limit_set)
assigned = Counter([limit_table[x] for x in limited_only]).values()
# 0..1 counter is ok
# >1 counter is over subscribed
return sum([x - 1 for x in assigned if x > 1])
def fixed_overflow(evlist):
return needed_limited_counter(evlist, fixed_to_num, ingroup_events)
def limit_overflow(evlist):
return needed_limited_counter(evlist, limited_counters, limited_set)
def needed_counters(evlist):
evset = set(evlist)
num_generic = len(evset - ingroup_events - limited_set)
# If we need more than 3 fixed counters (happens with any vs no any)
# promote those to generic counters
num = num_generic + fixed_overflow(evlist)
# account events that only schedule on one of the generic counters
# first allocate the limited counters that are not oversubscribed
num_limit = limit_overflow(evlist)
num += len(evset & limited_set) - num_limit
# if we need more than one of a limited counter make it look
# like it fills the group to limit first before adding them to force
# a split
if num_limit > 0:
num = max(num, cpu.counters) + num_limit
return num
def event_group(evlist):
e = ",".join(add_filter(evlist))
if not args.no_group and 1 < needed_counters(evlist) <= cpu.counters:
e = "{%s}" % (e,)
return e
def exe_dir():
d = os.path.dirname(sys.argv[0])
if d:
return d
return "."
feat = PerfFeatures()
emap = ocperf.find_emap()
if not emap:
sys.exit("Unknown CPU or CPU event map not found.")
p = argparse.ArgumentParser(usage='toplev [options] perf-arguments',
description='''
Estimate on which part of the CPU pipeline a workload bottlenecks using the TopDown model.
The bottlenecks are expressed as a tree with different levels.
Requires a modern Intel CPU.
Examples:
toplev.py -l2 program
measure whole system in level 2 while program is running
toplev.py -l1 --single-thread program
measure single threaded program. system must be idle.
toplev.py -l3 --no-desc -I 100 -x, sleep X
measure whole system for X seconds every 100ms, outputting in CSV format.
toplev.py --all --core C0 taskset -c 0,1 program
Measure program running on core 0 with all nodes and metrics enables
''', epilog='''
Other perf arguments allowed (see the perf documentation)
After -- perf arguments conflicting with toplev can be used.
Some caveats:
toplev defaults to measuring the full system and show data
for all CPUs. Use taskset to limit the workload to known CPUs if needed.
In some cases (idle system, single threaded workload) --single-thread
can also be used.
The lower levels of the measurement tree are less reliable
than the higher levels. They also rely on counter multi-plexing,
and can not run each equation in a single group, which can cause larger
measurement errors with non steady state workloads
(If you don't understand this terminology; it means measurements
in higher levels are less accurate and it works best with programs that primarily
do the same thing over and over)
If the program is very reproducible -- such as a simple kernel --
it is also possible to use --no-multiplex. In this case the
workload is rerun multiple times until all data is collected.
Do not use together with sleep.
toplev needs a new enough perf tool and has specific requirements on
the kernel. See http://github.com/andikleen/pmu-tools/wiki/toplev-kernel-support
Other CPUs can be forced with FORCECPU=name
This usually requires setting the correct event map with EVENTMAP=...
Valid CPU names: ''' + " ".join([x[0] for x in known_cpus]),
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('--verbose', '-v', help='Print all results even when below threshold or exceeding boundaries. Note this can result in bogus values, as the TopDown methodology relies on thresholds to correctly characterize workloads.',
action='store_true')
p.add_argument('--kernel', help='Only measure kernel code', action='store_true')
p.add_argument('--user', help='Only measure user code', action='store_true')
p.add_argument('--print-group', '-g', help='Print event group assignments',
action='store_true')
p.add_argument('--no-desc', help='Do not print event descriptions', action='store_true')
p.add_argument('--csv', '-x', help='Enable CSV mode with specified delimeter')
p.add_argument('--interval', '-I', help='Enable interval mode with ms interval',
type=int)
p.add_argument('--output', '-o', help='Set output file', default=sys.stderr,
type=argparse.FileType('w'))
p.add_argument('--graph', help='Automatically graph interval output with tl-barplot.py',
action='store_true')
p.add_argument("--graph-cpu", help="CPU to graph using --graph")
p.add_argument('--title', help='Set title of graph')
p.add_argument('--xkcd', help='Use xkcd plotting mode for graph', action='store_true')
p.add_argument('--level', '-l', help='Measure upto level N (max 5)',
type=int, default=1)
p.add_argument('--detailed', '-d', help=argparse.SUPPRESS, action='store_true')
p.add_argument('--metrics', '-m', help="Print extra metrics", action='store_true')
p.add_argument('--raw', help="Print raw values", action='store_true')
p.add_argument('--sw', help="Measure perf Linux metrics", action='store_true')
p.add_argument('--no-util', help="Do not measure CPU utilization", action='store_true')
p.add_argument('--cpu', '-C', help=argparse.SUPPRESS)
p.add_argument('--pid', '-p', help=argparse.SUPPRESS)
p.add_argument('--tsx', help="Measure TSX metrics", action='store_true')
p.add_argument('--all', help="Measure everything available", action='store_true')
p.add_argument('--frequency', help="Measure frequency", action='store_true')
p.add_argument('--repl', action='store_true', help=argparse.SUPPRESS)
p.add_argument('--no-group', help='Dont use groups', action='store_true')
p.add_argument('--no-multiplex',
help='Do not multiplex, but run the workload multiple times as needed. Requires reproducible workloads.',
action='store_true')
p.add_argument('--show-sample', help='Show command line to rerun workload with sampling', action='store_true')
p.add_argument('--run-sample', help='Automatically rerun workload with sampling', action='store_true')
p.add_argument('--sample-args', help='Extra rguments to pass to perf record for sampling. Use + to specify -', default='-g')
p.add_argument('--sample-repeat', help='Repeat measurement and sampling N times. This interleaves counting and sampling', type=int)
p.add_argument('--sample-basename', help='Base name of sample perf.data files', default="perf.data")
p.add_argument('--valcsv', '-V', help='Write raw counter values into CSV file', type=argparse.FileType('w'))
p.add_argument('--stats', help='Show statistics on what events counted', action='store_true')
p.add_argument('--power', help='Display power metrics', action='store_true')
p.add_argument('--version', help=argparse.SUPPRESS, action='store_true')
p.add_argument('--debug', help=argparse.SUPPRESS, action='store_true')
p.add_argument('--core', help='Limit output to cores. Comma list of Sx-Cx-Tx. All parts optional.')
p.add_argument('--single-thread', '-S', help='Measure workload as single thread. Workload must run single threaded. In SMT mode other thread must be idle.', action='store_true')
p.add_argument('--long-desc', help='Print long descriptions instead of abbreviated ones.',
action='store_true')
p.add_argument('--force-events', help='Assume kernel supports all events. May give wrong results.', action='store_true')
p.add_argument('--columns', help='Print CPU output in multiple columns', action='store_true')
p.add_argument('--nodes', help='Include or exclude nodes (with + to add, ^ to remove, comma separated list, wildcards allowed)')
p.add_argument('--quiet', help='Avoid unnecessary status output', action='store_true')
p.add_argument('--bottleneck', help='Show critical bottleneck', action='store_true')
p.add_argument('--reduced', help='Use reduced server subset of nodes/metrics', action='store_true')
p.add_argument('--ignore-errata', help='Do not disable events with errata', action='store_true')
args, rest = p.parse_known_args()
rest = [x for x in rest if x != "--"]
if args.version:
print "toplev"
sys.exit(0)
if len(rest) == 0:
p.print_help()
sys.exit(0)
if args.all:
args.tsx = True
args.power = True
args.sw = True
args.metrics = True
args.frequency = True
args.level = 5
if args.graph:
if not args.interval:
args.interval = 100
extra = ""
if args.title:
title = args.title
else:
title = "cpu %s" % (args.graph_cpu if args.graph_cpu else 0)
extra += '--title "' + title + '" '
if args.xkcd:
extra += '--xkcd '
if args.output != sys.stderr:
extra += '--output "' + args.output.name + '" '
if args.graph_cpu:
extra += "--cpu " + args.graph_cpu + " "
args.csv = ','
cmd = "PATH=$PATH:%s ; tl-barplot.py %s /dev/stdin" % (exe_dir(), extra)
if not args.quiet:
print cmd
args.output = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE).stdin
if args.sample_repeat:
args.run_sample = True
print_all = args.verbose # or args.csv
dont_hide = args.verbose
detailed_model = (args.level > 1) or args.detailed
csv_mode = args.csv
interval_mode = args.interval
ring_filter = ""
if args.kernel:
ring_filter = 'k'
if args.user:
ring_filter = 'u'
if args.user and args.kernel:
ring_filter = None
print_group = args.print_group
if args.cpu:
rest = ["--cpu", args.cpu] + rest
if args.pid:
rest = ["--pid", args.pid] + rest
MAX_ERROR = 0.05
def check_ratio(l):
if print_all:
return True
return 0 - MAX_ERROR < l < 1 + MAX_ERROR
cpu = CPU(known_cpus)
def print_perf(r):
if args.quiet:
return
l = ["'" + x + "'" if x.find("{") >= 0 else x for x in r]
l = [x.replace(";", "\;") for x in l]
i = l.index('--log-fd')
del l[i:i+2]
print " ".join(l)
sys.stdout.flush()
class PerfRun:
"""Control a perf subprocess."""
def execute(self, r):
outp, inp = pty.openpty()
n = r.index("--log-fd")
r[n + 1] = "%d" % (inp)
print_perf(r)
self.perf = subprocess.Popen(r)
os.close(inp)
return os.fdopen(outp, 'r')
def wait(self):
ret = 0
if self.perf:
ret = self.perf.wait()
return ret
fixed_counters = {
"CPU_CLK_UNHALTED.THREAD": "cycles",
"CPU_CLK_UNHALTED.THREAD:amt1": "cpu/event=0x3c,umask=0x0,any=1/",
"INST_RETIRED.ANY": "instructions",
"CPU_CLK_UNHALTED.REF_TSC": "ref-cycles",
"CPU_CLK_UNHALTED.REF_TSC:amt1": "cpu/event=0x0,umask=0x3,any=1/",
"CPU_CLK_UNHALTED.REF_TSC:sup": "cpu/event=0x0,umask=0x3/k",
"CPU_CLK_UNHALTED.REF_TSC:SUP": "cpu/event=0x0,umask=0x3/k",
}
fixed_set = frozenset(fixed_counters.keys())
fixed_to_name = dict(zip(fixed_counters.values(), fixed_counters.keys()))
def separator(x):
if x.startswith("cpu"):
return ""
return ":"
def add_filter_event(e):
if "/" in e and not e.startswith("cpu"):
return e
s = separator(e)
if not e.endswith(s + ring_filter):
return e + s + ring_filter
return e
def add_filter(s):
if ring_filter:
s = map(add_filter_event, s)
return s
notfound_cache = set()
def raw_event(i, name="", period=False):
orig_i = i
if i.count(".") > 0:
if i in fixed_counters:
return fixed_counters[i]
e = emap.getevent(i)
if e is None:
if i in event_fixes:
e = emap.getevent(event_fixes[i])
if e is None:
if i not in notfound_cache:
notfound_cache.add(i)
print >>sys.stderr, "%s not found" % (i,)
return "dummy"
oi = i
i = e.output(noname=True, name=name, period=period)
if len(re.findall(r'[a-z0-9_]+/.*?/[a-z]*', i)) > 1:
print "Event", oi, "maps to multiple units. Ignored."
return "dummy" # FIXME
emap.update_event(e.output(noname=True), e)
# next three things should be moved somewhere else
if i.startswith("uncore"):
outgroup_events.add(i)
if e.counter != cpu.standard_counters and not e.counter.startswith("Fixed"):
# for now use the first counter only to simplify
# the assignment. This is sufficient for current
# CPUs
limited_counters[i] = int(e.counter.split(",")[0])
limited_set.add(i)
if e.errata and e.errata in errata_whitelist:
errata_events[orig_i] = e.errata
return i
# generate list of converted raw events from events string
def raw_events(evlist):
return map(raw_event, evlist)
def mark_fixed(s):
r = raw_event(s)
if r in ingroup_events:
return "%s[F]" % s
return s
def pwrap(s, linelen=70, indent=""):
print indent + ("\n" + indent).join(textwrap.wrap(s, linelen, break_long_words=False))
def pwrap_not_quiet(s, linelen=70, indent=""):
if not args.quiet:
pwrap(s, linelen, indent)
def has(obj, name):
return name in obj.__class__.__dict__
def flatten(x):
return itertools.chain(*x)
def print_header(work, evlist):
evnames0 = [obj.evlist for obj in work]
evnames = set(flatten(evnames0))
names = ["%s[%d]" % (obj.__class__.__name__, obj.__class__.level if has(obj, 'level') else 0) for obj in work]
pwrap(" ".join(names) + ":", 78)
pwrap(" ".join(map(mark_fixed, evnames)).lower() +
" [%d counters]" % (needed_counters(raw_events(evnames))), 75, " ")
def perf_args(evstr, rest):
add = []
if interval_mode:
add += ['-I', str(interval_mode)]
return [perf, "stat", "-x;", "--log-fd", "X", "-e", evstr] + add + rest
def setup_perf(evstr, rest):
prun = PerfRun()
inf = prun.execute(perf_args(evstr, rest))
return inf, prun
class Stat:
def __init__(self):
self.total = 0
self.errors = Counter()
def print_not(a, count , msg, j):
print >>sys.stderr, ("%s %s %s %.2f%% in %d measurements"
% (emap.getperf(j), j, msg, 100.0 * (float(count) / float(a.total)), a.total))
# XXX need to get real ratios from perf
def print_account(ad):
total = Counter()
for j in ad:
a = ad[j]
for e in a.errors:
if args.stats:
print_not(a, a.errors[e], e, j)
total[e] += 1
if sum(total.values()) > 0 and not args.quiet:
print >>sys.stderr, ", ".join(["%d events %s" % (num, e) for e, num in total.iteritems()])
def event_regexp():
return "|".join(valid_events)
def is_event(l, n):
if len(l) <= n:
return False
return re.match(event_regexp(), l[n])
def set_interval(env, d):
env['interval-ns'] = d * 1e9
if args.raw:
print "interval-ns val", env['interval-ns']
def key_to_coreid(k):
x = cpu.cputocore[int(k)]
return x[0] * 1000 + x[1]
def core_fmt(core):
if cpu.sockets > 1:
return "S%d-C%d" % (core / 1000, core % 1000,)
return "C%d" % (core % 1000,)
def thread_fmt(j):
return core_fmt(key_to_coreid(j)) + ("-T%d" % cpu.cputothread[int(j)])
def display_core(cpunum, ignore_thread=False):
for match in args.core.split(","):
m = re.match(r'(?P<socket>S\d+)?-?(?P<core>C\d+)?-?(?P<thread>T\d+)?', match, re.I)
if not m:
sys.exit("Bad core match %s" % match)
def matching(name, mapping):
return mapping[cpunum] == int(m.group(name)[1:])
if m.group('socket') and not matching('socket', cpu.cputosocket):
continue
if m.group('core') and cpu.cputocore[cpunum][1] != int(m.group('core')[1:]):
continue
if not ignore_thread and m.group('thread') and not matching('thread', cpu.cputothread):
continue
return True
return False
def display_keys(runner, keys):
if len(keys) > 1 and smt_mode:
cores = [key_to_coreid(x) for x in keys if int(x) in runner.allowed_threads]
threads = map(thread_fmt, runner.allowed_threads)
all_cpus = list(set(map(core_fmt, cores) + threads))
else:
all_cpus = keys
if any(map(package_node, runner.olist)):
all_cpus += ["S%d" % x for x in range(cpu.sockets)]
return all_cpus
def print_keys(runner, res, rev, valstats, out, interval, env):
stat = runner.stat
out.set_cpus(display_keys(runner, res.keys()))
if smt_mode:
printed_cores = set()
for j in sorted(res.keys()):
if j != "" and int(j) not in runner.allowed_threads:
continue
runner.reset_thresh()
# collect counts from all threads of cores as lists
# this way the model can access all threads individually
core = key_to_coreid(j)
cpus = [x for x in res.keys() if key_to_coreid(x) == core]
combined_res = list(itertools.izip(*[res[x] for x in cpus]))
st = [combine_valstat(z) for z in itertools.izip(*[valstats[x] for x in cpus])]
# repeat a few times to get stable threshold values
# in case of mutual dependencies between SMT and non SMT
# XXX should use topological sort
used_stat = stat
for _ in range(3):
runner.compute(res[j], rev[j], valstats[j], env, thread_node, used_stat)
runner.compute(combined_res, rev[cpus[0]], st, env, core_node, used_stat)
used_stat = None
# print the SMT aware nodes
if core not in printed_cores:
runner.print_res(out, interval, core_fmt(core), core_node)
printed_cores.add(core)
# print the non SMT nodes
# recompute the nodes so we get up-to-date values
runner.print_res(out, interval, thread_fmt(j), thread_node)
if args.bottleneck:
runner.print_bottleneck(out, thread_fmt(j), not_package_node)
else:
for j in sorted(res.keys()):
if j != "" and int(j) not in runner.allowed_threads:
continue
runner.compute(res[j], rev[j], valstats[j], env, not_package_node, stat)
runner.print_res(out, interval, j, not_package_node)
if args.bottleneck:
runner.print_bottleneck(out, j, not_package_node)
packages = set()
for j in sorted(res.keys()):
if j == "":
continue
if int(j) not in runner.allowed_threads:
continue
p_id = cpu.cputosocket[int(j)]
if p_id in packages:
continue
packages.add(p_id)
runner.compute(res[j], rev[j], valstats[j], env, package_node, stat)
runner.print_res(out, interval, "S%d" % p_id, package_node)
# no bottlenecks from package nodes for now
out.flush()
stat.referenced_check(res)
stat.compute_errors()
def is_outgroup(x):
return set(x) - outgroup_events == set()
class SaveContext:
"""Save (some) environment context, in this case stdin seek offset to make < file work
when we reexecute the workload multiple times."""
def __init__(self):
try:
self.startoffset = sys.stdin.tell()
except exceptions.IOError:
self.startoffset = None
def restore(self):
if self.startoffset is not None:
sys.stdin.seek(self.startoffset)
def execute_no_multiplex(runner, out, rest):
if args.interval: # XXX
sys.exit('--no-multiplex is not supported with interval mode')
res = defaultdict(list)
rev = defaultdict(list)
valstats = defaultdict(list)
env = dict()
groups = [x for x in runner.evgroups if len(x) > 0]
num_runs = len(groups) - count(is_outgroup, groups)
outg = []
n = 0
ctx = SaveContext()
# runs could be further reduced by tweaking
# the scheduler to avoid any duplicated events
for g in groups:
if is_outgroup(g):
outg.append(g)
continue
n += 1
print "RUN #%d of %d" % (n, num_runs)
ret, res, rev, interval, valstats = do_execute(runner, outg + [g], out, rest,
res, rev, valstats, env)
ctx.restore()
outg = []
assert num_runs == n
print_keys(runner, res, rev, valstats, out, interval, env)
return ret
def execute(runner, out, rest):
env = dict()
events = filter(lambda x: len(x) > 0, runner.evgroups)
ctx = SaveContext()
ret, res, rev, interval, valstats = do_execute(runner, events,
out, rest,
defaultdict(list),
defaultdict(list),
defaultdict(list),
env)
ctx.restore()
print_keys(runner, res, rev, valstats, out, interval, env)
return ret
def group_number(num, events):
gnum = itertools.count(1)
def group_nums(group):
if all([x in outgroup_events for x in group]):
idx = 0
else:
idx = gnum.next()
return [idx] * len(group)
gnums = map(group_nums, events)
return list(flatten(gnums))[num]
def dump_raw(interval, title, event, val, index, events, stddev, multiplex):
if event in fixed_to_name:
ename = fixed_to_name[event].lower()
else:
ename = event_rmap(event)
gnum = group_number(index, events)
if args.raw:
print "raw", title, "event", event, "val", val, "ename", ename, "index", index, "group", gnum
if args.valcsv:
runner.valcsv.writerow((interval, title, gnum, ename, val, event, index, stddev, multiplex))
perf_fields = [
r"[0-9.]+",
r"<.*?>",
r"S\d+-C\d+?",
r"S\d+",
r"raw 0x[0-9a-f]+",
r"Joules",
""]
def do_execute(runner, events, out, rest, res, rev, valstats, env):
evstr = ",".join(map(event_group, events))
account = defaultdict(Stat)
inf, prun = setup_perf(evstr, rest)
prev_interval = 0.0
interval = None
start = time.time()
init_res = copy.deepcopy(res)
while True:
try:
l = inf.readline()
if not l:
break
l = l.strip()
# some perf versions break CSV output lines incorrectly for power events
if l.endswith("Joules"):
l2 = inf.readline()
l = l + l2.strip()
except exceptions.IOError:
# handle pty EIO
break
except KeyboardInterrupt:
continue
if interval_mode:
m = re.match(r"\s*([0-9.]+);(.*)", l)
if m:
interval = float(m.group(1))
l = m.group(2)
if interval != prev_interval:
if res:
set_interval(env, interval - prev_interval)
print_keys(runner, res, rev, valstats, out, prev_interval, env)
res = defaultdict(list)
rev = defaultdict(list)
valstats = defaultdict(list)
prev_interval = interval
n = l.split(";")
# filter out the empty unit field added by 3.14
n = filter(lambda x: x != "" and x != "Joules", n)
# timestamp is already removed
# -a --per-socket socket,numcpus,count,event,...
# -a --per-core core,numcpus,count,event,...
# -a -A cpu,count,event,...
# count,event,...
if is_event(n, 1):
title, count, event, off = "", n[0], n[1], 2
elif is_event(n, 3):
title, count, event, off = n[0], n[2], n[3], 4
elif is_event(n, 2):
title, count, event, off = n[0], n[1], n[2], 3
else:
print "unparseable perf output"
sys.stdout.write(l)
continue
title = title.replace("CPU", "")
# code later relies on stripping ku flags
event = event.replace("/k", "/").replace("/u", "/")
multiplex = float('nan')
event = event.rstrip()
if re.match(r"[0-9.]+", count):
val = float(count)
elif count.startswith("<"):
account[event].errors[count.replace("<","").replace(">","")] += 1
multiplex = 0.
val = 0
else:
print "unparseable perf count"
sys.stdout.write(l)
continue
# post fixes:
# ,xxx% -> -rXXX stddev
stddev = 0.
if len(n) > off and n[off].endswith("%"):
stddev = (float(n[off].replace("%", "").replace(",", ".")) / 100.) * val
off += 1
# ,xxx,yyy -> multiplexing in newer perf
if len(n) > off + 1:
multiplex = float(n[off + 1].replace(",", "."))
off += 2
st = ValStat(stddev=stddev, multiplex=multiplex)
account[event].total += 1
# power/uncore events are only output once for every socket. duplicate them
# to all cpus in the socket to make the result lists match
# unless we use -A ??
# also -C xxx causes them to be duplicated too, unless single thread
if ((event.startswith("power") or event.startswith("uncore")) and
title != "" and (not (args.core and not args.single_thread))):
cpunum = int(title)
socket = cpu.cputosocket[cpunum]
for j in cpu.sockettocpus[socket]:
if not args.core or display_core(j, True):
res["%d" % (j)].append(val)
rev["%d" % (j)].append(event)
valstats["%d" % (j)].append(st)
else:
res[title].append(val)
rev[title].append(event)
valstats[title].append(st)
if args.raw or args.valcsv:
dump_raw(interval if interval_mode else "",
title,
event,
val,
len(res[title]) - len(init_res[title]) - 1,
events, stddev, multiplex)
inf.close()
if 'interval-ns' not in env:
set_interval(env, time.time() - start)
ret = prun.wait()
print_account(account)
return ret, res, rev, interval, valstats
def ev_append(ev, level, obj):
if isinstance(ev, types.LambdaType):
return ev(lambda ev, level: ev_append(ev, level, obj), level)
if ev in nonperf_events:
return 99
if not (ev, level, obj.name) in obj.evlevels:
obj.evlevels.append((ev, level, obj.name))
if has(obj, 'nogroup') and obj.nogroup:
outgroup_events.add(ev.lower())
if not ev.startswith("cpu"):
# add first to overwrite more generic regexprs list r...
valid_events.insert(0, ev)
return 99
def canon_event(e):
m = re.match(r"(.*?):(.*)", e)
if m and m.group(2) != "amt1" and m.group(2) not in ("sup", "SUP"):
e = m.group(1)
if e in fixed_counters:
return fixed_counters[e]
if m:
e = m.group(1)
if e.endswith("_0"):
e = e[:-2]
return e.lower()
fixes = dict(zip(event_fixes.values(), event_fixes.keys()))
def event_rmap(e):
n = canon_event(emap.getperf(e))
if emap.getevent(n):
return n
if n.upper() in fixes:
n = fixes[n.upper()].lower()
if n:
return n
return "dummy"
def lookup_res(res, rev, ev, obj, env, level, referenced, cpuoff, st):
if ev in env:
return env[ev]
if ev == "mux":
return combine_valstat(st).multiplex
#
# when the model passed in a lambda run the function for each logical cpu
# (by resolving its EVs to only that CPU)
# and then sum up. This is needed for the workarounds to make various
# per thread counters at least as big as unhalted cycles.
#
# otherwise we always sum up.
#
if isinstance(ev, types.LambdaType):
return sum([ev(lambda ev, level:
lookup_res(res, rev, ev, obj, env, level, referenced, off, st), level)
for off in range(cpu.threads)])
index = obj.res_map[(ev, level, obj.name)]
referenced.add(index)
#print (ev, level, obj.name), "->", index
rmap_ev = event_rmap(rev[index]).lower()
assert (rmap_ev == canon_event(ev).replace("/k", "/") or
(ev in event_fixes and canon_event(event_fixes[ev]) == rmap_ev) or
rmap_ev == "dummy")
if isinstance(res[index], types.TupleType):
if cpuoff == -1:
return sum(res[index])
else:
try:
return res[index][cpuoff]
except IndexError:
print >>sys.stderr, "warning: Partial CPU thread data from perf"
return 0
return res[index]
def add_key(k, x, y):
k[x] = y
# dedup a and keep b uptodate
def dedup2(a, b):
k = dict()
map(lambda x, y: add_key(k, x, y), a, b)
return k.keys(), map(lambda x: k[x], k.keys())
def cmp_obj(a, b):
if a.level == b.level:
return a.nc - b.nc
return a.level - b.level
def update_res_map(evnum, objl, base):
for obj in objl:
for lev in obj.evlevels:
r = raw_event(lev[0])
if r in evnum:
obj.res_map[lev] = base + evnum.index(r)
class BadEvent:
def __init__(self, name):
self.event = name
# XXX check for errata
def sample_event(e):
ev = emap.getevent(e.replace("_PS", ""))
if not ev:
raise BadEvent(e)
postfix = ring_filter
if ev.pebs and int(ev.pebs):
postfix = "pp"
if postfix:
postfix = ":" + postfix
return ev.name + postfix
def sample_desc(s):
try:
return " ".join([sample_event(x) for x in s])
except BadEvent as e:
#return "Unknown sample event %s" % (e.event)
return ""
def get_levels(evlev):
return [x[1] for x in evlev]
def get_names(evlev):
return [x[0] for x in evlev]
def grab_group(l):