Skip to content

Feat: implement smp initially#58

Merged
muou000 merged 27 commits into
mainfrom
feat-smp
Jul 19, 2026
Merged

Feat: implement smp initially#58
muou000 merged 27 commits into
mainfrom
feat-smp

Conversation

@muou000

@muou000 muou000 commented Jul 18, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • 新功能
    • 增强多核启动与 CPU 在线状态跟踪,并为远程调度/处理器间中断提供错误回传与 IPI 能力开关。
    • 引入跨 CPU TLB shootdown(含固定邮箱完成机制),并将内存映射/解除映射的 TLB 刷新与回收按统一时机完成。
    • 新增可中断异步等待与任务中断接口。
  • Bug 修复
    • 修复并发下 Ext4 目录结构修改的竞态,提升用户地址页故障处理一致性。
    • 改善网络/平台(LoongArch64/RISC-V)启动、定时器与中断处理稳定性。
  • 测试
    • 扩展多核、CPU 拓扑、IPI/TLB、定时器与中断相关测试覆盖。

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

本次变更扩展了 SMP、IPI、TLB shootdown、CPU 拓扑、平台启动、中断、任务调度、地址空间、futex、Ext4 并发保护及 QEMU 资源配置,并新增相关错误类型、特性开关和初始化流程。

Changes

SMP、平台与内核并发

Layer / File(s) Summary
接口、特性与基础配置
crates/axplat/*, arceos/modules/axhal/*, Makefile, AGENTS.md
新增 IPI 与 CPU 引导错误接口,增加 CPU 在线状态 API,并更新 IPI 特性和 QEMU 默认资源配置。
RISC-V 拓扑、内存与中断平台
crates/axplat-riscv64-qemu-virt/*
新增 DTB 拓扑和内存解析,重构 PLIC、IPI、CPU 启动、页表及多核初始化。
LoongArch 平台启动、中断与定时器
crates/axplat-loongarch64-qemu-virt/*
更新内存映射、启动栈传递、串口、中断、CPU 引导和 oneshot 定时器实现。
IPI、TLB shootdown 与地址空间
arceos/modules/axipi/*, arceos/modules/axmm/*
新增 IPI 就绪与错误传播、固定邮箱 TLB shootdown、页故障完成语义和延迟地址空间克隆刷新。
任务调度、中断与栈管理
arceos/modules/axtask/*, arceos/modules/axruntime/*
增加远程调度状态、任务中断 API、任务切换竞态处理、在线 CPU 等待和每 CPU 栈缓存。
进程、futex 与用户内存路径
pulse_core/src/task/*, pulse_core/src/mm/loader.rs, pulse_syscalls/src/*
调整页故障完成、用户内存访问、futex 清理、线程注册退出和信号中断处理。
MemorySet、DMA 与文件系统并发
crates/memory_set/*, arceos/modules/axdma/*, arceos/modules/axfs/*, crates/ext4plus/*
为映射回收、DMA 属性更新、Ext4 目录操作和块分配增加延迟回收或并发保护。

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Poem

小兔蹦进多核窝,
IPI 叮咚传得多;
TLB 清风绕页飞,
任务醒来不再睡;
八核八G齐欢歌。

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题与本次引入 SMP 初始支持的主要变更直接相关,且简短明确。
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request introduces multi-core (SMP) and Inter-Processor Interrupt (IPI) support across the ArceOS runtime, memory management, and task scheduling modules, including platform-specific updates for RISC-V 64 and LoongArch64. Key enhancements include DTB-based CPU topology parsing, safe task migration, deferred waking, and multi-core TLB shootdowns. Feedback on these changes highlights three important issues: a critical infinite busy-wait loop in the garbage collection task when a task's reference count is greater than one, a potential concurrency race condition when assuming a single page table lock across page boundaries during allocation, and a false BadAddress error for zero-length unaligned writes.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread arceos/modules/axtask/src/run_queue.rs
Comment thread arceos/modules/axmm/src/backend/alloc.rs
Comment thread arceos/modules/axmm/src/aspace.rs
@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Initial SMP bring-up: CPU online tracking, IPIs, and 8G RAM boot fixes

✨ Enhancement 🐞 Bug fix ⚙️ Configuration changes 📝 Documentation 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Add initial SMP support with CPU online tracking, safer secondary boot, and interrupt routing.
• Harden scheduler wakeups, futex waits, and process/thread lifecycle against cross-CPU races.
• Support 8G RAM QEMU configs by mapping high RAM early and parsing DTB memory/topology.
Diagram

graph TD
  A(["Platform boot"]) --> B["DTB topo + RAM"] --> C[("CPU online mask")]
  C --> D["axruntime SMP start"] --> E["axipi IPI/TLB"] --> F["axmm COW + TLB"]
  D --> G["axtask scheduler"] --> E
  H["pulse_core proc/futex"] --> G --> F
  subgraph Legend
    direction LR
    _boot(["Boot stage"]) ~~~ _mod["Kernel module"] ~~~ _state[("Shared state")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Rely solely on queued IPI callbacks for TLB shootdowns
  • ➕ Less bespoke state (no per-CPU ticket mailboxes)
  • ➕ Reuse existing IPI queue/handler path
  • ➖ Unsafe when multiple CPUs fault with IRQs disabled; can deadlock or miss shootdowns
  • ➖ Harder to guarantee bounded progress under nested fault/lock contexts
2. Barrier-based SMP bring-up instead of CPU-online masks
  • ➕ Simpler mental model (global barriers at phases)
  • ➕ Less per-CPU state used by scheduler/IRQ routing
  • ➖ Less flexible for partial CPU boot failures / NotSupported cases
  • ➖ Harder to gate per-feature readiness (e.g., IPI queue readiness vs IRQ routing readiness)
3. Keep external IRQ routing pinned to boot CPU initially
  • ➕ Reduces moving parts while SMP stabilizes
  • ➕ Avoids rebalancing logic in PLIC/EIOINTC during early bring-up
  • ➖ Becomes a scalability bottleneck quickly
  • ➖ Complicates affinity and wake/migration behavior; diverges from SMP intent

Recommendation: The PR’s approach (explicit CPU-online publication + readiness gating, dedicated TLB shootdown tickets, and platform-level IRQ routing updates) is the safer option for kernel SMP. It avoids relying on general IPI callback draining in contexts where IRQs may be disabled, and it cleanly separates “possible CPUs” from “online/ready CPUs” for scheduling and interrupt delivery.

Files changed (59) +2289 / -608

Enhancement (20) +1411 / -259
irq.rsPass CPU ID into IRQ handler and expose IpiError +2/-2

Pass CPU ID into IRQ handler and expose IpiError

• Extends IRQ dispatch to pass the current CPU ID down to axplat::irq::handle. Re-exports IpiError for callers when ipi is enabled.

arceos/modules/axhal/src/irq.rs

lib.rsIntroduce global online CPU mask and publication API +50/-5

Introduce global online CPU mask and publication API

• Adds ONLINE_CPU_MASK plus helpers (online_cpu_mask/count, is_cpu_online, mark_cpu_online). Validates configured cpu_num fits within the mask width and notifies the platform IRQ controller when CPUs come online.

arceos/modules/axhal/src/lib.rs

lib.rsHarden IPI delivery and add fixed-mailbox TLB shootdowns +110/-23

Harden IPI delivery and add fixed-mailbox TLB shootdowns

• Adds per-CPU readiness gating, error-returning IPI APIs, and rollback on failed hardware sends. Introduces ticket-based TLB shootdowns that remain safe when IRQs are disabled and integrates servicing into ipi_handler.

arceos/modules/axipi/src/lib.rs

queue.rsSupport rollback of queued IPI events +5/-0

Support rollback of queued IPI events

• Adds pop_back() to remove the newest queued callback when the hardware IPI send fails. Used to keep queue state consistent with delivery guarantees.

arceos/modules/axipi/src/queue.rs

api.rsAdd task interruption API and tighten affinity validation +13/-7

Add task interruption API and tighten affinity validation

• Adds interrupt_task() to interrupt blocked tasks and unblock them when needed. Ensures set_current_affinity only accepts masks that include at least one online CPU and uses full task stacks for migration tasks.

arceos/modules/axtask/src/api.rs

mod.rsAdd interruptible future combinator and Interrupted error type +32/-1

Add interruptible future combinator and Interrupted error type

• Introduces Interrupted and interruptible() to stop futures when the current task is interrupted. Provides AxError conversion to integrate with syscall error handling.

arceos/modules/axtask/src/future/mod.rs

task.rsAdd switch-out serialization, task interruption, and per-CPU stack caching +135/-26

Add switch-out serialization, task interruption, and per-CPU stack caching

• Replaces on_cpu atomics with a switch_state lock supporting deferred wakes during switch-out. Adds interrupt flags + AtomicWaker for interruptible waits and implements a small per-CPU cache for standard-sized kernel task stacks to reduce churn.

arceos/modules/axtask/src/task.rs

irq.rsSeparate CPU-local vs external IRQ handling and implement IPIs +149/-26

Separate CPU-local vs external IRQ handling and implement IPIs

• Introduces CPU-local IRQ IDs (timer/IPI) distinct from external EIOINTC vectors and registers local handlers separately. Implements cpu_online tracking, IPI delivery via IOCSR, and robust dispatch for raw timer/IPI causes.

crates/axplat-loongarch64-qemu-virt/src/irq.rs

irq_common.rsIntroduce CPU-local IRQ flag and helpers +29/-0

Introduce CPU-local IRQ flag and helpers

• Defines CPU_LOCAL_IRQ_FLAG plus RAW_* and flagged TIMER/IPI IRQ IDs, and adds helpers to classify external IRQs and update enable masks. Includes tests validating the ID split and mask updates.

crates/axplat-loongarch64-qemu-virt/src/irq/irq_common.rs

power.rsPropagate CpuBootError from LoongArch cpu_boot +6/-4

Propagate CpuBootError from LoongArch cpu_boot

• Updates PowerIf::cpu_boot to return Result and forward errors from mp::start_secondary_cpu. Aligns the platform with the new generic power error model.

crates/axplat-loongarch64-qemu-virt/src/power.rs

init.rsInitialize platform memory from DTB and split primary/secondary IRQ init +4/-3

Initialize platform memory from DTB and split primary/secondary IRQ init

• Uses DTB pointer (mbi) to initialize platform memory layout early. Splits IRQ init into init_primary/init_secondary and aligns later init paths accordingly.

crates/axplat-riscv64-qemu-virt/src/init.rs

irq.rsSupport per-CPU external IRQ contexts and error-returning IPIs +45/-37

Support per-CPU external IRQ contexts and error-returning IPIs

• Routes PLIC claim/complete using the current logical CPU’s context, enables external interrupts on all harts, and wires cpu_online into PLIC routing. send_ipi now returns IpiError and resolves firmware hart IDs via topology.

crates/axplat-riscv64-qemu-virt/src/irq.rs

lib.rsWire in DTB topology modules +2/-0

Wire in DTB topology modules

• Adds cpu_topology and topology modules to the platform crate. Enables DTB-driven CPU mapping and PLIC context discovery.

crates/axplat-riscv64-qemu-virt/src/lib.rs

mem.rsParse DTB RAM and reserved ranges; publish immutable layout +249/-20

Parse DTB RAM and reserved ranges; publish immutable layout

• Adds DTB-based RAM range discovery (with fallback), reserved-memory extraction (including DTB itself), alignment/intersection logic, and one-time publication to static storages. Includes unit tests for range normalization and reserved alignment.

crates/axplat-riscv64-qemu-virt/src/mem.rs

plic.rsRework PLIC for SMP: CPU online routing and global source state +169/-91

Rework PLIC for SMP: CPU online routing and global source state

• Adds global PLIC state tracking enabled sources and online CPUs, initializes contexts for all CPUs, and routes external interrupts across online CPUs. Updates claim/complete to use per-CPU contexts and adds tests for CPU selection logic.

crates/axplat-riscv64-qemu-virt/src/plic.rs

power.rsReturn CpuBootError and resolve hart IDs for secondary boot +31/-6

Return CpuBootError and resolve hart IDs for secondary boot

• Makes cpu_boot return Result, checks for HSM availability, maps logical CPU IDs to firmware hart IDs, and decodes SBI error codes into CpuBootError variants. cpu_num now reflects DTB-discovered CPU count.

crates/axplat-riscv64-qemu-virt/src/power.rs

topology.rsAdd DTB-based CPU/PLIC topology publication +296/-0

Add DTB-based CPU/PLIC topology publication

• Parses /cpus for available harts, maps them to logical CPU IDs, and optionally discovers PLIC base/size/ndev and per-CPU supervisor external interrupt contexts. Publishes a legacy mapping fallback when DTB data is incomplete and validates DTB bounds within RAM.

crates/axplat-riscv64-qemu-virt/src/topology.rs

irq.rsAdd IpiError, cpu_online hook, and CPU-aware IRQ handling +33/-2

Add IpiError, cpu_online hook, and CPU-aware IRQ handling

• Extends the platform IRQ interface: handle now includes cpu_id, controllers can be notified when CPUs come online, and send_ipi returns a typed IpiError. This standardizes error reporting across platforms.

crates/axplat/src/irq.rs

power.rsAdd CpuBootError and make cpu_boot fallible +37/-1

Add CpuBootError and make cpu_boot fallible

• Introduces CpuBootError with Display/Error impls and updates PowerIf::cpu_boot to return Result. Enables runtime SMP code to handle partial boot failures (e.g., NotSupported) deterministically.

crates/axplat/src/power.rs

mod.rsShard global thread registry to reduce lock contention +14/-5

Shard global thread registry to reduce lock contention

• Replaces a single global THREAD_REGISTRY lock with 16 shards indexed by tid. Improves scalability and reduces hot lock contention under SMP.

pulse_core/src/task/mod.rs

Bug fix (19) +569 / -324
fs.rsSerialize ext4 directory mutations at filesystem scope +2/-0

Serialize ext4 directory mutations at filesystem scope

• Adds a filesystem-level async mutex to guard directory mutation operations. This reduces cross-task mutation races under SMP.

arceos/modules/axfs/src/fs/ext4/fs.rs

inode.rsGuard ext4 directory operations with directory-mutation lock +4/-0

Guard ext4 directory operations with directory-mutation lock

• Takes the new filesystem directory_mutation lock in create/link/unlink/rename paths. Prevents concurrent directory updates from corrupting state.

arceos/modules/axfs/src/fs/ext4/inode.rs

aspace.rsValidate user-writable pages on kernel writes and flush TLB on COW remaps +44/-2

Validate user-writable pages on kernel writes and flush TLB on COW remaps

• Makes AddrSpace::write verify all covered pages are mapped and user-writable, failing early so callers can fault/break COW first. Flushes TLB across CPUs when a page-fault handler changes an existing mapping (notably COW) and switches COW demotion flush to an all-CPU flush when IPIs are available.

arceos/modules/axmm/src/aspace.rs

alloc.rsBatch deallocation and tighten page-table locking in alloc backend +83/-44

Batch deallocation and tighten page-table locking in alloc backend

• Aggregates contiguous freed frames into runs to reduce allocator overhead during unmap. Reworks placeholder mapping handling to avoid repeated locks and deallocates unused frames after mapping attempts, improving correctness under concurrency.

arceos/modules/axmm/src/backend/alloc.rs

mod.rsMake network blocking waits interruptible +2/-1

Make network blocking waits interruptible

• Wraps smoltcp wait logic in axtask::future::interruptible, mapping interruptions into AxError. This lets signals/group-exit interrupt networking waits under SMP.

arceos/modules/axnet/src/smoltcp_impl/mod.rs

lib.rsTrack booted CPUs and gate init completion on actual started set +33/-1

Track booted CPUs and gate init completion on actual started set

• Adds BOOTED_CPU_MASK and SECONDARY_START_COMPLETE to avoid waiting for CPUs that were never started or not supported. Publishes IPI readiness and CPU-online state early, and waits for all CPUs to be IPI-ready before entering main.

arceos/modules/axruntime/src/lib.rs

mp.rsHarden secondary CPU start loop and publish CPU readiness +30/-11

Harden secondary CPU start loop and publish CPU readiness

• Switches to stack-slot accounting independent of cpu_id and records BOOTED_CPU_MASK per attempted boot. Handles CpuBootError failures (including NotSupported) and marks CPUs online only after scheduler/IPI init completes.

arceos/modules/axruntime/src/mp.rs

run_queue.rsMake SMP wake/migration safe and add IPI-based reschedule kicks +154/-74

Make SMP wake/migration safe and add IPI-based reschedule kicks

• Adds per-CPU run-queue readiness flags and uses axhal online state to avoid scheduling onto uninitialized CPUs. Replaces weak prev-task tracking with a strong reference until switch completion, adds deferred-wake handoff to close wake/context-save races, and uses IPIs to kick remote CPUs on enqueue/migration.

arceos/modules/axtask/src/run_queue.rs

boot.rsMap all high RAM during boot and read secondary stack from IOCSR mailbox +24/-15

Map all high RAM during boot and read secondary stack from IOCSR mailbox

• Builds boot page tables to map every 1G block of RAM needed for early boot with large memory. Makes _start_secondary public to mp code and switches secondary stack discovery to IOCSR mailbox1.

crates/axplat-loongarch64-qemu-virt/src/boot.rs

console.rsSerialize UART access and use ns16550 put loop +13/-20

Serialize UART access and use ns16550 put loop

• Removes raw volatile UART writes and funnels output through a locked UART instance with busy-wait put(). Prevents interleaved output across CPUs and avoids unsafe multi-base writes.

crates/axplat-loongarch64-qemu-virt/src/console.rs

eiointc.rsSerialize EIOINTC enable-mask updates +8/-3

Serialize EIOINTC enable-mask updates

• Adds a lock around enable register RMW updates and factors bit updates through a helper. Prevents lost updates when multiple CPUs toggle IRQ enables concurrently.

crates/axplat-loongarch64-qemu-virt/src/irq/eiointc.rs

mem.rsExpose split RAM ranges matching QEMU virt layout +9/-1

Expose split RAM ranges matching QEMU virt layout

• Changes phys_ram_ranges to return two ranges: low memory below the MMIO hole and high memory starting at PHYS_MEMORY_BASE. Enables allocators to see the full 8G layout correctly.

crates/axplat-loongarch64-qemu-virt/src/mem.rs

mp.rsHarden secondary CPU boot protocol using cached DMW and mailbox slots +24/-65

Harden secondary CPU boot protocol using cached DMW and mailbox slots

• Validates CPU IDs and stack bounds, converts entry/stack to cached DMW addresses, and writes stack+entry into distinct mailboxes before sending the boot IPI. Returns CpuBootError on failure instead of silently continuing.

crates/axplat-loongarch64-qemu-virt/src/mp.rs

time.rsProgram one-shot timers safely and clamp intervals to hardware width +17/-9

Program one-shot timers safely and clamp intervals to hardware width

• Disables timer before reprogramming, clears pending interrupts, and computes aligned/clamped intervals using timer bit-width. Prevents spurious timer IRQs and overflow/underflow in one-shot intervals.

crates/axplat-loongarch64-qemu-virt/src/time.rs

boot.rsMap all configured RAM early and initialize DTB topology +38/-11

Map all configured RAM early and initialize DTB topology

• Refactors boot page table initialization to map all 1G RAM chunks (identity + direct map) so the DTB placed near top-of-RAM remains accessible. Calls topology::init_from_dtb on primary and maps secondary harts to logical CPU IDs.

crates/axplat-riscv64-qemu-virt/src/boot.rs

lib.rsSerialize ext4 block-group bitmap mutations +2/-0

Serialize ext4 block-group bitmap mutations

• Adds per-block-group locking around block bitmap checks and descriptor updates. Prevents concurrent mutations from racing under SMP during allocation/free paths.

crates/ext4plus/src/lib.rs

process.rsFix futex/process races and reduce locking for common writes +74/-63

Fix futex/process races and reduce locking for common writes

• Fixes futex queue removal criteria to avoid orphaning waiters and ensures empty-queue cleanup occurs after releasing queue locks. Makes write_user_bytes attempt a read-locked fast path before taking write lock, adds no-fault u32 writes, publishes task refs before spawn on other CPUs, and switches group-exit wakes to interruptible task interruption.

pulse_core/src/task/process.rs

thread.rsInterrupt blocked threads on signals and avoid COW faults in clear_child_tid +7/-4

Interrupt blocked threads on signals and avoid COW faults in clear_child_tid

• Only interrupts tasks when a deliverable signal is pending, using interrupt_task instead of wake_task. Avoids syncing shared FS context for empty threads and uses write_user_u32_no_fault when clearing child TID during thread exit.

pulse_core/src/task/thread.rs

handler.rsClear task interruption state at syscall entry +1/-0

Clear task interruption state at syscall entry

• Clears any pending task interruption before resuming userspace syscall handling. Prevents stale interruptions from leaking across syscalls.

pulse_syscalls/src/handler.rs

Refactor (4) +21 / -7
dummy.rsAlign dummy platform interfaces with new SMP/IPI error APIs +14/-4

Align dummy platform interfaces with new SMP/IPI error APIs

• Updates dummy PowerIf::cpu_boot and IrqIf::send_ipi signatures to return Result with CpuBootError/IpiError. Adds stub cpu_online and updated handle signature.

arceos/modules/axhal/src/dummy.rs

lib.rsWire in new boot/mp/time helper modules +6/-1

Wire in new boot/mp/time helper modules

• Registers boot_common, mp_common, and time_common modules behind appropriate feature gates. Minor formatting fix for configuration assertion string.

crates/axplat-loongarch64-qemu-virt/src/lib.rs

loader.rsSilence unused page index during prefault +1/-1

Silence unused page index during prefault

• Renames the enumerate index binding to _page_idx. Purely avoids warnings during prefault range iteration.

pulse_core/src/mm/loader.rs

main.rsRemove unused Process import +0/-1

Remove unused Process import

• Drops an unused pulse_core::task::Process import. No functional change.

src/main.rs

Tests (4) +260 / -0
boot_common.rsAdd helpers for mapping QEMU split RAM in 1G L1 blocks +40/-0

Add helpers for mapping QEMU split RAM in 1G L1 blocks

• Introduces constants and functions to compute L1 block indices and required high-memory blocks. Includes unit tests for common RAM sizes (including 8G).

crates/axplat-loongarch64-qemu-virt/src/boot_common.rs

mp_common.rsAdd cached DMW address conversion and stack validation helpers +67/-0

Add cached DMW address conversion and stack validation helpers

• Provides const helpers to convert physical/kernel virtual addresses to cached DMW addresses and validate stack tops against RAM bounds. Includes unit tests for conversions and bounds checks.

crates/axplat-loongarch64-qemu-virt/src/mp_common.rs

time_common.rsAdd reusable one-shot tick alignment/clamp logic with tests +59/-0

Add reusable one-shot tick alignment/clamp logic with tests

• Implements tick alignment to TCFG granularity and clamps intervals to the timer counter width. Includes tests for minimum delay, rounding behavior, and clamping.

crates/axplat-loongarch64-qemu-virt/src/time_common.rs

cpu_topology.rsIntroduce compact hart-to-logical CPU topology structure +94/-0

Introduce compact hart-to-logical CPU topology structure

• Adds CpuTopology to map non-dense firmware hart IDs into dense logical CPU IDs. Includes tests for insertion order, duplicates, and capacity limits.

crates/axplat-riscv64-qemu-virt/src/cpu_topology.rs

Documentation (1) +3 / -3
AGENTS.mdUpdate QEMU run commands for 8 CPUs and 8G RAM +3/-3

Update QEMU run commands for 8 CPUs and 8G RAM

• Adjusts RISC-V and LoongArch QEMU command lines to use -smp 8 and -m 8G. Keeps guidance text formatting consistent.

AGENTS.md

Other (11) +25 / -15
config.tomlTemporarily disable vendored Cargo sources +4/-4

Temporarily disable vendored Cargo sources

• Comments out crates-io source replacement and vendored-sources directory configuration. This allows fetching dependencies directly during early SMP bring-up.

.cargo/config.toml

Cargo.tomlAdd smp feature flag and switch to 64G page allocator feature +2/-1

Add smp feature flag and switch to 64G page allocator feature

• Enables a workspace-level smp feature that wires axfeat smp + ipi. Replaces page-alloc-4g with page-alloc-64g to support larger RAM footprints.

Cargo.toml

MakefileDefault QEMU memory to 8G +1/-1

Default QEMU memory to 8G

• Changes exported MEM from 1G to 8G to match the new platform configuration and high-RAM boot mapping.

Makefile

Cargo.tomlPropagate IPI support into axtask when enabled +1/-1

Propagate IPI support into axtask when enabled

• Extends the axfeat ipi feature to also enable axtask’s ipi integration. This allows scheduler reschedule kicks via IPIs.

arceos/api/axfeat/Cargo.toml

Cargo.tomlAdd optional axipi dependency for cross-CPU TLB flushes +2/-0

Add optional axipi dependency for cross-CPU TLB flushes

• Introduces an ipi feature enabling axipi integration. Allows axmm to issue TLB shootdowns when COW remaps occur on other CPUs.

arceos/modules/axmm/Cargo.toml

Cargo.tomlEnable axmm ipi support when runtime ipi is enabled +1/-1

Enable axmm ipi support when runtime ipi is enabled

• Extends the runtime ipi feature to also enable axmm’s ipi integration. Ensures memory-management paths can issue TLB shootdowns when IPIs are in use.

arceos/modules/axruntime/Cargo.toml

Cargo.tomlAdd optional IPI integration feature for scheduler kicks +2/-0

Add optional IPI integration feature for scheduler kicks

• Introduces an ipi feature (depends on irq + axipi) and adds optional axipi dependency. Enables cross-CPU reschedule notifications for SMP.

arceos/modules/axtask/Cargo.toml

qemu.mkUse 8G memory for LoongArch QEMU runs +1/-1

Use 8G memory for LoongArch QEMU runs

• Overrides LoongArch MEM from 1G to 8G, matching updated platform memory maps and boot-time mappings.

arceos/scripts/make/qemu.mk

axconfig.tomlConfigure 8G RAM and split CPU-local IRQ IDs for LoongArch +5/-3

Configure 8G RAM and split CPU-local IRQ IDs for LoongArch

• Bumps phys-memory-size to 8G and encodes timer-irq and ipi-irq with a CPU-local flag bit. This separates CPU-local IRQ IDs from external EIOINTC vectors.

crates/axplat-loongarch64-qemu-virt/axconfig.toml

Cargo.tomlAdd fdt-raw dependency for DTB parsing +3/-0

Add fdt-raw dependency for DTB parsing

• Introduces the fdt-raw crate to support parsing CPU topology, PLIC properties, and memory ranges from the QEMU DTB.

crates/axplat-riscv64-qemu-virt/Cargo.toml

axconfig.tomlSet 8 CPUs and 8G RAM for RISC-V QEMU virt +3/-3

Set 8 CPUs and 8G RAM for RISC-V QEMU virt

• Bumps max-cpu-num to 8 and phys-memory-size to 8G. Matches the new boot page table mapping and DTB-driven topology discovery.

crates/axplat-riscv64-qemu-virt/axconfig.toml

@qodo-code-review

qodo-code-review Bot commented Jul 18, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 5 rules

Grey Divider


Action required

1. clear_child_tid skips COW ✓ Resolved 🐞 Bug ≡ Correctness
Description
Thread::clear_child_tid_on_exit now uses Process::write_user_u32_no_fault, which performs a
non-faulting AddrSpace::write that rejects read-only/COW-demoted pages. When this write fails, the
'?' returns early so the futex wake is skipped, leaving joiners blocked and CLONE_CHILD_CLEARTID
semantics broken.
Code

pulse_core/src/task/thread.rs[257]

+        self.process().write_user_u32_no_fault(clear_child_tid, 0)?;
Relevance

⭐⭐⭐ High

Team has accepted COW/user-memory correctness fixes, incl. tid-width writes and COW rollback
refcounting in PR #3.

PR-#3

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new exit hook uses a no-fault write that relies on AddrSpace::write, which explicitly errors out
unless the page is already writable; this contradicts the COW model where pages are demoted to
read-only and must be made writable via a fault/COW resolution path. Because the call is ?, a
failure prevents the futex wake from running.

pulse_core/src/task/thread.rs[252-263]
pulse_core/src/task/process.rs[1198-1208]
arceos/modules/axmm/src/aspace.rs[469-500]
arceos/modules/axmm/src/aspace.rs[920-923]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`Thread::clear_child_tid_on_exit()` was switched from `write_user_u32()` to `write_user_u32_no_fault()`. The new helper uses `AddrSpace::write()` under a read lock and explicitly rejects mappings that are not already `WRITE|USER` (e.g., COW-demoted pages), so clearing the user TID can fail on common fork/COW paths. Because the call uses `?`, a write failure also skips the subsequent futex wake, leaving waiters asleep.

### Issue Context
- COW cloning demotes parent mappings from writable to read-only, expecting the first write to fault and resolve COW.
- `write_user_u32_no_fault()` intentionally does *not* fault or resolve COW, so it is incompatible with `clear_child_tid` semantics.

### Fix Focus Areas
- pulse_core/src/task/thread.rs[252-263]
- pulse_core/src/task/process.rs[1198-1208]
- arceos/modules/axmm/src/aspace.rs[469-500]

### Suggested fix
- Prefer restoring `self.process().write_user_u32(clear_child_tid, 0)?;` so the existing fault/COW-handling path is used.
- If you truly must avoid faults here, implement a targeted fallback: on `BadAddress` due to non-writable mapping, attempt to fault/break COW (`try_fault_in_user_range(..., MappingFlags::WRITE)` or equivalent) and retry once, otherwise return the error (keeping the futex wake conditional on successful store).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. TLB shootdown panics ✓ Resolved 🐞 Bug ☼ Reliability
Description
axmm::flush_tlb_asid_all calls axipi::flush_tlb_all_cpus().expect(...), so any IPI delivery error
becomes an unconditional kernel panic in COW/page-fault paths. This is a reliability regression
unless the project explicitly treats shootdown failure as fatal and documents/guards that policy.
Code

arceos/modules/axmm/src/aspace.rs[R959-964]

+fn flush_tlb_asid_all(asid: usize) {
+    #[cfg(feature = "ipi")]
+    {
+        let _ = asid;
+        axipi::flush_tlb_all_cpus().expect("failed to issue TLB shootdown IPI");
+    }
Relevance

⭐⭐⭐ High

Team previously accepted reducing kernel panics in fault paths (avoid panicking on non-user faults)
in PR #11.

PR-#11

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new helper uses expect() on a Result-returning shootdown function. The shootdown path can fail
(e.g., if a CPU is not ready/online or the platform does not support IPIs), so the panic is
reachable unless higher layers guarantee infallibility.

arceos/modules/axmm/src/aspace.rs[959-964]
arceos/modules/axipi/src/lib.rs[99-141]
arceos/modules/axhal/src/dummy.rs[123-129]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`flush_tlb_asid_all()` panics on any error from `axipi::flush_tlb_all_cpus()`. Since `flush_tlb_all_cpus()` can return errors (offline CPU, platform/firmware failures, not supported), this turns an IPI problem into a hard crash inside memory-management operations.

### Issue Context
A fail-stop policy might be intentional for TLB coherency correctness, but the current code escalates *all* errors via `expect()` and provides no way for callers to handle/propagate the failure.

### Fix Focus Areas
- arceos/modules/axmm/src/aspace.rs[959-970]
- arceos/modules/axipi/src/lib.rs[99-141]

### Suggested fix
- Change `flush_tlb_asid_all()` to return `Result<(), IpiError>` (or `AxResult<()>`) instead of panicking.
- At call sites (COW clone, COW remap/page-fault paths), decide a consistent policy:
 - either propagate the error and fail the operation safely (preferred for robustness), or
 - if failure must be fatal, replace `expect()` with an explicit `panic!` that explains why continuing would be unsafe and consider feature/platform gating so it cannot trigger on unsupported configurations.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Vendored-sources config commented out ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The PR comments out the Cargo source replacement in .cargo/config.toml, changing dependency
sourcing behavior in a way that is not clearly tied to the stated SMP feature. This broad
build/config change increases review and audit scope and should be justified as SMP-required or
moved/reverted.
Code

.cargo/config.toml[R1-5]

+# [source.crates-io]
+# replace-with = "vendored-sources"

-[source.vendored-sources]
-directory = "vendor"
+# [source.vendored-sources]
+# directory = "vendor"
Relevance

⭐⭐ Medium

No historical evidence: .cargo/config.toml and .cargo/ not present on default branch; can’t infer
team stance.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2078110 requires each modified file to be within the functional scope of the
described feature. The diff shows .cargo/config.toml was changed to comment out the
vendored-sources configuration, which is a broad build configuration change not inherently specific
to SMP functionality.

Rule 2078110: Limit changesets to functional scope of modified files
.cargo/config.toml[1-5]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`.cargo/config.toml` now comments out the `source.crates-io` / `vendored-sources` configuration, altering dependency sourcing; this change is not clearly part of the SMP feature scope.

## Issue Context
PR title is `Feat: implement smp initially`, but this modification affects global build configuration and can impact reproducibility and dependency provenance.

## Fix Focus Areas
- .cargo/config.toml[1-5]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread .cargo/config.toml Outdated
Comment thread pulse_core/src/task/thread.rs Outdated
Comment thread arceos/modules/axmm/src/aspace.rs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 11

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
arceos/modules/axtask/src/run_queue.rs (1)

732-755: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

不要让外部任务引用无限期保留已退出任务的内核栈。

只要调用方保留 join handle 或 AxTaskRefstrong_count 就不会降到 1,此任务会被永久放回 EXITED_TASKS,其 kstack 也始终无法释放。上下文切出完成后应独立回收栈,而不是要求整个任务对象没有其他观察者。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@arceos/modules/axtask/src/run_queue.rs` around lines 732 - 755, Update
gc_entry’s exited-task cleanup so kernel stack reclamation is independent of
external join handles or AxTaskRef ownership. After the task’s context
switch-out is complete, release its kstack even when Arc::strong_count(&task) is
greater than one, while retaining the task object for remaining observers and
avoiding repeated stack cleanup.
pulse_core/src/task/thread.rs (1)

252-263: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

不要让合法的 clear_child_tid 映射因缺页而跳过 futex 唤醒。

write_user_u32_no_fault 不会处理尚未驻留或需要 COW 的有效页面;这里的 ? 随后会直接跳过 futex wake,可能令 pthread_join 永久等待。退出路径仍持有有效地址空间,应保留可缺页写入。

建议修复
-        self.process().write_user_u32_no_fault(clear_child_tid, 0)?;
+        self.process().write_user_u32(clear_child_tid, 0)?;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pulse_core/src/task/thread.rs` around lines 252 - 263, 将
clear_child_tid_on_exit 中的 write_user_u32_no_fault 替换为可处理缺页和 COW 的常规用户态 u32
写入接口,确保合法但未驻留的 clear_child_tid 映射仍能完成清零;保留后续两次 futex_wake_no_resched
调用及现有错误传播行为。
🧹 Nitpick comments (1)
arceos/modules/axfs/src/fs/ext4/inode.rs (1)

544-544: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift

避免用 filesystem-wide 锁串行化所有目录修改。

这把锁在磁盘读写、inode 分配/删除和缓存失效期间一直持有,会让不同目录之间的 create/link/unlink/rename 完全串行,削弱 SMP 下的并发能力。若 ext4plus 的底层操作已具备足够保护,建议改为按目录或按目录对锁定;否则至少缩短锁的 I/O 持有范围。

Also applies to: 612-612, 639-639, 693-693

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@arceos/modules/axfs/src/fs/ext4/inode.rs` at line 544, 移除
create/link/unlink/rename 路径中通过 self.fs.directory_mutation 获取的 filesystem-wide
锁,避免不同目录操作被全局串行化;改用按目录或目录对的锁保护共享状态,或至少将锁定范围缩短至必要的元数据更新,不要覆盖磁盘 I/O、inode
分配/删除及缓存失效流程。同步处理 inode.rs 中其他对应的 directory_mutation 使用点。
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@arceos/modules/axhal/src/dummy.rs`:
- Around line 94-99: Update the Dummy implementation’s cpu_boot method to return
axplat::power::CpuBootError::NotSupported instead of Ok(()), preserving its
existing signature and unused parameters so callers skip waiting for unsupported
secondary-CPU startup.

In `@arceos/modules/axipi/src/lib.rs`:
- Around line 116-128: 修复 TLB shootdown 发送流程中的部分失败处理:在包含 target_tickets 递增和 IPI
发送的调用路径中,不要让 send_ipi 的 ? 提前返回而遗留未完成票据。发送失败时应先完成或回滚所有已发布请求,并保持已刷新 CPU
与票据状态一致,使调用方能够安全重试。

In `@arceos/modules/axmm/src/aspace.rs`:
- Around line 959-969: Update flush_tlb_asid_all to stop using expect on
axipi::flush_tlb_all_cpus; propagate or return its Result so callers can handle
TLB shootdown failures without panicking. Ensure the surrounding
address-space/page-table update flow handles failure through CPU lifecycle
synchronization or rollback, so no remote stale TLB remains after an
unsuccessful shootdown.

In `@arceos/modules/axruntime/src/lib.rs`:
- Around line 182-188: CPU 在 IPI handler 和 IRQ 准备完成前被标记为
ready/online,可能导致请求滞留或同步等待死锁。更新 arceos/modules/axruntime/src/lib.rs:182-188,将主
CPU 的 axhal::mark_cpu_online 发布移至 axipi::init 与 axipi::mark_current_cpu_ready
完成之后;更新 arceos/modules/axruntime/src/mp.rs:66-82,使次级 CPU 仅在启用 IRQ
后发布,或在启动屏障中安全处理固定的 TLB mailbox。

In `@arceos/modules/axruntime/src/mp.rs`:
- Around line 30-36: 调整 cpu_boot 错误处理流程,不要将 CpuBootError::AlreadyOn 当作普通启动失败清除
BOOTED_CPU_MASK;为 AlreadyOn 增加单独的已启动 CPU 确认与计数路径,确保与 rust_main_secondary 的
INITED_CPUS 增加保持一致并满足 is_init_ok() 的计数条件,同时保留其他错误的现有清除和重试行为。

In `@arceos/scripts/make/qemu.mk`:
- Line 26: Update the MEM assignment to use a default-only value instead of
forcibly overriding user input, so command-line values such as make MEM=1G are
preserved while 8G remains the fallback for unspecified configurations.

In `@crates/axplat-loongarch64-qemu-virt/src/irq.rs`:
- Around line 87-98: Update the local IRQ unregister path around TIMER_HANDLER
and IPI_HANDLER so unregistering either global handler disables the
corresponding interrupt line on every online CPU, not only the calling CPU. Use
the existing cross-CPU execution mechanism and preserve the current per-CPU
set_enable behavior for external IRQ handlers; alternatively, reject
local-handler unregistration while SMP CPUs are online.

In `@crates/axplat-loongarch64-qemu-virt/src/mp.rs`:
- Around line 17-20: Update the stack validation in the boot path around
valid_stack_top to validate against each actual RAM segment from RAM_RANGES
instead of the single PHYS_MEMORY_BASE/PHYS_MEMORY_SIZE interval. Expose
RAM_RANGES as pub(crate) if needed, and accept the stack only when it falls
within at least one configured range; otherwise return
CpuBootError::InvalidAddress.

In `@crates/axplat-riscv64-qemu-virt/src/mem.rs`:
- Around line 90-105: 更新 push_u64_range 及其调用方,使 RangeList::push
的容量溢出状态能够向上传递;在收集 DTB、memreserve 和 reserved-memory 条目时检查失败结果,任何保留区间无法加入
candidates 都必须终止启动或采取等效的 fail-closed 策略,禁止继续发布不完整的内存布局。

In `@pulse_core/src/task/process.rs`:
- Around line 2751-2759: 在创建 queues 的流程中同时保存每个 waiter 入队时计算出的 futex `(key,
is_priv)`,并将其传递到清理阶段。更新 `futex_key` 相关逻辑,清理时直接复用已保存的 key
和私有性标记,不要根据当前地址重新计算;保持私有表与 `GLOBAL_FUTEX_TABLE` 的现有分支清理行为。

In `@pulse_syscalls/src/handler.rs`:
- Line 111: 调整 syscall 返回路径中 axtask::current().clear_interrupt() 的位置:将其移到 Line
88 对中断状态进行检查之前,用于清除旧状态;检查完成后不要再无条件清除,确保检查期间到达的新中断保持锁存并由后续可中断阻塞 syscall 处理。

---

Outside diff comments:
In `@arceos/modules/axtask/src/run_queue.rs`:
- Around line 732-755: Update gc_entry’s exited-task cleanup so kernel stack
reclamation is independent of external join handles or AxTaskRef ownership.
After the task’s context switch-out is complete, release its kstack even when
Arc::strong_count(&task) is greater than one, while retaining the task object
for remaining observers and avoiding repeated stack cleanup.

In `@pulse_core/src/task/thread.rs`:
- Around line 252-263: 将 clear_child_tid_on_exit 中的 write_user_u32_no_fault
替换为可处理缺页和 COW 的常规用户态 u32 写入接口,确保合法但未驻留的 clear_child_tid 映射仍能完成清零;保留后续两次
futex_wake_no_resched 调用及现有错误传播行为。

---

Nitpick comments:
In `@arceos/modules/axfs/src/fs/ext4/inode.rs`:
- Line 544: 移除 create/link/unlink/rename 路径中通过 self.fs.directory_mutation 获取的
filesystem-wide 锁,避免不同目录操作被全局串行化;改用按目录或目录对的锁保护共享状态,或至少将锁定范围缩短至必要的元数据更新,不要覆盖磁盘
I/O、inode 分配/删除及缓存失效流程。同步处理 inode.rs 中其他对应的 directory_mutation 使用点。
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c15200bb-5773-42ae-b595-fa6460007ea0

📥 Commits

Reviewing files that changed from the base of the PR and between e473bf8 and 9b80727.

⛔ Files ignored due to path filters (2)
  • Cargo.lock is excluded by !**/*.lock
  • Cargo.toml is excluded by !*.toml
📒 Files selected for processing (58)
  • .cargo/config.toml
  • AGENTS.md
  • Makefile
  • arceos/api/axfeat/Cargo.toml
  • arceos/modules/axfs/src/fs/ext4/fs.rs
  • arceos/modules/axfs/src/fs/ext4/inode.rs
  • arceos/modules/axhal/src/dummy.rs
  • arceos/modules/axhal/src/irq.rs
  • arceos/modules/axhal/src/lib.rs
  • arceos/modules/axipi/src/lib.rs
  • arceos/modules/axipi/src/queue.rs
  • arceos/modules/axmm/Cargo.toml
  • arceos/modules/axmm/src/aspace.rs
  • arceos/modules/axmm/src/backend/alloc.rs
  • arceos/modules/axnet/src/smoltcp_impl/mod.rs
  • arceos/modules/axruntime/Cargo.toml
  • arceos/modules/axruntime/src/lib.rs
  • arceos/modules/axruntime/src/mp.rs
  • arceos/modules/axtask/Cargo.toml
  • arceos/modules/axtask/src/api.rs
  • arceos/modules/axtask/src/future/mod.rs
  • arceos/modules/axtask/src/run_queue.rs
  • arceos/modules/axtask/src/task.rs
  • arceos/scripts/make/qemu.mk
  • crates/axplat-loongarch64-qemu-virt/axconfig.toml
  • crates/axplat-loongarch64-qemu-virt/src/boot.rs
  • crates/axplat-loongarch64-qemu-virt/src/boot_common.rs
  • crates/axplat-loongarch64-qemu-virt/src/console.rs
  • crates/axplat-loongarch64-qemu-virt/src/irq.rs
  • crates/axplat-loongarch64-qemu-virt/src/irq/eiointc.rs
  • crates/axplat-loongarch64-qemu-virt/src/irq/irq_common.rs
  • crates/axplat-loongarch64-qemu-virt/src/lib.rs
  • crates/axplat-loongarch64-qemu-virt/src/mem.rs
  • crates/axplat-loongarch64-qemu-virt/src/mp.rs
  • crates/axplat-loongarch64-qemu-virt/src/mp_common.rs
  • crates/axplat-loongarch64-qemu-virt/src/power.rs
  • crates/axplat-loongarch64-qemu-virt/src/time.rs
  • crates/axplat-loongarch64-qemu-virt/src/time_common.rs
  • crates/axplat-riscv64-qemu-virt/Cargo.toml
  • crates/axplat-riscv64-qemu-virt/axconfig.toml
  • crates/axplat-riscv64-qemu-virt/src/boot.rs
  • crates/axplat-riscv64-qemu-virt/src/cpu_topology.rs
  • crates/axplat-riscv64-qemu-virt/src/init.rs
  • crates/axplat-riscv64-qemu-virt/src/irq.rs
  • crates/axplat-riscv64-qemu-virt/src/lib.rs
  • crates/axplat-riscv64-qemu-virt/src/mem.rs
  • crates/axplat-riscv64-qemu-virt/src/plic.rs
  • crates/axplat-riscv64-qemu-virt/src/power.rs
  • crates/axplat-riscv64-qemu-virt/src/topology.rs
  • crates/axplat/src/irq.rs
  • crates/axplat/src/power.rs
  • crates/ext4plus/src/lib.rs
  • pulse_core/src/mm/loader.rs
  • pulse_core/src/task/mod.rs
  • pulse_core/src/task/process.rs
  • pulse_core/src/task/thread.rs
  • pulse_syscalls/src/handler.rs
  • src/main.rs
💤 Files with no reviewable changes (1)
  • src/main.rs

Comment thread arceos/modules/axhal/src/dummy.rs
Comment thread arceos/modules/axipi/src/lib.rs Outdated
Comment thread arceos/modules/axmm/src/aspace.rs Outdated
Comment thread arceos/modules/axruntime/src/lib.rs
Comment thread arceos/modules/axruntime/src/mp.rs Outdated
Comment thread crates/axplat-loongarch64-qemu-virt/src/irq.rs
Comment thread crates/axplat-loongarch64-qemu-virt/src/mp.rs
Comment thread crates/axplat-riscv64-qemu-virt/src/mem.rs
Comment thread pulse_core/src/task/process.rs
Comment thread pulse_syscalls/src/handler.rs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pulse_core/src/task/process.rs (1)

2632-2638: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

在分配内存前限制 nr_futexes 的最大值以防止 DoS 攻击。

没有任何限制地使用用户传入的 nr_futexes 调用 Vec::with_capacity,若传入极大的值会导致内核分配器因请求过大内存而引发 Panic (OOM),从而产生拒绝服务 (DoS) 漏洞。建议参考 Linux 引入 FUTEX_WAITV_MAX (128) 限制,同时拦截 nr_futexes == 0 的非法请求。

🐛 建议的修复
     pub fn futex_waitv(
         &self,
         waiters_addr: usize,
         nr_futexes: u32,
         _flags: u32,
         timeout_ns: Option<u64>,
     ) -> AxResult<isize> {
+        const FUTEX_WAITV_MAX: u32 = 128;
+        if nr_futexes == 0 || nr_futexes > FUTEX_WAITV_MAX {
+            return Err(AxError::InvalidInput);
+        }
         let mut waiters = alloc::vec::Vec::with_capacity(nr_futexes as usize);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pulse_core/src/task/process.rs` around lines 2632 - 2638, 在包含
Vec::with_capacity 的 futex 等待方法中,先校验用户传入的 nr_futexes:拒绝 nr_futexes == 0 以及超过
128(FUTEX_WAITV_MAX)的请求,并返回该方法约定的无效参数错误;仅在校验通过后分配 waiters,避免过大的容量请求触发 OOM。
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@pulse_core/src/task/process.rs`:
- Around line 2632-2638: 在包含 Vec::with_capacity 的 futex 等待方法中,先校验用户传入的
nr_futexes:拒绝 nr_futexes == 0 以及超过
128(FUTEX_WAITV_MAX)的请求,并返回该方法约定的无效参数错误;仅在校验通过后分配 waiters,避免过大的容量请求触发 OOM。

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f06679cc-21e2-4050-a9a6-db4b295d894e

📥 Commits

Reviewing files that changed from the base of the PR and between 9b80727 and 8e68dbe.

📒 Files selected for processing (11)
  • arceos/modules/axhal/src/dummy.rs
  • arceos/modules/axruntime/src/lib.rs
  • arceos/modules/axruntime/src/mp.rs
  • arceos/scripts/make/qemu.mk
  • crates/axplat-loongarch64-qemu-virt/src/irq.rs
  • crates/axplat-loongarch64-qemu-virt/src/mem.rs
  • crates/axplat-loongarch64-qemu-virt/src/mp.rs
  • crates/axplat-riscv64-qemu-virt/src/mem.rs
  • pulse_core/src/task/process.rs
  • pulse_core/src/task/thread.rs
  • pulse_syscalls/src/handler.rs
🚧 Files skipped from review as they are similar to previous changes (6)
  • pulse_syscalls/src/handler.rs
  • crates/axplat-loongarch64-qemu-virt/src/mem.rs
  • crates/axplat-loongarch64-qemu-virt/src/mp.rs
  • crates/axplat-riscv64-qemu-virt/src/mem.rs
  • crates/axplat-loongarch64-qemu-virt/src/irq.rs
  • arceos/modules/axruntime/src/lib.rs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pulse_core/src/record_lock.rs`:
- Around line 128-137: 在 do_record_lock 的成功加锁路径中,检测 clear_owner_range
是否实际释放或收窄了原有锁区间;若存在冲突区间已消失,克隆对应 target 的 wait_queue 并调用 notify_all
唤醒等待者。保持无实际范围变化时不发送通知,并保留现有新锁记录写入与成功返回逻辑。
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a8b46430-97ce-422d-8cf1-834eb37c310f

📥 Commits

Reviewing files that changed from the base of the PR and between 8e68dbe and fe8c5ea.

📒 Files selected for processing (9)
  • arceos/modules/axmm/src/aspace.rs
  • arceos/modules/axmm/src/lib.rs
  • arceos/modules/axtask/src/timers.rs
  • crates/axplat-loongarch64-qemu-virt/axconfig.toml
  • pulse_core/src/lib.rs
  • pulse_core/src/mm/loader.rs
  • pulse_core/src/record_lock.rs
  • pulse_core/src/task/process.rs
  • pulse_syscalls/src/impls/fs/fd.rs

Comment thread pulse_core/src/record_lock.rs Outdated
@muou000
muou000 merged commit 0b55924 into main Jul 19, 2026
1 check was pending
@muou000
muou000 deleted the feat-smp branch July 19, 2026 09:58

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
arceos/modules/axmm/src/aspace.rs (1)

51-87: 🚀 Performance & Scalability | 🔵 Trivial

IPI 路径下每次页表变更都会触发全局 TLB flush。

ipi 特性下,complete_after_unlock 忽略 asidslet _ = asids;)并调用 axipi::flush_tlb_all_cpus(),这是对所有 CPU 的全量 TLB 刷新。由于 unmap/protect/remap/COW 缺页(handle_page_faultHandledWithShootdown)都会走到这里,多线程进程的 COW 缺页热路径会在每次故障时对所有核发起一次全局 shootdown,SMP 下可能成为可扩展性瓶颈。

功能上正确,仅作架构提示:后续可考虑提供按 ASID / 按页范围的定向 shootdown 接口,让 TlbShootdown 携带的 asids 在 IPI 路径中真正生效,减少不必要的全量刷新。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@arceos/modules/axmm/src/aspace.rs` around lines 51 - 87, Update
TlbShootdown::complete_after_unlock in the IPI path to use the ASIDs carried by
asids for targeted TLB shootdowns instead of discarding them via let _ = asids
and calling axipi::flush_tlb_all_cpus(). Preserve the existing reclaim and
shootdown-error handling while routing invalidation only to the affected address
spaces.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@arceos/modules/axmm/src/backend/alloc.rs`:
- Around line 218-223: 修复 alloc.rs 中 pt.unmap 成功后的 page_size.is_huge 分支:返回 false
前先调用 tlb.flush() 并将 frame 交给 reclaim.defer_frame(frame)。同时在 file.rs 的 pt.unmap
流程中,为 page_size != PageSize::Size4K 分支应用相同处理,确保两处均遵守延迟回收契约。

---

Nitpick comments:
In `@arceos/modules/axmm/src/aspace.rs`:
- Around line 51-87: Update TlbShootdown::complete_after_unlock in the IPI path
to use the ASIDs carried by asids for targeted TLB shootdowns instead of
discarding them via let _ = asids and calling axipi::flush_tlb_all_cpus().
Preserve the existing reclaim and shootdown-error handling while routing
invalidation only to the affected address spaces.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 73aa1c84-fe82-4cf1-a2c5-f39c87701c4b

📥 Commits

Reviewing files that changed from the base of the PR and between 18f794b and c2e719c.

📒 Files selected for processing (16)
  • arceos/modules/axdma/src/dma.rs
  • arceos/modules/axipi/src/lib.rs
  • arceos/modules/axmm/src/aspace.rs
  • arceos/modules/axmm/src/backend/alloc.rs
  • arceos/modules/axmm/src/backend/cow.rs
  • arceos/modules/axmm/src/backend/file.rs
  • arceos/modules/axmm/src/backend/mod.rs
  • arceos/modules/axmm/src/lib.rs
  • crates/memory_set/README.md
  • crates/memory_set/src/area.rs
  • crates/memory_set/src/backend.rs
  • crates/memory_set/src/set.rs
  • crates/memory_set/src/tests.rs
  • pulse_core/src/fd_table.rs
  • pulse_syscalls/src/impls/ipc/shm.rs
  • pulse_syscalls/src/impls/mm.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • arceos/modules/axmm/src/lib.rs

Comment on lines 218 to +223
if let Ok((frame, page_size, tlb)) = pt.unmap(addr) {
// Deallocate the physical frame if there is a mapping in the
// page table.
if page_size.is_huge() {
return false;
}
tlb.flush();
if frame.as_usize() != 0 {
dealloc_frame(frame);
}
} else {
// Deallocation is needn't if the page is not mapped.
reclaim.defer_frame(frame);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

违反 unmap 延迟回收契约:提前 return false 会泄漏刚解除映射的帧。

crates/memory_set/src/backend.rs(L30-L32)明确要求:从页表分离的资源即使在部分 unmap 后返回 false 也必须加入 reclaim。这两处在遇到非预期页大小时,pt.unmap(addr) 已成功分离了该帧,却在未 defer_frame(也未 tlb.flush)的情况下直接返回 false,导致该物理帧被泄漏。虽然 alloc/file 后端理论上不应出现大页,但仍建议在返回前把已分离的帧交给 reclaim 以遵守契约。

  • arceos/modules/axmm/src/backend/alloc.rs#L218-L223:在 if page_size.is_huge() 分支返回 false 前,先 tlb.flush()reclaim.defer_frame(frame)
  • arceos/modules/axmm/src/backend/file.rs#L189-L192:在 if page_size != PageSize::Size4K 分支返回 false 前,对已分离的 frame 执行相同的 tlb.flush() + reclaim.defer_frame(frame)
📍 Affects 2 files
  • arceos/modules/axmm/src/backend/alloc.rs#L218-L223 (this comment)
  • arceos/modules/axmm/src/backend/file.rs#L189-L192
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@arceos/modules/axmm/src/backend/alloc.rs` around lines 218 - 223, 修复 alloc.rs
中 pt.unmap 成功后的 page_size.is_huge 分支:返回 false 前先调用 tlb.flush() 并将 frame 交给
reclaim.defer_frame(frame)。同时在 file.rs 的 pt.unmap 流程中,为 page_size !=
PageSize::Size4K 分支应用相同处理,确保两处均遵守延迟回收契约。

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant