xref: /linux/tools/power/x86/intel_pstate_tracer/intel_pstate_tracer.py (revision a5778046a02570fd23bdf0b48dce330237d1996c)
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
6intel_pstate driver. This utility can be used in two ways:
7- If there is Linux trace file with pstate_sample events enabled, then
8this utility can parse the trace file and generate performance plots.
9- If user has not specified a trace file as input via command line parameters,
10then this utility enables and collects trace data for a user specified interval
11and generates performance plots.
12
13Prerequisites:
14    Python version 3.6.x or higher
15    gnuplot 5.0 or higher
16    python3-gnuplot 1.8 or higher
17    (Most of the distributions have these required packages. They may be called
18     gnuplot-py, python-gnuplot or python3-gnuplot, gnuplot-nox, ... )
19
20    HWP (Hardware P-States are disabled)
21    Kernel config for Linux trace is enabled
22
23    see print_help(): for Usage and Output details
24
25"""
26
27from datetime import datetime
28import subprocess
29import os
30import time
31import re
32import signal
33import sys
34import getopt
35from decimal import *
36
37__author__ = "Srinivas Pandruvada"
38__copyright__ = " Copyright (c) 2017, Intel Corporation. "
39__license__ = "GPL version 2"
40
41
42MAX_CPUS = 256
43
44# Define the csv file columns
45C_COMM = 18
46C_GHZ = 17
47C_ELAPSED = 16
48C_SAMPLE = 15
49C_DURATION = 14
50C_LOAD = 13
51C_BOOST = 12
52C_FREQ = 11
53C_TSC = 10
54C_APERF = 9
55C_MPERF = 8
56C_TO = 7
57C_FROM = 6
58C_SCALED = 5
59C_CORE = 4
60C_USEC = 3
61C_SEC = 2
62C_CPU = 1
63
64global sample_num, last_sec_cpu, last_usec_cpu, start_time, testname, trace_file
65
66# 11 digits covers uptime to 115 days
67getcontext().prec = 11
68
69sample_num =0
70last_sec_cpu = [0] * MAX_CPUS
71last_usec_cpu = [0] * MAX_CPUS
72
73def print_help(driver_name):
74    print('%s_tracer.py:'%driver_name)
75    print('  Usage:')
76    print('    If the trace file is available, then to simply parse and plot, use (sudo not required):')
77    print('      ./%s_tracer.py [-c cpus] -t <trace_file> -n <test_name>'%driver_name)
78    print('    Or')
79    print('      ./%s_tracer.py [--cpu cpus] ---trace_file <trace_file> --name <test_name>'%driver_name)
80    print('    To generate trace file, parse and plot, use (sudo required):')
81    print('      sudo ./%s_tracer.py [-c cpus] -i <interval> -n <test_name> -m <kbytes>'%driver_name)
82    print('    Or')
83    print('      sudo ./%s_tracer.py [--cpu cpus] --interval <interval> --name <test_name> --memory <kbytes>'%driver_name)
84    print('    Optional argument:')
85    print('      cpus:   comma separated list of CPUs')
86    print('      kbytes: Kilo bytes of memory per CPU to allocate to the trace buffer. Default: 10240')
87    print('  Output:')
88    print('    If not already present, creates a "results/test_name" folder in the current working directory with:')
89    print('      cpu.csv - comma separated values file with trace contents and some additional calculations.')
90    print('      cpu???.csv - comma separated values file for CPU number ???.')
91    print('      *.png - a variety of PNG format plot files created from the trace contents and the additional calculations.')
92    print('  Notes:')
93    print('    Avoid the use of _ (underscore) in test names, because in gnuplot it is a subscript directive.')
94    print('    Maximum number of CPUs is {0:d}. If there are more the script will abort with an error.'.format(MAX_CPUS))
95    print('    Off-line CPUs cause the script to list some warnings, and create some empty files. Use the CPU mask feature for a clean run.')
96    print('    Empty y range warnings for autoscaled plots can occur and can be ignored.')
97
98def plot_perf_busy_with_sample(cpu_index):
99    """ Plot method to per cpu information """
100
101    file_name = 'cpu{:0>3}.csv'.format(cpu_index)
102    if os.path.exists(file_name):
103        output_png = "cpu%03d_perf_busy_vs_samples.png" % cpu_index
104        g_plot = common_all_gnuplot_settings(output_png)
105#   autoscale this one, no set y1 range
106        g_plot('set y2range [0:200]')
107        g_plot('set y2tics 0, 10')
108        g_plot('set title "{} : cpu perf busy vs. sample : CPU {:0>3} : {:%F %H:%M}"'.format(testname, cpu_index, datetime.now()))
109#       Override common
110        g_plot('set xlabel "Samples"')
111        g_plot('set ylabel "P-State"')
112        g_plot('set y2label "Scaled Busy/performance/io-busy(%)"')
113        set_4_plot_linestyles(g_plot)
114        g_plot('plot "' + file_name + '" using {:d}:{:d} with linespoints linestyle 1 axis x1y2 title "performance",\\'.format(C_SAMPLE, C_CORE))
115        g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 2 axis x1y2 title "scaled-busy",\\'.format(C_SAMPLE, C_SCALED))
116        g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 3 axis x1y2 title "io-boost",\\'.format(C_SAMPLE, C_BOOST))
117        g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 4 axis x1y1 title "P-State"'.format(C_SAMPLE, C_TO))
118
119def plot_perf_busy(cpu_index):
120    """ Plot some per cpu information """
121
122    file_name = 'cpu{:0>3}.csv'.format(cpu_index)
123    if os.path.exists(file_name):
124        output_png = "cpu%03d_perf_busy.png" % cpu_index
125        g_plot = common_all_gnuplot_settings(output_png)
126#   autoscale this one, no set y1 range
127        g_plot('set y2range [0:200]')
128        g_plot('set y2tics 0, 10')
129        g_plot('set title "{} : perf busy : CPU {:0>3} : {:%F %H:%M}"'.format(testname, cpu_index, datetime.now()))
130        g_plot('set ylabel "P-State"')
131        g_plot('set y2label "Scaled Busy/performance/io-busy(%)"')
132        set_4_plot_linestyles(g_plot)
133        g_plot('plot "' + file_name + '" using {:d}:{:d} with linespoints linestyle 1 axis x1y2 title "performance",\\'.format(C_ELAPSED, C_CORE))
134        g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 2 axis x1y2 title "scaled-busy",\\'.format(C_ELAPSED, C_SCALED))
135        g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 3 axis x1y2 title "io-boost",\\'.format(C_ELAPSED, C_BOOST))
136        g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 4 axis x1y1 title "P-State"'.format(C_ELAPSED, C_TO))
137
138def plot_durations(cpu_index):
139    """ Plot per cpu durations """
140
141    file_name = 'cpu{:0>3}.csv'.format(cpu_index)
142    if os.path.exists(file_name):
143        output_png = "cpu%03d_durations.png" % cpu_index
144        g_plot = common_all_gnuplot_settings(output_png)
145#       autoscale this one, no set y range
146        g_plot('set title "{} : durations : CPU {:0>3} : {:%F %H:%M}"'.format(testname, cpu_index, datetime.now()))
147        g_plot('set ylabel "Timer Duration (MilliSeconds)"')
148#       override common
149        g_plot('set key off')
150        set_4_plot_linestyles(g_plot)
151        g_plot('plot "' + file_name + '" using {:d}:{:d} with linespoints linestyle 1 axis x1y1'.format(C_ELAPSED, C_DURATION))
152
153def plot_loads(cpu_index):
154    """ Plot per cpu loads """
155
156    file_name = 'cpu{:0>3}.csv'.format(cpu_index)
157    if os.path.exists(file_name):
158        output_png = "cpu%03d_loads.png" % cpu_index
159        g_plot = common_all_gnuplot_settings(output_png)
160        g_plot('set yrange [0:100]')
161        g_plot('set ytics 0, 10')
162        g_plot('set title "{} : loads : CPU {:0>3} : {:%F %H:%M}"'.format(testname, cpu_index, datetime.now()))
163        g_plot('set ylabel "CPU load (percent)"')
164#       override common
165        g_plot('set key off')
166        set_4_plot_linestyles(g_plot)
167        g_plot('plot "' + file_name + '" using {:d}:{:d} with linespoints linestyle 1 axis x1y1'.format(C_ELAPSED, C_LOAD))
168
169def plot_pstate_cpu_with_sample():
170    """ Plot all cpu information """
171
172    if os.path.exists('cpu.csv'):
173        output_png = 'all_cpu_pstates_vs_samples.png'
174        g_plot = common_all_gnuplot_settings(output_png)
175#       autoscale this one, no set y range
176#       override common
177        g_plot('set xlabel "Samples"')
178        g_plot('set ylabel "P-State"')
179        g_plot('set title "{} : cpu pstate vs. sample : {:%F %H:%M}"'.format(testname, datetime.now()))
180        title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).decode('utf-8').replace('\n', ' ')
181        plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_SAMPLE, C_TO)
182        g_plot('title_list = "{}"'.format(title_list))
183        g_plot(plot_str)
184
185def plot_pstate_cpu():
186    """ Plot all cpu information from csv files """
187
188    output_png = 'all_cpu_pstates.png'
189    g_plot = common_all_gnuplot_settings(output_png)
190#   autoscale this one, no set y range
191    g_plot('set ylabel "P-State"')
192    g_plot('set title "{} : cpu pstates : {:%F %H:%M}"'.format(testname, datetime.now()))
193
194#    the following command is really cool, but doesn't work with the CPU masking option because it aborts on the first missing file.
195#    plot_str = 'plot for [i=0:*] file=sprintf("cpu%03d.csv",i) title_s=sprintf("cpu%03d",i) file using 16:7 pt 7 ps 1 title title_s'
196#
197    title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).decode('utf-8').replace('\n', ' ')
198    plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_TO)
199    g_plot('title_list = "{}"'.format(title_list))
200    g_plot(plot_str)
201
202def plot_load_cpu():
203    """ Plot all cpu loads """
204
205    output_png = 'all_cpu_loads.png'
206    g_plot = common_all_gnuplot_settings(output_png)
207    g_plot('set yrange [0:100]')
208    g_plot('set ylabel "CPU load (percent)"')
209    g_plot('set title "{} : cpu loads : {:%F %H:%M}"'.format(testname, datetime.now()))
210
211    title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).decode('utf-8').replace('\n', ' ')
212    plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_LOAD)
213    g_plot('title_list = "{}"'.format(title_list))
214    g_plot(plot_str)
215
216def plot_frequency_cpu():
217    """ Plot all cpu frequencies """
218
219    output_png = 'all_cpu_frequencies.png'
220    g_plot = common_all_gnuplot_settings(output_png)
221#   autoscale this one, no set y range
222    g_plot('set ylabel "CPU Frequency (GHz)"')
223    g_plot('set title "{} : cpu frequencies : {:%F %H:%M}"'.format(testname, datetime.now()))
224
225    title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).decode('utf-8').replace('\n', ' ')
226    plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_FREQ)
227    g_plot('title_list = "{}"'.format(title_list))
228    g_plot(plot_str)
229
230def plot_duration_cpu():
231    """ Plot all cpu durations """
232
233    output_png = 'all_cpu_durations.png'
234    g_plot = common_all_gnuplot_settings(output_png)
235#   autoscale this one, no set y range
236    g_plot('set ylabel "Timer Duration (MilliSeconds)"')
237    g_plot('set title "{} : cpu durations : {:%F %H:%M}"'.format(testname, datetime.now()))
238
239    title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).decode('utf-8').replace('\n', ' ')
240    plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_DURATION)
241    g_plot('title_list = "{}"'.format(title_list))
242    g_plot(plot_str)
243
244def plot_scaled_cpu():
245    """ Plot all cpu scaled busy """
246
247    output_png = 'all_cpu_scaled.png'
248    g_plot = common_all_gnuplot_settings(output_png)
249#   autoscale this one, no set y range
250    g_plot('set ylabel "Scaled Busy (Unitless)"')
251    g_plot('set title "{} : cpu scaled busy : {:%F %H:%M}"'.format(testname, datetime.now()))
252
253    title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).decode('utf-8').replace('\n', ' ')
254    plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_SCALED)
255    g_plot('title_list = "{}"'.format(title_list))
256    g_plot(plot_str)
257
258def plot_boost_cpu():
259    """ Plot all cpu IO Boosts """
260
261    output_png = 'all_cpu_boost.png'
262    g_plot = common_all_gnuplot_settings(output_png)
263    g_plot('set yrange [0:100]')
264    g_plot('set ylabel "CPU IO Boost (percent)"')
265    g_plot('set title "{} : cpu io boost : {:%F %H:%M}"'.format(testname, datetime.now()))
266
267    title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).decode('utf-8').replace('\n', ' ')
268    plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_BOOST)
269    g_plot('title_list = "{}"'.format(title_list))
270    g_plot(plot_str)
271
272def plot_ghz_cpu():
273    """ Plot all cpu tsc ghz """
274
275    output_png = 'all_cpu_ghz.png'
276    g_plot = common_all_gnuplot_settings(output_png)
277#   autoscale this one, no set y range
278    g_plot('set ylabel "TSC Frequency (GHz)"')
279    g_plot('set title "{} : cpu TSC Frequencies (Sanity check calculation) : {:%F %H:%M}"'.format(testname, datetime.now()))
280
281    title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).decode('utf-8').replace('\n', ' ')
282    plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_GHZ)
283    g_plot('title_list = "{}"'.format(title_list))
284    g_plot(plot_str)
285
286def common_all_gnuplot_settings(output_png):
287    """ common gnuplot settings for multiple CPUs one one graph. """
288
289    g_plot = common_gnuplot_settings()
290    g_plot('set output "' + output_png + '"')
291    return(g_plot)
292
293def common_gnuplot_settings():
294    """ common gnuplot settings. """
295
296    import Gnuplot
297
298    g_plot = Gnuplot.Gnuplot(persist=1)
299#   The following line is for rigor only. It seems to be assumed for .csv files
300    g_plot('set datafile separator \",\"')
301    g_plot('set ytics nomirror')
302    g_plot('set xtics nomirror')
303    g_plot('set xtics font ", 10"')
304    g_plot('set ytics font ", 10"')
305    g_plot('set tics out scale 1.0')
306    g_plot('set grid')
307    g_plot('set key out horiz')
308    g_plot('set key bot center')
309    g_plot('set key samplen 2 spacing .8 font ", 9"')
310    g_plot('set term png size 1200, 600')
311    g_plot('set title font ", 11"')
312    g_plot('set ylabel font ", 10"')
313    g_plot('set xlabel font ", 10"')
314    g_plot('set xlabel offset 0, 0.5')
315    g_plot('set xlabel "Elapsed Time (Seconds)"')
316    return(g_plot)
317
318def set_4_plot_linestyles(g_plot):
319    """ set the linestyles used for 4 plots in 1 graphs. """
320
321    g_plot('set style line 1 linetype 1 linecolor rgb "green" pointtype -1')
322    g_plot('set style line 2 linetype 1 linecolor rgb "red" pointtype -1')
323    g_plot('set style line 3 linetype 1 linecolor rgb "purple" pointtype -1')
324    g_plot('set style line 4 linetype 1 linecolor rgb "blue" pointtype -1')
325
326def store_csv(cpu_int, time_pre_dec, time_post_dec, core_busy, scaled, _from, _to, mperf, aperf, tsc, freq_ghz, io_boost, common_comm, load, duration_ms, sample_num, elapsed_time, tsc_ghz, cpu_mask):
327    """ Store master csv file information """
328
329    global graph_data_present
330
331    if cpu_mask[cpu_int] == 0:
332        return
333
334    try:
335        f_handle = open('cpu.csv', 'a')
336        string_buffer = "CPU_%03u, %05u, %06u, %u, %u, %u, %u, %u, %u, %u, %.4f, %u, %.2f, %.3f, %u, %.3f, %.3f, %s\n" % (cpu_int, int(time_pre_dec), int(time_post_dec), int(core_busy), int(scaled), int(_from), int(_to), int(mperf), int(aperf), int(tsc), freq_ghz, int(io_boost), load, duration_ms, sample_num, elapsed_time, tsc_ghz, common_comm)
337        f_handle.write(string_buffer);
338        f_handle.close()
339    except:
340        print('IO error cpu.csv')
341        return
342
343    graph_data_present = True;
344
345def split_csv(current_max_cpu, cpu_mask):
346    """ separate the main csv file into per CPU csv files. """
347
348    if os.path.exists('cpu.csv'):
349        for index in range(0, current_max_cpu + 1):
350            if cpu_mask[int(index)] != 0:
351                os.system('grep -m 1 common_cpu cpu.csv > cpu{:0>3}.csv'.format(index))
352                os.system('grep CPU_{:0>3} cpu.csv >> cpu{:0>3}.csv'.format(index, index))
353
354def fix_ownership(path):
355    """Change the owner of the file to SUDO_UID, if required"""
356
357    uid = os.environ.get('SUDO_UID')
358    gid = os.environ.get('SUDO_GID')
359    if uid is not None:
360        os.chown(path, int(uid), int(gid))
361
362def cleanup_data_files():
363    """ clean up existing data files """
364
365    if os.path.exists('cpu.csv'):
366        os.remove('cpu.csv')
367    f_handle = open('cpu.csv', 'a')
368    f_handle.write('common_cpu, common_secs, common_usecs, core_busy, scaled_busy, from, to, mperf, aperf, tsc, freq, boost, load, duration_ms, sample_num, elapsed_time, tsc_ghz, common_comm')
369    f_handle.write('\n')
370    f_handle.close()
371
372def clear_trace_file():
373    """ Clear trace file """
374
375    try:
376        f_handle = open('/sys/kernel/tracing/trace', 'w')
377        f_handle.close()
378    except:
379        print('IO error clearing trace file ')
380        sys.exit(2)
381
382def enable_trace(trace_file):
383    """ Enable trace """
384
385    try:
386        open(trace_file,'w').write("1")
387    except:
388        print('IO error enabling trace ')
389        sys.exit(2)
390
391def disable_trace(trace_file):
392    """ Disable trace """
393
394    try:
395       open(trace_file, 'w').write("0")
396    except:
397        print('IO error disabling trace ')
398        sys.exit(2)
399
400def set_trace_buffer_size(memory):
401    """ Set trace buffer size """
402
403    try:
404       with open('/sys/kernel/tracing/buffer_size_kb', 'w') as fp:
405          fp.write(memory)
406    except:
407       print('IO error setting trace buffer size ')
408       sys.exit(2)
409
410def free_trace_buffer():
411    """ Free the trace buffer memory """
412
413    try:
414       open('/sys/kernel/tracing/buffer_size_kb'
415                 , 'w').write("1")
416    except:
417        print('IO error freeing trace buffer ')
418        sys.exit(2)
419
420def read_trace_data(filename, cpu_mask):
421    """ Read and parse trace data """
422
423    global current_max_cpu
424    global sample_num, last_sec_cpu, last_usec_cpu, start_time
425
426    try:
427        data = open(filename, 'r').read()
428    except:
429        print('Error opening ', filename)
430        sys.exit(2)
431
432    for line in data.splitlines():
433        search_obj = \
434            re.search(r'(^(.*?)\[)((\d+)[^\]])(.*?)(\d+)([.])(\d+)(.*?core_busy=)(\d+)(.*?scaled=)(\d+)(.*?from=)(\d+)(.*?to=)(\d+)(.*?mperf=)(\d+)(.*?aperf=)(\d+)(.*?tsc=)(\d+)(.*?freq=)(\d+)'
435                      , line)
436
437        if search_obj:
438            cpu = search_obj.group(3)
439            cpu_int = int(cpu)
440            cpu = str(cpu_int)
441
442            time_pre_dec = search_obj.group(6)
443            time_post_dec = search_obj.group(8)
444            core_busy = search_obj.group(10)
445            scaled = search_obj.group(12)
446            _from = search_obj.group(14)
447            _to = search_obj.group(16)
448            mperf = search_obj.group(18)
449            aperf = search_obj.group(20)
450            tsc = search_obj.group(22)
451            freq = search_obj.group(24)
452            common_comm = search_obj.group(2).replace(' ', '')
453
454            # Not all kernel versions have io_boost field
455            io_boost = '0'
456            search_obj = re.search(r'.*?io_boost=(\d+)', line)
457            if search_obj:
458                io_boost = search_obj.group(1)
459
460            if sample_num == 0 :
461                start_time = Decimal(time_pre_dec) + Decimal(time_post_dec) / Decimal(1000000)
462            sample_num += 1
463
464            if last_sec_cpu[cpu_int] == 0 :
465                last_sec_cpu[cpu_int] = time_pre_dec
466                last_usec_cpu[cpu_int] = time_post_dec
467            else :
468                duration_us = (int(time_pre_dec) - int(last_sec_cpu[cpu_int])) * 1000000 + (int(time_post_dec) - int(last_usec_cpu[cpu_int]))
469                duration_ms = Decimal(duration_us) / Decimal(1000)
470                last_sec_cpu[cpu_int] = time_pre_dec
471                last_usec_cpu[cpu_int] = time_post_dec
472                elapsed_time = Decimal(time_pre_dec) + Decimal(time_post_dec) / Decimal(1000000) - start_time
473                load = Decimal(int(mperf)*100)/ Decimal(tsc)
474                freq_ghz = Decimal(freq)/Decimal(1000000)
475#               Sanity check calculation, typically anomalies indicate missed samples
476#               However, check for 0 (should never occur)
477                tsc_ghz = Decimal(0)
478                if duration_ms != Decimal(0) :
479                    tsc_ghz = Decimal(tsc)/duration_ms/Decimal(1000000)
480                store_csv(cpu_int, time_pre_dec, time_post_dec, core_busy, scaled, _from, _to, mperf, aperf, tsc, freq_ghz, io_boost, common_comm, load, duration_ms, sample_num, elapsed_time, tsc_ghz, cpu_mask)
481
482            if cpu_int > current_max_cpu:
483                current_max_cpu = cpu_int
484# End of for each trace line loop
485# Now separate the main overall csv file into per CPU csv files.
486    split_csv(current_max_cpu, cpu_mask)
487
488def signal_handler(signal, frame):
489    print(' SIGINT: Forcing cleanup before exit.')
490    if interval:
491        disable_trace(trace_file)
492        clear_trace_file()
493        # Free the memory
494        free_trace_buffer()
495        sys.exit(0)
496
497if __name__ == "__main__":
498    trace_file = "/sys/kernel/tracing/events/power/pstate_sample/enable"
499    signal.signal(signal.SIGINT, signal_handler)
500
501    interval = ""
502    filename = ""
503    cpu_list = ""
504    testname = ""
505    memory = "10240"
506    graph_data_present = False;
507
508    valid1 = False
509    valid2 = False
510
511    try:
512        opts, args = getopt.getopt(sys.argv[1:],"ht:i:c:n:m:",["help","trace_file=","interval=","cpu=","name=","memory="])
513    except getopt.GetoptError:
514        print_help('intel_pstate')
515        sys.exit(2)
516    for opt, arg in opts:
517        if opt == '-h':
518            print_help('intel_pstate')
519            sys.exit()
520        elif opt in ("-t", "--trace_file"):
521            valid1 = True
522            location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
523            filename = os.path.join(location, arg)
524        elif opt in ("-i", "--interval"):
525            valid1 = True
526            interval = arg
527        elif opt in ("-c", "--cpu"):
528            cpu_list = arg
529        elif opt in ("-n", "--name"):
530            valid2 = True
531            testname = arg
532        elif opt in ("-m", "--memory"):
533            memory = arg
534
535    if not (valid1 and valid2):
536        print_help('intel_pstate')
537        sys.exit()
538
539    from numpy import zeros
540
541    cpu_mask = zeros((MAX_CPUS,), dtype=int)
542
543    if cpu_list:
544        for p in re.split("[,]", cpu_list):
545            if int(p) < MAX_CPUS :
546                cpu_mask[int(p)] = 1
547    else:
548        for i in range (0, MAX_CPUS):
549            cpu_mask[i] = 1
550
551    if not os.path.exists('results'):
552        os.mkdir('results')
553        # The regular user needs to own the directory, not root.
554        fix_ownership('results')
555
556    os.chdir('results')
557    if os.path.exists(testname):
558        print('The test name directory already exists. Please provide a unique test name. Test re-run not supported, yet.')
559        sys.exit()
560    os.mkdir(testname)
561    # The regular user needs to own the directory, not root.
562    fix_ownership(testname)
563    os.chdir(testname)
564
565    # Temporary (or perhaps not)
566    cur_version = sys.version_info
567    print('python version (should be >= 3.6):')
568    print(cur_version)
569
570    # Left as "cleanup" for potential future re-run ability.
571    cleanup_data_files()
572
573    if interval:
574        filename = "/sys/kernel/tracing/trace"
575        clear_trace_file()
576        set_trace_buffer_size(memory)
577        enable_trace(trace_file)
578        print('Sleeping for ', interval, 'seconds')
579        time.sleep(int(interval))
580        disable_trace(trace_file)
581
582    current_max_cpu = 0
583
584    read_trace_data(filename, cpu_mask)
585
586    if interval:
587        clear_trace_file()
588        # Free the memory
589        free_trace_buffer()
590
591    if graph_data_present == False:
592        print('No valid data to plot')
593        sys.exit(2)
594
595    for cpu_no in range(0, current_max_cpu + 1):
596        plot_perf_busy_with_sample(cpu_no)
597        plot_perf_busy(cpu_no)
598        plot_durations(cpu_no)
599        plot_loads(cpu_no)
600
601    plot_pstate_cpu_with_sample()
602    plot_pstate_cpu()
603    plot_load_cpu()
604    plot_frequency_cpu()
605    plot_duration_cpu()
606    plot_scaled_cpu()
607    plot_boost_cpu()
608    plot_ghz_cpu()
609
610    # It is preferrable, but not necessary, that the regular user owns the files, not root.
611    for root, dirs, files in os.walk('.'):
612        for f in files:
613            fix_ownership(f)
614
615    os.chdir('../../')
616