Last active
May 4, 2025 13:08
-
-
Save lzlrd/6ef94300609e2499e95a8335a75742f9 to your computer and use it in GitHub Desktop.
A Systemd Service to disable CPU C-States at runtime. A hack whilst I tune voltages for stability.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env bash | |
SYSFS_FILES_PATTERN="/sys/devices/system/cpu/cpu*/cpuidle/state[$1]/disable" | |
if [[ $EUID -ne 0 ]]; then | |
echo "This script must be run as root." | |
exit 1 | |
fi | |
cleanup() { | |
echo "Received termination signal. Re-enabling idle states..." | |
shopt -s nullglob | |
local file_count=0 | |
for file in $SYSFS_FILES_PATTERN; do | |
if [[ -w "$file" ]]; then | |
echo "Writing 0 to $file" | |
echo 0 > "$file" 2>/dev/null | |
file_count=$((file_count + 1)) | |
fi | |
done | |
shopt -u nullglob | |
if [[ $file_count -eq 0 ]]; then | |
echo "Warning: No matching files found to re-enable during cleanup." | |
fi | |
echo "Cleanup finished. Exiting." | |
} | |
trap cleanup SIGINT SIGTERM SIGHUP | |
echo "Disabling CPU idle states..." | |
shopt -s nullglob | |
files_found=0 | |
for file in $SYSFS_FILES_PATTERN; do | |
if [[ -w "$file" ]]; then | |
echo "Writing 1 to $file" | |
echo 1 > "$file" 2>/dev/null | |
if [[ $? -ne 0 ]]; then | |
echo "Warning: Failed to write to $file" | |
else | |
files_found=$((files_found + 1)) | |
fi | |
else | |
echo "Warning: File $file not found or not writable." | |
fi | |
done | |
shopt -u nullglob | |
if [[ $files_found -eq 0 ]]; then | |
echo "Error: No matching CPU idle state files found or writable at $SYSFS_FILES_PATTERN" | |
echo "Ensure the pattern is correct and you are running as root." | |
exit 1 | |
fi | |
echo "$files_found idle states disabled. Script is running and waiting for termination signal..." | |
echo "Press Ctrl+C or send SIGTERM (e.g., systemctl stop your-service) to exit gracefully." | |
sleep inf |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Unit] | |
After = sysinit.target | |
Description = Disable CPU C-States | |
Documentation = https://www.kernel.org/doc/Documentation/power/pm_qos_interface.txt | |
[Service] | |
ExecStart = /usr/local/sbin/disable-cstate 2-4 | |
Restart = on-failure | |
RestartSec = 5s | |
Type = simple | |
User = root | |
[Install] | |
WantedBy = multi-user.target |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment