Skip to content

[libc] fix: 64-bit truncations in timer_settime() and timer_gettime() - #11938

Open
Yunlk wants to merge 1 commit into
RT-Thread:masterfrom
Yunlk:fix/timer-gettime-truncation
Open

Yunlk wants to merge 1 commit into
RT-Thread:masterfrom
Yunlk:fix/timer-gettime-truncation

Conversation

@Yunlk

@Yunlk Yunlk commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

拉取/合并请求描述:(PR description)

[

为什么提交这份PR (why to submit this PR)

修复 #11924。issue 指出 timer_gettime() 把总纳秒存进 rt_uint32_t,这是真的;但进一步查发现它前面还有一个更严重的同类截断,只修 gettime 不会让结果变对。

1. timer_settime() 把 64 位的分辨率截成 32 位(主要问题)

unsigned long res = rt_clock_time_get_res_scaled();
timer->reload = (ns * RT_CLOCK_TIME_RESMUL) / res;

rt_clock_time_get_res_scaled() 的实现是 (1e9 * res_scale) / freq(clock_time_core.c:78)。对 100 Hz 的时钟源它就是 1e13,远超 UINT32_MAX。存进 unsigned long 只留下低 32 位(在 qemu-vexpress-a9 上是 1316134912),于是:

10 秒定时器 reload = (10e9 * 1e6) / 1316134912 = 7598005 ticks ≈ 21 小时

定时器本身就被 arm 成了错的时长,这时候 timer_gettime() 再准也没意义。

2. timer_gettime() 的两处截断

rt_uint32_t nanoseconds;    /* 存的是总纳秒,不只是秒以下部分 */
unsigned long remain_cnt;
nanoseconds = ((remain_cnt - rt_clock_time_get_counter()) * ...) / ...;
  • 总纳秒超过约 4.29 s 就截断(issue 指出的那处)
  • 32 位的到期计数减 64 位的硬件计数器,结果下溢成天文数字

你的解决方案是什么 (what is your solution)

  • timer_settime():用 64 位做换算,并对 res == 0 返回 EINVAL 而不是拿它做除数
  • timer_gettime():在 32 位空间里做减法(与 hrtimer 核心 _cnt_convert() 的做法一致),差值落在上半区视为已到期
  • 总纳秒用 64 位保存,直到拆成秒和纳秒

请提供验证的bsp和config (provide the config and bsp)

  • BSP: bsp/qemu-vexpress-a9(RT_TICK_PER_SECOND=100,res_scaled=1e13)
  • .config: 默认配置 + RT_USING_POSIX_TIMER(默认已开)+ utest 相关开关
  • action: 未使用 GitHub Actions;本地 QEMU 11.0.0 + arm-none-eabi-gcc 15.2.1,master 1c801efa

同一份固件、同一个探针,改前/改后各跑一次,timer_settime() 之后立刻 timer_gettime():

设定 改前 改后
1 s {0 s, 202853376 ns} {1 s, 0 ns}
3 s {0 s, 759022738 ns} {3 s, 0 ns}
5 s {1 s, 305192100 ns} {5 s, 0 ns}
10 s {2 s, 640384201 ns} {10 s, 0 ns}
60 s 同量级乱数 {60 s, 0 ns}

新增 utest 覆盖 1/3/5/10 s,在不打补丁的 master 上四个用例全部失败,打上后全部通过。断言同时检查「上报值不超过请求值」与「不小于请求值减 200 ms」,因为时钟源是 100 Hz 的 tick,读数时已经过了一部分 tick 是正常的。

两点说明

  1. timer->reload 仍是 unsigned long。修正 res 之后 reload 本身是 tick 数,10 秒在 100 Hz 下只有 1000,装得下;只有当单次定时超过 UINT32_MAX / freq(100 Hz 下约 497 天)才会溢出,那是另一个层面的问题,本次没有一并处理。

  2. utest 的 Kconfig 依赖是 RT_USING_POSIX_TIMER,需要 RT_USING_SIGNALS(用例用 SIGEV_SIGNAL 创建定时器)。如果 CI 的某个 BSP 没开信号,用例会创建失败——需要确认放在哪个 BSP/config 跑。

]

当前拉取/合并请求的状态 Intent for your PR

必须选择一项 Choose one (Mandatory):

  • 本拉取/合并请求是一个草稿版本 This PR is for a code-review and is intended to get feedback
  • 本拉取/合并请求是一个成熟版本 This PR is mature, and ready to be integrated into the repo

代码质量 Code Quality:

我在这个拉取/合并请求中已经考虑了 As part of this pull request, I've considered the following:

  • 已经仔细查看过代码改动的对比 Already check the difference between PR and old code
  • 代码风格正确,包括缩进空格,命名及其他风格 Style guide is adhered to, including spacing, naming and other styles
  • 没有垃圾代码,代码尽量精简,不包含#if 0代码,不包含已经被注释了的代码 All redundant code is removed and cleaned up
  • 所有变更均有原因及合理的,并且不会影响到其他软件组件代码或BSP All modifications are justified and not affect other components or BSP
  • 对难懂代码均提供对应的注释 I've commented appropriately where code is tricky
  • 代码是高质量的 Code in this PR is of high quality
  • 已经使用clang-format 源码格式化工具确保格式符合RT-Thread代码规范 This PR has been formatted with clang-format and complies with RT-Thread code specification
  • 如果是新增bsp, 已经添加ci检查到.github/ALL_BSP_COMPILE.json 详细请参考链接BSP自查

Both functions stored a 64-bit quantity in 32 bits, and the first one is far
more damaging than the second.

timer_settime():

    unsigned long res = rt_clock_time_get_res_scaled();
    timer->reload = (ns * RT_CLOCK_TIME_RESMUL) / res;

rt_clock_time_get_res_scaled() is (1e9 * res_scale) / freq, so it is 1e13 for a
100 Hz source - well above UINT32_MAX. Narrowing it to unsigned long picked up
the low 32 bits (1316134912 on qemu-vexpress-a9) and armed the timer for the
wrong duration: a 10 s timer got reload = 7598005 ticks, about 21 hours. The
reported remaining time was therefore wrong even before timer_gettime() had a
chance to truncate anything.

timer_gettime():

    rt_uint32_t nanoseconds;    /* holds the total, not just the sub-second part */
    unsigned long remain_cnt;

    nanoseconds = ((remain_cnt - rt_clock_time_get_counter()) * ...) / ...;

Two problems here: the total number of nanoseconds does not fit in rt_uint32_t
once the remainder exceeds about 4.29 s, and the 32-bit expiry count was
subtracted from the 64-bit hardware counter, which underflows into a huge value.

Fix both:

- convert in 64 bits in timer_settime(), and reject a zero resolution instead of
  dividing by it
- subtract the counter from the 32-bit expiry count in 32-bit space, treating a
  difference in the upper half as "already expired", the same way the hrtimer
  core does in _cnt_convert()
- keep the total in 64 bits until it is split into seconds and nanoseconds

Measured on bsp/qemu-vexpress-a9 (100 Hz tick source, res_scaled = 1e13,
QEMU 11.0.0, arm-none-eabi-gcc 15.2.1). A timer is armed and timer_gettime() is
called immediately afterwards:

    requested    before                                  after
    1 s          {0 s, 202853376 ns}                     {1 s, 0 ns}
    3 s          {0 s, 759022738 ns}                     {3 s, 0 ns}
    5 s          {1 s, 305192100 ns}                     {5 s, 0 ns}
    10 s         {2 s, 640384201 ns}                     {10 s, 0 ns}
    60 s         {7 s, ...}                              {60 s, 0 ns}

The new utest covers 1/3/5/10 s and fails on all four cases without this patch.

Refs RT-Thread#11924
@Yunlk
Yunlk requested a review from mysterywolf as a code owner October 28, 2026 06:10
@github-actions

Copy link
Copy Markdown

👋 感谢您对 RT-Thread 的贡献!Thank you for your contribution to RT-Thread!

为确保代码符合 RT-Thread 的编码规范,请在你的仓库中执行以下步骤运行代码格式化工作流(如果格式化CI运行失败)。
To ensure your code complies with RT-Thread's coding style, please run the code formatting workflow by following the steps below (If the formatting of CI fails to run).


🛠 操作步骤 | Steps

  1. 前往 Actions 页面 | Go to the Actions page
    点击进入工作流 → | Click to open workflow →

  2. 点击 Run workflow | Click Run workflow

  • Use workflow from 保持默认分支(通常为 master)
    Keep the default branch (usually master) in Use workflow from
  • 在 branch 输入框填写 PR 分支 fix/timer-gettime-truncation
    Enter PR branch fix/timer-gettime-truncation in the branch field
  • 设置需排除的文件/目录(目录请以"/"结尾)
    Set files/directories to exclude (directories should end with "/")
  1. 等待工作流完成 | Wait for the workflow to complete
    格式化后的代码将作为独立提交推送至你的分支。
    The formatting changes will be pushed to your branch as a separate commit.

完成后,提交将自动更新至 fix/timer-gettime-truncation 分支,关联的 Pull Request 也会同步更新。
Once completed, commits will be pushed to the fix/timer-gettime-truncation branch automatically, and the related Pull Request will be updated.

如有问题欢迎联系我们,再次感谢您的贡献!💐
If you have any questions, feel free to reach out. Thanks again for your contribution!

@github-actions

Copy link
Copy Markdown

📌 Code Review Assignment

🏷️ Tag: components

Reviewers: @Maihuanyi

Changed Files (Click to expand)
  • components/libc/compilers/common/ctime.c
  • components/libc/compilers/common/utest/Kconfig
  • components/libc/compilers/common/utest/SConscript
  • components/libc/compilers/common/utest/timer_gettime_tc.c

🏷️ Tag: components_libc

Reviewers: @GorrayLi @mysterywolf

Changed Files (Click to expand)
  • components/libc/compilers/common/ctime.c
  • components/libc/compilers/common/utest/Kconfig
  • components/libc/compilers/common/utest/SConscript
  • components/libc/compilers/common/utest/timer_gettime_tc.c

📊 Current Review Status (Last Updated: 2026-10-28 14:12 CST)


📝 Review Instructions

  1. 维护者可以通过单击此处来刷新审查状态: 🔄 刷新状态
    Maintainers can refresh the review status by clicking here: 🔄 Refresh Status

  2. 确认审核通过后评论 LGTM/lgtm
    Comment LGTM/lgtm after confirming approval

  3. PR合并前需至少一位维护者确认
    PR must be confirmed by at least one maintainer before merging

ℹ️ 刷新CI状态操作需要具备仓库写入权限。
ℹ️ Refresh CI status operation requires repository Write permission.

@github-actions

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant