Skip to content

feat[libcpu][cortex-m4]: Detect interrupt context from IPSR on Cortex-M4`#11316

Open
wdfk-prog wants to merge 2 commits intoRT-Thread:masterfrom
wdfk-prog:Cortex-interrupt
Open

feat[libcpu][cortex-m4]: Detect interrupt context from IPSR on Cortex-M4`#11316
wdfk-prog wants to merge 2 commits intoRT-Thread:masterfrom
wdfk-prog:Cortex-interrupt

Conversation

@wdfk-prog
Copy link
Copy Markdown
Contributor

@wdfk-prog wdfk-prog commented Apr 5, 2026

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

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

当前补丁的核心目标,是将 Cortex-M4 平台上的中断上下文识别与相关 hook 调用路径显式化,并减少调度器对外部中断嵌套计数变量的直接耦合。

现有实现中,scheduler_up.c 直接依赖 rt_interrupt_nest 判断当前是否处于中断上下文;而在 Cortex-M4 平台上,这类信息本身可以直接通过 IPSR 寄存器判断。与此同时,本补丁还补充了 rt_interrupt_enter() / rt_interrupt_leave() 的平台侧实现,以及中断屏蔽状态查询接口 rt_hw_interrupt_is_disabled(),使 Cortex-M4 平台上的中断相关行为更完整、更清晰。

因此提交本 PR,以完善 Cortex-M4 架构下的中断上下文识别能力、补齐中断 enter/leave hook 调用链,并将调度器中的中断态判断改为通过统一接口获取,降低对内部变量的直接依赖。

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

本 PR 主要做了以下修改:

  1. 补充 Cortex-M4 中断上下文识别能力

    • libcpu/arm/cortex-m4/cpuport.c 中新增 __get_IPSR()
    • 基于 IPSR 实现 rt_interrupt_get_nest()
    • 当前实现用于判断“是否处于中断上下文”,返回值语义等价于布尔态。
  2. 补充 Cortex-M4 中断 enter/leave 路径

    • cpuport.c 中新增 rt_interrupt_enter()
    • cpuport.c 中新增 rt_interrupt_leave()
    • 两个接口都会调用对应的 hook:
      • rt_interrupt_enter_hook
      • rt_interrupt_leave_hook
  3. 暴露中断 hook 指针供平台侧使用

    • src/irq.c 中,将:
      • rt_interrupt_enter_hook
      • rt_interrupt_leave_hook
        从文件内 static 变量改为全局可见符号;
    • 使平台实现能够复用统一的 hook 机制。
  4. 增加中断屏蔽状态查询接口

    • cpuport.c 中新增 rt_hw_get_primask_value()
    • 基于 PRIMASK 实现 rt_hw_interrupt_is_disabled()
    • 用于判断当前 maskable interrupt 是否被关闭。
  5. 调整调度器中的中断态判断方式

    • src/scheduler_up.c 中移除对 rt_interrupt_nest 的直接 extern 依赖;
    • 将日志与调度分支中的判断改为调用 rt_interrupt_get_nest()
    • 避免直接依赖特定内部计数变量。

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

  • BSP:

    • 任意 ARM Cortex-M4 BSP
    • 建议至少补充 1 个你实际验证过的 BSP,例如:
      • bsp/stm32/stm32f407-atk-explorer
      • 或你本次修改实际使用的 Cortex-M4 BSP 路径
  • .config:

    • CONFIG_ARCH_ARM_CORTEX_M4
    • 如需验证 hook 路径,建议开启:
      • CONFIG_RT_USING_HOOK
    • 如需结合日志验证,可补充对应日志宏或调试配置
  • 验证方式:

    • 编译通过 Cortex-M4 BSP;
    • 进入线程上下文时,rt_interrupt_get_nest() 返回 0;
    • 进入中断处理函数时,rt_interrupt_get_nest() 返回非 0;
    • rt_interrupt_enter() / rt_interrupt_leave() 能正常触发 hook;
    • rt_schedule() 在中断上下文下不会走线程态切换路径;
    • rt_hw_interrupt_is_disabled() 在关中断/开中断场景下返回值符合预期。
  • action:

    • 请填写你自己仓库 PR branch 对应的 CI / Action 链接

当前拉取/合并请求的状态 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
  • 已经使用 formatting 等源码格式化工具确保格式符合 RT-Thread 代码规范 This PR complies with RT-Thread code specification
  • 如果是新增 bsp, 已经添加 ci 检查到 .github/ALL_BSP_COMPILE.json 详细请参考链接 BSP 自查

@github-actions
Copy link
Copy Markdown

github-actions bot commented Apr 5, 2026

👋 感谢您对 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

  • 设置需排除的文件/目录(目录请以"/"结尾)
    Set files/directories to exclude (directories should end with "/")
  • 将目标分支设置为 \ Set the target branch to:Cortex-interrupt
  • 设置PR number为 \ Set the PR number to:11316
  1. 等待工作流完成 | Wait for the workflow to complete
    格式化后的代码将自动推送至你的分支。
    The formatted code will be automatically pushed to your branch.

完成后,提交将自动更新至 Cortex-interrupt 分支,关联的 Pull Request 也会同步更新。
Once completed, commits will be pushed to the Cortex-interrupt 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 github-actions bot added the libcpu label Apr 5, 2026
@github-actions github-actions bot added the Kernel PR has src relate code label Apr 6, 2026
@github-actions
Copy link
Copy Markdown

github-actions bot commented Apr 6, 2026

📌 Code Review Assignment

🏷️ Tag: kernel

Reviewers: @GorrayLi @ReviewSun @hamburger-os @lianux-mm @wdfk-prog @xu18838022837

Changed Files (Click to expand)
  • src/irq.c
  • src/scheduler_up.c

📊 Current Review Status (Last Updated: 2026-04-06 09:11 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.

@wdfk-prog wdfk-prog changed the title feat[libcpu][cortex-m4]: Add interrupt state query helpers for Cortex-M4 feat[libcpu][cortex-m4]: Detect interrupt context from IPSR on Cortex-M4` Apr 6, 2026
@Rbb666 Rbb666 requested a review from Copilot April 7, 2026 02:04
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR aims to make “interrupt context” detection on Cortex-M4 explicit (via IPSR), reduce direct scheduler coupling to rt_interrupt_nest, and complete Cortex-M4-side interrupt hook/IRQ-mask query support.
本 PR 目标是在 Cortex-M4 上显式化“中断上下文”识别(基于 IPSR),降低调度器对 rt_interrupt_nest 的直接耦合,并补齐 Cortex-M4 侧的中断 hook / 中断屏蔽状态查询能力。

Changes:

  • Replace src/scheduler_up.c direct dependency on rt_interrupt_nest with rt_interrupt_get_nest().
  • Expose interrupt enter/leave hook function pointers for platform-side reuse.
  • Add Cortex-M4 implementations for rt_interrupt_enter/leave, rt_interrupt_get_nest(), and rt_hw_interrupt_is_disabled().

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 9 comments.

File Description
src/scheduler_up.c Switch interrupt-context checks/logging to rt_interrupt_get_nest() instead of rt_interrupt_nest.
src/irq.c Make interrupt enter/leave hook pointers globally visible (non-static).
libcpu/arm/cortex-m4/cpuport.c Add IPSR/PRIMASK helpers and Cortex-M4 overrides for IRQ enter/leave, nest query, and IRQ-disabled query.

"thread:%.*s(sp:0x%08x), "
"from thread:%.*s(sp: 0x%08x)",
rt_interrupt_nest, highest_ready_priority,
rt_interrupt_get_nest(), highest_ready_priority,
Copy link

Copilot AI Apr 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[custom/类别]: 🟡 [PR Title/PR 标题]: Missing or incorrect prefix format / 缺少或错误的前缀格式

English: PR title should follow format: [module][subsystem] Description in lowercase. Current title starts with feat and does not start with the bracketed prefix, which diverges from the repo’s PR title convention.
中文:PR 标题应遵循格式:小写的 [模块][子系统] 描述。当前标题以 feat 开头且未以方括号前缀开头,与仓库约定不一致。

Copilot generated this review using guidance from repository custom instructions.
Comment on lines +29 to +30
void (*rt_interrupt_enter_hook)(void);
void (*rt_interrupt_leave_hook)(void);
Copy link

Copilot AI Apr 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[maintainability/类别]: Exported hook function pointers lack a public declaration / 导出的 hook 函数指针缺少公开声明

English: rt_interrupt_enter_hook / rt_interrupt_leave_hook are now global symbols but are not declared in any header, forcing other translation units to redeclare them with extern (as done in cpuport.c). To avoid drift and keep types consistent, please add a single authoritative declaration in an appropriate internal header (guarded by RT_USING_HOOK && RT_HOOK_USING_FUNC_PTR), or alternatively keep the pointers private and expose a small rt_interrupt_enter_hook_call()/rt_interrupt_leave_hook_call() helper.
中文:rt_interrupt_enter_hook / rt_interrupt_leave_hook 现在变成了全局符号,但当前没有任何头文件声明它们,导致其他文件只能各自 extern 重复声明(如 cpuport.c)。为避免类型不一致与维护成本,建议在合适的内部头文件中提供唯一声明(并用 RT_USING_HOOK && RT_HOOK_USING_FUNC_PTR 保护),或保持指针私有并提供 rt_interrupt_enter_hook_call()/rt_interrupt_leave_hook_call() 之类的小封装接口。

Suggested change
void (*rt_interrupt_enter_hook)(void);
void (*rt_interrupt_leave_hook)(void);
static void (*rt_interrupt_enter_hook)(void);
static void (*rt_interrupt_leave_hook)(void);

Copilot uses AI. Check for mistakes.
Comment on lines +349 to 353
rt_interrupt_get_nest(), highest_ready_priority,
RT_NAME_MAX, to_thread->parent.name, to_thread->sp,
RT_NAME_MAX, from_thread->parent.name, from_thread->sp);

RT_SCHEDULER_STACK_CHECK(to_thread);
Copy link

Copilot AI Apr 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[performance/类别]: Avoid calling rt_interrupt_get_nest() multiple times in rt_schedule / 避免在 rt_schedule 中重复调用 rt_interrupt_get_nest()

English: rt_interrupt_get_nest() can be relatively expensive on some ports (e.g., it may mask/restore IRQs to read an atomic counter). Here it’s called for logging; please cache the value in a local variable and reuse it for the subsequent ISR-context check.
中文:在部分架构上 rt_interrupt_get_nest() 可能会关/开中断以读取原子计数,代价不低。此处用于日志打印时已调用一次,建议缓存到局部变量并在后续 ISR 上下文判断时复用。

Copilot uses AI. Check for mistakes.
Comment on lines +473 to +477
void rt_interrupt_enter(void)
{
extern void (*rt_interrupt_enter_hook)(void);
RT_OBJECT_HOOK_CALL(rt_interrupt_enter_hook,());
LOG_D("irq has come...");
Copy link

Copilot AI Apr 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[bug/类别]: rt_interrupt_enter() override does not increment interrupt nest counter / 覆盖实现的 rt_interrupt_enter() 未增加中断嵌套计数

English: The generic src/irq.c implementation increments rt_interrupt_nest before calling the enter hook. This Cortex-M4 override only calls the hook/log, so the nesting counter will never increase on Cortex-M4, breaking code/tests that rely on nesting depth. Please keep rt_interrupt_nest maintenance consistent (or avoid overriding if not needed).
中文:通用实现(src/irq.c)会在调用 enter hook 前递增 rt_interrupt_nest。当前 Cortex-M4 覆盖实现仅调用 hook/日志,导致 Cortex-M4 上嵌套计数不会增加,从而影响依赖嵌套深度的代码/测试。建议保持 rt_interrupt_nest 的维护语义一致(或如果无必要则不要覆盖该函数)。

Copilot uses AI. Check for mistakes.
Comment on lines +488 to +489
{
extern void (*rt_interrupt_leave_hook)(void);
Copy link

Copilot AI Apr 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[bug/类别]: rt_interrupt_leave() override does not decrement interrupt nest counter / 覆盖实现的 rt_interrupt_leave() 未减少中断嵌套计数

English: The generic src/irq.c implementation decrements rt_interrupt_nest on leave. This Cortex-M4 override doesn’t update the counter, so rt_interrupt_nest becomes inconsistent on Cortex-M4 builds. Please decrement the nest counter (and keep hook call order consistent with the generic implementation) or avoid overriding.
中文:通用实现(src/irq.c)在 leave 时会递减 rt_interrupt_nest。当前 Cortex-M4 覆盖实现未更新该计数,导致 Cortex-M4 上 rt_interrupt_nest 失真。建议补齐递减逻辑(并保持 hook 调用顺序与通用实现一致),或避免覆盖实现。

Suggested change
{
extern void (*rt_interrupt_leave_hook)(void);
{
extern rt_uint8_t rt_interrupt_nest;
extern void (*rt_interrupt_leave_hook)(void);
rt_interrupt_nest--;

Copilot uses AI. Check for mistakes.
Comment on lines +502 to +505
rt_uint8_t rt_interrupt_get_nest(void)
{
return (__get_IPSR() != 0);
}
Copy link

Copilot AI Apr 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[bug/类别]: rt_interrupt_get_nest() changed from “nesting depth” to boolean / rt_interrupt_get_nest() 从“嵌套深度”变为布尔语义

English: The API contract is “the number of nested interrupts”, but this implementation returns only 0/1 based on IPSR. This can break callers that expect depth > 1 (e.g., IRQ nesting tests or logic distinguishing nested vs first-level ISR). Please keep rt_interrupt_get_nest() returning the real nesting count; add a separate fast helper for “in ISR context” if needed.
中文:该 API 约定是“中断嵌套次数”,但当前实现仅基于 IPSR 返回 0/1。这样会破坏依赖嵌套深度 > 1 的调用方(例如中断嵌套测试或需要区分是否发生嵌套的逻辑)。建议保持 rt_interrupt_get_nest() 返回真实嵌套计数;若需要快速判断 ISR 上下文,可新增独立接口。

Copilot uses AI. Check for mistakes.
Comment on lines +448 to +452
rt_inline rt_uint32_t __get_IPSR(void)
{
#if defined(__CC_ARM)
register uint32_t __regIPSR __asm("ipsr");
return(__regIPSR);
Copy link

Copilot AI Apr 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[best_practices/类别]: Avoid defining __get_IPSR (reserved/CMSIS name) in RT-Thread code / 避免在 RT-Thread 代码中定义 __get_IPSR(保留标识符/CMSIS 重名)

English: __get_IPSR is commonly provided by CMSIS and the leading __ identifier is reserved by the C standard. Defining it here risks redefinition conflicts depending on BSP/CMSIS include order. Prefer using the CMSIS intrinsic (include the proper CMSIS header) or rename this helper to an RT-Thread-specific name.
中文:__get_IPSR 通常由 CMSIS 提供,且以 __ 开头的标识符属于 C 标准保留名称。在此处定义可能因 BSP/CMSIS 头文件包含顺序导致重定义冲突。建议直接使用 CMSIS 的实现(包含对应头文件),或将本地辅助函数改为 RT-Thread 风格命名。

Copilot uses AI. Check for mistakes.
Comment on lines +450 to +454
#if defined(__CC_ARM)
register uint32_t __regIPSR __asm("ipsr");
return(__regIPSR);
#elif defined(__clang__)
uint32_t result;
Copy link

Copilot AI Apr 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[bug/类别]: __get_IPSR() lacks a final #else/#error or return path / __get_IPSR() 缺少最终 #else/#error 或返回路径

English: This #if/#elif chain has no final #else branch. If none of the toolchain macros match, the function may compile without a return (UB) or fail under Werror. Please add a final #else with #error (preferred) or a safe fallback return.
中文:该 #if/#elif 分支没有最终的 #else。若工具链宏都不匹配,可能出现“非 void 函数未返回”的未定义行为,或在 Werror 下编译失败。建议补充最终 #else:给出 #error(推荐)或安全兜底返回值。

Copilot uses AI. Check for mistakes.
Comment on lines +514 to +518
#if defined(__CC_ARM)
register uint32_t __regPRIMASK __asm("primask");
return (__regPRIMASK);
#elif defined(__clang__)
uint32_t result;
Copy link

Copilot AI Apr 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[bug/类别]: rt_hw_get_primask_value() lacks a final #else/#error or return path / rt_hw_get_primask_value() 缺少最终 #else/#error 或返回路径

English: Like __get_IPSR(), this helper has no final #else branch. Please add a final #else with #error (preferred) or a safe fallback return to avoid undefined behavior / build failures on unexpected toolchains.
中文:与 __get_IPSR() 类似,该辅助函数也缺少最终 #else 分支。建议补充最终 #else:使用 #error(推荐)或安全兜底返回值,以避免在非预期工具链下出现未定义行为/编译失败。

Copilot uses AI. Check for mistakes.
@kurisaW kurisaW added the 5.3.0 label Apr 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

5.3.0 Kernel PR has src relate code libcpu

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants