Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
116 changes: 107 additions & 9 deletions src/usr/local/emhttp/plugins/fanctrlplus2/include/Common.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
// ================================
Expand Down
18 changes: 13 additions & 5 deletions src/usr/local/emhttp/plugins/fanctrlplus2/include/ConfigBackup.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php
require_once __DIR__.'/Common.php';
require_once __DIR__.'/CurveConfig.php';
// Configuration files are sourced by Bash. A restore is data, never shell code.
const FCP_BACKUP_MAX_BYTES = 2097152;
Expand Down Expand Up @@ -55,6 +56,14 @@ function fcp_backup_sys_path(string $path, bool $pwm): bool {
return preg_match('#^/sys/(?:devices|class/(?:hwmon|thermal))/[A-Za-z0-9_.:/-]+/'.$end.'$#D', $path) === 1;
}

// One saved temperature sensor: an hwmon path, the identity of a chip's
// tempN input (fcp_sensor_identity), or, in the aux list, a tool or script.
function fcp_backup_sensor(string $value, bool $aux): bool {
if (fcp_backup_sys_path($value, false)) return true;
if (preg_match(FCP_SENSOR_IDENTITY, $value, $m)) return !preg_match('#(?:^|/)\.\.?(?:/|$)#', $m[3]);
return $aux && 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', $value) === 1;
}

function fcp_backup_binding(string $value): bool {
if (strpos($value, 'usb:') !== 0) return fcp_backup_sys_path($value, true);
$hex = substr($value, 4);
Expand Down Expand Up @@ -102,7 +111,7 @@ function fcp_validate_fan_config(string $text): array {
$values = fcp_backup_assignments($text);
$boolean = ['service','syslog','notify','log_enable','cpu_enable','aux_enable'];
$numeric = ['pwm','max','idle','idle_percent','low','high','interval','interval_sec','disk_group_count','cpu_min_temp','cpu_max_temp','aux_min_temp','aux_max_temp'];
$string = ['custom','label','controller','controller_identity','fan','disks','cpu_sensor','aux_sensor'];
$string = ['custom','label','controller','controller_identity','fan','disks','cpu_sensor','cpu_sensor_identity','aux_sensor','aux_sensor_identity'];
foreach ($values as $key=>$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.');
Expand All @@ -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')) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,11 @@ class="interval-input fcp-interval-input"
<?php foreach ($cpu_sensors as $path => $label): ?>
<option value="<?=htmlspecialchars($path)?>" <?=($cfg['cpu_sensor'] ?? '') == $path ? 'selected' : ''?>><?=htmlspecialchars($label)?></option>
<?php endforeach; ?>
<?php // A saved sensor that is not listed stays selected, so saving keeps it rather than the first one listed.
$cpu_saved = (string)($cfg['cpu_sensor'] ?? '');
if ($cpu_saved !== '' && !array_key_exists($cpu_saved, $cpu_sensors)): ?>
<option value="<?=htmlspecialchars($cpu_saved)?>" selected><?=htmlspecialchars(fcp_sensor_unavailable_label($cpu_saved))?></option>
<?php endif; ?>
</select>
</td>
</tr>
Expand Down Expand Up @@ -328,7 +333,8 @@ class="interval-input fcp-interval-input"
<tr class="aux-control aux-control-<?=$i?>">
<td class="aux-label fcp-help-cursor" title="Select one or more auxiliary temperature sensors to monitor. The highest temperature across all selected sensors is used. Lists non-CPU, non-NVMe hwmon sensors, plus storcli, nvidia-smi and Mellanox NICs if available, and any script you dropped in sensors.d.">Sensor(s):</td>
<td class="fcp-ddcl-cell">
<?php $aux_selected = array_filter(explode(',', $cfg['aux_sensor'] ?? '')); ?>
<?php $aux_selected = array_filter(explode(',', $cfg['aux_sensor'] ?? ''));
$aux_unlisted = array_diff($aux_selected, array_column(array_merge([], ...array_values($aux_sensors)), 'path')); ?>
<select class="aux-select aux-input fcp-w-300" name="aux_sensor[<?=$i?>][]" multiple <?=($cfg['aux_enable'] ?? '') != '1' ? 'disabled' : ''?>>
<?php foreach ($aux_sensors as $group => $entries): ?>
<optgroup label="<?=htmlspecialchars($group)?>">
Expand All @@ -337,6 +343,13 @@ class="interval-input fcp-interval-input"
<?php endforeach; ?>
</optgroup>
<?php endforeach; ?>
<?php if ($aux_unlisted): ?>
<optgroup label="Unavailable">
<?php foreach ($aux_unlisted as $sensor): ?>
<option value="<?=htmlspecialchars($sensor)?>" selected><?=htmlspecialchars(fcp_sensor_unavailable_label($sensor))?></option>
<?php endforeach; ?>
</optgroup>
<?php endif; ?>
</select>
</td>
</tr>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'];
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions tests/aux_sensor_read_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading