xref: /linux/tools/power/x86/amd_pstate_tracer/amd_pstate_trace.py (revision 8a922b7728a93d837954315c98b84f6b78de0c4f)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0-only
3# -*- coding: utf-8 -*-
4#
5""" This utility can be used to debug and tune the performance of the
6AMD P-State driver. It imports intel_pstate_tracer to analyze AMD P-State
7trace event.
8
9Prerequisites:
10    Python version 2.7.x or higher
11    gnuplot 5.0 or higher
12    gnuplot-py 1.8 or higher
13    (Most of the distributions have these required packages. They may be called
14     gnuplot-py, phython-gnuplot or phython3-gnuplot, gnuplot-nox, ... )
15
16    Kernel config for Linux trace is enabled
17
18    see print_help(): for Usage and Output details
19
20"""
21from __future__ import print_function
22from datetime import datetime
23import subprocess
24import os
25import time
26import re
27import signal
28import sys
29import getopt
30import Gnuplot
31from numpy import *
32from decimal import *
33sys.path.append('../intel_pstate_tracer')
34#import intel_pstate_tracer
35import intel_pstate_tracer as ipt
36
37__license__ = "GPL version 2"
38
39MAX_CPUS = 256
40# Define the csv file columns
41C_COMM = 15
42C_ELAPSED = 14
43C_SAMPLE = 13
44C_DURATION = 12
45C_LOAD = 11
46C_TSC = 10
47C_APERF = 9
48C_MPERF = 8
49C_FREQ = 7
50C_MAX_PERF = 6
51C_DES_PERF = 5
52C_MIN_PERF = 4
53C_USEC = 3
54C_SEC = 2
55C_CPU = 1
56
57global sample_num, last_sec_cpu, last_usec_cpu, start_time, test_name, trace_file
58
59getcontext().prec = 11
60
61sample_num =0
62last_sec_cpu = [0] * MAX_CPUS
63last_usec_cpu = [0] * MAX_CPUS
64
65def plot_per_cpu_freq(cpu_index):
66    """ Plot per cpu frequency """
67
68    file_name = 'cpu{:0>3}.csv'.format(cpu_index)
69    if os.path.exists(file_name):
70        output_png = "cpu%03d_frequency.png" % cpu_index
71        g_plot = ipt.common_gnuplot_settings()
72        g_plot('set output "' + output_png + '"')
73        g_plot('set yrange [0:7]')
74        g_plot('set ytics 0, 1')
75        g_plot('set ylabel "CPU Frequency (GHz)"')
76        g_plot('set title "{} : frequency : CPU {:0>3} : {:%F %H:%M}"'.format(test_name, cpu_index, datetime.now()))
77        g_plot('set ylabel "CPU frequency"')
78        g_plot('set key off')
79        ipt.set_4_plot_linestyles(g_plot)
80        g_plot('plot "' + file_name + '" using {:d}:{:d} with linespoints linestyle 1 axis x1y1'.format(C_ELAPSED, C_FREQ))
81
82def plot_per_cpu_des_perf(cpu_index):
83    """ Plot per cpu desired perf """
84
85    file_name = 'cpu{:0>3}.csv'.format(cpu_index)
86    if os.path.exists(file_name):
87        output_png = "cpu%03d_des_perf.png" % cpu_index
88        g_plot = ipt.common_gnuplot_settings()
89        g_plot('set output "' + output_png + '"')
90        g_plot('set yrange [0:255]')
91        g_plot('set ylabel "des perf"')
92        g_plot('set title "{} : cpu des perf : CPU {:0>3} : {:%F %H:%M}"'.format(test_name, cpu_index, datetime.now()))
93        g_plot('set key off')
94        ipt.set_4_plot_linestyles(g_plot)
95        g_plot('plot "' + file_name + '" using {:d}:{:d} with linespoints linestyle 1 axis x1y1'.format(C_ELAPSED, C_DES_PERF))
96
97def plot_per_cpu_load(cpu_index):
98    """ Plot per cpu load """
99
100    file_name = 'cpu{:0>3}.csv'.format(cpu_index)
101    if os.path.exists(file_name):
102        output_png = "cpu%03d_load.png" % cpu_index
103        g_plot = ipt.common_gnuplot_settings()
104        g_plot('set output "' + output_png + '"')
105        g_plot('set yrange [0:100]')
106        g_plot('set ytics 0, 10')
107        g_plot('set ylabel "CPU load (percent)"')
108        g_plot('set title "{} : cpu load : CPU {:0>3} : {:%F %H:%M}"'.format(test_name, cpu_index, datetime.now()))
109        g_plot('set key off')
110        ipt.set_4_plot_linestyles(g_plot)
111        g_plot('plot "' + file_name + '" using {:d}:{:d} with linespoints linestyle 1 axis x1y1'.format(C_ELAPSED, C_LOAD))
112
113def plot_all_cpu_frequency():
114    """ Plot all cpu frequencies """
115
116    output_png = 'all_cpu_frequencies.png'
117    g_plot = ipt.common_gnuplot_settings()
118    g_plot('set output "' + output_png + '"')
119    g_plot('set ylabel "CPU Frequency (GHz)"')
120    g_plot('set title "{} : cpu frequencies : {:%F %H:%M}"'.format(test_name, datetime.now()))
121
122    title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).decode('utf-8').replace('\n', ' ')
123    plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_FREQ)
124    g_plot('title_list = "{}"'.format(title_list))
125    g_plot(plot_str)
126
127def plot_all_cpu_des_perf():
128    """ Plot all cpu desired perf """
129
130    output_png = 'all_cpu_des_perf.png'
131    g_plot = ipt.common_gnuplot_settings()
132    g_plot('set output "' + output_png + '"')
133    g_plot('set ylabel "des perf"')
134    g_plot('set title "{} : cpu des perf : {:%F %H:%M}"'.format(test_name, datetime.now()))
135
136    title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).decode('utf-8').replace('\n', ' ')
137    plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 255 ps 1 title i".format(C_ELAPSED, C_DES_PERF)
138    g_plot('title_list = "{}"'.format(title_list))
139    g_plot(plot_str)
140
141def plot_all_cpu_load():
142    """ Plot all cpu load  """
143
144    output_png = 'all_cpu_load.png'
145    g_plot = ipt.common_gnuplot_settings()
146    g_plot('set output "' + output_png + '"')
147    g_plot('set yrange [0:100]')
148    g_plot('set ylabel "CPU load (percent)"')
149    g_plot('set title "{} : cpu load : {:%F %H:%M}"'.format(test_name, datetime.now()))
150
151    title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).decode('utf-8').replace('\n', ' ')
152    plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 255 ps 1 title i".format(C_ELAPSED, C_LOAD)
153    g_plot('title_list = "{}"'.format(title_list))
154    g_plot(plot_str)
155
156def store_csv(cpu_int, time_pre_dec, time_post_dec, min_perf, des_perf, max_perf, freq_ghz, mperf, aperf, tsc, common_comm, load, duration_ms, sample_num, elapsed_time, cpu_mask):
157    """ Store master csv file information """
158
159    global graph_data_present
160
161    if cpu_mask[cpu_int] == 0:
162        return
163
164    try:
165        f_handle = open('cpu.csv', 'a')
166        string_buffer = "CPU_%03u, %05u, %06u, %u, %u, %u, %.4f, %u, %u, %u, %.2f, %.3f, %u, %.3f, %s\n" % (cpu_int, int(time_pre_dec), int(time_post_dec), int(min_perf), int(des_perf), int(max_perf), freq_ghz, int(mperf), int(aperf), int(tsc), load, duration_ms, sample_num, elapsed_time, common_comm)
167        f_handle.write(string_buffer)
168        f_handle.close()
169    except:
170        print('IO error cpu.csv')
171        return
172
173    graph_data_present = True;
174
175
176def cleanup_data_files():
177    """ clean up existing data files """
178
179    if os.path.exists('cpu.csv'):
180        os.remove('cpu.csv')
181    f_handle = open('cpu.csv', 'a')
182    f_handle.write('common_cpu, common_secs, common_usecs, min_perf, des_perf, max_perf, freq, mperf, aperf, tsc, load, duration_ms, sample_num, elapsed_time, common_comm')
183    f_handle.write('\n')
184    f_handle.close()
185
186def read_trace_data(file_name, cpu_mask):
187    """ Read and parse trace data """
188
189    global current_max_cpu
190    global sample_num, last_sec_cpu, last_usec_cpu, start_time
191
192    try:
193        data = open(file_name, 'r').read()
194    except:
195        print('Error opening ', file_name)
196        sys.exit(2)
197
198    for line in data.splitlines():
199        search_obj = \
200            re.search(r'(^(.*?)\[)((\d+)[^\]])(.*?)(\d+)([.])(\d+)(.*?amd_min_perf=)(\d+)(.*?amd_des_perf=)(\d+)(.*?amd_max_perf=)(\d+)(.*?freq=)(\d+)(.*?mperf=)(\d+)(.*?aperf=)(\d+)(.*?tsc=)(\d+)'
201                      , line)
202
203        if search_obj:
204            cpu = search_obj.group(3)
205            cpu_int = int(cpu)
206            cpu = str(cpu_int)
207
208            time_pre_dec = search_obj.group(6)
209            time_post_dec = search_obj.group(8)
210            min_perf = search_obj.group(10)
211            des_perf = search_obj.group(12)
212            max_perf = search_obj.group(14)
213            freq = search_obj.group(16)
214            mperf = search_obj.group(18)
215            aperf = search_obj.group(20)
216            tsc = search_obj.group(22)
217
218            common_comm = search_obj.group(2).replace(' ', '')
219
220            if sample_num == 0 :
221                start_time = Decimal(time_pre_dec) + Decimal(time_post_dec) / Decimal(1000000)
222            sample_num += 1
223
224            if last_sec_cpu[cpu_int] == 0 :
225                last_sec_cpu[cpu_int] = time_pre_dec
226                last_usec_cpu[cpu_int] = time_post_dec
227            else :
228                duration_us = (int(time_pre_dec) - int(last_sec_cpu[cpu_int])) * 1000000 + (int(time_post_dec) - int(last_usec_cpu[cpu_int]))
229                duration_ms = Decimal(duration_us) / Decimal(1000)
230                last_sec_cpu[cpu_int] = time_pre_dec
231                last_usec_cpu[cpu_int] = time_post_dec
232                elapsed_time = Decimal(time_pre_dec) + Decimal(time_post_dec) / Decimal(1000000) - start_time
233                load = Decimal(int(mperf)*100)/ Decimal(tsc)
234                freq_ghz = Decimal(freq)/Decimal(1000000)
235                store_csv(cpu_int, time_pre_dec, time_post_dec, min_perf, des_perf, max_perf, freq_ghz, mperf, aperf, tsc, common_comm, load, duration_ms, sample_num, elapsed_time, cpu_mask)
236
237            if cpu_int > current_max_cpu:
238                current_max_cpu = cpu_int
239# Now separate the main overall csv file into per CPU csv files.
240    ipt.split_csv(current_max_cpu, cpu_mask)
241
242
243def signal_handler(signal, frame):
244    print(' SIGINT: Forcing cleanup before exit.')
245    if interval:
246        ipt.disable_trace(trace_file)
247        ipt.clear_trace_file()
248        ipt.free_trace_buffer()
249        sys.exit(0)
250
251trace_file = "/sys/kernel/tracing/events/amd_cpu/enable"
252signal.signal(signal.SIGINT, signal_handler)
253
254interval = ""
255file_name = ""
256cpu_list = ""
257test_name = ""
258memory = "10240"
259graph_data_present = False;
260
261valid1 = False
262valid2 = False
263
264cpu_mask = zeros((MAX_CPUS,), dtype=int)
265
266
267try:
268    opts, args = getopt.getopt(sys.argv[1:],"ht:i:c:n:m:",["help","trace_file=","interval=","cpu=","name=","memory="])
269except getopt.GetoptError:
270    ipt.print_help('amd_pstate')
271    sys.exit(2)
272for opt, arg in opts:
273    if opt == '-h':
274        print()
275        sys.exit()
276    elif opt in ("-t", "--trace_file"):
277        valid1 = True
278        location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
279        file_name = os.path.join(location, arg)
280    elif opt in ("-i", "--interval"):
281        valid1 = True
282        interval = arg
283    elif opt in ("-c", "--cpu"):
284        cpu_list = arg
285    elif opt in ("-n", "--name"):
286        valid2 = True
287        test_name = arg
288    elif opt in ("-m", "--memory"):
289        memory = arg
290
291if not (valid1 and valid2):
292    ipt.print_help('amd_pstate')
293    sys.exit()
294
295if cpu_list:
296    for p in re.split("[,]", cpu_list):
297        if int(p) < MAX_CPUS :
298            cpu_mask[int(p)] = 1
299else:
300    for i in range (0, MAX_CPUS):
301        cpu_mask[i] = 1
302
303if not os.path.exists('results'):
304    os.mkdir('results')
305    ipt.fix_ownership('results')
306
307os.chdir('results')
308if os.path.exists(test_name):
309    print('The test name directory already exists. Please provide a unique test name. Test re-run not supported, yet.')
310    sys.exit()
311os.mkdir(test_name)
312ipt.fix_ownership(test_name)
313os.chdir(test_name)
314
315cur_version = sys.version_info
316print('python version (should be >= 2.7):')
317print(cur_version)
318
319cleanup_data_files()
320
321if interval:
322    file_name = "/sys/kernel/tracing/trace"
323    ipt.clear_trace_file()
324    ipt.set_trace_buffer_size(memory)
325    ipt.enable_trace(trace_file)
326    time.sleep(int(interval))
327    ipt.disable_trace(trace_file)
328
329current_max_cpu = 0
330
331read_trace_data(file_name, cpu_mask)
332
333if interval:
334    ipt.clear_trace_file()
335    ipt.free_trace_buffer()
336
337if graph_data_present == False:
338    print('No valid data to plot')
339    sys.exit(2)
340
341for cpu_no in range(0, current_max_cpu + 1):
342    plot_per_cpu_freq(cpu_no)
343    plot_per_cpu_des_perf(cpu_no)
344    plot_per_cpu_load(cpu_no)
345
346plot_all_cpu_des_perf()
347plot_all_cpu_frequency()
348plot_all_cpu_load()
349
350for root, dirs, files in os.walk('.'):
351    for f in files:
352        ipt.fix_ownership(f)
353
354os.chdir('../../')
355