Skip to content

Commit

Permalink
不再使用轮询来监控gpu频率,使用inotify监控pp_od_clk_voltage,提高效率
Browse files Browse the repository at this point in the history
  • Loading branch information
Gawah committed Nov 24, 2023
1 parent 5f717d0 commit fbd46af
Show file tree
Hide file tree
Showing 7 changed files with 258 additions and 262 deletions.
1 change: 1 addition & 0 deletions backend/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
RYZENADJ_PATH="{}/plugins/PowerControl/bin/ryzenadj".format(HOMEBREW_PATH)
GPU_DEVICE_PATH = glob.glob("/sys/class/drm/card?/device")[0]
GPUFREQ_PATH = "{}/pp_od_clk_voltage".format(GPU_DEVICE_PATH)
GPULEVEL_PATH = "{}/power_dpm_force_performance_level".format(GPU_DEVICE_PATH)
except Exception as e:
logging.error(f"路径配置异常|{e}")

Expand Down
4 changes: 2 additions & 2 deletions backend/cpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
cpu_avaMinFreq=1600000
cpu_nowLimitFreq=0

class CPU_Manager ():
class CPUManager ():
def __init__(self):
self.get_cpuMaxNum() # 获取 cpu_maxNum
# 获取 cpu_topology
Expand Down Expand Up @@ -289,4 +289,4 @@ def online_cpu(self, cpu_number):
with open(cpu_online_path, 'w') as file:
file.write('1')

cpuManager = CPU_Manager()
cpuManager = CPUManager()
4 changes: 2 additions & 2 deletions backend/fan.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from config import FAN_RAM_REG_ADDR,FAN_RAM_REG_DATA,FAN_RAM_MANUAL_OFFSET,FAN_RAM_RPMWRITE_OFFSET,FAN_RAM_RPMREAD_OFFSET,FAN_RAM_RPMREAD_LENGTH


class FAN_Manager ():
class FanManager ():
def __init__(self):
self.FAN_ISFIND_HWMON=False #是否找到风扇hwmon
self.FAN_HWMON_NAME="" #风扇hwmon名字
Expand Down Expand Up @@ -218,4 +218,4 @@ def get_fanIsAdapted(self):
logging.error(f"获取机型适配异常:{e}")
return 0

fanManager = FAN_Manager()
fanManager = FanManager()
333 changes: 122 additions & 211 deletions backend/gpu.py

Large diffs are not rendered by default.

112 changes: 112 additions & 0 deletions backend/inotify.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import asyncio
import os
import time
import subprocess
import ctypes
import struct
import sys
import threading
import re
from ctypes import CDLL, get_errno
from threading import Thread, Timer

IN_ACCESS = 0x00000001 # 文件被访问
IN_MODIFY = 0x00000002 # 文件被修改
IN_ATTRIB = 0x00000004 # 元数据改变
IN_CLOSE_WRITE = 0x00000008 # 可写文件被关闭
IN_CLOSE_NOWRITE = 0x00000010 # 不可写文件被关闭
IN_OPEN = 0x00000020 # 文件被打开
IN_MOVED_FROM = 0x00000040 # 文件从X移动
IN_MOVED_TO = 0x00000080 # 文件被移动到Y
IN_CREATE = 0x00000100 # 子文件创建
IN_DELETE = 0x00000200 # 子文件删除
IN_DELETE_SELF = 0x00000400 # 自身(被监视的项本身)被删除
IN_MOVE_SELF = 0x00000800 # 自身(被监视的项本身)被移动

class Inotify:
def __init__(self):
try:
self._libc = CDLL(None, use_errno=True)
self._libc.inotify_init.argtypes = []
self._libc.inotify_init.restype = ctypes.c_int
self._libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32]
self._libc.inotify_add_watch.restype = ctypes.c_int
self._libc.inotify_rm_watch.argtypes = [ctypes.c_int, ctypes.c_int]
self._libc.inotify_rm_watch.restype = ctypes.c_int

self.fd = self._libc.inotify_init()

self._wdMap = {}
self._delay = 0.002
self._delaytimer = None
self._runThread = None
except Exception as e:
print(e)

def _process(self):
try:
if self._runThread:
nowThread = self._runThread.name
while self._runThread and self._runThread.name == nowThread:
buf = os.read(self.fd, 4096)
pos = 0
wdMap = self._wdMap.copy()
while pos < len(buf):
(wd, mask, cookie, name_len) = struct.unpack('iIII', buf[pos:pos + 16])
pos += 16
(name,) = struct.unpack('%ds' % name_len, buf[pos:pos + name_len])
pos += name_len
item = wdMap.get(wd)
if item and self._runThread and self._runThread.name == nowThread:
print(f"callback path:{item['path']}, mask:{mask}")
self._delayCall(item['callback'], item['path'], mask)
except Exception as e:
print(e)

def _delayCall(self, callfunc, *args):
try:
if self._delaytimer is not None and self._delaytimer.is_alive():
self._delaytimer.cancel()
self._delaytimer = Timer(self._delay, lambda: callfunc(*args))
self._delaytimer.start()
except Exception as e:
print(e)

def add_watch(self, path, mask, callback):
try:
print(f"add_watch(self, path:{path}, mask:{mask}, callback:{callback})")
path_buf = ctypes.create_string_buffer(path.encode(sys.getfilesystemencoding()))
wd = self._libc.inotify_add_watch(self.fd, path_buf, mask)
self._wdMap[wd] = {'path': path, 'callback': callback}
if wd < 0:
sys.stderr.write(f"can't add watch for {path_buf}: {os.strerror(get_errno())}\n")
return wd
except Exception as e:
print(e)

def remove_watch(self, path):
try:
for wd in list(self._wdMap):
if path == self._wdMap[wd]['path']:
if self._libc.inotify_rm_watch(self.fd, wd) < 0:
sys.stderr.write(f"can't remove watch: {os.strerror(get_errno())}\n")
else:
self._wdMap.pop(wd)
except Exception as e:
print(e)

def run(self):
try:
if self._runThread:
pass
else:
self._runThread = Thread(target=self._process)
self._runThread.start()
except Exception as e:
print(e)

def stop(self):
self._runThread = None

notify = Inotify()
notify.run()
40 changes: 11 additions & 29 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@
from cpu import cpuManager
from fan import fanManager
from sysInfo import sysInfoManager
logging.info("PowerControl main.py")

except Exception as e:
logging.error(e)

class Plugin:
async def _main(self):
while True:
await asyncio.sleep(3)
logging.info("PowerControl main.py")

async def _unload(self):
gpuManager.unload()
logging.info("End PowerControl")

async def get_hasRyzenadj(self):
try:
Expand All @@ -43,23 +46,9 @@ async def get_tdpMax(self):
logging.error(e)
return 0

async def get_gpuFreqMax(self):
async def get_gpuFreqRange(self):
try:
return gpuManager.get_gpuFreqMax()
except Exception as e:
logging.error(e)
return 0

async def get_gpuFreqMin(self):
try:
return gpuManager.get_gpuFreqMin()
except Exception as e:
logging.error(e)
return 0

async def get_gpuFreqMin(self):
try:
return gpuManager.get_gpuFreqMin()
return gpuManager.get_gpuFreqRange()
except Exception as e:
logging.error(e)
return 0
Expand Down Expand Up @@ -143,23 +132,16 @@ def set_gpuAuto(self, value:bool):
logging.error(e)
return False

def set_gpuAutoMaxFreq(self, value: int):
try:
return gpuManager.set_gpuAutoMaxFreq(value)
except Exception as e:
logging.error(e)
return False

def set_gpuAutoMinFreq(self, value: int):
def set_gpuAutoFreqRange(self, min: int,max:int):
try:
return gpuManager.set_gpuAutoMinFreq(value)
return gpuManager.set_gpuAutoFreqRange(min,max)
except Exception as e:
logging.error(e)
return False

def set_gpuFreq(self, value: int):
try:
return gpuManager.set_gpuFreq(value)
return gpuManager.set_gpuFreqFix(value)
except Exception as e:
logging.error(e)
return False
Expand Down
26 changes: 8 additions & 18 deletions src/util/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,13 @@ export class BackendData{
this.has_tdpMax = true;
}
})
await serverAPI!.callPluginMethod<{},number>("get_gpuFreqMax",{}).then(res=>{
await serverAPI!.callPluginMethod<{},number[]>("get_gpuFreqRange",{}).then(res=>{
if (res.success){
console.info("gpuMax = " + res.result);
this.gpuMax = res.result;
this.has_gpuMax = true;
}
})
await serverAPI!.callPluginMethod<{},number>("get_gpuFreqMin",{}).then(res=>{
if (res.success){
console.info("gpuMin = " + res.result);
this.gpuMin = res.result;
console.info("gpuRange = " + res.result);
this.gpuMin = res.result[0];
this.gpuMax = res.result[1];
this.has_gpuMin = true;
this.has_gpuMax = true;
}
})
await this.serverAPI!.callPluginMethod<{},number>("get_fanMAXRPM",{}).then(res=>{
Expand Down Expand Up @@ -187,15 +182,11 @@ export class Backend {
this.serverAPI!.callPluginMethod("set_gpuAuto", {"value":auto});
}

private static applyGPUAutoMax(maxAutoFreq:number){
private static applyGPUAutoRange(minAutoFreq:number,maxAutoFreq:number){
console.log("Applying gpuAuto" + maxAutoFreq.toString());
this.serverAPI!.callPluginMethod("set_gpuAutoMaxFreq", {"value":maxAutoFreq});
this.serverAPI!.callPluginMethod("set_gpuAutoFreqRange", {"min":minAutoFreq,"max":maxAutoFreq});
}

private static applyGPUAutoMin(minAutoFreq:number){
console.log("Applying gpuAuto" + minAutoFreq.toString());
this.serverAPI!.callPluginMethod("set_gpuAutoMinFreq", {"value":minAutoFreq});
}
private static applyFanAuto(auto:boolean){
this.serverAPI!.callPluginMethod("set_fanAuto", {"value":auto});
}
Expand Down Expand Up @@ -251,8 +242,7 @@ export class Backend {
console.log(`开始自动优化GPU频率`)
//Settings.setTDPEnable(false);
Settings.setCpuboost(false);
Backend.applyGPUAutoMax(gpuAutoMaxFreq);
Backend.applyGPUAutoMin(gpuAutoMinFreq);
Backend.applyGPUAutoRange(gpuAutoMinFreq,gpuAutoMaxFreq);
Backend.applyGPUAuto(true);
} else if (gpuMode == GPUMODE.RANGE) {
Backend.applyGPUAuto(false);
Expand Down

0 comments on commit fbd46af

Please sign in to comment.