diff --git a/Makefile b/Makefile index 5c6b8ab..d70dab8 100644 --- a/Makefile +++ b/Makefile @@ -17,6 +17,7 @@ EXEC=macfand BINFLAGS=-g -lconfig -lm ETC_DIR = /etc MACHINES_DIR = $(PREFIX)/macfand/machines +.PHONY: all macfand clean install all: macfand macfand: diff --git a/PKGBUILD b/PKGBUILD index ff40376..96d9362 100644 --- a/PKGBUILD +++ b/PKGBUILD @@ -14,6 +14,7 @@ makedepends=(git make) provides=("${_pkgname}") conflicts=("${_pkgname}") source=("git+$url") +backup=('etc/macfand.conf') options=(!debug strip) md5sums=('SKIP') diff --git a/README.md b/README.md index d868b3f..7cb1e2c 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # macfand -Fan control daemon for Apple Computers running Linux through the applesmc kernel module. +Fan control daemon for Apple Computers running Linux through the applesmc kernel module, +or the macsmc_hwmon driver on Linux 7.3+ (T2 Macs such as the MacPro7,1; load it with +`options macsmc_hwmon fan_control=1`). ## Configuration See the [Configuration](https://github.com/ablakely/macfand/wiki/Configuration) wiki page diff --git a/include/applesmc.h b/include/applesmc.h index dd62177..7c1cb27 100644 --- a/include/applesmc.h +++ b/include/applesmc.h @@ -20,6 +20,7 @@ struct sensor char name[50]; char fname[PATH_MAX]; float value; + bool valid; }; struct fan @@ -28,6 +29,9 @@ struct fan char out_path[PATH_MAX]; char manual_path[PATH_MAX]; int speed; + int last_speed; /* last speed written, 0 = none yet */ + int hw_min; /* fanN_min from sysfs, 0 if unknown */ + int hw_max; /* fanN_max from sysfs, 0 if unknown */ float sensor_avg; }; @@ -38,6 +42,7 @@ struct applesmc int fan_cnt; float temp_avg; int active_sensors; + bool is_macsmc; /* macsmc_hwmon (kernel >= 7.3) instead of applesmc */ struct sensor *sensors; struct fan *fans; @@ -48,5 +53,6 @@ int countFans(char *basePath); void find_applesmc(struct applesmc *smc); void scan_sensors(struct applesmc *smc, struct mfdconfig cfg); void read_sensors(struct applesmc *smc, struct mfdconfig cfg); +void release_fans(struct applesmc *smc); #endif \ No newline at end of file diff --git a/include/config.h b/include/config.h index a103a6e..3159df2 100644 --- a/include/config.h +++ b/include/config.h @@ -14,7 +14,8 @@ #define HWMON_DIR "/sys/class/hwmon" #define APPLESMC_ID "applesmc" -#define SENSKEY_MAXLEN 16 +#define MACSMC_HWMON_ID "macsmc_hwmon" +#define SENSKEY_MAXLEN 48 #define MAXFANS 18 #define MAXSENSORS 100 #define MACHINESDIR "/usr/local/macfand/machines" @@ -44,6 +45,8 @@ struct mfdconfig int temp_avg_ceiling; bool use_avgctrl; int pollingInterval; + int rampdown_deadband; /* ignore slow-downs smaller than this (RPM) */ + int rampdown_step; /* max slow-down per poll (RPM), 0 = unlimited */ char blacklist[MAX_EXCLUDE][SENSKEY_MAXLEN]; int blacklist_cnt; struct fan_ctrl fanctrl[MAXFANS]; diff --git a/macfand.conf b/macfand.conf index 3217057..ef6a27b 100644 --- a/macfand.conf +++ b/macfand.conf @@ -26,7 +26,11 @@ config: #This is an array of elements, such as: #fan_ctrl = ( # { - # # fan 1 + # # fan 1 - follows the HOTTEST of fan_sensors. Besides SMC keys, + # # any hwmon sensor can be named as ":" + # # (see /sys/class/hwmon/*/name and temp*_label), e.g. + # # "coretemp:Package id 0" or "amdgpu:junction". T2 Macs need this: + # # their SMC has no usable CPU die / GPU junction sensor. # fan_sensors = ("TC0P", "TM0P", "TM8P"); # floor = 45; # ceiling = 55; @@ -43,6 +47,12 @@ config: # }, ... #); + #rampdown_deadband / rampdown_step - Smoothing (RPM). Speed-ups always + #apply immediately; slow-downs smaller than the deadband are ignored and + #larger ones are limited to rampdown_step per poll (0 = unlimited). + #rampdown_deadband = 100; + #rampdown_step = 250; + #log_level - Logging Verbosity # 0 - startup/exit logging only # 1 - basic temp / fan logging diff --git a/src/applesmc.c b/src/applesmc.c index affd8e3..1369832 100644 --- a/src/applesmc.c +++ b/src/applesmc.c @@ -69,6 +69,65 @@ int countFans(char *basePath) return fancnt; } +static int read_sysfs_int(const char *path, int *out) +{ + char buf[32]; + int fd = open(path, O_RDONLY); + if (fd < 0) + return -1; + int n = read(fd, buf, sizeof(buf) - 1); + close(fd); + if (n < 1) + return -1; + buf[n] = 0; + *out = atoi(buf); + return 0; +} + +/* Kernel >= 7.3 (T2 Macs): macsmc_hwmon. Attributes live directly in the + * hwmon directory and the hwmon "name" file identifies it. */ +static void find_macsmc_hwmon(struct applesmc *smc) +{ + DIR *d = opendir(HWMON_DIR); + struct dirent *e; + char p[PATH_MAX]; + char name[64]; + + if (d == NULL) + return; + + while ((e = readdir(d)) != NULL && smc->path[0] == 0) + { + if (e->d_name[0] == '.') + continue; + + snprintf(p, sizeof(p), "%s/%s/name", HWMON_DIR, e->d_name); + int fd = open(p, O_RDONLY); + if (fd < 0) + continue; + int n = read(fd, name, sizeof(name) - 1); + close(fd); + if (n < 1) + continue; + name[n] = 0; + char *nl = strchr(name, '\n'); + if (nl) *nl = 0; + + if (strcmp(name, MACSMC_HWMON_ID) == 0) + { + snprintf(p, sizeof(p), "%s/%s", HWMON_DIR, e->d_name); + char *real = realpath(p, NULL); + if (real != NULL) + { + strlcpy(smc->path, real, PATH_MAX); + free(real); + smc->is_macsmc = true; + } + } + } + closedir(d); +} + void find_applesmc(struct applesmc *smc) { int i, ret, fd_name; @@ -125,9 +184,13 @@ void find_applesmc(struct applesmc *smc) closedir(fd_dir); } + smc->is_macsmc = false; + if (smc->path[0] == 0) + find_macsmc_hwmon(smc); + if (smc->path[0] == 0) { - printf("Error: Cannot find applesmc device.\n"); + printf("Error: Cannot find applesmc or macsmc_hwmon device.\n"); exit(-1); } @@ -139,13 +202,34 @@ void find_applesmc(struct applesmc *smc) smc->fans[i].id = i + 1; - sprintf(path, "%s/fan%d_output", smc->path, i+1); - strlcpy(smc->fans[i].out_path, path, PATH_MAX); + if (smc->is_macsmc) + { + /* macsmc_hwmon: writing a value in [min,max] to fanN_target + * switches the fan to manual; writing 0 returns it to the SMC. */ + sprintf(path, "%s/fan%d_target", smc->path, i+1); + strlcpy(smc->fans[i].out_path, path, PATH_MAX); + smc->fans[i].manual_path[0] = 0; + } + else + { + sprintf(path, "%s/fan%d_output", smc->path, i+1); + strlcpy(smc->fans[i].out_path, path, PATH_MAX); + + sprintf(path, "%s/fan%d_manual", smc->path, i+1); + strlcpy(smc->fans[i].manual_path, path, PATH_MAX); + } - sprintf(path, "%s/fan%d_manual", smc->path, i+1); - strlcpy(smc->fans[i].manual_path, path, PATH_MAX); + smc->fans[i].hw_min = 0; + smc->fans[i].hw_max = 0; + sprintf(path, "%s/fan%d_min", smc->path, i+1); + read_sysfs_int(path, &smc->fans[i].hw_min); + sprintf(path, "%s/fan%d_max", smc->path, i+1); + read_sysfs_int(path, &smc->fans[i].hw_max); } + printf("Using %s at %s (%d fans)\n", + smc->is_macsmc ? MACSMC_HWMON_ID : APPLESMC_ID, smc->path, smc->fan_cnt); + free(name_path); } @@ -194,6 +278,25 @@ void scan_sensors(struct applesmc *smc, struct mfdconfig cfg) { printf("Error: cannot open %s\n", fname); } + else if (smc->is_macsmc) + { + char label[256] = {0}; + int n = fread(label, 1, sizeof(label) - 1, fp); + char *open_p = (n > 0) ? strrchr(label, '(') : NULL; + char *close_p = open_p ? strchr(open_p, ')') : NULL; + + memset(smc->sensors[i].key, 0, SENSKEY_MAXLEN); + if (open_p && close_p && close_p > open_p + 1) + { + int klen = min((int)(close_p - open_p - 1), SENSKEY_MAXLEN - 1); + memcpy(smc->sensors[i].key, open_p + 1, klen); + } + else + { + printf("Error: cannot parse label in %s\n", fname); + } + fclose(fp); + } else { int n = fread(key_buf, 1, SENSKEY_MAXLEN - 1, fp); @@ -277,6 +380,93 @@ void scan_sensors(struct applesmc *smc, struct mfdconfig cfg) free(key_buf); } +/* + * External (non-SMC) sensors for per-fan fan_sensors lists, written as + * ":", e.g. "coretemp:Package id 0" or + * "amdgpu:junction". The SMC on T2 Macs has no usable CPU die or GPU + * junction sensor, so these are needed to track real load. + */ +#define MAX_EXT 16 +static struct { char spec[SENSKEY_MAXLEN]; char path[PATH_MAX]; bool warned; } ext[MAX_EXT]; +static int ext_cnt = 0; + +static void resolve_ext(const char *spec, char *out) +{ + char hw[SENSKEY_MAXLEN], p[PATH_MAX], buf[128]; + const char *colon = strchr(spec, ':'); + DIR *d; + struct dirent *e; + + out[0] = 0; + if (!colon) return; + snprintf(hw, sizeof(hw), "%.*s", (int)(colon - spec), spec); + const char *label = colon + 1; + + d = opendir(HWMON_DIR); + if (!d) return; + while ((e = readdir(d)) != NULL && out[0] == 0) + { + if (e->d_name[0] == '.') continue; + snprintf(p, sizeof(p), "%s/%s/name", HWMON_DIR, e->d_name); + FILE *f = fopen(p, "r"); + if (!f) continue; + if (!fgets(buf, sizeof(buf), f)) { fclose(f); continue; } + fclose(f); + buf[strcspn(buf, "\n")] = 0; + if (strcmp(buf, hw) != 0) continue; + + for (int t = 1; t < 64 && out[0] == 0; t++) + { + snprintf(p, sizeof(p), "%s/%s/temp%d_label", HWMON_DIR, e->d_name, t); + f = fopen(p, "r"); + if (!f) continue; + if (fgets(buf, sizeof(buf), f)) + { + buf[strcspn(buf, "\n")] = 0; + if (strcmp(buf, label) == 0) + snprintf(out, PATH_MAX, "%s/%s/temp%d_input", HWMON_DIR, e->d_name, t); + } + fclose(f); + } + } + closedir(d); +} + +/* Returns 1 and sets *val on success. */ +static int read_ext_sensor(const char *spec, float *val) +{ + int i, v; + for (i = 0; i < ext_cnt; i++) + if (strcmp(ext[i].spec, spec) == 0) break; + + if (i == ext_cnt) + { + if (ext_cnt == MAX_EXT) return 0; + strlcpy(ext[i].spec, spec, SENSKEY_MAXLEN); + ext[i].warned = false; + ext_cnt++; + resolve_ext(spec, ext[i].path); + if (ext[i].path[0]) + printf("External sensor %s -> %s\n", spec, ext[i].path); + } + + if (ext[i].path[0] == 0 || read_sysfs_int(ext[i].path, &v) != 0) + { + /* hwmon numbering can change (e.g. module reload): re-resolve */ + resolve_ext(spec, ext[i].path); + if (ext[i].path[0] == 0 || read_sysfs_int(ext[i].path, &v) != 0) + { + if (!ext[i].warned) + printf("Error: external sensor %s not found\n", spec); + ext[i].warned = true; + return 0; + } + } + ext[i].warned = false; + *val = v / 1000.0; + return 1; +} + void read_sensors(struct applesmc *smc, struct mfdconfig cfg) { int i, j, k, cnt, avgcnt, sensorcnt; @@ -290,6 +480,7 @@ void read_sensors(struct applesmc *smc, struct mfdconfig cfg) strlcpy(smc->sensors[i].name, cfg.profile->sensordesc[k].desc, strlen(cfg.profile->sensordesc[k].desc)+1); } + smc->sensors[i].valid = false; if (smc->sensors[i].blacklisted != true) { int fd = open(smc->sensors[i].fname, O_RDONLY); @@ -309,7 +500,13 @@ void read_sensors(struct applesmc *smc, struct mfdconfig cfg) } else { + val_buf[min(n, (int)sizeof(val_buf) - 1)] = 0; + smc->sensors[i].valid = true; smc->sensors[i].value = (float)atoi(val_buf) / 1000.0; + /* macsmc exposes PECI-relative, trend and error keys that + * are <= 0 or nonsense; never let them into averages. */ + if (smc->is_macsmc && (smc->sensors[i].value <= 0.0 || smc->sensors[i].value > 125.0)) + smc->sensors[i].valid = false; if (smc->sensors[i].value <= 0.0 && smc->sensors[i].value != 0.0) smc->sensors[i].value *= -1; } @@ -324,53 +521,82 @@ void read_sensors(struct applesmc *smc, struct mfdconfig cfg) for (i = 0; i < smc->sensor_cnt; i++) { - if (smc->sensors[i].blacklisted != true) + if (smc->sensors[i].blacklisted != true && smc->sensors[i].valid) { smc->temp_avg += smc->sensors[i].value; smc->active_sensors++; } } - smc->temp_avg = smc->temp_avg / smc->active_sensors; + if (smc->active_sensors > 0) + smc->temp_avg = smc->temp_avg / smc->active_sensors; for (i = 0; i < smc->fan_cnt; i++) { + /* Per-fan control uses the HOTTEST listed sensor: averaging a + * cool sensor with a hot one hides exactly the heat we react to. */ tempavg = 0; avgcnt = 0; - cnt = (cfg.fanctrl[i].sensor_cnt > 0) ? cfg.fanctrl[i].sensor_cnt : cfg.profile->fanctrl[i].sensor_cnt; + int use_cfg = cfg.fanctrl[i].sensor_cnt > 0; + cnt = use_cfg ? cfg.fanctrl[i].sensor_cnt : cfg.profile->fanctrl[i].sensor_cnt; for (j = 0; j < cnt; j++) { - if (cfg.fanctrl[i].sensor_cnt > 0) + const char *want = use_cfg ? cfg.fanctrl[i].sensors[j] : cfg.profile->fanctrl[i].sensors[j]; + float v; + + if (strchr(want, ':')) { - for (k = 0; k < MAXSENSORS; k++) + if (read_ext_sensor(want, &v)) { - if (strcmp(cfg.fanctrl[i].sensors[j], smc->sensors[k].key) == 0 && smc->sensors[k].blacklisted != true) - { - tempavg += smc->sensors[k].value; - avgcnt++; - } + if (avgcnt == 0 || v > tempavg) tempavg = v; + avgcnt++; } + continue; } - else + + for (k = 0; k < smc->sensor_cnt; k++) { - for (k = 0; k < MAXSENSORS; k++) + if (strcmp(want, smc->sensors[k].key) == 0 && smc->sensors[k].blacklisted != true && smc->sensors[k].valid) { - if (strcmp(cfg.profile->fanctrl[i].sensors[j], smc->sensors[k].key) == 0 && smc->sensors[k].blacklisted != true) - { - tempavg += smc->sensors[k].value; - avgcnt++; - } + v = smc->sensors[k].value; + if (avgcnt == 0 || v > tempavg) tempavg = v; + avgcnt++; } } } - tempavg = tempavg / avgcnt; - - if (tempavg <= 0.0 && tempavg != 0) - tempavg *= -1; + /* No readable sensor for this fan: fail hot, not cold. */ + if (cnt > 0 && avgcnt == 0) + { + printf("Error: no readable sensors for fan %d, forcing max\n", i + 1); + tempavg = 200.0; + } smc->fans[i].sensor_avg = floor(tempavg); } -} \ No newline at end of file +} + +/* Hand the fans back to the SMC's own control (called on shutdown). */ +void release_fans(struct applesmc *smc) +{ + int i, fd; + + for (i = 0; i < smc->fan_cnt; i++) + { + const char *p = smc->is_macsmc ? smc->fans[i].out_path : smc->fans[i].manual_path; + if (p[0] == 0) + continue; + fd = open(p, O_WRONLY); + if (fd < 0) + { + printf("Error: cannot release fan: %s\n", p); + continue; + } + if (write(fd, "0", 1) < 0) + printf("Error: cannot release fan: %s\n", p); + close(fd); + } + fflush(stdout); +} diff --git a/src/config.c b/src/config.c index 83534b9..a3a2690 100644 --- a/src/config.c +++ b/src/config.c @@ -78,6 +78,16 @@ struct mfdconfig read_cfg(struct mfdconfig config, char *file) config.pollingInterval = 5; } + /* Smoothing: speed-ups always apply immediately; slow-downs are + * deadbanded and rate limited so jittery sensors (e.g. CPU package + * temp) don't make fans hunt up and down every poll. */ + config.rampdown_deadband = 100; + config.rampdown_step = 250; + if (config_lookup_int(cf, "config.rampdown_deadband", &intbase) && intbase >= 0) + config.rampdown_deadband = intbase; + if (config_lookup_int(cf, "config.rampdown_step", &intbase) && intbase >= 0) + config.rampdown_step = intbase; + if (config_lookup_int(cf, "config.log_level", &intbase)) config.log_level = intbase; @@ -111,6 +121,16 @@ struct mfdconfig read_cfg(struct mfdconfig config, char *file) { config_setting_t *fanc = config_setting_get_elem(fan_ctrl, n); + config.fanctrl[n].active = 1; + config.fanctrl[n].use_avgctrl = 0; + config.fanctrl[n].sensor_cnt = 0; + if (config.fanctrl[n].sensors == NULL) + { + config.fanctrl[n].sensors = calloc(MAX_TARGETS, sizeof(char *)); + for (n2 = 0; n2 < MAX_TARGETS; n2++) + config.fanctrl[n].sensors[n2] = calloc(SENSKEY_MAXLEN, sizeof(char)); + } + if (config_setting_lookup_int(fanc, "floor", &intbase)) config.fanctrl[n].floor = intbase; @@ -132,7 +152,7 @@ struct mfdconfig read_cfg(struct mfdconfig config, char *file) fansensors = config_setting_get_member(fanc, "fan_sensors"); if (fansensors != NULL) { - config.fanctrl[n].sensor_cnt = config_setting_length(fansensors); + config.fanctrl[n].sensor_cnt = min(config_setting_length(fansensors), MAX_TARGETS); for (n2 = 0; n2 < config.fanctrl[n].sensor_cnt; n2++) { diff --git a/src/control.c b/src/control.c index 51a1ba8..4075fcb 100644 --- a/src/control.c +++ b/src/control.c @@ -41,7 +41,9 @@ void calc_fan(struct applesmc *smc, struct mfdconfig cfg) fan_max = (cfg.fanctrl[i].max_speed > 0) ? cfg.fanctrl[i].max_speed : cfg.profile->fanctrl[i].max_speed; fan_min = (cfg.fanctrl[i].min_speed > 0) ? cfg.fanctrl[i].min_speed : cfg.profile->fanctrl[i].min_speed; - if (cfg.fanctrl[i].use_avgctrl == 1 || cfg.profile->fanctrl[i].use_avgctrl == 1) + int use_avg = cfg.fanctrl[i].active ? cfg.fanctrl[i].use_avgctrl + : cfg.profile->fanctrl[i].use_avgctrl; + if (use_avg == 1) { avg_ceiling = (cfg.temp_avg_ceiling > 0) ? cfg.temp_avg_ceiling : cfg.profile->defaultcfg->temp_avg_ceiling; avg_floor = (cfg.temp_avg_floor > 0) ? cfg.temp_avg_floor : cfg.profile->defaultcfg->temp_avg_floor; @@ -59,11 +61,14 @@ void calc_fan(struct applesmc *smc, struct mfdconfig cfg) } - fan_window = fan_max - fan_min; - avg_speed = (normalized_temp * fan_window); + /* Linear ramp: fan_min at/below floor, fan_max at/above ceiling. + * (Previously |normalized| * window, which made fans speed up as + * temps fell below the floor and never reached fan_max.) */ + if (normalized_temp < 0.0) normalized_temp = 0.0; + if (normalized_temp > 1.0) normalized_temp = 1.0; - if (avg_speed <= 0.0 && avg_speed != 0.0) - avg_speed *= -1; + fan_window = fan_max - fan_min; + avg_speed = fan_min + (normalized_temp * fan_window); if (avg_speed > fan_max) avg_speed = fan_max; @@ -71,7 +76,20 @@ void calc_fan(struct applesmc *smc, struct mfdconfig cfg) if (avg_speed < fan_min) avg_speed = fan_min; - smc->fans[i].speed = (int)avg_speed; + int want = (int)avg_speed; + int last = smc->fans[i].last_speed; + + if (last > 0 && want < last) + { + /* Deadband never blocks the final step back to fan_min, + * otherwise a fan can park just above minimum forever. */ + if (last - want < cfg.rampdown_deadband && want > fan_min) + want = last; /* hold */ + else if (cfg.rampdown_step > 0 && last - want > cfg.rampdown_step) + want = last - cfg.rampdown_step; /* ease down */ + } + + smc->fans[i].speed = want; } } @@ -82,9 +100,21 @@ void set_fan(struct applesmc *smc, struct mfdconfig cfg) for (i = 0; i < smc->fan_cnt; i++) { - buf = calloc(10, sizeof(char)); - fd = open(smc->fans[i].manual_path, O_WRONLY); - if (fd < 0) + buf = calloc(16, sizeof(char)); + + /* The driver rejects (EINVAL) anything outside the hardware range, + * e.g. a configured max of 2763 when the SMC reports 2762. */ + if (smc->fans[i].hw_max > 0 && smc->fans[i].speed > smc->fans[i].hw_max) + smc->fans[i].speed = smc->fans[i].hw_max; + if (smc->fans[i].hw_min > 0 && smc->fans[i].speed < smc->fans[i].hw_min) + smc->fans[i].speed = smc->fans[i].hw_min; + + fd = (smc->fans[i].manual_path[0] == 0) ? -2 : open(smc->fans[i].manual_path, O_WRONLY); + if (fd == -2) + { + /* macsmc_hwmon: no manual file, writing the target enables manual */ + } + else if (fd < 0) { printf("Error: cannot open fan: %s\n", smc->fans[i].manual_path); } @@ -103,7 +133,10 @@ void set_fan(struct applesmc *smc, struct mfdconfig cfg) else { sprintf(buf, "%d", smc->fans[i].speed); - write(fd, buf, strlen(buf)); + if (write(fd, buf, strlen(buf)) < 0) + printf("Error: write %s to %s failed\n", buf, smc->fans[i].out_path); + else + smc->fans[i].last_speed = smc->fans[i].speed; close(fd); } diff --git a/src/macfan.c b/src/macfan.c index 1a421fc..5ed845c 100644 --- a/src/macfan.c +++ b/src/macfan.c @@ -25,7 +25,9 @@ #define PID_FILE "/var/run/macfand.pid" #define LOG_FILE "/var/log/macfand.log" +#ifndef CFG_FILE #define CFG_FILE "/etc/macfand.conf" +#endif int running = 1; int lock_fd = -1; @@ -39,7 +41,7 @@ struct applesmc *smc; void init() { cf.modelID = malloc(sizeof(char*) *32); - smc = calloc(1, sizeof(struct applesmc *)); + smc = calloc(1, sizeof(struct applesmc)); } @@ -154,6 +156,8 @@ int main(int argc, char *argv[]) sleep(cf.pollingInterval); } + release_fans(smc); + if (lock_fd != -1) { close(lock_fd);