[PATCH] Add functionality to set the cstate of specified CPUs when running tuna

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



We would like to be able to set the cstate of CPUs while running tuna.

This patch adds the file cpupower.py and options to tuna-cmd.py.
This allows the user to execute the cpupower command from tuna,
allowing the user to set the cstate on a given list or cpus.
Once tuna exits, the original cstate configuration will be restored.

This will let the user to test balancing power consumption and
performance.

Signed-off-by: Anubhav Shelat <ashelat@xxxxxxxxxx>
---
 tuna-cmd.py      | 18 +++++++++--
 tuna/cpupower.py | 79 ++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 94 insertions(+), 3 deletions(-)
 create mode 100644 tuna/cpupower.py

diff --git a/tuna-cmd.py b/tuna-cmd.py
index f37e286bffdb..2c1fbdc43a22 100755
--- a/tuna-cmd.py
+++ b/tuna-cmd.py
@@ -21,7 +21,7 @@ from functools import reduce
 import tuna.new_eth as ethtool
 import tuna.tuna_sched as tuna_sched
 import procfs
-from tuna import tuna, sysfs
+from tuna import tuna, sysfs, cpupower
 import logging
 import time
 import shutil
@@ -116,7 +116,10 @@ def gen_parser():
             "disable_perf": dict(action='store_true', help="Explicitly disable usage of perf in GUI for process view"),
             "refresh": dict(default=2500, metavar='MSEC', type=int, help="Refresh the GUI every MSEC milliseconds"),
             "priority": dict(default=(None, None), metavar="POLICY:RTPRIO", type=tuna.get_policy_and_rtprio, help="Set thread scheduler tunables: POLICY and RTPRIO"),
-            "background": dict(action='store_true', help="Run command as background task")
+            "background": dict(action='store_true', help="Run command as background task"),
+            "cstate": dict(dest='cstate', metavar='CSTATE', help='Set cpus in IDLE-LIST to a specific cstate'),
+            "idle_list": dict(dest="idle_list", metavar='IDLE-LIST',
+                              help='CPU list to set idle states on (default: all cpus).')
          }
 
     parser = HelpMessageParser(description="tuna - Application Tuning Program")
@@ -125,6 +128,8 @@ def gen_parser():
     parser.add_argument('-v', '--version', **MODS['version'])
     parser.add_argument('-L', '--logging', **MODS['logging'])
     parser.add_argument('-D', '--debug', **MODS['debug'])
+    parser.add_argument('-i', '--cstate', **MODS['cstate'])
+    parser.add_argument('-l', '--idle-list', **MODS['idle_list'])
 
     subparser = parser.add_subparsers(dest='command')
 
@@ -649,7 +654,7 @@ def main():
     parser = gen_parser()
     # Set all necessary defaults for gui subparser if no arguments provided
     args = parser.parse_args() if len(sys.argv) > 1 else parser.parse_args(['gui'])
-
+    print(args)
     if args.debug:
         my_logger = setup_logging("my_logger")
         my_logger.addHandler(add_handler("DEBUG", tofile=False))
@@ -667,6 +672,10 @@ def main():
             print("Valid log levels: NOTSET, DEBUG, INFO, WARNING, ERROR")
             print("Log levels may be specified numerically (0-4)\n")
 
+    if args.cstate:
+        cpupower_controller = cpupower.Cpupower(args.idle_list, args.cstate)
+        cpupower_controller.enable_idle_state()
+
     if 'irq_list' in vars(args):
         ps = procfs.pidstats()
         if tuna.has_threaded_irqs(ps):
@@ -760,6 +769,9 @@ def main():
         except KeyboardInterrupt:
             pass
 
+    if cpupower_controller:
+        cpupower_controller.restore_cstate()
+
 
 if __name__ == '__main__':
     main()
diff --git a/tuna/cpupower.py b/tuna/cpupower.py
new file mode 100644
index 000000000000..abbbe0448a8a
--- /dev/null
+++ b/tuna/cpupower.py
@@ -0,0 +1,79 @@
+#! /user/bin/python3
+
+import subprocess
+import argparse
+import os
+import multiprocessing
+import time 
+
+
+class Cpupower:
+    def __init__(self, cpulist, cstate):
+        self.cpulist = cpulist
+        self.cstate = cstate
+        self.nstates = len(os.listdir('/sys/devices/system/cpu/cpu0/cpuidle/'))    # number of cstates
+        self.cpu_count = multiprocessing.cpu_count()
+        self.cstate_cfg = []
+
+
+    def enable_idle_state(self):
+        ''' Enable a specific cstate, while disabling all other cstates, and save the current cstate configuration '''
+        self.cstate_cfg = self.get_cstate_cfg()
+
+        # enable cstate and disable the rest
+        if (self.cpulist):
+            subprocess.run(['sudo', 'cpupower', '-c', self.cpulist,'idle-set', '-e', str(self.cstate)], stdout=open(os.devnull, 'wb'))
+            for cs in range(self.nstates):
+                if str(cs) != self.cstate:
+                    subprocess.run(['sudo', 'cpupower', '-c', self.cpulist,'idle-set', '-d', str(cs)], stdout=open(os.devnull, 'wb'))
+        else:
+            subprocess.run(['sudo', 'cpupower', 'idle-set', '-e', str(self.cstate)], stdout=open(os.devnull, 'wb'))
+            for cs in range(self.nstates):
+                if str(cs) != self.cstate:
+                    subprocess.run(['sudo', 'cpupower', 'idle-set', '-d', str(cs)], stdout=open(os.devnull, 'wb'))
+        
+        if self.cpulist: print(f'Idlestate {self.cstate} enabled on CPUs {self.cpulist}')
+        else: print(f'Idlestate {self.cstate} enabled on all CPUs')
+
+
+    def get_cstate_cfg(self):
+        ''' Store the current cstate config '''
+        # cstate [m] configuration on cpu [n] can be found in '/sys/devices/system/cpu/cpu*/cpuidle/state*/disable'
+        cfg = []
+        for cpu in range(self.cpu_count):
+            cfg.append([])
+            for cs in range(self.nstates):
+                f = open('/sys/devices/system/cpu/cpu'+str(cpu)+'/cpuidle/state'+str(cs)+'/disable', 'r')
+                d = f.read(1)
+                cfg[cpu].append(d)   # cstate_cfg[n][m] stores the m-th idle state on the n-th cpu
+
+        return cfg
+
+
+    def restore_cstate(self):
+        for cpu in range(self.cpu_count):
+            for cs in range(self.nstates):
+                f = open('/sys/devices/system/cpu/cpu'+str(cpu)+'/cpuidle/state'+str(cs)+'/disable', 'w')
+                f.write(self.cstate_cfg[cpu][cs])
+                f.close()
+        print('Idle state configuration restored')
+
+
+if __name__ == '__main__':
+    parser = argparse.ArgumentParser()
+    parser.add_argument('-c', '--cpu-list', required=False, default=None, 
+                        help='List of cpus to perform cpupower-idle-set operation on.')
+    parser.add_argument('-s', '--cstate', default='',
+                        help='Specify cstate to enable/disable')
+    
+    args = parser.parse_args()
+    print(args)
+    cpulist = args.cpu_list
+    cstate = args.cstate
+    cpupower = Cpupower(cpulist, cstate)
+
+    cpupower.enable_idle_state()
+    time.sleep(10)
+    cpupower.restore_cstate()
+
+
-- 
2.45.2





[Index of Archives]     [RT Stable]     [Kernel Newbies]     [IDE]     [Security]     [Git]     [Netfilter]     [Bugtraq]     [Yosemite]     [Yosemite News]     [MIPS Linux]     [ARM Linux]     [Linux Security]     [Linux RAID]     [Linux ATA RAID]     [Samba]     [Video 4 Linux]     [Device Mapper]

  Powered by Linux