Files
geminux/src/geminux-daemons/geminux-powerd.c
T

481 lines
15 KiB
C
Raw Normal View History

#define _GNU_SOURCE
#include "geminux-power-policy.h"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <linux/input.h>
#include <linux/netlink.h>
#include <poll.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <sys/signalfd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/timerfd.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
#define SOCK_PATH "/run/geminux/powerd.sock"
#define PROFILE_FILE "/run/geminux/power-profile"
#define MAX_EVDEVS 16
typedef struct {
int epfd;
int sig_fd;
int uev_fd;
int srv_fd;
int tmr_fd;
int ev_fds[MAX_EVDEVS];
int num_ev;
int saved_brightness;
geminux_power_policy_t policy;
} powerd_ctx_t;
static int write_sysfs_str(const char *path, const char *val) {
int fd = open(path, O_WRONLY | O_CLOEXEC);
if (fd < 0) return -1;
ssize_t w = write(fd, val, strlen(val));
close(fd);
return (w >= 0) ? 0 : -1;
}
static int read_sysfs_line(const char *path, char *buf, size_t sz) {
FILE *f = fopen(path, "r");
if (!f) return -1;
if (!fgets(buf, (int)sz, f)) {
fclose(f);
return -1;
}
fclose(f);
size_t n = strlen(buf);
while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0';
return 0;
}
static void ensure_run_dir(void) {
mkdir("/run/geminux", 0775);
chmod("/run/geminux", 0775);
struct group *gr = getgrnam("wheel");
if (gr) chown("/run/geminux", 0, gr->gr_gid);
}
static void refresh_ac_and_hdmi(powerd_ctx_t *ctx) {
write_sysfs_str("/sys/class/power_supply/battery/charge_control_end_threshold", "100");
ctx->policy.on_ac_power = false;
DIR *d = opendir("/sys/class/power_supply");
if (d) {
struct dirent *de;
while ((de = readdir(d)) != NULL) {
if (de->d_name[0] == '.') continue;
char p[320], typ[32] = {0}, onl[16] = {0};
snprintf(p, sizeof(p), "/sys/class/power_supply/%s/type", de->d_name);
if (read_sysfs_line(p, typ, sizeof(typ)) == 0 && strcmp(typ, "Battery") != 0) {
snprintf(p, sizeof(p), "/sys/class/power_supply/%s/online", de->d_name);
if (read_sysfs_line(p, onl, sizeof(onl)) == 0 && atoi(onl) == 1) {
ctx->policy.on_ac_power = true;
break;
}
}
}
closedir(d);
}
ctx->policy.hdmi_connected = false;
d = opendir("/sys/class/drm");
if (d) {
struct dirent *de;
while ((de = readdir(d)) != NULL) {
if (!strstr(de->d_name, "HDMI")) continue;
char p[320], st[32] = {0};
snprintf(p, sizeof(p), "/sys/class/drm/%s/status", de->d_name);
if (read_sysfs_line(p, st, sizeof(st)) == 0 && strcmp(st, "connected") == 0) {
ctx->policy.hdmi_connected = true;
break;
}
}
closedir(d);
}
}
static void apply_cpu_policy(powerd_ctx_t *ctx) {
geminux_profile_params_t par = geminux_policy_params(ctx->policy.profile, ctx->policy.on_ac_power);
bool a72_ready = (access("/sys/module/mt6797_a72", F_OK) == 0);
if (!par.a72_online || a72_ready) {
for (int cpu = 8; cpu <= 9; cpu++) {
char p[128];
snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpu%d/online", cpu);
write_sysfs_str(p, par.a72_online ? "1" : "0");
}
}
DIR *d = opendir("/sys/devices/system/cpu/cpufreq");
if (d) {
struct dirent *de;
while ((de = readdir(d)) != NULL) {
if (strncmp(de->d_name, "policy", 6) != 0) continue;
char p[256], freq_buf[32];
snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_governor", de->d_name);
write_sysfs_str(p, par.governor);
int first_cpu = atoi(de->d_name + 6);
unsigned long cap = (first_cpu >= 8) ? par.a72_max_khz : par.a53_max_khz;
if (cap > 0) {
snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_max_freq", de->d_name);
snprintf(freq_buf, sizeof(freq_buf), "%lu", cap);
write_sysfs_str(p, freq_buf);
}
}
closedir(d);
}
ensure_run_dir();
write_sysfs_str(PROFILE_FILE, geminux_policy_profile_name(ctx->policy.profile));
struct itimerspec its;
memset(&its, 0, sizeof(its));
if (par.suspend_timeout_s > 0 && !ctx->policy.hdmi_connected && ctx->policy.inhibit_count == 0) {
its.it_value.tv_sec = par.suspend_timeout_s;
}
timerfd_settime(ctx->tmr_fd, 0, &its, NULL);
}
static void toggle_backlight(powerd_ctx_t *ctx, bool on) {
DIR *d = opendir("/sys/class/backlight");
if (!d) return;
struct dirent *de;
while ((de = readdir(d)) != NULL) {
if (de->d_name[0] == '.') continue;
char p[320], cur[32] = {0};
snprintf(p, sizeof(p), "/sys/class/backlight/%s/brightness", de->d_name);
if (!on) {
if (read_sysfs_line(p, cur, sizeof(cur)) == 0 && atoi(cur) > 0) {
ctx->saved_brightness = atoi(cur);
}
write_sysfs_str(p, "0");
} else {
char restore[32];
int val = ctx->saved_brightness > 0 ? ctx->saved_brightness : 128;
snprintf(restore, sizeof(restore), "%d", val);
write_sysfs_str(p, restore);
}
break;
}
closedir(d);
}
static bool is_lock_running(void) {
DIR *d = opendir("/proc");
if (!d) return false;
struct dirent *de;
while ((de = readdir(d)) != NULL) {
if (de->d_name[0] < '0' || de->d_name[0] > '9') continue;
char p[300], comm[32] = {0};
snprintf(p, sizeof(p), "/proc/%s/comm", de->d_name);
if (read_sysfs_line(p, comm, sizeof(comm)) == 0 && strcmp(comm, "geminux-lock") == 0) {
closedir(d);
return true;
}
}
closedir(d);
return false;
}
static void lock_x11_session(void) {
if (access("/tmp/.X11-unix/X0", F_OK) != 0) return;
if (is_lock_running()) return;
struct passwd *pw = getpwuid(10000);
if (!pw) pw = getpwnam("user");
if (!pw) return;
int pfd[2];
if (pipe(pfd) < 0) return;
fcntl(pfd[0], F_SETFD, FD_CLOEXEC);
pid_t pid = fork();
if (pid < 0) {
close(pfd[0]);
close(pfd[1]);
return;
}
if (pid == 0) {
close(pfd[0]);
setsid();
pid_t p2 = fork();
if (p2 == 0) {
int devnull = open("/dev/null", O_RDWR);
if (devnull >= 0) {
if (devnull != STDIN_FILENO) dup2(devnull, STDIN_FILENO);
if (devnull != STDOUT_FILENO) dup2(devnull, STDOUT_FILENO);
if (devnull != STDERR_FILENO) dup2(devnull, STDERR_FILENO);
if (devnull > 2 && devnull != pfd[1]) close(devnull);
}
initgroups(pw->pw_name, pw->pw_gid);
if (setgid(pw->pw_gid) == 0 && setuid(pw->pw_uid) == 0) {
const char *home = (pw->pw_dir && pw->pw_dir[0]) ? pw->pw_dir : "/home/user";
char xauth[256], rfd_str[16];
snprintf(xauth, sizeof(xauth), "%s/.Xauthority", home);
snprintf(rfd_str, sizeof(rfd_str), "%d", pfd[1]);
setenv("HOME", home, 1);
setenv("USER", pw->pw_name, 1);
setenv("LOGNAME", pw->pw_name, 1);
setenv("DISPLAY", ":0", 1);
setenv("XAUTHORITY", xauth, 1);
setenv("GEMINUX_LOCK_READY_FD", rfd_str, 1);
const char *argv[] = {"/usr/bin/geminux-lock", NULL};
execv(argv[0], (char *const *)argv);
}
_exit(127);
}
close(pfd[1]);
_exit(0);
}
close(pfd[1]);
waitpid(pid, NULL, 0);
struct pollfd pf = { .fd = pfd[0], .events = POLLIN };
poll(&pf, 1, 500);
close(pfd[0]);
}
static void trigger_suspend(powerd_ctx_t *ctx) {
lock_x11_session();
toggle_backlight(ctx, false);
write_sysfs_str("/sys/power/mem_sleep", "deep");
if (write_sysfs_str("/sys/power/state", "mem") == 0 ||
write_sysfs_str("/sys/power/state", "freeze") == 0) {
/* Woken back up from suspend */
toggle_backlight(ctx, true);
refresh_ac_and_hdmi(ctx);
apply_cpu_policy(ctx);
} else if (!ctx->policy.lid_closed) {
toggle_backlight(ctx, true);
}
}
static void scan_input_devices(powerd_ctx_t *ctx) {
for (int i = 0; i < ctx->num_ev; i++) {
epoll_ctl(ctx->epfd, EPOLL_CTL_DEL, ctx->ev_fds[i], NULL);
close(ctx->ev_fds[i]);
}
ctx->num_ev = 0;
ctx->policy.lid_closed = false;
for (int i = 0; i < 32 && ctx->num_ev < MAX_EVDEVS; i++) {
char p[64];
snprintf(p, sizeof(p), "/dev/input/event%d", i);
int fd = open(p, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
if (fd < 0) continue;
unsigned long evbits = 0;
if (ioctl(fd, EVIOCGBIT(0, sizeof(evbits)), &evbits) >= 0 &&
((evbits & (1UL << EV_SW)) || (evbits & (1UL << EV_KEY)))) {
if (evbits & (1UL << EV_SW)) {
unsigned long swbits = 0, swstate = 0;
if (ioctl(fd, EVIOCGBIT(EV_SW, sizeof(swbits)), &swbits) >= 0 &&
(swbits & (1UL << SW_LID)) &&
ioctl(fd, EVIOCGSW(sizeof(swstate)), &swstate) >= 0) {
ctx->policy.lid_closed = !!(swstate & (1UL << SW_LID));
}
}
struct epoll_event ev = { .events = EPOLLIN, .data.fd = fd };
if (epoll_ctl(ctx->epfd, EPOLL_CTL_ADD, fd, &ev) == 0) {
ctx->ev_fds[ctx->num_ev++] = fd;
continue;
}
}
close(fd);
}
}
static void handle_client_cmd(powerd_ctx_t *ctx, int cfd) {
char buf[256] = {0};
ssize_t n = read(cfd, buf, sizeof(buf) - 1);
if (n <= 0) return;
while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0';
if (strncmp(buf, "profile ", 8) == 0) {
if (geminux_policy_set_profile_name(&ctx->policy, buf + 8)) {
apply_cpu_policy(ctx);
dprintf(cfd, "OK profile=%s\n", geminux_policy_profile_name(ctx->policy.profile));
} else {
dprintf(cfd, "ERR unknown profile\n");
}
} else if (strcmp(buf, "suspend") == 0) {
dprintf(cfd, "OK suspending\n");
trigger_suspend(ctx);
} else if (strncmp(buf, "inhibit add ", 12) == 0) {
geminux_policy_add_inhibit(&ctx->policy, buf + 12);
apply_cpu_policy(ctx);
dprintf(cfd, "OK inhibits=%d\n", ctx->policy.inhibit_count);
} else if (strncmp(buf, "inhibit del ", 12) == 0) {
geminux_policy_del_inhibit(&ctx->policy, buf + 12);
apply_cpu_policy(ctx);
dprintf(cfd, "OK inhibits=%d\n", ctx->policy.inhibit_count);
} else if (strcmp(buf, "lid-suspend on") == 0) {
ctx->policy.lid_suspend_enabled = true;
dprintf(cfd, "OK lid_suspend=on\n");
} else if (strcmp(buf, "lid-suspend off") == 0) {
ctx->policy.lid_suspend_enabled = false;
dprintf(cfd, "OK lid_suspend=off\n");
} else if (strcmp(buf, "status") == 0) {
dprintf(cfd, "profile=%s ac=%d hdmi=%d lid_closed=%d lid_suspend=%d inhibits=%d\n",
geminux_policy_profile_name(ctx->policy.profile),
ctx->policy.on_ac_power ? 1 : 0,
ctx->policy.hdmi_connected ? 1 : 0,
ctx->policy.lid_closed ? 1 : 0,
ctx->policy.lid_suspend_enabled ? 1 : 0,
ctx->policy.inhibit_count);
} else {
dprintf(cfd, "ERR unknown command\n");
}
}
static int setup_unix_server(void) {
ensure_run_dir();
unlink(SOCK_PATH);
int fd = socket(AF_UNIX, SOCK_STREAM | O_NONBLOCK | O_CLOEXEC, 0);
if (fd < 0) return -1;
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", SOCK_PATH);
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0 || listen(fd, 8) < 0) {
close(fd);
return -1;
}
struct group *gr = getgrnam("wheel");
if (gr) chown(SOCK_PATH, 0, gr->gr_gid);
chmod(SOCK_PATH, 0660);
return fd;
}
static int setup_uevent_socket(void) {
int fd = socket(PF_NETLINK, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT);
if (fd < 0) return -1;
struct sockaddr_nl nls;
memset(&nls, 0, sizeof(nls));
nls.nl_family = AF_NETLINK;
nls.nl_pid = (uint32_t)getpid();
nls.nl_groups = 1;
if (bind(fd, (struct sockaddr *)&nls, sizeof(nls)) < 0) {
close(fd);
return -1;
}
return fd;
}
int main(void) {
signal(SIGPIPE, SIG_IGN);
powerd_ctx_t ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.saved_brightness = 128;
geminux_policy_init(&ctx.policy);
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGTERM);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGHUP);
sigprocmask(SIG_BLOCK, &mask, NULL);
ctx.sig_fd = signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC);
ctx.epfd = epoll_create1(EPOLL_CLOEXEC);
ctx.tmr_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
ctx.srv_fd = setup_unix_server();
ctx.uev_fd = setup_uevent_socket();
int fixed[4] = {ctx.sig_fd, ctx.tmr_fd, ctx.srv_fd, ctx.uev_fd};
for (int i = 0; i < 4; i++) {
if (fixed[i] >= 0) {
struct epoll_event ev = { .events = EPOLLIN, .data.fd = fixed[i] };
epoll_ctl(ctx.epfd, EPOLL_CTL_ADD, fixed[i], &ev);
}
}
refresh_ac_and_hdmi(&ctx);
scan_input_devices(&ctx);
apply_cpu_policy(&ctx);
struct epoll_event events[16];
bool running = true;
while (running) {
int n = epoll_wait(ctx.epfd, events, 16, -1);
if (n < 0) {
if (errno == EINTR) continue;
break;
}
for (int i = 0; i < n; i++) {
int fd = events[i].data.fd;
if (fd == ctx.sig_fd) {
struct signalfd_siginfo si;
while (read(ctx.sig_fd, &si, sizeof(si)) > 0) {
if (si.ssi_signo == SIGHUP) {
refresh_ac_and_hdmi(&ctx);
apply_cpu_policy(&ctx);
} else {
running = false;
}
}
} else if (fd == ctx.srv_fd) {
int cfd;
while ((cfd = accept4(ctx.srv_fd, NULL, NULL, SOCK_CLOEXEC)) >= 0) {
handle_client_cmd(&ctx, cfd);
close(cfd);
}
} else if (fd == ctx.tmr_fd) {
uint64_t exp = 0;
while (read(ctx.tmr_fd, &exp, sizeof(exp)) > 0) {}
refresh_ac_and_hdmi(&ctx);
if (!ctx.policy.on_ac_power && !ctx.policy.hdmi_connected && ctx.policy.inhibit_count == 0) {
trigger_suspend(&ctx);
}
} else if (fd == ctx.uev_fd) {
char ubuf[2048];
ssize_t ur;
bool need_ev_rescan = false;
while ((ur = recv(ctx.uev_fd, ubuf, sizeof(ubuf), 0)) > 0) {
if (memmem(ubuf, (size_t)ur, "SUBSYSTEM=input", 15)) {
need_ev_rescan = true;
}
}
if (need_ev_rescan) scan_input_devices(&ctx);
refresh_ac_and_hdmi(&ctx);
apply_cpu_policy(&ctx);
} else {
struct input_event iev;
while (read(fd, &iev, sizeof(iev)) == (ssize_t)sizeof(iev)) {
if (iev.type == EV_SW && iev.code == SW_LID) {
ctx.policy.lid_closed = (iev.value != 0);
if (ctx.policy.lid_closed) {
lock_x11_session();
if (geminux_should_suspend_on_lid(&ctx.policy)) {
trigger_suspend(&ctx);
} else {
toggle_backlight(&ctx, false);
}
} else {
toggle_backlight(&ctx, true);
refresh_ac_and_hdmi(&ctx);
apply_cpu_policy(&ctx);
}
} else if (iev.type == EV_KEY && iev.code == KEY_POWER && iev.value == 1) {
trigger_suspend(&ctx);
}
}
}
}
}
unlink(SOCK_PATH);
close(ctx.epfd);
return 0;
}