缓存、并发、错误处理与电源管理

缓存、并发、错误处理与电源管理

1. 为什么缓存

一次 sensors 会连续读取 input、min、max、alarm、label。若每个 sysfs read 都访问 I2C:

  • 总线流量高;
  • 读取跨 conversion 不一致;
  • 增加功耗;
  • 触发 read-to-clear 副作用;
  • 放大故障。

2. 常见模式

1
2
3
4
5
6
7
mutex_lock
if invalid or cache expired:
read all related registers
if success:
update data/last_updated/valid
value = cache
mutex_unlock

失败时通常返回错误,是否保留旧值必须由驱动明确决定,不能无提示把 stale 数据当新值。

3. Regmap

优势:

  • bus abstraction;
  • endian;
  • cache;
  • volatile/precious register;
  • bulk/update_bits;
  • debugfs。

传感器数据寄存器通常 volatile;状态寄存器可能 precious/read-clear,不能错误缓存。

4. 锁

常见:

  • mutex:配置、缓存、page/bank select;
  • spinlock:tach IRQ pulse counter;
  • timer/work:周期采样;
  • regmap内部锁;
  • PMBus page access锁。

sysfs回调在进程上下文,可以睡眠;tach IRQ不能直接进行 I2C transaction。

5. 原子快照

多字节寄存器可能需要:

  • SMBus word transaction;
  • latch;
  • bulk read;
  • high-low-high retry;
  • conversion ready bit。

否则可能读到 rollover 中间值。

6. 错误语义

错误 含义
-ENODEV 芯片不存在/移除
-EIO 通信或设备错误
-ETIMEDOUT conversion/总线超时
-EBADMSG CRC/PEC
-EINVAL 属性/channel/value 无效
-EOPNOTSUPP 当前芯片不支持
-EPROBE_DEFER provider 未就绪

监控程序应记录 read failure,不能把错误当作 0。

7. PM

策略因芯片而异:

  • continuous conversion;
  • one-shot;
  • shutdown mode;
  • regulator power gate;
  • runtime PM;
  • suspend保留 alarm wake。

resume 后可能需要恢复 config/threshold/calibration并使 cache invalid。

8. 并发写

用户写 threshold/PWM 与 thermal governor、fan daemon或 kernel worker可能竞争。driver mutex只能防寄存器并发,不能定义多个控制策略的优先级;系统集成必须指定唯一 controller。

9. 生命周期

remove 顺序:

  1. 禁止新硬件事件;
  2. disable IRQ;
  3. del_timer_sync/cancel work;
  4. unregister notifier/cooling;
  5. devm移除 hwmon;
  6. power off。

使用 devm不自动替代对异步任务的同步停止。

10. Trace

HWMON Core有 read/write tracepoints,可配合 ftrace 判断哪个进程高频读取和 callback 延迟。I2C trace、function graph和 dynamic debug应只在调试时使用。

文章互动

阅读 --

留言

0 条留言

正在加载留言…