tianole/docs/agents/tasks/04-time-scheduler.md

77 lines
3.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 04 时钟、内核线程与调度
## 目标
建立 kernel 内部并发执行能力,为驱动等待、异步 I/O、进程和用户态做准备。
## 前置条件
- 中断入口可用。
- 内存分配可用。
- 至少一个 timer 可接入。
## 建议边界
- `kernel/sched/`:线程、调度器、等待队列。
- `kernel/time/`:通用时间与 timer 抽象。
- `arch/x86/`:具体 timer、上下文切换。
## 实现内容
- 建立 kernel thread。
- 建立上下文切换。
- 建立 run queue。
- 建立 sleep/wakeup。
- 建立基础 spinlock 或 interrupt-safe lock。
- 接入 timer tick 或 one-shot timer。
- 为 workqueue、deferred work、completion、引用计数生命周期管理预留位置。
## 非玩具化约束
- 调度器不能直接绑定某一种硬件 timer。
- 线程数量不能固定写死。
- 等待队列要能被驱动、文件系统和进程等待复用。
- 日志只能辅助观察,不能成为调度逻辑的一部分。
- 内核对象不能依赖“永不释放”的假设。
- 任何可睡眠路径和不可睡眠路径要从接口上区分。
## 验收方式
- 两个以上 kernel thread 能轮转。
- 线程可以 sleep 并被 timer 唤醒。
- 调度现场保存和恢复稳定。
- 基础对象生命周期规则有文档和调用约束。
## 当前状态
基础完成:
- 已建立 x86 PIC remap外部 IRQ 使用 vector 32-47不再和 CPU exception 混用。
- 已接入 PIT periodic timer当前频率为 100Hz。
- 已建立通用 `timer_tick()` 入口和 `timer_ticks()` 计数接口。
- 已在 trap dispatch 中区分 CPU exception 和外部 IRQ。
- 已对 timer IRQ0 发送 EOI避免中断只触发一次。
- 已建立最小 kernel thread 对象,包含 id、状态、入口、参数、内核栈和 run queue 链接。
- 已建立动态 run queue不固定写死线程数量。
- 已能通过 `kernel_thread_create()` 动态分配线程对象和内核栈。
- 已建立 x86 上下文切换入口,保存/恢复 callee-saved 寄存器和栈指针。
- 已建立线程 trampoline新线程能从独立内核栈进入自己的入口函数。
- 已建立协作式 round-robin两个 kernel thread 能通过 `sched_yield()` 轮转运行。
- 已把调度接入 `timer_tick()`timer tick 会唤醒到期 sleep 线程并触发 round-robin。
- 已建立 idle thread所有普通线程 sleep/wait 时由 idle 承接 CPU。
- 已提供 `sched_sleep()`,线程可以睡眠指定 tick 数并被 timer 唤醒。
- 已提供 `wait_queue_init()`、`wait_queue_sleep()`、`wait_queue_wake_one()` 和 `wait_queue_wake_all()`
- `scripts/check.sh` 已验证 `timer initialized`、`timer tick=1/2/3`、`scheduler initialized`、`kernel thread selftest ok`、timer 驱动线程轮转、`sched_sleep()` 和 wait queue wakeup。
后续扩展:
- 把 IRQ 分发扩展为可注册 handler 的表,而不是只处理 timer。
- 把当前直接在 timer IRQ 内触发调度的路径收敛为更明确的 interrupt-exit reschedule 模型。
- 建立基础 spinlock 或 interrupt-safe lock。
- 为 wait queue 增加条件等待、超时等待和状态检查。
- 为线程退出增加资源回收路径。
下一阶段:
- 继续在 `04-time-scheduler.md` 内推进 interrupt-safe lock、线程退出回收和更严格的 interrupt-exit reschedule。