diff --git a/README.md b/README.md
index 7f7d10a..030d4b6 100644
--- a/README.md
+++ b/README.md
@@ -200,6 +200,25 @@ reappear after serial ambiguity is resolved.
The identity identifies the controller's header, not the physical fan attached
to it; replacing the fan does not change the saved assignment.
+## Temperature sensor identity
+
+CPU and auxiliary hwmon sensors are listed as `/sys/class/hwmon/hwmonN` paths,
+and `hwmonN` follows probe order: on a machine with NVMe drives, which register
+hwmon devices too, the CPU or board sensor can come up under another number
+after a reboot. Each selected sensor is therefore also saved with the chip
+name, its device path below `/sys/devices`, and its `tempN` input, for example
+`hwmon:coretemp:temp1:platform/coretemp.0`, in `cpu_sensor_identity` and
+`aux_sensor_identity`. The runtime paths are resolved again whenever the
+service starts, and existing configurations get their identities recorded at
+that point, from the sensors their saved paths name then.
+
+A sensor whose identity is missing or matches more than one input is not
+replaced by another one. It keeps its identity in place of the path, has no
+reading, and triggers the missing-sensor warning described above; the
+settings page lists it as not found and keeps it selected until the sensor
+is back or another one is chosen. Tool and script sensors (`storcli:`,
+`nvidia:`, `mlx:`, `custom:`) are saved as they are.
+
## MSI boards with the nct6687 driver
On some MSI boards the nct6687 driver accepts speed changes for the system
diff --git a/src/usr/local/emhttp/plugins/fanctrlplus2/include/Common.php b/src/usr/local/emhttp/plugins/fanctrlplus2/include/Common.php
index a1d0adb..5767ed5 100644
--- a/src/usr/local/emhttp/plugins/fanctrlplus2/include/Common.php
+++ b/src/usr/local/emhttp/plugins/fanctrlplus2/include/Common.php
@@ -318,18 +318,116 @@ function migrate_cfg_and_labels(string $plugin, string $cfgpath = '', string $hw
if ($new_path !== $old_path) log_migrate("migrate cfg: $cfgfile controller: $old_path → $new_path");
}
if ($ini === $original) continue;
- // Only these two fields changed. Re-serializing the entire INI would
- // re-escape free-text values that are also sourced by the shell.
- $buf = (string)file_get_contents($cfgfile);
- foreach (['controller', 'controller_identity'] as $k) {
- $v = str_replace(["\\", '"', '$', '`', "\r", "\n"], ["\\\\", '\\"', '\\$', '\\`', '', ''], (string)$ini[$k]);
- $line = "$k=\"$v\"";
- $buf = preg_replace_callback('/^[ \t]*'.$k.'[ \t]*=.*$/m', function () use ($line) { return $line; }, $buf, -1, $count);
- if ($count === 0) $buf = rtrim($buf, "\n")."\n".$line."\n";
+ fcp_rewrite_cfg_fields($cfgfile, ['controller' => $ini['controller'], 'controller_identity' => $ini['controller_identity']]);
+ }
+
+ fcp_migrate_sensors($cfgfiles, fcp_sensor_identity_map($hwmon_glob));
+}
+
+// Only the given fields change. Re-serializing the entire INI would
+// re-escape free-text values that are also sourced by the shell.
+function fcp_rewrite_cfg_fields(string $cfgfile, array $fields): void {
+ $buf = (string)file_get_contents($cfgfile);
+ foreach ($fields as $k => $v) {
+ $v = str_replace(["\\", '"', '$', '`', "\r", "\n"], ["\\\\", '\\"', '\\$', '\\`', '', ''], (string)$v);
+ $line = "$k=\"$v\"";
+ $buf = preg_replace_callback('/^[ \t]*'.$k.'[ \t]*=.*$/m', function () use ($line) { return $line; }, $buf, -1, $count);
+ if ($count === 0) $buf = rtrim($buf, "\n")."\n".$line."\n";
+ }
+ safe_rewrite($cfgfile, $buf);
+}
+
+// A temperature input is the tempN channel of a named hwmon chip on a device.
+// Its /sys/class/hwmon/hwmonN path follows probe order instead, so on a box
+// with NVMe drives (which register hwmon devices too) the CPU or board
+// sensor can come up under another hwmonN after a reboot, and the saved path
+// then names a different sensor. The identity is readable, and holds nothing
+// a cfg value, the shell or the comma-separated aux list would need to
+// escape; a chip whose name or device path holds anything else keeps its
+// path binding.
+const FCP_SENSOR_IDENTITY = '#^hwmon:([A-Za-z0-9_]+):(temp\d+):([A-Za-z0-9_.:/-]+)$#D';
+
+function fcp_sensor_identity(string $path): ?string {
+ if (!preg_match('#/(temp\d+)_input$#', $path, $t)) return null;
+ $hwmon = realpath(dirname($path));
+ if ($hwmon === false || !is_file("$hwmon/{$t[1]}_input")) return null;
+ // The device the hwmon node belongs to, without the hwmonN index:
+ // platform/coretemp.0/hwmon/hwmon4 and .../nvme/nvme0/hwmon1 alike.
+ if (!preg_match('#/devices/(.+?)(?:/hwmon)?/hwmon\d+$#', $hwmon, $d)) return null;
+ if (preg_match('#(?:^|/)\.\.?(?:/|$)#', $d[1])) return null;
+ $key = 'hwmon:'.trim((string)@file_get_contents("$hwmon/name")).":{$t[1]}:{$d[1]}";
+ return preg_match(FCP_SENSOR_IDENTITY, $key) ? $key : null;
+}
+
+// Every temperature input under the hwmon glob, by identity, at the
+// /sys/class/hwmon path the settings page lists. Two inputs that share an
+// identity pin neither one (null), so neither is guessed.
+function fcp_sensor_identity_map(string $hwmon_glob = '/sys/class/hwmon/hwmon*'): array {
+ $map = [];
+ foreach (glob($hwmon_glob) ?: [] as $hwmon) {
+ foreach (glob("$hwmon/temp*_input") ?: [] as $input) {
+ $key = fcp_sensor_identity($input);
+ if ($key === null) continue;
+ $map[$key] = array_key_exists($key, $map) ? null : $input;
+ }
+ }
+ return $map;
+}
+
+// What to save for one selected sensor: its identity while that uniquely
+// names this input, else the value itself (a path binding, or a sensor such
+// as storcli:c0:roc or custom:ambient, which is already stable).
+function fcp_sensor_binding(string $sensor, array $identities): string {
+ if (preg_match(FCP_SENSOR_IDENTITY, $sensor)) return $sensor;
+ $key = fcp_sensor_identity($sensor);
+ if ($key === null || ($identities[$key] ?? null) === null) return $sensor;
+ return realpath($identities[$key]) === realpath($sensor) ? $key : $sensor;
+}
+
+// Resolve every fan's CPU and aux sensors again, as the controller is above.
+// cpu_sensor_identity and aux_sensor_identity hold the bindings and win over
+// the runtime paths; a config without them gets them recorded from its
+// current paths. A missing or ambiguous identity is not replaced by another
+// sensor: the runtime value becomes the identity itself, which has no
+// reading, so the fan's missing-sensor warning names it, and the binding
+// stays saved until the sensor is back.
+function fcp_migrate_sensors(array $cfgfiles, array $identities): void {
+ foreach ($cfgfiles as $cfgfile) {
+ $ini = @parse_ini_file($cfgfile);
+ if (!$ini) continue;
+ $fields = [];
+ foreach (['cpu_sensor', 'aux_sensor'] as $k) {
+ $saved = (string)($ini["{$k}_identity"] ?? $ini[$k] ?? '');
+ $paths = []; $bindings = [];
+ foreach ($saved === '' ? [] : explode(',', $saved) as $entry) {
+ if ($entry === '') continue;
+ if (preg_match(FCP_SENSOR_IDENTITY, $entry)) {
+ $path = $identities[$entry] ?? null;
+ if ($path === null) log_migrate("migrate sensor: no match for $entry in $cfgfile, keep identity");
+ $paths[] = $path ?? $entry;
+ $bindings[] = $entry;
+ } else {
+ $paths[] = $entry;
+ $bindings[] = fcp_sensor_binding($entry, $identities);
+ }
+ }
+ $fields[$k] = implode(',', $paths);
+ $fields["{$k}_identity"] = implode(',', $bindings);
}
- safe_rewrite($cfgfile, $buf);
+ $changed = array_filter($fields, fn($v, $k) => (string)($ini[$k] ?? '') !== $v, ARRAY_FILTER_USE_BOTH);
+ if (!$changed) continue;
+ foreach (['cpu_sensor', 'aux_sensor'] as $k) {
+ if (isset($changed[$k])) log_migrate("migrate cfg: $cfgfile $k: ".($ini[$k] ?? '')." → {$fields[$k]}");
+ }
+ fcp_rewrite_cfg_fields($cfgfile, $changed);
}
}
+
+// How the settings page lists a saved sensor it did not find this time.
+function fcp_sensor_unavailable_label(string $sensor): string {
+ if (preg_match(FCP_SENSOR_IDENTITY, $sensor, $m)) return "Not found: {$m[1]} - {$m[2]} ({$m[3]})";
+ return "No reading: $sensor";
+}
// ================================
// END: Migrate hwmonX (cfg+labels)
// ================================
diff --git a/src/usr/local/emhttp/plugins/fanctrlplus2/include/ConfigBackup.php b/src/usr/local/emhttp/plugins/fanctrlplus2/include/ConfigBackup.php
index 99dd8ef..3e6d47d 100644
--- a/src/usr/local/emhttp/plugins/fanctrlplus2/include/ConfigBackup.php
+++ b/src/usr/local/emhttp/plugins/fanctrlplus2/include/ConfigBackup.php
@@ -1,4 +1,5 @@
$value) {
$group = preg_match('/^disk_group_(\d+)_(name|disks|low|high)$/D', $key, $m);
if ($group && (strlen($m[1]) > 3 || (int)$m[1] > 255)) throw new InvalidArgumentException('Too many disk groups.');
@@ -123,15 +132,14 @@ function fcp_validate_fan_config(string $text): array {
}
if ($key === 'controller' && !fcp_backup_sys_path($value, true)) throw new InvalidArgumentException('Invalid PWM controller path.');
if ($key === 'controller_identity' && !fcp_backup_binding($value)) throw new InvalidArgumentException('Invalid controller identity.');
- if ($key === 'cpu_sensor' && !fcp_backup_sys_path($value, false)) throw new InvalidArgumentException('Invalid CPU sensor path.');
+ if (($key === 'cpu_sensor' || $key === 'cpu_sensor_identity') && !fcp_backup_sensor($value, false)) throw new InvalidArgumentException('Invalid CPU sensor path.');
if ($key === 'fan' && $value !== '') {
$pwmPath = preg_replace('#/fan(\d+)_input$#', '/pwm$1', $value);
if ($pwmPath === $value || !fcp_backup_sys_path($pwmPath, true)) throw new InvalidArgumentException('Invalid legacy fan input.');
}
- if ($key === 'aux_sensor') {
+ if ($key === 'aux_sensor' || $key === 'aux_sensor_identity') {
foreach ($value === '' ? [] : explode(',', $value) as $sensor) {
- if (fcp_backup_sys_path($sensor, false)) continue;
- if (!preg_match('/^(?:custom:[A-Za-z0-9_-][A-Za-z0-9._-]*|storcli:c\d+:roc|nvidia:gpu\d+|mlx:[0-9a-fA-F]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.[0-9a-fA-F])$/D', $sensor)) throw new InvalidArgumentException('Invalid auxiliary sensor.');
+ if (!fcp_backup_sensor($sensor, true)) throw new InvalidArgumentException('Invalid auxiliary sensor.');
}
}
if ($key === 'disks' || ($group && $m[2] === 'disks')) {
diff --git a/src/usr/local/emhttp/plugins/fanctrlplus2/include/FanBlockRender.php b/src/usr/local/emhttp/plugins/fanctrlplus2/include/FanBlockRender.php
index ed8c907..440738f 100644
--- a/src/usr/local/emhttp/plugins/fanctrlplus2/include/FanBlockRender.php
+++ b/src/usr/local/emhttp/plugins/fanctrlplus2/include/FanBlockRender.php
@@ -299,6 +299,11 @@ class="interval-input fcp-interval-input"
$label): ?>
+
+
+
@@ -328,7 +333,8 @@ class="interval-input fcp-interval-input"
Sensor(s):
-
+
diff --git a/src/usr/local/emhttp/plugins/fanctrlplus2/include/update.fanctrlplus2.php b/src/usr/local/emhttp/plugins/fanctrlplus2/include/update.fanctrlplus2.php
index 9b2b5d7..a46524d 100644
--- a/src/usr/local/emhttp/plugins/fanctrlplus2/include/update.fanctrlplus2.php
+++ b/src/usr/local/emhttp/plugins/fanctrlplus2/include/update.fanctrlplus2.php
@@ -159,6 +159,13 @@
}
// Save every validated block. Preflight has checked every name, so nothing here can refuse a block.
+// Temperature sensors are saved with the identity of their chip and device
+// too, which the service start resolves again (see fcp_migrate_sensors).
+$sensor_identities = fcp_sensor_identity_map();
+$sensor_bindings = fn(string $list) => implode(',', array_map(
+ fn($sensor) => fcp_sensor_binding($sensor, $sensor_identities),
+ $list === '' ? [] : explode(',', $list)
+));
foreach ($_POST['#file'] as $i => $file) {
$plan = $plans[$i];
$custom = $plan['custom'];
@@ -266,10 +273,12 @@
'notify' => (string)($previous['notify'] ?? '1'),
'cpu_enable' => $cpu_enable,
'cpu_sensor' => $cpu_sensor,
+ 'cpu_sensor_identity' => $sensor_bindings($cpu_sensor),
'cpu_min_temp' => $legacy['cpu_min_temp'],
'cpu_max_temp' => $legacy['cpu_max_temp'],
'aux_enable' => $aux_enable,
'aux_sensor' => $aux_sensor,
+ 'aux_sensor_identity' => $sensor_bindings($aux_sensor),
'aux_min_temp' => $legacy['aux_min_temp'],
'aux_max_temp' => $legacy['aux_max_temp'],
] + $disk_groups_out + $curve_fields;
diff --git a/src/usr/local/emhttp/plugins/fanctrlplus2/scripts/aux_sensors.sh b/src/usr/local/emhttp/plugins/fanctrlplus2/scripts/aux_sensors.sh
index 5347fcd..a4416cd 100755
--- a/src/usr/local/emhttp/plugins/fanctrlplus2/scripts/aux_sensors.sh
+++ b/src/usr/local/emhttp/plugins/fanctrlplus2/scripts/aux_sensors.sh
@@ -145,6 +145,11 @@ aux_read_sensor() {
[[ "$temp" =~ ^-?[0-9]+(\.[0-9]+)?$ ]] || return 0
temp="${temp%%.*}"
;;
+ hwmon:*)
+ # A saved sensor identity the service start could not resolve to one
+ # input (fcp_migrate_sensors): it has no reading until the sensor is back.
+ return 0
+ ;;
*)
# An hwmon input reading exactly 0 is the long-standing marker for a
# sensor that is present but not populated, not a reading of 0 °C.
diff --git a/tests/aux_sensor_read_test.sh b/tests/aux_sensor_read_test.sh
index 0c92384..9fc8b6a 100755
--- a/tests/aux_sensor_read_test.sh
+++ b/tests/aux_sensor_read_test.sh
@@ -416,6 +416,14 @@ expect_equal "50" "$(aux_hottest_reading <<< "$readings")" \
expect_equal "" "$(aux_unread_sensors <<< "$(aux_temp_readings "$tmp/temp3_input")")" \
"When every sensor reads, none is named."
+# A sensor identity the service start could not resolve stands in for the
+# path; it has no reading, so the warning names the sensor that is gone.
+readings=$(aux_temp_readings "hwmon:it8625:temp1:platform/asustor_it87.2608,$tmp/temp3_input")
+expect_equal "hwmon:it8625:temp1:platform/asustor_it87.2608" "$(aux_unread_sensors <<< "$readings")" \
+ "An unresolved sensor identity must count as unread, never as a reading."
+expect_equal "50" "$(aux_hottest_reading <<< "$readings")" \
+ "The other sensors of the list must still be read."
+
if (( failures > 0 )); then
printf '%d aux sensor assertion(s) failed.\n' "$failures" >&2
exit 1
diff --git a/tests/sensor_identity_test.php b/tests/sensor_identity_test.php
new file mode 100644
index 0000000..74b95c7
--- /dev/null
+++ b/tests/sensor_identity_test.php
@@ -0,0 +1,138 @@
+ ['pci0000:00/0000:00:1c.0/0000:01:00.0/nvme/nvme0', 'nvme', 1],
+ 'nvme1' => ['pci0000:00/0000:00:1c.4/0000:02:00.0/nvme/nvme1', 'nvme', 1],
+ 'acpitz' => ['virtual/thermal/thermal_zone0', 'acpitz', 1],
+ 'it8625' => ['platform/asustor_it87.2608/hwmon', 'it8625', 3],
+ 'coretemp'=> ['platform/coretemp.0/hwmon', 'coretemp', 2],
+];
+// One boot: the hwmonN each device gets, in probe order.
+$boot = function (array $order) use ($root, $class, $devices) {
+ exec('rm -rf '.escapeshellarg("$root/devices").' '.escapeshellarg($class));
+ // Each service start is a new PHP process, with nothing cached.
+ clearstatcache(true);
+ mkdir($class, 0777, true);
+ foreach ($order as $n => $device) {
+ [$parent, $name, $inputs] = $devices[$device];
+ $dir = "$root/devices/$parent/hwmon$n";
+ mkdir($dir, 0777, true);
+ file_put_contents("$dir/name", "$name\n");
+ for ($t = 1; $t <= $inputs; $t++) file_put_contents("$dir/temp{$t}_input", (string)(30000 + 1000 * $n + $t)."\n");
+ symlink($dir, "$class/hwmon$n");
+ }
+};
+$migrate = function () use ($cfg, $class) { migrate_cfg_and_labels('fanctrlplus2', $cfg, "$class/hwmon*"); };
+$read = fn() => parse_ini_file("$cfg/fanctrlplus2_nas.cfg");
+
+$boot(['nvme0', 'nvme1', 'acpitz', 'it8625', 'coretemp']);
+$check(fcp_sensor_identity("$class/hwmon4/temp1_input") === 'hwmon:coretemp:temp1:platform/coretemp.0',
+ 'A platform chip must be identified by its name, device and input, without hwmonN.');
+$check(fcp_sensor_identity("$class/hwmon2/temp1_input") === 'hwmon:acpitz:temp1:virtual/thermal/thermal_zone0',
+ 'A thermal zone, with its hwmon node directly below the device, must be identified the same way.');
+$check(fcp_sensor_identity("$class/hwmon4/temp9_input") === null, 'An input the chip does not have has no identity.');
+$check(fcp_sensor_identity("$class/hwmon4/pwm1") === null, 'Only temperature inputs have a sensor identity.');
+
+// A configuration saved before identities existed: plain paths.
+$metadata = 'disk_group_0_name="Top \` (group)"'."\n";
+file_put_contents("$cfg/fanctrlplus2_nas.cfg", "custom=\"nas\"\nservice=\"1\"\ncpu_enable=\"1\"\n"
+ ."cpu_sensor=\"$class/hwmon4/temp1_input\"\naux_enable=\"1\"\n"
+ ."aux_sensor=\"$class/hwmon3/temp2_input,$class/hwmon2/temp1_input,custom:ambient\"\n".$metadata);
+$migrate();
+$saved = $read();
+$check($saved['cpu_sensor'] === "$class/hwmon4/temp1_input", 'Recording an identity must not move a sensor that is where it was saved.');
+$check(($saved['cpu_sensor_identity'] ?? '') === 'hwmon:coretemp:temp1:platform/coretemp.0', 'Startup must record the CPU sensor identity of an older configuration.');
+$check(($saved['aux_sensor_identity'] ?? '') === 'hwmon:it8625:temp2:platform/asustor_it87.2608,hwmon:acpitz:temp1:virtual/thermal/thermal_zone0,custom:ambient',
+ 'Startup must record each aux identity in order, and keep a script sensor as it is.');
+$check(strpos(file_get_contents("$cfg/fanctrlplus2_nas.cfg"), $metadata) !== false, 'Identity capture must not change unrelated escaped values.');
+$before = file_get_contents("$cfg/fanctrlplus2_nas.cfg");
+$migrate();
+$check(file_get_contents("$cfg/fanctrlplus2_nas.cfg") === $before, 'A start with nothing to change must not rewrite the configuration.');
+
+// The next boot: the NVMe drives probe last, and every other hwmonN shifts.
+// hwmon4, the saved CPU path, is now an NVMe drive.
+$boot(['acpitz', 'coretemp', 'it8625', 'nvme0', 'nvme1']);
+$migrate();
+$saved = $read();
+$check($saved['cpu_sensor'] === "$class/hwmon1/temp1_input", 'The CPU sensor must follow its chip to its new hwmonN, got '.$saved['cpu_sensor']);
+$check($saved['aux_sensor'] === "$class/hwmon2/temp2_input,$class/hwmon0/temp1_input,custom:ambient", 'Every aux sensor must follow its chip, got '.$saved['aux_sensor']);
+$check($saved['cpu_sensor_identity'] === 'hwmon:coretemp:temp1:platform/coretemp.0', 'Renumbering must not change the saved identity.');
+$check(strpos(file_get_contents("$cfg/fanctrlplus2_nas.cfg"), $metadata) !== false, 'Renumbering must preserve unrelated configuration bytes.');
+
+// Two inputs with one identity pin neither: the sensor is not guessed.
+$twin = "$root/devices/platform/coretemp.0/hwmon/hwmon7";
+mkdir($twin, 0777, true);
+file_put_contents("$twin/name", "coretemp\n");
+file_put_contents("$twin/temp1_input", "41000\n");
+symlink($twin, "$class/hwmon7");
+$migrate();
+$saved = $read();
+$check($saved['cpu_sensor'] === 'hwmon:coretemp:temp1:platform/coretemp.0', 'An ambiguous identity must leave no readable path, got '.$saved['cpu_sensor']);
+$check($saved['cpu_sensor_identity'] === 'hwmon:coretemp:temp1:platform/coretemp.0', 'An ambiguous identity must remain saved for recovery.');
+exec('rm -rf '.escapeshellarg($twin).' '.escapeshellarg("$class/hwmon7"));
+clearstatcache(true);
+$migrate();
+$check($read()['cpu_sensor'] === "$class/hwmon1/temp1_input", 'The sensor must come back once the ambiguity is gone.');
+
+// A chip that is gone (driver not loaded) leaves its identity in place of the path.
+$boot(['acpitz', 'coretemp', 'nvme0', 'nvme1']);
+$migrate();
+$saved = $read();
+$check($saved['aux_sensor'] === "hwmon:it8625:temp2:platform/asustor_it87.2608,$class/hwmon0/temp1_input,custom:ambient",
+ 'A missing chip must not be replaced by whatever now has its hwmonN, got '.$saved['aux_sensor']);
+$boot(['acpitz', 'coretemp', 'nvme0', 'nvme1', 'it8625']);
+$migrate();
+$check($read()['aux_sensor'] === "$class/hwmon4/temp2_input,$class/hwmon0/temp1_input,custom:ambient", 'A chip that is back must be found again.');
+
+// What the settings page saves for a selection.
+$identities = fcp_sensor_identity_map("$class/hwmon*");
+$check(fcp_sensor_binding("$class/hwmon1/temp1_input", $identities) === 'hwmon:coretemp:temp1:platform/coretemp.0', 'A selected sensor must be saved by identity.');
+$check(fcp_sensor_binding('nvidia:gpu0', $identities) === 'nvidia:gpu0', 'A tool sensor is already stable and must be kept as it is.');
+$check(fcp_sensor_binding('hwmon:it8625:temp2:platform/asustor_it87.2608', []) === 'hwmon:it8625:temp2:platform/asustor_it87.2608',
+ 'Saving an unresolved sensor must keep its identity.');
+
+// The settings page keeps a saved sensor it cannot list selected, instead of
+// selecting the first one listed and saving that.
+$block = render_fan_block(['file' => 'fanctrlplus2_nas.cfg', 'custom' => 'nas', 'cpu_enable' => '1', 'aux_enable' => '1',
+ 'cpu_sensor' => 'hwmon:coretemp:temp1:platform/coretemp.0', 'aux_sensor' => 'custom:ambient'],
+ 0, [], [], [], ["$class/hwmon1/temp1_input" => 'coretemp - Package id 0 (45°C)'], []);
+$check(preg_match('##', $block) === 1,
+ 'An unresolved CPU sensor must stay selected and say it was not found.');
+$check(preg_match('#