#define _GNU_SOURCE #include "geminux-power-policy.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define SOCK_PATH "/run/geminux/powerd.sock" #define PROFILE_FILE "/run/geminux/power-profile" #define FG_STATE_DIR "/var/lib/geminux" #define FG_STATE_FILE "/var/lib/geminux/fuel-gauge.state" #define FG_SYSFS_DIR "/sys/class/power_supply/battery/device" #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; uint64_t last_input_ms; geminux_idle_stage_t idle_stage; geminux_power_policy_t policy; bool charge_thresh_set; bool fg_restored; bool fg_file_synced; uint32_t saved_fg_r_uohm; uint32_t saved_fg_full_uah; bool policy_applied; geminux_profile_t applied_profile; bool applied_ac; bool applied_a72_ready; bool applied_cpufreq_present; bool applied_interactive_boost; pid_t consys_restore_pid; bool consys_suspended; bool bt_was_loaded; bool bt_was_blocked; bool gnss_was_loaded; bool radio_was_loaded; } powerd_ctx_t; static uint64_t monotonic_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L); } 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 int read_sysfs_u32(const char *path, uint32_t *out) { char buf[48] = {0}; if (read_sysfs_line(path, buf, sizeof(buf)) != 0 || !buf[0]) return -1; char *end = NULL; errno = 0; unsigned long long v = strtoull(buf, &end, 10); if (errno != 0 || end == buf || *end != '\0' || v > 0xffffffffULL) return -1; *out = (uint32_t)v; return 0; } static void restore_fuel_gauge_state(powerd_ctx_t *ctx) { const char *r_path = FG_SYSFS_DIR "/learned_resistance_uohm"; const char *f_path = FG_SYSFS_DIR "/learned_full_uah"; if (access(r_path, F_OK) != 0 || access(f_path, F_OK) != 0) return; FILE *f = fopen(FG_STATE_FILE, "r"); if (f) { char buf[256] = {0}; size_t n = fread(buf, 1, sizeof(buf) - 1, f); fclose(f); buf[n] = '\0'; uint32_t r_val = 0, f_val = 0; if (geminux_fg_state_parse(buf, &r_val, &f_val)) { char r_str[32], f_str[32]; snprintf(r_str, sizeof(r_str), "%u", r_val); snprintf(f_str, sizeof(f_str), "%u", f_val); write_sysfs_str(r_path, r_str); write_sysfs_str(f_path, f_str); ctx->fg_file_synced = true; } } uint32_t cur_r = 0, cur_f = 0; if (read_sysfs_u32(r_path, &cur_r) == 0 && read_sysfs_u32(f_path, &cur_f) == 0) { ctx->saved_fg_r_uohm = cur_r; ctx->saved_fg_full_uah = cur_f; } ctx->fg_restored = true; } static void save_fuel_gauge_state(powerd_ctx_t *ctx) { uint32_t r_val = 0, f_val = 0; if (read_sysfs_u32(FG_SYSFS_DIR "/learned_resistance_uohm", &r_val) != 0 || read_sysfs_u32(FG_SYSFS_DIR "/learned_full_uah", &f_val) != 0) { return; } char content[128]; if (geminux_fg_state_format(r_val, f_val, content, sizeof(content)) != 0) return; if (ctx->fg_file_synced && r_val == ctx->saved_fg_r_uohm && f_val == ctx->saved_fg_full_uah) { return; } mkdir("/var/lib", 0755); mkdir(FG_STATE_DIR, 0755); char tmp_path[128]; snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", FG_STATE_FILE); int fd = open(tmp_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd < 0) return; size_t len = strlen(content), off = 0; bool ok = true; while (off < len) { ssize_t w = write(fd, content + off, len - off); if (w <= 0) { if (w < 0 && errno == EINTR) continue; ok = false; break; } off += (size_t)w; } if (ok && fsync(fd) != 0) ok = false; if (close(fd) != 0) ok = false; if (ok && rename(tmp_path, FG_STATE_FILE) == 0) { ctx->saved_fg_r_uohm = r_val; ctx->saved_fg_full_uah = f_val; ctx->fg_file_synced = true; } else { unlink(tmp_path); } } static void refresh_ac_and_hdmi(powerd_ctx_t *ctx) { if (!ctx->charge_thresh_set) { if (write_sysfs_str("/sys/class/power_supply/battery/charge_control_end_threshold", "100") == 0) { ctx->charge_thresh_set = true; } } 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 lock_x11_session(void); static void trigger_suspend(powerd_ctx_t *ctx); static void apply_cpu_sysfs(powerd_ctx_t *ctx, bool force); static void apply_cpu_policy(powerd_ctx_t *ctx, bool force); static void save_active_brightness(powerd_ctx_t *ctx, const char *bri_path) { if (ctx->idle_stage != IDLE_STAGE_ACTIVE) return; char cur[32] = {0}; if (read_sysfs_line(bri_path, cur, sizeof(cur)) == 0 && atoi(cur) > 0) { ctx->saved_brightness = atoi(cur); } } 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]; snprintf(p, sizeof(p), "/sys/class/backlight/%s/brightness", de->d_name); if (!on) { save_active_brightness(ctx, p); write_sysfs_str(p, "0"); } else { char pwr[320]; snprintf(pwr, sizeof(pwr), "/sys/class/backlight/%s/bl_power", de->d_name); write_sysfs_str(pwr, "0"); 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 void dim_backlight(powerd_ctx_t *ctx) { 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], max_buf[32] = {0}; snprintf(p, sizeof(p), "/sys/class/backlight/%s/brightness", de->d_name); save_active_brightness(ctx, p); int max_bri = 255; snprintf(p, sizeof(p), "/sys/class/backlight/%s/max_brightness", de->d_name); if (read_sysfs_line(p, max_buf, sizeof(max_buf)) == 0 && atoi(max_buf) > 0) { max_bri = atoi(max_buf); } int cur_base = ctx->saved_brightness > 0 ? ctx->saved_brightness : 128; int target = cur_base / 5; int min_floor = max_bri / 20; if (target < min_floor) target = min_floor; if (target >= cur_base) target = cur_base / 2; if (target < 4) target = 4; if (target > cur_base) target = cur_base; char dim_str[32]; snprintf(dim_str, sizeof(dim_str), "%d", target); snprintf(p, sizeof(p), "/sys/class/backlight/%s/brightness", de->d_name); write_sysfs_str(p, dim_str); break; } closedir(d); } static void arm_timer_ms(int tmr_fd, uint64_t wait_ms) { struct itimerspec its; memset(&its, 0, sizeof(its)); if (wait_ms > 0) { its.it_value.tv_sec = (time_t)(wait_ms / 1000ULL); its.it_value.tv_nsec = (long)((wait_ms % 1000ULL) * 1000000ULL); if (its.it_value.tv_sec == 0 && its.it_value.tv_nsec == 0) { its.it_value.tv_nsec = 1000000L; } } timerfd_settime(tmr_fd, 0, &its, NULL); } static void evaluate_idle(powerd_ctx_t *ctx) { uint64_t now = monotonic_ms(); uint64_t elapsed = (now >= ctx->last_input_ms) ? (now - ctx->last_input_ms) : 0; uint64_t next_wait_ms = 0; geminux_idle_action_t act = geminux_policy_eval_idle(&ctx->policy, ctx->idle_stage, elapsed, &next_wait_ms); if (act == IDLE_ACT_DIM) { dim_backlight(ctx); ctx->idle_stage = IDLE_STAGE_DIMMED; apply_cpu_sysfs(ctx, false); arm_timer_ms(ctx->tmr_fd, next_wait_ms); } else if (act == IDLE_ACT_LOCK_BLANK) { lock_x11_session(); toggle_backlight(ctx, false); ctx->idle_stage = IDLE_STAGE_LOCKED_BLANK; apply_cpu_sysfs(ctx, false); arm_timer_ms(ctx->tmr_fd, 0); } else if (act == IDLE_ACT_SUSPEND) { arm_timer_ms(ctx->tmr_fd, 0); trigger_suspend(ctx); } else { arm_timer_ms(ctx->tmr_fd, next_wait_ms); } } static void note_user_activity(powerd_ctx_t *ctx) { ctx->last_input_ms = monotonic_ms(); if (ctx->idle_stage != IDLE_STAGE_ACTIVE) { ctx->idle_stage = IDLE_STAGE_ACTIVE; toggle_backlight(ctx, true); apply_cpu_sysfs(ctx, false); evaluate_idle(ctx); } } static void apply_cpu_sysfs(powerd_ctx_t *ctx, bool force) { bool a72_ready = (access("/sys/module/mt6797_a72", F_OK) == 0); bool cpufreq_present = (access("/sys/devices/system/cpu/cpufreq/policy0", F_OK) == 0); bool interactive_boost = (ctx->policy.profile == POWER_PROFILE_BALANCED && ctx->idle_stage == IDLE_STAGE_ACTIVE && !ctx->policy.lid_closed); if (!force && ctx->policy_applied && ctx->applied_profile == ctx->policy.profile && ctx->applied_ac == ctx->policy.on_ac_power && ctx->applied_a72_ready == a72_ready && ctx->applied_cpufreq_present == cpufreq_present && ctx->applied_interactive_boost == interactive_boost) { return; } geminux_profile_params_t par = geminux_policy_params(ctx->policy.profile, ctx->policy.on_ac_power); 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], min_buf[32] = "221000", max_hw_buf[32] = {0}; int first_cpu = atoi(de->d_name + 6); snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/cpuinfo_min_freq", de->d_name); (void)read_sysfs_line(p, min_buf, sizeof(min_buf)); snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/cpuinfo_max_freq", de->d_name); unsigned long hw_max = (read_sysfs_line(p, max_hw_buf, sizeof(max_hw_buf)) == 0) ? strtoul(max_hw_buf, NULL, 10) : 0UL; snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_governor", de->d_name); write_sysfs_str(p, par.governor); unsigned long cap = (first_cpu >= 8) ? par.a72_max_khz : (first_cpu >= 4) ? par.a53_max_khz : par.a53_ll_max_khz; if (hw_max > 0 && (cap == 0 || cap > hw_max)) { cap = hw_max; } /* Reset floor before adjusting ceiling so scaling_min_freq never blocks scaling_max_freq. */ snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_min_freq", de->d_name); write_sysfs_str(p, min_buf); 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); if (interactive_boost && first_cpu < 8) { snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_min_freq", de->d_name); write_sysfs_str(p, freq_buf); } } } closedir(d); } if (force || !ctx->policy_applied || ctx->applied_profile != ctx->policy.profile) { ensure_run_dir(); write_sysfs_str(PROFILE_FILE, geminux_policy_profile_name(ctx->policy.profile)); } ctx->policy_applied = true; ctx->applied_profile = ctx->policy.profile; ctx->applied_ac = ctx->policy.on_ac_power; ctx->applied_a72_ready = a72_ready; ctx->applied_cpufreq_present = cpufreq_present; ctx->applied_interactive_boost = interactive_boost; } static void apply_cpu_policy(powerd_ctx_t *ctx, bool force) { apply_cpu_sysfs(ctx, force); evaluate_idle(ctx); } 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 int run_cmd_sync(const char *const argv[]) { pid_t pid = fork(); if (pid < 0) return -1; if (pid == 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) close(devnull); } execv(argv[0], (char *const *)argv); _exit(127); } int st = 0; while (waitpid(pid, &st, 0) < 0) { if (errno != EINTR) return -1; } return (WIFEXITED(st) && WEXITSTATUS(st) == 0) ? 0 : -1; } static void reap_consys_restore(powerd_ctx_t *ctx, bool wait_block) { if (ctx->consys_restore_pid <= 0) return; int opts = wait_block ? 0 : WNOHANG; pid_t r; do { r = waitpid(ctx->consys_restore_pid, NULL, opts); } while (r < 0 && errno == EINTR); if (r == ctx->consys_restore_pid || (r < 0 && errno == ECHILD)) { ctx->consys_restore_pid = -1; } } static bool is_bt_rfkill_soft_blocked(void) { DIR *d = opendir("/sys/class/rfkill"); if (!d) return true; bool found = false; bool blocked = true; struct dirent *de; while ((de = readdir(d)) != NULL) { if (de->d_name[0] == '.') continue; char p[320], typ[32] = {0}, soft[16] = {0}; snprintf(p, sizeof(p), "/sys/class/rfkill/%s/type", de->d_name); if (read_sysfs_line(p, typ, sizeof(typ)) == 0 && strcmp(typ, "bluetooth") == 0) { found = true; snprintf(p, sizeof(p), "/sys/class/rfkill/%s/soft", de->d_name); if (read_sysfs_line(p, soft, sizeof(soft)) == 0 && atoi(soft) == 0) { blocked = false; } } } closedir(d); return found ? blocked : true; } static void set_bt_rfkill_soft_blocked(bool blocked) { DIR *d = opendir("/sys/class/rfkill"); if (d) { struct dirent *de; while ((de = readdir(d)) != NULL) { if (de->d_name[0] == '.') continue; char p[320], typ[32] = {0}; snprintf(p, sizeof(p), "/sys/class/rfkill/%s/type", de->d_name); if (read_sysfs_line(p, typ, sizeof(typ)) == 0 && strcmp(typ, "bluetooth") == 0) { snprintf(p, sizeof(p), "/sys/class/rfkill/%s/soft", de->d_name); write_sysfs_str(p, blocked ? "1" : "0"); } } closedir(d); } if (blocked) { const char *argv[] = {"/usr/sbin/rfkill", "block", "bluetooth", NULL}; run_cmd_sync(argv); } } /* mt6797_consys_prepare() refuses suspend with -EBUSY while CONN is powered; * unloading reverse dependents lets mt6797_consys_remove() power off CONN/VCN rails. */ static void prepare_consys_for_suspend(powerd_ctx_t *ctx) { reap_consys_restore(ctx, true); if (access("/sys/module/mt6797_consys", F_OK) != 0) { ctx->consys_suspended = false; return; } ctx->consys_suspended = true; ctx->bt_was_loaded = (access("/sys/module/btmt6797", F_OK) == 0); ctx->bt_was_blocked = ctx->bt_was_loaded ? is_bt_rfkill_soft_blocked() : true; ctx->gnss_was_loaded = (access("/sys/module/gnss_mt6797", F_OK) == 0); ctx->radio_was_loaded = (access("/sys/module/radio_mt6797", F_OK) == 0); static const char *const mods[] = { "btmt6797", "radio_mt6797", "gnss_mt6797", "mac", "mt6797_consys", }; for (size_t i = 0; i < sizeof(mods) / sizeof(mods[0]); i++) { char mpath[128]; snprintf(mpath, sizeof(mpath), "/sys/module/%s", mods[i]); if (access(mpath, F_OK) == 0) { const char *argv[] = {"/sbin/rmmod", mods[i], NULL}; run_cmd_sync(argv); } } } static void restore_consys_after_resume(powerd_ctx_t *ctx) { if (!ctx->consys_suspended) return; ctx->consys_suspended = false; reap_consys_restore(ctx, true); bool bt_loaded = ctx->bt_was_loaded; bool bt_blocked = ctx->bt_was_blocked; bool gnss_loaded = ctx->gnss_was_loaded; bool radio_loaded = ctx->radio_was_loaded; pid_t pid = fork(); if (pid < 0) return; if (pid == 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) close(devnull); } const char *wlan_core[] = {"/sbin/modprobe", "mt6797-wlan-core", NULL}; const char *consys[] = {"/sbin/modprobe", "mt6797-consys", NULL}; const char *mac[] = {"/sbin/modprobe", "mac", NULL}; run_cmd_sync(wlan_core); run_cmd_sync(consys); run_cmd_sync(mac); if (bt_loaded) { const char *bt[] = {"/sbin/modprobe", "btmt6797", NULL}; run_cmd_sync(bt); if (bt_blocked) { set_bt_rfkill_soft_blocked(true); } } if (gnss_loaded) { const char *gnss[] = {"/sbin/modprobe", "gnss-mt6797", NULL}; run_cmd_sync(gnss); } if (radio_loaded) { const char *radio[] = {"/sbin/modprobe", "radio-mt6797", NULL}; run_cmd_sync(radio); } _exit(0); } ctx->consys_restore_pid = pid; } static void refresh_lid_state(powerd_ctx_t *ctx) { for (int i = 0; i < ctx->num_ev; i++) { unsigned long evbits = 0; if (ioctl(ctx->ev_fds[i], EVIOCGBIT(0, sizeof(evbits)), &evbits) >= 0 && (evbits & (1UL << EV_SW))) { unsigned long swbits = 0, swstate = 0; if (ioctl(ctx->ev_fds[i], EVIOCGBIT(EV_SW, sizeof(swbits)), &swbits) >= 0 && (swbits & (1UL << SW_LID)) && ioctl(ctx->ev_fds[i], EVIOCGSW(sizeof(swstate)), &swstate) >= 0) { ctx->policy.lid_closed = !!(swstate & (1UL << SW_LID)); } } } } /* gpio-keys SW_LID applies a 64 ms debounce timer on wakeup; wait up to * timeout_ms using poll() so a lid-open wake sees SW_LID == 0 before we * decide whether to light the backlight. */ static void wait_post_resume_lid_events(powerd_ctx_t *ctx, int timeout_ms) { refresh_lid_state(ctx); if (!ctx->policy.lid_closed || ctx->num_ev <= 0) return; uint64_t deadline = monotonic_ms() + (uint64_t)timeout_ms; struct pollfd pfds[MAX_EVDEVS]; while (ctx->policy.lid_closed) { uint64_t now = monotonic_ms(); if (now >= deadline) break; int slice = (int)(deadline - now); if (slice > 20) slice = 20; for (int i = 0; i < ctx->num_ev; i++) { pfds[i].fd = ctx->ev_fds[i]; pfds[i].events = POLLIN; pfds[i].revents = 0; } int pr = poll(pfds, (nfds_t)ctx->num_ev, slice); if (pr < 0) { if (errno == EINTR) continue; break; } for (int i = 0; i < ctx->num_ev; i++) { if (!(pfds[i].revents & POLLIN)) continue; struct input_event iev; while (read(ctx->ev_fds[i], &iev, sizeof(iev)) == (ssize_t)sizeof(iev)) { if (iev.type == EV_SW && iev.code == SW_LID) { ctx->policy.lid_closed = (iev.value != 0); } else if (iev.type == EV_KEY || iev.type == EV_REL || iev.type == EV_ABS) { ctx->last_input_ms = monotonic_ms(); } } } refresh_lid_state(ctx); } } static void prepare_cpus_for_suspend(void) { 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], min_buf[32] = "221000"; snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/cpuinfo_min_freq", de->d_name); (void)read_sysfs_line(p, min_buf, sizeof(min_buf)); snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_min_freq", de->d_name); write_sysfs_str(p, min_buf); snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_governor", de->d_name); write_sysfs_str(p, "powersave"); snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpufreq/%s/scaling_max_freq", de->d_name); write_sysfs_str(p, min_buf); } closedir(d); } for (int cpu = 9; cpu >= 1; cpu--) { char p[128]; snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpu%d/online", cpu); write_sysfs_str(p, "0"); } } static void restore_cpus_after_resume(powerd_ctx_t *ctx) { for (int cpu = 1; cpu <= 7; cpu++) { char p[128]; snprintf(p, sizeof(p), "/sys/devices/system/cpu/cpu%d/online", cpu); write_sysfs_str(p, "1"); } ctx->policy_applied = false; } static void trigger_suspend(powerd_ctx_t *ctx) { arm_timer_ms(ctx->tmr_fd, 0); lock_x11_session(); toggle_backlight(ctx, false); save_fuel_gauge_state(ctx); prepare_consys_for_suspend(ctx); prepare_cpus_for_suspend(); write_sysfs_str("/sys/power/mem_sleep", "deep"); bool suspended = (write_sysfs_str("/sys/power/state", "mem") == 0 || write_sysfs_str("/sys/power/state", "freeze") == 0); restore_cpus_after_resume(ctx); restore_consys_after_resume(ctx); wait_post_resume_lid_events(ctx, 90); refresh_ac_and_hdmi(ctx); if (suspended && !ctx->policy.lid_closed) { ctx->idle_stage = IDLE_STAGE_ACTIVE; ctx->last_input_ms = monotonic_ms(); toggle_backlight(ctx, true); apply_cpu_policy(ctx, true); } else { toggle_backlight(ctx, false); ctx->idle_stage = IDLE_STAGE_LOCKED_BLANK; arm_timer_ms(ctx->tmr_fd, 0); apply_cpu_sysfs(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) | (1UL << EV_KEY) | (1UL << EV_REL) | (1UL << EV_ABS)))) { 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, false); 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, false); 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, false); 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.consys_restore_pid = -1; 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); } } ctx.last_input_ms = monotonic_ms(); ctx.idle_stage = IDLE_STAGE_ACTIVE; restore_fuel_gauge_state(&ctx); refresh_ac_and_hdmi(&ctx); scan_input_devices(&ctx); apply_cpu_policy(&ctx, true); struct epoll_event events[16]; bool running = true; while (running) { int n = epoll_wait(ctx.epfd, events, 16, -1); reap_consys_restore(&ctx, false); 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, true); } 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); evaluate_idle(&ctx); } else if (fd == ctx.uev_fd) { char ubuf[2048]; ssize_t ur; bool need_ev_rescan = false; bool need_ps = false; bool need_ps_or_drm = false; while ((ur = recv(ctx.uev_fd, ubuf, sizeof(ubuf), 0)) > 0) { if (geminux_uevent_has_subsystem(ubuf, (size_t)ur, "input")) { need_ev_rescan = true; } if (geminux_uevent_has_subsystem(ubuf, (size_t)ur, "power_supply")) { need_ps = true; need_ps_or_drm = true; } else if (geminux_uevent_has_subsystem(ubuf, (size_t)ur, "drm")) { need_ps_or_drm = true; } } if (need_ev_rescan) scan_input_devices(&ctx); if (need_ps) { if (!ctx.fg_restored) { restore_fuel_gauge_state(&ctx); } else { save_fuel_gauge_state(&ctx); } } if (need_ps_or_drm) { bool prev_ac = ctx.policy.on_ac_power; bool prev_hdmi = ctx.policy.hdmi_connected; refresh_ac_and_hdmi(&ctx); if (prev_ac != ctx.policy.on_ac_power || prev_hdmi != ctx.policy.hdmi_connected) { if (!ctx.policy.lid_closed) { note_user_activity(&ctx); } apply_cpu_policy(&ctx, false); } } } else { struct input_event iev; bool saw_activity = false; bool power_pressed = false; 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(); evaluate_idle(&ctx); if (geminux_should_suspend_on_lid(&ctx.policy)) { trigger_suspend(&ctx); } else { toggle_backlight(&ctx, false); } } else { ctx.idle_stage = IDLE_STAGE_ACTIVE; ctx.last_input_ms = monotonic_ms(); toggle_backlight(&ctx, true); refresh_ac_and_hdmi(&ctx); apply_cpu_policy(&ctx, true); } } else if (iev.type == EV_KEY && iev.code == KEY_POWER && iev.value == 1) { if (ctx.idle_stage == IDLE_STAGE_LOCKED_BLANK) { note_user_activity(&ctx); } else { power_pressed = true; } } else if (iev.type == EV_KEY || iev.type == EV_REL || iev.type == EV_ABS) { saw_activity = true; } } if (power_pressed) { trigger_suspend(&ctx); } else if (saw_activity && !ctx.policy.lid_closed) { note_user_activity(&ctx); } } } } save_fuel_gauge_state(&ctx); unlink(SOCK_PATH); close(ctx.epfd); return 0; }