From b62bf9515e3fb2742256539f9de8076855889baa Mon Sep 17 00:00:00 2001
From: Quant-TheodoreFelix
<53819958+Quant-TheodoreFelix@users.noreply.github.com>
Date: Fri, 13 Nov 2026 05:32:24 +0900
Subject: [PATCH 1/2] Add serial console input and an operator terminal
- Kernel receive path for PL011 and SBSA UART behind `console-input`, with the logic in a new host tested crate `k0-conin`
- `CONSOLE_READ` with one waiter, timeouts and rights on the `Console` capability
- Console interrupt number from the device tree or SPCR, shown in the platform line
- Vault gets an operator role, `INIT` only delivers the seed and `KEYGEN` makes the key
- New crate `k0-term` and a service stage in the root task behind `terminal`
- `tools/term-test.py`, judge mode in the boot test and new matrix rows
---
Cargo.lock | 13 +
Cargo.toml | 3 +
crates/k0-abi/src/lib.rs | 61 ++-
crates/k0-abi/src/tests.rs | 18 +-
crates/k0-arch/Cargo.toml | 4 +
crates/k0-arch/src/conin.rs | 205 +++++++++
crates/k0-arch/src/earlycon.rs | 6 +-
crates/k0-arch/src/earlycon/uart.rs | 11 +-
crates/k0-arch/src/irq.rs | 333 ++++++++++++++-
crates/k0-arch/src/lib.rs | 2 +
crates/k0-boot/Cargo.toml | 4 +
crates/k0-boot/build.rs | 4 +
crates/k0-boot/src/platform.rs | 76 +++-
crates/k0-boot/src/platform/tests.rs | 85 +++-
crates/k0-boot/src/testing.rs | 1 +
crates/k0-cap/Cargo.toml | 5 +
crates/k0-cap/src/lib.rs | 44 +-
crates/k0-cap/src/tests.rs | 73 +++-
crates/k0-conin/Cargo.toml | 8 +
crates/k0-conin/src/lib.rs | 345 +++++++++++++++
crates/k0-conin/src/tests.rs | 601 +++++++++++++++++++++++++++
crates/k0-efi/src/acpi.rs | 15 +-
crates/k0-efi/src/synth.rs | 8 +
crates/k0-efi/src/tests.rs | 48 ++-
crates/k0-ipc/Cargo.toml | 3 +
crates/k0-ipc/src/console.rs | 232 +++++++++++
crates/k0-ipc/src/lib.rs | 18 +-
crates/k0-task/Cargo.toml | 2 +
crates/k0-task/src/lib.rs | 4 +
kernel/Cargo.toml | 7 +
kernel/src/main.rs | 75 +++-
kernel/src/syscall.rs | 97 ++++-
tools/boot-matrix.sh | 102 +++++
tools/host-test.sh | 5 +-
tools/qemu-boot-test.sh | 68 ++-
tools/term-test.py | 328 +++++++++++++++
userspace/k0-term/Cargo.toml | 14 +
userspace/k0-term/src/lib.rs | 550 ++++++++++++++++++++++++
userspace/k0-term/src/tests.rs | 563 +++++++++++++++++++++++++
userspace/k0-term/src/wire.rs | 148 +++++++
userspace/k0-vault/src/proto.rs | 192 ++++++++-
userspace/k0-vault/src/server.rs | 128 +++++-
userspace/k0-vault/src/tests.rs | 373 ++++++++++++++---
userspace/root-task/Cargo.toml | 10 +-
userspace/root-task/src/main.rs | 237 ++++++++++-
userspace/root-task/src/oracle.rs | 175 +++++---
userspace/root-task/src/service.rs | 398 ++++++++++++++++++
47 files changed, 5464 insertions(+), 238 deletions(-)
create mode 100644 crates/k0-arch/src/conin.rs
create mode 100644 crates/k0-conin/Cargo.toml
create mode 100644 crates/k0-conin/src/lib.rs
create mode 100644 crates/k0-conin/src/tests.rs
create mode 100644 crates/k0-ipc/src/console.rs
create mode 100755 tools/term-test.py
create mode 100644 userspace/k0-term/Cargo.toml
create mode 100644 userspace/k0-term/src/lib.rs
create mode 100644 userspace/k0-term/src/tests.rs
create mode 100644 userspace/k0-term/src/wire.rs
create mode 100644 userspace/root-task/src/service.rs
diff --git a/Cargo.lock b/Cargo.lock
index ad657a8..3d65e9b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -120,6 +120,7 @@ name = "k0-arch"
version = "0.1.0"
dependencies = [
"k0-abi",
+ "k0-conin",
]
[[package]]
@@ -133,6 +134,10 @@ dependencies = [
name = "k0-cap"
version = "0.1.0"
+[[package]]
+name = "k0-conin"
+version = "0.1.0"
+
[[package]]
name = "k0-efi"
version = "0.1.0"
@@ -202,6 +207,13 @@ dependencies = [
"k0-mm",
]
+[[package]]
+name = "k0-term"
+version = "0.1.0"
+dependencies = [
+ "k0-vault",
+]
+
[[package]]
name = "k0-vault"
version = "0.1.0"
@@ -240,6 +252,7 @@ name = "root-task"
version = "0.1.0"
dependencies = [
"k0-abi",
+ "k0-term",
"k0-vault",
]
diff --git a/Cargo.toml b/Cargo.toml
index 4de7ed5..01efbac 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -11,8 +11,10 @@ members = [
"crates/k0-boot",
"crates/k0-abi",
"crates/k0-efi",
+ "crates/k0-conin",
"userspace/root-task",
"userspace/k0-vault",
+ "userspace/k0-term",
"loader",
]
# UEFI 로더는 타겟이 달라(aarch64-unknown-uefi) 기본 빌드 대상에서 뺌.
@@ -28,6 +30,7 @@ default-members = [
"crates/k0-boot",
"crates/k0-abi",
"crates/k0-efi",
+ "crates/k0-conin",
"userspace/root-task",
]
diff --git a/crates/k0-abi/src/lib.rs b/crates/k0-abi/src/lib.rs
index 3b2b87a..66050a9 100644
--- a/crates/k0-abi/src/lib.rs
+++ b/crates/k0-abi/src/lib.rs
@@ -34,9 +34,11 @@ pub const PA_CEILING: u64 = KERNEL_IMAGE_VA - KERNEL_VA_OFFSET;
pub mod syscall {
/// 바이트 하나를 커널 디버그 콘솔로 출력
///
- /// x0 = Console 슬롯, x1 = 바이트(하위 8비트만 사용). 출력 가능한
- /// ASCII(0x20-0x7E)와 개행만 그대로 나가고 그 외 바이트(터미널 제어
- /// 문자 등)는 `?`로 바뀝니다. 성공 시 x0 = 0, 실패 시 음수 에러
+ /// x0 = Console 슬롯(쓰기 권한 W 필요), x1 = 바이트(하위 8비트만 사용).
+ /// 출력 가능한 ASCII(0x20-0x7E)와 개행만 그대로 나가고 그 외 바이트(터미널
+ /// 제어 문자 등)는 `?`로 바뀝니다. `console-input`으로 빌드한 이미지에서
+ /// 읽기 권한 R도 있는 케이퍼빌리티로 부르면 백스페이스(0x08)가 그대로
+ /// 나갑니다(입력한 글자를 지우는 데 필요). 성공 시 x0 = 0, 실패 시 음수 에러
pub const DEBUG_PUTC: u64 = 0;
/// 스케줄러 양보(준비된 다른 태스크가 없으면 즉시 복귀)
pub const YIELD: u64 = 1;
@@ -104,8 +106,8 @@ pub mod syscall {
///
/// x0 = 원본 슬롯, x1 = 목적지 CNode를 가리키는 CNode 슬롯, x2 = 그
/// CNode 안의 빈 목적지 슬롯, x3 = 남길 권한 비트([super::rights]),
- /// x4 = 배지(0 = 붙이지 않음). 권한은 줄일 수만 있고 Frame / Endpoint에만
- /// 적용됩니다. 배지는 배지가 없는 Endpoint에만 붙일 수 있습니다. 복사본은
+ /// x4 = 배지(0 = 붙이지 않음). 권한은 줄일 수만 있고 Frame / Endpoint /
+ /// Console에만 적용됩니다. 배지는 배지가 없는 Endpoint에만 붙일 수 있습니다. 복사본은
/// 원본의 자식이라 원본을 회수하거나 삭제하면 함께 사라집니다. Untyped와
/// PageTable은 복사할 수 없습니다. 성공 시 x0 = 0
pub const CAP_COPY: u64 = 12;
@@ -125,6 +127,34 @@ pub mod syscall {
/// x0 = 슬롯. untyped를 회수하면 거기서 잘라낸 오브젝트가 전부 종료되고
/// 메모리를 다시 재분류할 수 있습니다. 성공 시 x0 = 0
pub const CAP_REVOKE: u64 = 15;
+ /// 콘솔 입력에서 바이트 하나를 읽음(커널을 `console-input`으로 빌드한
+ /// 이미지에만 있음)
+ ///
+ /// x0 = Console 슬롯(읽기 권한 R 필요), x1 = 플래그([super::console]).
+ /// 받아 둔 바이트가 없으면 올 때까지 블록됩니다. 한 번에 한 태스크만
+ /// 기다릴 수 있습니다. 성공 시 x0 = 0, x1 = 바이트, x2 = 이 바이트 바로
+ /// 앞에서 입력이 유실됐으면 [super::console::LOST], 아니면 0. 커널은
+ /// 바이트를 해석하지 않습니다. 기다리는 동안 그 케이퍼빌리티를 잃으면
+ /// REVOKED로 깨어납니다
+ pub const CONSOLE_READ: u64 = 16;
+}
+
+/// CONSOLE_READ의 플래그(x1)와 결과(x2) 모듈입니다.
+pub mod console {
+ /// 받아 둔 바이트가 없으면 블록 대신 WOULD_BLOCK으로 즉시 복귀
+ pub const NONBLOCK: u64 = 1;
+ /// 읽기 전에, 지금까지 받아 둔 입력과 유실 표시를 전부 버림
+ ///
+ /// 프롬프트를 내기 전에 들어온 입력이 명령으로 읽히지 않게 하는 데
+ /// 씁니다. 버리는 양은 커널의 버퍼와 장치의 FIFO 크기로 묶여 있습니다
+ pub const FLUSH: u64 = 2;
+ /// 플래그 레지스터에서 뜻이 정해지지 않은 비트. 하나라도 서 있으면
+ /// BAD_FLAGS로 거부됩니다. 상위 32비트는 IPC와 같은 형식의 타임아웃입니다
+ /// ([super::ipc::TIMEOUT_SHIFT])
+ pub const RESERVED: u64 = 0xFFFF_FFFC;
+ /// 결과(x2): 이 바이트 바로 앞에서 입력이 유실됨(장치의 FIFO가 넘쳤거나
+ /// 오류가 난 문자를 버렸음)
+ pub const LOST: u64 = 1;
}
/// IPC 플래그(x1) 모듈입니다.
@@ -185,9 +215,9 @@ pub mod perm {
/// 케이퍼빌리티 권한 비트 모듈입니다. (CAP_COPY의 x3)
pub mod rights {
- /// Frame: 읽기 매핑, Endpoint: 수신
+ /// Frame: 읽기 매핑, Endpoint: 수신, Console: 입력 읽기
pub const R: u64 = 1;
- /// Frame: 쓰기 매핑, Endpoint: 송신
+ /// Frame: 쓰기 매핑, Endpoint: 송신, Console: 출력
pub const W: u64 = 2;
/// Frame: 실행 매핑
pub const X: u64 = 4;
@@ -231,7 +261,8 @@ pub mod err {
pub const NO_REPLY: i64 = -15;
/// 케이퍼빌리티에 이 연산에 필요한 권한 비트가 없음
pub const NO_RIGHTS: i64 = -16;
- /// 대기하던 엔드포인트가 종료됨
+ /// 대기하던 엔드포인트가 종료됨. 콘솔 입력을 기다리던 중이라면 그
+ /// Console 케이퍼빌리티를 잃었음
pub const REVOKED: i64 = -17;
/// 배지를 붙일 수 없는 케이퍼빌리티이거나 이미 다른 배지가 있음
pub const BAD_BADGE: i64 = -18;
@@ -245,6 +276,10 @@ pub mod err {
pub const REPLY_TIMEOUT: i64 = -21;
/// IPC 플래그 레지스터에 뜻이 정해지지 않은 비트가 서 있음
pub const BAD_FLAGS: i64 = -22;
+ /// 다른 태스크가 이미 콘솔 입력을 기다리는 중임
+ pub const BUSY: i64 = -23;
+ /// 이 이미지나 이 기계에 콘솔 입력 경로가 없거나, 커널이 그 경로를 껐음
+ pub const NO_DEVICE: i64 = -24;
}
/// 커널이 루트 태스크에 RO로 매핑해 주는 bootinfo 페이지 모듈입니다.
@@ -257,7 +292,10 @@ pub mod bootinfo {
/// bootinfo 페이지의 사용자 VA(양 플랫폼 그래뉼 정렬)
pub const VA: u64 = 0x0F00_0000;
/// 레이아웃 버전(불일치 시 루트 태스크는 진행하면 안 됨)
- pub const VERSION: u64 = 3;
+ ///
+ /// 버전 4부터 Console 케이퍼빌리티에 권한 비트가 있습니다(R = 입력 읽기,
+ /// W = 출력). 디스크립터의 `rights`가 그 값을 알립니다
+ pub const VERSION: u64 = 4;
/// 루트 태스크의 진입 레지스터 x4로 오는 시드 정보에서, 시드에 들어간
/// `rng-seed` 바이트 수를 담는 비트
@@ -301,8 +339,9 @@ pub mod bootinfo {
///
/// untyped는 `base` / `size`가 물리 구간입니다. 루트 태스크 이미지의
/// Frame은 `base`가 그 프레임이 루트 주소 공간에 매핑된 VA, `size`가
- /// 프레임 크기, `rights`가 권한 비트([super::rights])입니다. 나머지
- /// 종류는 전부 0입니다(커널 내부 주소 노출 최소화).
+ /// 프레임 크기, `rights`가 권한 비트([super::rights])입니다. Console은
+ /// `rights`만 채웁니다. 나머지 종류는 전부 0입니다(커널 내부 주소 노출
+ /// 최소화).
#[repr(C)]
pub struct CapDesc {
pub kind: u64,
diff --git a/crates/k0-abi/src/tests.rs b/crates/k0-abi/src/tests.rs
index 389192d..e6b6c81 100644
--- a/crates/k0-abi/src/tests.rs
+++ b/crates/k0-abi/src/tests.rs
@@ -29,6 +29,7 @@ fn syscall_numbers_are_unique_and_dense() {
syscall::CAP_MOVE,
syscall::CAP_DELETE,
syscall::CAP_REVOKE,
+ syscall::CONSOLE_READ,
];
assert_unique(&nrs.map(i128::from));
for (i, nr) in nrs.iter().enumerate() {
@@ -61,6 +62,8 @@ fn error_codes_are_unique_and_negative() {
err::TIMEOUT,
err::REPLY_TIMEOUT,
err::BAD_FLAGS,
+ err::BUSY,
+ err::NO_DEVICE,
];
assert_unique(&errs.map(i128::from));
for e in errs {
@@ -132,9 +135,22 @@ fn flag_register_bits_are_all_accounted_for() {
assert_eq!(ipc::NONBLOCK | ipc::RESERVED | ipc::timeout(u32::MAX), u64::MAX);
}
+#[test]
+fn console_read_flag_bits_are_all_accounted_for() {
+ assert_eq!(console::NONBLOCK & console::FLUSH, 0);
+ assert_eq!((console::NONBLOCK | console::FLUSH) & console::RESERVED, 0);
+ assert_eq!(
+ console::NONBLOCK | console::FLUSH | console::RESERVED | ipc::timeout(u32::MAX),
+ u64::MAX
+ );
+ // 블록하지 않는 읽기는 IPC와 같은 비트를 씀
+ assert_eq!(console::NONBLOCK, ipc::NONBLOCK);
+ assert_eq!(console::LOST, 1);
+}
+
#[test]
fn bootinfo_layout_is_stable() {
- assert_eq!(bootinfo::VERSION, 3);
+ assert_eq!(bootinfo::VERSION, 4);
assert_eq!(bootinfo::SEED_RNG_SEED_BYTES & bootinfo::SEED_RNDR, 0);
assert_eq!(size_of::(), 32);
assert_eq!(offset_of!(bootinfo::Header, version), 0);
diff --git a/crates/k0-arch/Cargo.toml b/crates/k0-arch/Cargo.toml
index e35d1ff..ba1c618 100644
--- a/crates/k0-arch/Cargo.toml
+++ b/crates/k0-arch/Cargo.toml
@@ -13,6 +13,10 @@ publish.workspace = true
console-pl011 = []
# 16550 계열. 읽기만으로 확인할 식별 레지스터가 없음
console-16550 = []
+# 콘솔 입력의 수신 경로(UART 수신 인터럽트와 그 SPI 하나). 수신 드라이버는
+# PL011과 SBSA UART에만 있어서 console-pl011과 함께 골라야 입력이 생김
+console-input = ["dep:k0-conin"]
[dependencies]
k0-abi = { path = "../k0-abi" }
+k0-conin = { path = "../k0-conin", optional = true }
diff --git a/crates/k0-arch/src/conin.rs b/crates/k0-arch/src/conin.rs
new file mode 100644
index 0000000..04de2ef
--- /dev/null
+++ b/crates/k0-arch/src/conin.rs
@@ -0,0 +1,205 @@
+//! 콘솔 입력의 커널 쪽 접착부 모듈입니다.
+//!
+//! # Features
+//! 수신 로직(링, 게이트, 유실 표시, 원인 없는 인터럽트의 차단)은 `k0-conin`
+//! 크레이트에 있고 호스트에서 가짜 UART로 시험됩니다. 이 모듈은 그 로직을 실제
+//! UART의 레지스터와 커널의 static 하나에 잇기만 합니다. feature
+//! `console-input`이 켜져 있을 때만 빌드되므로, 고르지 않은 이미지에는 UART에서
+//! 읽는 코드가 없습니다.
+//!
+//! 수신 드라이버는 PL011과 SBSA UART에만 있습니다(feature `console-pl011`).
+//! 16550 콘솔에서는 [prepare]가 false를 돌려주고 입력이 없습니다.
+//!
+//! 수신 상태는 인터럽트 핸들러와 시스템 콜 경로가 함께 씁니다. 단일 코어이고
+//! 모든 접근이 인터럽트를 마스크한 구간 안에서 이루어지므로 서로 겹치지
+//! 않습니다. 핸들러는 링에 바이트를 옮기기만 하고 스케줄러는 건드리지 않습니다.
+//! 기다리는 태스크를 깨우는 일은 커널이 자기 문맥에서 합니다.
+
+#[cfg(feature = "console-pl011")]
+mod pl011 {
+ use core::cell::UnsafeCell;
+ use core::sync::atomic::{AtomicBool, Ordering};
+
+ use k0_conin::{Irq, Reg, Regs, Rx};
+
+ use crate::earlycon::{mask_irqs, pl011_base, restore_irqs};
+
+ /// 매핑된 UART 레지스터에 닿는 통로입니다.
+ struct Mmio(usize);
+
+ impl Regs for Mmio {
+ fn read(&mut self, reg: Reg) -> u32 {
+ // SAFETY: prepare의 계약대로 매핑된 PL011 레지스터에 대한 volatile 접근
+ unsafe { core::ptr::read_volatile((self.0 + reg.offset()) as *const u32) }
+ }
+
+ fn write(&mut self, reg: Reg, value: u32) {
+ // SAFETY: prepare의 계약대로 매핑된 PL011 레지스터에 대한 volatile 접근
+ unsafe { core::ptr::write_volatile((self.0 + reg.offset()) as *mut u32, value) }
+ }
+ }
+
+ struct Cell(UnsafeCell);
+
+ // SAFETY: 단일 코어이고 모든 접근이 with 안에서 인터럽트를 마스크한 채
+ // 이루어지므로 동시에 두 곳에서 접근하지 않음
+ unsafe impl Sync for Cell {}
+
+ static RX: Cell = Cell(UnsafeCell::new(Rx::new(true)));
+ /// prepare가 끝나 수신 경로가 준비됐는지
+ static READY: AtomicBool = AtomicBool::new(false);
+
+ /// 인터럽트를 마스크한 채 수신 상태에 접근하는 함수입니다. 수신 경로가
+ /// 준비되지 않았으면 `None`입니다.
+ fn with(f: impl FnOnce(&mut Rx, &mut Mmio) -> R) -> Option {
+ if !READY.load(Ordering::Relaxed) {
+ return None;
+ }
+ let base = pl011_base()?;
+ let daif = mask_irqs();
+ // SAFETY: 인터럽트가 마스크된 단일 코어 구간이라 이 가변 참조는 유일함.
+ // 핸들러 안에서 불려도 그 핸들러가 끊은 코드는 이 구간 밖에 있음
+ let r = f(unsafe { &mut *RX.0.get() }, &mut Mmio(base));
+ restore_irqs(daif);
+ Some(r)
+ }
+
+ pub unsafe fn prepare(has_cr: bool) -> bool {
+ let Some(base) = pl011_base() else {
+ return false;
+ };
+ let daif = mask_irqs();
+ // SAFETY: 인터럽트가 마스크된 단일 코어 구간이고, 아직 READY가 아니라
+ // 다른 경로는 이 상태에 접근하지 않음
+ unsafe { *RX.0.get() = Rx::new(has_cr) };
+ Rx::quiesce(&mut Mmio(base));
+ READY.store(true, Ordering::Relaxed);
+ restore_irqs(daif);
+ true
+ }
+
+ pub fn available() -> bool {
+ with(|rx, _| !rx.is_off()).unwrap_or(false)
+ }
+
+ pub fn open() {
+ with(|rx, regs| rx.open(regs));
+ }
+
+ pub fn pop() -> Option<(u8, bool)> {
+ with(|rx, regs| rx.pop(regs)).flatten()
+ }
+
+ pub fn flush() {
+ with(|rx, regs| rx.flush(regs));
+ }
+
+ pub fn poll() {
+ with(|rx, regs| rx.poll(regs));
+ }
+
+ pub fn has_data() -> bool {
+ with(|rx, _| rx.has_data()).unwrap_or(false)
+ }
+
+ pub fn shut() {
+ with(|rx, regs| rx.turn_off(regs));
+ }
+
+ pub(crate) fn interrupt() -> Irq {
+ with(|rx, regs| rx.interrupt(regs)).unwrap_or(Irq::Spurious)
+ }
+}
+
+/// 수신 드라이버가 없는 빌드(16550만 고른 커널)에서 자리를 채우는 모듈입니다.
+/// 이 빌드에는 UART에서 읽는 코드가 없습니다.
+#[cfg(not(feature = "console-pl011"))]
+mod pl011 {
+ pub unsafe fn prepare(_has_cr: bool) -> bool {
+ false
+ }
+
+ pub fn available() -> bool {
+ false
+ }
+
+ pub fn open() {}
+
+ pub fn pop() -> Option<(u8, bool)> {
+ None
+ }
+
+ pub fn flush() {}
+
+ pub fn poll() {}
+
+ pub fn has_data() -> bool {
+ false
+ }
+
+ pub fn shut() {}
+
+ pub(crate) fn interrupt() -> k0_conin::Irq {
+ k0_conin::Irq::Spurious
+ }
+}
+
+/// 붙어 있는 콘솔에 수신 경로를 준비하는 함수입니다. UART의 인터럽트를 전부
+/// 막아 두기만 하고 켜지는 않습니다(켜는 것은 [open]).
+///
+/// 인터럽트 컨트롤러에서 콘솔의 선을 켜기 전에 불러야 합니다. 수신 드라이버가
+/// 없는 UART면 false를 돌려줍니다.
+///
+/// # Arguments
+/// `has_cr` - 제어 레지스터가 있는 UART(PL011)면 true, SBSA UART면 false
+///
+/// # Safety
+/// 콘솔이 [crate::earlycon::attach]로 붙어 있어야 하고, 그 레지스터 프레임에서
+/// 수신 로직이 쓰는 범위(오프셋 0x48 미만)가 Device로 매핑돼 있어야 합니다.
+pub unsafe fn prepare(has_cr: bool) -> bool {
+ // SAFETY: 함수 계약을 그대로 전달
+ unsafe { pl011::prepare(has_cr) }
+}
+
+/// 입력 경로가 있고 꺼지지 않았는지 알려 주는 함수입니다.
+pub fn available() -> bool {
+ pl011::available()
+}
+
+/// 입력을 쓰기 시작하는 함수입니다. 그동안 장치에 쌓인 바이트를 버리고 수신
+/// 인터럽트를 켭니다. 이미 열린 경로에는 아무 일도 하지 않습니다.
+pub fn open() {
+ pl011::open();
+}
+
+/// 받아 둔 바이트 하나를 꺼내는 함수입니다. 둘째 값은 이 바이트 바로 앞에서
+/// 입력이 유실됐는지입니다.
+pub fn pop() -> Option<(u8, bool)> {
+ pl011::pop()
+}
+
+/// 받아 둔 입력과 유실 표시를 전부 버리는 함수입니다.
+pub fn flush() {
+ pl011::flush();
+}
+
+/// 인터럽트 없이 장치의 FIFO를 들여다보는 함수입니다. 틱마다, 그리고 읽는
+/// 태스크가 잠들기 직전에 부릅니다.
+pub fn poll() {
+ pl011::poll();
+}
+
+/// 꺼낼 바이트가 있는지 알려 주는 함수입니다.
+pub fn has_data() -> bool {
+ pl011::has_data()
+}
+
+/// 입력 경로를 끄는 함수입니다. 되돌리지 않습니다.
+pub fn shut() {
+ pl011::shut();
+}
+
+/// 콘솔 인터럽트 하나를 처리하는 함수입니다.
+pub(crate) fn interrupt() -> k0_conin::Irq {
+ pl011::interrupt()
+}
diff --git a/crates/k0-arch/src/earlycon.rs b/crates/k0-arch/src/earlycon.rs
index 74d1119..87f7a6b 100644
--- a/crates/k0-arch/src/earlycon.rs
+++ b/crates/k0-arch/src/earlycon.rs
@@ -38,6 +38,8 @@ pub use uart::{Uart, attach, attached};
#[cfg(any(feature = "console-pl011", feature = "console-16550"))]
use uart::hw_put;
+#[cfg(all(feature = "console-pl011", feature = "console-input"))]
+pub(crate) use uart::pl011_base;
/// 드라이버가 하나도 없는 빌드에서 UART 송신 자리를 채우는 함수입니다.
/// 아무것도 하지 않으며, 이 빌드에는 UART에 접근하는 코드가 없습니다.
@@ -123,14 +125,14 @@ fn log_push(b: u8, user: bool) {
restore_irqs(daif);
}
-fn mask_irqs() -> u64 {
+pub(crate) fn mask_irqs() -> u64 {
let daif: u64;
// SAFETY: DAIF를 읽고 전부 마스크함, 호출자가 restore_irqs로 되돌림
unsafe { asm!("mrs {}, daif", "msr daifset, #0xf", out(reg) daif, options(nostack)) };
daif
}
-fn restore_irqs(daif: u64) {
+pub(crate) fn restore_irqs(daif: u64) {
// SAFETY: mask_irqs가 읽어 둔 값을 그대로 복원함
unsafe { asm!("msr daif, {}", in(reg) daif, options(nostack)) };
}
diff --git a/crates/k0-arch/src/earlycon/uart.rs b/crates/k0-arch/src/earlycon/uart.rs
index e74340f..13c8e48 100644
--- a/crates/k0-arch/src/earlycon/uart.rs
+++ b/crates/k0-arch/src/earlycon/uart.rs
@@ -1,7 +1,9 @@
//! 콘솔 UART 송신 드라이버 모듈입니다.
//!
//! # Features
-//! 커널이 기계 밖으로 출력을 내보내는 유일한 경로입니다. 송신만 합니다.
+//! 커널이 기계 밖으로 출력을 내보내는 유일한 경로입니다. 송신만 합니다(수신은
+//! feature `console-input`을 고른 빌드에서 [crate::conin]이 같은 레지스터
+//! 프레임으로 따로 합니다).
//! 초기화 쓰기와 보율 설정은 하지 않고 부트로더가 켜 둔 상태를 그대로 씁니다.
//! 송신 가능 대기에는 시간 상한이 있어서, 응답 없는 UART가 인터럽트를 막은 채
//! 커널을 붙잡지 못합니다.
@@ -188,6 +190,13 @@ pub unsafe fn attach(uart: Uart, base: usize, counter_hz: u64) {
}
}
+/// 붙어 있는 콘솔이 PL011(또는 SBSA UART)이면 그 레지스터 0의 주소를 주는
+/// 함수입니다. 수신 경로가 같은 레지스터 프레임을 씁니다.
+#[cfg(all(feature = "console-pl011", feature = "console-input"))]
+pub(crate) fn pl011_base() -> Option {
+ (KIND.load(Ordering::Relaxed) == KIND_PL011).then(|| BASE.load(Ordering::Relaxed))
+}
+
/// 콘솔이 붙어 있는지 알려 주는 함수입니다.
pub fn attached() -> bool {
KIND.load(Ordering::Relaxed) != KIND_NONE
diff --git a/crates/k0-arch/src/irq.rs b/crates/k0-arch/src/irq.rs
index 2567ed7..e49befc 100644
--- a/crates/k0-arch/src/irq.rs
+++ b/crates/k0-arch/src/irq.rs
@@ -9,6 +9,10 @@
//! 정리한 뒤, 타이머 PPI 하나만 켭니다. 가상 타이머를 쓰는 이유는 하이퍼바이저
//! 게스트에서도 항상 쓸 수 있는 타이머가 그것뿐이기 때문입니다.
//!
+//! feature `console-input`을 고른 빌드에서는 콘솔 UART의 SPI 하나를 더 받을 수
+//! 있습니다([enable_console_irq]). 그 번호는 DTB가 알려 준 것이라 틀릴 수 있고,
+//! 틀린 번호가 선을 붙들면 수신 로직이 몇 번 만에 그 선을 끕니다([crate::conin]).
+//!
//! 설계상 발생할 수 없는 FIQ와 미지의 `INTID`는 fail-secure로 정지합니다.
//!
//! 틱 주기는 1초입니다. 틱은 선점 신호이면서 IPC 타임아웃의 단위이고, EL0가
@@ -62,6 +66,15 @@ pub enum IrqError {
NoFrequency,
/// 타이머의 INTID가 PPI 범위(16..=31) 밖
BadIntid,
+ /// 콘솔 인터럽트 번호가 이 컨트롤러의 SPI 범위 밖임
+ #[cfg(feature = "console-input")]
+ SpiOutOfRange,
+ /// 콘솔의 SPI를 레벨 트리거로 둘 수 없음
+ #[cfg(feature = "console-input")]
+ SpiNotLevel,
+ /// 콘솔의 SPI가 이 보안 상태의 것이 아님(켜기 비트가 서지 않음)
+ #[cfg(feature = "console-input")]
+ SpiNotOwned,
}
const KIND_NONE: u8 = 0;
@@ -74,6 +87,18 @@ static GICC: AtomicUsize = AtomicUsize::new(0);
static TIMER_INTID: AtomicU32 = AtomicU32::new(0);
static TIMER_HZ: AtomicU64 = AtomicU64::new(0);
static TICKS: AtomicU64 = AtomicU64::new(0);
+/// 디스트리뷰터 레지스터의 가상 주소(콘솔의 SPI를 켜고 끄는 데 씀)
+#[cfg(feature = "console-input")]
+static GICD: AtomicUsize = AtomicUsize::new(0);
+/// 이 컨트롤러가 구현한 INTID의 수(1020을 넘지 않게 묶음)
+#[cfg(feature = "console-input")]
+static INTID_LIMIT: AtomicU32 = AtomicU32::new(0);
+/// 콘솔의 INTID. 켠 적이 없으면 어떤 INTID와도 같지 않은 값
+#[cfg(feature = "console-input")]
+static CONSOLE_INTID: AtomicU32 = AtomicU32::new(u32::MAX);
+/// 주기적인 틱 줄을 멈췄는지
+#[cfg(feature = "console-input")]
+static QUIET_TICKS: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
/// 로그에 남기는 틱 줄의 수. 이후의 틱은 콘솔에만 찍음
const LOGGED_TICKS: u64 = 4;
@@ -137,10 +162,33 @@ pub mod gicv3 {
use super::*;
const GICD_CTLR: usize = 0x0000;
- const GICD_TYPER: usize = 0x0004;
+ pub(super) const GICD_TYPER: usize = 0x0004;
+ #[cfg(feature = "console-input")]
+ const GICD_IGROUPR: usize = 0x0080;
+ #[cfg(feature = "console-input")]
+ const GICD_ISENABLER: usize = 0x0100;
const GICD_ICENABLER: usize = 0x0180;
const GICD_ICPENDR: usize = 0x0280;
const GICD_ICACTIVER: usize = 0x0380;
+ #[cfg(feature = "console-input")]
+ const GICD_IPRIORITYR: usize = 0x0400;
+ #[cfg(feature = "console-input")]
+ const GICD_ICFGR: usize = 0x0C00;
+ #[cfg(feature = "console-input")]
+ const GICD_IGRPMODR: usize = 0x0D00;
+ #[cfg(feature = "console-input")]
+ const GICD_IROUTER: u64 = 0x6000;
+
+ /// SPI의 라우팅 레지스터(GICD_IROUTER)가 디스트리뷰터 프레임 안에서 놓이는
+ /// 위치를 주는 함수입니다. 초기화에 쓰는 첫 페이지 밖에 있어서, 콘솔의
+ /// SPI를 켜려면 호출자가 그 페이지를 따로 매핑해야 합니다.
+ ///
+ /// # Arguments
+ /// `intid` - SPI의 INTID
+ #[cfg(feature = "console-input")]
+ pub const fn router_offset(intid: u32) -> u64 {
+ GICD_IROUTER + 8 * intid as u64
+ }
/// 식별 레지스터 PIDR2가 프레임 안에서 놓이는 위치
pub const PIDR2: u64 = 0xFFE8;
pub const GICR_TYPER: u64 = 0x0008;
@@ -379,6 +427,59 @@ pub mod gicv3 {
Ok(())
}
+ /// SPI 하나를 이 코어로 오게 구성하고 켜는 함수입니다.
+ ///
+ /// 비보안 Group 1, 타이머와 같은 우선순위, 레벨 트리거로 두고 이 코어의
+ /// 어피니티로 보냅니다. 보안 상태가 소유한 SPI는 비보안에서 쓰기가
+ /// 무시되므로 켜기 비트를 읽어 보아 가립니다.
+ ///
+ /// # Safety
+ /// `dist`는 [init]이 초기화를 마친 디스트리뷰터 프레임의 매핑된 주소,
+ /// `router`는 이 SPI의 라우팅 레지스터([router_offset])가 매핑된 주소여야
+ /// 하고, `intid`는 이 컨트롤러가 구현한 SPI여야 합니다.
+ #[cfg(feature = "console-input")]
+ pub(super) unsafe fn enable_spi(dist: usize, router: usize, intid: u32) -> Result<(), IrqError> {
+ let n = intid as usize;
+ let (word, bit) = (4 * (n / 32), 1u32 << (n % 32));
+ let mpidr: u64;
+ // SAFETY: MPIDR_EL1 읽기는 부작용이 없음
+ unsafe { asm!("mrs {}, mpidr_el1", out(reg) mpidr, options(nomem, nostack)) };
+ // GICD_IROUTER의 어피니티 배치는 MPIDR과 같음(Aff3이 비트 39..32). 비트
+ // 31(아무 코어로나 보내기)은 0으로 둠
+ let route = mpidr & 0xFF_00FF_FFFF;
+ // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근
+ unsafe {
+ write32(dist + GICD_IGROUPR + word, read32(dist + GICD_IGROUPR + word) | bit);
+ write32(dist + GICD_IGRPMODR + word, read32(dist + GICD_IGRPMODR + word) & !bit);
+ write8(dist + GICD_IPRIORITYR + n, PRIORITY as u8);
+ // 설정은 꺼진 동안에만 바꿀 수 있음. init이 SPI를 전부 꺼 두었음
+ let cfg = dist + GICD_ICFGR + 4 * (n / 16);
+ let cfg_bit = 1u32 << (2 * (n % 16) + 1);
+ write32(cfg, read32(cfg) & !cfg_bit);
+ if read32(cfg) & cfg_bit != 0 {
+ return Err(IrqError::SpiNotLevel);
+ }
+ core::ptr::write_volatile(router as *mut u64, route);
+ write32(dist + GICD_ISENABLER + word, bit);
+ wait_clear(dist + GICD_CTLR, CTLR_RWP, IrqError::GicRwpTimeout)?;
+ if read32(dist + GICD_ISENABLER + word) & bit == 0 {
+ return Err(IrqError::SpiNotOwned);
+ }
+ }
+ Ok(())
+ }
+
+ /// SPI 하나를 끄는 함수입니다.
+ ///
+ /// # Safety
+ /// [enable_spi]와 같습니다.
+ #[cfg(feature = "console-input")]
+ pub(super) unsafe fn disable_spi(dist: usize, intid: u32) {
+ let n = intid as usize;
+ // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근
+ unsafe { write32(dist + GICD_ICENABLER + 4 * (n / 32), 1u32 << (n % 32)) };
+ }
+
pub(super) fn ack() -> u64 {
let iar: u64;
// SAFETY: ICC_IAR1_EL1 읽기는 최고 우선순위 대기 인터럽트를 승인함
@@ -397,13 +498,15 @@ pub mod gicv2 {
use super::*;
const GICD_CTLR: usize = 0x000;
- const GICD_TYPER: usize = 0x004;
+ pub(super) const GICD_TYPER: usize = 0x004;
const GICD_IGROUPR: usize = 0x080;
const GICD_ISENABLER: usize = 0x100;
const GICD_ICENABLER: usize = 0x180;
const GICD_ICPENDR: usize = 0x280;
const GICD_ICACTIVER: usize = 0x380;
const GICD_IPRIORITYR: usize = 0x400;
+ #[cfg(feature = "console-input")]
+ const GICD_ITARGETSR: usize = 0x800;
const GICD_ICFGR: usize = 0xC00;
const GICD_PIDR2: usize = 0xFE8;
const GICC_CTLR: usize = 0x00;
@@ -481,6 +584,55 @@ pub mod gicv2 {
}
Ok(())
}
+
+ /// SPI 하나를 이 코어로 오게 구성하고 켜는 함수입니다.
+ ///
+ /// # Safety
+ /// `dist`는 [init]이 초기화를 마친 디스트리뷰터 프레임의 매핑된 주소여야
+ /// 하고, `intid`는 이 컨트롤러가 구현한 SPI여야 합니다.
+ #[cfg(feature = "console-input")]
+ pub(super) unsafe fn enable_spi(dist: usize, intid: u32) -> Result<(), IrqError> {
+ let n = intid as usize;
+ let (word, bit) = (4 * (n / 32), 1u32 << (n % 32));
+ // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근
+ unsafe {
+ // 타이머와 같은 그룹에 둠. 보안 확장이 있으면 이 레지스터는
+ // 비보안에서 읽기 0 / 쓰기 무시임
+ if read32(dist + GICD_TYPER) & (1 << 10) == 0 {
+ write32(dist + GICD_IGROUPR + word, read32(dist + GICD_IGROUPR + word) & !bit);
+ }
+ write8(dist + GICD_IPRIORITYR + n, PRIORITY as u8);
+ let cfg = dist + GICD_ICFGR + 4 * (n / 16);
+ let cfg_bit = 1u32 << (2 * (n % 16) + 1);
+ write32(cfg, read32(cfg) & !cfg_bit);
+ if read32(cfg) & cfg_bit != 0 {
+ return Err(IrqError::SpiNotLevel);
+ }
+ // 이 CPU 인터페이스의 마스크는 ITARGETSR0의 첫 바이트로 읽힘. CPU가
+ // 하나뿐인 구현에서는 이 레지스터가 읽기 0 / 쓰기 무시이고 모든
+ // 인터럽트가 그 CPU로 가므로, 0이면 쓰지 않음
+ let me = read32(dist + GICD_ITARGETSR) & 0xFF;
+ if me != 0 {
+ write8(dist + GICD_ITARGETSR + n, me as u8);
+ }
+ write32(dist + GICD_ISENABLER + word, bit);
+ if read32(dist + GICD_ISENABLER + word) & bit == 0 {
+ return Err(IrqError::SpiNotOwned);
+ }
+ }
+ Ok(())
+ }
+
+ /// SPI 하나를 끄는 함수입니다.
+ ///
+ /// # Safety
+ /// [enable_spi]와 같습니다.
+ #[cfg(feature = "console-input")]
+ pub(super) unsafe fn disable_spi(dist: usize, intid: u32) {
+ let n = intid as usize;
+ // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근
+ unsafe { write32(dist + GICD_ICENABLER + 4 * (n / 32), 1u32 << (n % 32)) };
+ }
}
/// 초기화할 인터럽트 컨트롤러와 그 레지스터의 가상 주소입니다.
@@ -524,8 +676,20 @@ fn timer_arm(interval: u64) {
fn timer_tick() {
let n = TICKS.load(Ordering::Relaxed) + 1;
TICKS.store(n, Ordering::Relaxed);
+ // 수신 인터럽트가 오지 않는 UART(수신 타임아웃이 없거나 번호가 조용히
+ // 틀린 경우)에서도 입력이 늦게나마 도착하게 틱마다 한 번 들여다봄. 닫혀
+ // 있는 동안에는 아무 일도 하지 않음
+ #[cfg(feature = "console-input")]
+ crate::conin::poll();
+ // 태스크가 콘솔 입력을 쓰기 시작한 뒤에는 틱 줄을 내지 않음(입력하는 줄
+ // 사이에 끼어들지 않게). 틱과 타임아웃은 그대로 동작함
+ #[cfg(feature = "console-input")]
+ let quiet = QUIET_TICKS.load(Ordering::Relaxed);
+ #[cfg(not(feature = "console-input"))]
+ let quiet = false;
// 틱은 끝없이 이어지므로 처음 몇 줄만 로그에 남김
- if n <= LOGGED_TICKS {
+ if quiet {
+ } else if n <= LOGGED_TICKS {
let _ = writeln!(EarlyCon, "k0: tick {n}");
} else {
// 콘솔 드라이버가 없는 빌드에는 쓸 곳이 없으므로 서식 작업도 하지 않음
@@ -543,6 +707,100 @@ pub fn ticks() -> u64 {
TICKS.load(Ordering::Relaxed)
}
+/// 주기적인 틱 줄을 멈추는 함수입니다. 처음 불렸으면 true를 돌려줍니다.
+///
+/// 태스크가 콘솔 입력을 쓰기 시작할 때 커널이 부릅니다. 틱 자체와 IPC
+/// 타임아웃은 그대로 동작합니다.
+#[cfg(feature = "console-input")]
+pub fn quiet_ticks() -> bool {
+ !QUIET_TICKS.swap(true, Ordering::Relaxed)
+}
+
+/// 콘솔 UART의 SPI를 이 코어로 오게 구성하고 켜는 함수입니다.
+///
+/// UART 쪽의 인터럽트는 [crate::conin::prepare]가 먼저 전부 막아 두었어야
+/// 합니다. 그래야 여기서 선을 켜도 태스크가 입력을 쓰기 전까지는 인터럽트가
+/// 오지 않습니다.
+///
+/// # Arguments
+/// `_irq` - 컨트롤러가 초기화됐음을 증명하는 토큰
+/// `intid` - DTB가 알려 준 콘솔의 INTID
+/// `router` - GICv3에서 이 SPI의 라우팅 레지스터([gicv3::router_offset])가
+/// 매핑된 주소. GICv2에서는 쓰지 않음
+///
+/// # Safety
+/// [init]에 넘긴 디스트리뷰터의 매핑이 그대로 살아 있어야 하고, GICv3라면
+/// `router`가 Device로 매핑된 그 레지스터의 주소여야 합니다.
+///
+/// # Errors
+/// 번호가 이 컨트롤러의 SPI가 아니거나 타이머의 번호이면 `SpiOutOfRange`,
+/// 레벨 트리거로 둘 수 없으면 `SpiNotLevel`, 켜기 비트가 서지 않으면
+/// `SpiNotOwned`. 어느 경우든 잃는 것은 콘솔 입력뿐이고 부팅은 계속됩니다
+#[cfg(feature = "console-input")]
+pub unsafe fn enable_console_irq(_irq: &Irq, intid: u32, router: Option) -> Result<(), IrqError> {
+ let limit = INTID_LIMIT.load(Ordering::Relaxed);
+ if !(32..limit).contains(&intid) || intid == TIMER_INTID.load(Ordering::Relaxed) {
+ return Err(IrqError::SpiOutOfRange);
+ }
+ let dist = GICD.load(Ordering::Relaxed);
+ // 켜자마자 인터럽트가 올 수 있으므로 분배기가 알아볼 번호를 먼저 적어 둠
+ CONSOLE_INTID.store(intid, Ordering::Relaxed);
+ // SAFETY: 함수 계약대로 매핑된 디스트리뷰터이고 번호는 위에서 확인한 SPI임
+ let r = unsafe {
+ match KIND.load(Ordering::Relaxed) {
+ KIND_V3 => match router {
+ Some(router) => gicv3::enable_spi(dist, router, intid),
+ None => Err(IrqError::ProbeFailed),
+ },
+ KIND_V2 => gicv2::enable_spi(dist, intid),
+ _ => Err(IrqError::WrongGic),
+ }
+ };
+ if r.is_err() {
+ // 반쯤 구성된 선은 꺼 둠. 번호는 그대로 두어, 이미 전달돼 있던
+ // 인터럽트가 "미지의 INTID"로 커널을 멈추지 않게 함
+ // SAFETY: 위와 같음
+ unsafe { disable_console_irq() };
+ }
+ r
+}
+
+/// 콘솔의 SPI를 끄는 함수입니다.
+///
+/// # Safety
+/// [enable_console_irq]와 같습니다.
+#[cfg(feature = "console-input")]
+unsafe fn disable_console_irq() {
+ let (dist, intid) = (GICD.load(Ordering::Relaxed), CONSOLE_INTID.load(Ordering::Relaxed));
+ if intid == u32::MAX {
+ return;
+ }
+ // SAFETY: 함수 계약을 그대로 전달
+ unsafe {
+ match KIND.load(Ordering::Relaxed) {
+ KIND_V3 => gicv3::disable_spi(dist, intid),
+ KIND_V2 => gicv2::disable_spi(dist, intid),
+ _ => {}
+ }
+ }
+}
+
+/// 콘솔 인터럽트 하나를 처리하는 함수입니다.
+///
+/// 수신 로직이 원인 없는 인터럽트가 이어진다고 판단하면(DTB가 다른 장치의
+/// 번호를 준 경우) 컨트롤러에서 그 선을 끄고 한 줄을 남깁니다. 커널은 계속
+/// 실행되고 입력만 없어집니다.
+#[cfg(feature = "console-input")]
+fn console_irq() {
+ if crate::conin::interrupt() == k0_conin::Irq::CutOff {
+ // SAFETY: 이 인터럽트가 왔다는 것은 enable_console_irq가 선을 켰다는
+ // 뜻이고, 그 계약대로 디스트리뷰터가 매핑돼 있음
+ unsafe { disable_console_irq() };
+ let intid = CONSOLE_INTID.load(Ordering::Relaxed);
+ let _ = writeln!(EarlyCon, "k0: console input off (interrupt {intid} fired without a uart cause)");
+ }
+}
+
/// 실행할 태스크가 없을 때 다음 인터럽트까지 코어를 재우고 그 인터럽트를
/// 처리하는 함수입니다.
///
@@ -596,12 +854,16 @@ pub unsafe fn init(_vectors: &Vectors, gic: &Gic, intid: u32, hz: u64) -> Result
Gic::V3(frames) => unsafe {
gicv3::init(frames, intid)?;
KIND.store(KIND_V3, Ordering::Relaxed);
+ #[cfg(feature = "console-input")]
+ remember_distributor(frames.dist, read32(frames.dist + gicv3::GICD_TYPER));
},
// SAFETY: 함수 계약을 그대로 전달
Gic::V2 { dist, cpu } => unsafe {
gicv2::init(*dist, *cpu, intid)?;
GICC.store(*cpu, Ordering::Relaxed);
KIND.store(KIND_V2, Ordering::Relaxed);
+ #[cfg(feature = "console-input")]
+ remember_distributor(*dist, read32(*dist + gicv2::GICD_TYPER));
},
}
TIMER_INTID.store(intid, Ordering::Relaxed);
@@ -614,6 +876,15 @@ pub unsafe fn init(_vectors: &Vectors, gic: &Gic, intid: u32, hz: u64) -> Result
Ok(Irq { _sealed: () })
}
+/// 콘솔의 SPI를 켤 때 쓸 디스트리뷰터 주소와 INTID의 상한을 적어 두는
+/// 함수입니다. 상한은 GICD_TYPER의 ITLinesNumber에서 나오고, 1020부터는 특수
+/// 번호라 넘지 않게 묶습니다.
+#[cfg(feature = "console-input")]
+fn remember_distributor(dist: usize, typer: u32) {
+ GICD.store(dist, Ordering::Relaxed);
+ INTID_LIMIT.store((32 * ((typer & 0x1F) + 1)).min(1020), Ordering::Relaxed);
+}
+
/// 설계상 발생할 수 없는 인터럽트를 fail-secure로 정지시키는 함수입니다.
///
/// # Arguments
@@ -637,13 +908,32 @@ unsafe extern "C" {
/// EL0에서 진입한 IRQ/FIQ 컨텍스트에서 벡터가 사용자 컨텍스트 저장을
/// 마친 뒤에만 호출됩니다.
fn k0_preempt();
+
+ /// 콘솔 입력이 도착했을 때 기다리는 태스크를 깨우는 정책, 커널 바이너리가
+ /// 정의함 (링크 계약)
+ ///
+ /// # Safety
+ /// [k0_preempt]와 같습니다.
+ #[cfg(feature = "console-input")]
+ fn k0_console_event();
}
+/// 분배 결과: 타이머 틱이었음(EL0 경로의 선점 판단용)
+const EV_TICK: u8 = 1;
+/// 분배 결과: 콘솔 인터럽트였음(기다리는 태스크를 깨울지 커널이 판단)
+#[cfg(feature = "console-input")]
+const EV_CONSOLE: u8 = 2;
+
/// EL1과 EL0 양쪽 IRQ 벡터가 공유하는 실제 분배 함수입니다.
///
-/// 타이머 틱이었으면 true를 반환합니다(EL0 경로의 선점 판단용).
-fn dispatch_irq() -> bool {
+/// 무슨 인터럽트였는지를 `EV_` 비트로 돌려줍니다. 콘솔 인터럽트의 가지는 그
+/// 선을 끈 뒤에도 남겨 둡니다. 끄기 전에 이미 CPU로 전달돼 있던 인터럽트가
+/// 미지의 INTID로 취급되어 커널을 멈추면 안 되기 때문입니다(그때의 수신
+/// 로직은 레지스터를 건드리지 않고 돌아옴).
+fn dispatch_irq() -> u8 {
let timer = u64::from(TIMER_INTID.load(Ordering::Relaxed));
+ #[cfg(feature = "console-input")]
+ let console = u64::from(CONSOLE_INTID.load(Ordering::Relaxed));
match KIND.load(Ordering::Relaxed) {
KIND_V3 => {
let iar = gicv3::ack();
@@ -651,9 +941,15 @@ fn dispatch_irq() -> bool {
id if id == timer => {
timer_tick();
gicv3::eoi(iar);
- true
+ EV_TICK
}
- 1020..=1023 => false, // 스퓨리어스: 승인 없이 복귀
+ #[cfg(feature = "console-input")]
+ id if id == console => {
+ console_irq();
+ gicv3::eoi(iar);
+ EV_CONSOLE
+ }
+ 1020..=1023 => 0, // 스퓨리어스: 승인 없이 복귀
other => unexpected("irq", other),
}
}
@@ -666,9 +962,16 @@ fn dispatch_irq() -> bool {
timer_tick();
// SAFETY: 승인에서 받은 값 그대로 완료 통지
unsafe { write32(cpu + gicv2::GICC_EOIR, iar) };
- true
+ EV_TICK
}
- 1020..=1023 => false,
+ #[cfg(feature = "console-input")]
+ id if id == console => {
+ console_irq();
+ // SAFETY: 승인에서 받은 값 그대로 완료 통지
+ unsafe { write32(cpu + gicv2::GICC_EOIR, iar) };
+ EV_CONSOLE
+ }
+ 1020..=1023 => 0,
other => unexpected("irq", other),
}
}
@@ -680,7 +983,7 @@ fn dispatch_irq() -> bool {
///
/// 커널은 모든 인터럽트를 IRQ로만 받으므로 FIQ는 설계상 없고, 들어오면
/// fail-secure로 정지합니다.
-fn dispatch_fiq() -> bool {
+fn dispatch_fiq() -> u8 {
unexpected("fiq", 0)
}
@@ -705,7 +1008,13 @@ extern "C" fn fiq_current() {
/// 복원하며 수행합니다.
#[unsafe(no_mangle)]
extern "C" fn irq_lower(_ctx: &mut crate::usermode::Context) {
- if dispatch_irq() {
+ let events = dispatch_irq();
+ #[cfg(feature = "console-input")]
+ if events & EV_CONSOLE != 0 {
+ // SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 IRQ 경로임
+ unsafe { k0_console_event() };
+ }
+ if events & EV_TICK != 0 {
// SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 IRQ 경로임
unsafe { k0_preempt() };
}
@@ -714,7 +1023,7 @@ extern "C" fn irq_lower(_ctx: &mut crate::usermode::Context) {
/// 사용자 공간(EL0) 실행 중 FIQ 벡터가 사용하는 디스패처 함수입니다.
#[unsafe(no_mangle)]
extern "C" fn fiq_lower(_ctx: &mut crate::usermode::Context) {
- if dispatch_fiq() {
+ if dispatch_fiq() & EV_TICK != 0 {
// SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 FIQ 경로임
unsafe { k0_preempt() };
}
diff --git a/crates/k0-arch/src/lib.rs b/crates/k0-arch/src/lib.rs
index 52d44b9..a87afeb 100644
--- a/crates/k0-arch/src/lib.rs
+++ b/crates/k0-arch/src/lib.rs
@@ -7,6 +7,8 @@
#![no_std]
+#[cfg(feature = "console-input")]
+pub mod conin;
pub mod earlycon;
pub mod hardening;
pub mod irq;
diff --git a/crates/k0-boot/Cargo.toml b/crates/k0-boot/Cargo.toml
index 49853ec..73b1087 100644
--- a/crates/k0-boot/Cargo.toml
+++ b/crates/k0-boot/Cargo.toml
@@ -13,6 +13,10 @@ roottask = []
# 보고 루트 태스크의 빌드에 같은 이름의 feature를 넘김
vault = ["roottask"]
vault-ed25519 = ["vault"]
+# 콘솔 입력: 루트 태스크의 자가 검증에 입력 시스템 콜의 시험을 넣음
+console-input = ["roottask"]
+# 운영자 터미널: 자가 검증 뒤에 서비스(볼트가 있으면 볼트와 터미널)를 시작함
+terminal = ["console-input"]
# 테스트용 DTB 빌더와 퍼즈 도우미를 다른 크레이트의 테스트에 공개함(std 필요)
test-support = []
diff --git a/crates/k0-boot/build.rs b/crates/k0-boot/build.rs
index d19ed2f..8e12e32 100644
--- a/crates/k0-boot/build.rs
+++ b/crates/k0-boot/build.rs
@@ -152,6 +152,8 @@ fn main() {
for (var, name) in [
("CARGO_FEATURE_VAULT", "vault"),
("CARGO_FEATURE_VAULT_ED25519", "vault-ed25519"),
+ ("CARGO_FEATURE_CONSOLE_INPUT", "console-input"),
+ ("CARGO_FEATURE_TERMINAL", "terminal"),
] {
if env::var_os(var).is_some() {
features.push(name);
@@ -252,6 +254,8 @@ fn main() {
"userspace/root-task/src",
"userspace/k0-vault/src",
"userspace/k0-vault/Cargo.toml",
+ "userspace/k0-term/src",
+ "userspace/k0-term/Cargo.toml",
"Cargo.lock",
"userspace/root-task/Cargo.toml",
"userspace/root-task/build.rs",
diff --git a/crates/k0-boot/src/platform.rs b/crates/k0-boot/src/platform.rs
index f64f06f..037de83 100644
--- a/crates/k0-boot/src/platform.rs
+++ b/crates/k0-boot/src/platform.rs
@@ -65,6 +65,10 @@ pub struct Console {
pub span: u64,
/// DTB가 선언한 레지스터 구간 전체 (겹침 검사용)
pub reg: Region,
+ /// 콘솔의 인터럽트 번호(INTID). 노드에 없거나, 발견한 인터럽트 컨트롤러의
+ /// SPI 하나로 읽히지 않으면 `None`이고 그때는 콘솔 입력이 없습니다.
+ /// 인터럽트를 못 읽는 것은 부팅 거부 사유가 아닙니다.
+ pub irq: Option,
}
/// 인터럽트 컨트롤러를 나타내는 열거형입니다.
@@ -240,12 +244,13 @@ pub fn discover_blob(blob: &[u8]) -> Result {
return Err(DiscoverError::DuplicatePhandle);
}
let (intc, interrupt_cells) = intc.ok_or(DiscoverError::IntcNotFound)??;
+ let timer_parent = timer.parent;
let timer = Timer {
intid: timer_intid(&timer, interrupt_cells)?,
clock_hz: timer.clock.unwrap_or(0),
};
- let (console, no_console) = match find_console(&fdt, stdout)? {
+ let (console, no_console) = match find_console(&fdt, stdout, Some((timer_parent, interrupt_cells)))? {
Ok(c) => (Some(c), None),
Err(why) => (None, Some(why)),
};
@@ -531,7 +536,15 @@ fn read_intc(levels: &Levels<'_>, node: &Node<'_>, depth: usize) -> Result<(Intc
///
/// 콘솔을 못 찾는 경우는 전부 안쪽 `Err(NoConsole)`이고, 바깥 `Err`는 DTB
/// 구조 위반뿐입니다.
-fn find_console(fdt: &Fdt<'_>, stdout: Option<&[u8]>) -> Result, BootError> {
+///
+/// `gic`는 발견한 인터럽트 컨트롤러의 phandle과 `#interrupt-cells`입니다. 주면
+/// 콘솔의 인터럽트도 읽고, `None`이면(컨트롤러를 찾기 전의 조기 콘솔 탐색)
+/// 인터럽트 없이 돌려줍니다.
+fn find_console(
+ fdt: &Fdt<'_>,
+ stdout: Option<&[u8]>,
+ gic: Option<(u32, u32)>,
+) -> Result, BootError> {
let Some(value) = stdout else {
return Ok(Err(NoConsole::NoStdoutPath));
};
@@ -569,7 +582,10 @@ fn find_console(fdt: &Fdt<'_>, stdout: Option<&[u8]>) -> Result, stdout: Option<&[u8]>) -> Result, node: &Node<'_>, depth: usize, gic: u32, cells: u32) -> Option {
+ if node.has(P::InterruptsExtended) {
+ return None;
+ }
+ let spec = node.get(P::Interrupts)?;
+ let mut parent = node.u32(P::InterruptParent).ok()?;
+ let mut k = depth;
+ while parent.is_none() && k > 1 {
+ k -= 1;
+ if levels[k].has_interrupt_cells {
+ return None;
+ }
+ parent = levels[k].interrupt_parent().ok()?;
+ }
+ if parent? != gic || cells != 3 || spec.len() != 12 {
+ return None;
+ }
+ let cell = |i: usize| read_cells(&spec[i * 4..i * 4 + 4]);
+ // SPI 번호의 상한 987은 INTID 1019(1020부터는 특수 번호)
+ if cell(0) != 0 || cell(1) > 987 || cell(2) != 4 {
+ return None;
+ }
+ Some(32 + cell(1) as u32)
+}
+
fn read_console(levels: &Levels<'_>, node: &Node<'_>, depth: usize) -> Result {
if !usable(levels, node, depth) {
return Err(NoConsole::Disabled);
@@ -651,6 +700,7 @@ fn read_console(levels: &Levels<'_>, node: &Node<'_>, depth: usize) -> Result Option {
Ok(Flow::Continue)
})
.ok()?;
- find_console(&fdt, stdout).ok()?.ok()
+ find_console(&fdt, stdout, None).ok()?.ok()
}
impl fmt::Display for Platform {
@@ -808,13 +858,19 @@ impl fmt::Display for Platform {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.console {
None => write!(f, "con=none")?,
- Some(c) => match c.kind {
- ConsoleKind::Pl011 => write!(f, "con=pl011@{:#x}", c.base)?,
- ConsoleKind::SbsaUart => write!(f, "con=sbsa@{:#x}", c.base)?,
- ConsoleKind::Ns16550 { reg_shift, io_width } => {
- write!(f, "con=ns16550@{:#x},s{reg_shift},w{io_width}", c.base)?;
+ Some(c) => {
+ match c.kind {
+ ConsoleKind::Pl011 => write!(f, "con=pl011@{:#x}", c.base)?,
+ ConsoleKind::SbsaUart => write!(f, "con=sbsa@{:#x}", c.base)?,
+ ConsoleKind::Ns16550 { reg_shift, io_width } => {
+ write!(f, "con=ns16550@{:#x},s{reg_shift},w{io_width}", c.base)?;
+ }
}
- },
+ // 커널이 켜는 인터럽트이므로 플랫폼 줄(고정 모드의 대조 대상)에 넣음
+ if let Some(irq) = c.irq {
+ write!(f, ",irq{irq}")?;
+ }
+ }
}
match &self.intc {
Intc::GicV2 { dist, cpu } => write!(f, " gic=v2@{:#x} cpu={:#x}", dist.base, cpu.base)?,
diff --git a/crates/k0-boot/src/platform/tests.rs b/crates/k0-boot/src/platform/tests.rs
index 6c7c5fc..89d42f4 100644
--- a/crates/k0-boot/src/platform/tests.rs
+++ b/crates/k0-boot/src/platform/tests.rs
@@ -36,6 +36,7 @@ fn qemu_virt_gicv3_is_discovered() {
base: 0x900_0000,
span: 0x1C,
reg: Region { base: 0x900_0000, size: 0x1000 },
+ irq: Some(33),
}),
intc: Intc::GicV3 {
dist: Region { base: 0x800_0000, size: 0x1_0000 },
@@ -48,7 +49,7 @@ fn qemu_virt_gicv3_is_discovered() {
);
assert_eq!(
d.platform.to_string(),
- "con=pl011@0x9000000 gic=v3@0x8000000 rd=0x80a0000+0xf60000 tmr=27"
+ "con=pl011@0x9000000,irq33 gic=v3@0x8000000 rd=0x80a0000+0xf60000 tmr=27"
);
}
@@ -65,7 +66,7 @@ fn qemu_virt_gicv2_is_discovered() {
assert_eq!(d.platform.timer.intid, 27);
assert_eq!(
d.platform.to_string(),
- "con=pl011@0x9000000 gic=v2@0x8000000 cpu=0x8010000 tmr=27"
+ "con=pl011@0x9000000,irq33 gic=v2@0x8000000 cpu=0x8010000 tmr=27"
);
}
@@ -79,6 +80,7 @@ fn raspberry_pi_4_shape_is_translated_through_soc_ranges() {
base: 0xfe21_5040,
span: 24,
reg: Region { base: 0xfe21_5040, size: 0x40 },
+ irq: None,
})
);
assert_eq!(
@@ -104,12 +106,89 @@ fn rk3399_shape_uses_four_cell_specifiers_and_a_shifted_uart() {
base: 0xff1a_0000,
span: 24,
reg: Region { base: 0xff1a_0000, size: 0x100 },
+ irq: None,
})
);
assert_eq!(d.platform.intc.redist(), &[Region { base: 0xfef0_0000, size: 0xc_0000 }]);
assert_eq!(d.platform.timer.intid, 27);
}
+#[test]
+fn the_console_interrupt_is_one_level_high_spi_of_the_discovered_controller() {
+ let irq = |t: &N| ok(t).platform.console.unwrap().irq;
+ assert_eq!(irq(&virt3()), Some(33));
+ assert_eq!(irq(&virt2()), Some(33));
+
+ // 가장 큰 SPI 번호는 INTID 1019
+ let mut t = virt3();
+ t.kid("pl011@9000000").set("interrupts", cells(&[0, 987, 4]));
+ assert_eq!(irq(&t), Some(1019));
+ assert!(ok(&t).platform.to_string().starts_with("con=pl011@0x9000000,irq1019 "));
+
+ // 받지 않는 모양은 전부 "인터럽트 없음"이고 부팅 거부가 아님
+ let bad: [&[u32]; 9] = [
+ &[0, 988, 4], // 특수 INTID에 닿는 번호
+ &[1, 1, 4], // PPI
+ &[2, 1, 4], // 모르는 종류
+ &[0, 1, 1], // 에지 트리거
+ &[0, 1, 8], // 액티브 로우
+ &[0, 1, 0x104], // 플래그에 다른 비트
+ &[0, 1], // 셀이 모자람
+ &[0, 1, 4, 0], // 셀이 남음
+ &[0, 1, 4, 0, 2, 4], // 항목이 둘
+ ];
+ for spec in bad {
+ let mut t = virt3();
+ t.kid("pl011@9000000").set("interrupts", cells(spec));
+ let d = ok(&t);
+ assert_eq!(d.platform.console.unwrap().irq, None, "{spec:?}");
+ assert!(d.platform.to_string().starts_with("con=pl011@0x9000000 gic="), "{spec:?}");
+ }
+
+ // 속성이 없는 콘솔, interrupts-extended를 쓰는 콘솔
+ let mut t = virt3();
+ t.kid("pl011@9000000").del("interrupts");
+ assert_eq!(irq(&t), None);
+ let mut t = virt3();
+ t.kid("pl011@9000000").set("interrupts-extended", cells(&[GIC_PHANDLE, 0, 1, 4]));
+ assert_eq!(irq(&t), None);
+
+ // 인터럽트 부모가 발견한 컨트롤러가 아니면 읽지 않음
+ let mut t = virt3();
+ t.kid("pl011@9000000").set("interrupt-parent", cells(&[GIC_PHANDLE + 1]));
+ assert_eq!(irq(&t), None);
+ // 노드 자신의 interrupt-parent가 그 컨트롤러면 읽음
+ let mut t = virt3();
+ t.kid("pl011@9000000").set("interrupt-parent", cells(&[GIC_PHANDLE]));
+ assert_eq!(irq(&t), Some(33));
+}
+
+#[test]
+fn a_controller_with_four_cell_specifiers_gives_no_console_interrupt() {
+ // rk3399 모양: 컨트롤러의 #interrupt-cells가 4라서 셀 셋짜리 지정자를
+ // 추측해 읽지 않음
+ let mut t = rk3399();
+ let d = ok(&t);
+ assert_eq!(d.platform.console.unwrap().irq, None);
+ // 지정자를 넷으로 맞춰 줘도 받지 않음(받는 모양은 셀 셋뿐)
+ fn uart(n: &mut N) -> Option<&mut N> {
+ if n.name.starts_with("serial@") {
+ return Some(n);
+ }
+ n.kids.iter_mut().find_map(uart)
+ }
+ if let Some(u) = uart(&mut t) {
+ u.set("interrupts", cells(&[0, 100, 4, 0]));
+ }
+ assert_eq!(ok(&t).platform.console.unwrap().irq, None);
+}
+
+#[test]
+fn early_console_discovery_does_not_read_the_interrupt() {
+ // 컨트롤러를 찾기 전의 조기 탐색은 출력만 쓰므로 인터럽트를 읽지 않음
+ assert_eq!(console_of(&virt3().blob()).unwrap().irq, None);
+}
+
#[test]
fn the_virtual_timer_number_comes_from_the_tree() {
// Qualcomm sdm845: <1 1>, <1 2>, <1 3>, <1 0>
@@ -217,7 +296,7 @@ fn console_nodes_are_checked_before_use() {
let mut t = virt3();
t.kid("pl011@9000000").set("compatible", strs(&["arm,sbsa-uart"]));
assert_eq!(ok(&t).platform.console.map(|c| c.kind), Some(ConsoleKind::SbsaUart));
- assert!(ok(&t).platform.to_string().starts_with("con=sbsa@0x9000000 "));
+ assert!(ok(&t).platform.to_string().starts_with("con=sbsa@0x9000000,irq33 "));
}
#[test]
diff --git a/crates/k0-boot/src/testing.rs b/crates/k0-boot/src/testing.rs
index 7a7da70..3c8be64 100644
--- a/crates/k0-boot/src/testing.rs
+++ b/crates/k0-boot/src/testing.rs
@@ -237,6 +237,7 @@ pub fn pl011() -> N {
N::new("pl011@9000000")
.p("compatible", strs(&["arm,pl011", "arm,primecell"]))
.p("reg", cells(&[0, 0x900_0000, 0, 0x1000]))
+ .p("interrupts", cells(&[0, 1, 4]))
}
pub fn gicv3() -> N {
diff --git a/crates/k0-cap/Cargo.toml b/crates/k0-cap/Cargo.toml
index b200c33..06d36e7 100644
--- a/crates/k0-cap/Cargo.toml
+++ b/crates/k0-cap/Cargo.toml
@@ -5,4 +5,9 @@ edition.workspace = true
license.workspace = true
publish.workspace = true
+# 루트 CNode를 1024슬롯으로 만듦. 자가 검증 뒤에 서비스를 새로 띄우는 이미지
+# (터미널)가 켬. 주지 않으면 512슬롯 그대로임
+[features]
+root-cnode-1024 = []
+
[dependencies]
diff --git a/crates/k0-cap/src/lib.rs b/crates/k0-cap/src/lib.rs
index f808044..237e471 100644
--- a/crates/k0-cap/src/lib.rs
+++ b/crates/k0-cap/src/lib.rs
@@ -38,7 +38,14 @@ use core::ptr;
pub const SLOT_SIZE: usize = 64;
/// 루트 CNode의 슬롯 수
+///
+/// 자가 검증 뒤에 서비스(볼트와 터미널)를 새로 띄우는 이미지는 주소 공간 둘을
+/// 더 만들 슬롯이 필요하므로 feature `root-cnode-1024`로 두 배를 받습니다.
+/// 그 밖의 이미지는 그대로입니다.
+#[cfg(not(feature = "root-cnode-1024"))]
pub const ROOT_CNODE_SLOTS: usize = 512;
+#[cfg(feature = "root-cnode-1024")]
+pub const ROOT_CNODE_SLOTS: usize = 1024;
/// 파생 깊이 상한, 초과하는 복사는 거부됩니다
pub const MAX_DEPTH: u64 = 1 << 32;
@@ -46,7 +53,8 @@ pub const MAX_DEPTH: u64 = 1 << 32;
/// 케이퍼빌리티 권한 비트 모듈입니다.
///
/// Frame은 R/W/X를 매핑 권한의 상한으로 쓰고, Endpoint는 R을 수신, W를
-/// 송신으로 씁니다. 다른 종류는 권한 비트를 갖지 않습니다.
+/// 송신으로, Console은 R을 입력 읽기, W를 출력으로 씁니다. 다른 종류는 권한
+/// 비트를 갖지 않습니다.
pub mod rights {
pub const R: u8 = 1;
pub const W: u8 = 2;
@@ -123,8 +131,9 @@ pub enum Cap {
CNode { base: u64, slots: u64 },
/// 사용자 주소 공간(TTBR0 루트 테이블)
AddrSpace { root_pa: u64, asid: u64 },
- /// 커널 디버그 콘솔 출력 권한(오브젝트 없음)
- Console,
+ /// 커널 콘솔에 대한 권한(오브젝트 없음), `rights`의 W가 출력이고 R이
+ /// 입력 읽기
+ Console { rights: u8 },
}
/// 재분류로 만들 수 있는 커널 오브젝트 종류를 나타내는 열거형입니다.
@@ -270,7 +279,7 @@ fn encode(cap: &Cap) -> [u64; 4] {
],
Cap::CNode { base, slots } => [base | KIND_CNODE, *slots, 0, 0],
Cap::AddrSpace { root_pa, asid } => [root_pa | KIND_ADDR_SPACE, *asid, 0, 0],
- Cap::Console => [KIND_CONSOLE, 0, 0, 0],
+ Cap::Console { rights } => [KIND_CONSOLE | (u64::from(*rights) << RIGHTS_SHIFT), 0, 0, 0],
}
}
@@ -387,11 +396,11 @@ fn decode(w: &[u64; 4]) -> Result
-**In scope**: everything under `kernel/`, `crates/` (including `crates/k0-efi`), `loader/`, `userspace/root-task/` and `userspace/k0-vault` with its wiring in the root task. The UEFI loader is part of the boot chain, but it is code of this repository, so its handling of the memory map, the device tree and the kernel image is in scope.
+**In scope**: everything under `kernel/`, `crates/` (including `crates/k0-efi`), `loader/`, `userspace/root-task/` and `userspace/k0-vault` and `userspace/k0-term` with their wiring in the root task. The UEFI loader is part of the boot chain, but it is code of this repository, so its handling of the memory map, the device tree and the kernel image is in scope.
**Out of scope**: the rest of the boot chain before the kernel entry point (for example firmware, any other boot loader and the hypervisor), and the integrity of the kernel image itself. Kernel image signing is the boot chain's responsibility. Under UEFI that means Secure Boot in the firmware, because the loader's SHA-256 check is not a signature (see "The UEFI loader").
diff --git a/SECURITY_KR.md b/SECURITY_KR.md
index 84ff69f..29a5b96 100644
--- a/SECURITY_KR.md
+++ b/SECURITY_KR.md
@@ -47,7 +47,7 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다.
### 현재 `main` 브랜치(릴리즈 전)
-현재 `main` 브랜치에는 태스크 격리가 들어 있습니다. 아직 어떤 릴리즈나 태그에도 포함되지 않았고, 시스템 콜 ABI가 `v0.1.0`과 호환되지 않습니다(bootinfo 레이아웃 버전 3).
+현재 `main` 브랜치에는 태스크 격리가 들어 있습니다. 아직 어떤 릴리즈나 태그에도 포함되지 않았고, 시스템 콜 ABI가 `v0.1.0`과 호환되지 않습니다(bootinfo 레이아웃 버전 4).
격리된 태스크의 성질은 다음과 같습니다.
@@ -55,7 +55,7 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다.
- **주소 공간**: 태스크는 `AddrSpace` 케이퍼빌리티가 가리키는 주소 공간에서 실행됩니다. 태스크는 그 `AddrSpace` 케이퍼빌리티를 가진 쪽이 해당 주소 공간에 매핑해 준 메모리에만 접근합니다.
- **바인딩**: 두 바인딩은 모두 태스크의 TCB 안에 케이퍼빌리티로 보관됩니다. 둘 중 하나가 revoke되거나 삭제되면 그 태스크는 해체됩니다.
- **격리의 범위**: 격리는 서로 다른 CNode와 주소 공간에 묶인 태스크 사이에서 성립합니다. 루트 태스크의 보조 스레드처럼 같은 것을 함께 사용하는 태스크끼리는 서로의 스레드입니다. 태스크의 TCB, CNode, AddrSpace 케이퍼빌리티를 가진 쪽이 그 태스크를 통제합니다.
-- **권한**: 케이퍼빌리티는 권한(R, W, X)을 가집니다. 권한은 `CAP_COPY`로 줄이기만 할 수 있고 늘릴 수는 없습니다. `Endpoint` 케이퍼빌리티는 `CAP_COPY`로 한 번 설정하는 배지를 가질 수 있고, 수신자가 이 배지를 받습니다. retype된 프레임은 X를 얻을 수 없고 X는 루트 태스크의 text 프레임에만 있으므로, 어떤 물리 프레임도 한 곳에서 쓰기 가능하면서 다른 곳에서 실행 가능하지 않습니다.
+- **권한**: 케이퍼빌리티는 권한(R, W, X)을 가집니다. 권한은 `CAP_COPY`로 줄이기만 할 수 있고 늘릴 수는 없습니다. `Endpoint` 케이퍼빌리티는 `CAP_COPY`로 한 번 설정하는 배지를 가질 수 있고, 수신자가 이 배지를 받습니다. `Console` 케이퍼빌리티도 같은 방식으로 R(입력 읽기)과 W(출력 쓰기) 권한을 가집니다. retype된 프레임은 X를 얻을 수 없고 X는 루트 태스크의 text 프레임에만 있으므로, 어떤 물리 프레임도 한 곳에서 쓰기 가능하면서 다른 곳에서 실행 가능하지 않습니다.
- **파생과 해체**: 케이퍼빌리티는 파생 목록을 이룹니다. `CAP_REVOKE`는 파생된 모든 케이퍼빌리티를 제거하고, `CAP_DELETE`는 슬롯까지 제거합니다. 오브젝트는 원본 케이퍼빌리티가 제거될 때 finalize되며, 그 뒤 해당 `Untyped` 메모리를 다시 retype할 수 있습니다. retype된 오브젝트는 케이퍼빌리티가 만들어지기 전에 0으로 지워집니다.
- **폴트 격리**: 격리된 태스크의 폴트, 종료, 알 수 없는 시스템 콜은 그 태스크만 종료시킵니다.
@@ -71,15 +71,16 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다.
- **미구현 기능**: 핸들러 태스크로의 폴트 전달, 알림(notification), IPC를 통한 케이퍼빌리티 전송이 아직 없습니다.
- **EL0에서 보이는 시간**: EL0는 여전히 하드웨어 카운터나 타이머를 읽을 수 없습니다. IPC 타임아웃은 태스크에 스케줄러 틱(1초)만큼 거친 시계와 타이머 인터럽트에 맞춰진 깨어남을 제공합니다. 이것이 캐시나 추측 실행 공격에 쓸 만한 시간 원천으로 증폭될 수 있는지는 분석하지 않았습니다.
- **revoke 뒤의 송신자**: 엔드포인트에 이미 대기 중인 송신자는 케이퍼빌리티가 revoke된 뒤에도 한 번 전달됩니다.
+- **직렬 회선**: feature `console-input` 또는 `terminal`을 포함해 빌드한 이미지에서는 외부 당사자가 직렬 회선으로 커널에 닿을 수 있습니다. 운영자 터미널에는 인증이 없고, 외부 당사자가 태스크 실행 중에 인터럽트를 일으킬 수 있으며, 입력은 실행 중인 태스크 뒤에서 기다립니다("직렬 입력과 운영자 터미널" 참고).
- **코어 수**: 단일 코어만 지원합니다.
- **실행 코드**: 부팅 후에는 새 실행 코드를 로드할 수 없으므로, 격리된 태스크는 루트 태스크 이미지의 코드를 실행합니다.
- **지원 범위**: [INTRODUCTION_KR.md](INTRODUCTION_KR.md)의 증거 단계에 든 것만 지원한다고 봅니다. 실제 보드, KVM 등 다른 하이퍼바이저, 16550 콘솔 드라이버, `HCR_EL2.E2H`가 1로 고정된 프로세서는 한 번도 부팅한 적이 없습니다.
- **디바이스 트리**: 디바이스 트리는 신뢰하지 않지만, 이제 장치 주소를 여기서 가져옵니다. 잘못되었거나 악의적인 디바이스 트리가 콘솔을 다른 장치로 향하게 할 수 있습니다. 커널은 이를 다음과 같이 제한합니다. 플랫폼 기술자를 메모리 맵과 대조합니다. GIC와 PL011의 식별 레지스터를 확인합니다(PL011은 임시 프로브 매핑으로 확인하므로 확인에 실패한 장치는 매핑된 채 남지 않습니다. 16550과 SBSA UART에는 그런 레지스터가 없어서 이 확인이 없습니다). 검증이 끝난 뒤에만 장치 페이지를 매핑합니다. 콘솔 대기는 모두 시간 제한으로 묶습니다. 다른 플랫폼을 거부하는 고정 빌드(`K0_PIN`)도 제공합니다. 고정 빌드는 디바이스 트리에서 나온 값을 비교하므로 악의적인 부트 체인은 막지 못합니다.
- **디바이스 트리의 주소**: 디바이스 트리의 주소는 처음 읽기 전에 검사할 방법이 없습니다. 부트로더가 이 주소를 `x0`로 넘기는데, 커널은 그 블롭을 읽기 전에는 메모리 맵을 모릅니다. 커널은 널이거나 정렬이 맞지 않는 주소, 2^47 이상인 주소, 커널 이미지와 겹치는 구간을 거부합니다. 그런 다음 그 주소를 읽기 전용 일반 메모리로 매핑하고 8바이트를 읽습니다. 그 바이트가 디바이스 트리 헤더처럼 보일 때만 더 읽습니다(최대 2 MiB). 따라서 부트로더가 장치의 주소를 넘기면 커널은 장치 레지스터를 메모리처럼 읽게 되고, 일부 레지스터는 읽기만 해도 부작용이 생깁니다. 이 매핑은 캐시 가능한 메모리라서 프로세서가 커널이 요청한 8바이트보다 그 페이지를 더 많이 가져올 수 있습니다. 디바이스 트리가 선언된 메모리 안에 있는지 보는 나중의 검사는 같은 블롭에서 나온 메모리 맵을 사용합니다. 이 매핑으로 쓰기를 하는 것은 단 한 번뿐이며, 블롭을 파싱하고 검증한 뒤에 일어납니다. 커널은 루트 태스크에 진입하기 직전에 `rng-seed`와 `kaslr-seed` 값을 0으로 지웁니다("서명 오라클" 절의 "부트 시드와 시드 삭제" 참고). 두 번째 `/chosen` 노드는 거부합니다.
-- **출력의 출처**: 커널 출력과 태스크 출력은 부트 로그 하나를 함께 사용합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔 하나도 함께 사용합니다. 줄에는 누가 썼는지 표시가 없습니다. `Console` 케이퍼빌리티를 가진 태스크는 `k0:`로 시작하는 줄을 출력할 수 있습니다. 커널은 제어 바이트를 바꾸고 태스크 출력이 부트 로그에서 차지할 수 있는 양을 제한합니다. 그래도 콘솔이나 로그를 읽는 쪽은 `tools/qemu-boot-test.sh`를 포함해 누구도 `k0: entering root task (el0)` 뒤에 나온 `k0:` 줄을 커널이 쓴 것으로 믿을 수 없습니다. `k0: console drivers [...]` 줄도 여기에 포함됩니다("선택적 콘솔 출력" 참고).
+- **출력의 출처**: 커널 출력과 태스크 출력은 부트 로그 하나를 함께 사용합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔 하나도 함께 사용합니다. 줄에는 누가 썼는지 표시가 없습니다. 쓰기 권한이 있는 `Console` 케이퍼빌리티를 가진 태스크는 `k0:`로 시작하는 줄을 출력할 수 있습니다. 커널은 제어 바이트를 바꾸고 태스크 출력이 부트 로그에서 차지할 수 있는 양을 제한합니다. 그래도 콘솔이나 로그를 읽는 쪽은 `tools/qemu-boot-test.sh`를 포함해 누구도 `k0: entering root task (el0)` 뒤에 나온 `k0:` 줄을 커널이 쓴 것으로 믿을 수 없습니다. `k0: console drivers [...]` 줄도 여기에 포함됩니다("선택적 콘솔 출력" 참고).
- **EL2 트랩**: 격리는 기밀성과 무결성을 다루고 가용성은 다루지 않습니다. 커널이 EL1로 내려온 뒤 EL2로 트랩이 오면 설계상 기계 전체를 멈춥니다.
- **EL2 진입**: EL2 진입은 Linux와 같은 펌웨어 약속을 전제로 합니다. EL3 펌웨어는 세분화된 트랩과 HCRX 제어 기능이 있으면 이를 켜 주어야 합니다.
-- **루트 태스크**: 루트 태스크는 여전히 신뢰 대상이며 최초의 `Untyped` 케이퍼빌리티를 가지고, `write_bootinfo`는 그 물리 주소를 루트 태스크에 계속 노출합니다. 서명 오라클이 있는 이미지에서는 루트 태스크가 볼트도 만들며 볼트의 메모리를 읽을 수 있습니다("서명 오라클" 참고).
+- **루트 태스크**: 루트 태스크는 여전히 신뢰 대상이며 최초의 `Untyped` 케이퍼빌리티를 가지고, `write_bootinfo`는 그 물리 주소를 루트 태스크에 계속 노출합니다. 서명 오라클이 있는 이미지에서는 루트 태스크가 볼트도 만들며 볼트의 메모리를 읽을 수 있습니다("서명 오라클" 참고). feature `terminal`이 있는 이미지에서는 터미널 태스크도 시작하며, 터미널이나 볼트가 죽어도 다시 시작하지 않습니다.
> [!WARNING]
> `main`에서도 신뢰하지 않는 코드의 실행은 실험적인 것으로 취급하세요. 위의 가용성 한계는 그대로 적용됩니다.
@@ -120,9 +121,9 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다.
K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다.
> [!NOTE]
-> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다.
+> 입력은 feature `console-input`을 포함해 빌드한 이미지에만 있고, PL011과 SBSA UART에만 있습니다. 16550 콘솔에는 출력만 있고 입력이 없습니다("직렬 입력과 운영자 터미널" 참고).
-콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. 입력은 어떤 이미지에도 없습니다. `k0-kernel`의 콘솔 feature는 다음과 같습니다.
+콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. `console-input` 없이 빌드한 이미지에는 입력 코드가 전혀 없습니다. `k0-kernel`의 콘솔 feature는 다음과 같습니다.
| feature | 포함하는 드라이버 |
| --- | --- |
@@ -130,7 +131,7 @@ K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Car
| `console-16550` | 16550 계열의 송신 드라이버 |
| `console` | 위의 두 드라이버 모두 |
-이 feature는 콘솔 출력을 더하기만 하며 `default`에는 절대 추가하지 않습니다. 따라서 모든 빌드 명령이 이름을 직접 적습니다. 다음 명령은 각각 콘솔이 있는 4 KiB 이미지와 콘솔이 없는 이미지를 만듭니다.
+이 feature는 콘솔 출력을 더하기만 하며 `k0-kernel`의 모든 feature와 마찬가지로 `default`에는 절대 추가하지 않습니다. 따라서 모든 빌드 명령이 이름을 직접 적습니다. 다음 명령은 각각 콘솔이 있는 4 KiB 이미지와 콘솔이 없는 이미지를 만듭니다.
```sh
$ cargo build -p k0-kernel --features console --offline
@@ -148,7 +149,7 @@ $ cargo build -p k0-kernel --offline
**모든 이미지**에는 다음이 남습니다.
- 커널은 여전히 디바이스 트리의 콘솔 노드를 찾아 검사합니다. 판단 기준, `K0_PIN` 줄, UEFI 로더의 자가 검사가 모두 같습니다. 콘솔이 검사를 통과하지 못하는 디바이스 트리는 콘솔을 전혀 쓰지 않을 이미지도 거부합니다.
-- `DEBUG_PUTC` 시스템 콜과 `Console` 케이퍼빌리티가 남고, 태스크가 출력한 것은 여전히 부트 로그에 닿습니다.
+- `DEBUG_PUTC` 시스템 콜과 `Console` 케이퍼빌리티가 남고, 태스크가 출력한 것은 여전히 부트 로그에 닿습니다. `DEBUG_PUTC`에는 `Console` 케이퍼빌리티의 쓰기 권한(W)이 필요합니다.
- 부트 로그가 남습니다.
- UEFI 로더는 내장한 커널을 어떻게 빌드했든, 부트 서비스를 종료하기 전에는 자기 줄을 펌웨어 콘솔로 출력합니다.
@@ -169,10 +170,58 @@ $ grep -a 'k0: console drivers' <이미지 파일>
1. `quiet` 행의 비어 있는 직렬 로그는 PL011인 QEMU virt의 직렬 포트로 한 바이트도 나오지 않았다는 것만 보여 줍니다. 레지스터 읽기에 대해서는 아무것도 말하지 않습니다. 그것은 심볼 검사와, 커널 자신의 보고인 장치 페이지 목록이 다룹니다.
2. 심볼 검사는 디버그 이미지에서 실행합니다. 콘솔 없는 feature 조합의 릴리즈(LTO) 이미지는 매트릭스가 빌드하거나 부팅하지 않으며, 콘솔 없는 이미지를 UEFI로 부팅해 본 적도 없습니다.
-3. 16550 드라이버는 어떤 테스트로도 실행된 적이 없습니다. QEMU virt에 그런 UART가 없기 때문입니다. 코드는 리뷰로만 확인했습니다. SBSA UART는 식별 확인 없이 PL011 드라이버를 사용합니다. 실제 하드웨어에서 실행한 것은 없습니다.
+3. 16550 드라이버는 어떤 테스트로도 실행된 적이 없습니다. QEMU virt에 그런 UART가 없기 때문이며, 입력 경로도 없습니다. 코드는 리뷰로만 확인했습니다. SBSA UART는 식별 확인 없이 PL011 드라이버를 사용합니다. 실제 하드웨어에서 실행한 것은 없습니다.
4. 콘솔 없는 이미지가 줄이는 것은 출력 경로이지 커널이 메모리에 가진 내용이 아닙니다. 부트 로그는 평범한 커널 메모리이며, RAM을 읽거나 디버거를 붙일 수 있는 사람은 누구나 봅니다.
5. `Console` 케이퍼빌리티를 가진 태스크는 커널 줄처럼 보이는 줄을 출력할 수 있으며, `k0: console drivers [...]`도 여기에 포함됩니다. 로그에서 그 줄의 첫 번째 등장 또는 이미지 파일만이 빌드를 식별합니다. 이 줄은 증거가 아니라 표지입니다.
+## 직렬 입력과 운영자 터미널
+
+입력은 외부 데이터가 커널로 들어오는 두 번째 경로이므로 기본으로 꺼져 있고 자체 feature를 가집니다. 다음 표의 두 feature는 `k0-kernel`에서 코드를 더하기만 하며 `default`에는 절대 추가하지 않습니다.
+
+| feature | 추가하는 것 |
+| --- | --- |
+| `console-input` | 콘솔 UART용 커널 수신 경로와 시스템 콜 `CONSOLE_READ`입니다. 콘솔 드라이버 feature가 있어야 동작합니다. 수신은 PL011과 SBSA UART에만 있습니다. |
+| `terminal` | 루트 태스크 이미지 안의 운영자 터미널 태스크이며, 자가 시험 뒤에 서비스로 시작합니다. `console-input`을 켭니다. `vault`와 함께면 터미널이 볼트의 운영자가 되고, `vault-ed25519`와 함께면 Ed25519 키를 만들 수 있습니다. |
+
+> [!WARNING]
+> 직렬 회선에는 인증이 없습니다. 회선을 쥔 쪽이 운영자이며, 키를 지우는 것을 포함해 운영자의 네 연산(`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`)을 정확히 할 수 있습니다. 운영자는 서명을 받을 수 없고, 시드를 전달할 수 없으며, 정책을 바꿀 수 없습니다.
+
+`console-input` 없이 빌드한 이미지에는 수신 코드, `CONSOLE_READ`, 새 로그 줄이 전혀 없습니다(정적 부팅 매트릭스 행 `input-symbols`가 확인합니다). `terminal` 없이 빌드한 이미지에는 터미널 코드가 없습니다.
+
+커널이 입력으로 하는 일은 다음과 같습니다.
+
+- **수신 경로**: 커널의 UART 드라이버가 받은 바이트를 256바이트 링에 넣습니다. 커널은 바이트를 해석하지 않습니다. 손실(FIFO 오버런, 브레이크, 프레이밍 또는 패리티 오류)은 구멍 뒤의 바이트에 표시합니다.
+- **입력 읽기**: `CONSOLE_READ`(시스템 콜 16번). 호출자가 `Console` 슬롯과 플래그(`NONBLOCK`, `FLUSH`, 63..32비트의 틱 단위 타임아웃, 그 밖의 비트는 `BAD_FLAGS`로 거부)를 지정합니다. 호출마다 한 바이트를 돌려줍니다. 한 번에 한 태스크만 기다릴 수 있고 두 번째 읽는 쪽은 `BUSY`를 받습니다. 입력 경로가 없거나 꺼져 있으면 `NO_DEVICE`를 돌려줍니다. 기다리던 태스크의 케이퍼빌리티가 삭제, revoke 또는 이동되면 즉시 `REVOKED`로 깨어납니다. 깨어난 읽는 쪽은 준비 큐의 맨 뒤로 가므로 입력은 선점하지 않습니다.
+- **Console 케이퍼빌리티의 권한**: R(입력 읽기)과 W(출력 쓰기)입니다. `CAP_COPY`는 이를 줄이기만 할 수 있습니다. 루트 태스크의 케이퍼빌리티는 W를 가지며, R은 `console-input`이 있는 이미지에서만 가집니다. `bootinfo::VERSION`은 4입니다.
+- **출력 필터**: 바뀌지 않았습니다. 다만 R이 있는 `Console` 케이퍼빌리티(터미널의 것)는 백스페이스(0x08)도 내보낼 수 있습니다. 다른 제어 바이트는 여전히 `?`로 출력됩니다.
+- **수신 인터럽트는 꺼진 채로 둡니다**: 어떤 태스크가 권한을 가지고 처음 콘솔 입력을 읽을 때까지입니다. 그 첫 읽기가 장치에 있던 것을 버리고, 주기적인 `k0: tick N` 줄은 `k0: tick lines off (console input in use)` 한 줄을 남기고 멈춥니다. 틱, 선점, 타임아웃은 계속 동작합니다.
+- **인터럽트 작업의 상한**: 링이 가득 차면 커널이 UART의 수신 인터럽트를 스스로 마스크하고, 읽는 쪽이 링의 절반을 가져간 뒤 다시 엽니다. 따라서 폭주 중에도 인터럽트 빈도는 읽는 쪽이 정하는 만큼으로 제한됩니다. 같은 비우기가 틱마다 한 번 더 실행되므로, 인터럽트가 오지 않아도 입력은 최대 한 틱 늦게 도착합니다.
+- **인터럽트 번호**: 디바이스 트리(콘솔 노드의 `interrupts`: 찾아낸 GIC의 SPI 하나, 레벨, active high)에서, UEFI 로더를 거치면 ACPI SPCR 테이블에서 가져옵니다. 플랫폼 줄(`k0: platform con=pl011@0x9000000,irq33 ...`)에 출력되므로 `K0_PIN`이 고정합니다. 이 변경 이전에 만든 고정 문자열은 더 이상 맞지 않으므로 다시 만들어야 합니다.
+- **잘못된 인터럽트 번호가 치르는 비용은 입력 경로뿐입니다**: 범위를 벗어나거나 쓸 수 없으면 부팅 때 `k0: console input off (...)`가 나오고, UART 원인 없이 계속 발생하는 회선은 8번 진입한 뒤 `k0: console input off (interrupt N fired without a uart cause)`와 함께 꺼집니다. 쓸 수 있는 인터럽트가 없는 콘솔 노드는 부팅 거부 사유가 아니며 입력만 꺼집니다.
+- **부트 로그**: `k0: console input on (pl011 irq 33)` 또는 `k0: console input off ()`입니다.
+
+터미널의 정체는 다음과 같습니다.
+
+- **격리**: 터미널은 자기 주소 공간을 가진 태스크이며 케이퍼빌리티를 두 개 가집니다. R과 W가 있는 `Console` 사본, 그리고 송신 권한과 운영자 배지가 있는 볼트 엔드포인트입니다. 볼트의 응답 프레임은 터미널에 읽기 전용으로 매핑됩니다.
+- **시작**: 자가 시험이 끝나면 루트 태스크가 새 볼트를 시작하고 부트 시드를 넘기며, 터미널과 똑같이 연결한 적대적 태스크 둘을 실행하고(거부되어 폴트로 끝나야 합니다), 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작한 뒤 영원히 블록됩니다. `root: terminal wiring holds`와 `root: service started` 줄이 이를 보고합니다. 입력 경로가 없는 기계에서는 루트 태스크가 `root: no console input, terminal not started`를 출력합니다.
+- **입력 규칙**: 한 줄은 출력 가능한 ASCII 최대 64자입니다. 터미널은 프롬프트 전에 UART에 닿은 것을 버리고, 보고된 손실은 다음 줄 끝까지의 모든 것을 버립니다(`err input-lost`).
+
+한계는 다음과 같습니다.
+
+1. 직렬 회선은 그 회선에 닿을 수 있는 쪽만큼만 신뢰할 수 있습니다. 운영자는 키를 지울 수 있으며, 이는 설계상의 서비스 거부입니다.
+2. 커널의 수신 코드는 EL1에서 실행됩니다. 작고 바이트를 해석하지 않지만, 외부 당사자가 구동하는 커널 코드입니다. 사용자 공간 드라이버에는 장치와 인터럽트의 위임이 필요한데, K0에는 이것이 없습니다.
+3. 외부 당사자가 이제 태스크 실행 중에 인터럽트를 일으킬 수 있으며, 그 빈도는 읽는 쪽이 제한합니다. 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 되고, 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. 이것은 분석하지 않은 타이밍 채널입니다.
+4. 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱입니다.
+5. 16550 콘솔에는 입력이 없습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU에서 실행되지 않으며, 가짜 UART를 쓰는 호스트 테스트(`crates/k0-conin`)가 유일한 검증입니다. UART 원인 없이 발생하는 인터럽트 회선을 끊는 동작도 호스트 테스트로만 검증합니다.
+6. 기계에서 폭주 중의 커널 시간을 측정한 테스트는 없습니다. 상한은 게이트에서 논증하고 호스트 테스트로 보입니다.
+7. "프롬프트 전에 버림"은 UART에 닿은 바이트를 센 것입니다. 바이트를 붙잡아 두는 에뮬레이터나 어댑터는 나중에 전달하며, QEMU가 그렇게 합니다.
+8. 운영자가 입력하는 동안 커널 줄이 나타나면 화면의 줄은 쪼개지지만 버퍼는 온전하며, Enter는 버퍼 전체를 실행합니다.
+9. `Console` 출력이 있는 모든 태스크는 여전히 커널 줄이나 루트 태스크 줄처럼 보이는 줄을 출력할 수 있으며, 접두어를 인증하는 것은 없습니다. 터미널은 추가로 자기 현재 줄 안에서 지울 수 있습니다.
+10. 서비스 모드에는 서명 클라이언트가 없습니다. 볼트의 키는 만들어지고 표시되지만 다른 태스크가 사용하지 않습니다. 클라이언트의 서명은 자가 시험이 보여 줍니다.
+11. 터미널과 볼트는 죽어도 다시 시작하지 않습니다. 루트 태스크는 신뢰 대상입니다.
+12. 터미널 출력은 메모리 안 부트 로그의 사용자 몫에 포함됩니다. 그 몫이 차면 이후 태스크 출력은 거기에 기록되지 않습니다.
+13. "서명 오라클"의 볼트 한계는 모두 그대로입니다. 실제 하드웨어에서 실행한 것은 없습니다.
+
## 서명 오라클
서명 오라클은 격리 코어 위에 올라가는 첫 번째 서비스입니다. 볼트 태스크 하나가 Ed25519 키 하나를 보관합니다. 클라이언트 태스크는 IPC로 서명과 공개 키를 받으며 키 자체는 받지 못합니다. 이 기능은 선택 사항이며 기본으로 꺼져 있습니다.
@@ -183,28 +232,30 @@ $ grep -a 'k0: console drivers' <이미지 파일>
오라클이 주장하는 것은 다음과 같습니다.
- **키 분리**: 키는 볼트 자신의 주소 공간과 스택에 있습니다. 루트 태스크가 볼트를 만들며, 루트 태스크 외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없습니다. 클라이언트의 CNode에는 볼트 엔드포인트의 송신 전용 배지 사본만 들어 있습니다.
-- **프레임 권한**: 호출자마다 요청 프레임(호출자 읽기·쓰기, 볼트 읽기 전용)과 응답 프레임(볼트 읽기·쓰기, 호출자 읽기 전용)이 있으며, 권한을 줄인 프레임 케이퍼빌리티 사본으로 강제합니다.
-- **고정 정책**: 정책은 빌드 시점에 고정되고 엔드포인트 배지를 키로 삼습니다. 배지는 커널이 전달하므로 클라이언트가 위조할 수 없습니다. 역할은 admin(루트 태스크: STATUS, INIT, ZEROIZE, SIGN은 불가), signer(STATUS, PUBLIC_KEY, SIGN), reader(STATUS, PUBLIC_KEY)입니다. 배지가 없거나 알 수 없는 배지로 한 호출은 거부합니다. 정책을 바꾸는 연산은 없습니다.
+- **프레임 권한**: 호출자마다 요청 프레임(호출자 읽기·쓰기, 볼트 읽기 전용)과 응답 프레임(볼트 읽기·쓰기, 호출자 읽기 전용)이 있으며, 권한을 줄인 프레임 케이퍼빌리티 사본으로 강제합니다. operator에게는 응답 프레임만 있고 요청 프레임은 없습니다. 볼트는 배지와 연산만으로 어느 프레임을 읽고 쓸지 정하며, 역할이 가질 수 없는 본문이 있다고 주장하는 요청은 메모리를 건드리지 않고 거부합니다.
+- **고정 정책**: 정책은 빌드 시점에 고정되고 엔드포인트 배지를 키로 삼습니다. 배지는 커널이 전달하므로 클라이언트가 위조할 수 없습니다. 역할 넷이 빌드 시점에 고정됩니다. admin(루트 태스크: STATUS, INIT, KEYGEN, ZEROIZE, SIGN은 불가), operator(터미널: STATUS, PUBLIC_KEY, KEYGEN, ZEROIZE, SIGN과 INIT은 불가), signer(STATUS, PUBLIC_KEY, SIGN), reader(STATUS, PUBLIC_KEY)입니다. 배지가 없거나 알 수 없는 배지로 한 호출은 거부합니다. 정책을 바꾸는 연산은 없습니다.
- **고정 이미지**: 볼트 코드는 루트 태스크 이미지의 일부이며 이전처럼 부팅할 때 SHA-256으로 검사합니다. 부팅 후에는 아무것도 로드하지 않습니다.
- **요청을 한 번만 읽음**: 볼트는 길이를 먼저 확정한 뒤 요청 본문을 비공개 버퍼로 한 번만 읽고 그 사본만 사용합니다. 응답은 항상 레지스터 네 개(상태, 길이, 표시 비트, 호출자의 nonce)를 채웁니다. 클라이언트는 자신의 nonce가 담긴 OK 응답을 받은 뒤에만 응답 프레임을 신뢰해야 합니다.
-- **실패 상태**: 알려진 답 자가 시험(RFC 8032 벡터 두 개)이나 키 생성 뒤의 쌍 일관성 시험이 실패하면 볼트는 STATUS 외의 모든 것을 거부하는 실패 상태가 됩니다. 검증은 엄격 모드(`verify_strict`)입니다. 키를 내보내는 기능은 없고, ZEROIZE는 키를 버려 SIGN과 PUBLIC_KEY를 끝냅니다.
+- **실패 상태**: 알려진 답 자가 시험(RFC 8032 벡터 두 개)이나 키 생성 뒤의 쌍 일관성 시험이 실패하면 볼트는 STATUS 외의 모든 것을 거부하는 실패 상태가 됩니다. 실패 상태로 들어가는 모든 경로는 시드와 키를 지웁니다. 검증은 엄격 모드(`verify_strict`)입니다. 키를 내보내는 기능은 없고, ZEROIZE는 키를 버려 SIGN과 PUBLIC_KEY를 끝냅니다.
오라클이 주장하지 않는 것은 다음과 같습니다.
1. 알고리즘은 Ed25519(SHA-512를 쓰는 PureEdDSA, FIPS 186-5와 RFC 8032에 있음)입니다. 구현은 벤더링한 크레이트 `ed25519-dalek` 2.2.0이며 어떤 종류의 검증도 받지 않았습니다. 키는 승인된 난수 비트 생성기에서 나오지 않습니다.
2. 이 커널 위에서 크레이트의 부채널 분석은 하지 않았습니다.
-3. 키는 하나이고, 영속성, 키 가져오기·내보내기, DRBG, 운영자 입력이 없습니다. 양자 내성 알고리즘은 아직 없습니다.
+3. 키는 부팅마다 하나이고(두 번째 KEYGEN은 `key-exists`로 거부하며, ZEROIZE 뒤에는 재부팅이 필요합니다), 영속성, 키 가져오기·내보내기, DRBG가 없습니다. 운영자 입력은 인증이 없는 직렬 터미널뿐입니다("직렬 입력과 운영자 터미널" 참고). 양자 내성 알고리즘은 아직 없습니다.
4. 모든 signer가 키 하나를 공유하므로 서명에는 클라이언트 신원이 담기지 않습니다.
-5. 볼트의 가용성은 보호하지 않습니다. 클라이언트는 엔드포인트 하나를 공유하며 타임아웃을 사용해야 합니다.
+5. 볼트의 가용성은 보호하지 않습니다. 클라이언트는 엔드포인트 하나를 공유하며 타임아웃을 사용해야 하고, 운영자는 키를 지울 수 있습니다.
6. 루트 태스크는 신뢰 대상이며 볼트를 읽을 수 있습니다.
7. 오라클은 QEMU(TCG와 HVF)에서만 실행했습니다. 스택 사본(커널 부트 스택, 서명 뒤의 볼트 스택)의 삭제는 최선을 다하는 수준입니다.
-8. 자가 시험은 클라이언트를 하나의 클라이언트 주소 공간에서 차례로 실행하므로, 클라이언트 사이가 아니라 볼트와 클라이언트 사이의 격리를 보여 줍니다.
+8. 자가 시험은 클라이언트를 하나의 클라이언트 주소 공간에서 차례로 실행하므로, 클라이언트 사이가 아니라 볼트와 클라이언트 사이의 격리를 보여 줍니다. 자가 시험은 공개된 RFC 8032 테스트 시드로 키를 만들며, 실제 시드 정보를 함께 넘기므로 엔트로피 규칙은 여전히 시험됩니다.
+
+시드와 키는 다음과 같습니다. 볼트의 상태는 `fresh`, `seeded`, `ready`, `zeroized`, `failed`입니다. INIT(admin 전용, 한 번)은 시드를 전달하기만 합니다. 볼트는 엔트로피 규칙을 확인하고 시드를 보관합니다(`seeded`). KEYGEN(admin과 operator)은 보관한 시드에서 선택한 알고리즘으로 키를 만들고 시드를 지웁니다(`ready`). 알고리즘이 없는 이미지의 볼트는 시드를 거부하고 `fresh`에 머물며, 모두 0인 시드도 거부합니다.
-엔트로피 규칙은 다음과 같습니다. 볼트는 부트 시드에 `rng-seed` 바이트가 32바이트 이상 있거나 RNDR에서 온 256비트가 있지 않으면 키 생성을 거부합니다(상태 `NO_ENTROPY`). QEMU virt는 32바이트 `rng-seed`를 제공합니다. 모든 응답에는 표시 비트가 담깁니다. 알고리즘이 FIPS 186-5에 있는지, 자가 시험이 통과했는지, `rng-seed`가 32바이트 이상 키 시드에 들어갔는지, RNDR이 키 시드에 들어갔는지입니다. 이 비트는 일어난 일을 보고할 뿐 검증 주장이 아닙니다.
+엔트로피 규칙은 다음과 같습니다. 볼트는 부트 시드에 `rng-seed` 바이트가 32바이트 이상 있거나 RNDR에서 온 256비트가 있지 않으면 부트 시드를 거부합니다(상태 `NO_ENTROPY`). QEMU virt는 32바이트 `rng-seed`를 제공합니다. 모든 응답에는 표시 비트가 담깁니다. 알고리즘이 FIPS 186-5에 있는지, 자가 시험이 통과했는지, `rng-seed`가 32바이트 이상 키 시드에 들어갔는지, RNDR이 키 시드에 들어갔는지입니다. 이 비트는 일어난 일을 보고할 뿐 검증 주장이 아닙니다. STATUS 응답은 상태, 키의 알고리즘, 이미지에 있는 알고리즘을 한 워드에 담습니다.
### 부트 시드와 시드 삭제
-커널은 루트 태스크용 32바이트를 디바이스 트리 엔트로피, 카운터, CPU에 RNDR이 있으면 새 RNDR 워드 네 개로부터 자기만의 도메인 문자열을 붙인 SHA-256으로 유도합니다. 도메인 분리 덕분에 PAC 키와는 독립입니다. 시드는 입력만큼만 좋고 그 이상은 아닙니다. 시드는 진입 레지스터 `x0`~`x3`로 루트 태스크에 전달되며, `x4`가 사용한 `rng-seed` 바이트 수와 RNDR 기여 여부를 알려 줍니다. bootinfo 페이지에는 없고, 루트 태스크는 시드가 아니라 출처만 출력합니다.
+커널은 루트 태스크용 32바이트를 디바이스 트리 엔트로피, 카운터, CPU에 RNDR이 있으면 새 RNDR 워드 네 개로부터 자기만의 도메인 문자열을 붙인 SHA-256으로 유도합니다. 도메인 분리 덕분에 PAC 키와는 독립입니다. 시드는 입력만큼만 좋고 그 이상은 아닙니다. 시드는 진입 레지스터 `x0`~`x3`로 루트 태스크에 전달되며, `x4`가 사용한 `rng-seed` 바이트 수와 RNDR 기여 여부를 알려 줍니다. bootinfo 페이지에는 없고, 루트 태스크는 시드가 아니라 출처만 출력합니다. 실제 부트 시드는 `terminal`과 `vault`가 있는 이미지의 서비스 볼트가 정확히 한 번 사용합니다. 그 밖의 모든 이미지에서는 루트 태스크가 진입할 때 지웁니다.
커널은 루트 태스크에 진입하기 직전에 디바이스 트리의 `rng-seed`와 `kaslr-seed` 바이트를 0으로 지웁니다. 그 페이지의 읽기 전용 별칭 항목을 제자리에서 읽기·쓰기로 바꾸고, 0을 쓰고, 캐시 줄을 비우고 무효화한 뒤, 다시 되돌리고 바이트를 읽어 확인합니다. 그런 다음 `BootInfo` 안의 자기 사본을 지우고, `k0: dtb seeds wiped B`를 출력하고, 활성 프레임 아래의 부트 스택을 0으로 지웁니다. 펌웨어나 UEFI 로더가 보관한 사본과 부트 스택의 활성 프레임에 있는 것은 지우지 않습니다.
@@ -233,7 +284,7 @@ $ grep -a 'k0: console drivers' <이미지 파일>
- **권장**: 에서 draft advisory를 작성하세요.
- **대안**: 메인테이너 에게 메일을 보내세요. 영향을 받는 커밋 해시, 플랫폼(QEMU 머신과 CPU 모델, 하이퍼바이저 또는 보드), 진입 단계(EL1 또는 EL2), 페이지 크기(4 KiB 또는 16 KiB), 부트 로그의 `k0: platform ...` 줄, 재현 방법이 있으면 포함해 주세요.
-`v0.1.0` 이하의 격리 공백과, "`main`에서도 여전히 제공하지 않는 것"에 적은 가용성·자원 한계는 이미 알려진 문제이기 때문에 **다시 신고하실 필요는 없습니다**. 현재 `main` 브랜치의 격리 우회는 환영합니다. 예를 들어 한 태스크가 다른 태스크의 메모리나 케이퍼빌리티에 닿는 경우, revoke된 케이퍼빌리티가 계속 동작하는 경우, unmap·revoke·주소 공간 파괴 뒤에도 낡은 매핑이 남는 경우입니다. 서명 오라클에 관한 신고도 환영합니다. 예를 들어 클라이언트에 키가 노출되는 경우, 정책 우회, 엉뚱한 호출자에게 응답이 가는 경우입니다. UEFI 로더에 관한 신고도 환영합니다. 예를 들어 펌웨어가 아직 쓰는 메모리를 커널에 넘기게 만드는 메모리 맵이나 디바이스 트리, 일어나야 할 거부가 일어나지 않는 경우입니다. 그 외의 문제, 예를 들어 부팅 시 메모리 맵 검증, 예외 처리, 스케줄러 정책, IPC 상태 기계에 관한 신고는 언제든 환영합니다.
+`v0.1.0` 이하의 격리 공백과, "`main`에서도 여전히 제공하지 않는 것"에 적은 가용성·자원 한계는 이미 알려진 문제이기 때문에 **다시 신고하실 필요는 없습니다**. 현재 `main` 브랜치의 격리 우회는 환영합니다. 예를 들어 한 태스크가 다른 태스크의 메모리나 케이퍼빌리티에 닿는 경우, revoke된 케이퍼빌리티가 계속 동작하는 경우, unmap·revoke·주소 공간 파괴 뒤에도 낡은 매핑이 남는 경우입니다. 서명 오라클에 관한 신고도 환영합니다. 예를 들어 클라이언트에 키가 노출되는 경우, 정책 우회, 엉뚱한 호출자에게 응답이 가는 경우입니다. 직렬 입력 경로와 운영자 터미널에 관한 신고도 환영합니다. 예를 들어 커널을 오동작하게 만드는 바이트 열, 엉뚱한 태스크를 깨우는 경우, 나열한 네 가지를 넘는 운영자 연산입니다. UEFI 로더에 관한 신고도 환영합니다. 예를 들어 펌웨어가 아직 쓰는 메모리를 커널에 넘기게 만드는 메모리 맵이나 디바이스 트리, 일어나야 할 거부가 일어나지 않는 경우입니다. 그 외의 문제, 예를 들어 부팅 시 메모리 맵 검증, 예외 처리, 스케줄러 정책, IPC 상태 기계에 관한 신고는 언제든 환영합니다.
## 범위
@@ -243,7 +294,7 @@ $ grep -a 'k0: console drivers' <이미지 파일>
-**범위 안**: `kernel/`, `crates/`(`crates/k0-efi` 포함), `loader/`, `userspace/root-task/`, `userspace/k0-vault`(루트 태스크 안의 연결 코드 포함) 하위의 모든 코드입니다. UEFI 로더는 부트 체인의 일부이지만 이 저장소의 코드이므로, 메모리 맵과 디바이스 트리와 커널 이미지를 다루는 부분은 범위 안입니다.
+**범위 안**: `kernel/`, `crates/`(`crates/k0-efi` 포함), `loader/`, `userspace/root-task/`, `userspace/k0-vault`와 `userspace/k0-term`(루트 태스크 안의 연결 코드 포함) 하위의 모든 코드입니다. UEFI 로더는 부트 체인의 일부이지만 이 저장소의 코드이므로, 메모리 맵과 디바이스 트리와 커널 이미지를 다루는 부분은 범위 안입니다.
**범위 밖**: 커널 진입점 이전의 나머지 부트 체인(예: 펌웨어, 다른 부트로더, 하이퍼바이저)과 커널 이미지 자체의 무결성입니다(커널 이미지 서명은 부트 체인의 책임입니다). UEFI에서는 이것이 펌웨어의 Secure Boot를 뜻합니다. 로더의 SHA-256 검사는 서명이 아니기 때문입니다("UEFI 로더" 절 참고).
diff --git a/USAGE.md b/USAGE.md
index 7e8e692..87135b6 100644
--- a/USAGE.md
+++ b/USAGE.md
@@ -33,9 +33,9 @@ This builds the kernel with a console driver and starts it in QEMU. The boot mes
Input and output are optional in K0. You can select them with Cargo features of the kernel crate.
> [!NOTE]
-> A feature for input or for a terminal does not exist yet. Console output is the only thing you can select today.
+> Console input and the operator terminal are features too, but they are off by default. They are described in "Operator terminal" below.
-Console output exists only in an image built with a console feature. No image has input. `cargo virt` is an alias for `cargo run -p k0-kernel --features console`, so it always includes the console. The following picture shows where the output goes, depending on the features in the build.
+Console output exists only in an image built with a console feature. An image has input only if it was built with `console-input` or `terminal`. `cargo virt` is an alias for `cargo run -p k0-kernel --features console`, so it always includes the console. The following picture shows where the output goes, depending on the features in the build.
@@ -189,12 +189,112 @@ In the boot log you should see these lines, in addition to the lines in "Reading
- `k0: dtb seeds wiped 40B` and `root: boot seed from rng-seed bytes 0x0000000000000020 without rndr` (with `K0_QEMU_CPU=max` the second line ends with `and rndr`). QEMU virt provides a 32-byte `rng-seed`, which is `0x20`.
- Two more `k0: task fault` lines, 8 in total. They come from two clients that the self-test lets break the memory rules on purpose.
-- `root: oracle tests pass` before `root: sched tests pass`. This line means that all the checks of the oracle passed: the vault made its key from the boot seed, a signer got a signature that verifies, a changed message or signature does not verify, the admin and a reader were refused when they asked to sign, and signing was refused after the key was erased.
+- `root: oracle tests pass` before `root: sched tests pass`. This line means that all the checks of the oracle passed: the vault made its key from the public RFC 8032 test seed, a signer got a signature that verifies, a changed message or signature does not verify, the admin and a reader were refused when they asked to sign, and signing was refused after the key was erased.
The vault makes a key only if the boot seed holds at least 32 `rng-seed` bytes or 256 bits from RNDR. If it does not, for example on a machine whose device tree has no `rng-seed` and whose CPU has no RNDR, the vault answers `NO_ENTROPY` and makes no key. The root task then prints `root: oracle made no key (boot seed has no entropy)` and stops the oracle test there. `root: oracle tests pass` does not appear, so a boot test that requires it fails, which is the intended result.
> [!NOTE]
-> The implementation of Ed25519 is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind, and the key does not come from an approved random bit generator. There is one key, no persistence, no key import or export and no input from an operator. The availability of the vault is not protected, because all clients share one endpoint and must use timeouts. The root task is trusted and could read the vault. The oracle was only run in QEMU (TCG and HVF). The details and the limits are in [SECURITY.md](SECURITY.md).
+> The implementation of Ed25519 is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind, and the key does not come from an approved random bit generator. There is one key, no persistence, no key import or export and no authentication of the operator. The availability of the vault is not protected, because all clients share one endpoint and must use timeouts. The root task is trusted and could read the vault. The oracle was only run in QEMU (TCG and HVF). The details and the limits are in [SECURITY.md](SECURITY.md).
+
+### Operator terminal
+
+The operator terminal is a small task that lets you type commands on the serial line and talk to the vault. It is optional and off by default. Two features of `k0-kernel` select it, and features only add.
+
+| Feature | Adds |
+| --- | --- |
+| `console-input` | The kernel's receive path for the console UART and the system call `CONSOLE_READ`. It needs a console driver feature to do anything. Receive exists for PL011 and SBSA UART only, so a 16550 console has output and no input |
+| `terminal` | The terminal task in the root task image, started as a service after the self-tests. It turns `console-input` on. With `vault` the terminal is the vault's operator. With `vault-ed25519` it can make an Ed25519 key |
+
+An image without `console-input` has no receive code, no `CONSOLE_READ` and none of the new log lines. An image without `terminal` has no terminal code. You can build and run it as follows:
+
+```sh
+$ cargo build -p k0-kernel --features console,terminal,vault-ed25519
+$ cargo run -p k0-kernel --features console,terminal,vault-ed25519
+```
+
+`cargo run` starts QEMU with the serial port on your terminal. QEMU's own escape key is `Ctrl-A` there (`Ctrl-A`, then `X` quits QEMU), so `Ctrl-A` never reaches K0.
+
+After the self-tests, the root task starts the vault, hands it the boot seed, runs two hostile tasks wired like the terminal (they must be refused and end in a fault), drops its admin capability and starts the terminal. The boot log shows `root: vault seeded`, `root: terminal console filter [...]`, `root: terminal wiring holds`, two `k0: task fault` lines, `root: service started` and then the banner. On a machine without an input path it shows `root: no console input, terminal not started`. After the first read, the periodic `k0: tick N` lines stop, and one line `k0: tick lines off (console input in use)` marks that. In the following session, every command ends with exactly one line, `ok` or `err `:
+
+```
+K0 operator console, type 'help'
+k0> vault status
+state=seeded
+alg=none
+selftest=passed
+seed=rng-seed
+validated=no
+ok
+k0> vault keygen ed25519
+state=ready
+alg=ed25519
+ok
+k0> vault pubkey
+pubkey=<32 hex characters>
+ <32 hex characters>
+ok
+k0> vault zeroize
+hint=type 'vault zeroize confirm' to erase the key
+err confirm-required
+k0>
+```
+
+Values are printed as `name=value`. The screen prompt is `k0> `. In the following table, the first column is what you type:
+
+| Command | Argument | What it does |
+| --- | --- | --- |
+| `help` | | Lists the commands |
+| `vault status` | | Prints the vault state (see below) |
+| `vault pubkey` | | Prints the public key |
+| `vault keygen ` | `ed25519` | Makes the key from the held seed with the chosen algorithm and wipes the seed |
+| `vault zeroize confirm` | | Erases the key. `vault zeroize` alone prints `hint=type 'vault zeroize confirm' to erase the key` and `err confirm-required` |
+
+`vault status` prints `state=fresh|seeded|ready|zeroized|failed`, `alg=none|ed25519`, `selftest=passed|failed`, `seed=none|rng-seed|rndr|rng-seed+rndr` and `validated=no`. `seed=rng-seed` means that the bytes were present, not that they were unpredictable. `validated=no` is always printed, because the implementation has no validation of any kind. `vault pubkey` prints `pubkey=` and 32 hex characters, then a second line indented by 7 spaces with the other 32. A vault makes one key per boot: a second `vault keygen` gives `err key-exists`, and after `vault zeroize confirm` you have to reboot. Without the `vault` feature, `help` lists only `help` and `vault ...` answers `err no-vault`.
+
+In the following table, the keys work on the line you are typing:
+
+| Key | Effect |
+| --- | --- |
+| Enter (CR or LF) | Runs the line. A line has at most 64 characters, printable ASCII only |
+| Backspace or DEL | Erases one character |
+| `Ctrl-C` or `Ctrl-U` | Cancels the line (shown as `^C` or `^U`) |
+| ESC sequences (arrow keys) | Ignored |
+
+Bytes that reached the UART before the prompt are dropped. If the input was lost (a FIFO overrun, a break, a framing or parity error), everything up to the next line end is discarded and the command answers `err input-lost`. A keygen or zeroize that was delivered but not answered in time adds `hint=run 'vault status' to see whether it took effect`. In the following table, the error names are what comes after `err `:
+
+| Error | Meaning |
+| --- | --- |
+| `unknown-command` | The command is not known |
+| `bad-argument` | An argument is wrong or missing |
+| `line-too-long` | The line is longer than 64 characters |
+| `input-lost` | Input was lost before the line end |
+| `confirm-required` | `vault zeroize` without `confirm` |
+| `denied` | The operation is not allowed for the operator |
+| `no-vault` | The image has no vault |
+| `no-key` | The vault has no key |
+| `key-exists` | The vault already made its key this boot |
+| `no-entropy` | The boot seed has no entropy |
+| `unsupported-algorithm` | The algorithm is not in this image |
+| `zeroized` | The key was erased; a reboot is needed |
+| `vault-failed` | The vault failed and wiped seed and key |
+| `vault-timeout` | The vault did not answer in time |
+
+> [!WARNING]
+> There is no authentication on the serial line. Whoever holds the line is the operator and can do exactly the operator's four operations (`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`), including erasing the key. The operator cannot get a signature, cannot deliver a seed and cannot change policy.
+
+What stays true, and what is not covered:
+
+- **Kernel code**: the receive code runs at EL1. It is small and never interprets a byte, but it is kernel code driven by an outside party. A user-space driver needs device and interrupt delegation, which K0 does not have.
+- **Timing**: an outside party can now cause interrupts while tasks run (bounded by the reader), and the reader learns arrival times finer than the tick. Other tasks can notice the stolen time. This timing channel is not analysed.
+- **Latency**: input waits behind running tasks. There are no priorities, so the latency is up to a tick per ready task.
+- **Hardware**: a 16550 console has no input. The SBSA UART path, FIFO overruns and the receive timeout interrupt are not exercised by QEMU, only by host tests with a fake UART. The cut-off for an interrupt line that fires without a UART cause is also covered only by host tests. No test measures kernel time under a flood on a machine. Nothing ran on real hardware.
+- **Screen**: if a kernel line appears while you are typing, the screen line is split but the buffer is whole, and Enter runs the whole buffer. Any task with `Console` output can still print lines that look like kernel or root task lines, and nothing authenticates the prefix. The terminal can additionally erase within its current line.
+- **Bytes held back**: "dropped before the prompt" counts bytes that reached the UART. An emulator or adapter that holds bytes back delivers them later (QEMU does).
+- **Service**: no signing client exists in service mode yet. The key is made and shown but not used by another task. The terminal and the vault are not restarted if they die. The root task is trusted.
+- **Boot log**: terminal output counts against the user share of the in-memory boot log. Once that share is full, later task output is not recorded there.
+- **Vault**: all earlier limits stay. The implementation is unvalidated, there is no side-channel analysis, the key does not come from an approved random bit generator, there is no persistence and there is no PQC. The availability of the vault and of the terminal is not protected.
+
+If the console interrupt number is wrong, only the input path is lost: the boot log shows `k0: console input off (...)`. The reasons are `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range` and `interrupt not available`. A line that keeps firing without a UART cause is switched off after 8 entries with `k0: console input off (interrupt N fired without a uart cause)`. With input on, the boot log shows `k0: console input on (pl011 irq 33)`. The interrupt number is part of the platform line (`k0: platform con=pl011@0x9000000,irq33 ...`), so a `K0_PIN` made before this change no longer matches and must be made again.
## Booting through UEFI
@@ -307,9 +407,9 @@ $ tools/qemu-boot-test.sh # boot in QEMU and che
$ tools/boot-matrix.sh # boot every supported configuration (builds the 16 KiB, pinned and UEFI loader images too)
```
-- `tools/host-test.sh` runs the 276 host tests (190 on an x86-64 computer): small tests of single parts of the kernel (unit tests) as ordinary programs on your computer. It also does **fuzzing**: it feeds the device tree parser and the UEFI loader's planning code random, broken input to find crashes. The 276 are 14 (`k0-abi`), 42 (`k0-cap`), 82 (`k0-boot`), 32 (`k0-efi`), 20 (`k0-vault`, which is 13 with Ed25519 and 7 without) and 43 for each of the two page sizes (`k0-mm`). The memory management tests use ARM instructions, so they run only on an ARM computer (an Apple Silicon Mac or Linux arm64), and the x86-64 count leaves out those 86.
+- `tools/host-test.sh` runs the 354 host tests (268 on other hosts): small tests of single parts of the kernel (unit tests) as ordinary programs on your computer. It also does **fuzzing**: it feeds the device tree parser and the UEFI loader's planning code random, broken input to find crashes. The 354 are 15 (`k0-abi`), 44 (`k0-cap`), 85 (`k0-boot`), 33 (`k0-efi`), 15 (`k0-conin`), 31 (`k0-vault`, which is 20 with Ed25519 and 11 without), 45 (`k0-term`, which is 24 with the vault feature and 21 without) and 43 for each of the two page sizes (`k0-mm`). The memory management tests use ARM instructions, so they run only on an ARM computer (an Apple Silicon Mac or Linux arm64), and the count on other hosts leaves out those 86.
- `tools/qemu-boot-test.sh` boots the kernel and reads the log line by line in a fixed order. It fails on any error line, checks the exact number of intentional fault lines, and stops QEMU when it is done. The root task's timeout tests wait for real timer ticks, so a boot takes about 4 seconds longer than it did before they existed. The test also counts the tick lines between `root: teardown tests pass` and `root: timeout tests pass` and wants at least 4, which is how it checks that a timeout does not end early. It prints `boot-test: pass` on success and saves the full log in `target/qemu-boot-test.log`. It takes the machine from the `K0_QEMU_*` variables above. It accepts `K0_BOOT_REUSE=skip` for memory layouts that have no untyped region of the right size, where the root task skips its reuse test. It reads the kernel lines from the **serial port**, so it needs an image with a console driver. For an image without one, see "Testing an image without console" below. If the serial log has no kernel line, it prints a hint about a kernel built without a console feature.
-- `tools/boot-matrix.sh` boots the kernel in **each** configuration that K0 calls supported and checks the result. It boots QEMU virt with GICv3 and GICv2 at EL1 and EL2, and also three CPU models, 4 cores, the 16 KiB image, other load addresses, `xlnx-versal-virt`, a pinned image and the images with the signing oracle. It also checks statically that the image does not touch the physical timer. The matrix has 61 rows on a Mac with HVF and 51 in CI. You can name single rows as arguments. CI runs it.
+- `tools/boot-matrix.sh` boots the kernel in **each** configuration that K0 calls supported and checks the result. It boots QEMU virt with GICv3 and GICv2 at EL1 and EL2, and also three CPU models, 4 cores, the 16 KiB image, other load addresses, `xlnx-versal-virt`, a pinned image and the images with the signing oracle. It also checks statically that the image does not touch the physical timer. The matrix has 76 rows on a Mac with HVF and 65 in CI. You can name single rows as arguments. CI runs it.
The console rows check the console features. The following table lists the console rows and what they check.
@@ -336,7 +436,24 @@ The `uefi-*` rows boot the kernel through the UEFI loader on EDK2: GICv3 and GIC
For configurations that must be refused, it reads the reason from the boot log in memory, or for the loader from the serial log. These are a 16 KiB kernel on `cortex-a72` and a kernel with one changed byte.
-On an Apple Silicon Mac, `K0_MATRIX_HVF=1 tools/boot-matrix.sh` adds rows that run the kernel, also through the UEFI loader, on the real CPU cores through QEMU's HVF accelerator. Among them are `hvf-quiet` for the image without console and `hvf-vault` for the image with the oracle.
+On an Apple Silicon Mac, `K0_MATRIX_HVF=1 tools/boot-matrix.sh` adds rows that run the kernel, also through the UEFI loader, on the real CPU cores through QEMU's HVF accelerator. Among them are `hvf-quiet` for the image without console, `hvf-vault` for the image with the oracle and `hvf-term` for the terminal image.
+
+The input and terminal rows check the receive path and the terminal. In the following table, the rows `input-only`, `input-gicv2`, `input-16550` and `input-bad-irq` boot images with `console-input` and no terminal:
+
+| Row | What it checks |
+| --- | --- |
+| `input-only` | An image with `console-input` and no terminal |
+| `input-gicv2` | The same on GICv2 |
+| `input-16550` | An image with only the 16550 driver: input is off (`console not attached`) and the log says so |
+| `input-bad-irq` | A device tree with an interrupt number out of range costs only the input path (`interrupt number out of range`) |
+| `input-symbols` | Static check. An image without `console-input` contains no receive code, no `CONSOLE_READ` and none of the new log lines |
+| `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k` | The terminal image, run through `tools/term-test.py` on the default CPU, on the `max` CPU, at EL2, on GICv2 and with a 16 KiB image |
+| `term-no-vault` | A terminal without the vault: `help` lists only `help` |
+| `term-no-alg` | A terminal with `vault` but no algorithm |
+| `term-uefi`, `term-uefi-acpi` | The terminal image through the UEFI loader (device tree path and ACPI path) |
+| `hvf-term` | The terminal image under HVF (Mac only) |
+
+`tools/term-test.py ` boots the image with QEMU's serial port on pipes and runs a scripted session. It covers every command and error, erase and cancel, CR LF, an ESC sequence, a line that is too long, key generation, the public key format, zeroize, 200 kB without a line end, 2000 lines in a row and a serial break. `tools/qemu-boot-test.sh` also knows `K0_BOOT_INPUT=on|off` and `K0_BOOT_SERVICE=vault|plain|none` to say what the image should show, and a judge-only mode `K0_BOOT_JUDGE`. A terminal image prints two more `k0: task fault` lines than the same image without the terminal (8 without the vault, 10 with it), so use `K0_BOOT_FAULTS` for it.
### Testing an image without console
@@ -397,3 +514,7 @@ The following table lists what to do for each problem.
| `build-loader: kernel ELF not found` | Build the kernel first with `cargo build -p k0-kernel --features console --offline` |
| `build-loader: embedding a kernel with: k0: console drivers [none]` | The loader will carry a kernel without console. It still prints its own lines, and the kernel prints nothing after them. Build the kernel with `--features console` and run `tools/build-loader.sh` again if you want output |
| The screen shows only firmware messages, or the firmware menu | The firmware could not start the loader, or the loader refused and the firmware went on. Look for `k0-loader:` lines. With none, check that the `.efi` file exists and, with `K0_QEMU_ESP`, that the drive is found |
+| The terminal shows no `k0> ` prompt | Either the image was built without `terminal` (and `console-input`), or the log shows `k0: console input off (...)` or `root: no console input, terminal not started`. Build with `--features console,terminal,vault-ed25519` and read the reason in the boot log |
+| Nothing happens when I type, or `Ctrl-A` does not arrive | Under `cargo run` QEMU keeps `Ctrl-A` for itself. A 16550 console has no input at all |
+| `boot-test` fails on the number of `k0: task fault` lines for a terminal image | That image prints 2 more than without the terminal (8 or 10). Use `K0_BOOT_FAULTS` |
+| A `K0_PIN` made earlier no longer matches | The platform line now contains the console interrupt (`irq33`). Make the pin again |
diff --git a/USAGE_KR.md b/USAGE_KR.md
index 9ca5f66..ccae298 100644
--- a/USAGE_KR.md
+++ b/USAGE_KR.md
@@ -33,9 +33,9 @@ $ cargo virt
K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다.
> [!NOTE]
-> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다.
+> 콘솔 입력과 운영자 터미널도 feature이지만 기본으로는 꺼져 있습니다. 뒤의 "운영자 터미널"에서 설명합니다.
-콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. 입력은 어떤 이미지에도 없습니다. `cargo virt`는 `cargo run -p k0-kernel --features console`의 별칭이므로 항상 콘솔을 포함합니다. 다음 그림은 빌드에 포함한 feature에 따라 출력이 어디에 닿는지 보여 줍니다.
+콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. 입력은 `console-input` 또는 `terminal`을 포함해 빌드한 이미지에만 있습니다. `cargo virt`는 `cargo run -p k0-kernel --features console`의 별칭이므로 항상 콘솔을 포함합니다. 다음 그림은 빌드에 포함한 feature에 따라 출력이 어디에 닿는지 보여 줍니다.
@@ -189,12 +189,112 @@ $ K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE='k0: dtb seeds wiped 40B|root: oracle tests p
- `k0: dtb seeds wiped 40B`와 `root: boot seed from rng-seed bytes 0x0000000000000020 without rndr`입니다(`K0_QEMU_CPU=max`에서는 두 번째 줄이 `and rndr`로 끝납니다). QEMU virt는 32바이트 `rng-seed`를 제공하며, 이것이 `0x20`입니다.
- `k0: task fault` 줄이 두 개 더 나와 모두 8개입니다. 자가 테스트가 일부러 메모리 규칙을 어기게 하는 클라이언트 둘에서 나온 줄입니다.
-- `root: sched tests pass` 앞의 `root: oracle tests pass`입니다. 이 줄은 오라클의 검사가 모두 통과했다는 뜻입니다. 볼트가 부트 시드로 키를 만들었고, 서명자가 검증되는 서명을 받았으며, 메시지나 서명을 바꾸면 검증되지 않고, 관리자와 읽기 전용 클라이언트는 서명을 요청했을 때 거부되었으며, 키를 지운 뒤에는 서명이 거부되었습니다.
+- `root: sched tests pass` 앞의 `root: oracle tests pass`입니다. 이 줄은 오라클의 검사가 모두 통과했다는 뜻입니다. 볼트가 공개 RFC 8032 테스트 시드로 키를 만들었고, 서명자가 검증되는 서명을 받았으며, 메시지나 서명을 바꾸면 검증되지 않고, 관리자와 읽기 전용 클라이언트는 서명을 요청했을 때 거부되었으며, 키를 지운 뒤에는 서명이 거부되었습니다.
볼트는 부트 시드에 `rng-seed` 바이트가 32개 이상 있거나 RNDR에서 온 256비트가 있을 때만 키를 만듭니다. 그렇지 않으면, 예를 들어 디바이스 트리에 `rng-seed`가 없고 CPU에 RNDR도 없는 머신에서는 볼트가 `NO_ENTROPY`로 답하고 키를 만들지 않습니다. 그러면 루트 태스크가 `root: oracle made no key (boot seed has no entropy)`를 출력하고 오라클 테스트를 거기서 멈춥니다. `root: oracle tests pass`는 나오지 않으므로 이 줄을 요구하는 부팅 테스트는 실패하며, 이것이 의도한 결과입니다.
> [!NOTE]
-> Ed25519 구현은 vendor에 넣은 `ed25519-dalek` 2.2.0 크레이트이며 어떤 종류의 검증도 받지 않았고, 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 키는 하나뿐이고, 영속성도 키의 가져오기나 내보내기도 운영자 입력도 아직 없습니다. 클라이언트가 엔드포인트 하나를 함께 사용하므로 볼트의 가용성은 보호되지 않으며 타임아웃을 써야 합니다. 루트 태스크는 신뢰 대상이며 볼트를 읽을 수 있습니다. 오라클은 QEMU(TCG와 HVF)에서만 실행해 보았습니다. 자세한 내용과 한계는 [SECURITY_KR.md](SECURITY_KR.md)에 있습니다.
+> Ed25519 구현은 vendor에 넣은 `ed25519-dalek` 2.2.0 크레이트이며 어떤 종류의 검증도 받지 않았고, 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 키는 하나뿐이고, 영속성도 키의 가져오기나 내보내기도 운영자 인증도 아직 없습니다. 클라이언트가 엔드포인트 하나를 함께 사용하므로 볼트의 가용성은 보호되지 않으며 타임아웃을 써야 합니다. 루트 태스크는 신뢰 대상이며 볼트를 읽을 수 있습니다. 오라클은 QEMU(TCG와 HVF)에서만 실행해 보았습니다. 자세한 내용과 한계는 [SECURITY_KR.md](SECURITY_KR.md)에 있습니다.
+
+### 운영자 터미널
+
+운영자 터미널은 직렬 포트에서 명령을 입력해 볼트와 대화하는 작은 태스크입니다. 선택 사항이며 기본으로는 꺼져 있습니다. 커널 크레이트의 feature 두 개로 선택하며, feature는 더하기만 합니다.
+
+| Feature | 추가하는 것 |
+| --- | --- |
+| `console-input` | 콘솔 UART용 커널 수신 경로와 시스템 콜 `CONSOLE_READ`. 동작하려면 콘솔 드라이버 feature가 필요함. 수신은 PL011과 SBSA UART에만 있으므로 16550 콘솔에는 출력만 있고 입력은 없음 |
+| `terminal` | 루트 태스크 이미지 안의 터미널 태스크로, 자가 테스트 뒤에 서비스로 시작함. `console-input`을 켬. `vault`를 포함하면 터미널이 볼트의 운영자가 되고, `vault-ed25519`를 포함하면 Ed25519 키를 만들 수 있음 |
+
+`console-input` 없이 빌드한 이미지에는 수신 코드도 `CONSOLE_READ`도 새 로그 줄도 없습니다. `terminal` 없이 빌드한 이미지에는 터미널 코드가 없습니다. 다음과 같이 빌드하고 실행할 수 있습니다.
+
+```sh
+$ cargo build -p k0-kernel --features console,terminal,vault-ed25519
+$ cargo run -p k0-kernel --features console,terminal,vault-ed25519
+```
+
+`cargo run`은 직렬 포트를 내 터미널에 연결해 QEMU를 시작합니다. 이때 QEMU 자신의 이스케이프 키는 `Ctrl-A`입니다(`Ctrl-A`를 누른 다음 `X`로 QEMU 종료). 따라서 `Ctrl-A`는 K0에 전달되지 않습니다.
+
+자가 테스트가 끝나면 루트 태스크가 볼트를 시작해 부트 시드를 넘기고, 터미널과 똑같이 연결한 적대적 태스크 둘을 돌리고(둘 다 거부되어 폴트로 끝나야 함), 관리자 케이퍼빌리티를 버린 뒤 터미널을 시작합니다. 부트 로그에는 `root: vault seeded`, `root: terminal console filter [...]`, `root: terminal wiring holds`, `k0: task fault` 두 줄, `root: service started`, 그다음 배너가 나옵니다. 입력 경로가 없는 머신에서는 `root: no console input, terminal not started`가 나옵니다. 처음 읽은 뒤에는 주기적인 `k0: tick N` 줄이 멈추고, `k0: tick lines off (console input in use)` 한 줄이 그 사실을 알립니다. 다음 세션에서 모든 명령은 `ok` 또는 `err ` 중 정확히 한 줄로 끝납니다.
+
+```
+K0 operator console, type 'help'
+k0> vault status
+state=seeded
+alg=none
+selftest=passed
+seed=rng-seed
+validated=no
+ok
+k0> vault keygen ed25519
+state=ready
+alg=ed25519
+ok
+k0> vault pubkey
+pubkey=<32 hex characters>
+ <32 hex characters>
+ok
+k0> vault zeroize
+hint=type 'vault zeroize confirm' to erase the key
+err confirm-required
+k0>
+```
+
+값은 `name=value` 형태로 출력됩니다. 화면 프롬프트는 `k0> `입니다. 다음 표의 첫 열이 입력하는 명령입니다.
+
+| 명령 | 인자 | 하는 일 |
+| --- | --- | --- |
+| `help` | | 명령 목록을 출력함 |
+| `vault status` | | 볼트 상태를 출력함(아래 참고) |
+| `vault pubkey` | | 공개 키를 출력함 |
+| `vault keygen ` | `ed25519` | 보관 중인 시드로 고른 알고리즘의 키를 만들고 시드를 지움 |
+| `vault zeroize confirm` | | 키를 지움. `vault zeroize`만 입력하면 `hint=type 'vault zeroize confirm' to erase the key`와 `err confirm-required`를 출력함 |
+
+`vault status`는 `state=fresh|seeded|ready|zeroized|failed`, `alg=none|ed25519`, `selftest=passed|failed`, `seed=none|rng-seed|rndr|rng-seed+rndr`, `validated=no`를 출력합니다. `seed=rng-seed`는 바이트가 있었다는 뜻이지 예측할 수 없다는 뜻이 아닙니다. 구현이 어떤 종류의 검증도 받지 않았으므로 `validated=no`는 항상 출력됩니다. `vault pubkey`는 `pubkey=`와 16진수 32자를 출력하고, 7칸 들여쓴 둘째 줄에 나머지 32자를 출력합니다. 볼트는 부팅 한 번에 키를 하나만 만듭니다. `vault keygen`을 한 번 더 하면 `err key-exists`가 나오고, `vault zeroize confirm` 뒤에는 재부팅해야 합니다. `vault` feature가 없으면 `help`는 `help`만 나열하고 `vault ...`는 `err no-vault`로 답합니다.
+
+다음 표의 키는 입력 중인 줄에 작용합니다.
+
+| 키 | 효과 |
+| --- | --- |
+| Enter(CR 또는 LF) | 줄을 실행함. 한 줄은 최대 64자이며 출력 가능한 ASCII만 허용함 |
+| Backspace 또는 DEL | 한 글자를 지움 |
+| `Ctrl-C` 또는 `Ctrl-U` | 줄을 취소함(`^C` 또는 `^U`로 표시) |
+| ESC 시퀀스(방향키) | 무시함 |
+
+프롬프트가 나오기 전에 UART에 도착한 바이트는 버려집니다. 입력이 유실되면(FIFO 오버런, 브레이크, 프레이밍 또는 패리티 오류) 다음 줄 끝까지 모두 버리고 명령은 `err input-lost`로 답합니다. 전달은 됐지만 제때 응답받지 못한 keygen 또는 zeroize는 `hint=run 'vault status' to see whether it took effect`를 덧붙입니다. 다음 표의 오류 이름은 `err ` 뒤에 나오는 것입니다.
+
+| 오류 | 뜻 |
+| --- | --- |
+| `unknown-command` | 모르는 명령 |
+| `bad-argument` | 인자가 틀렸거나 빠짐 |
+| `line-too-long` | 한 줄이 64자를 넘음 |
+| `input-lost` | 줄이 끝나기 전에 입력이 유실됨 |
+| `confirm-required` | `confirm` 없는 `vault zeroize` |
+| `denied` | 운영자에게 허용되지 않은 동작 |
+| `no-vault` | 이미지에 볼트가 없음 |
+| `no-key` | 볼트에 키가 없음 |
+| `key-exists` | 볼트가 이번 부팅에서 이미 키를 만듦 |
+| `no-entropy` | 부트 시드에 엔트로피가 없음 |
+| `unsupported-algorithm` | 이 이미지에 없는 알고리즘 |
+| `zeroized` | 키가 지워짐. 재부팅이 필요함 |
+| `vault-failed` | 볼트가 실패해 시드와 키를 지움 |
+| `vault-timeout` | 볼트가 제때 응답하지 않음 |
+
+> [!WARNING]
+> 직렬 포트에는 인증이 없습니다. 포트를 쥔 사람이 곧 운영자이며, 키 삭제를 포함해 운영자의 네 가지 동작(`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`)을 그대로 할 수 있습니다. 운영자는 서명을 받을 수 없고, 시드를 넘길 수 없으며, 정책을 바꿀 수 없습니다.
+
+계속 유효한 한계와 다루지 않는 부분은 다음과 같습니다.
+
+- **커널 코드**: 수신 코드는 EL1에서 실행됩니다. 작고 바이트를 해석하지 않지만, 외부 당사자가 구동하는 커널 코드입니다. 사용자 공간 드라이버에는 장치 및 인터럽트 위임이 필요한데, K0에는 그것이 없습니다.
+- **타이밍**: 외부 당사자가 이제 태스크가 도는 동안 인터럽트를 일으킬 수 있고(읽는 쪽이 상한을 정함), 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 됩니다. 다른 태스크가 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널은 분석하지 않았습니다.
+- **지연**: 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱입니다.
+- **하드웨어**: 16550 콘솔에는 입력이 없습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU로 실행되지 않고 가짜 UART를 쓰는 호스트 테스트로만 다룹니다. UART 원인 없이 발생하는 인터럽트 선을 끊는 동작도 호스트 테스트로만 다룹니다. 플러드 상황에서 커널이 쓰는 시간을 머신에서 측정하는 테스트는 없습니다. 실제 하드웨어에서는 아무것도 돌려 보지 않았습니다.
+- **화면**: 입력 중에 커널 줄이 나타나면 화면의 줄은 갈라지지만 버퍼는 온전하며, Enter는 버퍼 전체를 실행합니다. `Console` 출력이 있는 태스크는 여전히 커널이나 루트 태스크 줄처럼 보이는 줄을 출력할 수 있고, 접두어를 인증하는 것은 없습니다. 터미널은 추가로 자기 현재 줄 안을 지울 수 있습니다.
+- **붙잡힌 바이트**: "프롬프트 전에 버림"은 UART에 도착한 바이트를 말합니다. 바이트를 붙잡아 두는 에뮬레이터나 어댑터는 나중에 전달합니다(QEMU가 그렇습니다).
+- **서비스**: 서비스 모드에는 서명 클라이언트가 아직 없습니다. 키는 만들어지고 보이지만 다른 태스크가 사용하지 않습니다. 터미널과 볼트는 죽어도 다시 시작되지 않습니다. 루트 태스크는 신뢰 대상입니다.
+- **부트 로그**: 터미널 출력은 메모리 부트 로그의 사용자 몫을 소모합니다. 그 몫이 차면 이후 태스크 출력은 거기에 기록되지 않습니다.
+- **볼트**: 이전의 한계는 모두 유지됩니다. 구현은 검증을 받지 않았고, 부채널 분석이 없으며, 키는 승인된 난수 비트 생성기에서 나오지 않고, 영속성도 PQC도 없습니다. 볼트와 터미널의 가용성은 보호되지 않습니다.
+
+콘솔 인터럽트 번호가 틀려도 잃는 것은 입력 경로뿐이며, 부트 로그에 `k0: console input off (...)`가 나옵니다. 이유는 `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range`, `interrupt not available`입니다. UART 원인 없이 계속 발생하는 인터럽트 선은 8번 진입한 뒤 `k0: console input off (interrupt N fired without a uart cause)`와 함께 꺼집니다. 입력이 켜지면 부트 로그에 `k0: console input on (pl011 irq 33)`이 나옵니다. 인터럽트 번호는 플랫폼 줄(`k0: platform con=pl011@0x9000000,irq33 ...`)에 들어 있으므로, 이번 변경 이전에 만든 `K0_PIN`은 더 이상 맞지 않아 다시 만들어야 합니다.
## UEFI로 부팅
@@ -307,9 +407,9 @@ $ tools/qemu-boot-test.sh # QEMU에서 부팅하
$ tools/boot-matrix.sh # 지원하는 구성을 전부 부팅(16 KiB 이미지, 고정 이미지, UEFI 로더 이미지도 빌드함)
```
-- `tools/host-test.sh`는 호스트 테스트 276개를 실행합니다(x86-64 컴퓨터에서는 190개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 276개는 `k0-abi` 14개, `k0-cap` 42개, `k0-boot` 82개, `k0-efi` 32개, `k0-vault` 20개(Ed25519를 포함하면 13개, 없으면 7개), `k0-mm` 43개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, x86-64의 개수는 그 86개를 뺀 것입니다.
+- `tools/host-test.sh`는 호스트 테스트 354개를 실행합니다(그 밖의 호스트에서는 268개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 354개는 `k0-abi` 15개, `k0-cap` 44개, `k0-boot` 85개, `k0-efi` 33개, `k0-conin` 15개, `k0-vault` 31개(Ed25519를 포함하면 20개, 없으면 11개), `k0-term` 45개(`vault` feature를 포함하면 24개, 없으면 21개), `k0-mm` 43개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, 그 밖의 호스트의 개수는 그 86개를 뺀 것입니다.
- `tools/qemu-boot-test.sh`는 커널을 부팅하고, 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 줄이 하나라도 나오면 실패하고, 일부러 일으킨 폴트 줄의 개수를 정확히 맞춘 뒤 QEMU를 끕니다. 루트 태스크의 타임아웃 테스트는 실제 타이머 틱을 기다리므로, 부팅 한 번이 그 테스트가 생기기 전보다 약 4초 더 걸립니다. `root: teardown tests pass`와 `root: timeout tests pass` 사이의 틱 줄도 세어 4개 이상을 요구하는데, 이것이 타임아웃이 일찍 끝나지 않는지 확인하는 방법입니다. 성공하면 `boot-test: pass`를 출력하고 전체 로그를 `target/qemu-boot-test.log`에 남깁니다. 머신은 앞의 `K0_QEMU_*` 변수에서 가져옵니다. 맞는 크기의 untyped 영역이 없는 메모리 배치에서는 루트 태스크가 재사용 시험을 건너뛰므로, 그때는 `K0_BOOT_REUSE=skip`을 받습니다. 커널 줄을 **직렬 포트**에서 읽으므로 콘솔 드라이버가 있는 이미지가 필요합니다. 콘솔 없는 이미지는 뒤의 "콘솔 없는 이미지 시험"을 보세요. 직렬 로그에 커널 줄이 하나도 없으면 콘솔 feature 없이 빌드한 커널이 아닌지 알려 주는 힌트를 출력합니다.
-- `tools/boot-matrix.sh`는 K0가 지원한다고 말하는 **구성마다** 커널을 부팅해서 결과를 확인합니다. GICv3와 GICv2의 QEMU virt를 EL1과 EL2에서 부팅하고, CPU 모델 세 가지, 코어 4개, 16 KiB 이미지, 다른 적재 주소, `xlnx-versal-virt`, 고정 이미지, 서명 오라클이 있는 이미지도 부팅합니다. 이미지가 물리 타이머를 건드리지 않는지는 정적으로 검사합니다. 행렬은 HVF가 있는 Mac에서 61행, CI에서 51행입니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다.
+- `tools/boot-matrix.sh`는 K0가 지원한다고 말하는 **구성마다** 커널을 부팅해서 결과를 확인합니다. GICv3와 GICv2의 QEMU virt를 EL1과 EL2에서 부팅하고, CPU 모델 세 가지, 코어 4개, 16 KiB 이미지, 다른 적재 주소, `xlnx-versal-virt`, 고정 이미지, 서명 오라클이 있는 이미지도 부팅합니다. 이미지가 물리 타이머를 건드리지 않는지는 정적으로 검사합니다. 행렬은 HVF가 있는 Mac에서 76행, CI에서 65행입니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다.
콘솔 행은 콘솔 feature를 확인합니다. 다음 표는 콘솔 행과 확인하는 내용입니다.
@@ -336,7 +436,24 @@ $ tools/boot-matrix.sh # 지원하는 구성
거부해야 하는 구성에서는 커널의 사유를 메모리에 남은 부트 로그에서 읽고, 로더의 사유는 직렬 로그에서 읽습니다. 이런 구성으로 `cortex-a72`에서의 16 KiB 커널과 한 바이트를 바꾼 커널이 있습니다.
-Apple Silicon Mac에서는 `K0_MATRIX_HVF=1 tools/boot-matrix.sh`로 QEMU의 HVF 가속기를 통해 실제 CPU 코어에서 커널을 (UEFI 로더를 거치는 경우도 포함해) 돌리는 행을 더할 수 있습니다. 콘솔 없는 이미지용으로는 `hvf-quiet`이, 오라클이 있는 이미지용으로는 `hvf-vault`가 있습니다.
+Apple Silicon Mac에서는 `K0_MATRIX_HVF=1 tools/boot-matrix.sh`로 QEMU의 HVF 가속기를 통해 실제 CPU 코어에서 커널을 (UEFI 로더를 거치는 경우도 포함해) 돌리는 행을 더할 수 있습니다. 콘솔 없는 이미지용으로는 `hvf-quiet`이, 오라클이 있는 이미지용으로는 `hvf-vault`가, 터미널 이미지용으로는 `hvf-term`이 있습니다.
+
+입력 및 터미널 행은 수신 경로와 터미널을 확인합니다. 다음 표에서 `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq` 행은 `console-input`을 포함하고 터미널은 없는 이미지를 부팅합니다.
+
+| 행 | 확인하는 것 |
+| --- | --- |
+| `input-only` | `console-input`을 포함하고 터미널이 없는 이미지 |
+| `input-gicv2` | GICv2에서 같은 이미지 |
+| `input-16550` | 16550 드라이버만 있는 이미지. 입력이 꺼지고(`console not attached`) 로그에 그렇게 남음 |
+| `input-bad-irq` | 디바이스 트리의 인터럽트 번호가 범위를 벗어나도 입력 경로만 잃는지(`interrupt number out of range`) |
+| `input-symbols` | 정적 검사. `console-input` 없는 이미지에 수신 코드도 `CONSOLE_READ`도 새 로그 줄도 없음 |
+| `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k` | 터미널 이미지를 `tools/term-test.py`로 실행. 기본 CPU, `max` CPU, EL2, GICv2, 16 KiB 이미지 |
+| `term-no-vault` | 볼트가 없는 터미널. `help`가 `help`만 나열함 |
+| `term-no-alg` | `vault`는 있고 알고리즘은 없는 터미널 |
+| `term-uefi`, `term-uefi-acpi` | UEFI 로더를 거치는 터미널 이미지(디바이스 트리 경로와 ACPI 경로) |
+| `hvf-term` | HVF에서의 터미널 이미지(Mac 전용) |
+
+`tools/term-test.py <이미지>`는 QEMU의 직렬 포트를 파이프에 연결해 이미지를 부팅하고 정해진 세션을 실행합니다. 모든 명령과 오류, 지우기와 취소, CR LF, ESC 시퀀스, 너무 긴 줄, 키 생성, 공개 키 형식, zeroize, 줄 끝 없는 200 kB, 연속 2000줄, 직렬 브레이크를 다룹니다. `tools/qemu-boot-test.sh`는 이미지가 보여야 할 것을 알려 주는 `K0_BOOT_INPUT=on|off`와 `K0_BOOT_SERVICE=vault|plain|none`, 그리고 판정만 하는 모드 `K0_BOOT_JUDGE`도 이해합니다. 터미널 이미지는 터미널 없는 같은 이미지보다 `k0: task fault` 줄이 두 개 더 나오므로(볼트 없이 8개, 볼트와 함께 10개) `K0_BOOT_FAULTS`를 사용하세요.
### 콘솔 없는 이미지 시험
@@ -397,3 +514,7 @@ GitHub도 풀 리퀘스트와 `main` 푸시가 있을 때마다 이 테스트를
| `build-loader: kernel ELF not found` | 먼저 `cargo build -p k0-kernel --features console --offline`로 커널을 빌드하세요 |
| `build-loader: embedding a kernel with: k0: console drivers [none]` | 로더가 콘솔 없는 커널을 품게 됩니다. 로더는 자기 줄을 계속 출력하고, 그 뒤로 커널은 아무것도 출력하지 않습니다. 출력이 필요하면 `--features console`로 커널을 빌드하고 `tools/build-loader.sh`를 다시 실행하세요 |
| 화면에 펌웨어 메시지나 펌웨어 메뉴만 나옴 | 펌웨어가 로더를 시작하지 못했거나, 로더가 거부해서 펌웨어가 다음으로 넘어간 것입니다. `k0-loader:` 줄이 있는지 보세요. 없다면 `.efi` 파일이 있는지, `K0_QEMU_ESP`를 사용했다면 드라이브가 보이는지 확인하세요 |
+| 터미널에 `k0> ` 프롬프트가 나오지 않음 | 이미지를 `terminal`(과 `console-input`) 없이 빌드했거나, 로그에 `k0: console input off (...)` 또는 `root: no console input, terminal not started`가 있습니다. `--features console,terminal,vault-ed25519`로 빌드하고 부트 로그에서 이유를 읽으세요 |
+| 입력해도 반응이 없거나 `Ctrl-A`가 전달되지 않음 | `cargo run`에서는 QEMU가 `Ctrl-A`를 자기 몫으로 씁니다. 16550 콘솔에는 입력이 전혀 없습니다 |
+| 터미널 이미지에서 `boot-test`가 `k0: task fault` 줄 수 때문에 실패 | 그 이미지는 터미널 없는 이미지보다 2개 더 출력합니다(8개 또는 10개). `K0_BOOT_FAULTS`를 사용하세요 |
+| 이전에 만든 `K0_PIN`이 더 이상 맞지 않음 | 플랫폼 줄에 이제 콘솔 인터럽트(`irq33`)가 들어 있습니다. 핀을 다시 만드세요 |
diff --git a/assets/terminal-flow.svg b/assets/terminal-flow.svg
new file mode 100644
index 0000000..44e9405
--- /dev/null
+++ b/assets/terminal-flow.svg
@@ -0,0 +1,60 @@
+
diff --git a/assets/terminal-flow_KR.svg b/assets/terminal-flow_KR.svg
new file mode 100644
index 0000000..5e542aa
--- /dev/null
+++ b/assets/terminal-flow_KR.svg
@@ -0,0 +1,60 @@
+
diff --git a/ci/threat_model.md b/ci/threat_model.md
index f9df62f..767a6a4 100644
--- a/ci/threat_model.md
+++ b/ci/threat_model.md
@@ -1,6 +1,6 @@
# Threat model: K0
-K0 is a capability-based microkernel for AArch64, written in Rust `no_std` in the style of seL4 and licensed under PolyForm Noncommercial 1.0.0. The kernel runs at EL1. The only user-space code today is the root task, which runs at EL0 and doubles as the self-test harness. Console output is optional: it exists only in an image built with a console feature (see "Optional console output" in `SECURITY.md`). One generic image finds the console, the interrupt controller (GICv2 or GICv3) and the timer in the device tree at boot, and it may be entered at EL1 or at EL2. The 4 KiB granule is the default and the 16 KiB granule is a build option. It can also be started by a UEFI loader (`loader/`) that embeds the kernel. Only QEMU machines can be exercised in this image, with the EDK2 firmware package installed for the loader.
+K0 is a capability-based microkernel for AArch64, written in Rust `no_std` in the style of seL4 and licensed under PolyForm Noncommercial 1.0.0. The kernel runs at EL1. The user-space code is the root task, which runs at EL0 and doubles as the self-test harness, and the vault and terminal tasks that it starts in images built with those features. Console output is optional: it exists only in an image built with a console feature (see "Optional console output" in `SECURITY.md`). Serial input and the operator terminal are optional too: they exist only in an image built with the feature `console-input` or `terminal`, and an image without them has no input code at all (see "Serial input and the operator terminal" in `SECURITY.md`). One generic image finds the console, the interrupt controller (GICv2 or GICv3) and the timer in the device tree at boot, and it may be entered at EL1 or at EL2. The 4 KiB granule is the default and the 16 KiB granule is a build option. It can also be started by a UEFI loader (`loader/`) that embeds the kernel. Only QEMU machines can be exercised in this image, with the EDK2 firmware package installed for the loader.
Read `SECURITY.md` at the repository root first. It describes the isolation model of the released version 0.1.0, the unreleased isolation work on the current `main` branch, and the issues that are already known. This model describes the current `main` branch.
@@ -15,7 +15,8 @@ Trust boundaries, from least to most trusted:
5. **The root task image** is embedded in the kernel at build time together with its SHA-256 (`crates/k0-boot/build.rs`, `verify_root_task`). It is part of the trusted computing base today. The hash detects corruption, not a malicious image; signature verification is a documented TODO.
6. **The UEFI loader** (`loader/`, `crates/k0-efi`) sits between the firmware and the kernel, and it is in scope. Its inputs come from firmware and are treated as wrong or hostile data: the UEFI memory map, the firmware device tree or, without one, the ACPI static tables (RSDP, XSDT, MADT, GTDT, SPCR) from the configuration table, the random number protocol and the embedded kernel image. It decides which memory the kernel sees as RAM, so a mistake there hands firmware memory to user space without any kernel bug. Entry path: `loader/src/load.rs` (flow) -> `crates/k0-efi/src/prepare.rs` (plan, rewrite, self-check with the kernel's own parser, discovery, `Platform::validate` and `boot_window`) -> `loader/src/handoff.rs` (cache flush, MMU off, jump). The pure logic is in `memmap.rs`, `fdtw.rs`, `verify.rs` and `image.rs` of `k0-efi`, none of it `unsafe`. The loader does not verify a signature: its SHA-256 over the embedded kernel is a corruption check, and authenticity is the firmware's Secure Boot job.
-7. **The vault task and its clients** (optional, features `vault` and `vault-ed25519` of `k0-kernel`). The vault holds one Ed25519 key in its own address space. Clients send requests over one endpoint with a badge that the kernel delivers; the badge selects the role (admin, signer, reader) in a policy fixed at build time. Everything in a request (operation, algorithm, length, message, nonce) is attacker controlled, and the vault reads the body once into a private buffer. The root task builds the vault and is trusted, so a root task that reads the vault is not a finding. Entry path: `userspace/k0-vault` (`server`, `proto`, `provider`) and the wiring and self-test in `userspace/root-task/src/oracle.rs`. The Ed25519 code is the vendored crate `ed25519-dalek` 2.2.0, which has no validation of any kind.
+7. **The vault task and its clients** (optional, features `vault` and `vault-ed25519` of `k0-kernel`). The vault holds one Ed25519 key in its own address space. Clients send requests over one endpoint with a badge that the kernel delivers; the badge selects the role (admin, operator, signer, reader) in a policy fixed at build time. The operator is the terminal of boundary 8. Everything in a request (operation, algorithm, length, message, nonce) is attacker controlled, and the vault reads the body once into a private buffer. The root task builds the vault and is trusted, so a root task that reads the vault is not a finding. Entry path: `userspace/k0-vault` (`server`, `proto`, `provider`) and the wiring and self-test in `userspace/root-task/src/oracle.rs`. The Ed25519 code is the vendored crate `ed25519-dalek` 2.2.0, which has no validation of any kind.
+8. **The serial line and the operator terminal** (optional, features `console-input` and `terminal` of `k0-kernel`). Every byte that arrives on the console UART is attacker controlled, and so is its timing. The kernel's receive path runs at EL1 in interrupt context: it puts bytes into a ring of 256 bytes and never interprets them, and the console interrupt is the second interrupt source after the timer. `CONSOLE_READ` hands one byte at a time to the one task that holds a `Console` capability with the read right (R). The terminal task (`userspace/k0-term`) parses lines in its own address space and, when the vault is built in, acts as the vault's operator: it can ask for `STATUS`, `PUBLIC_KEY`, `KEYGEN` and `ZEROIZE`, nothing else. There is no authentication on the serial line, so whoever reaches it is the operator, and erasing the key is a denial of service by design. Entry path: `crates/k0-arch/src/conin.rs` and `crates/k0-conin` (receive logic), `crates/k0-ipc/src/console.rs` and `kernel/src/syscall.rs` (`CONSOLE_READ`, the rights of `Console`), `userspace/k0-term` (`lib.rs`, `wire.rs`) and its wiring in `userspace/root-task/src/oracle.rs`. The interrupt number comes from the device tree or the ACPI SPCR table, which are inputs of boundary 4 and 6.
Out of the kernel's control and therefore trusted: the rest of the boot chain (firmware, any other boot loader, the hypervisor), the integrity of the kernel image itself, and the hardware. Under UEFI the firmware is trusted to run honestly, but the loader must still not trust what it describes.
@@ -36,6 +37,8 @@ Highest value, all in scope:
- `userspace/k0-vault` and `userspace/root-task/src/oracle.rs`: the request state machine (`Vault::handle`), the badge policy, the provider boundary around the crypto crate, the entropy rule (`NO_ENTROPY`), the rights of the request and response frames, and the nonce handshake. Reports that are welcome: a key disclosed to a client, a policy bypass (an operation a role must not have), and a reply that reaches the wrong caller.
+- The input path: `crates/k0-conin` (ring, drain, gate and loss marking), `crates/k0-arch/src/conin.rs` and the PL011 and SBSA receive code in `earlycon/uart.rs`, the receive interrupt handling in `irq.rs`, the `Console` rights (R and W) and the output filter, `CONSOLE_READ` and its waiter (`crates/k0-ipc/src/console.rs`), and `userspace/k0-term` with its wiring check in `oracle.rs`. Reports that are welcome: a byte stream that makes the kernel misbehave, interrupt work that is not bounded by the reader, a wake-up of the wrong task, a `Console` right that is gained instead of removed, and an operator operation beyond the four listed.
+
Lower value:
- `userspace/root-task` (other than `oracle.rs`): the trusted root task and test harness. Bugs here are not kernel vulnerabilities, but it is the right place to write reproducers.
@@ -45,12 +48,12 @@ Lower value:
## How to exercise it
-- Build: `cargo build -p k0-kernel --features console --offline` (generic 4 KiB image with console, dev profile with debug info; `panic = "abort"` in every profile). Input and output are Cargo features that only add and are never in `default`, so every command names them. `cargo build -p k0-kernel --offline` builds an image without console: it has no UART driver, never maps the console page and prints nothing on the serial port, and `tools/qemu-boot-test.sh` cannot judge it from the serial log (it prints a hint). All feature sets write the same ELF path, so give an image without console its own directory, for example `--target-dir target/quiet`. The 16 KiB image is `cargo build -p k0-kernel --offline --no-default-features --features granule-16k,console --target-dir target/g16`. It boots only on a CPU model with 16 KiB pages: `K0_QEMU_CPU=max tools/qemu-boot-test.sh target/g16/aarch64-unknown-none-softfloat/debug/k0-kernel`. `grep -a 'k0: console drivers' ` tells which I/O an image was built with.
+- Build: `cargo build -p k0-kernel --features console --offline` (generic 4 KiB image with console, dev profile with debug info; `panic = "abort"` in every profile). Input and output are Cargo features that only add and are never in `default`, so every command names them. The operator terminal image is `cargo build -p k0-kernel --features console,terminal,vault-ed25519`, and `cargo run -p k0-kernel --features console,terminal,vault-ed25519` boots it under QEMU with the serial port on the terminal (QEMU's own escape key is Ctrl-A, so it never reaches K0 there). `tools/term-test.py ` boots an image with QEMU's serial port on pipes and runs a scripted session (every command and error, a line that is too long, 200 kB without a line end, 2000 lines in a row, a serial break), and `tools/qemu-boot-test.sh` takes `K0_BOOT_INPUT=on|off` and `K0_BOOT_SERVICE=vault|plain|none`. `cargo build -p k0-kernel --offline` builds an image without console: it has no UART driver, never maps the console page and prints nothing on the serial port, and `tools/qemu-boot-test.sh` cannot judge it from the serial log (it prints a hint). All feature sets write the same ELF path, so give an image without console its own directory, for example `--target-dir target/quiet`. The 16 KiB image is `cargo build -p k0-kernel --offline --no-default-features --features granule-16k,console --target-dir target/g16`. It boots only on a CPU model with 16 KiB pages: `K0_QEMU_CPU=max tools/qemu-boot-test.sh target/g16/aarch64-unknown-none-softfloat/debug/k0-kernel`. `grep -a 'k0: console drivers' ` tells which I/O an image was built with.
- Run: `tools/qemu-virt-runner.sh target/aarch64-unknown-none-softfloat/debug/k0-kernel`, which is what `cargo virt` (alias of `cargo run -p k0-kernel --features console`) does. A plain `cargo run -p k0-kernel` boots the image without console, and the runner then prints `runner: this kernel has no console driver and prints nothing here (build with --features console to see output)`. It converts the ELF to a raw image with `llvm-objcopy` and boots `qemu-system-aarch64 -machine virt,gic-version=3 -cpu cortex-a72 -smp 1 -m 512M -nographic`. `K0_QEMU_MACHINE`, `K0_QEMU_CPU`, `K0_QEMU_SMP` and `K0_QEMU_MEM` change the machine, for example `K0_QEMU_MACHINE=virt,gic-version=2` or `K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on` (entry at EL2). `tools/boot-matrix.sh` runs every configuration that K0 calls supported. The kernel never exits: once the root task finishes its self-tests it yields forever and an image with a console driver prints `k0: tick N` on the console once a second (every image logs only the first 4 tick lines in the boot log). Wrap every run in `timeout`, or use `tools/qemu-boot-test.sh`, which checks the expected log lines in order, requires an exact number of `k0: task fault` lines and exactly one `k0: unknown syscall` line, and stops QEMU once they appear.
-- A healthy boot log is in `/src/bootcheck.log`, captured when this image was built. The lines that matter are `k0: w^x checks pass`, `k0: user w^x checks pass`, `root: retype/map tests pass`, `root: child exit test pass`, `root: ipc tests pass`, `root: fault isolation tests pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: timeout tests pass`, `root: revocation tests pass`, `root: kernel reserve tests pass` and `root: sched tests pass`. Every image also prints `k0: dtb seeds wiped B` (40B on QEMU virt) and `root: boot seed from rng-seed bytes ...`. An image built with the feature `vault` also prints `root: oracle tests pass` and two more `k0: task fault` lines (8 instead of 6).
+- A healthy boot log is in `/src/bootcheck.log`, captured when this image was built. The lines that matter are `k0: w^x checks pass`, `k0: user w^x checks pass`, `root: retype/map tests pass`, `root: child exit test pass`, `root: ipc tests pass`, `root: fault isolation tests pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: timeout tests pass`, `root: revocation tests pass`, `root: kernel reserve tests pass` and `root: sched tests pass`. Every image also prints `k0: dtb seeds wiped B` (40B on QEMU virt) and `root: boot seed from rng-seed bytes ...`. An image built with the feature `vault` also prints `root: oracle tests pass` and two more `k0: task fault` lines (8 instead of 6). An image built with the feature `terminal` shows two more `k0: task fault` lines than the same image without it (the hostile wiring checks: 8 in total without `vault`, 10 with it), `root: terminal wiring holds` and `root: service started`. An image with `console-input` prints `k0: console input on (pl011 irq 33)` or `k0: console input off ()` and `root: console input tests pass`. When a task first reads console input the `k0: tick N` lines stop after `k0: tick lines off (console input in use)`.
- Reproducers: the root task (`userspace/root-task/src/main.rs`) is the only EL0 image and already contains the test harness and thin `sys*` wrappers around `svc`. Add a test there; when the reproducer needs its own thread, build a task with its own CNode and address space (`RETYPE`, `TCB_CONFIGURE`, `TCB_RESUME`), which then runs code from the root task image, rebuild and run. `crates/k0-boot/build.rs` rebuilds and re-embeds the root task automatically.
- UEFI loader: `cargo build -p k0-kernel --features console --offline`, then `tools/build-loader.sh`, which embeds that kernel into the loader, prints `build-loader: embedding a kernel with: k0: console drivers [...]` so that nobody embeds a silent kernel unknowingly, and prints the path (`.efi`). `tools/qemu-virt-runner.sh .efi` boots it through EDK2 with `-machine virt,gic-version=3,acpi=off` (firmware from `K0_QEMU_FIRMWARE`, else Homebrew's `edk2-aarch64-code.fd`, else `/usr/share/AAVMF/AAVMF_CODE.fd`, which is the Debian package in this image). `K0_QEMU_ESP=1` boots it from a FAT drive instead of `-kernel`, and `K0_QEMU_EXTRA` passes extra QEMU arguments. `tools/qemu-boot-test.sh .efi` judges the run from the loader's first line, `k0-loader: start`, so firmware messages before it do not count. The loader prints `k0-loader: ...` lines before the kernel's, and a refusal reads `k0-loader: refused: `. `K0_QEMU_MACHINE=virt,gic-version=3` (ACPI on, no device tree) boots through the static tables. `tools/pe-check.py .efi` checks the PE form and the order of the cache and MMU instructions. `K0_LOADER_FEATURES=refuse-halt tools/build-loader.sh` builds a loader that parks instead of returning to the firmware. The UEFI rows of `tools/boot-matrix.sh` (`uefi-*`) cover GICv2 and GICv3 at EL1 and EL2, the max CPU, 4 cores, the 16 KiB image, a firmware RNG, the FAT drive, the ACPI rows (`uefi-acpi-*`) and the refusals.
-- Host tests: `tools/host-test.sh` runs the unit tests of `k0-abi`, `k0-cap`, `k0-boot` and `k0-efi` on any host and those of `k0-mm` on AArch64 hosts. `k0-cap` includes a model test over random retype, copy, move, delete and revoke sequences, and `k0-mm` runs the real user page table walkers and the address space registry. The DTB parser has a deterministic mutation fuzzer: `K0_FUZZ_ITERS=5000000 cargo test --release --offline --target "$(rustc -vV | sed -n 's/^host: //p')" -p k0-boot fuzz -- --nocapture`. A failing case prints `K0_FUZZ_CASE=0x...`, which replays it and dumps the input. The fuzzer's DTB builder in `crates/k0-boot/src/fdt/builder.rs` is a convenient way to write a crafted DTB for a reproducer. `k0-efi` has three more deterministic fuzzers (`fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees`, `fuzz_prepare_end_to_end`) with the same `K0_FUZZ_ITERS`, `K0_FUZZ_SEED` and `K0_FUZZ_CASE` variables: run them with `-p k0-efi fuzz`. The unit tests of `k0-efi` use measured firmware memory maps as vectors; a crafted memory map or firmware DTB is the natural reproducer for the loader.
+- Host tests: `tools/host-test.sh` runs the unit tests of `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-vault` and `k0-term` on any host and those of `k0-mm` on AArch64 hosts. `k0-cap` includes a model test over random retype, copy, move, delete and revoke sequences, and `k0-mm` runs the real user page table walkers and the address space registry. The DTB parser has a deterministic mutation fuzzer: `K0_FUZZ_ITERS=5000000 cargo test --release --offline --target "$(rustc -vV | sed -n 's/^host: //p')" -p k0-boot fuzz -- --nocapture`. A failing case prints `K0_FUZZ_CASE=0x...`, which replays it and dumps the input. The fuzzer's DTB builder in `crates/k0-boot/src/fdt/builder.rs` is a convenient way to write a crafted DTB for a reproducer. `k0-efi` has three more deterministic fuzzers (`fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees`, `fuzz_prepare_end_to_end`) with the same `K0_FUZZ_ITERS`, `K0_FUZZ_SEED` and `K0_FUZZ_CASE` variables: run them with `-p k0-efi fuzz`. The unit tests of `k0-efi` use measured firmware memory maps as vectors; a crafted memory map or firmware DTB is the natural reproducer for the loader.
- PAC, PAN and RNDR paths: the default `cortex-a72` model has none of them. `tools/qemu-boot-test.sh target/aarch64-unknown-none-softfloat/debug/k0-kernel -cpu max` (an image built with `--features console`) boots on a CPU that has all three.
- A boot that the kernel refuses before it has a console prints nothing, and an image without a console feature prints nothing on the serial port at all. The reason is in the boot log in memory: start QEMU with `K0_QEMU_MONITOR=` and read it with `tools/boot-log.py ` (the load address on QEMU `virt` is `0x40080000`).
- Debugging: append `-s -S` to the runner (`tools/qemu-virt-runner.sh -s -S`) and attach with `gdb-multiarch target/aarch64-unknown-none-softfloat/debug/k0-kernel -ex 'target remote :1234'`. `-d int,guest_errors` prints exception traces. `llvm-objdump -d` (from the pinned toolchain, linked into `/usr/local/bin`) disassembles both images.
@@ -63,6 +66,7 @@ Rate by what EL0 code can do to EL1 or, on the current `main` branch, to another
- **Critical**: any EL0 -> EL1 privilege escalation, and on the current `main` branch any break of task isolation (reading or writing another task's memory, using a slot or capability of another task, a revoked capability or stale mapping that still works). Executing attacker-chosen code at EL1; reading or writing kernel memory or arbitrary physical memory through a system call; obtaining a mapping, capability or object that the caller's slot arguments do not grant (bypassing a capability or permission check); mapping memory that is both writable and executable for EL0, or kernel memory into TTBR0; getting the kernel to restore EL1 state (mode, exception level, interrupt masks) that came from user input.
- **High**: memory-safety bugs in kernel code reachable from EL0, with or without a demonstrated exploit (out-of-bounds index, integer overflow or truncation in size or address arithmetic, stale raw pointers, aliasing `&mut`, unsound `unsafe`); a system call or fault sequence that halts the whole system (kernel panic, `exception_fatal`, an unbounded loop with interrupts masked, or a scheduler that cannot continue); missing TLB or cache maintenance that lets a task keep using memory after it was unmapped or retyped; kernel register or memory contents leaking to EL0 (registers not restored or cleared on the return path, uninitialised memory handed out by `retype` or `map`); checks that a race between the timer interrupt and a system call can bypass.
- **Loader findings** are rated by what the kernel ends up trusting. **Critical**: a memory map or firmware device tree that makes the loader pass the kernel a RAM range that includes memory firmware still uses (runtime or boot services memory, MMIO, a reservation) so that it can reach user space, or that makes the loader start a kernel image that fails its own check. **High**: memory-safety bugs in the loader, a refusal that is skipped (the loader boots on input it should refuse), or an `ExitBootServices` path that leaves the system in an undefined state. **Medium**: a panic or an overly cautious refusal on a valid map, a leak of memory the loader should have wiped, a plan that loses RAM beyond the stated policy. Findings that need hostile firmware are Low (see "Anything to leave alone").
+- **Input findings** are rated by what an outside party on the serial line gains. **Critical**: a byte stream or timing that gives code execution or memory access at EL1, or that makes a task do more than the operator's four operations. **High**: a stream that halts the machine or lets kernel work in interrupt context grow without the reader's bound; a wake-up or a byte delivered to a task that does not hold the read right. **Medium**: a stream that wedges the terminal or the input path until reboot. The lack of authentication on the serial line and the operator's power to erase the key are known (see "Anything to leave alone").
- **Medium**: malformed DTB input that panics, reads out of bounds, produces an unsafe memory map or gets a device mapped over memory that is handed out (the boot chain is trusted, so cap these at Medium unless they give code execution); exhaustion of kernel resources (for example untyped memory, TCB or endpoint objects; the kernel page tables and the address space registry are reserved at boot and no longer run out) by a single task that denies service to others without halting the kernel; scheduler starvation; mistakes in `write_bootinfo` beyond the known physical address exposure.
- **Low**: problems that need a misbehaving root task to trigger; `build.rs` issues with trusted source inputs; console formatting and diagnostic wording; hardening that is missing but has no exploitable consequence today.
- A root-cause analysis plus a patch is welcome at every level. A reproducer counts for more than a severity argument.
@@ -85,9 +89,10 @@ These are known, tracked in `SECURITY.md`, and are not new findings:
- DTB memory regions are not bounded by the physical address width (GHSA-hj3f-38h9-hrpj). The current `main` branch stops the boot on such a region; the advisory itself is still a draft.
- No KASLR: the kernel image always sits at the same virtual address. `write_bootinfo` exposes the physical addresses of `Untyped` regions to the root task.
- A wrong or hostile DTB can stop the boot, or point the console at another device that passes the checks (a 16550 and an SBSA UART have no identification register). An image without a console driver never maps or writes the console page, but it still refuses a device tree whose console node fails the checks. A pinned build (`K0_PIN`) compares values that come from the DTB, so it does not stop a hostile boot chain.
-- Signing oracle limits, all in `SECURITY.md` under "The signing oracle": the Ed25519 implementation is unvalidated and the key does not come from an approved random bit generator; no side-channel analysis; one key shared by all signers; no persistence, import, export or DRBG; the availability of the vault is not protected; the root task is trusted and could read the vault; only run in QEMU. The kernel zeroes the `rng-seed` and `kaslr-seed` bytes in the DTB once, right before it enters the root task; copies kept by firmware or the loader and live boot stack frames are not wiped.
+- Signing oracle limits, all in `SECURITY.md` under "The signing oracle": the Ed25519 implementation is unvalidated and the key does not come from an approved random bit generator; no side-channel analysis; one key shared by all signers, one key per boot; no persistence, import, export or DRBG; the availability of the vault is not protected; the root task is trusted and could read the vault; only run in QEMU. The kernel zeroes the `rng-seed` and `kaslr-seed` bytes in the DTB once, right before it enters the root task; copies kept by firmware or the loader and live boot stack frames are not wiped.
+- Serial input limits, all in `SECURITY.md` under "Serial input and the operator terminal": there is no authentication on the serial line, and the operator can erase the key (denial of service by design) but cannot sign, deliver a seed or change policy; the receive code runs at EL1 and a user-space driver would need device and interrupt delegation, which K0 does not have; an outside party can cause interrupts while tasks run (bounded by the reader), the reader learns arrival times finer than the tick and other tasks can notice the stolen time, a timing channel that has not been analysed; input waits behind running tasks (no priorities, up to a tick per ready task); a 16550 console has no input; the SBSA UART path, FIFO overruns, the receive timeout interrupt and the cut-off of an interrupt line without a UART cause are covered only by host tests with a fake UART; no test measures kernel time under a flood on a machine; "dropped before the prompt" counts bytes that reached the UART, and an emulator that holds bytes back delivers them later; a kernel line that appears while the operator types splits the screen line but not the buffer; the terminal can erase within its current line; no signing client exists in service mode; the terminal and the vault are not restarted if they die; terminal output counts against the user share of the in-memory boot log. Nothing ran on real hardware.
- The DTB pointer in `x0` is mapped read-only and read before any memory map exists. A boot loader that passes the address of a device makes the kernel read device registers as memory.
-- A task with a `Console` capability can print lines that look like kernel output (`k0: ...`), in the boot log and, in an image with a console driver, on the console. Its output is filtered for control bytes but not marked. That includes the `k0: console drivers [...]` line, so only its first occurrence, or the image file, identifies a build.
+- A task with a `Console` capability that has the write right can print lines that look like kernel output (`k0: ...`), in the boot log and, in an image with a console driver, on the console. Its output is filtered for control bytes (only a capability with the read right may also emit backspace) but not marked. That includes the `k0: console drivers [...]` line, so only its first occurrence, or the image file, identifies a build.
- Optional console output: an empty serial log shows only that no byte reached the serial port of QEMU virt (a PL011), not that no register was read; the symbol check runs on debug images and release (LTO) images without console are not booted; no image without console is booted through UEFI; the boot log in kernel memory is readable by anyone who can read RAM or attach a debugger. See "Optional console output" in `SECURITY.md`.
- A trap to EL2 after the kernel has dropped to EL1 parks the whole machine by design.
- PAC keys are shared between EL0 and EL1. No `pac-ret` code generation is enabled yet, so there is nothing to forge today.
@@ -96,5 +101,5 @@ These are known, tracked in `SECURITY.md`, and are not new findings:
- The root task is trusted; its image is embedded and hashed, not signed. Kernel image integrity belongs to the boot chain.
- The UEFI loader's known limits, all in `SECURITY.md` under "The UEFI loader": hostile firmware is not defended against, only wrong firmware; the SHA-256 of the embedded kernel is a corruption check and not a signature (only the firmware's Secure Boot gives authenticity); only this loader may start the kernel under UEFI, since a generic loader that passes the firmware device tree through hands firmware memory to user space; a refusal returns to the firmware unless the loader was built with `refuse-halt`; the cache flush and MMU-off sequence cannot be tested under QEMU (TCG has no caches) and is checked only for presence by `tools/pe-check.py`; a pinned build under UEFI is untested; a device left running by firmware can still write to memory (no IOMMU); the loader's entropy stays readable in the device tree in memory; the kernel never calls UEFI runtime services; firmware that types device registers as `EfiReservedMemoryType` or gives one malformed descriptor makes the loader refuse (fail closed); the block re-placement and free-on-refusal paths were not exercised; the loader file is not bit-for-bit reproducible across build directories. About 23 to 32 MiB of boot services memory is left unused on purpose. Firmware with neither a device tree nor ACPI static tables is refused. The ACPI path reads only the static tables (RSDP, XSDT, MADT, GTDT and SPCR, never AML) and has been booted only on QEMU virt.
- Real boards, U-Boot's EFI implementation, Raspberry Pi UEFI, firmware other than EDK2 `ArmVirtQemu`, and KVM have never been booted under UEFI either; do not report "untested on hardware".
-- Only QEMU runs in this image. Real boards, KVM and other hypervisors, the 16550 console driver (no test has executed it), the SBSA UART and CPUs with `HCR_EL2.E2H` fixed to 1 have never been booted. Review of those paths is welcome; do not report "untested on hardware".
+- Only QEMU runs in this image. Real boards, KVM and other hypervisors, the 16550 console driver (no test has executed it, and it has no input path), the SBSA UART and CPUs with `HCR_EL2.E2H` fixed to 1 have never been booted. Review of those paths is welcome; do not report "untested on hardware".
- Upstream issues in vendored crates that are not reachable from the kernel's SHA-256 use.
diff --git a/design/en/README.md b/design/en/README.md
index 14f7abb..baa07cf 100644
--- a/design/en/README.md
+++ b/design/en/README.md
@@ -26,5 +26,6 @@ Read them in the order of the following table the first time. This order follows
| [scheduling.md](scheduling.md) | TCBs and their bound CNode and address space, task creation and teardown, the round-robin scheduler, and timer preemption |
| [ipc.md](ipc.md) | Endpoints and badges, `SEND`, `RECV`, `CALL` and `REPLY_RECV`, the single-use reply right, and what happens to waiting tasks when an endpoint is deleted |
| [vault.md](vault.md) | The signing oracle: the vault task and its frames, the `CALL` protocol and nonce, the fixed badge policy, the provider boundary, the boot seed and its wipe, features, tests, and known gaps |
+| [terminal.md](terminal.md) | Serial input and the operator terminal: why the kernel receives, the receive ring and its bounds, `CONSOLE_READ` and the Console rights, waiting and waking, the terminal's wiring and the hostile-task check, the screen and command rules, tests, and known gaps |
Every note ends with a "**Known gaps**" section. The open security advisories are listed in [SECURITY.md](../../SECURITY.md).
diff --git a/design/en/boot.md b/design/en/boot.md
index dc537a5..37c8e50 100644
--- a/design/en/boot.md
+++ b/design/en/boot.md
@@ -108,7 +108,8 @@ In the following table, each row gives a log line and the step it stands for, in
| `k0: dtb rejected: ...` (only on failure) | `map_dtb` maps the DTB read-only through the alias. It checks the pointer (not null, 8-byte aligned) and `dtb_span`, which reads only the magic and total size. |
| `k0: memory ...` | The DTB is parsed through the alias. [dtb.md](dtb.md) covers the parser. |
| `k0: console drivers [...]` | The first line of platform bring-up, printed even when the platform is later refused. It names the console drivers built into this image (see "Optional console output"). |
-| `k0: platform ...` | `bring_up_platform` finds the console, the interrupt controller and the timer interrupt in the DTB and builds one immutable platform descriptor. It checks the descriptor against the memory map before it maps any device page: RAM must lie below 2^47, the kernel image and the DTB must lie inside declared memory, and no device range, widened to whole granules, may overlap memory or a reserved range or reach beyond the CPU's physical address width (`k0_mm::pa_bits`). In pinned mode it then compares the line with the expected one. Only after that does it attach the console. An image with a driver for this kind of console maps it and attaches it, which replays the buffered log. An image without one maps nothing and prints `k0: no console (driver not built in)`. If the platform is refused, the kernel attaches the console first when the console alone passes the checks (and the image is not pinned, and a driver exists), so that the reason is visible. `k0: no console (...)` names the reason when there is none. See [dtb.md](dtb.md). |
+| `k0: platform ...` | `bring_up_platform` finds the console, its interrupt (if the console node has a usable one), the interrupt controller and the timer interrupt in the DTB and builds one immutable platform descriptor. It checks the descriptor against the memory map before it maps any device page: RAM must lie below 2^47, the kernel image and the DTB must lie inside declared memory, and no device range, widened to whole granules, may overlap memory or a reserved range or reach beyond the CPU's physical address width (`k0_mm::pa_bits`). The line carries the console interrupt number, for example `k0: platform con=pl011@0x9000000,irq33 ...`. In pinned mode it then compares the line with the expected one, so a pin string made before this field existed no longer matches and must be made again. Only after that does it attach the console. An image with a driver for this kind of console maps it and attaches it, which replays the buffered log. An image without one maps nothing and prints `k0: no console (driver not built in)`. If the platform is refused, the kernel attaches the console first when the console alone passes the checks (and the image is not pinned, and a driver exists), so that the reason is visible. `k0: no console (...)` names the reason when there is none. See [dtb.md](dtb.md). |
+| `k0: console input on (pl011 irq 33)` or `k0: console input off ()` | Printed only by an image built with `console-input`, right after the platform is accepted. See "Optional console input". |
| `k0: root task integrity ok (...)` | The embedded root task image is hashed again and compared with the hash fixed at build time. |
| `k0: entropy ...`, `k0: pac=... bti=... pan=...` | PAC keys are derived and loaded, and the key words are wiped from the boot stack. The 32-byte seed for the root task is derived here too, independent of the PAC keys, and kept for the handoff. PAN is enabled and EL0 access to counters, debug and PMU is turned off. See [hardening.md](hardening.md). |
| `k0: irq on (timer 1s)` | `setup_irq` maps only the interrupt controller pages it needs. For GICv3 it looks at the redistributor frames one at a time to find the boot CPU's frame, then maps that frame and its SGI frame. The driver checks the GIC identification registers against what the DTB claimed. The EL1 virtual timer is programmed with the interrupt number from the platform descriptor. IRQ and SError are unmasked. |
@@ -116,7 +117,7 @@ In the following table, each row gives a log line and the step it stands for, in
| `k0: root task loaded (entry ...)` | The root task is copied into frames from the window, its root TCB is made in the window, and its address space is built. The kernel does not print the physical address of the user root table. The address space is then entered in the address space registry. See [user-address-space.md](user-address-space.md). |
| `k0: memory + not handed out ()` (only when it happens), `k0: kernel reserve tables + address space entries = bytes in ranges` | `reserve_kernel_share` carves the kernel share out of each free physical range before any untyped capability exists (see "Carving the kernel share out of untyped memory"). A range that cannot hold its share is not handed out, and the kernel prints the first kind of line with the reason. The second line is printed once, for example `k0: kernel reserve 262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges` on QEMU virt with 512 MiB and the 4 KiB granule. |
| `k0: untyped ...`, `k0: root cnode ready (N caps, N untyped, N image frames, N slots)` | The root CNode (an object in the window with `ROOT_CNODE_SLOTS` = 512 slots, as the log shows) is filled: slot 1 the root TCB, slot 2 the root address space, slot 3 the console, slot 4 the root CNode itself, then every free physical range that was handed out as an untyped capability, then one Frame capability per mapped granule of the root task image (text with R and X, read-only data with R, data with R and W). Finally the root task is bound to its CNode and address space, exactly as any other task is: copies of those two capabilities go into its TCB. See [capabilities.md](capabilities.md). |
-| `k0: bootinfo page ready` | The capability list is written into the read-only bootinfo page (layout version 3): a header and one descriptor per slot, with the VA, size and rights of every image Frame. The page does not hold the boot seed. |
+| `k0: bootinfo page ready` | The capability list is written into the read-only bootinfo page (layout version 4): a header and one descriptor per slot, with the VA, size and rights of every image Frame. The page does not hold the boot seed. |
| `k0: user w^x checks pass` | `TTBR0` now points at the user tables, the identity map is gone, and the user mappings are checked from both EL0 and EL1. |
| `k0: dtb seeds wiped B` | The DTB is not needed any more, so the kernel zeroes the `rng-seed` and `kaslr-seed` bytes in it (through the read-only alias, switched to read-write for the write), reads them back, and wipes its own copy. The line is `40B` on QEMU virt. If the read-back is not zero, the line is `k0: WARNING dtb seeds not wiped`. See [hardening.md](hardening.md). |
| `k0: device pages [...] of 0x1000 bytes` | Every device page the kernel keeps mapped. After this line the kernel maps no further device. |
@@ -159,12 +160,9 @@ Every line the kernel prints also goes into a **16 KiB buffer** in kernel memory
## Optional console output
-Input and output are optional in K0. You can select them with Cargo features of the kernel crate (`k0-kernel`).
+Input and output are optional in K0. You can select them with Cargo features of the kernel crate (`k0-kernel`). Console output is selected with the console features below. Console input and the operator terminal have their own features, described in "Optional console input".
-> [!NOTE]
-> A feature for input or for a terminal does not exist yet. Console output is the only thing you can select today.
-
-Console output exists only in an image built with a console feature (opt-in). No image has input. The following figure shows where the output goes, depending on the features in the build.
+Console output exists only in an image built with a console feature (opt-in). An image built without `console-input` has no input code at all. The following figure shows where the output goes, depending on the features in the build.
@@ -225,11 +223,30 @@ All feature sets write the same ELF path, so a separate `--target-dir`, for exam
**Rule for contributors**: you must follow these rules.
-- Every new input or output path goes behind a Cargo feature from the start (today the only one is console output).
+- Every new input or output path goes behind a Cargo feature from the start (today: console output, `console-input` and `terminal`).
- Features only add and are never in `default`.
- Every supported combination gets a row in the boot matrix.
- The scripts, the `virt` alias and CI name the features explicitly.
+### Optional console input
+
+Console input is a second opt-in layer. It is off by default, and features only add. The following table lists the features of `k0-kernel`.
+
+| Feature | Adds |
+| --- | --- |
+| `console-input` | the kernel's receive path for the console UART and the system call `CONSOLE_READ` (see [exceptions.md](exceptions.md)). It needs a console driver feature to do anything. Receive exists for the PL011 and the SBSA UART only, so a 16550 console has output and no input. |
+| `terminal` | the operator terminal task in the root task image. It turns `console-input` on. |
+
+> [!NOTE]
+> An image built without `console-input` contains no receive code, no `CONSOLE_READ` and none of the log lines below. The static matrix row `input-symbols` checks this.
+
+- **Bring-up**: the console interrupt number comes from the device tree (see [dtb.md](dtb.md)) or, under UEFI, from the ACPI SPCR table, and it is part of the `k0: platform` line. The receive interrupt stays off until a task first reads console input with the read right. A console node without a usable interrupt is not a boot refusal, input is just off.
+- **Log lines**: `k0: console input on (pl011 irq 33)` or `k0: console input off ()`. The reasons are `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range` and `interrupt not available`. A wrong interrupt number costs only the input path.
+- **First read**: it discards what the device holds and stops the periodic `k0: tick N` lines after one line `k0: tick lines off (console input in use)`. Ticks, preemption and timeouts keep working.
+- **Evidence**: the rows `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq`, `input-symbols` (static), `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi` and `hvf-term` are in `tools/boot-matrix.sh`. `tools/qemu-boot-test.sh` reads `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none` and, for judging only, `K0_BOOT_JUDGE`. `tools/term-test.py ` runs a scripted terminal session over QEMU's serial port.
+
+The SBSA UART path, FIFO overruns and the receive timeout interrupt are not exercised by QEMU. They are covered only by host tests with a fake UART (`crates/k0-conin`).
+
## Trust
The DTB now supplies device addresses, so a wrong or hostile DTB can point the console at some other device. The kernel limits this in five ways:
@@ -308,5 +325,5 @@ The self-checks inside `kernel_main` are themselves tests: if a mapping is wrong
- Only one core runs, and the boot loader must enter exactly one CPU. K0 has no code to start or park other CPUs.
- The kernel always sits at the same virtual address. There is no address randomization.
- A release build prints nothing on panic. That is intentional, but it also means a release build gives no diagnosis on panic.
-- No image has input. Console output exists only in an image built with a console feature, and the limits of that evidence are listed in "Optional console output".
+- Console output exists only in an image built with a console feature, and console input only in an image built with `console-input`. The limits of that evidence are listed in "Optional console output" and "Optional console input".
- Under UEFI, the cache flush and the MMU switch-off in the loader cannot be tested by QEMU (it has no caches), and ACPI-only firmware boots only through the three static tables (only QEMU virt has been booted). [uefi.md](uefi.md) lists all the limits of the loader.
diff --git a/design/en/capabilities.md b/design/en/capabilities.md
index d2de923..c9aa54b 100644
--- a/design/en/capabilities.md
+++ b/design/en/capabilities.md
@@ -23,7 +23,7 @@ The related code is in the files of the following table.
| `crates/k0-abi/src/lib.rs` | numbers and error codes (the source of truth for the ABI) |
> [!IMPORTANT]
-> The system call ABI changed incompatibly with this model (bootinfo version 2, now 3). Read the "Known gaps" section before relying on any of this.
+> The system call ABI changed incompatibly with this model (bootinfo version 2, now 4). Read the "Known gaps" section before relying on any of this.
Capability-based isolation covers confidentiality and integrity between tasks. It does not cover availability.
@@ -66,14 +66,15 @@ In the following table, each kind is listed with the time it is created and what
| `Endpoint` | by `RETYPE` | a rendezvous point for synchronous IPC |
| `CNode` | by `RETYPE`, and at boot for the root CNode | an array of slots, used as a capability space and as a destination for copies and moves |
| `AddrSpace` | by `RETYPE`, and at boot for the root task | an address space: the right to map into it and to run a task in it |
-| `Console` | at boot | the right to write bytes to the debug output: the boot log, and the console in an image built with a console driver |
+| `Console` | at boot | the right to write bytes to the debug output (`W`): the boot log, and the console in an image built with a console driver. With `R` it also grants reading console input in an image built with `console-input` |
### Rights
-The **rights bits** are `R` = 1, `W` = 2 and `X` = 4. They have meaning on two kinds only.
+The **rights bits** are `R` = 1, `W` = 2 and `X` = 4. They have meaning on three kinds only.
- **Frame**: the ceiling for mapping permissions. `RO` needs `R`, `RW` needs `R|W`, `RX` needs `R|X`. A frame made by `RETYPE` has `R|W` and can never gain `X`.
- **Endpoint**: `R` is the right to receive, `W` the right to send. A new endpoint capability has both.
+- **Console**: `W` is the right to write output (`DEBUG_PUTC`), and `R` is the right to read input (`CONSOLE_READ`). `CAP_COPY` can only remove them, and a copy that would keep no right fails with `NO_RIGHTS`. A `Console` capability with `R` may also emit the backspace byte (0x08) through `DEBUG_PUTC`. Every other control byte is still printed as `?`.
All other kinds carry no rights, and the rights mask of `CAP_COPY` is ignored for them. **Rights can only be removed**, and only by `CAP_COPY`.
@@ -114,7 +115,7 @@ The root task's CNode is the root CNode. It has `ROOT_CNODE_SLOTS` (512) slots a
| 0 | null |
| 1 | `Tcb` of the root task |
| 2 | `AddrSpace` of the root task |
-| 3 | `Console` |
+| 3 | `Console`, with `W`. It has `R` only in an image built with `console-input` |
| 4 | `CNode`, a capability to the root CNode itself, so it can be used as a copy or move destination |
| 5 and up | `Untyped` capabilities, then one `Frame` capability per mapped granule of the root task image |
@@ -138,7 +139,7 @@ Running out of slots also stops the boot. A DTB memory region beyond the CPU's p
## The bootinfo page
-Just before the handoff, the kernel writes a description of the root CNode into the bootinfo page, which is mapped read-only for the root task at `bootinfo::VA`. The version is 3 (`bootinfo::VERSION`). The page layout did not change from version 2; the version changed because the root task now receives a boot seed in its entry registers (the seed in `x0..x3`, its description in `x4`; see [boot.md](boot.md)), and the seed is not in this page. A root task that sees another version must not proceed.
+Just before the handoff, the kernel writes a description of the root CNode into the bootinfo page, which is mapped read-only for the root task at `bootinfo::VA`. The version is 4 (`bootinfo::VERSION`). The page layout did not change from version 2. Version 3 came because the root task receives a boot seed in its entry registers (the seed in `x0..x3`, its description in `x4`; see [boot.md](boot.md)), and the seed is not in this page. Version 4 came because the `Console` capability now carries rights. A root task that sees another version must not proceed.
The page starts with a header `{version, frame_size, cap_count, cnode_slots}`, followed by `cap_count` descriptors `{kind, base, size, rights}`. The index of a descriptor is its slot number in the root CNode, and every slot at or beyond `cap_count` is empty. A descriptor is filled in by kind as follows:
@@ -232,6 +233,7 @@ When an original capability is removed, its object is finalized by the callbacks
- **Frame**: the mapping this capability made is removed. This happens for any `Frame` capability that has a mapping record, including copies.
- **PageTable**: it is detached from its address space (the same, for any capability with a record).
- **Endpoint** (original): every queued task is woken with `REVOKED`.
+- **Console**: a task that waits in `CONSOLE_READ` on this capability wakes at once with `REVOKED` when the capability is deleted, revoked or moved (see [ipc.md](ipc.md)).
- **Tcb** (original), and any capability bound to a task: the task is torn down, see [scheduling.md](scheduling.md) and [ipc.md](ipc.md).
- **AddrSpace** (original): it is released in the registry (which bumps its generation). If it is installed in TTBR0, TTBR0 is switched to an empty table from the kernel pool.
@@ -247,7 +249,8 @@ The following table lists the capabilities and rights each system call requires.
| System call | Capabilities and rights it requires |
| --- | --- |
-| `DEBUG_PUTC` | `Console` |
+| `DEBUG_PUTC` | a `Console` with `W` |
+| `CONSOLE_READ` | a `Console` with `R` (only in images built with `console-input`) |
| `RETYPE` | an `Untyped`, and a free destination slot in the caller's CNode |
| `MAP` | a `Frame` whose rights cover the permission (`RO` needs `R`, `RW` needs `R\|W`, `RX` needs `R\|X`) or a `PageTable`, and an `AddrSpace` naming the target |
| `UNMAP` | a `Frame` or `PageTable` that is mapped |
@@ -280,7 +283,7 @@ The following table lists the error codes for slot problems and their meaning.
| `BAD_PERM` | the mapping permission or the rights mask is not valid |
| `BAD_BADGE` | a badge on a kind that cannot carry one, or a different badge on an already badged capability |
| `TOO_DEEP` | the derivation depth limit would be exceeded |
-| `REVOKED` | returned to a task that was waiting on an endpoint that was deleted |
+| `REVOKED` | returned to a task that was waiting on an endpoint that was deleted, or in `CONSOLE_READ` on a `Console` capability that was deleted, revoked or moved |
| `KERNEL_RESOURCE` | an internal resource is missing. It is still a defined code, but neither the kernel alias tables nor the address space registry can cause it any more |
## How it is tested
diff --git a/design/en/dtb.md b/design/en/dtb.md
index a967d72..6485bba 100644
--- a/design/en/dtb.md
+++ b/design/en/dtb.md
@@ -95,9 +95,10 @@ Every violation returns a `BootError`, and the kernel then prints `k0: dtb rejec
## The platform descriptor
-Besides memory, the kernel finds exactly three devices in the DTB and nothing else (`discover` in `crates/k0-boot/src/platform.rs`):
+Besides memory, the kernel finds exactly three devices in the DTB, plus the console's interrupt, and nothing else (`discover` in `crates/k0-boot/src/platform.rs`):
- **The console**: only the node named by `/chosen/stdout-path` (an absolute path, or an alias that resolves to one). The node must be enabled, and its `compatible` must name a PL011 (`arm,pl011`), an SBSA UART (`arm,sbsa-uart`) or a 16550-family UART (`ns16550a`, `ns16550`, `snps,dw-apb-uart`, `brcm,bcm2835-aux-uart`). Any other UART, a missing or unresolvable `stdout-path`, or a node the kernel cannot translate to a CPU physical address gives a boot with no console. That is not an error. The kernel prints `k0: no console (...)` with the reason, and the boot log buffer is the only record (see [boot.md](boot.md)). Every image does this discovery and validation, also an image built without a console driver, which then maps nothing and prints `k0: no console (driver not built in)`. Such an image refuses a device tree whose console fails the checks like any other. The register range the driver touches must lie inside the declared `reg` and inside one granule.
+ - **The console interrupt** (read only in an image built with `console-input`, see [boot.md](boot.md)): the `interrupts` property of the console node, taken only when the interrupt parent is the discovered GIC and the property is exactly one SPI (three cells, first cell 0) with a level type and active high. The number is the SPI number plus 32. A console node with no property, another form or another parent is not an error: the platform has no console interrupt and input is off. A number that is out of range is caught later, when input is brought up (`k0: console input off (...)`).
- **The interrupt controller**: the node that the timer node's interrupt parent points to (`arm,armv8-timer` or `arm,armv7-timer`, exactly one enabled node). It must be a GICv3 (`arm,gic-v3`) or a GICv2 (`arm,gic-400`, `arm,cortex-a15-gic`, `arm,cortex-a7-gic`) with the expected cell counts and frame alignment. Up to four GICv3 redistributor ranges are accepted. A duplicate phandle, a disabled node, an `interrupt-map`, or a GICv2 without per-CPU banked interfaces (`cpu-offset`) is refused.
- **The EL1 virtual timer interrupt number**: taken from the timer node's `interrupts` (the `virt` entry when `interrupt-names` exists, else the third entry) as a PPI number plus 16. A timer node that declares a timer erratum (`fsl,erratum-a008585`, `hisilicon,erratum-161010101` or `allwinner,erratum-unknown1`) is refused, because the kernel has no workaround code.
@@ -106,7 +107,7 @@ Besides memory, the kernel finds exactly three devices in the DTB and nothing el
Register addresses are translated through the `ranges` of the parent buses to CPU physical addresses. A bus without `ranges` cannot be translated.
-The result is one immutable `Platform` value. The kernel prints it as the single line `k0: platform con=... gic=... tmr=...`, in a fixed format. Before any device page is mapped, `Platform::validate` checks it against the memory map. The checks are the following:
+The result is one immutable `Platform` value. The kernel prints it as the single line `k0: platform con=... gic=... tmr=...`, in a fixed format. The console field carries the interrupt number when there is one, for example `con=pl011@0x9000000,irq33`. Before any device page is mapped, `Platform::validate` checks it against the memory map. The checks are the following:
- RAM must lie below 2^47.
- The kernel image and the DTB must lie inside declared memory.
@@ -126,7 +127,7 @@ A mismatch makes the kernel refuse or, for the console, continue without one.
### Pinned mode
-The platform line, the entry exception level and the RAM range form the string ` el= ram=-`. If `K0_PIN` was set at build time to the text after `k0: platform ` from a boot log of the target, the image refuses to boot when this string differs. It catches a wrong board or a swapped DTB. It **does not defend against a hostile boot chain**, because the compared values are derived from the DTB.
+The platform line, the entry exception level and the RAM range form the string ` el= ram=-`. If `K0_PIN` was set at build time to the text after `k0: platform ` from a boot log of the target, the image refuses to boot when this string differs. It catches a wrong board or a swapped DTB. Pin strings made before the console interrupt joined the platform line no longer match and must be made again. It **does not defend against a hostile boot chain**, because the compared values are derived from the DTB.
## How it is tested
diff --git a/design/en/exceptions.md b/design/en/exceptions.md
index 465b3fe..04727c3 100644
--- a/design/en/exceptions.md
+++ b/design/en/exceptions.md
@@ -20,7 +20,7 @@ The following figure shows the path that the kernel follows for each kind of exc
## The vector table
-AArch64 has 16 vector entries: four kinds of exception (synchronous, IRQ, FIQ, SError) for each of four origins. K0 gives each entry one of four behaviors. The kernel takes only IRQs, so a FIQ is a state that should not happen. The FIQ entries call a dispatcher that prints `k0: UNEXPECTED fiq intid=0` and parks. The following table lists the behavior of each entry.
+AArch64 has 16 vector entries: four kinds of exception (synchronous, IRQ, FIQ, SError) for each of four origins. K0 gives each entry one of four behaviors. The kernel takes only IRQs (never FIQs), so a FIQ is a state that should not happen. The FIQ entries call a dispatcher that prints `k0: UNEXPECTED fiq intid=0` and parks. The following table lists the behavior of each entry.
| Origin | Sync | IRQ | FIQ | SError |
| --- | --- | --- | --- | --- |
@@ -86,7 +86,7 @@ The system call number is in `x8`. Arguments are in `x0` to `x5`, and the result
| Number | Call | Description |
| --- | --- | --- |
-| 0 | `DEBUG_PUTC` | write one filtered byte to the boot log, and to the console in an image built with a console driver; needs a `Console` capability |
+| 0 | `DEBUG_PUTC` | write one filtered byte to the boot log, and to the console in an image built with a console driver; needs a `Console` capability with the write right |
| 1 | `YIELD` | go to the back of the ready queue |
| 2 | `EXIT` | terminate the calling task |
| 3 | `RETYPE` | create a kernel object from untyped memory, into a destination slot the caller names |
@@ -102,6 +102,7 @@ The system call number is in `x8`. Arguments are in `x0` to `x5`, and the result
| 13 | `CAP_MOVE` | move a capability to another slot |
| 14 | `CAP_DELETE` | delete a capability and everything derived from it |
| 15 | `CAP_REVOKE` | delete everything derived from a capability and keep the capability |
+| 16 | `CONSOLE_READ` | read one byte of console input (only in an image built with `console-input`, see below); needs a `Console` capability with the read right |
> [!IMPORTANT]
> An unknown number is not just an error code. K0 treats it as a sign that the task is broken or hostile, prints `k0: unknown syscall N, killing task`, and terminates the caller.
@@ -134,19 +135,29 @@ When no task is ready (for example the last runnable task died, or every task is
| `k0: idle (waiting for a timeout)` | the first time the kernel idles while at least one waiter has a deadline |
| `k0: all tasks stopped (none ready, no timeout pending)` | the first time the kernel idles while no waiter has a deadline |
-In the second state nothing can wake a task today, because there are no notification objects and no device interrupts for tasks. The machine stays idle. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure.
+In the second state nothing can wake a task today, because there are no notification objects and no device interrupts for tasks other than console input. The machine stays idle. In an image with `console-input`, a task that waits for console input counts as a waiter: when that is the only thing left to wait for, the kernel prints nothing, which is the normal state of a terminal image. The second line is printed only when there is neither a timed waiter nor a console waiter. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure.
## Timer interrupts from EL0
-The only interrupt the kernel enables is **the EL1 virtual timer**. Its interrupt number comes from the DTB, and the kernel uses no physical timer. The interrupt controller is GICv2 or GICv3, whichever the DTB says is the timer's interrupt parent. Before it writes anything, the driver checks the identification registers against that description and refuses to boot if they differ. See [dtb.md](dtb.md).
+The interrupt the kernel always enables is **the EL1 virtual timer**. An image built with `console-input` takes a second one, the console UART's receive interrupt (see below). Its interrupt number comes from the DTB, and the kernel uses no physical timer. The interrupt controller is GICv2 or GICv3, whichever the DTB says is the timer's interrupt parent. Before it writes anything, the driver checks the identification registers against that description and refuses to boot if they differ. See [dtb.md](dtb.md).
An IRQ taken from EL0 is saved the same way as a system call. The handler acknowledges the interrupt. If it was the timer, it re-arms the timer for one second, and prints `k0: tick N`. In an image built with a console driver, the line also goes to the console; only the first 4 tick lines are logged. Then it calls `k0_preempt`. That function first expires the IPC timeouts that are due (`k0_ipc::expire_timeouts`), so a waiter whose deadline has passed is ready before the round-robin switch, and then rotates to the next ready task. Spurious interrupt numbers 1020 to 1023 are ignored. Any other interrupt number, or any FIQ, cannot happen by design, so the kernel prints `k0: UNEXPECTED ...` and parks.
+Once a tick has been counted, the handler also drains the console receive ring (an image with `console-input`), and after a task has started reading console input it stops printing the periodic tick lines (see [boot.md](boot.md)). Ticks, preemption and timeouts are unchanged.
+
+## Console interrupt
+
+An image built with `console-input` takes one more interrupt: the console UART's receive interrupt. The dispatcher tells the two apart by interrupt number (the timer's, then the console's), in the same function for IRQs taken at EL0 and at EL1. Anything else is still `k0: UNEXPECTED ...`. The console branch drains the UART into a ring of 256 bytes and never interprets a byte. It reports to the kernel binary through `k0_console_event`, a policy function like `k0_preempt`, which wakes a waiting `CONSOLE_READ` caller. The woken task goes to the end of the ready queue, so input does not preempt a running task.
+
+The interrupt is bounded by the reader. When the ring is full the kernel masks the UART's receive interrupt itself and reopens it after the reader has taken half of the ring. The same drain also runs once per tick, so input still arrives, up to a tick late, when the interrupt does not. A line that fires without a UART cause is switched off after 8 entries with `k0: console input off (interrupt N fired without a uart cause)`. The cut-off is covered only by host tests. Receive interrupts stay off until a task first reads console input with the read right.
+
+`CONSOLE_READ` takes the `Console` slot in `x0` and flags in `x1` (`NONBLOCK` = 1, `FLUSH` = 2, a timeout in ticks in bits 63..32, other bits refused with `BAD_FLAGS`). It returns the byte in `x1`, and `x2` is 1 if input was lost right before this byte. Only one task can wait at a time, a second reader gets `BUSY`, and `NO_DEVICE` means there is no input path or it was turned off. A waiter whose capability is deleted, revoked or moved wakes at once with `REVOKED`.
+
## How it is tested
The root task self-tests start tasks that fault in each way that matters. They check that only the faulting task dies, that the code after the faulting instruction never runs, and that the root task and the other tasks continue. The faults are a store through a null pointer, an FP/SIMD instruction, a read of an address that is mapped only in the root task, a write to a read-only page, a branch into a stack page, and a read of a kernel address. The test also kills a task with one unknown system call, and checks that thread pointer registers stay separate per task.
-`tools/qemu-boot-test.sh` counts the lines **exactly**. It requires exactly six `k0: task fault ` lines (overridable with `K0_BOOT_FAULTS`) and exactly one `k0: unknown syscall ` line, and it requires that the fault line for the root-only address shows that address in `far`. A task that is resumed after it was destroyed, or that dies for a different reason, adds or removes a line and fails the test.
+`tools/qemu-boot-test.sh` counts the lines **exactly**. It requires exactly six `k0: task fault ` lines (overridable with `K0_BOOT_FAULTS`; an image with the terminal shows two more than the same image without it, 8 without the vault and 10 with it) and exactly one `k0: unknown syscall ` line, and it requires that the fault line for the root-only address shows that address in `far`. A task that is resumed after it was destroyed, or that dies for a different reason, adds or removes a line and fails the test.
The test also requires the ordered markers, among them `k0: task fault dabort-lower`, `k0: task fault fp-simd`, `k0: task fault iabort-lower`, `k0: unknown syscall 65535, killing task` and `root: fault isolation tests pass`. It fails on `k0: FATAL`, `k0: EXCEPTION`, `k0: PANIC` and `k0: UNEXPECTED`.
diff --git a/design/en/hardening.md b/design/en/hardening.md
index 8b408a1..9b86d73 100644
--- a/design/en/hardening.md
+++ b/design/en/hardening.md
@@ -46,7 +46,7 @@ Because the inputs are hashed together, a hostile or predictable input cannot ca
The kernel also derives a 32-byte seed for the root task (`k0_boot::derive_root_seed`). It is SHA-256 over its own domain string (`k0-root-task-seed-v1`), the length of the DTB entropy, the DTB entropy itself, the counter and, when the CPU has `RNDR`, four fresh `RNDR` words. The domain string differs from the one of the PAC keys, so the two outputs are independent of each other by domain separation: knowing one does not give the other. They do share the DTB entropy and the counter, so the seed is as good as its inputs and no better.
-The seed is not in the bootinfo page. The kernel puts it into the saved context of the root task, so it arrives in the entry registers `x0` to `x3`. Register `x4` is the seed info word: bits 15..0 hold how many `rng-seed` bytes went into the seed, and bit 16 is set when `RNDR` contributed. The layout of the bootinfo page is now version 3 (`bootinfo::VERSION`), and a root task that sees another version stops. The kernel wipes its own copies of the seed from the boot stack. The root task prints only the material, never the seed: `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr`.
+The seed is not in the bootinfo page. The kernel puts it into the saved context of the root task, so it arrives in the entry registers `x0` to `x3`. Register `x4` is the seed info word: bits 15..0 hold how many `rng-seed` bytes went into the seed, and bit 16 is set when `RNDR` contributed. The layout of the bootinfo page is now version 4 (`bootinfo::VERSION`), and a root task that sees another version stops. The kernel wipes its own copies of the seed from the boot stack. The root task prints only the material, never the seed: `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr`.
### Wiping the seed from the DTB
@@ -106,9 +106,12 @@ EL0 still cannot read any hardware counter or timer. IPC timeouts, however, give
The EL0 thread pointer registers `TPIDR_EL0` and `TPIDRRO_EL0` are part of each task's saved context. `TCB_CONFIGURE` zeroes them, so a new task starts without the creator's values.
-`DEBUG_PUTC` requires the `Console` capability and replaces every byte that is neither printable ASCII nor a newline with `?`. A task cannot send terminal escape sequences to whoever reads the console (in an image built with a console driver) or the boot log.
+`DEBUG_PUTC` requires the `Console` capability with the write right (W) and replaces every byte that is neither printable ASCII nor a newline with `?`. The one exception is backspace (0x08), which a `Console` capability with the read right (R), the terminal's, may also emit. A task cannot send terminal escape sequences to whoever reads the console (in an image built with a console driver) or the boot log.
-The filter does not mark who wrote a line. Kernel output and task output share the boot log, and in an image built with a console driver also the console.
+The filter does not mark who wrote a line. Kernel output and task output share the boot log, and in an image built with a console driver also the console. The terminal can additionally erase within its current line.
+
+> [!NOTE]
+> In an image built with `console-input`, an outside party can cause interrupts while tasks run. The kernel masks the receive interrupt itself when the ring is full, so the rate is bounded by the reader. The reader still learns arrival times finer than the tick, and other tasks can notice the stolen time. This timing channel has not been analysed. The kernel's receive code runs at EL1 and never interprets a byte, but it is kernel code driven by an outside party, and a user-space driver would need device and interrupt delegation, which K0 does not have.
> [!WARNING]
> A task with a `Console` capability can print a newline followed by text that starts with `k0:`. A reader of the console or the log, including `tools/qemu-boot-test.sh`, cannot treat a `k0:` line that appears after `k0: entering root task (el0)` as written by the kernel.
diff --git a/design/en/ipc.md b/design/en/ipc.md
index 38b030e..fc12cc6 100644
--- a/design/en/ipc.md
+++ b/design/en/ipc.md
@@ -13,7 +13,7 @@ This note describes K0's inter-process communication. It covers the following:
- the badge that tells a server its clients apart
- the single-use reply right that makes `CALL` safe
-The code is in `crates/k0-ipc/src/lib.rs`, with the endpoint queue in `crates/k0-task/src/lib.rs`.
+The code is in `crates/k0-ipc/src/lib.rs`, with the endpoint queue in `crates/k0-task/src/lib.rs`. The system call `CONSOLE_READ` waits like an IPC call and shares its timeouts, its teardown and its `REVOKED` wake-up. It is described in "Waiting for console input". It exists only in images built with `console-input`.
## Design in one paragraph
@@ -101,6 +101,7 @@ The teardown looks only at the task's state and cuts every kernel pointer to it:
- **Ready**: removed from the ready queue.
- **Blocked in SEND, RECV or CALL**: removed from the queue of the endpoint it waits on, whether it is the head, the middle or the tail.
+- **Waiting for console input** (`BlockedConsole`): removed from the one waiter place of the console.
- **Waiting for a reply** (`BlockedReply`): the reply right is cut in both directions. So the server holds no right to answer it, and a late reply cannot wake a dead task.
- **Holding a reply right**: the caller waiting for it wakes with `NO_REPLY`.
- **Inactive, stopped or running**: nothing to unlink.
@@ -127,6 +128,7 @@ The following table lists what the caller gets when a wait ends by timeout.
| `RECV`, `REPLY_RECV` | in the endpoint queue | `TIMEOUT` | nothing received (a reply given by `REPLY_RECV` was already delivered) |
| `CALL` | in the endpoint queue | `TIMEOUT` | not delivered |
| `CALL` | `BlockedReply` | `REPLY_TIMEOUT` | delivered, and the server may or may not have acted |
+| `CONSOLE_READ` | the console waiter place | `TIMEOUT` | no byte read |
When a `CALL` ends with `REPLY_TIMEOUT`, the kernel clears the reply right of the server that holds it. If the server answers later, its `REPLY_RECV` finds no reply right to use, and the late reply is dropped. The next caller receives its own reply.
@@ -154,13 +156,43 @@ A task that has to wait is marked with its blocked state and linked into the end
If no task is ready at that point, the kernel does not stop. It idles in `idle_until_ready` (`kernel/src/syscall.rs`): it waits for the next interrupt, wakes every waiter whose deadline has passed, and switches to a ready task if there is one. Timer ticks keep being counted and handled meanwhile. The idle loop prints one of two lines, each at most once per boot:
- `k0: idle (waiting for a timeout)`: at least one waiter has a deadline, so something will wake a task.
-- `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline. Nothing can wake a task in that state today, because K0 has no notification objects and no device interrupts for tasks, so the machine stays idle. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure.
+- `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline and no task waits for console input. Nothing can wake a task in that state today, because K0 has no notification objects and the only device interrupt that wakes a task is console input, so the machine stays idle. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure.
+
+When the only thing left to wait for is console input, the kernel prints neither line. That is the normal state of a terminal image.
> [!WARNING]
> The kernel no longer halts when every task is blocked, and a task can bound its own waits with timeouts. Availability is still not protected. A task that waits without a timeout can wait forever if its partner never acts, and a confined task that holds a capability to an endpoint can still make others wait. This is the subject of advisory GHSA-q99x-2wrv-358p in [SECURITY.md](../../SECURITY.md). The advisory is updated at release time.
A server, or the root task, that must stay responsive has to give a timeout on every wait. Task isolation does not change this.
+## Waiting for console input
+
+`CONSOLE_READ` (number 16) reads one byte of console input. It exists only in an image built with `console-input` and a console driver that can receive (PL011 and SBSA UART, not 16550). The arguments and results are the following:
+
+| Register | Meaning |
+| --- | --- |
+| `x0` (in) | the slot of a `Console` capability with `R` |
+| `x1` (in) | flags: `NONBLOCK` = 1, `FLUSH` = 2, a timeout in ticks in bits 63 to 32. Any other bit fails with `BAD_FLAGS` |
+| `x0` (out) | 0, or an error code |
+| `x1` (out) | the byte |
+| `x2` (out) | 1 if input was lost right before this byte, otherwise 0 |
+
+One call returns one byte. The kernel never interprets a byte. `FLUSH` discards what the kernel and the device hold before the read, so that input that arrived before a prompt is not read as a command. `NONBLOCK` returns `WOULD_BLOCK` when no byte is ready.
+
+If no byte is ready, the task waits in the state `BlockedConsole`. The wait works like the waits above:
+
+- **One waiter**: only one task can wait at a time. A second reader gets `BUSY`.
+- **Timeouts**: the timeout uses the same timed list as IPC, and a wait that runs out returns `TIMEOUT`.
+- **Revocation**: a waiter whose `Console` capability is deleted, revoked or moved wakes at once with `REVOKED`, and gets no byte.
+- **No input path**: `NO_DEVICE` means that the image has no receive driver for this console, or that the input path was turned off. A waiter wakes with it when the path is turned off while it waits.
+- **Teardown**: a task that dies while it waits is removed from the waiter place.
+- **Wake-up order**: a woken reader goes to the end of the ready queue. Input does not preempt a running task.
+
+Receive interrupts stay off until a task first reads console input with the right. That first read discards what the device holds and stops the periodic `k0: tick N` lines after one line `k0: tick lines off (console input in use)`. Ticks, preemption and timeouts keep working. The receive path and its limits are described in [USAGE.md](../../USAGE.md) and [exceptions.md](exceptions.md).
+
+> [!NOTE]
+> Input waits behind running tasks. There are no priorities, so the latency of a byte is up to one tick per ready task.
+
## Errors
The following table lists the error codes and their causes.
@@ -172,10 +204,12 @@ The following table lists the error codes and their causes.
| `NO_RIGHTS` | the endpoint capability lacks `W` (`SEND`, `CALL`) or `R` (`RECV`, `REPLY_RECV`) |
| `WOULD_BLOCK` | `NONBLOCK` was set and the other side was not ready |
| `NO_REPLY` | the receiver of a `CALL` exited, faulted or took a newer `CALL` without replying, or was destroyed |
-| `REVOKED` | the original capability of the endpoint was deleted while the caller was queued on it |
+| `REVOKED` | the original capability of the endpoint was deleted while the caller was queued on it. For `CONSOLE_READ`, the `Console` capability was deleted, revoked or moved while the caller waited |
| `TIMEOUT` | the wait ended before a partner arrived, and the message was not delivered |
| `REPLY_TIMEOUT` | a `CALL` was delivered but no reply came in time, and the server may or may not have acted |
-| `BAD_FLAGS` | a reserved bit (31 to 1) of the flags register was set |
+| `BAD_FLAGS` | a reserved bit (31 to 1) of the flags register was set. For `CONSOLE_READ`, any bit other than `NONBLOCK`, `FLUSH` and the timeout |
+| `BUSY` (-23) | `CONSOLE_READ` found another task already waiting for console input |
+| `NO_DEVICE` (-24) | `CONSOLE_READ` found no input path: the image has no receive driver for the console, or the path was turned off |
## How it is tested
@@ -199,6 +233,8 @@ The timeout tests (`test_timeouts` in `userspace/root-task/src/main.rs`) wait fo
The timeout tests take their objects from the largest untyped. The tests wait for real ticks, so a boot test takes about 4 seconds longer.
+The input tests are part of the root task self-test in images built with `console-input`. They print `root: backspace without the input right [?]` and `root: console input tests pass`, or `root: console input tests pass (no input path)`, or `... cut short (the line is busy)` when bytes arrive during the test. The receive logic is in the separate crate `crates/k0-conin` and is tested on the host with a fake UART. `tools/term-test.py` runs a scripted session against a terminal image.
+
The capability tests check that a badge can be set once and is refused a second time, that a copy keeps the badge, that a send-only capability cannot receive and a receive-only one cannot send (`NO_RIGHTS`), and that revoking an endpoint removes every copy while the original stays.
The isolation tests start a confined task whose CNode holds only a send-only, badged endpoint capability. The root task checks that the task receives the badge it was given in `x1` and that slot numbers of the root task mean nothing in the confined CNode (`BAD_SLOT`).
@@ -224,6 +260,7 @@ The boot test script also requires an exact number of `k0: task fault` lines and
- **Timeouts say when a task becomes ready, not when it runs**: there is no priority and no CPU budget, and the scheduler is round robin with a one-tick slice (see [scheduling.md](scheduling.md)).
- **Long system calls**: the kernel is not preemptible, so a long call such as `CAP_REVOKE` on an untyped with many objects delays every other task and every timeout.
- **Fatal stops**: a `k0_arch::fatal` or a kernel panic still stops the machine.
-- **Timing source for EL0**: whether the tick-aligned wake-up can be used for timing attacks has not been analysed.
+- **Timing source for EL0**: whether the tick-aligned wake-up can be used for timing attacks has not been analysed. In an image with console input, an outside party can cause interrupts while tasks run (bounded by the reader), and the reader learns arrival times finer than the tick. Other tasks can notice the stolen time. This timing channel is not analysed either.
+- **Input latency**: a `CONSOLE_READ` waiter is woken behind running tasks, so a byte can wait up to a tick per ready task.
- **A queued sender**: it delivers once after revocation. A sender that is already waiting on an endpoint keeps the badge of the send that queued it. If its capability is revoked while it waits, its message is still delivered once to the next receiver.
- **Four words per message**: larger data needs shared memory. The holder of a task's `AddrSpace` capability must map it into that task's address space, since tasks can now run in separate address spaces.
diff --git a/design/en/scheduling.md b/design/en/scheduling.md
index 063b9f9..6b1a435 100644
--- a/design/en/scheduling.md
+++ b/design/en/scheduling.md
@@ -56,9 +56,10 @@ The following figure shows the task states and the transitions between them. The
| `Running` | the current task |
| `BlockedSend`, `BlockedRecv`, `BlockedCall` | waiting in an endpoint queue |
| `BlockedReply` | waiting for the answer to a `CALL` |
+| `BlockedConsole` | waiting for console input in `CONSOLE_READ` (only in an image built with `console-input`). The task is in no queue. One kernel waiter slot points at it, and only one task can wait at a time. |
| `Dead` | exited, killed, or torn down |
-A task in any of the blocked states can also become `Ready` when its deadline passes (see [Timeouts](#timeouts)).
+A task in any of the blocked states can also become `Ready` when its deadline passes. A `BlockedConsole` task also becomes `Ready` when a byte arrives or when its capability is deleted, revoked or moved (for deadlines see [Timeouts](#timeouts)).
`Inactive` has the value 0. A freshly retyped frame is all zeroes, so it already is a valid `Inactive` TCB with empty queue links, empty embedded slots and no reply right. Retype needs no constructor.
@@ -107,12 +108,12 @@ Three operations use this switch, as shown in the following table.
## Preemption
-The timer fires once per second. When it fires while EL0 is running, the IRQ path acknowledges it, re-arms the timer, prints `k0: tick N` and calls `k0_preempt`, which calls `rotate`. The `k0: tick N` line goes to the console in an image built with a console driver, and only the first 4 tick lines are logged. A task that never yields therefore **loses the CPU after at most one second**.
+The timer fires once per second. When it fires while EL0 is running, the IRQ path acknowledges it, re-arms the timer, prints `k0: tick N` and calls `k0_preempt`, which calls `rotate`. The `k0: tick N` line goes to the console in an image built with a console driver, and only the first 4 tick lines are logged. A task that never yields therefore **loses the CPU after at most one second**. Once a task has read console input, the tick lines stop after one line `k0: tick lines off (console input in use)`, but the tick, the preemption and the timeouts go on.
> [!IMPORTANT]
> The kernel itself is never preempted. Exception entry masks interrupts, and the kernel keeps them masked while it handles a system call or fault.
-A timer interrupt that arrives at EL1 is possible only during boot, before the handoff, and it only counts the tick.
+A timer interrupt that arrives at EL1 is possible only during boot, before the handoff, and it only counts the tick. In an image with `console-input`, an arriving input byte does not preempt: the woken reader goes to the end of the ready queue like any other woken task. There are no priorities, so input latency is up to a tick per ready task.
## Timeouts
@@ -145,6 +146,7 @@ The following table shows what teardown does in each state.
| `Ready` | removes the task from the ready queue |
| `BlockedSend`, `BlockedRecv`, `BlockedCall` | removes the task from the endpoint queue named by `blocked_on`, and from the timed list if it has a deadline |
| `BlockedReply` | clears the reply right in the task that holds it (`reply_from`), and removes the task from the timed list if it has a deadline |
+| `BlockedConsole` | clears the kernel's console waiter slot and removes the task from the timed list if it has a deadline |
| `Running` | nothing is unlinked. See below. |
For every state it then withdraws any reply right the task itself holds, so that the caller waiting for that reply wakes with `NO_REPLY` and does not stay blocked forever. Finally it sets the state to `Dead`, clears the queue links, `blocked_on`, `reply_from`, `ipc_badge` and `ttbr0_pa`, and, unless the task is `Running`, zeroes its saved registers. A queue or reply link that does not match what the state promises is a kernel invariant violation, and the kernel halts with `k0: FATAL ...` (see [exceptions.md](exceptions.md)).
@@ -164,7 +166,9 @@ The kernel no longer parks the core when no task can run. If the current task bl
Timer ticks keep being counted and handled while the kernel idles. The idle loop prints one of two lines, each at most once per boot:
- `k0: idle (waiting for a timeout)`: at least one waiter has a deadline.
-- `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline. Nothing can wake a task in that state today, because there are no notification objects and no device interrupts for tasks, so the machine stays idle.
+- `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline and no task waits for console input. Nothing can wake a task in that state today, because there are no notification objects and no device interrupts for tasks other than console input, so the machine stays idle.
+
+When the only thing left to wait for is console input (an image with `console-input`), the kernel prints nothing: that is the normal state of a terminal image. The idle loop also looks for arrived input after each interrupt and wakes the reader.
> [!WARNING]
> Availability is still not protected. A task that waits without a timeout can wait forever if its partner never acts, and a confined task that is the last one to block can still leave the system with nothing to run (advisory GHSA-q99x-2wrv-358p in [SECURITY.md](../../SECURITY.md), updated at release time). Isolation protects confidentiality and integrity between tasks, not availability.
diff --git a/design/en/terminal.md b/design/en/terminal.md
new file mode 100644
index 0000000..fedecaa
--- /dev/null
+++ b/design/en/terminal.md
@@ -0,0 +1,165 @@
+# Serial input and the operator terminal
+
+
+
+English | [한국어](../kr/terminal_KR.md)
+
+
+
+This note describes how a person can talk to K0 over the serial line. The kernel receives bytes from the console UART and hands them to one task, the **terminal**, with the system call `CONSOLE_READ`. The terminal is the operator of the vault (see [vault.md](vault.md)): it shows the vault's state, makes the key and erases it. The code is in `crates/k0-conin` (the receive logic), `kernel/src/syscall.rs` (`CONSOLE_READ`), `userspace/k0-term` (the terminal) and `userspace/root-task/src/service.rs` (wiring and the check).
+
+> [!NOTE]
+> Input and the terminal are optional and off by default. An image built without `console-input` has no receive code, no `CONSOLE_READ` and none of the log lines in this note. An image built without `terminal` has no terminal code.
+
+## Purpose and scope
+
+The vault of the previous note makes its key once from the boot seed and then only answers calls. Without an operator nobody can look at its state, and nobody can erase the key on purpose. The terminal closes this gap with a small, fixed text interface on the serial line.
+
+Scope: one console UART, one reader at a time, one byte per call, and four vault operations for the operator (`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`). The terminal cannot sign and cannot deliver a seed.
+
+
+
+
+
+## Why the kernel receives
+
+A user-space driver would need the UART's registers and its interrupt. K0 cannot delegate a device or an interrupt to a task yet. So the receive code runs in the kernel, at EL1, and the kernel gives the bytes to user space.
+
+The kernel code is kept small and never interprets a byte. It does not know what a line, a command or a control key is. All of that is the terminal's job, in user space.
+
+> [!NOTE]
+> The receive code is still kernel code that an outside party drives. A user-space driver does not exist yet, because device and interrupt delegation does not exist yet.
+
+The features are the following, and features only add:
+
+| Feature of `k0-kernel` | Adds |
+| --- | --- |
+| `console-input` | The kernel's receive path for the console UART and `CONSOLE_READ`. It needs a console driver feature to do anything. Receive exists for PL011 and SBSA UART only. |
+| `terminal` | The terminal task in the root task image, started as a service after the self-tests. It turns `console-input` on. With `vault` it is the vault's operator, and with `vault-ed25519` it can make an Ed25519 key. |
+
+You can build and run it as follows:
+
+```sh
+$ cargo build -p k0-kernel --features console,terminal,vault-ed25519
+$ cargo run -p k0-kernel --features console,terminal,vault-ed25519
+```
+
+QEMU shows the serial port on your terminal. Under `cargo run`, QEMU's own escape key is Ctrl-A (Ctrl-A x quits QEMU), so Ctrl-A never reaches K0 there.
+
+## The receive path and its bounds
+
+The kernel's UART driver puts every received byte into a ring of 256 bytes. The receive logic is a separate crate, `crates/k0-conin`, written against a small register trait, so that the host tests can drive it with a fake UART.
+
+- **Receive interrupts stay off** until a task first reads console input with the right. That first read discards what the device holds. It also stops the periodic `k0: tick N` lines after one line `k0: tick lines off (console input in use)`. Ticks, preemption and timeouts keep working.
+- **Bound on kernel work**: when the ring is full, the kernel masks the UART's receive interrupt itself. It reopens the interrupt after the reader has taken half of the ring. So the interrupt rate under a flood is bounded by the reader, not by the sender.
+- **A drain on every tick**: the same drain also runs once per tick, so input still arrives (up to a tick late) when the interrupt does not.
+- **Loss is marked**: a FIFO overrun, a break, a framing error or a parity error is marked on the byte after the hole. `CONSOLE_READ` returns that mark to the reader.
+- **The interrupt number** comes from the device tree (the `interrupts` property of the console node: one SPI, level, active high, of the discovered GIC) or, through the UEFI loader, from the ACPI SPCR table. It is printed in the platform line, for example `k0: platform con=pl011@0x9000000,irq33 ...`, and therefore pinned by `K0_PIN`. Pin strings made before this change no longer match and must be made again. A console node without a usable interrupt is not a boot refusal. Input is just off.
+- **A wrong interrupt number costs only input**: an out-of-range or unavailable number gives `k0: console input off (...)` at boot. A line that keeps firing without a UART cause is switched off after 8 entries with `k0: console input off (interrupt N fired without a uart cause)`.
+
+At boot the kernel prints `k0: console input on (pl011 irq 33)` or `k0: console input off ()`. The reasons are `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range` and `interrupt not available`.
+
+## CONSOLE_READ and the Console rights
+
+`CONSOLE_READ` is system call number 16. It returns one byte per call.
+
+| Register | In | Out |
+| --- | --- | --- |
+| x0 | the `Console` capability slot | 0 on success, or an error |
+| x1 | flags | the byte |
+| x2 | | 1 if input was lost right before this byte |
+
+The flags are `NONBLOCK` (1) and `FLUSH` (2), and a timeout in ticks in bits 63 to 32. Any other bit is refused with `BAD_FLAGS`. `NO_DEVICE` (-24) means that there is no input path or that it was turned off.
+
+The `Console` capability now has rights: **R** reads input and **W** writes output. `CAP_COPY` can only remove them. The root task's capability has W, and R only in images with `console-input`. `DEBUG_PUTC` needs W. `bootinfo::VERSION` is 4.
+
+The output filter is unchanged, except for one thing: a `Console` capability with R (the terminal's) may also emit backspace (0x08). Every other control byte is still printed as `?`.
+
+## Waiting and waking
+
+Only one task can wait for input at a time. A second reader gets `BUSY` (-23). A reader that finds the ring empty and did not ask for `NONBLOCK` goes to sleep, with the timeout from its flags if there is one.
+
+- **Waking on a byte**: a received byte wakes the waiter. It goes to the end of the ready queue. There is no preemption on input.
+- **Waking on a capability change**: a waiter whose capability is deleted, revoked or moved wakes at once with `REVOKED`.
+- **Waking on a timeout**: a reader that gave a timeout in its flags is woken when it runs out (see [scheduling.md](scheduling.md) for timeouts).
+- **Quiet idle**: when the only thing left to wait for is console input, the kernel prints nothing. That is the normal state of a terminal image. `k0: all tasks stopped (none ready, no timeout pending)` is printed only when there is neither a timed waiter nor a console waiter.
+
+## The terminal's wiring and the hostile-task check
+
+A terminal image runs all self-tests first. Then the root task does the following:
+
+1. It starts a new vault (if one is built in) and hands it the boot seed. The log line is `root: vault seeded`, or `root: vault has no seed (boot seed has no entropy)`, or `root: vault has no seed (no algorithm in this image)`.
+2. It runs two hostile tasks wired exactly like the terminal. They must be refused and must end in a fault. The lines are `root: terminal console filter [...]`, `root: terminal wiring holds` and two `k0: task fault` lines.
+3. It drops its own admin capability, starts the terminal and blocks for ever. The line is `root: service started`, then the banner follows.
+
+On a machine without an input path the root task prints `root: no console input, terminal not started`.
+
+The terminal task has its own address space and two capabilities:
+
+- a `Console` copy with R and W, and
+- the vault endpoint with the send right and the operator badge.
+
+The vault's response frame is mapped read-only for it. The vault decides from the badge and the operation alone which frame it reads or writes. The operator has a response frame and no request frame. A request that claims a body it cannot have is refused without touching memory.
+
+The two hostile tasks are the check that the wiring means what it says. They are wired exactly like the terminal, and the root task expects both to be refused and to end in a fault. If one of them is not refused, the check fails.
+
+> [!WARNING]
+> There is no authentication on the serial line. Whoever holds the line is the operator and can do exactly the operator's four operations, including erasing the key. The operator cannot sign, cannot deliver a seed and cannot change the policy.
+
+## The screen and command rules
+
+The screen is plain text. The banner is `K0 operator console, type 'help'`, the prompt is `k0> `, values are printed as `name=value`, and every command ends with exactly one line, `ok` or `err `.
+
+| Command | What it does |
+| --- | --- |
+| `help` | Lists the commands. |
+| `vault status` | Prints the state of the vault. |
+| `vault pubkey` | Prints the public key. |
+| `vault keygen ` | Makes the key from the held seed. The only algorithm is `ed25519`. |
+| `vault zeroize confirm` | Erases the key. `vault zeroize` alone prints `hint=type 'vault zeroize confirm' to erase the key` and `err confirm-required`. |
+
+`vault status` prints `state=fresh|seeded|ready|zeroized|failed`, `alg=none|ed25519`, `selftest=passed|failed`, `seed=none|rng-seed|rndr|rng-seed+rndr` and `validated=no`. The value `seed=rng-seed` means that the bytes were present, not that they were unpredictable. The line `validated=no` is always printed, because the implementation has no validation of any kind.
+
+`vault pubkey` prints `pubkey=` and 32 hex characters, then a second line indented by 7 spaces with the other 32.
+
+The error names are `unknown-command`, `bad-argument`, `line-too-long`, `input-lost`, `confirm-required`, `denied`, `no-vault`, `no-key`, `key-exists`, `no-entropy`, `unsupported-algorithm`, `zeroized`, `vault-failed` and `vault-timeout`. A keygen or zeroize that was delivered but not answered in time adds `hint=run 'vault status' to see whether it took effect`.
+
+The input rules are the following. The state machine is `feed` in `userspace/k0-term/src/lib.rs`.
+
+- A line ends with CR or LF, has at most 64 characters, and contains printable ASCII only.
+- Backspace and DEL erase one character. Ctrl-C and Ctrl-U cancel the line and are shown as `^C` and `^U`.
+- ESC sequences (arrow keys) are ignored.
+- What reached the UART before the prompt is dropped.
+- A reported loss discards everything up to the next line end and prints `err input-lost`.
+- Without the vault feature, `help` lists only `help` and `vault ...` answers `err no-vault`.
+
+The vault side changed with this feature. There are four roles by endpoint badge, fixed at build time: admin (the root task), operator (the terminal), signer and reader. `INIT` (admin only, once) now only delivers the seed. The vault checks the entropy rule and holds the seed in the state `seeded`. The new operation `KEYGEN` (admin and operator) makes the key from the held seed and wipes the seed (state `ready`). One key per boot: a second `KEYGEN` is refused with `key-exists`, and after `ZEROIZE` a reboot is needed. Every way into `failed` wipes seed and key.
+
+## How it is tested
+
+**Host tests** (`tools/host-test.sh`): `k0-conin` has 15 tests with a fake UART, `k0-term` has 24 with the vault feature and 21 without, and `k0-vault` has 20 with Ed25519 and 11 without. The suite has 354 tests on an ARM host and 268 on other hosts.
+
+**Boot matrix**: the new rows are `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq`, the static row `input-symbols` (an image without `console-input` has no receive code and none of the new log lines), `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi` and `hvf-term`. The matrix has 76 rows on a Mac with HVF and 65 in CI.
+
+**Scripted session**: `tools/term-test.py ` boots the image with QEMU's serial port on pipes and runs a session. It covers every command and every error, erase and cancel, CR LF, an ESC sequence, a line that is too long, key generation, the public key format, zeroize, 200 kB without a line end, 2000 lines in a row and a serial break. `tools/qemu-boot-test.sh` reads `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none` and a judge-only mode `K0_BOOT_JUDGE`.
+
+**Root task self-test** (images with `console-input`): `root: backspace without the input right [?]` and `root: console input tests pass`. The second line may also read `... pass (no input path)` or `... cut short (the line is busy)` when bytes arrive during the test. A terminal image also shows two more `k0: task fault` lines than the same image without the terminal (8 without the vault, 10 with it).
+
+## Known gaps
+
+> [!NOTE]
+> Nothing ran on real hardware. The SBSA UART path, FIFO overruns and the receive timeout interrupt are not exercised by QEMU, and they are covered only by host tests with a fake UART. The cut-off for an interrupt line that fires without a UART cause is covered only by host tests.
+
+- **No authentication**: the serial line is as trusted as whoever can reach it. The operator can erase the key (a denial of service by design) but gets no signature and cannot change policy.
+- **Kernel code driven from outside**: the receive code runs at EL1.
+- **A timing channel that is not analysed**: an outside party can now cause interrupts while tasks run, bounded by the reader. The reader learns arrival times finer than the tick, and other tasks can notice the stolen time.
+- **Latency**: input waits behind running tasks. There are no priorities, so the latency is up to a tick per ready task.
+- **No input on a 16550 console**: a 16550 console has output and no input.
+- **No measurement under a flood**: no test measures kernel time under a flood on a machine. The bound is argued from the gate and shown in host tests.
+- **Dropped before the prompt**: this counts bytes that reached the UART. An emulator or adapter that holds bytes back delivers them later (QEMU does).
+- **Split screen line**: if a kernel line appears while the operator is typing, the screen line is split but the buffer is whole. Enter runs the whole buffer.
+- **Lines can be imitated**: any task with `Console` output can still print lines that look like kernel or root task lines, because nothing authenticates the prefix. The terminal can additionally erase within its current line.
+- **No signing client in service mode**: the key is made and shown, but no other task uses it yet. Client signing is shown by the self-test.
+- **No restart**: the terminal and the vault are not restarted if they die. The root task is trusted.
+- **Boot log share**: terminal output counts against the user share of the in-memory boot log. Once that share is full, later task output is not recorded there.
+- **All earlier limits of the vault stay**: the implementation is unvalidated, there is no side-channel analysis, the key does not come from an approved random bit generator, there is no persistence and there is no post-quantum algorithm. Availability is not protected (see [ipc.md](ipc.md)).
diff --git a/design/en/uefi.md b/design/en/uefi.md
index cd5691c..6c016a2 100644
--- a/design/en/uefi.md
+++ b/design/en/uefi.md
@@ -183,7 +183,7 @@ The loader has no signature code. Under Secure Boot the firmware verifies the wh
- **Host unit tests**: `crates/k0-efi/src/tests.rs` holds 32 tests. The vectors are measured firmware memory maps. They cover the descriptor rules, overlap, the entry limit, the writer, the rewrite, the verifier, the ACPI reader and the tree synthesis. A fourth fuzzer, `fuzz_acpi_with_mutated_tables`, mutates table images. Campaigns of 2 to 3 million cases passed on 2026-11-12, and it found one real mismatch earlier (the reader accepted a GIC frame alignment that the kernel's discovery refuses), which is fixed by applying the kernel's placement rules in the reader.
- **Three deterministic fuzzers**: `fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees` and `fuzz_prepare_end_to_end` in `k0-efi`. They use the same variables as the other fuzzers: `K0_FUZZ_ITERS`, `K0_FUZZ_SEED`, `K0_FUZZ_CASE`. The defaults are 20,000, 20,000 and 5,000 cases. The weekly workflow runs all three at 5 million cases. Campaigns of 5 million cases each passed on 2026-11-12. The planner fuzzer found one real bug earlier (a block at physical address 0 was accepted). It is fixed.
-- **Host test script**: `tools/host-test.sh` now runs 276 tests on an ARM host (`k0-abi` 14, `k0-cap` 42, `k0-boot` 82, `k0-efi` 32, `k0-vault` 13 with Ed25519 and 7 without, and `k0-mm` 43 for each of the two granules) and 190 on other hosts, where the `k0-mm` tests are skipped.
+- **Host test script**: `tools/host-test.sh` now runs 354 tests on an ARM host (`k0-abi` 15, `k0-cap` 44, `k0-boot` 85, `k0-efi` 33, `k0-conin` 15, `k0-vault` 20 with Ed25519 and 11 without, `k0-term` 24 with the vault feature and 21 without, and `k0-mm` 43 for each of the two granules) and 268 on other hosts, where the `k0-mm` tests are skipped.
- **PE check**: `tools/pe-check.py .efi` checks the PE form (four sections, none both writable and executable) and the order of the cache and MMU instructions, and prints `pe-check: ok (...)`.
- **Boot tests under EDK2**: `tools/qemu-virt-runner.sh` boots a `.efi` argument through EDK2 firmware. The default machine is `virt,gic-version=3,acpi=off`, so it uses the device tree path. The ACPI rows pass `K0_QEMU_MACHINE=virt,gic-version=3` or `virt,gic-version=2`. `tools/qemu-boot-test.sh` judges a failure from the loader's first line, `k0-loader: start`, so firmware messages do not count. `tools/build-loader.sh ` embeds an already built kernel and prints the path of the `.efi`, which is `.efi`. This way the UEFI rows boot the same kernel binary as the other rows. The usage notes in [USAGE.md](../../USAGE.md) show the commands.
@@ -253,6 +253,7 @@ Also: firmware that gives a device tree uses it, and ACPI is then not read. Firm
- **GIC from the MADT**: there is one distributor entry. Version 2 is GICv2, 3 or 4 is GICv3, 0 is decided by whether redistributors are described, and anything else is refused. GICv2 frame sizes are not in the table, so the loader uses 4 KiB for the distributor and 8 KiB for the CPU interface (the values Linux uses). GICv3 redistributors come from GICR entries (at most 4) or, without those, from the CPU entries, merged when adjacent at the 128 KiB or 256 KiB stride. The boot CPU's entry must be among them. Frames must be aligned, must not overlap each other, and must not lie in RAM or firmware memory according to the memory map, otherwise the loader refuses.
- **Timer from the GTDT**: the virtual EL1 timer interrupt must be 16 to 31.
- **Console from the SPCR** (optional): PL011 (type 0x03), SBSA UART (0x0D, 0x0E), and a 16550 (0x00, 0x01, 0x12) only with 8-bit registers and byte access, because the SPCR cannot express the register stride.
+- **Console interrupt from the SPCR** (optional): the interrupt type must be GIC only (bit 3 and no other) and the global system interrupt must be an SPI (32 to 1019). The loader writes it as the `interrupts` property of the console node (SPI number, level, active high), and the kernel reads it as described in [dtb.md](dtb.md). A table too short to hold the field, or any other form, gives a console without an interrupt, which is not a refusal: input is just off. The number appears in the `k0: platform` line (`irq33`), so a pin string made before this field existed no longer matches.
- **Refused versus booted without console**: a bad table, GIC, timer or a device in memory is refused (`ACPI tables: `). A console the kernel has no driver for, a wrong SPCR, or a console that lies in memory means a boot without console. The loader prints `k0-loader: device tree built from ACPI tables (MADT, GTDT and SPCR)` or `(MADT and GTDT, no usable SPCR console)`.
- **Entropy**: a tree built from ACPI has no firmware seed. The kernel gets 32 bytes when the firmware has `EFI_RNG_PROTOCOL` and nothing otherwise (it logs `k0: entropy dtb=0B` and continues).
- **Flushing the work area**: the loader also flushes its work area from the data cache before the jump. `tools/pe-check.py` requires three flush calls (block, work area, trampoline).
diff --git a/design/en/vault.md b/design/en/vault.md
index fda9683..893eb05 100644
--- a/design/en/vault.md
+++ b/design/en/vault.md
@@ -6,26 +6,28 @@ English | [한국어](../kr/vault_KR.md)
-This note describes the first service on top of K0's isolation core. A **vault** task holds one Ed25519 key. Client tasks get signatures and the public key over IPC, and they never get the key. The code is in `userspace/k0-vault` (the crate), `userspace/root-task/src/oracle.rs` (wiring and self-test) and `crates/k0-boot` (the boot seed).
+This note describes the first service on top of K0's isolation core. A **vault** task holds one Ed25519 key. Client tasks get signatures and the public key over IPC, and they never get the key. The code is in `userspace/k0-vault` (the crate), `userspace/root-task/src/oracle.rs` (wiring and self-test), `userspace/root-task/src/service.rs` (the service that starts after the self-tests) and `crates/k0-boot` (the boot seed). In an image built with `terminal`, the operator of the vault is the serial terminal (see "The service vault and the operator").
> [!NOTE]
> The vault is optional and off by default. The default image has no vault and no crypto code.
## Purpose and scope
-The vault shows that the isolation core can keep a secret away from the tasks that use it. It offers a small, fixed service: report status, return the public key, and sign a message of up to 1024 bytes.
+The vault shows that the isolation core can keep a secret away from the tasks that use it. It offers a small, fixed service: report status, return the public key, and sign a message of up to 1024 bytes. The key is made in two steps. The root task delivers a seed, and then the admin or the operator asks for a key.
The algorithm is Ed25519 (PureEdDSA with SHA-512, as in FIPS 186-5 and RFC 8032). The implementation is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind. The key does not come from an approved random bit generator. 14 crates were added to `vendor/` for it, and half of them are build-time or other-target code that is not compiled into a K0 image.
## Objects and who can map what
-
+
+
+
The root task creates the following objects:
-- **one endpoint**: the vault receives on it. A client's CNode holds only a send-only, badged copy of it (and a report endpoint in the self-test).
+- **one endpoint**: the vault receives on it. A client's CNode holds only a send-only, badged copy of it (and a report endpoint in the self-test). The terminal gets the same kind of copy with the operator badge.
- **the vault task**: it has its own address space and its own stack. The key lives there.
-- **per caller, a request frame and a response frame**: the request frame is read-write for the caller and read-only for the vault. The response frame is read-write for the vault and read-only for the caller. This is enforced by reduced-rights copies of the frame capabilities.
+- **per caller, a request frame and a response frame**: the request frame is read-write for the caller and read-only for the vault. The response frame is read-write for the vault and read-only for the caller. This is enforced by reduced-rights copies of the frame capabilities. The operator is the exception: it has a response frame, mapped read-only for it, and no request frame.
> [!WARNING]
> The root task builds all of this, so it is outside the isolation and could read the vault. The statement that holds is "no task other than the root task can map the vault's memory".
@@ -49,46 +51,82 @@ The reply sets all four registers:
| MR2 | the indicator bits |
| MR3 | the nonce |
-The operations are `STATUS`, `PUBLIC_KEY`, `SIGN` (a message of up to 1024 bytes in the request frame) and, for the admin badge only, `INIT` (the seed and the seed info, 40 bytes, once) and `ZEROIZE`.
+The operations are the following:
+
+| Operation | Meaning |
+| --- | --- |
+| `STATUS` | the state, the algorithm of the key and the algorithms in the image |
+| `PUBLIC_KEY` | the public key, in the response frame |
+| `SIGN` | signs a message of up to 1024 bytes in the request frame |
+| `INIT` | delivers the seed and the seed info (40 bytes, once, admin only). It makes no key |
+| `KEYGEN` | makes the key from the held seed with the algorithm chosen in MR0, and wipes the seed |
+| `ZEROIZE` | wipes the key and the held seed |
+
+`STATUS` packs the state, the algorithm of the key and the algorithms built into the image into the one word of MR1 (`proto::status_word`).
**The single fetch**: `server::fetch` fixes the length first, then reads the body once into a private buffer with volatile reads. Only the copy is used, so a caller that changes the frame during the call gains nothing. The response frame starts with the nonce and the length, and `server::publish` writes the nonce last. A client must trust the frame only after an `OK` reply that carries its own nonce.
-The state machine is `Vault::handle` in `userspace/k0-vault/src/server.rs`.
+The vault decides from the badge and the operation alone which frame it reads or writes (`proto::fetch_plan` and `proto::publish_plan`). Only `SIGN` and `INIT` carry a request body, and only `PUBLIC_KEY` and `SIGN` give a response body. A request that claims a body it cannot have is refused with `BAD_REQUEST`, and the vault touches no memory for it. This matters for the operator, which has no request frame: a made-up length cannot make the vault read an address that is not mapped.
+
+The state machine is `Vault::handle` in `userspace/k0-vault/src/server.rs`. The vault is in one of five states:
+
+| State | Meaning |
+| --- | --- |
+| `fresh` | no seed and no key |
+| `seeded` | `INIT` delivered a seed that passed the entropy rule, and the vault holds it |
+| `ready` | `KEYGEN` made the key and wiped the seed |
+| `zeroized` | `ZEROIZE` wiped the key and the seed. Only a reboot makes a new key |
+| `failed` | a self-test or the pairwise test failed. Every way into this state wipes the seed and the key |
+
+There is one key per boot. A second `KEYGEN` is refused with `KEY_EXISTS` (`key-exists` on the terminal).
## The fixed policy and badges
-The policy is fixed at build time and keyed by the endpoint badge. The kernel delivers the badge, and a client cannot forge it (see [ipc.md](ipc.md)). The roles are the following:
+The policy is fixed at build time and keyed by the endpoint badge. The kernel delivers the badge, and a client cannot forge it (see [ipc.md](ipc.md)). There are four roles, fixed at build time:
| Role | Operations |
| --- | --- |
-| admin (the root task) | `STATUS`, `INIT`, `ZEROIZE`, not `SIGN` |
+| admin (the root task) | `STATUS`, `INIT`, `KEYGEN`, `ZEROIZE`, not `SIGN` and not `PUBLIC_KEY` |
+| operator (the terminal) | `STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`, not `SIGN` and not `INIT` |
| signer | `STATUS`, `PUBLIC_KEY`, `SIGN` |
| reader | `STATUS`, `PUBLIC_KEY` |
-A call without a badge or with an unknown badge is refused. No operation changes the policy. All signers share the one key, so a signature carries no client identity.
+The operator can neither get a signature nor deliver a seed. A call without a badge or with an unknown badge is refused. No operation changes the policy. All signers share the one key, so a signature carries no client identity.
## The provider boundary
`userspace/k0-vault/src/provider.rs` is the only place that touches the crypto crate.
- **Self-test**: at start the vault runs a known-answer test with two RFC 8032 vectors (public key, signature, verification, and rejection of a changed message and of a changed signature).
-- **Key generation and the entropy rule**: the vault refuses to make a key (status `NO_ENTROPY`) unless the boot seed contains at least 32 bytes of `rng-seed` or 256 bits from RNDR. QEMU virt provides a 32-byte `rng-seed`.
-- **Pairwise test**: after key generation the vault checks that its own signature verifies. A failed self-test or a failed pairwise test puts the vault into a failed state that refuses everything but `STATUS`.
+- **Seed check and the entropy rule**: `INIT` refuses the seed (status `NO_ENTROPY`) unless the boot seed contains at least 32 bytes of `rng-seed` or 256 bits from RNDR, and it refuses an all-zero seed. A vault in an image without an algorithm refuses the seed (`UNSUPPORTED`) and stays `fresh`. QEMU virt provides a 32-byte `rng-seed`.
+- **Key generation**: `KEYGEN` makes the key from the held seed with the chosen algorithm and wipes the seed whether or not a key came out.
+- **Pairwise test**: after key generation the vault checks that its own signature verifies. A failed self-test or a failed pairwise test puts the vault into the `failed` state that refuses everything but `STATUS`.
- **Strict verification**: verification uses `verify_strict`.
- **No key export**: no operation returns the key.
-- **Zeroization**: `ZEROIZE` drops the key (the crate wipes it). The vault then refuses `SIGN` and `PUBLIC_KEY`.
-- **Indicator bits**: every reply carries four bits: the algorithm is in FIPS 186-5, the self-tests passed, at least 32 `rng-seed` bytes went into the key seed, and RNDR went into the key seed.
+- **Zeroization**: `ZEROIZE` drops the key (the crate wipes it) and the held seed. The vault then refuses `SIGN`, `PUBLIC_KEY` and `KEYGEN`.
+- **Indicator bits**: every reply carries four bits: the algorithm is in FIPS 186-5, the self-tests passed, at least 32 `rng-seed` bytes went into the key seed, and RNDR went into the key seed. `STATUS` reports the last two also for a seed that the vault still holds. A bit means that the bytes were present, not that they were unpredictable.
## The boot seed path
The kernel derives 32 bytes for the root task with SHA-256 under its own domain string from the DTB entropy, the counter and, when the CPU has RNDR, four fresh RNDR words (`k0_boot::derive_root_seed`). It is independent of the PAC keys by domain separation. The seed is as good as its inputs and no better.
-The seed is delivered in the root task's entry registers `x0` to `x3`. `x4` holds how many `rng-seed` bytes were used (bits 15 to 0), and bit 16 says that RNDR contributed. It is not in the bootinfo page, and `bootinfo::VERSION` is 3. The root task prints only `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr`, never the seed. It then gives the seed to the vault with `INIT`.
+The seed is delivered in the root task's entry registers `x0` to `x3`. `x4` holds how many `rng-seed` bytes were used (bits 15 to 0), and bit 16 says that RNDR contributed. It is not in the bootinfo page, and `bootinfo::VERSION` is 4. The root task prints only `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr`, never the seed. It then gives the seed to a vault with `INIT`, which only delivers it. The key is made later by `KEYGEN`.
**Seed wipe**: the FDT parser records where the `rng-seed` and `kaslr-seed` values are, and a second `/chosen` node is refused (`DuplicateChosen`, also in the UEFI loader's pre-check, which shares the parser). Right before the kernel enters the root task, it zeroes those bytes. `k0_mm::wipe_ro_alias` switches the read-only alias entry of the page to read-write in place (break-before-make), writes zeros, cleans and invalidates the cache lines, and switches it back. The kernel then reads the bytes back, wipes its own copy in `BootInfo`, prints `k0: dtb seeds wiped B` (40B on QEMU virt) and zeroes the boot stack below the live frames. This is the only write the kernel makes through the DTB mapping, and it happens after the DTB was parsed and validated.
> [!NOTE]
-> Copies that the firmware or the UEFI loader keep are not wiped, and neither is anything in the live frames of the boot stack. The scrubs of stack copies (the kernel boot stack, the vault stack after signing) are best effort.
+> Copies that the firmware or the UEFI loader keep are not wiped, and neither is anything in the live frames of the boot stack. The scrubs of stack copies (the kernel boot stack, the vault stack after key generation and signing) are best effort.
+
+## The service vault and the operator
+
+The real boot seed is used exactly once. In an image built with `terminal` and `vault`, the root task first runs all self-tests. Then it starts a new vault, the **service vault**, and hands it the boot seed with `INIT`. It prints `root: vault seeded`, or `root: vault has no seed (boot seed has no entropy)`, or `root: vault has no seed (no algorithm in this image)`. In every other image the root task wipes the seed at entry.
+
+The root task then runs two hostile tasks that are wired exactly like the terminal. They must be refused and end in a fault. After that it drops its own admin capability, starts the terminal and blocks for ever. The terminal can ask the service vault for `STATUS`, `PUBLIC_KEY`, `KEYGEN` and `ZEROIZE` through the operator badge, and for nothing else. The commands, the screen and the limits of the terminal are described in [USAGE.md](../../USAGE.md).
+
+> [!WARNING]
+> The serial line has no authentication. Whoever holds the line is the operator and can run exactly the four operator operations, including erasing the key. The operator cannot get a signature and cannot change the policy.
+
+The self-test vault is a different vault. It makes its key from the public RFC 8032 test seed, with the real seed info, so the entropy rule is still exercised, and the real seed never reaches it.
## Features and the fixed image
@@ -97,7 +135,13 @@ The `k0-kernel` crate has two features, and features only add:
- `vault`: the service, its protocol, policy and self-test, with no signing algorithm. Every signing request answers `UNSUPPORTED`.
- `vault-ed25519`: adds Ed25519.
-You can build it as follows:
+The feature `terminal` of the same crate adds the operator terminal. With `vault` the terminal is the operator of the vault, and with `vault-ed25519` it can make an Ed25519 key. It is off by default and needs a console driver. A terminal image is built as follows:
+
+```sh
+$ cargo build -p k0-kernel --features console,terminal,vault-ed25519
+```
+
+You can build an image with the vault as follows:
```sh
$ cargo build -p k0-kernel --features console,vault-ed25519
@@ -107,17 +151,18 @@ $ cargo build -p k0-kernel --features console,vault-ed25519
## How it is tested
-**Host tests** (`tools/host-test.sh` runs `k0-vault` with and without the algorithm feature). The tests are in `userspace/k0-vault/src/tests.rs`: 13 with Ed25519 and 7 without. The test names are the following:
+**Host tests** (`tools/host-test.sh` runs `k0-vault` with and without the algorithm feature). The tests are in `userspace/k0-vault/src/tests.rs`: 20 with Ed25519 and 11 without. The test names are the following:
-- always: `badges_map_to_fixed_roles`, `policy_is_enforced_before_anything_else`, `malformed_requests_are_refused_whole`, `a_seed_without_real_entropy_makes_no_key`, `init_happens_once_and_zeroize_is_final`, `fetch_clamps_the_length_and_publish_writes_header_and_body`, and `without_an_algorithm_every_signing_request_is_unsupported` (the last one without the algorithm only).
-- with Ed25519: `the_self_test_passes_and_is_reported`, `signatures_verify_and_the_key_follows_the_seed`, `a_public_key_request_carries_no_body`, `unknown_algorithms_are_unsupported`, `nothing_is_served_after_zeroize`, `a_small_order_public_key_is_refused_even_with_a_matching_signature`, `a_failed_vault_refuses_everything_but_status`.
+- always: `badges_map_to_fixed_roles_and_frames`, `each_role_may_do_exactly_its_operations`, `no_frame_is_touched_for_a_request_that_cannot_have_a_body`, `a_request_that_claims_a_body_it_cannot_have_is_refused`, `the_status_word_packs_state_algorithm_and_what_is_built`, `a_call_without_a_known_badge_is_denied`, `malformed_requests_are_refused_whole`, `a_seed_without_real_entropy_makes_no_key`, `the_seed_is_taken_once_and_zeroize_is_final`, `fetch_clamps_the_length_and_publish_writes_header_and_body`, and `without_an_algorithm_the_vault_takes_no_seed_and_serves_nothing` (the last one without the algorithm only).
+- with Ed25519: `the_self_test_passes_and_is_reported`, `key_generation_follows_the_states`, `the_operator_gets_the_public_key_and_never_a_signature`, `a_vault_that_fails_holds_no_secret`, `signatures_verify_and_the_key_follows_the_seed`, `a_public_key_request_carries_no_body`, `unknown_algorithms_are_unsupported`, `nothing_is_served_after_zeroize`, `a_small_order_public_key_is_refused_even_with_a_matching_signature`, `a_failed_vault_refuses_everything_but_status`.
-With the other crates, the host suite has 276 tests on an ARM host and 190 on other hosts (without `k0-mm`).
+With the other crates, the host suite has 354 tests on an ARM host and 268 on other hosts (without `k0-mm`).
**Root task self-test** (`test_oracle` in `userspace/root-task/src/oracle.rs`, only in images built with `vault`). It checks the following:
- the self-test is reported, and an unbadged call is refused,
-- a key is made from the boot seed, and a second `INIT` is refused,
+- the self-test vault gets the public RFC 8032 test seed with `INIT` (state `seeded`), the operator cannot seed or sign, and a second `INIT` is refused,
+- `KEYGEN` makes the key from that seed, and a second `KEYGEN` is refused (`KEY_EXISTS`),
- the admin cannot sign,
- a signer client gets a signature that verifies, and that does not verify for a changed message or a changed signature,
- a reader is refused `SIGN`,
@@ -128,14 +173,16 @@ With the other crates, the host suite has 276 tests on an ARM host and 190 on ot
The marker is `root: oracle tests pass`. The client tasks run one after another in one client address space, because root CNode slots are scarce. The test shows isolation between the vault and a client, not between clients.
-**Boot matrix rows**: `vault`, `vault-max` (RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, and the static row `vault-symbols` (the default image has no vault or crypto code, and the vault image has no writable static from them). The matrix has 61 rows on a Mac with HVF and 51 in CI. Every image now also prints `k0: dtb seeds wiped B` and `root: boot seed from rng-seed bytes ...`.
+**Boot matrix rows**: `vault`, `vault-max` (RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, and the static row `vault-symbols` (the default image has no vault or crypto code, and the vault image has no writable static from them). The matrix has 76 rows on a Mac with HVF and 65 in CI. The rows for the terminal are `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi` and `hvf-term`. `tools/term-test.py ` boots a terminal image with QEMU's serial port on pipes and runs a scripted session. Every image now also prints `k0: dtb seeds wiped B` and `root: boot seed from rng-seed bytes ...`.
## Known gaps
> [!NOTE]
> The implementation is unvalidated, there is no side-channel analysis of the crate on this kernel, and the oracle was only run in QEMU (TCG and HVF).
-- **One key**: there is no persistence, no key import or export, no DRBG, no operator input and no post-quantum algorithm yet.
+- **One key**: there is no persistence, no key import or export, no DRBG and no post-quantum algorithm yet. A new key needs a reboot.
+- **No signing client in service mode**: the service vault's key is made and shown, but no other task uses it yet. Client signing is shown by the self-test.
+- **The terminal and the vault are not restarted**: if they die, they stay dead. The root task is trusted.
- **Availability is not protected**: clients share one endpoint and must use timeouts on every call (see [ipc.md](ipc.md)).
- **The root task is trusted**: it builds the vault and could read it.
- **No client identity**: all signers share the one key.
diff --git a/design/kr/README.md b/design/kr/README.md
index 88976b7..faa7f0f 100644
--- a/design/kr/README.md
+++ b/design/kr/README.md
@@ -26,5 +26,6 @@
| [scheduling_KR.md](scheduling_KR.md) | TCB와 거기에 묶인 CNode, 주소 공간, 태스크 생성과 정리, 라운드 로빈 스케줄러, 타이머 선점 |
| [ipc_KR.md](ipc_KR.md) | 엔드포인트와 배지, `SEND`, `RECV`, `CALL`, `REPLY_RECV`, 1회성 응답 자격, 엔드포인트가 삭제될 때 대기 중인 태스크의 처리 |
| [vault_KR.md](vault_KR.md) | 서명 오라클: 볼트 태스크와 프레임, `CALL` 프로토콜과 nonce, 고정된 배지 정책, 프로바이더 경계, 부팅 시드와 지우기, feature, 테스트, 알려진 공백 |
+| [terminal_KR.md](terminal_KR.md) | 시리얼 입력과 운영자 터미널: 커널이 입력을 받는 이유, 수신 링과 그 한계, `CONSOLE_READ`와 Console 권한, 대기와 깨우기, 터미널의 연결과 적대적 태스크 점검, 화면과 명령 규칙, 테스트, 알려진 공백 |
모든 노트는 "**알려진 공백**" 절로 끝납니다. 열려 있는 보안 어드바이저리는 [SECURITY_KR.md](../../SECURITY_KR.md)에 정리되어 있습니다.
diff --git a/design/kr/boot_KR.md b/design/kr/boot_KR.md
index 771c4e8..4511bf9 100644
--- a/design/kr/boot_KR.md
+++ b/design/kr/boot_KR.md
@@ -102,7 +102,7 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16
| `k0: dtb rejected: ...` (실패할 때만) | `map_dtb`가 별칭을 통해 DTB를 읽기 전용으로 매핑합니다. 포인터(null이 아니고 8바이트 정렬)와, 매직과 전체 크기만 읽는 `dtb_span`을 검사합니다. |
| `k0: memory ...` | 별칭을 통해 DTB를 파싱합니다. 파서는 [dtb_KR.md](dtb_KR.md)에서 다룹니다. |
| `k0: console drivers [...]` | 플랫폼 기동의 첫 줄이며, 나중에 플랫폼이 거부되더라도 출력됩니다. 이 이미지에 들어 있는 콘솔 드라이버를 알려 줍니다("선택적 콘솔 출력" 참고). |
-| `k0: platform ...` | `bring_up_platform`이 DTB에서 콘솔, 인터럽트 컨트롤러, 타이머 인터럽트를 찾아 불변인 플랫폼 기술서 하나를 만듭니다. 디바이스 페이지를 매핑하기 전에 기술서를 메모리 맵과 대조합니다. RAM은 2^47 아래여야 하고, 커널 이미지와 DTB는 선언된 메모리 안에 있어야 하며, 그래뉼 단위로 넓힌 디바이스 구간은 메모리나 예약 구간과 겹치거나 CPU의 물리 주소 폭(`k0_mm::pa_bits`)을 넘으면 안 됩니다. 고정 모드에서는 이어서 이 줄을 기대값과 비교합니다. 그 뒤에야 콘솔을 연결합니다. 이 종류의 콘솔 드라이버가 있는 이미지는 콘솔을 매핑하고 연결하며, 이때 버퍼에 쌓인 로그가 재생됩니다. 드라이버가 없는 이미지는 아무것도 매핑하지 않고 `k0: no console (driver not built in)`을 출력합니다. 플랫폼이 거부되더라도 콘솔만으로 대조를 통과하면(그리고 이미지가 고정 모드가 아니고 드라이버가 있으면) 사유가 보이도록 콘솔을 먼저 연결합니다. 콘솔이 없으면 `k0: no console (...)`이 이유를 알려 줍니다. [dtb_KR.md](dtb_KR.md)를 참고하세요. |
+| `k0: platform ...` | `bring_up_platform`이 DTB에서 콘솔, 콘솔의 인터럽트(콘솔 노드에 쓸 만한 것이 있을 때), 인터럽트 컨트롤러, 타이머 인터럽트를 찾아 불변인 플랫폼 기술서 하나를 만듭니다. 디바이스 페이지를 매핑하기 전에 기술서를 메모리 맵과 대조합니다. RAM은 2^47 아래여야 하고, 커널 이미지와 DTB는 선언된 메모리 안에 있어야 하며, 그래뉼 단위로 넓힌 디바이스 구간은 메모리나 예약 구간과 겹치거나 CPU의 물리 주소 폭(`k0_mm::pa_bits`)을 넘으면 안 됩니다. 이 줄에는 콘솔 인터럽트 번호가 들어갑니다(예: `k0: platform con=pl011@0x9000000,irq33 ...`). 고정 모드에서는 이어서 이 줄을 기대값과 비교하므로, 이 필드가 생기기 전에 만든 고정 문자열은 더 이상 맞지 않아 다시 만들어야 합니다. 그 뒤에야 콘솔을 연결합니다. 이 종류의 콘솔 드라이버가 있는 이미지는 콘솔을 매핑하고 연결하며, 이때 버퍼에 쌓인 로그가 재생됩니다. 드라이버가 없는 이미지는 아무것도 매핑하지 않고 `k0: no console (driver not built in)`을 출력합니다. 플랫폼이 거부되더라도 콘솔만으로 대조를 통과하면(그리고 이미지가 고정 모드가 아니고 드라이버가 있으면) 사유가 보이도록 콘솔을 먼저 연결합니다. 콘솔이 없으면 `k0: no console (...)`이 이유를 알려 줍니다. [dtb_KR.md](dtb_KR.md)를 참고하세요. |
| `k0: root task integrity ok (...)` | 내장 루트 태스크 이미지를 다시 해시하고 빌드 시점에 고정된 해시와 비교합니다. |
| `k0: entropy ...`, `k0: pac=... bti=... pan=...` | PAC 키를 파생해 적재하고 키 워드를 부트 스택에서 지웁니다. 루트 태스크에 넘길 32바이트 시드도 여기서 PAC 키와 독립적으로 파생하여 이양까지 보관합니다. PAN을 켜고, 카운터·디버그·PMU에 대한 EL0 접근을 끕니다. [hardening_KR.md](hardening_KR.md)를 참고하세요. |
| `k0: irq on (timer 1s)` | `setup_irq`가 필요한 인터럽트 컨트롤러 페이지만 매핑합니다. GICv3는 리디스트리뷰터 프레임을 하나씩 들여다보며 부트 CPU의 프레임을 찾은 뒤, 그 프레임과 SGI 프레임만 매핑합니다. 드라이버는 GIC 식별 레지스터가 DTB의 설명과 맞는지 확인합니다. EL1 가상 타이머는 플랫폼 기술서의 인터럽트 번호로 설정합니다. IRQ와 SError의 마스크를 해제합니다. |
@@ -110,7 +110,8 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16
| `k0: root task loaded (entry ...)` | 루트 태스크를 윈도우의 프레임에 복사하고, 윈도우에 루트 TCB를 만들고, 주소 공간을 만듭니다. 커널은 사용자 루트 테이블의 물리 주소를 출력하지 않습니다. 이후 이 주소 공간을 주소 공간 등록부에 올립니다. [user-address-space_KR.md](user-address-space_KR.md)를 참고하세요. |
| `k0: memory + not handed out ()`(일어날 때만), `k0: kernel reserve tables + address space entries = bytes in ranges` | `reserve_kernel_share`가 untyped 케이퍼빌리티가 만들어지기 전에 비어 있는 물리 범위마다 커널 몫을 떼어 냅니다("untyped 메모리에서 커널 몫 떼어 내기" 참고). 자기 몫을 담지 못하는 범위는 넘기지 않으며, 이때 커널은 첫 번째 종류의 줄에 이유를 출력합니다. 두 번째 줄은 한 번 출력됩니다. 예를 들어 512 MiB, 4 KiB 그래뉼의 QEMU virt에서는 `k0: kernel reserve 262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`입니다. |
| `k0: untyped ...`, `k0: root cnode ready (N caps, N untyped, N image frames, N slots)` | 루트 CNode(윈도우 안의 오브젝트이며 슬롯은 `ROOT_CNODE_SLOTS` = 512개, 로그에도 그렇게 나옵니다)를 채웁니다. 슬롯 1은 루트 TCB, 2는 루트 주소 공간, 3은 콘솔, 4는 루트 CNode 자신이고, 이어서 넘기기로 한 비어 있는 물리 범위마다 untyped 케이퍼빌리티, 루트 태스크 이미지의 매핑된 그래뉼마다 Frame 케이퍼빌리티 하나(text는 R과 X, 읽기 전용 데이터는 R, 데이터는 R과 W)가 들어갑니다. 마지막으로 루트 태스크를 다른 태스크와 똑같이 자신의 CNode와 주소 공간에 묶습니다. 두 케이퍼빌리티의 복사본이 TCB에 들어갑니다. [capabilities_KR.md](capabilities_KR.md)를 참고하세요. |
-| `k0: bootinfo page ready` | 케이퍼빌리티 목록을 읽기 전용 bootinfo 페이지(레이아웃 버전 3)에 기록합니다. 헤더와 슬롯마다 하나의 디스크립터이며, 이미지 Frame마다 VA, 크기, 권한이 들어갑니다. 이 페이지에는 부트 시드가 들어 있지 않습니다. |
+| `k0: console input on (pl011 irq 33)` 또는 `k0: console input off ()` | `console-input`으로 빌드한 이미지만 플랫폼이 받아들여진 직후에 출력합니다. "선택적 콘솔 입력"을 참고하십시오. |
+| `k0: bootinfo page ready` | 케이퍼빌리티 목록을 읽기 전용 bootinfo 페이지(레이아웃 버전 4)에 기록합니다. 헤더와 슬롯마다 하나의 디스크립터이며, 이미지 Frame마다 VA, 크기, 권한이 들어갑니다. 이 페이지에는 부트 시드가 들어 있지 않습니다. |
| `k0: user w^x checks pass` | `TTBR0`가 사용자 테이블을 가리키고, identity 매핑은 사라졌으며, 사용자 매핑을 EL0와 EL1 양쪽에서 검사합니다. |
| `k0: dtb seeds wiped B` | 이제 DTB는 필요 없으므로 커널이 그 안의 `rng-seed`와 `kaslr-seed` 바이트를 0으로 지웁니다(읽기 전용 별칭을 쓰는 동안만 읽기·쓰기로 바꿈). 지운 바이트를 다시 읽어 확인하고, 커널이 가진 자기 사본도 지웁니다. QEMU virt에서는 `40B`입니다. 다시 읽은 값이 0이 아니면 줄은 `k0: WARNING dtb seeds not wiped`가 됩니다. [hardening_KR.md](hardening_KR.md)를 참고하세요. |
| `k0: device pages [...] of 0x1000 bytes` | 커널이 매핑한 채로 두는 모든 디바이스 페이지입니다. 이 줄 뒤에 커널은 더 이상 디바이스를 매핑하지 않습니다. |
@@ -153,12 +154,9 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16
## 선택적 콘솔 출력
-K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트(`k0-kernel`)의 Cargo features로 선택할 수 있습니다.
+K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트(`k0-kernel`)의 Cargo features로 선택할 수 있습니다. 콘솔 출력은 아래 콘솔 feature로 선택합니다. 콘솔 입력과 운영자 터미널에는 별도의 feature가 있으며, "선택적 콘솔 입력"에서 설명합니다.
-> [!NOTE]
-> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다.
-
-콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다(옵트인). 입력은 어떤 이미지에도 없습니다. 다음 그림은 빌드에 포함한 feature에 따라 출력이 닿는 곳을 보여 줍니다.
+콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다(옵트인). `console-input` 없이 빌드한 이미지에는 입력 코드가 전혀 없습니다. 다음 그림은 빌드에 포함한 feature에 따라 출력이 닿는 곳을 보여 줍니다.
@@ -219,11 +217,30 @@ $ K0_PIN='...' cargo build -p k0-kernel --features console --offline --target-di
**기여자 규칙**: 다음 규칙을 지켜야 합니다.
-- 새로운 입력 또는 출력 경로는 처음부터 Cargo feature 뒤에 둡니다(지금 있는 것은 콘솔 출력뿐입니다).
+- 새로운 입력 또는 출력 경로는 처음부터 Cargo feature 뒤에 둡니다(지금 있는 것은 콘솔 출력, `console-input`, `terminal`입니다).
- feature는 더하기만 하며 `default`에 추가하지 않습니다.
- 지원하는 조합마다 부팅 매트릭스에 행을 둡니다.
- 스크립트, `virt` 별칭, CI는 feature를 명시합니다.
+### 선택적 콘솔 입력
+
+콘솔 입력은 두 번째 옵트인 계층입니다. 기본값은 꺼짐이며, feature는 기능을 더하기만 합니다. 다음 표는 `k0-kernel`의 feature를 보여 줍니다.
+
+| Feature | 추가하는 것 |
+| --- | --- |
+| `console-input` | 콘솔 UART의 커널 수신 경로와 시스템 콜 `CONSOLE_READ`([exceptions_KR.md](exceptions_KR.md) 참고). 콘솔 드라이버 feature가 있어야 동작합니다. 수신은 PL011과 SBSA UART에만 있어서, 16550 콘솔은 출력만 있고 입력은 없습니다. |
+| `terminal` | 루트 태스크 이미지에 들어가는 운영자 터미널 태스크. `console-input`을 함께 켭니다. |
+
+> [!NOTE]
+> `console-input` 없이 빌드한 이미지에는 수신 코드도, `CONSOLE_READ`도, 아래 로그 줄도 없습니다. 정적 매트릭스 행 `input-symbols`가 이를 검사합니다.
+
+- **기동**: 콘솔 인터럽트 번호는 디바이스 트리([dtb_KR.md](dtb_KR.md) 참고)에서 오고, UEFI에서는 ACPI SPCR 테이블에서 옵니다. 이 번호는 `k0: platform` 줄에 들어갑니다. 수신 인터럽트는 태스크가 읽기 권리로 콘솔 입력을 처음 읽을 때까지 꺼져 있습니다. 쓸 만한 인터럽트가 없는 콘솔 노드는 부팅 거부 사유가 아니며, 입력만 꺼집니다.
+- **로그 줄**: `k0: console input on (pl011 irq 33)` 또는 `k0: console input off ()`입니다. 이유는 `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range`, `interrupt not available`입니다. 인터럽트 번호가 틀려도 입력 경로만 잃습니다.
+- **첫 읽기**: 장치가 쥐고 있던 바이트를 버리고, 줄 하나 `k0: tick lines off (console input in use)`를 남긴 뒤 주기적인 `k0: tick N` 줄을 멈춥니다. 틱, 선점, 타임아웃은 그대로 동작합니다.
+- **증거**: 행 `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq`, `input-symbols`(정적), `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi`, `hvf-term`이 `tools/boot-matrix.sh`에 있습니다. `tools/qemu-boot-test.sh`는 `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none`, 판정 전용 `K0_BOOT_JUDGE`를 읽습니다. `tools/term-test.py `는 QEMU 시리얼 포트로 스크립트 터미널 세션을 실행합니다.
+
+SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU에서 실행되지 않습니다. 가짜 UART를 쓰는 호스트 테스트(`crates/k0-conin`)만 이를 다룹니다.
+
## 신뢰 문제
이제 DTB가 디바이스 주소를 제공하므로, 잘못되었거나 적대적인 DTB는 콘솔을 다른 디바이스로 향하게 할 수 있습니다. 커널은 다음 다섯 가지로 이를 제한합니다.
@@ -302,5 +319,5 @@ $ cargo build -p k0-kernel --features console --offline
- 코어 하나만 실행되며, 부트로더가 CPU를 정확히 하나만 진입시켜야 합니다. K0에는 다른 CPU를 시작하거나 파킹하는 코드가 없습니다.
- 커널은 항상 같은 가상 주소에 놓입니다. 주소 무작위화가 없습니다.
- 릴리즈 빌드는 패닉 때 아무것도 출력하지 않습니다. 의도한 동작이지만, 릴리즈 빌드에서는 패닉이 나도 진단을 얻을 수 없다는 뜻이기도 합니다.
-- 입력은 어떤 이미지에도 없습니다. 콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있으며, 그 증거의 한계는 "선택적 콘솔 출력"에 있습니다.
+- 콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있고, 콘솔 입력은 `console-input`으로 빌드한 이미지에만 있습니다. 그 증거의 한계는 "선택적 콘솔 출력"과 "선택적 콘솔 입력"에 있습니다.
- UEFI에서는 로더의 캐시 비우기와 MMU 끄기를 QEMU로 테스트할 수 없고(캐시가 없습니다), ACPI만 있는 펌웨어는 세 정적 테이블만으로 부팅합니다(부팅해 본 것은 QEMU virt뿐입니다). 로더의 한계는 [uefi_KR.md](uefi_KR.md)에 모두 있습니다.
diff --git a/design/kr/capabilities_KR.md b/design/kr/capabilities_KR.md
index a6bdd90..53d7a0c 100644
--- a/design/kr/capabilities_KR.md
+++ b/design/kr/capabilities_KR.md
@@ -23,7 +23,7 @@
| `crates/k0-abi/src/lib.rs` | 번호와 에러 코드(ABI의 기준) |
> [!IMPORTANT]
-> 이 모델과 함께 시스템 콜 ABI가 호환되지 않게 바뀌었습니다(bootinfo 버전 2, 현재 3). 이 내용에 의존하기 전에 "알려진 공백" 절을 먼저 읽어 주세요.
+> 이 모델과 함께 시스템 콜 ABI가 호환되지 않게 바뀌었습니다(bootinfo 버전 2, 현재 4). 이 내용에 의존하기 전에 "알려진 공백" 절을 먼저 읽어 주세요.
케이퍼빌리티 기반 격리가 다루는 것은 태스크 간 기밀성과 무결성입니다. 가용성은 포함하지 않습니다.
@@ -66,14 +66,15 @@
| `Endpoint` | `RETYPE`으로 | 동기 IPC의 랑데부 지점 |
| `CNode` | `RETYPE`으로, 그리고 루트 CNode용으로 부팅 시 | 슬롯 배열. 케이퍼빌리티 공간이자 복사와 이동의 목적지로 쓰임 |
| `AddrSpace` | `RETYPE`으로, 그리고 루트 태스크용으로 부팅 시 | 주소 공간. 그 안에 매핑하고 그 안에서 태스크를 실행할 권한 |
-| `Console` | 부팅 시 | 디버그 출력에 바이트를 쓸 권한. 부트 로그, 그리고 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔 |
+| `Console` | 부팅 시 | 디버그 출력에 바이트를 쓸 권한(`W`). 부트 로그, 그리고 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔. `R`이 있으면 `console-input`으로 빌드한 이미지에서 콘솔 입력을 읽을 권한도 됨 |
### 권한
-**권한 비트**는 `R` = 1, `W` = 2, `X` = 4입니다. 의미를 갖는 종류는 둘뿐입니다.
+**권한 비트**는 `R` = 1, `W` = 2, `X` = 4입니다. 의미를 갖는 종류는 셋뿐입니다.
- **Frame**: 매핑 권한의 상한입니다. `RO`는 `R`, `RW`는 `R|W`, `RX`는 `R|X`가 필요합니다. `RETYPE`으로 만든 프레임은 `R|W`를 갖고, `X`는 영영 얻을 수 없습니다.
- **Endpoint**: `R`은 수신, `W`는 송신 권한입니다. 새 엔드포인트 케이퍼빌리티는 둘 다 가집니다.
+- **Console**: `W`는 출력 권한(`DEBUG_PUTC`), `R`은 입력을 읽을 권한(`CONSOLE_READ`)입니다. `CAP_COPY`는 이 권한을 줄이는 것만 가능하며, 권한이 하나도 남지 않는 복사는 `NO_RIGHTS`로 실패합니다. `R`이 있는 `Console` 케이퍼빌리티는 `DEBUG_PUTC`로 백스페이스 바이트(0x08)도 내보낼 수 있습니다. 다른 제어 바이트는 여전히 `?`로 출력됩니다.
다른 종류는 권한을 갖지 않으며, 그 종류에서는 `CAP_COPY`의 권한 마스크가 무시됩니다. **권한은 줄이는 것만 가능**하며, 줄이는 방법은 `CAP_COPY`뿐입니다.
@@ -114,7 +115,7 @@
| 0 | null |
| 1 | 루트 태스크의 `Tcb` |
| 2 | 루트 태스크의 `AddrSpace` |
-| 3 | `Console` |
+| 3 | `W`가 있는 `Console`. `R`은 `console-input`으로 빌드한 이미지에만 있음 |
| 4 | `CNode`. 루트 CNode 자신에 대한 케이퍼빌리티로, 복사와 이동의 목적지로 쓸 수 있음 |
| 5 이후 | `Untyped` 케이퍼빌리티들, 그다음 루트 태스크 이미지의 매핑된 그래뉼마다 `Frame` 케이퍼빌리티 하나 |
@@ -138,7 +139,7 @@ untyped 케이퍼빌리티는 디바이스 트리가 보고한 RAM의 모든 바
## bootinfo 페이지
-이양 직전에 커널은 루트 CNode의 설명을 bootinfo 페이지에 기록합니다. 이 페이지는 루트 태스크에 읽기 전용으로 `bootinfo::VA`에 매핑됩니다. 버전은 3입니다(`bootinfo::VERSION`). 페이지 레이아웃은 버전 2와 같습니다. 버전이 바뀐 이유는 루트 태스크가 이제 진입 레지스터로 부트 시드를 받기 때문이며(시드는 `x0..x3`, 그 설명은 `x4`)(자세한 내용은 [boot_KR.md](boot_KR.md) 참고), 시드는 이 페이지에 없습니다. 다른 버전이면 루트 태스크는 진행하면 안 됩니다.
+이양 직전에 커널은 루트 CNode의 설명을 bootinfo 페이지에 기록합니다. 이 페이지는 루트 태스크에 읽기 전용으로 `bootinfo::VA`에 매핑됩니다. 버전은 4입니다(`bootinfo::VERSION`). 페이지 레이아웃은 버전 2와 같습니다. 버전 3은 루트 태스크가 진입 레지스터로 부트 시드를 받게 되어 생겼으며(시드는 `x0..x3`, 그 설명은 `x4`)(자세한 내용은 [boot_KR.md](boot_KR.md) 참고), 시드는 이 페이지에 없습니다. 버전 4는 `Console` 케이퍼빌리티에 권한이 생겨 만들어졌습니다. 다른 버전이면 루트 태스크는 진행하면 안 됩니다.
페이지는 헤더 `{version, frame_size, cap_count, cnode_slots}`로 시작하고, 그 뒤에 `cap_count`개의 디스크립터 `{kind, base, size, rights}`가 이어집니다. 디스크립터의 인덱스가 곧 루트 CNode의 슬롯 번호이며, `cap_count` 이상의 슬롯은 전부 비어 있습니다. 디스크립터는 종류에 따라 다음과 같이 채워집니다.
@@ -232,6 +233,7 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조
- **Frame**: 이 케이퍼빌리티가 만든 매핑을 지웁니다. 복사본을 포함해 매핑 기록이 있는 모든 `Frame` 케이퍼빌리티에 해당합니다.
- **PageTable**: 주소 공간에서 연결을 끊습니다(마찬가지로 기록이 있는 모든 케이퍼빌리티에 해당).
- **Endpoint**(원본): 줄 서 있던 태스크를 전부 `REVOKED`로 깨웁니다.
+- **Console**: 이 케이퍼빌리티로 `CONSOLE_READ`에서 기다리던 태스크는 케이퍼빌리티가 삭제, 회수, 이동되면 즉시 `REVOKED`로 깨어납니다([ipc_KR.md](ipc_KR.md) 참고).
- **Tcb**(원본), 그리고 태스크에 묶인 모든 케이퍼빌리티: 그 태스크를 종료시킵니다. [scheduling_KR.md](scheduling_KR.md)와 [ipc_KR.md](ipc_KR.md)를 참고하세요.
- **AddrSpace**(원본): 등록부에서 해제하고(이때 세대가 올라갑니다), TTBR0에 설치돼 있으면 TTBR0를 커널 풀의 빈 테이블로 바꿉니다.
@@ -247,7 +249,8 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조
| 시스템 콜 | 필요한 케이퍼빌리티와 권한 |
| --- | --- |
-| `DEBUG_PUTC` | `Console` |
+| `DEBUG_PUTC` | `W`가 있는 `Console` |
+| `CONSOLE_READ` | `R`이 있는 `Console`(`console-input`으로 빌드한 이미지에만 있음) |
| `RETYPE` | `Untyped`, 그리고 호출자 CNode의 빈 목적지 슬롯 |
| `MAP` | 권한이 요청한 매핑을 덮는 `Frame`(`RO`는 `R`, `RW`는 `R\|W`, `RX`는 `R\|X` 필요) 또는 `PageTable`, 그리고 타겟을 지정하는 `AddrSpace` |
| `UNMAP` | 매핑된 `Frame` 또는 `PageTable` |
@@ -280,7 +283,7 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조
| `BAD_PERM` | 매핑 권한이나 권한 마스크 값이 올바르지 않음 |
| `BAD_BADGE` | 배지를 가질 수 없는 종류에 배지를 요구했거나, 이미 배지가 있는 케이퍼빌리티에 다른 배지를 요구함 |
| `TOO_DEEP` | 파생 깊이 상한을 넘게 됨 |
-| `REVOKED` | 대기 중이던 엔드포인트가 삭제되어 깨어난 태스크가 받음 |
+| `REVOKED` | 대기 중이던 엔드포인트가 삭제되어 깨어난 태스크가 받음. `CONSOLE_READ`로 기다리던 `Console` 케이퍼빌리티가 삭제, 회수, 이동되어 깨어난 태스크도 받음 |
| `KERNEL_RESOURCE` | 커널 내부 자원 부족. 여전히 정의된 코드이지만, 커널 별칭 테이블과 주소 공간 등록부는 더 이상 원인이 될 수 없음 |
## 테스트 방법
diff --git a/design/kr/dtb_KR.md b/design/kr/dtb_KR.md
index 16fb372..6381254 100644
--- a/design/kr/dtb_KR.md
+++ b/design/kr/dtb_KR.md
@@ -95,9 +95,10 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야
## 플랫폼 기술서
-메모리 외에 커널이 DTB에서 찾는 디바이스는 정확히 세 가지이며 그 밖에는 없습니다(`crates/k0-boot/src/platform.rs`의 `discover`).
+메모리 외에 커널이 DTB에서 찾는 디바이스는 정확히 세 가지와 콘솔의 인터럽트뿐이며 그 밖에는 없습니다(`crates/k0-boot/src/platform.rs`의 `discover`).
- **콘솔**: `/chosen/stdout-path`가 가리키는 노드뿐입니다(절대 경로, 또는 절대 경로로 풀리는 별칭). 노드는 사용 가능해야 하고, `compatible`이 PL011(`arm,pl011`), SBSA UART(`arm,sbsa-uart`), 16550 계열(`ns16550a`, `ns16550`, `snps,dw-apb-uart`, `brcm,bcm2835-aux-uart`) 중 하나여야 합니다. 그 밖의 UART, 없거나 풀리지 않는 `stdout-path`, CPU 물리 주소로 변환할 수 없는 노드는 콘솔 없이 부팅합니다. 에러가 아닙니다. 커널은 이유와 함께 `k0: no console (...)`을 출력하고, 부트 로그 버퍼가 유일한 기록이 됩니다([boot_KR.md](boot_KR.md) 참고). 이 발견과 검증은 모든 이미지가 수행하며, 콘솔 드라이버 없이 빌드한 이미지도 마찬가지입니다. 그런 이미지는 아무것도 매핑하지 않고 `k0: no console (driver not built in)`을 출력하며, 콘솔이 검사를 통과하지 못하는 디바이스 트리는 다른 경우와 똑같이 거부합니다. 드라이버가 건드리는 레지스터 범위는 선언된 `reg` 안, 그리고 한 그래뉼 안에 있어야 합니다.
+ - **콘솔 인터럽트**(`console-input`으로 빌드한 이미지만 읽음, [boot_KR.md](boot_KR.md) 참고): 콘솔 노드의 `interrupts` 속성입니다. 인터럽트 부모가 발견한 GIC이고 속성이 레벨 타입·액티브 하이의 SPI 하나(셀 3개, 첫 셀 0)일 때만 받습니다. 번호는 SPI 번호에 32를 더한 값입니다. 속성이 없거나 다른 형태이거나 부모가 다른 콘솔 노드는 오류가 아닙니다. 플랫폼에 콘솔 인터럽트가 없고 입력이 꺼질 뿐입니다. 범위를 벗어난 번호는 입력을 기동할 때 걸러집니다(`k0: console input off (...)`).
- **인터럽트 컨트롤러**: 타이머 노드(`arm,armv8-timer` 또는 `arm,armv7-timer`, 사용 가능한 노드는 정확히 하나)의 인터럽트 부모가 가리키는 노드입니다. 기대하는 셀 수와 프레임 정렬을 갖춘 GICv3(`arm,gic-v3`) 또는 GICv2(`arm,gic-400`, `arm,cortex-a15-gic`, `arm,cortex-a7-gic`)여야 합니다. GICv3 리디스트리뷰터 구간은 최대 4개까지 받습니다. 중복된 phandle, 비활성 노드, `interrupt-map`, CPU별 뱅크가 없는 GICv2(`cpu-offset`)는 거부합니다.
- **EL1 가상 타이머의 인터럽트 번호**: 타이머 노드의 `interrupts`에서 가져오며(`interrupt-names`가 있으면 `virt` 항목, 없으면 세 번째 항목) PPI 번호에 16을 더한 값입니다. 타이머 정오표를 선언한 타이머 노드(`fsl,erratum-a008585`, `hisilicon,erratum-161010101`, `allwinner,erratum-unknown1`)는 우회 코드가 없으므로 거부합니다.
@@ -106,7 +107,7 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야
레지스터 주소는 부모 버스의 `ranges`를 따라 CPU 물리 주소로 변환합니다. `ranges`가 없는 버스는 변환할 수 없습니다.
-결과는 불변인 `Platform` 값 하나입니다. 커널은 이를 정해진 형식의 한 줄 `k0: platform con=... gic=... tmr=...`로 출력합니다. 디바이스 페이지를 매핑하기 전에 `Platform::validate`가 기술서를 메모리 맵과 대조합니다. 대조 항목은 다음과 같습니다.
+결과는 불변인 `Platform` 값 하나입니다. 커널은 이를 정해진 형식의 한 줄 `k0: platform con=... gic=... tmr=...`로 출력합니다. 콘솔 필드에는 인터럽트가 있을 때 그 번호가 들어갑니다(예: `con=pl011@0x9000000,irq33`). 디바이스 페이지를 매핑하기 전에 `Platform::validate`가 기술서를 메모리 맵과 대조합니다. 대조 항목은 다음과 같습니다.
- RAM은 2^47 아래여야 합니다.
- 커널 이미지와 DTB는 선언된 메모리 안에 있어야 합니다.
@@ -126,7 +127,7 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야
### 고정 모드
-플랫폼 줄, 진입 예외 레벨, RAM 범위는 `<플랫폼 줄> el= ram=-` 문자열이 됩니다. 빌드할 때 `K0_PIN`에 타겟의 부트 로그에서 `k0: platform ` 뒤의 문자열을 설정했다면, 이 문자열이 다를 때 이미지가 부팅을 거부합니다. 잘못된 보드나 바뀐 DTB를 잡아냅니다. 비교하는 값이 DTB에서 나온 값이므로, **적대적인 부트 체인에 대한 방어는 아닙니다**.
+플랫폼 줄, 진입 예외 레벨, RAM 범위는 `<플랫폼 줄> el= ram=-` 문자열이 됩니다. 빌드할 때 `K0_PIN`에 타겟의 부트 로그에서 `k0: platform ` 뒤의 문자열을 설정했다면, 이 문자열이 다를 때 이미지가 부팅을 거부합니다. 잘못된 보드나 바뀐 DTB를 잡아냅니다. 콘솔 인터럽트가 플랫폼 줄에 들어오기 전에 만든 고정 문자열은 더 이상 맞지 않아 다시 만들어야 합니다. 비교하는 값이 DTB에서 나온 값이므로, **적대적인 부트 체인에 대한 방어는 아닙니다**.
## 테스트 방법
diff --git a/design/kr/exceptions_KR.md b/design/kr/exceptions_KR.md
index 0bb183a..5148536 100644
--- a/design/kr/exceptions_KR.md
+++ b/design/kr/exceptions_KR.md
@@ -20,7 +20,7 @@
## 벡터 테이블
-AArch64는 벡터 엔트리를 16개 가집니다. 4가지 발생 위치마다 예외 종류(동기, IRQ, FIQ, SError)가 4개씩입니다. K0는 각 엔트리에 네 가지 동작 중 하나를 부여합니다. 커널은 IRQ만 받으므로 FIQ는 일어나서는 안 되는 상태입니다. FIQ 엔트리는 디스패처를 호출해 `k0: UNEXPECTED fiq intid=0`을 출력하고 파킹합니다. 다음 표는 엔트리별 동작입니다.
+AArch64는 벡터 엔트리를 16개 가집니다. 4가지 발생 위치마다 예외 종류(동기, IRQ, FIQ, SError)가 4개씩입니다. K0는 각 엔트리에 네 가지 동작 중 하나를 부여합니다. 커널은 IRQ만 받고 FIQ는 받지 않으므로 FIQ는 일어나서는 안 되는 상태입니다. FIQ 엔트리는 디스패처를 호출해 `k0: UNEXPECTED fiq intid=0`을 출력하고 파킹합니다. 다음 표는 엔트리별 동작입니다.
| 발생 위치 | 동기 | IRQ | FIQ | SError |
| --- | --- | --- | --- | --- |
@@ -86,7 +86,7 @@ FP/SIMD 레지스터는 컨텍스트에 포함되지 않습니다. EL0의 모든
| 번호 | 호출 | 설명 |
| --- | --- | --- |
-| 0 | `DEBUG_PUTC` | 필터를 거친 바이트 하나를 부트 로그에 기록하고, 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에도 출력. `Console` 케이퍼빌리티가 필요 |
+| 0 | `DEBUG_PUTC` | 필터를 거친 바이트 하나를 부트 로그에 기록하고, 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에도 출력. 쓰기 권리가 있는 `Console` 케이퍼빌리티가 필요 |
| 1 | `YIELD` | 준비 큐의 맨 뒤로 이동 |
| 2 | `EXIT` | 호출한 태스크 종료 |
| 3 | `RETYPE` | untyped 메모리에서 커널 오브젝트를 만들어 호출자가 지정한 목적지 슬롯에 추가함 |
@@ -102,6 +102,7 @@ FP/SIMD 레지스터는 컨텍스트에 포함되지 않습니다. EL0의 모든
| 13 | `CAP_MOVE` | 케이퍼빌리티를 다른 슬롯으로 이동 |
| 14 | `CAP_DELETE` | 케이퍼빌리티와 거기서 파생된 모든 것을 삭제 |
| 15 | `CAP_REVOKE` | 케이퍼빌리티에서 파생된 모든 것을 삭제하고 케이퍼빌리티 자신은 남김 |
+| 16 | `CONSOLE_READ` | 콘솔 입력 바이트 하나를 읽음(`console-input`으로 빌드한 이미지에만 있음, 아래 참고). 읽기 권리가 있는 `Console` 케이퍼빌리티가 필요 |
> [!IMPORTANT]
> 알 수 없는 번호는 단순한 오류 코드로 끝나지 않습니다. K0는 이를 태스크가 손상되었거나 악의적이라는 신호로 보고, `k0: unknown syscall N, killing task`를 출력한 뒤 호출자를 종료합니다.
@@ -134,19 +135,29 @@ k0: task fault dabort-lower (esr 0x92000046 elr 0x400398 far 0x0), killing task
| `k0: idle (waiting for a timeout)` | 기한을 가진 대기자가 하나 이상 있는 채로 커널이 처음 대기할 때 |
| `k0: all tasks stopped (none ready, no timeout pending)` | 기한을 가진 대기자가 없는 채로 커널이 처음 대기할 때 |
-두 번째 상태에서는 지금으로서는 태스크를 깨울 수단이 없습니다. 알림 오브젝트도, 태스크용 장치 인터럽트도 없기 때문입니다. 기계는 대기 상태로 남습니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄이 나오면 실패로 판정합니다.
+두 번째 상태에서는 지금으로서는 태스크를 깨울 수단이 없습니다. 알림 오브젝트도, 콘솔 입력을 제외하면 태스크용 장치 인터럽트도 없기 때문입니다. 기계는 대기 상태로 남습니다. `console-input` 이미지에서는 콘솔 입력을 기다리는 태스크도 대기자로 셉니다. 기다릴 것이 콘솔 입력뿐이면 커널은 아무것도 출력하지 않으며, 이것이 터미널 이미지의 정상 상태입니다. 두 번째 줄은 기한이 있는 대기자도 콘솔 대기자도 없을 때만 출력됩니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄이 나오면 실패로 판정합니다.
## EL0의 타이머 인터럽트
-커널이 켜는 인터럽트는 **EL1 가상 타이머 하나뿐**입니다. 인터럽트 번호는 DTB에서 가져오며, 커널은 물리 타이머를 사용하지 않습니다. 인터럽트 컨트롤러는 DTB가 타이머의 인터럽트 부모로 가리키는 GICv2 또는 GICv3입니다. 드라이버는 레지스터에 기록하기 전에 식별 레지스터를 그 기술과 대조하고, 다르면 부팅을 거부합니다. [dtb_KR.md](dtb_KR.md)를 참고하세요.
+커널이 항상 켜는 인터럽트는 **EL1 가상 타이머**입니다. `console-input`으로 빌드한 이미지는 콘솔 UART의 수신 인터럽트를 하나 더 받습니다(아래 참고). 인터럽트 번호는 DTB에서 가져오며, 커널은 물리 타이머를 사용하지 않습니다. 인터럽트 컨트롤러는 DTB가 타이머의 인터럽트 부모로 가리키는 GICv2 또는 GICv3입니다. 드라이버는 레지스터에 기록하기 전에 식별 레지스터를 그 기술과 대조하고, 다르면 부팅을 거부합니다. [dtb_KR.md](dtb_KR.md)를 참고하세요.
EL0에서 받은 IRQ는 시스템 콜과 같은 방식으로 저장됩니다. 핸들러는 인터럽트를 확인합니다. 타이머였다면 타이머를 1초 뒤로 다시 설정하고 `k0: tick N`을 출력합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에 출력하며, 로그에는 처음 4개의 tick 줄만 남깁니다. 그다음 `k0_preempt`를 호출합니다. 이 함수는 먼저 기한이 된 IPC 타임아웃을 만료시키고(`k0_ipc::expire_timeouts`), 그래서 기한이 지난 대기자는 라운드 로빈 전환 전에 준비 상태가 됩니다. 그런 다음 다음 준비 태스크로 순환합니다. 1020부터 1023까지의 가짜 인터럽트 번호는 무시합니다. 그 외의 인터럽트 번호와 모든 FIQ는 설계상 발생할 수 없으므로 커널은 `k0: UNEXPECTED ...`를 출력하고 파킹합니다.
+틱을 센 뒤 핸들러는 콘솔 수신 링도 비우며(`console-input` 이미지), 태스크가 콘솔 입력을 읽기 시작한 뒤에는 주기적인 틱 줄을 출력하지 않습니다([boot_KR.md](boot_KR.md) 참고). 틱, 선점, 타임아웃은 그대로입니다.
+
+## 콘솔 인터럽트
+
+`console-input`으로 빌드한 이미지는 인터럽트를 하나 더 받습니다. 콘솔 UART의 수신 인터럽트입니다. 디스패처는 인터럽트 번호로 둘을 구분합니다(타이머, 그다음 콘솔). EL0와 EL1에서 받은 IRQ가 같은 함수를 지납니다. 그 밖의 번호는 여전히 `k0: UNEXPECTED ...`입니다. 콘솔 가지는 UART를 256바이트 링으로 비우며, 바이트를 해석하지 않습니다. 커널 바이너리의 정책 함수 `k0_console_event`(`k0_preempt`와 같은 종류)를 불러 대기 중인 `CONSOLE_READ` 호출자를 깨웁니다. 깨어난 태스크는 준비 큐의 맨 뒤로 가므로 입력은 실행 중인 태스크를 선점하지 않습니다.
+
+인터럽트는 읽는 쪽이 한도를 정합니다. 링이 차면 커널이 UART의 수신 인터럽트를 스스로 가리고, 읽는 쪽이 링의 절반을 가져가면 다시 엽니다. 같은 비우기가 틱마다 한 번 더 실행되므로, 인터럽트가 오지 않아도 입력은 (최대 한 틱 늦게) 도착합니다. UART 원인 없이 발생하는 선은 8번 진입 뒤 `k0: console input off (interrupt N fired without a uart cause)`와 함께 꺼집니다. 이 차단은 호스트 테스트로만 확인했습니다. 수신 인터럽트는 태스크가 읽기 권리로 콘솔 입력을 처음 읽을 때까지 꺼져 있습니다.
+
+`CONSOLE_READ`는 `x0`에 `Console` 슬롯, `x1`에 플래그를 받습니다(`NONBLOCK` = 1, `FLUSH` = 2, 비트 63..32는 틱 단위 타임아웃, 나머지 비트는 `BAD_FLAGS`로 거부). 바이트는 `x1`로 돌아오고, 이 바이트 직전에 입력이 유실됐으면 `x2`가 1입니다. 한 번에 한 태스크만 기다릴 수 있으며 두 번째 읽는 쪽은 `BUSY`를 받습니다. `NO_DEVICE`는 입력 경로가 없거나 꺼졌다는 뜻입니다. 케이퍼빌리티가 삭제·회수·이동된 대기자는 `REVOKED`로 즉시 깨어납니다.
+
## 테스트 방법
루트 태스크 자가 테스트는 의미 있는 방식으로 각각 폴트를 일으키는 태스크들을 시작합니다. 그리고 폴트를 일으킨 태스크만 죽는지, 폴트를 일으킨 명령 뒤의 코드가 실행되지 않는지, 루트 태스크와 다른 태스크가 계속 실행되는지 검사합니다. 폴트는 널 포인터에 쓰기, FP/SIMD 명령, 루트 태스크에만 매핑된 주소 읽기, 읽기 전용 페이지에 쓰기, 스택 페이지로 분기, 커널 주소 읽기입니다. 또 알 수 없는 시스템 콜 하나로 태스크를 죽이고, 스레드 포인터 레지스터가 태스크별로 분리되어 있는지도 검사합니다.
-`tools/qemu-boot-test.sh`는 줄 수를 **정확히** 셉니다. `k0: task fault ` 줄이 정확히 6개(`K0_BOOT_FAULTS`로 바꿀 수 있음), `k0: unknown syscall ` 줄이 정확히 1개여야 하고, 루트 전용 주소에 대한 폴트 줄은 `far`에 그 주소가 찍혀야 합니다. 파괴된 뒤에 다시 실행되는 태스크나 엉뚱한 이유로 죽은 태스크는 줄을 늘리거나 줄여서 테스트를 실패시킵니다.
+`tools/qemu-boot-test.sh`는 줄 수를 **정확히** 셉니다. `k0: task fault ` 줄이 정확히 6개(`K0_BOOT_FAULTS`로 바꿀 수 있음, 터미널이 있는 이미지는 터미널이 없는 같은 이미지보다 2개 더 많아 vault 없이 8개, vault와 함께 10개), `k0: unknown syscall ` 줄이 정확히 1개여야 하고, 루트 전용 주소에 대한 폴트 줄은 `far`에 그 주소가 찍혀야 합니다. 파괴된 뒤에 다시 실행되는 태스크나 엉뚱한 이유로 죽은 태스크는 줄을 늘리거나 줄여서 테스트를 실패시킵니다.
순서가 있는 마커도 요구합니다. `k0: task fault dabort-lower`, `k0: task fault fp-simd`, `k0: task fault iabort-lower`, `k0: unknown syscall 65535, killing task`, `root: fault isolation tests pass` 등이 그렇습니다. `k0: FATAL`, `k0: EXCEPTION`, `k0: PANIC`, `k0: UNEXPECTED`가 나오면 실패합니다.
diff --git a/design/kr/hardening_KR.md b/design/kr/hardening_KR.md
index 6daad77..47727e5 100644
--- a/design/kr/hardening_KR.md
+++ b/design/kr/hardening_KR.md
@@ -46,7 +46,7 @@
커널은 루트 태스크에 넘길 32바이트 시드도 파생합니다(`k0_boot::derive_root_seed`). 자체 도메인 문자열(`k0-root-task-seed-v1`), DTB 엔트로피의 길이, DTB 엔트로피 자체, 카운터를 SHA-256으로 해시하고, CPU에 `RNDR`이 있으면 새로 뽑은 `RNDR` 워드 네 개를 더합니다. 도메인 문자열이 PAC 키의 것과 다르므로 두 출력은 도메인 분리로 서로 독립입니다. 하나를 안다고 다른 하나를 알 수는 없습니다. 다만 DTB 엔트로피와 카운터는 공유하므로, 시드는 입력만큼만 좋고 그보다 낫지 않습니다.
-시드는 bootinfo 페이지에 없습니다. 커널이 루트 태스크의 저장된 컨텍스트에 넣으므로 진입 레지스터 `x0`부터 `x3`으로 도착합니다. `x4`는 시드 정보 워드입니다. 비트 15..0은 시드에 들어간 `rng-seed` 바이트 수이고, 비트 16은 `RNDR`이 기여했을 때 설정됩니다. bootinfo 페이지의 레이아웃은 이제 버전 3(`bootinfo::VERSION`)이며, 다른 버전을 본 루트 태스크는 멈춥니다. 커널은 부트 스택에 있던 시드 사본을 직접 지웁니다. 루트 태스크는 시드가 아니라 재료만 출력합니다. `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr`입니다.
+시드는 bootinfo 페이지에 없습니다. 커널이 루트 태스크의 저장된 컨텍스트에 넣으므로 진입 레지스터 `x0`부터 `x3`으로 도착합니다. `x4`는 시드 정보 워드입니다. 비트 15..0은 시드에 들어간 `rng-seed` 바이트 수이고, 비트 16은 `RNDR`이 기여했을 때 설정됩니다. bootinfo 페이지의 레이아웃은 이제 버전 4(`bootinfo::VERSION`)이며, 다른 버전을 본 루트 태스크는 멈춥니다. 커널은 부트 스택에 있던 시드 사본을 직접 지웁니다. 루트 태스크는 시드가 아니라 재료만 출력합니다. `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr`입니다.
### DTB에서 시드 지우기
@@ -106,9 +106,12 @@ EL0는 여전히 어떤 하드웨어 카운터나 타이머도 읽을 수 없습
EL0 스레드 포인터 레지스터 `TPIDR_EL0`와 `TPIDRRO_EL0`는 각 태스크의 저장된 컨텍스트에 포함됩니다. `TCB_CONFIGURE`가 이를 0으로 만들기 때문에 새 태스크는 생성자의 값 없이 시작합니다.
-`DEBUG_PUTC`는 `Console` 케이퍼빌리티를 요구하며, 출력 가능한 ASCII도 개행도 아닌 모든 바이트를 `?`로 바꿉니다. 태스크는 콘솔을 읽는 쪽에 터미널 이스케이프 시퀀스를 보낼 수 없습니다(콘솔 드라이버를 포함해 빌드한 이미지의 콘솔, 또는 부트 로그).
+`DEBUG_PUTC`는 쓰기 권리(W)가 있는 `Console` 케이퍼빌리티를 요구하며, 출력 가능한 ASCII도 개행도 아닌 모든 바이트를 `?`로 바꿉니다. 태스크는 콘솔을 읽는 쪽에 터미널 이스케이프 시퀀스를 보낼 수 없습니다(콘솔 드라이버를 포함해 빌드한 이미지의 콘솔, 또는 부트 로그).
-이 필터는 줄을 누가 썼는지 표시하지 않습니다. 커널 출력과 태스크 출력이 부트 로그를 함께 사용하고 (콘솔 드라이버를 포함해 빌드한 이미지에서는) 콘솔도 함께 사용합니다.
+이 필터는 줄을 누가 썼는지 표시하지 않습니다. 커널 출력과 태스크 출력이 부트 로그를 함께 사용하고 (콘솔 드라이버를 포함해 빌드한 이미지에서는) 콘솔도 함께 사용합니다. 터미널은 추가로 자신의 현재 줄 안에서 지울 수 있습니다. 읽기 권리(R)가 있는 `Console` 케이퍼빌리티(터미널의 것)만 백스페이스(0x08)도 출력할 수 있습니다.
+
+> [!NOTE]
+> `console-input` 이미지에서는 외부가 태스크 실행 중에 인터럽트를 일으킬 수 있습니다. 링이 차면 커널이 수신 인터럽트를 스스로 가리므로 빈도는 읽는 쪽이 한도를 정합니다. 그래도 읽는 쪽은 틱보다 세밀한 도착 시각을 알게 되고 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널은 분석하지 않았습니다. 커널의 수신 코드는 EL1에서 실행되며 바이트를 해석하지 않지만 외부가 구동하는 커널 코드이고, 사용자 공간 드라이버에는 K0에 없는 장치·인터럽트 위임이 필요합니다.
> [!WARNING]
> `Console` 케이퍼빌리티를 가진 태스크는 개행 뒤에 `k0:`로 시작하는 글을 출력할 수 있습니다. 콘솔이나 로그를 읽는 쪽은 `tools/qemu-boot-test.sh`를 포함해 누구도 `k0: entering root task (el0)` 뒤에 나온 `k0:` 줄을 커널이 쓴 것으로 믿을 수 없습니다.
diff --git a/design/kr/ipc_KR.md b/design/kr/ipc_KR.md
index 708b0c3..96af3ed 100644
--- a/design/kr/ipc_KR.md
+++ b/design/kr/ipc_KR.md
@@ -13,7 +13,7 @@
- 서버가 클라이언트를 구분하게 해 주는 배지
- `CALL`을 안전하게 만드는 1회성 응답 자격
-코드는 `crates/k0-ipc/src/lib.rs`에 있고, 엔드포인트 큐는 `crates/k0-task/src/lib.rs`에 있습니다.
+코드는 `crates/k0-ipc/src/lib.rs`에 있고, 엔드포인트 큐는 `crates/k0-task/src/lib.rs`에 있습니다. 시스템 콜 `CONSOLE_READ`는 IPC 호출처럼 기다리며 타임아웃, 해체, `REVOKED`로 깨어나는 방식을 IPC와 공유합니다. "콘솔 입력 대기" 절에서 설명합니다. `console-input`으로 빌드한 이미지에만 있습니다.
## 설계 요약
@@ -101,6 +101,7 @@ K0의 IPC는 seL4 방식의 **동기 랑데부**입니다. 메시지는 레지
- **Ready**: 준비 큐에서 제거합니다.
- **SEND, RECV, CALL에서 블록**: 기다리던 엔드포인트의 큐에서, 머리든 중간이든 꼬리든 제거합니다.
+- **콘솔 입력 대기**(`BlockedConsole`): 콘솔의 하나뿐인 대기자 자리에서 제거합니다.
- **응답 대기**(`BlockedReply`): 응답 자격을 양방향으로 끊습니다. 그래서 서버는 응답할 자격을 잃고, 뒤늦은 응답이 죽은 태스크를 깨우는 일도 없습니다.
- **응답 자격 보유**: 그 자격을 기다리던 호출자를 `NO_REPLY`로 깨웁니다.
- **Inactive, Stopped, Running**: 풀 것이 없습니다.
@@ -127,6 +128,7 @@ K0의 IPC는 seL4 방식의 **동기 랑데부**입니다. 메시지는 레지
| `RECV`, `REPLY_RECV` | 엔드포인트 큐 | `TIMEOUT` | 받은 것 없음(`REPLY_RECV`가 준 응답은 이미 전달됨) |
| `CALL` | 엔드포인트 큐 | `TIMEOUT` | 전달되지 않음 |
| `CALL` | `BlockedReply` | `REPLY_TIMEOUT` | 전달됨, 서버가 동작했는지는 알 수 없음 |
+| `CONSOLE_READ` | 콘솔 대기자 자리 | `TIMEOUT` | 읽은 바이트 없음 |
`CALL`이 `REPLY_TIMEOUT`으로 끝나면 커널은 그 응답 자격을 쥔 서버의 자격을 지웁니다. 서버가 나중에 응답해도 그 `REPLY_RECV`에는 사용할 응답 자격이 없으므로 뒤늦은 응답은 버려집니다. 다음 호출자는 자기 응답을 받습니다.
@@ -154,13 +156,43 @@ TCB에는 `deadline`, `tnext`, `tprev` 필드가 있습니다. `k0-sched`는 기
그 시점에 준비된 태스크가 없어도 커널은 멈추지 않습니다. 커널은 `idle_until_ready`(`kernel/src/syscall.rs`)에서 idle 상태로 기다립니다. 다음 인터럽트까지 기다렸다가 기한이 지난 대기자를 모두 깨우고, 준비된 태스크가 있으면 그 태스크로 전환합니다. 그동안에도 타이머 틱은 계속 세고 처리합니다. idle 루프는 다음 두 줄 가운데 하나를 부팅당 최대 한 번씩 출력합니다.
- `k0: idle (waiting for a timeout)`: 기한이 있는 대기자가 하나 이상 있으므로 태스크를 깨울 것이 있습니다.
-- `k0: all tasks stopped (none ready, no timeout pending)`: 기한이 있는 대기자가 없습니다. 지금은 Notification 오브젝트도 태스크용 장치 인터럽트도 없으므로 이 상태에서는 어떤 것도 태스크를 깨울 수 없고, 머신은 idle 상태로 남습니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄을 모두 실패로 처리합니다.
+- `k0: all tasks stopped (none ready, no timeout pending)`: 기한이 있는 대기자도 콘솔 입력을 기다리는 태스크도 없습니다. 지금은 Notification 오브젝트가 없고 태스크를 깨우는 장치 인터럽트는 콘솔 입력뿐이므로 이 상태에서는 어떤 것도 태스크를 깨울 수 없고, 머신은 idle 상태로 남습니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄을 모두 실패로 처리합니다.
+
+기다릴 것이 콘솔 입력뿐이면 커널은 어느 줄도 출력하지 않습니다. 터미널 이미지에서는 이것이 정상 상태입니다.
> [!WARNING]
> 모든 태스크가 블록되어도 커널은 더 이상 정지하지 않으며, 태스크는 타임아웃으로 자신의 대기에 상한을 걸 수 있습니다. 그래도 가용성은 보호되지 않습니다. 타임아웃 없이 기다리는 태스크는 상대방이 동작하지 않으면 영원히 기다릴 수 있고, 엔드포인트 케이퍼빌리티를 가진 격리 태스크는 여전히 다른 태스크를 기다리게 만들 수 있습니다. 이것이 [SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-q99x-2wrv-358p의 주제입니다. 어드바이저리는 릴리즈 시점에 갱신합니다.
응답을 유지해야 하는 서버나 루트 태스크는 모든 대기에 타임아웃을 지정해야 합니다. 태스크 격리로도 이 점은 달라지지 않습니다.
+## 콘솔 입력 대기
+
+`CONSOLE_READ`(번호 16)는 콘솔 입력을 한 바이트 읽습니다. `console-input`으로 빌드하고 수신이 가능한 콘솔 드라이버(PL011과 SBSA UART, 16550은 아님)가 있는 이미지에만 있습니다. 인자와 결과는 다음과 같습니다.
+
+| 레지스터 | 의미 |
+| --- | --- |
+| `x0`(입력) | `R`이 있는 `Console` 케이퍼빌리티의 슬롯 |
+| `x1`(입력) | 플래그. `NONBLOCK` = 1, `FLUSH` = 2, 63부터 32비트에 틱 단위 타임아웃. 다른 비트는 `BAD_FLAGS`로 실패 |
+| `x0`(출력) | 0 또는 오류 코드 |
+| `x1`(출력) | 바이트 |
+| `x2`(출력) | 이 바이트 바로 앞에서 입력이 유실되었으면 1, 아니면 0 |
+
+호출 한 번에 한 바이트를 돌려줍니다. 커널은 바이트를 해석하지 않습니다. `FLUSH`는 읽기 전에 커널과 장치가 쥔 입력을 버려서, 프롬프트 전에 들어온 입력이 명령으로 읽히지 않게 합니다. `NONBLOCK`은 준비된 바이트가 없으면 `WOULD_BLOCK`을 돌려줍니다.
+
+준비된 바이트가 없으면 태스크는 `BlockedConsole` 상태로 기다립니다. 이 대기는 위의 대기들과 같은 방식으로 동작합니다.
+
+- **대기자는 하나**: 한 번에 한 태스크만 기다릴 수 있습니다. 두 번째 읽기는 `BUSY`를 받습니다.
+- **타임아웃**: 타임아웃은 IPC와 같은 기한 목록을 쓰며, 기한이 지나면 `TIMEOUT`을 돌려줍니다.
+- **회수**: `Console` 케이퍼빌리티가 삭제, 회수, 이동된 대기자는 즉시 `REVOKED`로 깨어나며 바이트를 받지 못합니다.
+- **입력 경로 없음**: `NO_DEVICE`는 이미지에 이 콘솔용 수신 드라이버가 없거나 입력 경로가 꺼졌다는 뜻입니다. 기다리는 동안 경로가 꺼지면 대기자가 이 값으로 깨어납니다.
+- **해체**: 기다리는 동안 죽은 태스크는 대기자 자리에서 제거됩니다.
+- **깨우는 순서**: 깨어난 읽기 태스크는 준비 큐의 끝에 섭니다. 입력이 실행 중인 태스크를 선점하지 않습니다.
+
+수신 인터럽트는 태스크가 권한을 가지고 처음 콘솔 입력을 읽을 때까지 꺼져 있습니다. 그 첫 읽기는 장치가 쥔 입력을 버리고, `k0: tick lines off (console input in use)` 한 줄을 출력한 뒤 주기적인 `k0: tick N` 줄을 멈춥니다. 틱, 선점, 타임아웃은 계속 동작합니다. 수신 경로와 그 한계는 [USAGE_KR.md](../../USAGE_KR.md)와 [exceptions_KR.md](exceptions_KR.md)에 있습니다.
+
+> [!NOTE]
+> 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 바이트의 지연은 준비된 태스크마다 최대 한 틱입니다.
+
## 오류
다음 표는 오류 코드와 그 원인입니다.
@@ -172,10 +204,12 @@ TCB에는 `deadline`, `tnext`, `tprev` 필드가 있습니다. `k0-sched`는 기
| `NO_RIGHTS` | 엔드포인트 케이퍼빌리티에 `W`(`SEND`, `CALL`) 또는 `R`(`RECV`, `REPLY_RECV`)이 없음 |
| `WOULD_BLOCK` | `NONBLOCK`이 지정됐고 상대가 준비되지 않음 |
| `NO_REPLY` | `CALL`의 수신자가 응답하지 않고 종료했거나, 폴트를 냈거나, 더 새로운 `CALL`을 받았거나, 파괴됨 |
-| `REVOKED` | 호출자가 줄 서 있는 동안 엔드포인트의 원본 케이퍼빌리티가 삭제됨 |
+| `REVOKED` | 호출자가 줄 서 있는 동안 엔드포인트의 원본 케이퍼빌리티가 삭제됨. `CONSOLE_READ`에서는 호출자가 기다리는 동안 `Console` 케이퍼빌리티가 삭제, 회수, 이동됨 |
| `TIMEOUT` | 상대가 오기 전에 대기가 끝났고, 메시지는 전달되지 않음 |
| `REPLY_TIMEOUT` | `CALL`은 전달됐지만 제때 응답이 오지 않았고, 서버가 동작했는지는 알 수 없음 |
-| `BAD_FLAGS` | 플래그 레지스터의 예약 비트(31부터 1)가 설정됨 |
+| `BAD_FLAGS` | 플래그 레지스터의 예약 비트(31부터 1)가 설정됨. `CONSOLE_READ`에서는 `NONBLOCK`, `FLUSH`, 타임아웃 외의 비트 |
+| `BUSY`(-23) | `CONSOLE_READ`가 이미 콘솔 입력을 기다리는 다른 태스크를 만남 |
+| `NO_DEVICE`(-24) | `CONSOLE_READ`가 입력 경로를 찾지 못함. 이미지에 콘솔용 수신 드라이버가 없거나 경로가 꺼짐 |
## 테스트 방법
@@ -199,6 +233,8 @@ IPC와 해체는 부팅으로 테스트합니다. 루트 태스크는 서버 태
타임아웃 테스트는 가장 큰 untyped에서 오브젝트를 가져옵니다. 실제 틱을 기다리므로 부팅 테스트는 약 4초 더 걸립니다.
+입력 테스트는 `console-input`으로 빌드한 이미지의 루트 태스크 자가 테스트에 포함됩니다. `root: backspace without the input right [?]`와 `root: console input tests pass`를 출력하며, 입력 경로가 없으면 `root: console input tests pass (no input path)`, 테스트 중에 바이트가 도착하면 `... cut short (the line is busy)`를 출력합니다. 수신 로직은 별도 크레이트 `crates/k0-conin`에 있으며 가짜 UART로 호스트에서 테스트합니다. `tools/term-test.py`는 터미널 이미지에 대해 스크립트로 짠 세션을 실행합니다.
+
케이퍼빌리티 테스트는 배지를 한 번만 붙일 수 있고 두 번째는 거부되는지, 복사본이 배지를 유지하는지, 송신 전용 케이퍼빌리티로는 수신할 수 없고 수신 전용으로는 송신할 수 없는지(`NO_RIGHTS`), 엔드포인트를 회수하면 복사본이 모두 사라지고 원본은 남는지를 검사합니다.
격리 테스트는 송신 전용이고 배지가 붙은 엔드포인트 케이퍼빌리티 하나만 CNode에 든 격리 태스크를 시작합니다. 루트 태스크는 그 태스크가 `x1`로 자신에게 주어진 배지를 받는지, 그리고 루트 태스크의 슬롯 번호가 격리 CNode에서 아무 의미가 없는지(`BAD_SLOT`)를 검사합니다.
@@ -224,6 +260,7 @@ IPC와 해체는 부팅으로 테스트합니다. 루트 태스크는 서버 태
- **타임아웃은 태스크가 준비되는 시점이지 실행되는 시점이 아님**: 우선순위도 CPU 예산도 없으며, 스케줄러는 1틱 슬라이스의 라운드 로빈입니다([scheduling_KR.md](scheduling_KR.md) 참고).
- **긴 시스템 콜**: 커널은 선점되지 않으므로, 객체가 많은 untyped에 대한 `CAP_REVOKE` 같은 긴 호출은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다.
- **치명적 정지**: `k0_arch::fatal`이나 커널 패닉은 여전히 머신을 정지시킵니다.
-- **EL0의 시간 소스**: 틱에 맞춰 깨어나는 성질을 타이밍 공격에 쓸 수 있는지는 분석하지 않았습니다.
+- **EL0의 시간 소스**: 틱에 맞춰 깨어나는 성질을 타이밍 공격에 쓸 수 있는지는 분석하지 않았습니다. 콘솔 입력이 있는 이미지에서는 외부의 누군가가 태스크가 실행되는 동안 인터럽트를 일으킬 수 있고(읽는 쪽이 속도를 정함), 읽는 태스크는 틱보다 세밀한 도착 시각을 압니다. 다른 태스크도 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널도 분석하지 않았습니다.
+- **입력 지연**: `CONSOLE_READ` 대기자는 실행 중인 태스크 뒤에서 깨어나므로 바이트는 준비된 태스크마다 최대 한 틱을 기다릴 수 있습니다.
- **큐에 있던 송신자**: 회수 뒤에도 메시지를 한 번 전달합니다. 엔드포인트에서 이미 기다리는 송신자는 자신을 큐에 세운 송신의 배지를 유지합니다. 기다리는 동안 그 케이퍼빌리티가 회수되어도 메시지는 다음 수신자에게 한 번 전달됩니다.
- **메시지당 워드 네 개**: 더 큰 데이터는 공유 메모리가 필요합니다. 태스크가 서로 다른 주소 공간에서 실행될 수 있으므로, 공유 메모리는 그 태스크의 `AddrSpace` 케이퍼빌리티를 가진 쪽이 해당 주소 공간에 매핑해 주어야 합니다.
diff --git a/design/kr/scheduling_KR.md b/design/kr/scheduling_KR.md
index 7fbae2b..828fffc 100644
--- a/design/kr/scheduling_KR.md
+++ b/design/kr/scheduling_KR.md
@@ -56,9 +56,10 @@
| `Running` | 현재 태스크 |
| `BlockedSend`, `BlockedRecv`, `BlockedCall` | 엔드포인트 큐에서 대기 중 |
| `BlockedReply` | `CALL`의 응답을 기다리는 중 |
+| `BlockedConsole` | `CONSOLE_READ`에서 콘솔 입력을 기다리는 중(`console-input`으로 빌드한 이미지에만 있음). 태스크는 어떤 큐에도 없으며 커널의 대기자 자리 하나가 가리킵니다. 한 번에 한 태스크만 기다릴 수 있습니다. |
| `Dead` | 종료, 강제 종료, 또는 정리됨 |
-블록 상태의 태스크는 기한이 지나도 `Ready`가 될 수 있습니다([타임아웃](#타임아웃) 참고).
+블록 상태의 태스크는 기한이 지나도 `Ready`가 될 수 있습니다([타임아웃](#타임아웃) 참고). `BlockedConsole` 태스크는 바이트가 도착하거나 케이퍼빌리티가 삭제·회수·이동될 때도 `Ready`가 됩니다.
`Inactive`의 값은 0입니다. 방금 retype한 프레임은 전부 0이므로, 큐 링크가 비어 있고 내장 슬롯이 비어 있으며 응답 자격이 없는 유효한 `Inactive` TCB입니다. retype에 생성자가 필요 없습니다.
@@ -107,12 +108,12 @@
## 선점
-타이머는 1초에 한 번 발생합니다. EL0가 실행 중일 때 발생하면 IRQ 경로가 인터럽트를 확인하고 타이머를 다시 설정한 뒤 `k0: tick N`을 출력하고 `k0_preempt`를 호출합니다. `k0_preempt`는 `rotate`를 호출합니다. `k0: tick N`은 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에 출력하며, 로그에는 처음 4개의 tick 줄만 남깁니다. 양보하지 않는 태스크도 **최대 1초 뒤에는 CPU를 잃습니다**.
+타이머는 1초에 한 번 발생합니다. EL0가 실행 중일 때 발생하면 IRQ 경로가 인터럽트를 확인하고 타이머를 다시 설정한 뒤 `k0: tick N`을 출력하고 `k0_preempt`를 호출합니다. `k0_preempt`는 `rotate`를 호출합니다. `k0: tick N`은 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에 출력하며, 로그에는 처음 4개의 tick 줄만 남깁니다. 양보하지 않는 태스크도 **최대 1초 뒤에는 CPU를 잃습니다**. 태스크가 콘솔 입력을 읽은 뒤에는 줄 하나 `k0: tick lines off (console input in use)`를 남기고 틱 줄이 멈추지만, 틱과 선점과 타임아웃은 계속됩니다.
> [!IMPORTANT]
> 커널 자체는 선점되지 않습니다. 예외 진입이 인터럽트를 마스크하고, 커널은 시스템 콜이나 폴트를 처리하는 동안 마스크를 유지합니다.
-EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에만 가능하며, 그때는 틱을 세기만 합니다.
+EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에만 가능하며, 그때는 틱을 세기만 합니다. `console-input` 이미지에서 입력 바이트가 도착해도 선점하지 않습니다. 깨어난 읽는 쪽은 다른 깨어난 태스크처럼 준비 큐의 맨 뒤로 갑니다. 우선순위가 없으므로 입력 지연은 준비된 태스크마다 최대 한 틱입니다.
## 타임아웃
@@ -145,6 +146,7 @@ EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에
| `Ready` | 준비 큐에서 태스크를 뺌 |
| `BlockedSend`, `BlockedRecv`, `BlockedCall` | `blocked_on`이 가리키는 엔드포인트 큐에서 태스크를 빼고, 기한이 있으면 기한 목록에서도 뺌 |
| `BlockedReply` | 응답 자격을 쥔 태스크(`reply_from`)에서 그 자격을 지우고, 기한이 있으면 기한 목록에서도 뺌 |
+| `BlockedConsole` | 커널의 콘솔 대기자 자리를 비우고, 기한이 있으면 기한 목록에서도 뺌 |
| `Running` | 뺄 링크 없음. 뒤의 설명 참고 |
모든 상태에서 이어서 태스크 자신이 쥔 응답 자격을 철회하므로, 그 응답을 기다리던 호출자는 `NO_REPLY`로 깨어나 영원히 블록되지 않습니다. 마지막으로 상태를 `Dead`로 바꾸고, 큐 링크, `blocked_on`, `reply_from`, `ipc_badge`, `ttbr0_pa`를 지우며, `Running`이 아니면 저장된 레지스터를 0으로 지웁니다. 상태가 약속하는 것과 큐나 응답 링크가 맞지 않으면 커널 불변식 위반이므로 커널은 `k0: FATAL ...`을 출력하고 정지합니다([exceptions_KR.md](exceptions_KR.md) 참고).
@@ -164,7 +166,9 @@ EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에
커널이 idle 상태인 동안에도 타이머 틱은 계속 세고 처리합니다. idle 루프는 다음 두 줄 가운데 하나를 부팅당 최대 한 번씩 출력합니다.
- `k0: idle (waiting for a timeout)`: 기한이 있는 대기자가 하나 이상 있습니다.
-- `k0: all tasks stopped (none ready, no timeout pending)`: 기한이 있는 대기자가 없습니다. 지금은 Notification 오브젝트도 태스크용 장치 인터럽트도 없으므로 이 상태에서는 어떤 것도 태스크를 깨울 수 없고, 머신은 idle 상태로 남습니다.
+- `k0: all tasks stopped (none ready, no timeout pending)`: 기한이 있는 대기자도 콘솔 입력을 기다리는 태스크도 없습니다. 지금은 Notification 오브젝트도, 콘솔 입력을 제외한 태스크용 장치 인터럽트도 없으므로 이 상태에서는 어떤 것도 태스크를 깨울 수 없고, 머신은 idle 상태로 남습니다.
+
+기다릴 것이 콘솔 입력뿐이면(`console-input` 이미지) 커널은 아무것도 출력하지 않으며, 이것이 터미널 이미지의 정상 상태입니다. idle 루프는 인터럽트마다 도착한 입력을 확인해 읽는 쪽을 깨웁니다.
> [!WARNING]
> 가용성은 여전히 보호되지 않습니다. 타임아웃 없이 기다리는 태스크는 상대방이 동작하지 않으면 영원히 기다릴 수 있고, 마지막으로 블록하는 격리 태스크는 여전히 시스템에 실행할 태스크가 없게 만들 수 있습니다([SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-q99x-2wrv-358p, 릴리즈 시점에 갱신). 격리는 태스크 사이의 기밀성과 무결성을 지키는 것이지 가용성을 지키지 않습니다.
diff --git a/design/kr/terminal_KR.md b/design/kr/terminal_KR.md
new file mode 100644
index 0000000..ac0515d
--- /dev/null
+++ b/design/kr/terminal_KR.md
@@ -0,0 +1,165 @@
+# 시리얼 입력과 운영자 터미널
+
+
+
+[English](../en/terminal.md) | 한국어
+
+
+
+이 노트는 사람이 시리얼 선으로 K0와 대화하는 방법을 설명합니다. 커널이 콘솔 UART에서 바이트를 받고, 시스템 콜 `CONSOLE_READ`로 태스크 하나, 즉 **터미널**에 넘겨 줍니다. 터미널은 볼트의 운영자입니다([vault_KR.md](vault_KR.md) 참고). 볼트의 상태를 보여 주고, 키를 만들고, 키를 지웁니다. 코드는 `crates/k0-conin`(수신 로직), `kernel/src/syscall.rs`(`CONSOLE_READ`), `userspace/k0-term`(터미널), `userspace/root-task/src/service.rs`(연결과 점검)에 있습니다.
+
+> [!NOTE]
+> 입력과 터미널은 선택 사항이며 기본값은 꺼짐입니다. `console-input` 없이 빌드한 이미지에는 수신 코드도, `CONSOLE_READ`도, 이 노트의 로그 줄도 없습니다. `terminal` 없이 빌드한 이미지에는 터미널 코드가 없습니다.
+
+## 목적과 범위
+
+앞선 노트의 볼트는 부팅 시드로 키를 한 번 만들고, 그 뒤에는 호출에 답하기만 합니다. 운영자가 없으면 아무도 볼트의 상태를 볼 수 없고, 아무도 키를 의도적으로 지울 수 없습니다. 터미널은 시리얼 선 위의 작고 고정된 텍스트 인터페이스로 이 빈틈을 메웁니다.
+
+범위는 다음과 같습니다. 콘솔 UART 하나, 한 번에 읽는 태스크 하나, 호출 한 번에 바이트 하나, 운영자가 쓸 수 있는 볼트 연산 넷(`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`)입니다. 터미널은 서명할 수 없고 시드를 전달할 수도 없습니다.
+
+
+
+
+
+## 커널이 입력을 받는 이유
+
+유저 공간 드라이버는 UART의 레지스터와 인터럽트가 필요합니다. K0는 아직 장치나 인터럽트를 태스크에 위임할 수 없습니다. 그래서 수신 코드가 커널의 EL1에서 실행되고, 커널이 바이트를 유저 공간에 넘겨 줍니다.
+
+커널 코드는 작게 유지하며, 바이트를 해석하지 않습니다. 줄, 명령, 제어 키가 무엇인지 커널은 모릅니다. 그것은 모두 유저 공간에 있는 터미널의 일입니다.
+
+> [!NOTE]
+> 수신 코드는 여전히 외부 당사자가 구동하는 커널 코드입니다. 유저 공간 드라이버는 아직 없습니다. 장치 및 인터럽트 위임이 아직 없기 때문입니다.
+
+feature는 다음과 같으며, feature는 기능을 더하기만 합니다.
+
+| `k0-kernel`의 feature | 추가하는 것 |
+| --- | --- |
+| `console-input` | 콘솔 UART용 커널 수신 경로와 `CONSOLE_READ`입니다. 동작하려면 콘솔 드라이버 feature가 필요합니다. 수신은 PL011과 SBSA UART에만 있습니다. |
+| `terminal` | 루트 태스크 이미지 안의 터미널 태스크이며, 자가 테스트 뒤에 서비스로 시작합니다. `console-input`을 함께 켭니다. `vault`가 있으면 볼트의 운영자가 되고, `vault-ed25519`가 있으면 Ed25519 키를 만들 수 있습니다. |
+
+다음과 같이 빌드하고 실행할 수 있습니다.
+
+```sh
+$ cargo build -p k0-kernel --features console,terminal,vault-ed25519
+$ cargo run -p k0-kernel --features console,terminal,vault-ed25519
+```
+
+QEMU는 시리얼 포트를 사용자의 터미널에 연결합니다. `cargo run`에서 QEMU 자체의 이스케이프 키는 Ctrl-A이며(Ctrl-A x로 QEMU를 종료), 그래서 Ctrl-A는 K0에 전달되지 않습니다.
+
+## 수신 경로와 그 한계
+
+커널의 UART 드라이버는 받은 바이트를 모두 256바이트 링에 넣습니다. 수신 로직은 별도 크레이트 `crates/k0-conin`이며, 작은 레지스터 트레이트에 맞춰 작성해 호스트 테스트가 가짜 UART로 구동할 수 있습니다.
+
+- **수신 인터럽트는 꺼진 채로 둡니다**: 태스크가 읽기 권한으로 콘솔 입력을 처음 읽을 때까지입니다. 그 첫 읽기는 장치가 쥐고 있던 바이트를 버립니다. 또한 `k0: tick lines off (console input in use)` 한 줄 뒤로 주기적인 `k0: tick N` 줄을 멈춥니다. 틱, 선점, 타임아웃은 계속 동작합니다.
+- **커널 작업량의 한계**: 링이 가득 차면 커널이 UART의 수신 인터럽트를 스스로 마스크합니다. 읽는 쪽이 링의 절반을 가져간 뒤에 다시 엽니다. 그래서 폭주 상황에서 인터럽트 빈도는 보내는 쪽이 아니라 읽는 쪽이 정한 한계 안에 있습니다.
+- **틱마다 비우기**: 같은 비우기를 틱마다 한 번 더 실행하므로, 인터럽트가 오지 않아도 입력은 (최대 한 틱 늦게) 도착합니다.
+- **유실 표시**: FIFO 오버런, 브레이크, 프레이밍 오류, 패리티 오류는 구멍 뒤의 바이트에 표시됩니다. `CONSOLE_READ`가 이 표시를 읽는 쪽에 돌려줍니다.
+- **인터럽트 번호**는 디바이스 트리(콘솔 노드의 `interrupts` 속성: 발견한 GIC의 SPI 하나, 레벨, active high)에서 가져오고, UEFI 로더를 거치면 ACPI SPCR 테이블에서 가져옵니다. 플랫폼 줄에 출력되며(예: `k0: platform con=pl011@0x9000000,irq33 ...`) 그래서 `K0_PIN`으로 고정됩니다. 이 변경 이전에 만든 핀 문자열은 더 이상 일치하지 않으므로 다시 만들어야 합니다. 사용할 수 있는 인터럽트가 없는 콘솔 노드는 부팅 거부 사유가 아닙니다. 입력만 꺼집니다.
+- **잘못된 인터럽트 번호는 입력만 잃습니다**: 범위를 벗어났거나 쓸 수 없는 번호는 부팅 때 `k0: console input off (...)`가 됩니다. UART 원인 없이 계속 발생하는 선은 8번 진입 뒤에 `k0: console input off (interrupt N fired without a uart cause)`와 함께 꺼집니다.
+
+부팅 때 커널은 `k0: console input on (pl011 irq 33)` 또는 `k0: console input off ()`를 출력합니다. 이유는 `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range`, `interrupt not available`입니다.
+
+## CONSOLE_READ와 Console 권한
+
+`CONSOLE_READ`는 시스템 콜 16번입니다. 호출 한 번에 바이트 하나를 돌려줍니다.
+
+| 레지스터 | 입력 | 출력 |
+| --- | --- | --- |
+| x0 | `Console` 케이퍼빌리티 슬롯 | 성공이면 0, 아니면 오류 |
+| x1 | 플래그 | 바이트 |
+| x2 | | 이 바이트 바로 앞에서 입력이 유실되었으면 1 |
+
+플래그는 `NONBLOCK`(1), `FLUSH`(2)이고, 63비트부터 32비트까지는 틱 단위 타임아웃입니다. 다른 비트는 `BAD_FLAGS`로 거부됩니다. `NO_DEVICE`(-24)는 입력 경로가 없거나 꺼졌다는 뜻입니다.
+
+`Console` 케이퍼빌리티에는 이제 권한이 있습니다. **R**은 입력 읽기, **W**는 출력 쓰기입니다. `CAP_COPY`는 권한을 제거하기만 할 수 있습니다. 루트 태스크의 케이퍼빌리티는 W를 가지며, R은 `console-input`이 있는 이미지에서만 가집니다. `DEBUG_PUTC`는 W가 필요합니다. `bootinfo::VERSION`은 4입니다.
+
+출력 필터는 한 가지를 빼고 그대로입니다. R이 있는 `Console` 케이퍼빌리티(터미널의 것)는 백스페이스(0x08)도 내보낼 수 있습니다. 다른 제어 바이트는 여전히 `?`로 출력됩니다.
+
+## 대기와 깨우기
+
+입력을 기다릴 수 있는 태스크는 한 번에 하나입니다. 두 번째로 읽으려는 태스크는 `BUSY`(-23)를 받습니다. 링이 비어 있고 `NONBLOCK`을 요구하지 않은 읽기는 잠들며, 플래그에 타임아웃이 있으면 그 시간만큼만 잡니다.
+
+- **바이트로 깨우기**: 바이트를 받으면 대기자를 깨웁니다. 대기자는 준비 큐의 맨 뒤로 갑니다. 입력 때문에 선점하지는 않습니다.
+- **케이퍼빌리티 변경으로 깨우기**: 케이퍼빌리티가 삭제, 회수 또는 이동된 대기자는 즉시 `REVOKED`로 깨어납니다.
+- **타임아웃으로 깨우기**: 플래그에 타임아웃을 준 읽기는 그 시간이 다 되면 깨어납니다(타임아웃은 [scheduling_KR.md](scheduling_KR.md) 참고).
+- **조용한 유휴**: 기다릴 것이 콘솔 입력뿐이면 커널은 아무것도 출력하지 않습니다. 이것이 터미널 이미지의 정상 상태입니다. `k0: all tasks stopped (none ready, no timeout pending)`는 시간 제한이 있는 대기자도, 콘솔 대기자도 없을 때만 출력됩니다.
+
+## 터미널의 연결과 적대적 태스크 점검
+
+터미널 이미지는 자가 테스트를 모두 먼저 실행합니다. 그다음 루트 태스크가 다음을 합니다.
+
+1. 새 볼트를 시작하고(빌드에 포함된 경우) 부팅 시드를 건넵니다. 로그 줄은 `root: vault seeded`, 또는 `root: vault has no seed (boot seed has no entropy)`, 또는 `root: vault has no seed (no algorithm in this image)`입니다.
+2. 터미널과 똑같이 연결한 적대적 태스크 둘을 실행합니다. 둘 다 거부되어야 하며 폴트로 끝나야 합니다. 줄은 `root: terminal console filter [...]`, `root: terminal wiring holds`, 그리고 `k0: task fault` 두 줄입니다.
+3. 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작하고, 영원히 블록합니다. 줄은 `root: service started`이며 그다음 배너가 나옵니다.
+
+입력 경로가 없는 머신에서 루트 태스크는 `root: no console input, terminal not started`를 출력합니다.
+
+터미널 태스크는 자체 주소 공간과 케이퍼빌리티 둘을 가집니다.
+
+- R과 W가 있는 `Console` 복사본
+- 송신 권한과 운영자 배지가 있는 볼트 엔드포인트
+
+볼트의 응답 프레임은 터미널에 읽기 전용으로 매핑됩니다. 볼트는 배지와 연산만으로 어느 프레임을 읽고 쓸지 결정합니다. 운영자에게는 응답 프레임이 있고 요청 프레임은 없습니다. 가질 수 없는 본문을 가졌다고 주장하는 요청은 메모리를 건드리지 않고 거부됩니다.
+
+적대적 태스크 둘은 연결이 말한 대로 작동하는지 확인하는 점검입니다. 터미널과 똑같이 연결되어 있고, 루트 태스크는 둘 다 거부되어 폴트로 끝나리라고 기대합니다. 하나라도 거부되지 않으면 점검이 실패합니다.
+
+> [!WARNING]
+> 시리얼 선에는 인증이 없습니다. 선을 쥔 사람이 운영자이며, 키 삭제를 포함해 운영자의 연산 넷을 그대로 할 수 있습니다. 운영자는 서명할 수 없고, 시드를 전달할 수 없고, 정책을 바꿀 수 없습니다.
+
+## 화면과 명령 규칙
+
+화면은 일반 텍스트입니다. 배너는 `K0 operator console, type 'help'`, 프롬프트는 `k0> `이고, 값은 `name=value`로 출력하며, 모든 명령은 정확히 한 줄 `ok` 또는 `err `으로 끝납니다.
+
+| 명령 | 하는 일 |
+| --- | --- |
+| `help` | 명령 목록을 보여 줍니다. |
+| `vault status` | 볼트의 상태를 출력합니다. |
+| `vault pubkey` | 공개 키를 출력합니다. |
+| `vault keygen ` | 쥐고 있는 시드로 키를 만듭니다. 알고리즘은 `ed25519` 하나뿐입니다. |
+| `vault zeroize confirm` | 키를 지웁니다. `vault zeroize`만 입력하면 `hint=type 'vault zeroize confirm' to erase the key`와 `err confirm-required`를 출력합니다. |
+
+`vault status`는 `state=fresh|seeded|ready|zeroized|failed`, `alg=none|ed25519`, `selftest=passed|failed`, `seed=none|rng-seed|rndr|rng-seed+rndr`, `validated=no`를 출력합니다. `seed=rng-seed`는 바이트가 있었다는 뜻이지 예측할 수 없다는 뜻이 아닙니다. 구현에 어떤 종류의 검증도 없으므로 `validated=no` 줄은 항상 출력됩니다.
+
+`vault pubkey`는 `pubkey=`와 16진수 32자를 출력하고, 7칸 들여 쓴 둘째 줄에 나머지 32자를 출력합니다.
+
+오류 이름은 `unknown-command`, `bad-argument`, `line-too-long`, `input-lost`, `confirm-required`, `denied`, `no-vault`, `no-key`, `key-exists`, `no-entropy`, `unsupported-algorithm`, `zeroized`, `vault-failed`, `vault-timeout`입니다. 전달되었지만 제때 답을 받지 못한 keygen 또는 zeroize에는 `hint=run 'vault status' to see whether it took effect`가 붙습니다.
+
+입력 규칙은 다음과 같습니다. 상태 기계는 `userspace/k0-term/src/lib.rs`의 `feed`입니다.
+
+- 줄은 CR 또는 LF로 끝나고, 64자 이하이며, 출력 가능한 ASCII만 포함합니다.
+- Backspace와 DEL은 한 글자를 지웁니다. Ctrl-C와 Ctrl-U는 줄을 취소하며 `^C`, `^U`로 표시됩니다.
+- ESC 시퀀스(화살표 키)는 무시합니다.
+- 프롬프트 전에 UART에 도착한 것은 버립니다.
+- 유실이 보고되면 다음 줄 끝까지 모두 버리고 `err input-lost`를 출력합니다.
+- vault feature가 없으면 `help`는 `help`만 나열하고 `vault ...`는 `err no-vault`로 답합니다.
+
+이 feature와 함께 볼트 쪽도 바뀌었습니다. 엔드포인트 배지에 따른 역할은 빌드 때 고정되는 넷입니다. admin(루트 태스크), operator(터미널), signer, reader입니다. `INIT`(admin 전용, 한 번)은 이제 시드를 전달하기만 합니다. 볼트는 엔트로피 규칙을 검사하고 시드를 `seeded` 상태로 쥐고 있습니다. 새 연산 `KEYGEN`(admin과 operator)은 쥐고 있던 시드로 키를 만들고 시드를 지웁니다(`ready` 상태). 부팅 한 번에 키 하나입니다. 두 번째 `KEYGEN`은 `key-exists`로 거부되고, `ZEROIZE` 뒤에는 재부팅이 필요합니다. `failed`로 들어가는 모든 길은 시드와 키를 지웁니다.
+
+## 테스트 방법
+
+**호스트 테스트**(`tools/host-test.sh`): `k0-conin`은 가짜 UART로 15개, `k0-term`은 vault feature가 있으면 24개, 없으면 21개, `k0-vault`는 Ed25519가 있으면 20개, 없으면 11개입니다. 전체는 ARM 호스트에서 354개, 다른 호스트에서 268개입니다.
+
+**부팅 매트릭스**: 새 행은 `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq`, 정적 행 `input-symbols`(`console-input`이 없는 이미지에는 수신 코드도 새 로그 줄도 없음), `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi`, `hvf-term`입니다. 매트릭스는 HVF가 있는 Mac에서 76행, CI에서 65행입니다.
+
+**스크립트 세션**: `tools/term-test.py `는 QEMU의 시리얼 포트를 파이프에 연결해 이미지를 부팅하고 세션을 실행합니다. 모든 명령과 모든 오류, 지우기와 취소, CR LF, ESC 시퀀스, 너무 긴 줄, 키 생성, 공개 키 형식, zeroize, 줄 끝이 없는 200 kB, 연속 2000줄, 시리얼 브레이크를 다룹니다. `tools/qemu-boot-test.sh`는 `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none`, 판정 전용 모드 `K0_BOOT_JUDGE`를 읽습니다.
+
+**루트 태스크 자가 테스트**(`console-input`이 있는 이미지): `root: backspace without the input right [?]`와 `root: console input tests pass`입니다. 테스트 중에 바이트가 도착하면 둘째 줄은 `... pass (no input path)` 또는 `... cut short (the line is busy)`일 수도 있습니다. 터미널 이미지는 터미널이 없는 같은 이미지보다 `k0: task fault` 줄이 둘 더 나옵니다(볼트 없이 8줄, 볼트와 함께 10줄).
+
+## 알려진 공백
+
+> [!NOTE]
+> 실제 하드웨어에서는 아무것도 실행하지 않았습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU에서 실행되지 않으며, 가짜 UART를 쓰는 호스트 테스트로만 확인했습니다. UART 원인 없이 발생하는 인터럽트 선을 끄는 동작도 호스트 테스트로만 확인했습니다.
+
+- **인증 없음**: 시리얼 선은 그 선에 닿을 수 있는 사람만큼만 신뢰할 수 있습니다. 운영자는 키를 지울 수 있지만(설계상의 서비스 거부) 서명을 얻지 못하고 정책을 바꿀 수 없습니다.
+- **외부가 구동하는 커널 코드**: 수신 코드는 EL1에서 실행됩니다.
+- **분석하지 않은 타이밍 채널**: 외부 당사자가 이제 태스크가 실행되는 동안 인터럽트를 일으킬 수 있습니다(읽는 쪽이 정한 한계 안에서). 읽는 쪽은 틱보다 세밀한 도착 시각을 알게 되고, 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다.
+- **지연**: 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 준비된 태스크마다 최대 한 틱씩 지연됩니다.
+- **16550 콘솔에는 입력 없음**: 16550 콘솔에는 출력만 있고 입력은 없습니다.
+- **폭주 중 측정 없음**: 어떤 테스트도 머신에서 폭주 중 커널 시간을 측정하지 않습니다. 한계는 게이트로 논증하고 호스트 테스트로 보였습니다.
+- **프롬프트 전에 버림**: UART에 도착한 바이트를 센 것입니다. 바이트를 붙잡고 있는 에뮬레이터나 어댑터는 나중에 전달합니다(QEMU가 그렇습니다).
+- **갈라진 화면 줄**: 운영자가 입력하는 동안 커널 줄이 나타나면 화면 줄은 갈라지지만 버퍼는 온전합니다. Enter는 버퍼 전체를 실행합니다.
+- **줄을 흉내 낼 수 있음**: `Console` 출력이 있는 태스크는 여전히 커널 또는 루트 태스크 줄처럼 보이는 줄을 출력할 수 있습니다. 접두어를 인증하는 것이 없기 때문입니다. 터미널은 추가로 현재 줄 안에서 지울 수 있습니다.
+- **서비스 모드에 서명 클라이언트 없음**: 키는 만들어 보여 주지만 다른 태스크가 아직 쓰지 않습니다. 클라이언트 서명은 자가 테스트가 보여 줍니다.
+- **재시작 없음**: 터미널과 볼트는 죽어도 다시 시작되지 않습니다. 루트 태스크는 신뢰합니다.
+- **부트 로그 몫**: 터미널 출력은 메모리 부트 로그의 사용자 몫을 소모합니다. 그 몫이 가득 차면 이후 태스크 출력은 거기에 기록되지 않습니다.
+- **볼트의 이전 한계는 모두 유지**: 구현은 검증되지 않았고, 부채널 분석이 없고, 키는 승인된 난수 비트 생성기에서 나오지 않고, 영속성이 없고, 양자 내성 알고리즘이 없습니다. 가용성은 보호되지 않습니다([ipc_KR.md](ipc_KR.md) 참고).
diff --git a/design/kr/uefi_KR.md b/design/kr/uefi_KR.md
index f7d606f..0a7b698 100644
--- a/design/kr/uefi_KR.md
+++ b/design/kr/uefi_KR.md
@@ -183,7 +183,7 @@ $ K0_LOADER_FEATURES=refuse-halt tools/build-loader.sh
- **호스트 단위 테스트**: `crates/k0-efi/src/tests.rs`에 32개가 있습니다. 벡터는 실제로 측정한 펌웨어 메모리 맵입니다. 디스크립터 규칙, 겹침, 항목 한계, 작성기와 재작성, 검증기, ACPI 리더, 트리 합성을 다룹니다. 네 번째 퍼저 `fuzz_acpi_with_mutated_tables`는 테이블 이미지를 변형합니다. 2026-11-12에 200만에서 300만 케이스의 캠페인이 통과했고, 앞서 실제 불일치 하나를 찾았습니다(리더가 커널의 디스커버리가 거부하는 GIC 프레임 정렬을 받아들였습니다). 커널의 배치 규칙을 리더에 적용해 수정했습니다.
- **결정적 퍼저 셋**: `k0-efi`의 `fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees`, `fuzz_prepare_end_to_end`입니다. 다른 퍼저와 같은 변수 `K0_FUZZ_ITERS`, `K0_FUZZ_SEED`, `K0_FUZZ_CASE`를 사용합니다. 기본값은 각각 20,000, 20,000, 5,000개의 케이스입니다. 주간 워크플로가 셋 모두를 500만 케이스로 실행합니다. 2026-11-12에 각각 500만 케이스의 캠페인이 통과했습니다. 계획 퍼저는 앞서 실제 버그 하나를 찾았습니다(물리 주소 0의 블록이 받아들여졌습니다). 수정되었습니다.
-- **호스트 테스트 스크립트**: `tools/host-test.sh`는 이제 ARM 호스트에서 276개(`k0-abi` 14, `k0-cap` 42, `k0-boot` 82, `k0-efi` 32, Ed25519 포함 13개와 제외 7개의 `k0-vault`, 두 그래뉼 각각에 `k0-mm` 43)를, `k0-mm` 테스트를 건너뛰는 그 밖의 호스트에서 190개를 실행합니다.
+- **호스트 테스트 스크립트**: `tools/host-test.sh`는 이제 ARM 호스트에서 354개(`k0-abi` 15, `k0-cap` 44, `k0-boot` 85, `k0-efi` 33, `k0-conin` 15, Ed25519 포함 20개와 제외 11개의 `k0-vault`, 볼트 feature 포함 24개와 제외 21개의 `k0-term`, 두 그래뉼 각각에 `k0-mm` 43)를, `k0-mm` 테스트를 건너뛰는 그 밖의 호스트에서 268개를 실행합니다.
- **PE 검사**: `tools/pe-check.py .efi`는 PE 형태(섹션 4개, 쓰기와 실행이 함께 가능한 섹션 없음)와 캐시 및 MMU 명령의 순서를 검사하고 `pe-check: ok (...)`를 출력합니다.
- **EDK2 부팅 테스트**: `tools/qemu-virt-runner.sh`는 `.efi` 인자를 EDK2 펌웨어로 부팅합니다. 기본 머신은 `virt,gic-version=3,acpi=off`이므로 디바이스 트리 경로입니다. ACPI 행은 `K0_QEMU_MACHINE=virt,gic-version=3` 또는 `virt,gic-version=2`를 넘깁니다. `tools/qemu-boot-test.sh`는 로더의 첫 줄 `k0-loader: start`부터 실패를 판정하므로 펌웨어 메시지는 세지 않습니다. `tools/build-loader.sh <커널 ELF>`는 이미 빌드된 커널을 내장하고 `.efi`의 경로(`<커널 ELF>.efi`)를 출력합니다. 그래서 UEFI 행도 다른 행과 같은 커널 바이너리를 부팅합니다. 명령은 [USAGE_KR.md](../../USAGE_KR.md)에 있습니다.
@@ -253,6 +253,7 @@ $ K0_LOADER_FEATURES=refuse-halt tools/build-loader.sh
- **MADT의 GIC**: 분배기 항목 하나입니다. 버전 2는 GICv2, 3과 4는 GICv3, 0은 리디스트리뷰터가 기술되었는지로 정하고, 그 밖의 값은 거부합니다. GICv2 프레임 크기는 테이블에 없으므로 로더는 분배기에 4 KiB, CPU 인터페이스에 8 KiB를 사용합니다(Linux가 사용하는 값). GICv3 리디스트리뷰터는 GICR 항목(최대 4개)에서 오고, 없으면 CPU 항목에서 오며, 인접하면 128 KiB 또는 256 KiB 간격으로 병합합니다. 부트 CPU의 항목이 그 안에 있어야 합니다. 프레임은 정렬되어 있어야 하고, 서로 겹치지 않아야 하며, 메모리 맵 기준으로 RAM이나 펌웨어 메모리에 있으면 안 됩니다. 그렇지 않으면 로더가 거부합니다.
- **GTDT의 타이머**: 가상 EL1 타이머 인터럽트는 16에서 31이어야 합니다.
- **SPCR의 콘솔**(선택): PL011(타입 0x03), SBSA UART(0x0D, 0x0E), 그리고 16550(0x00, 0x01, 0x12)은 8비트 레지스터와 바이트 접근일 때만 받습니다. SPCR이 레지스터 간격을 표현할 수 없기 때문입니다.
+- **SPCR의 콘솔 인터럽트**(선택): 인터럽트 종류는 GIC 하나뿐(비트 3만)이고 전역 시스템 인터럽트는 SPI(32~1019)여야 합니다. 로더는 이를 콘솔 노드의 `interrupts` 속성(SPI 번호, 레벨, 액티브 하이)으로 쓰고 커널은 [dtb_KR.md](dtb_KR.md)대로 읽습니다. 필드를 담기에 짧은 테이블이나 다른 형태는 인터럽트 없는 콘솔이 되며 거부가 아니라 입력만 꺼집니다. 번호는 `k0: platform` 줄(`irq33`)에 나타나므로, 이 필드가 생기기 전에 만든 고정 문자열은 더 이상 맞지 않습니다.
- **거부와 콘솔 없는 부팅의 구분**: 잘못된 테이블, GIC, 타이머, 메모리에 있는 장치는 거부합니다(`ACPI tables: `). 커널에 드라이버가 없는 콘솔, 잘못된 SPCR, 메모리에 있는 콘솔은 콘솔 없는 부팅이 됩니다. 로더는 `k0-loader: device tree built from ACPI tables (MADT, GTDT and SPCR)` 또는 `(MADT and GTDT, no usable SPCR console)`을 출력합니다.
- **엔트로피**: ACPI로 만든 트리에는 펌웨어 시드가 없습니다. 펌웨어에 `EFI_RNG_PROTOCOL`이 있으면 커널이 32바이트를 받고, 없으면 아무것도 받지 못합니다(`k0: entropy dtb=0B`를 로그에 남기고 계속합니다).
- **작업 영역 비우기**: 로더는 점프 전에 작업 영역도 데이터 캐시에서 비웁니다. `tools/pe-check.py`는 비우기 호출 셋(블록, 작업 영역, 트램펄린)을 요구합니다.
diff --git a/design/kr/vault_KR.md b/design/kr/vault_KR.md
index f533a7f..4e6ca65 100644
--- a/design/kr/vault_KR.md
+++ b/design/kr/vault_KR.md
@@ -6,26 +6,28 @@
-이 노트는 K0의 격리 코어 위에 올라가는 첫 번째 서비스를 설명합니다. **볼트** 태스크가 Ed25519 키 하나를 보관합니다. 클라이언트 태스크는 IPC로 서명과 공개 키를 받고, 키는 받지 못합니다. 코드는 `userspace/k0-vault`(크레이트), `userspace/root-task/src/oracle.rs`(연결과 자가 테스트), `crates/k0-boot`(부팅 시드)에 있습니다.
+이 노트는 K0의 격리 코어 위에 올라가는 첫 번째 서비스를 설명합니다. **볼트** 태스크가 Ed25519 키 하나를 보관합니다. 클라이언트 태스크는 IPC로 서명과 공개 키를 받고, 키는 받지 못합니다. 코드는 `userspace/k0-vault`(크레이트), `userspace/root-task/src/oracle.rs`(연결과 자가 테스트), `userspace/root-task/src/service.rs`(자가 테스트 뒤에 시작하는 서비스), `crates/k0-boot`(부팅 시드)에 있습니다. `terminal`로 빌드한 이미지에서는 직렬 터미널이 볼트의 운영자입니다("서비스 볼트와 운영자" 절 참고).
> [!NOTE]
> 볼트는 선택 사항이며 기본값은 꺼짐입니다. 기본 이미지에는 볼트도 암호 코드도 없습니다.
## 목적과 범위
-볼트는 격리 코어가 비밀을 그것을 쓰는 태스크로부터 떼어 놓을 수 있음을 보여 줍니다. 서비스는 작고 고정되어 있습니다. 상태를 알려 주고, 공개 키를 돌려주고, 1024바이트까지의 메시지에 서명합니다.
+볼트는 격리 코어가 비밀을 그것을 쓰는 태스크로부터 떼어 놓을 수 있음을 보여 줍니다. 서비스는 작고 고정되어 있습니다. 상태를 알려 주고, 공개 키를 돌려주고, 1024바이트까지의 메시지에 서명합니다. 키는 두 단계로 만들어집니다. 루트 태스크가 시드를 넘기고, 그다음 admin 또는 operator가 키를 만들게 합니다.
알고리즘은 Ed25519입니다(SHA-512를 쓰는 PureEdDSA, FIPS 186-5와 RFC 8032). 구현은 vendor에 넣은 크레이트 `ed25519-dalek` 2.2.0이며 어떤 종류의 검증도 받지 않았습니다. 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 이를 위해 `vendor/`에 크레이트 14개를 추가했고, 그중 절반은 빌드 시점 또는 다른 타겟용 코드라서 K0 이미지에 컴파일되어 들어가지 않습니다.
## 오브젝트와 누가 무엇을 매핑할 수 있는가
-
+
+
+
루트 태스크는 다음 오브젝트를 만듭니다.
-- **엔드포인트 하나**: 볼트가 여기서 받습니다. 클라이언트의 CNode에는 송신 전용 배지 복사본만 있습니다(자가 테스트에서는 보고용 엔드포인트도 있습니다).
+- **엔드포인트 하나**: 볼트가 여기서 받습니다. 클라이언트의 CNode에는 송신 전용 배지 복사본만 있습니다(자가 테스트에서는 보고용 엔드포인트도 있습니다). 터미널은 operator 배지가 붙은 같은 종류의 복사본을 받습니다.
- **볼트 태스크**: 자체 주소 공간과 자체 스택을 가집니다. 키는 여기에 있습니다.
-- **호출자마다 요청 프레임과 응답 프레임**: 요청 프레임은 호출자가 읽기·쓰기, 볼트가 읽기 전용입니다. 응답 프레임은 볼트가 읽기·쓰기, 호출자가 읽기 전용입니다. 프레임 케이퍼빌리티의 권한을 줄인 복사본으로 강제합니다.
+- **호출자마다 요청 프레임과 응답 프레임**: 요청 프레임은 호출자가 읽기·쓰기, 볼트가 읽기 전용입니다. 응답 프레임은 볼트가 읽기·쓰기, 호출자가 읽기 전용입니다. 프레임 케이퍼빌리티의 권한을 줄인 복사본으로 강제합니다. operator는 예외입니다. 읽기 전용으로 매핑된 응답 프레임만 있고 요청 프레임은 없습니다.
> [!WARNING]
> 루트 태스크가 이 모든 것을 만들므로 격리의 바깥에 있으며 볼트를 읽을 수 있습니다. 성립하는 문장은 "루트 태스크 외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없다"입니다.
@@ -49,46 +51,82 @@
| MR2 | 지표 비트 |
| MR3 | nonce |
-연산은 `STATUS`, `PUBLIC_KEY`, `SIGN`(요청 프레임에 1024바이트까지의 메시지)이며, admin 배지에만 `INIT`(시드와 시드 정보 40바이트, 한 번)과 `ZEROIZE`가 있습니다.
+연산은 다음과 같습니다.
+
+| 연산 | 의미 |
+| --- | --- |
+| `STATUS` | 상태, 키의 알고리즘, 이미지에 들어 있는 알고리즘 |
+| `PUBLIC_KEY` | 응답 프레임으로 받는 공개 키 |
+| `SIGN` | 요청 프레임에 있는 1024바이트까지의 메시지에 서명 |
+| `INIT` | 시드와 시드 정보(40바이트)를 넘깁니다(admin 전용, 한 번). 키는 만들지 않습니다 |
+| `KEYGEN` | MR0에 실린 알고리즘으로 쥐고 있는 시드에서 키를 만들고 시드를 지움 |
+| `ZEROIZE` | 키와 쥐고 있는 시드를 지움 |
+
+`STATUS`는 상태, 키의 알고리즘, 이미지에 들어 있는 알고리즘을 MR1의 한 워드에 묶습니다(`proto::status_word`).
**단일 가져오기**: `server::fetch`는 길이를 먼저 고정한 뒤 본문을 volatile 읽기로 비공개 버퍼에 한 번만 읽습니다. 사본만 사용하므로 호출 중에 프레임을 바꾸는 호출자는 얻는 것이 없습니다. 응답 프레임은 nonce와 길이로 시작하고, `server::publish`는 nonce를 마지막에 기록합니다. 클라이언트는 자신의 nonce가 담긴 `OK` 응답을 받은 뒤에만 프레임을 믿어야 합니다.
-상태 기계는 `userspace/k0-vault/src/server.rs`의 `Vault::handle`입니다.
+볼트는 배지와 연산만으로 어느 프레임을 읽고 쓸지 정합니다(`proto::fetch_plan`과 `proto::publish_plan`). 요청 본문이 있는 연산은 `SIGN`과 `INIT`뿐이고, 응답 본문이 있는 연산은 `PUBLIC_KEY`와 `SIGN`뿐입니다. 가질 수 없는 본문을 가졌다고 말하는 요청은 `BAD_REQUEST`로 거부되고, 볼트는 그때 메모리를 건드리지 않습니다. 요청 프레임이 없는 operator에게 이것이 중요합니다. 꾸며 낸 길이로 볼트가 매핑되지 않은 주소를 읽게 할 수 없습니다.
+
+상태 기계는 `userspace/k0-vault/src/server.rs`의 `Vault::handle`입니다. 볼트는 다섯 상태 중 하나입니다.
+
+| 상태 | 의미 |
+| --- | --- |
+| `fresh` | 시드도 키도 없음 |
+| `seeded` | `INIT`이 엔트로피 규칙을 통과한 시드를 넘겼고 볼트가 쥐고 있음 |
+| `ready` | `KEYGEN`이 키를 만들고 시드를 지움 |
+| `zeroized` | `ZEROIZE`가 키와 시드를 지움. 새 키는 재부팅해야 만들 수 있음 |
+| `failed` | 자가 테스트 또는 쌍 일관성 테스트가 실패함. 이 상태로 가는 모든 길에서 시드와 키를 지움 |
+
+키는 부팅당 하나입니다. 두 번째 `KEYGEN`은 `KEY_EXISTS`(터미널에서는 `key-exists`)로 거부됩니다.
## 고정된 정책과 배지
-정책은 빌드 시점에 고정되며 엔드포인트 배지를 키로 사용합니다. 배지는 커널이 전달하며 클라이언트가 위조할 수 없습니다([ipc_KR.md](ipc_KR.md) 참고). 역할은 다음과 같습니다.
+정책은 빌드 시점에 고정되며 엔드포인트 배지를 키로 사용합니다. 배지는 커널이 전달하며 클라이언트가 위조할 수 없습니다([ipc_KR.md](ipc_KR.md) 참고). 역할은 빌드 시점에 고정된 네 가지입니다.
| 역할 | 연산 |
| --- | --- |
-| admin (루트 태스크) | `STATUS`, `INIT`, `ZEROIZE`, `SIGN`은 불가 |
+| admin (루트 태스크) | `STATUS`, `INIT`, `KEYGEN`, `ZEROIZE`, `SIGN`과 `PUBLIC_KEY`는 불가 |
+| operator (터미널) | `STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`, `SIGN`과 `INIT`은 불가 |
| signer | `STATUS`, `PUBLIC_KEY`, `SIGN` |
| reader | `STATUS`, `PUBLIC_KEY` |
-배지가 없거나 알 수 없는 배지의 호출은 거부됩니다. 어떤 연산도 정책을 바꾸지 않습니다. 모든 signer가 키 하나를 공유하므로 서명에는 클라이언트 신원이 담기지 않습니다.
+operator는 서명을 받을 수도 시드를 넘길 수도 없습니다. 배지가 없거나 알 수 없는 배지의 호출은 거부됩니다. 어떤 연산도 정책을 바꾸지 않습니다. 모든 signer가 키 하나를 공유하므로 서명에는 클라이언트 신원이 담기지 않습니다.
## 프로바이더 경계
`userspace/k0-vault/src/provider.rs`만 암호 크레이트에 닿습니다.
- **자가 테스트**: 시작할 때 RFC 8032 벡터 두 개로 알려진 답 테스트를 합니다(공개 키, 서명, 검증, 바뀐 메시지와 바뀐 서명의 거부).
-- **키 생성과 엔트로피 규칙**: 부팅 시드에 `rng-seed` 32바이트 이상 또는 RNDR 256비트가 없으면 볼트는 키 생성을 거부합니다(상태 `NO_ENTROPY`). QEMU virt는 32바이트 `rng-seed`를 제공합니다.
-- **쌍 일관성 테스트**: 키 생성 뒤에 자신의 서명이 검증되는지 확인합니다. 자가 테스트 실패 또는 쌍 일관성 테스트 실패는 볼트를 `STATUS` 외의 모든 것을 거부하는 실패 상태로 만듭니다.
+- **시드 검사와 엔트로피 규칙**: 부팅 시드에 `rng-seed` 32바이트 이상 또는 RNDR 256비트가 없으면 `INIT`은 시드를 거부하고(상태 `NO_ENTROPY`), 전부 0인 시드도 거부합니다. 알고리즘이 없는 이미지의 볼트는 시드를 거부하고(`UNSUPPORTED`) `fresh`에 머뭅니다. QEMU virt는 32바이트 `rng-seed`를 제공합니다.
+- **키 생성**: `KEYGEN`은 고른 알고리즘으로 쥐고 있는 시드에서 키를 만들고, 키가 나오든 아니든 시드를 지웁니다.
+- **쌍 일관성 테스트**: 키 생성 뒤에 자신의 서명이 검증되는지 확인합니다. 자가 테스트 실패 또는 쌍 일관성 테스트 실패는 볼트를 `STATUS` 외의 모든 것을 거부하는 `failed` 상태로 만듭니다.
- **엄격한 검증**: 검증은 `verify_strict`를 사용합니다.
- **키 내보내기 없음**: 키를 돌려주는 연산이 없습니다.
-- **제로화**: `ZEROIZE`는 키를 버립니다(크레이트가 지웁니다). 이후 볼트는 `SIGN`과 `PUBLIC_KEY`를 거부합니다.
-- **지표 비트**: 모든 응답에 비트 네 개가 있습니다. 알고리즘이 FIPS 186-5에 있음, 자가 테스트 통과, `rng-seed` 32바이트 이상이 키 시드에 들어감, RNDR이 키 시드에 들어감입니다.
+- **제로화**: `ZEROIZE`는 키(크레이트가 지웁니다)와 쥐고 있는 시드를 버립니다. 이후 볼트는 `SIGN`, `PUBLIC_KEY`, `KEYGEN`을 거부합니다.
+- **지표 비트**: 모든 응답에 비트 네 개가 있습니다. 알고리즘이 FIPS 186-5에 있음, 자가 테스트 통과, `rng-seed` 32바이트 이상이 키 시드에 들어감, RNDR이 키 시드에 들어감입니다. `STATUS`는 뒤의 두 비트를 볼트가 아직 쥐고 있는 시드에 대해서도 알립니다. 비트는 바이트가 있었다는 뜻이지 그 바이트를 예측할 수 없었다는 뜻이 아닙니다.
## 부팅 시드 경로
커널은 루트 태스크용 32바이트를 자체 도메인 문자열로 SHA-256에 넣어 만듭니다. 입력은 DTB 엔트로피, 카운터, 그리고 CPU에 RNDR이 있으면 새 RNDR 워드 네 개입니다(`k0_boot::derive_root_seed`). 도메인 분리로 PAC 키와는 서로 독립입니다. 시드는 입력만큼만 좋습니다.
-시드는 루트 태스크의 진입 레지스터 `x0`부터 `x3`로 전달됩니다. `x4`는 사용한 `rng-seed` 바이트 수(비트 15부터 0)이고, 비트 16은 RNDR이 기여했음을 뜻합니다. bootinfo 페이지에는 없으며 `bootinfo::VERSION`은 3입니다. 루트 태스크는 `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr`만 출력하고 시드는 출력하지 않습니다. 이후 `INIT`으로 시드를 볼트에 줍니다.
+시드는 루트 태스크의 진입 레지스터 `x0`부터 `x3`로 전달됩니다. `x4`는 사용한 `rng-seed` 바이트 수(비트 15부터 0)이고, 비트 16은 RNDR이 기여했음을 뜻합니다. bootinfo 페이지에는 없으며 `bootinfo::VERSION`은 4입니다. 루트 태스크는 `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr`만 출력하고 시드는 출력하지 않습니다. 이후 `INIT`으로 시드를 볼트에 주며, `INIT`은 시드를 전달할 뿐입니다. 키는 나중에 `KEYGEN`이 만듭니다.
**시드 지우기**: FDT 파서는 `rng-seed`와 `kaslr-seed` 값의 위치를 기록하고, 두 번째 `/chosen` 노드는 거부합니다(`DuplicateChosen`, 파서를 공유하는 UEFI 로더의 사전 검사에서도 같습니다). 커널은 루트 태스크에 진입하기 직전에 그 바이트를 0으로 만듭니다. `k0_mm::wipe_ro_alias`가 페이지의 읽기 전용 별칭 항목을 제자리에서 읽기·쓰기로 바꾸고(break-before-make), 0을 쓰고, 캐시 라인을 clean 및 invalidate한 뒤 되돌립니다. 이어서 커널은 그 바이트를 다시 읽어 확인하고, `BootInfo`에 있는 자신의 사본을 지우고, `k0: dtb seeds wiped B`(QEMU virt에서는 40B)를 출력하고, 살아 있는 프레임 아래의 부트 스택을 0으로 만듭니다. 이것이 커널이 DTB 매핑으로 하는 유일한 쓰기이며, DTB를 파싱하고 검증한 뒤에 일어납니다.
> [!NOTE]
-> 펌웨어나 UEFI 로더가 보관하는 사본과 부트 스택의 살아 있는 프레임 안의 값은 지워지지 않습니다. 스택 사본 지우기(커널 부트 스택, 서명 뒤의 볼트 스택)는 최선 노력입니다.
+> 펌웨어나 UEFI 로더가 보관하는 사본과 부트 스택의 살아 있는 프레임 안의 값은 지워지지 않습니다. 스택 사본 지우기(커널 부트 스택, 키 생성과 서명 뒤의 볼트 스택)는 최선 노력입니다.
+
+## 서비스 볼트와 운영자
+
+진짜 부트 시드는 정확히 한 번 쓰입니다. `terminal`과 `vault`로 빌드한 이미지에서 루트 태스크는 먼저 자가 테스트를 모두 실행합니다. 그다음 새 볼트인 **서비스 볼트**를 띄우고 `INIT`으로 부트 시드를 넘깁니다. 그리고 `root: vault seeded`, `root: vault has no seed (boot seed has no entropy)`, `root: vault has no seed (no algorithm in this image)` 중 하나를 출력합니다. 그 밖의 모든 이미지에서 루트 태스크는 진입하자마자 시드를 지웁니다.
+
+이어서 루트 태스크는 터미널과 똑같이 배선한 적대적 태스크 둘을 실행합니다. 둘은 거부되어야 하고 폴트로 끝나야 합니다. 그 뒤 루트 태스크는 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작하고, 영원히 대기합니다. 터미널은 operator 배지로 서비스 볼트에 `STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`만 요청할 수 있습니다. 터미널의 명령, 화면, 한계는 [USAGE_KR.md](../../USAGE_KR.md)에 있습니다.
+
+> [!WARNING]
+> 직렬 선에는 인증이 없습니다. 선에 닿는 사람은 누구나 operator이며, 키 소거를 포함한 operator의 네 연산을 그대로 할 수 있습니다. operator는 서명을 받을 수 없고 정책을 바꿀 수 없습니다.
+
+자가 테스트 볼트는 다른 볼트입니다. 공개된 RFC 8032 시험 시드와 진짜 시드 정보로 키를 만들어서 엔트로피 규칙은 그대로 실행되고, 진짜 시드는 이 볼트에 닿지 않습니다.
## feature와 고정된 이미지
@@ -97,7 +135,13 @@
- `vault`: 서비스, 프로토콜, 정책, 자가 테스트이며 서명 알고리즘은 없습니다. 모든 서명 요청에 `UNSUPPORTED`로 답합니다.
- `vault-ed25519`: Ed25519를 추가합니다.
-다음과 같이 빌드할 수 있습니다.
+같은 크레이트의 feature `terminal`은 운영자 터미널을 추가합니다. `vault`와 함께 쓰면 터미널이 볼트의 operator가 되고, `vault-ed25519`와 함께 쓰면 Ed25519 키를 만들 수 있습니다. 기본값은 꺼짐이며 콘솔 드라이버가 필요합니다. 터미널 이미지는 다음과 같이 빌드합니다.
+
+```sh
+$ cargo build -p k0-kernel --features console,terminal,vault-ed25519
+```
+
+볼트가 든 이미지는 다음과 같이 빌드할 수 있습니다.
```sh
$ cargo build -p k0-kernel --features console,vault-ed25519
@@ -107,17 +151,18 @@ $ cargo build -p k0-kernel --features console,vault-ed25519
## 테스트 방법
-**호스트 테스트**(`tools/host-test.sh`가 알고리즘 feature 유무로 `k0-vault`를 실행합니다). 테스트는 `userspace/k0-vault/src/tests.rs`에 있으며 Ed25519가 있으면 13개, 없으면 7개입니다. 이름은 다음과 같습니다.
+**호스트 테스트**(`tools/host-test.sh`가 알고리즘 feature 유무로 `k0-vault`를 실행합니다). 테스트는 `userspace/k0-vault/src/tests.rs`에 있으며 Ed25519가 있으면 20개, 없으면 11개입니다. 이름은 다음과 같습니다.
-- 항상: `badges_map_to_fixed_roles`, `policy_is_enforced_before_anything_else`, `malformed_requests_are_refused_whole`, `a_seed_without_real_entropy_makes_no_key`, `init_happens_once_and_zeroize_is_final`, `fetch_clamps_the_length_and_publish_writes_header_and_body`, 그리고 `without_an_algorithm_every_signing_request_is_unsupported`(마지막 것은 알고리즘이 없을 때만).
-- Ed25519가 있을 때: `the_self_test_passes_and_is_reported`, `signatures_verify_and_the_key_follows_the_seed`, `a_public_key_request_carries_no_body`, `unknown_algorithms_are_unsupported`, `nothing_is_served_after_zeroize`, `a_small_order_public_key_is_refused_even_with_a_matching_signature`, `a_failed_vault_refuses_everything_but_status`.
+- 항상: `badges_map_to_fixed_roles_and_frames`, `each_role_may_do_exactly_its_operations`, `no_frame_is_touched_for_a_request_that_cannot_have_a_body`, `a_request_that_claims_a_body_it_cannot_have_is_refused`, `the_status_word_packs_state_algorithm_and_what_is_built`, `a_call_without_a_known_badge_is_denied`, `malformed_requests_are_refused_whole`, `a_seed_without_real_entropy_makes_no_key`, `the_seed_is_taken_once_and_zeroize_is_final`, `fetch_clamps_the_length_and_publish_writes_header_and_body`, 그리고 `without_an_algorithm_the_vault_takes_no_seed_and_serves_nothing`(마지막 것은 알고리즘이 없을 때만).
+- Ed25519가 있을 때: `the_self_test_passes_and_is_reported`, `key_generation_follows_the_states`, `the_operator_gets_the_public_key_and_never_a_signature`, `a_vault_that_fails_holds_no_secret`, `signatures_verify_and_the_key_follows_the_seed`, `a_public_key_request_carries_no_body`, `unknown_algorithms_are_unsupported`, `nothing_is_served_after_zeroize`, `a_small_order_public_key_is_refused_even_with_a_matching_signature`, `a_failed_vault_refuses_everything_but_status`.
-다른 크레이트와 합치면 호스트 테스트는 ARM 호스트에서 276개, 그 외 호스트에서 190개입니다(`k0-mm` 제외).
+다른 크레이트와 합치면 호스트 테스트는 ARM 호스트에서 354개, 그 외 호스트에서 268개입니다(`k0-mm` 제외).
**루트 태스크 자가 테스트**(`userspace/root-task/src/oracle.rs`의 `test_oracle`, `vault`로 빌드한 이미지에만 있음). 다음을 검사합니다.
- 자가 테스트가 보고되고, 배지 없는 호출이 거부됩니다.
-- 부팅 시드로 키가 만들어지고, 두 번째 `INIT`은 거부됩니다.
+- 자가 테스트 볼트가 `INIT`으로 공개된 RFC 8032 시험 시드를 받고(상태 `seeded`), operator는 시드를 넘기거나 서명할 수 없으며, 두 번째 `INIT`은 거부됩니다.
+- `KEYGEN`이 그 시드로 키를 만들고, 두 번째 `KEYGEN`은 거부됩니다(`KEY_EXISTS`).
- admin은 서명할 수 없습니다.
- signer 클라이언트는 검증되는 서명을 받고, 바뀐 메시지나 바뀐 서명에는 검증이 실패합니다.
- reader는 `SIGN`을 거부당합니다.
@@ -128,14 +173,16 @@ $ cargo build -p k0-kernel --features console,vault-ed25519
표지는 `root: oracle tests pass`입니다. 클라이언트 태스크는 루트 CNode 슬롯이 부족해 하나의 클라이언트 주소 공간에서 차례로 실행됩니다. 이 테스트는 볼트와 클라이언트 사이의 격리를 보여 주며 클라이언트끼리의 격리는 보여 주지 않습니다.
-**부팅 매트릭스 행**: `vault`, `vault-max`(RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, 그리고 정적 행 `vault-symbols`(기본 이미지에는 볼트나 암호 코드가 없고, 볼트 이미지에는 그 코드에서 온 쓰기 가능한 정적 변수가 없음)입니다. 매트릭스는 HVF가 있는 Mac에서 61행, CI에서 51행입니다. 이제 모든 이미지는 `k0: dtb seeds wiped B`와 `root: boot seed from rng-seed bytes ...`도 출력합니다.
+**부팅 매트릭스 행**: `vault`, `vault-max`(RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, 그리고 정적 행 `vault-symbols`(기본 이미지에는 볼트나 암호 코드가 없고, 볼트 이미지에는 그 코드에서 온 쓰기 가능한 정적 변수가 없음)입니다. 매트릭스는 HVF가 있는 Mac에서 76행, CI에서 65행입니다. 터미널용 행은 `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi`, `hvf-term`입니다. `tools/term-test.py `는 QEMU의 직렬 포트를 파이프에 연결해 터미널 이미지를 부팅하고 스크립트로 짠 세션을 실행합니다. 이제 모든 이미지는 `k0: dtb seeds wiped B`와 `root: boot seed from rng-seed bytes ...`도 출력합니다.
## 알려진 공백
> [!NOTE]
> 구현은 검증을 받지 않았고, 이 커널에서 크레이트의 부채널 분석은 없으며, 오라클은 QEMU(TCG와 HVF)에서만 실행했습니다.
-- **키 하나**: 영속성, 키 가져오기·내보내기, DRBG, 운영자 입력, 양자 내성 알고리즘이 아직 없습니다.
+- **키 하나**: 영속성, 키 가져오기·내보내기, DRBG, 양자 내성 알고리즘이 아직 없습니다. 새 키를 만들려면 재부팅해야 합니다.
+- **서비스 모드에 서명 클라이언트 없음**: 서비스 볼트의 키는 만들어지고 표시되지만 아직 다른 태스크가 쓰지 않습니다. 클라이언트 서명은 자가 테스트가 보여 줍니다.
+- **터미널과 볼트는 죽어도 다시 시작하지 않습니다**: 죽으면 그대로 멈춥니다. 루트 태스크는 신뢰 대상입니다.
- **가용성은 보호되지 않습니다**: 클라이언트는 엔드포인트 하나를 공유하며 모든 호출에 타임아웃을 써야 합니다([ipc_KR.md](ipc_KR.md) 참고).
- **루트 태스크는 신뢰 대상입니다**: 볼트를 만들고 읽을 수 있습니다.
- **클라이언트 신원 없음**: 모든 signer가 키 하나를 공유합니다.