中断信号任务化:100 次中断只唤醒 1 次任务,和 1 ms 轮询的 27 倍延迟代价

5 阅读21分钟

中断信号任务化:100 次中断只唤醒 1 次任务,和 1 ms 轮询的 27 倍延迟代价

中断处理为什么必须「任务化」

硬中断处理函数有三条铁律:

  1. 不能睡眠(不能 mutex_lock、不能 kmalloc(GFP_KERNEL)、不能等 I/O)
  2. 不能长时间占用(同一 CPU 上的其他中断全部被挡住)
  3. 不能调用大部分内核 API(很多 API 会隐式睡眠)

而业务逻辑几乎必然违反这三条:要读配置、要写日志、要发消息、要等锁。

所以标准做法是中断任务化——把中断处理拆成两半:

上半部(硬中断上下文): 清中断标志、取数据、投递事件  ← 必须极短
下半部(任务上下文)  : 干所有实际的活              ← 可以阻塞

Linux 内核里有 softirq / tasklet / workqueue 三种下半部机制。用户态没有这些,要靠「中断 → 信号/事件 → 任务」这条链路自己搭。

现网框架用信号做这件事(platform/ko/irq_sig.c + platform/utils/irq_sig.c):

硬件中断 → irq_sig_offset_handler() → sig_send(41, p)
        → send_sig_info() → 用户态信号处理函数 → sem_post(&sem1)
        → 工作线程 sem_wait(&sem1) 醒来

另一条路(硬件 mailbox)根本不用中断——共享内存 + 寄存器轮询,固定 usleep(1000)。

本文实测五件事,其中两件的结论跟直觉相反:

  • 100 次中断只唤醒任务 1 次——信号会合并,99% 的事件丢失
  • 1 ms 轮询的平均延迟是事件驱动的 27.3 倍,而且这个下限无法通过优化代码消除

链路延迟:平均 3 μs,最坏 135 μs

先看这条链路本身的延迟分布。10000 次往返:

measurements over 10000 round trips:
  average latency : 0.003129 ms (3.129 us)
  max latency     : 0.135100 ms (135.100 us)
  P50             : 0.002400 ms
  P90             : 0.005200 ms
  P99             : 0.012500 ms (12.500 us)
  P999            : 0.038000 ms
  min             : 0.001900 ms

  max / average ratio : 43.2x

平均值 3.1 μs,最坏 135.1 μs——43 倍的差距。

这个分布形态很重要:

分位延迟含义
min1.9 μs空载、缓存热、调度器立刻响应
P502.4 μs典型情况
P9912.5 μs1% 的情况超过这个值
max135.1 μs最坏情况

尾部延迟是调度产物,不是信号机制

The tail is a SCHEDULING artefact: the worker thread has to be
picked up by the scheduler, and when the CPU is busy or the
system is under load the wakeup is delayed by the scheduler,
not by the signal mechanism itself.

这点很关键。信号投递本身是 μs 级;尾部延迟来自「工作线程被调度器捡起来」这一步。

而调度延迟取决于:

  • 工作线程的优先级
  • 当前 CPU 上有没有更高优先级的任务
  • 有没有关抢占的临界区
  • 运行队列里有几个任务

源码的设计对这个延迟没有任何控制手段:

the source's design (a single semaphore, one worker) gives no
priority control over that scheduling delay.

一个信号量、一个工作线程、默认优先级。工作线程被调度器安排到哪个 CPU、什么时候跑,完全靠运气。

对控制回路的含义

A control loop that must meet a deadline has to be designed for
the P99/max, not the average.

如果你的控制回路要求「中断到处理完成 ≤ 50 μs」,那么:

  • 看平均值(3.1 μs)→ 觉得余量很大
  • 看 P99(12.5 μs)→ 还是觉得有余量
  • 看 max(135.1 μs)→ 超标 2.7 倍

控制回路的可行性必须用 max 判断,不能用 avg。 一个每 1000 次才出现一次的 135 μs 抖动,足以让一个「平均看起来很好」的系统在现场偶发失控。

核心缺陷:信号会合并,100 次事件丢 99 次

这是本文最重要的一节。

Linux 的信号语义

POSIX 规定:同一个信号在 pending 集合里只有一位。如果信号已经 pending,再次 raise 会被合并(不是排队):

Linux keeps only ONE pending instance of a given signal.  If the
signal is already pending when it is raised again, the second
raise is MERGED into the first: the handler still runs once, but
it has lost the information that TWO events happened.

实测 100 次突发:

coalescing:
  events raised        : 100
  handler invocations   : 1
  events LOST          : 99  (99.0%)
  the pending flag stayed set for 99 of the 100 raises, so
  those raises were merged into the first one.

counting:
  events raised        : 100
  handler invocations   : 100
  events LOST          : 0  (0.0%)

两种语义的对比:

语义100 次事件 → 处理次数丢失
合并型(一个 pending 标志)199(99%)
计数型(计数信号量)1000

源码的实际情况:好一半

源码在信号处理函数里用 sem_post(&sem1),工作线程用 sem_wait(&sem1)。

sem_post 对 POSIX 计数信号量是不合并的——每次 post 都加一,所以工作线程每次都会跑。

但合并发生在更早的地方:

  So the USER side preserves the count, but the KERNEL side
  (send_sig_info) has already merged the raises: if two IRQs
  arrive before the handler runs, the handler runs ONCE and
  sem_post() is called ONCE.  The count is lost in the KERNEL,
  not in the semaphore.

  Measured: 99 of 100 raises were merged away -- 99.0% of the
  events never reached the handler.

这是个很重要的认识:开发者选了「计数信号量」来避免合并,但合并发生在用户态看到信号之前。计数信号量只能保证「处理函数被调用几次,就 post 几次」——它无法恢复内核已经合并掉的信息。

后果:中断风暴下事件数被系统性低估

During an interrupt storm the number of real events is
systematically UNDER-ESTIMATED, and nothing in the system
reports the discrepancy.

假设某个中断源在 1 ms 内触发了 100 次:

  • 用户态处理函数被调用 1 次
  • sem_post 被调用 1 次
  • 工作线程处理 1 个事件
  • 99 次中断的实际数据全部丢失

而且系统里没有任何地方记录「丢了 99 次」。你看不到告警、看不到计数、看不到日志。

什么时候这个缺陷致命

场景后果
中断源是「状态变化通知」无害。合并后处理一次,读到的就是最新状态
中断源是「事件计数」(脉冲计数、包计数)致命。计数直接少 99%
中断源是「数据到达」致命。99% 的数据没被读走
中断源是「命令请求」致命。99% 的命令被丢弃

源码用来做中断通知(sig_send(41, p) 只是「告诉你有事」),如果是前者就没问题——只要处理函数去读共享内存里的最新状态,合并也无所谓。

但没有任何机制保证它只是「状态变化通知」。一旦将来某类中断需要「每次都要处理」,这个设计就崩了。

正确做法

A counting design would post one semaphore token per event from a
kernel thread (or use a per-event queue), which is precisely what
the source does NOT do.

三条路线:

路线 1:内核侧排队计数

/* 中断上下文:原子加 */
static atomic_t g_irq_count = ATOMIC_INIT(0);

static irqreturn_t handler(int irq, void *dev)
{
    atomic_inc(&g_irq_count);        /* 每次中断都计数 */
    send_sig_info(sig, &info, p);     /* 信号只是「有新事件」的提示 */
    return IRQ_HANDLED;
}

/* 用户态:处理函数只读计数差值 */
static void sig_handler(int sig)
{
    int n = atomic_read(&g_irq_count);   /* 通过 ioctl/mmap 读 */
    for (i = 0; i < n - last; i++) { process_one(); }
    last = n;
}

内核侧用原子计数保真,信号只做「唤醒提示」。用户态读计数差值,就知道合并了多少个。

路线 2:per-event 队列

中断上下文把事件塞进一个环形队列(kfifo),信号通知「队列非空」。用户态循环出队直到空。这样每次事件都被保留。

路线 3:不用信号,用 eventfd 或 poll

eventfd 是计数型的文件描述符——每次 write 累加,read 清零。中断侧 eventfd_signal 会累加计数,不合并。

这是用户态中断通知的现代做法,比信号安全(不涉及 async-signal-safety 问题)。

轮询 vs 事件驱动:27 倍的延迟差

源码里有两条通路:

通路机制延迟特性
中断通路信号 + 信号量事件驱动,无固定下限
硬件 mailbox共享内存 + usleep(1000) 轮询固定 1 ms 轮询周期

实测

生产者在独立线程上以 100..900 μs 的抖动间隔发事件(让到达相位相对轮询 tick 均匀分布),测「事件到达 → 处理完成」的延迟:

metric                       | polling        | event driven
-----------------------------+----------------+----------------
avg latency (ms)             | 1.778765       | 0.065051
min latency (ms)             | 0.001000       | 0.004800
max latency (ms)             | 63.461700      | 3.121000
P99 latency (ms)             | 27.788500      | 0.961400

  avg latency ratio (polling / event) : 27.3x
  P99 latency ratio (polling / event) : 28.9x
  max latency ratio (polling / event) : 20.3x
指标轮询事件驱动倍数
平均1.779 ms0.065 ms27.3×
P9927.789 ms0.961 ms28.9×
最大63.462 ms3.121 ms20.3×

为什么轮询「必然」慢半拍

  KEY RESULT: the polling version's latency is bounded ABOVE by
  one tick, and the histogram shows exactly that: the four bins
  below one tick hold 73.7% of the samples and are nearly EQUAL
  (373 / 384 / 383 / 334), which is a uniform distribution over the
  tick.  That is the signature of the polling model: an event
  arriving at a random phase waits, on average, HALF a tick.
  The measured P50 is 0.657 ms against a 1.342 ms tick.

四个桶的样本数 373 / 384 / 383 / 334——几乎相等。这是均匀分布的签名:事件到达时刻相对 tick 是随机的,所以落在每个 1/4 tick 区间的概率相同。

理论平均等待 = 半个 tick = 0.671 ms。实测 P50 = 0.657 ms。完全吻合。

这不是实现问题,是模型的性质。 轮询周期 1 ms,就必然产生平均 0.5 ms 的等待。想降低只能缩短周期,而缩短周期就增加 CPU 开销(见下一节)。

超过一个 tick 的尾巴

  Above one tick the samples form a tail: 26.3% of them land
  beyond it, up to 63.462 ms.  That tail is NOT a property of
  the polling model -- it is the HOST's timer firing late under
  load, and the host was busy during this measurement.

26.3% 的样本超过 1 ms,最大 63.5 ms。 这不是轮询模型的问题,是操作系统的定时器粒度 + 负载问题:

  • usleep(1000) 不保证 1 ms 后精确唤醒
  • 系统负载高时,定时器回调被推迟
  • 实测时主机负载 55.9%,所以尾巴很长

真实设备在负载下表现相同。 所以这个风险是真实的,不是实验环境的假象。

对控制回路的含义

  For a control path with a deadline that floor is the whole
  design constraint, and no amount of code tuning removes it.

「下限」这个词是关键。 事件驱动的延迟下限是「信号投递 + 调度」的 μs 级;轮询的延迟下限是「半个 tick」。

如果控制周期要求 ≤ 1 ms,轮询方案在设计上就不可行——不是优化能解决的问题。

CPU 成本:轮询 0.0521%,事件 0%

轮询不是白拿延迟的,但实测这个代价比想象小。

-- the polling version, idling for 60 s --
  wall clock       : 60000.066 ms
  poll wakeups     : 51640  (861 per second)
  CPU time         : 0.031250 s
  CPU / wall clock : 0.0521% of one core

-- the event-driven version, idling for 60 s --
  wall clock       : 60099.471 ms
  CPU time         : 0.000000 s
  CPU / wall clock : 0.0000% of one core
轮询事件驱动
CPU 时间(60 s)0.03125 s0.000 s
占单核0.0521%0.0000%
唤醒次数51640(861/s)—
  per-wakeup cost of the polling loop: 0.605 us
  At 1000 wakeups per second that is 0.061% of a core spent
  doing NOTHING but waking up to read an empty register.

每次唤醒 0.605 μs,1000 Hz 下占单核 0.061%。

这个代价很小。所以「轮询很浪费 CPU」这个说法,在单个低频通道上是不成立的。

但成本随通道数线性增长

  On the target the polling period is FIXED at 1 ms, so
  the cost scales linearly with the channel count: N
  polling channels cost N x 0.061% of a core.
通道数占单核
10.061%
100.61%
1006.1%
100061%

100 个通道就吃掉 6% 的单核。 而且这是「空转」成本——没有事件的时候也要付。

什么时候轮询是对的

轮询不是坏设计,它有明确的适用场景:

场景推荐理由
事件频率高(> 1 kHz)轮询事件几乎总在,轮询延迟接近 0,且无信号开销
事件频率低(< 10 Hz)事件驱动轮询空转成本占比高,延迟也不可接受
延迟要求 < 100 μs事件驱动轮询下限是半 tick
通道数多(> 20)事件驱动轮询成本线性增长
需要保证不丢事件轮询或队列信号会合并

源码的问题是「同一个系统里两条通路用了不同模型,但没有说明为什么」。 中断通路用事件驱动,mailbox 通路用 1 ms 轮询。如果两者承载的流量性质不同,这是合理设计;如果只是历史原因,就该统一。

缺陷:队列满时丢弃「最新」

osp_que_enque() 在队列满时:

    drops the NEW item, increments full_cnt, returns failure;
    osp_msg_send() then raises the DIAG_MSG_SEND_FAILED alarm.

实测:容量 64,灌 100 条。

  enqueued successfully : 64
  rejected (dropped)    : 36
  full_cnt final value  : 36
  queue occupancy now   : 64

  the ids that were DROPPED: 65 66 67 ... 100
  the ids that are IN the queue: 1 2 3 ... 64

  => the queue retains the OLDEST 64 messages and discards the
     NEWEST 36.

保留最旧的 64 条,丢弃最新的 36 条。 这叫 drop-tail(丢尾)。

对比网络栈常用的 drop-head(丢头):

-- the same burst with a drop-OLDEST policy --
  enqueued successfully : 100
  dropped (oldest)      : 36
  the queue now holds ids 37..100
  the most recent 64 messages survive

为什么 drop-tail 对控制总线是错的

  Why this is the wrong choice for a control message bus:
    the newest message carries the most recent state.  Dropping
    it means the consumer keeps acting on STALE state, while
    the old messages it does keep are the ones the producer
    already knows are outdated.  For a status/telemetry bus
    that means the display freezes at an old value and the
    only hint is the DIAG_MSG_SEND_FAILED alarm bit.
    For a COMMAND bus it is worse: the command that was
    rejected is exactly the one the operator just issued.

两种消息类型,两种灾难:

消息类型drop-tail 的后果
状态/遥测显示冻结在旧值。消费者看到的是过期状态,而且它以为这是最新状态
命令/控制操作员刚下发的命令被丢弃。界面显示「已发送」,设备没收到

命令总线的场景尤其严重:操作员按了「紧急停止」,队列满,这条命令被丢弃,osp_msg_send 返回失败——但如果调用方不检查返回值,界面依然显示成功。

正确的策略取决于语义

策略适用
drop-head(丢最旧)状态刷新型总线(只关心最新值)
drop-tail(丢最新)日志型总线(宁可保住历史,新消息失败让调用方重试)
阻塞命令总线(不能丢,宁可生产者等)
独立优先级队列混合流量(命令走高优先级队列)

状态总线必须 drop-head。 这是「消费者只关心最新」这个语义的直接推论。

源码用了 drop-tail 且没有区分消息类型——所有消息共用一个队列、一个策略。

一个更隐蔽的问题:两条合并路径

  Note the asymmetry this creates: the queue in EXP-5 drops the
  NEWEST message, and the signal layer drops the extra EVENTS.
  Both errors push the system towards acting on stale state.
  • 信号层:合并 → 丢的是「事件次数」,保住的是「第一次」
  • 队列层:drop-tail → 丢的是「最新消息」,保住的是「最旧的」

两条路径都在往「保留旧状态」的方向偏。 对控制总线来说,这个偏差方向完全错了——你要的是最新状态。

缺陷:全局指针的可见性竞态与 use-after-free

irq_sig.c(内核侧):

/* irq_sig_open() —— 进程上下文 */
p = current;

/* irq_sig_offset_handler() —— 中断上下文 */
send_sig_info(sig, &info, p);

/* irq_sig_release() —— 进程退出 */
/* 什么都不做 */

三个问题叠在一起。

问题一:没有内存屏障

There is NO READ_ONCE/WRITE_ONCE and NO memory barrier, so the
compiler AND the CPU may reorder the accesses, and the reader
may observe a stale value.

实测:

plain global (the source's code, a plain load in the reader):
  reads of the NEW value (0x1234) : 9689825
  reads of the OLD value (NULL)    : 2553356
  reads of a stale/garbage value   : 0
  total samples                   : 12243181
  fraction that saw a STALE value : 20.8553%

barrier-protected global (an interlocked load in the reader):
  reads of the NEW value (0x1234) : 7380990
  reads of the OLD value (NULL)    : 1039458
  total samples                   : 8420448
  fraction that saw a STALE value : 12.3445%

20.86% 的读取看到旧值。

但这里要诚实:

  On x86 the loads and stores are TSO, so the window is narrow
  and the plain version usually still wins the race in practice
  -- which is exactly why the bug survives testing.  On a weakly
  ordered CPU (ARM64, the actual target) the compiler may also
  reorder the load across the branch, and the window widens.
  • x86 是 TSO(全序存储),重排窗口很窄,实践中大多能赢
  • ARM64 是弱序,编译器还可能把 load 移出分支,窗口更宽

这正是这个 bug 能在测试中活下来的原因:开发机是 x86,测不出问题;目标是 ARM64。

而且 barrier 版本仍有 12.34% 看到旧值——因为这个实验测的是「写之前 vs 写之后」的时间窗口,不是纯粹的重排。屏障能防止重排,但不能让「还没写的操作」提前完成。

问题二:release 什么都不做 → use-after-free

  The far more serious half of the bug is that irq_sig_release()
  does NOTHING: when the owning process exits, `p` still points
  at the freed task_struct.  The next interrupt reads the
  dangling pointer and passes it to send_sig_info(), which
  dereferences it -> a use-after-free in interrupt context,
  i.e. a kernel crash or a security hole.

这是最严重的部分。

流程:

  1. 进程 A 打开设备 → p = current(指向 A 的 task_struct)
  2. 进程 A 退出 → task_struct 被释放
  3. irq_sig_release() 什么都不做 → p 依然指向已释放的内存
  4. 下一次中断到来 → send_sig_info(sig, &info, p) → 内核解引用 p → use-after-free

这是中断上下文里的 UAF,后果:

  • 内核 oops / panic
  • 或者更糟:task_struct 的内存被复用成别的对象,send_sig_info 往一个「假 task」发信号 → 权限提升

任何能打开这个设备然后退出的进程,都能触发。

问题三:si_code = -1 是非法值

info.si_code = -1

si_code 的合法值域有明确含义(SI_USER、SI_KERNEL、SI_QUEUE、SI_TIMER 等,正数或特定的负数)。-1 不是任何一个。

接收方的信号处理函数如果检查 si_code,会进入 default 分支,可能误判信号来源。

正确的修法

/* 写入侧 */
static void irq_sig_open_internal(struct file *filp)
{
    WRITE_ONCE(g_target_task, get_task_struct(current));   /* 持有引用 */
}

/* 读取侧 */
static irqreturn_t irq_sig_offset_handler(int irq, void *dev)
{
    struct task_struct *t = READ_ONCE(g_target_task);

    if (NULL == t) { return IRQ_HANDLED; }        /* 必须判空 */

    info.si_code = SI_KERNEL;                     /* 合法值 */
    send_sig_info(IRQ_SIG, &info, t);

    return IRQ_HANDLED;
}

/* 释放侧 */
static int irq_sig_release(struct inode *inode, struct file *filp)
{
    struct task_struct *t = READ_ONCE(g_target_task);

    WRITE_ONCE(g_target_task, NULL);               /* 先失效 */
    if (t) { put_task_struct(t); }                 /* 再放引用 */

    return 0;
}

四处关键:

  1. get_task_struct 持有引用——防止进程退出后 task_struct 被释放
  2. WRITE_ONCE / READ_ONCE——防止编译器重排和缓存
  3. 中断处理里判空——release 之后 p 是 NULL,要跳过
  4. si_code = SI_KERNEL——用合法值

顺序也很重要:先 WRITE_ONCE(NULL) 再 put_task_struct。反过来会有一个窗口:引用已经放了,但指针还指着它。

两套信号号体系并存

源码里有两种信号分配方式:

OSP's own real-time signals (SIGRTMIN+N):
  SIGRTMIN+1 = 34
  SIGRTMIN+2 = 35
  SIGRTMIN+3 = 36

The hardware interrupt signals (bare magic numbers):
  41 .. 48   (8 signals)

glibc's real-time signal range: SIGRTMIN = 32 .. SIGRTMAX = 64

  signal : 012345678901234567
  number : 333333334444444444
           ||||||||||||||||||
           ..OOO....HHHHHHHH.
             ^^^    ^

  legend: O = OSP's own RT signals (SIGRTMIN+1..+3)
          H = the hardware IRQ signals (41..48)

两套体系,同一个 33 号区间,没有任何东西把它们联系起来。

四个具体风险

  1. There is NO allocation table anywhere.  The OSP signals are
     written as SIGRTMIN+1/+2/+3 and the hardware ones as the
     literals 41..48, in different files, with nothing tying
     them together.

没有统一的分配表。想知道「41 号信号被谁用了」,得全工程 grep 数字 41。

  2. SIGRTMIN is NOT a compile-time constant in glibc.  It is a
     runtime function (__libc_current_sigrtmin) and glibc
     RESERVES the lowest RT numbers for NPTL -- glibc's
     __libc_current_sigrtmin() returns 34 (or 33) because the
     threads library reserves SIGRTMIN and SIGRTMIN+1.

这条最容易踩。 SIGRTMIN 在 glibc 里不是编译期常量:

#define SIGRTMIN  (__libc_current_sigrtmin ())

glibc 给 NPTL 保留最低的 RT 信号,所以 SIGRTMIN 可能是 34 而不是 32。

而源码写死了 41..48——这些数字在 SIGRTMIN=34 时仍然落在 RT 区间内(34..64),没撞车。但这是碰巧:

  • 如果哪天 glibc 保留更多信号(比如保留到 38),SIGRTMIN+7 = 41 就撞上硬件中断信号

  • 如果某个库也用 SIGRTMIN+9,就撞上 43

    3. The hardware signals 41..48 assume SIGRTMIN = 32, i.e. the
       value from an OLD glibc.
    
    4. 41..48 is only SAFE because SIGRTMAX = 64 leaves room.
       On a platform with fewer RT signals, or if the kernel
       reserved more, the hardcoded numbers could fall outside the
       RT range entirely and collide with a TERMINATION signal.
    

最后一条最可怕:如果硬编码的数字落在 RT 区间之外,可能撞上 SIGTERM、SIGKILL 这类信号——进程直接被杀死,而且看起来像「被别人 kill 了」。

修法:一张分配表

  The fix is a single allocation table: a header that defines
  the OSP signals RELATIVE to SIGRTMIN, assigns the hardware
  interrupts from a separate, non-overlapping block, and adds a
  runtime assertion that the two blocks do not intersect and
  that the whole scheme fits in [SIGRTMIN, SIGRTMAX].

#define IRQ_SIG_BASE      (SIGRTMIN + 8)    /* 从 RT 区间的第 8 个开始 */
#define IRQ_SIG(n)        (IRQ_SIG_BASE + (n))   /* n = 0..7 -> 8 路 */

#define OSP_SIG_TRACE     (SIGRTMIN + 1)
#define OSP_SIG_SUSPEND   (SIGRTMIN + 2)
#define OSP_SIG_RESUME    (SIGRTMIN + 3)
/* ... SIGRTMIN+4..+7 为其他用途保留 ... */

/* 编译期与运行期双重校验 */
_Static_assert(IRQ_SIG_BASE > OSP_SIG_RESUME, "signal blocks overlap");

static void signal_layout_check(void)
{
    assert(IRQ_SIG(0)  >  OSP_SIG_RESUME);
    assert(IRQ_SIG(7)  <= SIGRTMAX);
    assert(SIGRTMIN + 30 < SIGRTMAX);   /* 余量检查 */
}

关键三条:

  1. 所有信号都相对 SIGRTMIN 定义,不写绝对数字
  2. 两个块不重叠,用编译期断言保证
  3. 运行期检查整个方案落在 [SIGRTMIN, SIGRTMAX] 内

六处缺陷汇总

#位置缺陷后果
1send_sig_info 路径信号合并,无计数补偿99% 事件丢失
2irq_sig_release什么都不做中断上下文 UAF
3全局 p无 READ_ONCE/WRITE_ONCE20.86% 读到旧值
4info.si_code = -1非法值接收方误判来源
5osp_que_enquedrop-tail命令/状态总线上丢最新
6信号号两套体系并存,硬件用裸数字换 glibc 可能撞车

第 1 和第 2 是功能性/安全性硬缺陷,第 3 是平台相关(x86 测不出),第 5 是语义错误。

工程落地清单

  1. 信号只能做「有事发生」的提示,不能做「发生了几次」的计数。Linux 对同一信号只保留一个 pending,合并无法避免。

  2. 要保真就用内核侧原子计数或 per-event 队列。中断里 atomic_inc(),用户态读差值;或者 kfifo 排队。

  3. sem_post 防止不了内核侧的合并。计数信号量只保证「处理函数调用几次就 post 几次」。

  4. 中断通知优先用 eventfd。它是计数型的,eventfd_signal 累加不合并,而且不涉及 async-signal-safety 问题。

  5. release 必须失效全局指针。WRITE_ONCE(p, NULL) 并且中断处理里判空。否则进程退出后就是 UAF。

  6. 持有 task_struct 引用。用 get_task_struct/put_task_struct 而不是裸指针。

  7. 跨上下文共享的变量必须用 READ_ONCE/WRITE_ONCE。x86 上测不出来,ARM64 上会出问题。

  8. si_code 用合法值(SI_KERNEL / SI_USER / SI_QUEUE),不要写 -1。

  9. 队列满的策略要按消息语义选。状态刷新总线 drop-head(保最新),日志总线 drop-tail,命令总线阻塞。

  10. 轮询 vs 事件驱动要按延迟要求选。有 deadline 就用事件驱动,轮询的延迟下限是半个 tick,优化不掉。

  11. 轮询成本按通道数线性增长。单通道 0.061% 可忽略,100 通道 6.1% 就要考虑了。

  12. 控制回路的可行性用 max 判断,不是 avg。实测 avg 3.1 μs、max 135.1 μs,差 43 倍。

  13. 信号号必须相对 SIGRTMIN 定义。SIGRTMIN 是运行时函数不是常量,写死数字会在换 glibc 时撞车。

  14. 用一张分配表管理所有信号,加编译期断言防重叠。

附:实验环境

项值
编译器MinGW gcc 8.1.0(i686,32 位)
主机Windows,12 逻辑核(测量时负载 55.9%)
源码基线私有工程 platform/ko/irq_sig.c、platform/utils/irq_sig.c
实验程序e29_irq.c(7 节)

沙箱适配说明:

源码机制沙箱实现原因
SIGRTMIN+1 等 RT 信号用户态事件对象(ReleaseSemaphore/SetEvent)+ 条件变量MinGW 没有 SIGRTMIN、sigaction、41-48 号信号
sem_post/sem_waitWindows 计数信号量 / 事件对象语义等价
usleep(1000) 轮询timeBeginPeriod(1) + Sleep(1)主机默认 Sleep 粒度约 15 ms,需申请 1 ms 精度
send_sig_info 合并「一个 pending 事件对象」等价模型Windows 无内核信号投递

必须声明的局限:Windows 的 SetEvent/WaitForSingleObject 是用户态事件对象,不是 POSIX 信号。绝对延迟数值不可直接与 Linux POSIX 信号投递对比。但链路结构与争用点完全一致——处理函数在目标线程上下文执行、唤醒是一次上下文切换、工作线程必须被调度器捡起——这是本文测的东西。

声明:所有产品名、模块代号、业务语义均已脱敏,文中仅讨论通用 Linux 内核/用户态编程与中断处理设计。源码引用保留原始行号以便对照。